text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import Api from '../../';
import {
CheckoutSessionRequest,
CouponRequest,
CreateSignInCheckoutSessionRequest,
GuestPlaceOrderRequest,
InitiatePaymentRequest,
ShippingAddressImpl,
UpdatePaymentInformation,
UpdateQuantity,
UpdateShippingOption
} from '../../../../types';
/**
* The Order API provides interfaces that lets shoppers pay for items (for both eBay guest and eBay member buyers).
* Client Credentials: https://api.ebay.com/oauth/api_scope/buy.order
*/
export default class Order extends Api {
static id = 'Order';
get basePath(): string {
return '/buy/order/v1';
}
/**
* (Limited Release) You must be whitelisted to use this method.
* This method adds a coupon to an eBay proxy guest checkout session and applies it to all the eligible items in
* the order.
*
* @param {String} checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is
* returned by the initiateCheckoutSession method.
* @param body The container for the fields used to apply a coupon to a checkout session.
*/
public applyCoupon(checkoutSessionId: string, body: CouponRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/apply_coupon`, body);
}
/**
* This method returns the details of the specified eBay member checkout session.
*
* @param {String} checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is
* returned by the initiateCheckoutSession method.
*/
public getCheckoutSession(checkoutSessionId: string) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.get(`/checkout_session/${checkoutSessionId}`);
}
/**
* This method creates a eBay member checkout session, which is the first step in performing a checkout.
*
* @param body The container for the fields used by the initiateCheckoutSession method.
*/
public initiateCheckoutSession(body?: CreateSignInCheckoutSessionRequest) {
return this.post(`/checkout_session/initiate`, body);
}
/**
* This method creates the purchase order, pays for the items, and terminates the specified eBay member checkout
* session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
*/
public placeOrder(checkoutSessionId: string) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/place_order`);
}
/**
* (Limited Release) You must be whitelisted to use this method. This method removes a coupon from an eBay member
* checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body CouponRequest
*/
public removeCoupon(checkoutSessionId: string, body?: CouponRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/remove_coupon`, body);
}
/**
* This method changes the payment method information of the specified eBay member checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdatePaymentInformation
*/
public updatePaymentInfo(checkoutSessionId: string, body?: UpdatePaymentInformation) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/update_payment_info`, body);
}
/**
* This method changes the quantity of the specified line item in an eBay member checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateQuantity
*/
public updateQuantity(checkoutSessionId: string, body?: UpdateQuantity) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/update_quantity`, body);
}
/**
* This method changes the quantity of the specified line item in an eBay member checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateQuantity
*/
public checkoutSessionId(checkoutSessionId: string, body?: UpdateQuantity) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/update_quantity`, body);
}
/**
* This method changes the shipping address for in an eBay member checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body ShippingAddressImpl
*/
public updateShippingAddress(checkoutSessionId: string, body?: ShippingAddressImpl) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/update_shipping_address`, body);
}
/**
* This method changes the shipping method for the specified line item in an eBay member checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateShippingOption
*/
public updateShippingOption(checkoutSessionId: string, body?: UpdateShippingOption) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/checkout_session/${checkoutSessionId}/update_shipping_option`, body);
}
/**
* (Limited Release) You must be whitelisted to use this method. This method adds a coupon to an eBay guest
* checkout
* session and applies it to all the eligible items in the order.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body CouponRequest
*/
public applyGuestCoupon(checkoutSessionId: string, body?: CouponRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/apply_coupon`, body);
}
/**
* This method returns the details of the specified guest checkout session. The checkoutSessionId is passed in as a
* URI parameter and is required.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
*/
public getGuestCheckoutSession(checkoutSessionId: string) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.get(`/guest_checkout_session/${checkoutSessionId}`);
}
/**
* This method creates an eBay guest checkout session, which is the first step in performing a checkout.
*
* @param body CheckoutSessionRequest
*/
public initiateGuestCheckoutSession(body?: CheckoutSessionRequest) {
return this.post(`/guest_checkout_session/initiate`, body);
}
/**
* This method is used only in the PayPal Smart Button eBay guest payment flow.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body InitiatePaymentRequest
*/
public initiateGuestPayment(checkoutSessionId: string, body?: InitiatePaymentRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/initiate_payment`, body);
}
/**
* This method creates the purchase order, pays for the items, and terminates the specified guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body GuestPlaceOrderRequest
*/
public placeGuestOrder(checkoutSessionId: string, body?: GuestPlaceOrderRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/place_order`, body);
}
/**
* (Limited Release) You must be whitelisted to use this method. This method removes a coupon from an eBay guest
* checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body CouponRequest
*/
public removeGuestCoupon(checkoutSessionId: string, body?: CouponRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/remove_coupon`, body);
}
/**
* This method changes the payment method information of the specified guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdatePaymentInformation
*/
public updateGuestPaymentInfo(checkoutSessionId: string, body?: UpdatePaymentInformation) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/update_payment_info`, body);
}
/**
* This method changes the quantity of the specified line item in an eBay guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateQuantity
*/
public updateGuestQuantity(checkoutSessionId: string, body?: UpdateQuantity) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/update_quantity`, body);
}
/**
* This method changes the shipping address for the order in an eBay guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body ShippingAddressImpl
*/
public updateGuestShippingAddress(checkoutSessionId: string, body?: ShippingAddressImpl) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/update_shipping_address`, body);
}
/**
* This method changes the shipping method for the specified line item in an eBay guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateShippingOption
*/
public updateGuestShippingOption(checkoutSessionId: string, body?: UpdateShippingOption) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/guest_checkout_session/${checkoutSessionId}/update_shipping_option`, body);
}
/**
* (Limited Release) You must be whitelisted to use this method. This method adds a coupon to an eBay proxy guest
* checkout session and applies it to all the eligible items in the order.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body CouponRequest
*/
public applyProxyGuestCoupon(checkoutSessionId: string, body?: CouponRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/apply_coupon`, body);
}
/**
* This method returns the details of the specified eBay proxy guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
*/
public getProxyGuestCheckoutSession(checkoutSessionId: string) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.get(`/proxy_guest_checkout_session/${checkoutSessionId}`);
}
/**
* This method creates an eBay proxy guest checkout session, which is a payment flow that requires integration
* with a VSP (vault service provider), such as Braintree. The VSP handles only the methods within this flow that
* contain payment information.
*
* @param body CheckoutSessionRequest
*/
public initiateProxyGuestCheckoutSession(body?: CheckoutSessionRequest) {
return this.post(`/proxy_guest_checkout_session/initiate`, body);
}
/**
* This method creates the proxy guest purchase order, pays for the items, and terminates the specified guest
* checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body GuestPlaceOrderRequest
*/
public placeProxyGuestOrder(checkoutSessionId: string, body?: GuestPlaceOrderRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/place_order`, body);
}
/**
* (Limited Release) You must be whitelisted to use this method. This method removes a coupon from an eBay proxy
* guest checkout session. The checkoutSessionId is passed in as a URI parameter and is required.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body CouponRequest
*/
public removeProxyGuestCoupon(checkoutSessionId: string, body?: CouponRequest) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/remove_coupon`, body);
}
/**
* This method adds or changes the payment information of the specified proxy guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param authorization The oAuth2 token. Note: The eBay partner must include this header in the request.
* @param date The UTC timestamp of the request, which is generated and added to the request by the VSP.
* @param requestNonce A UUID (a 128-bit universal unique ID), which is generated and added to the request by the
* VSP.
* @param signature The HMAC signature, which is generated and added to the request by the VSP.
* @param body UpdatePaymentInformation
*/
public updateProxyGuestPaymentInfo(
checkoutSessionId: string,
authorization: string,
date: string,
requestNonce: string,
signature: string,
body?: UpdatePaymentInformation
) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/update_payment_info`, body, {
headers: {
'Authorization': authorization,
'X-EBAY-C-DATE': date,
'X-EBAY-C-REQUEST-NONCE': requestNonce,
'X-EBAY-C-SIGNATURE': signature
}
});
}
/**
* This method changes the quantity of the specified line item in an eBay proxy guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateQuantity
*/
public updateProxyGuestQuantity(checkoutSessionId: string, body?: UpdateQuantity) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/update_quantity`, body);
}
/**
* This method changes the shipping address for the order in an eBay proxy guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body ShippingAddressImpl
*/
public updateProxyGuestShippingAddress(checkoutSessionId: string, body?: ShippingAddressImpl) {
checkoutSessionId = encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/update_shipping_address`, body);
}
/**
* This method changes the shipping method for the specified line item in an eBay proxy guest checkout session.
*
* @param checkoutSessionId The eBay-assigned session ID, for a specific eBay marketplace, that is returned by the
* initiateCheckoutSession method.
* @param body UpdateShippingOption
*/
public updateProxyGuestShippingOption(checkoutSessionId: string, body?: UpdateShippingOption) {
checkoutSessionId= encodeURIComponent(checkoutSessionId);
return this.post(`/proxy_guest_checkout_session/${checkoutSessionId}/update_shipping_option`, body);
}
/**
* This method retrieves the details about a specific guest purchase order.
*
* @param purchaseOrderId The unique identifier of a purchase order made by a guest buyer, for which details are to
* be retrieved.
*/
public getGuestPurchaseOrder(purchaseOrderId: string) {
purchaseOrderId = encodeURIComponent(purchaseOrderId);
return this.get(`/guest_purchase_order/${purchaseOrderId}`);
}
/**
* This method retrieves the details about a specific eBay member purchase order.
*
* @param purchaseOrderId The unique identifier of a purchase order made by an eBay member, for which details are
* to be retrieved.
*/
public getPurchaseOrder(purchaseOrderId: string) {
purchaseOrderId = encodeURIComponent(purchaseOrderId);
return this.get(`/purchase_order/${purchaseOrderId}`);
}
} | the_stack |
import getResizeObserver from './polyfillLoaders/ResizeObserver.js';
import { ItemBox, Margins, Layout, Positions, LayoutConstructor, LayoutSpecifier } from './layouts/shared/Layout.js';
export const virtualizerRef = Symbol('virtualizerRef');
const SIZER_ATTRIBUTE = 'virtualizer-sizer';
interface InternalRange {
first: number;
last: number;
num: number;
remeasure: boolean;
stable: boolean;
firstVisible: number;
lastVisible: number;
}
interface Range {
first: number,
last: number
}
export class RangeChangedEvent extends Event {
static eventName = 'rangeChanged';
first: number;
last: number;
constructor(range: Range) {
super(RangeChangedEvent.eventName, {bubbles: true});
this.first = range.first;
this.last = range.last;
}
}
export class VisibilityChangedEvent extends Event {
static eventName = 'visibilityChanged';
first: number;
last: number;
constructor(range: Range) {
super(VisibilityChangedEvent.eventName, {bubbles: true});
this.first = range.first;
this.last = range.last;
}
}
declare global {
interface HTMLElementEventMap {
'rangeChanged': RangeChangedEvent;
'visibilityChanged': VisibilityChangedEvent;
}
}
export interface VirtualizerHostElement extends HTMLElement {
[virtualizerRef]?: Virtualizer
}
type VerticalScrollSize = {height: number};
type HorizontalScrollSize = {width: number};
type ScrollSize = VerticalScrollSize | HorizontalScrollSize;
type ChildMeasurements = {[key: number]: ItemBox};
export type ScrollToIndexValue = {index: number, position?: string} | null;
export interface VirtualizerConfig {
layout?: Layout | LayoutConstructor | LayoutSpecifier | null;
/**
* The parent of all child nodes to be rendered.
*/
hostElement: VirtualizerHostElement;
scroller?: boolean
}
/**
* Provides virtual scrolling boilerplate.
*
* Extensions of this class must set hostElement, layout, and scrollTarget.
*
* Extensions of this class must also override VirtualRepeater's DOM
* manipulation methods.
*/
export class Virtualizer {
private _benchmarkStart: number | null = null;
/**
* Whether the layout should receive an updated viewport size on the next
* render.
*/
// private _needsUpdateView: boolean = false;
private _layout: Layout | null = null;
private _clippingAncestors: Element[] = [];
/**
* Layout provides these values, we set them on _render().
* TODO @straversi: Can we find an XOR type, usable for the key here?
*/
private _scrollSize: ScrollSize | null = null;
/**
* Difference between scroll target's current and required scroll offsets.
* Provided by layout.
*/
private _scrollError: {left: number, top: number} | null = null;
/**
* A list of the positions (top, left) of the children in the current range.
*/
private _childrenPos: Array<{top: number, left: number}> | null = null;
// TODO: (graynorton): type
private _childMeasurements: ChildMeasurements | null = null;
private _toBeMeasured: Map<HTMLElement, unknown> = new Map();
private _rangeChanged = true;
private _itemsChanged = true;
private _visibilityChanged = true;
/**
* The HTMLElement that hosts the virtualizer. Set by hostElement.
*/
protected _hostElement?: VirtualizerHostElement;
private _isScroller = false;
private _sizer: HTMLElement | null = null;
/**
* Resize observer attached to hostElement.
*/
private _hostElementRO: ResizeObserver | null = null;
/**
* Resize observer attached to children.
*/
private _childrenRO: ResizeObserver | null = null;
private _mutationObserver: MutationObserver | null = null;
private _mutationPromise: Promise<void> | null = null;
private _mutationPromiseResolver: Function | null = null;
private _mutationsObserved = false;
private _scrollEventListeners: (Element | Window)[] = [];
private _scrollEventListenerOptions: AddEventListenerOptions = { passive: true };
// TODO (graynorton): Rethink, per longer comment below
private _loadListener = this._childLoaded.bind(this);
/**
* Index and position of item to scroll to.
*/
private _scrollToIndex: ScrollToIndexValue = null;
/**
* Items to render. Set by items.
*/
private _items: Array<unknown> = [];
/**
* Index of the first child in the range, not necessarily the first visible child.
* TODO @straversi: Consider renaming these.
*/
protected _first = -1;
/**
* Index of the last child in the range.
*/
protected _last = -1;
/**
* Index of the first item intersecting the viewport.
*/
private _firstVisible = -1;
/**
* Index of the last item intersecting the viewport.
*/
private _lastVisible = -1;
protected _scheduled = new WeakSet();
/**
* Invoked at the end of each render cycle: children in the range are
* measured, and their dimensions passed to this callback. Use it to layout
* children as needed.
*/
protected _measureCallback: ((sizes: ChildMeasurements) => void) | null = null;
protected _measureChildOverride: ((element: Element, item: unknown) => ItemBox) | null = null;
constructor(config: VirtualizerConfig) {
if (!config) {
throw new Error('Virtualizer constructor requires a configuration object');
}
if (config.hostElement) {
this._init(config);
}
else {
throw new Error('Virtualizer configuration requires the "hostElement" property');
}
}
set items(items: Array<unknown> | undefined) {
if (Array.isArray(items) && items !== this._items) {
this._itemsChanged = true;
this._items = items;
this._schedule(this._updateLayout);
}
}
_init(config: VirtualizerConfig) {
this._isScroller = !!config.scroller;
this._initHostElement(config);
this._initLayout(config);
}
private async _initObservers() {
this._mutationObserver = new MutationObserver(this._observeMutations.bind(this));
const ResizeObserver = await getResizeObserver();
this._hostElementRO = new ResizeObserver(
() => this._hostElementSizeChanged()
);
this._childrenRO =
new ResizeObserver(this._childrenSizeChanged.bind(this));
}
async _initLayout(config: VirtualizerConfig) {
if (config.layout) {
this.layout = config.layout;
}
else {
this.layout = (await import('./layouts/flow.js')).FlowLayout;
}
}
_initHostElement(config: VirtualizerConfig) {
const hostElement = (this._hostElement = config.hostElement);
this._applyVirtualizerStyles();
hostElement[virtualizerRef] = this;
}
async connected() {
await this._initObservers();
const includeSelf = this._isScroller;
this._clippingAncestors = getClippingAncestors(this._hostElement!, includeSelf);
this._schedule(this._updateLayout);
this._observeAndListen();
}
_observeAndListen() {
this._mutationObserver!.observe(this._hostElement!, { childList: true });
this._mutationPromise = new Promise(resolve => this._mutationPromiseResolver = resolve);
this._hostElementRO!.observe(this._hostElement!);
this._scrollEventListeners.push(window);
window.addEventListener('scroll', this, this._scrollEventListenerOptions);
this._clippingAncestors.forEach(ancestor => {
ancestor.addEventListener('scroll', this, this._scrollEventListenerOptions)
this._scrollEventListeners.push(ancestor);
this._hostElementRO!.observe(ancestor);
});
this._children.forEach((child) => this._childrenRO!.observe(child));
this._scrollEventListeners.forEach(target => target.addEventListener('scroll', this, this._scrollEventListenerOptions));
}
disconnected() {
this._scrollEventListeners.forEach((target) => target.removeEventListener('scroll', this, this._scrollEventListenerOptions));
this._scrollEventListeners = [];
this._clippingAncestors = [];
this._mutationObserver!.disconnect();
this._hostElementRO!.disconnect();
this._childrenRO!.disconnect();
}
private _applyVirtualizerStyles() {
const hostElement = this._hostElement!;
// Would rather set these CSS properties on the host using Shadow Root
// style scoping (and falling back to a global stylesheet where native
// Shadow DOM is not available), but this Mobile Safari bug is preventing
// that from working: https://bugs.webkit.org/show_bug.cgi?id=226195
const style = hostElement.style as CSSStyleDeclaration & { contain: string };
style.display = style.display || 'block';
style.position = style.position || 'relative';
style.contain = style.contain || 'strict';
if (this._isScroller) {
style.overflow = style.overflow || 'auto';
style.minHeight = style.minHeight || '150px';
}
}
_getSizer() {
const hostElement = this._hostElement!;
if (!this._sizer) {
// Use a pre-existing sizer element if provided (for better integration
// with vDOM renderers)
let sizer = hostElement.querySelector(`[${SIZER_ATTRIBUTE}]`) as HTMLElement;
if (!sizer) {
sizer = document.createElement('div');
sizer.setAttribute(SIZER_ATTRIBUTE, '');
hostElement.appendChild(sizer);
}
// When the scrollHeight is large, the height of this element might be
// ignored. Setting content and font-size ensures the element has a size.
Object.assign(sizer.style, {
position: 'absolute',
margin: '-2px 0 0 0',
padding: 0,
visibility: 'hidden',
fontSize: '2px',
});
sizer.innerHTML = ' ';
sizer.setAttribute(SIZER_ATTRIBUTE, '');
this._sizer = sizer;
}
return this._sizer;
}
// This will always actually return a layout instance,
// but TypeScript wants the getter and setter types to be the same
get layout(): Layout | LayoutConstructor | LayoutSpecifier | null {
return this._layout;
}
// TODO (graynorton): Consider not allowing dynamic layout changes and
// instead just creating a new Virtualizer instance when a layout
// change is desired. Might simplify quite a bit.
set layout(layout: Layout | LayoutConstructor | LayoutSpecifier | null) {
if (this._layout === layout) {
return;
}
let _layout: LayoutConstructor | Layout | null = null;
let _config: object = {};
if (typeof layout === 'object') {
if ((layout as LayoutSpecifier).type !== undefined) {
_layout = (layout as LayoutSpecifier).type;
// delete (layout as LayoutSpecifier).type;
}
_config = layout as object;
}
else {
_layout = layout;
}
if (typeof _layout === 'function') {
if (this._layout instanceof _layout) {
if (_config) {
this._layout!.config = _config;
}
return;
}
else {
_layout = new _layout(_config);
}
}
if (this._layout) {
this._measureCallback = null;
this._measureChildOverride = null;
this._layout.removeEventListener('scrollsizechange', this);
this._layout.removeEventListener('scrollerrorchange', this);
this._layout.removeEventListener('itempositionchange', this);
this._layout.removeEventListener('rangechange', this);
this._sizeHostElement(undefined);
this._hostElement!.removeEventListener('load', this._loadListener, true);
}
this._layout = _layout as Layout | null;
if (this._layout) {
if (this._layout.measureChildren && typeof this._layout.updateItemSizes === 'function') {
if (typeof this._layout.measureChildren === 'function') {
this._measureChildOverride = this._layout.measureChildren;
}
this._measureCallback = this._layout.updateItemSizes.bind(this._layout);
}
this._layout.addEventListener('scrollsizechange', this);
this._layout.addEventListener('scrollerrorchange', this);
this._layout.addEventListener('itempositionchange', this);
this._layout.addEventListener('rangechange', this);
if (this._layout.listenForChildLoadEvents) {
this._hostElement!.addEventListener('load', this._loadListener, true);
}
this._schedule(this._updateLayout);
}
}
// TODO (graynorton): Rework benchmarking so that it has no API and
// instead is always on except in production builds
startBenchmarking() {
if (this._benchmarkStart === null) {
this._benchmarkStart = window.performance.now();
}
}
stopBenchmarking() {
if (this._benchmarkStart !== null) {
const now = window.performance.now();
const timeElapsed = now - this._benchmarkStart;
const entries = performance.getEntriesByName('uv-virtualizing', 'measure');
const virtualizationTime = entries
.filter(e => e.startTime >= this._benchmarkStart! && e.startTime < now)
.reduce((t, m) => t + m.duration, 0);
this._benchmarkStart = null;
return { timeElapsed, virtualizationTime };
}
return null;
}
private _measureChildren(): void {
const mm: ChildMeasurements = {};
const children = this._children;
const fn = this._measureChildOverride || this._measureChild;
for (let i = 0; i < children.length; i++) {
const child = children[i];
const idx = this._first + i;
if (this._itemsChanged || this._toBeMeasured.has(child)) {
mm[idx] = fn.call(this, child, this._items[idx] /*as unknown as object*/);
}
}
this._childMeasurements = mm;
this._schedule(this._updateLayout);
this._toBeMeasured.clear();
}
/**
* Returns the width, height, and margins of the given child.
*/
_measureChild(element: Element): ItemBox {
// offsetWidth doesn't take transforms in consideration, so we use
// getBoundingClientRect which does.
const {width, height} = element.getBoundingClientRect();
return Object.assign({width, height}, getMargins(element));
}
/**
* Index and position of item to scroll to. The virtualizer will fix to that point
* until the user scrolls.
*/
set scrollToIndex(newValue: ScrollToIndexValue) {
this._scrollToIndex = newValue;
this._schedule(this._updateLayout);
}
protected async _schedule(method: Function): Promise<void> {
if (!this._scheduled.has(method)) {
this._scheduled.add(method);
await Promise.resolve();
this._scheduled.delete(method);
method.call(this);
}
}
async _updateDOM() {
const {_rangeChanged, _itemsChanged} = this;
if (this._visibilityChanged) {
this._notifyVisibility();
this._visibilityChanged = false;
}
if (_rangeChanged || _itemsChanged) {
this._notifyRange();
await this._mutationPromise;
}
this._children.forEach((child) => this._childrenRO!.observe(child));
this._positionChildren(this._childrenPos!);
this._sizeHostElement(this._scrollSize);
if (this._scrollError) {
this._correctScrollError(this._scrollError);
this._scrollError = null;
}
if (this._benchmarkStart && 'mark' in window.performance) {
window.performance.mark('uv-end');
}
}
_updateLayout() {
if (this._layout) {
this._layout!.totalItems = this._items.length;
if (this._scrollToIndex !== null) {
this._layout!.scrollToIndex(this._scrollToIndex.index, this._scrollToIndex!.position!);
this._scrollToIndex = null;
}
this._updateView();
if (this._childMeasurements !== null) {
// If the layout has been changed, we may have measurements but no callback
if (this._measureCallback) {
this._measureCallback(this._childMeasurements);
}
this._childMeasurements = null;
}
this._layout!.reflowIfNeeded(this._itemsChanged);
if (this._benchmarkStart && 'mark' in window.performance) {
window.performance.mark('uv-end');
}
}
}
private _handleScrollEvent() {
if (this._benchmarkStart && 'mark' in window.performance) {
try {
window.performance.measure(
'uv-virtualizing',
'uv-start',
'uv-end'
);
} catch(e) {
console.warn('Error measuring performance data: ', e);
}
window.performance.mark('uv-start');
}
this._schedule(this._updateLayout);
}
handleEvent(event: CustomEvent) {
switch (event.type) {
case 'scroll':
if (event.currentTarget === window || this._clippingAncestors.includes(event.currentTarget as Element)) {
this._handleScrollEvent();
}
break;
case 'scrollsizechange':
this._scrollSize = event.detail;
this._schedule(this._updateDOM);
break;
case 'scrollerrorchange':
this._scrollError = event.detail;
this._schedule(this._updateDOM);
break;
case 'itempositionchange':
this._childrenPos = event.detail;
this._schedule(this._updateDOM);
break;
case 'rangechange':
this._adjustRange(event.detail);
this._schedule(this._updateDOM);
break;
default:
console.warn('event not handled', event);
}
}
get _children(): Array<HTMLElement> {
const arr = [];
let next = this._hostElement!.firstElementChild as HTMLElement;
while (next) {
if (!next.hasAttribute(SIZER_ATTRIBUTE)) {
arr.push(next);
}
next = next.nextElementSibling as HTMLElement;
}
return arr;
}
private _updateView() {
const hostElement = this._hostElement!;
const layout = this._layout!;
let top, left, bottom, right, scrollTop, scrollLeft;
const hostElementBounds = hostElement.getBoundingClientRect();
top = 0
left = 0;
bottom = window.innerHeight;
right = window.innerWidth;
for (let ancestor of this._clippingAncestors) {
const ancestorBounds = ancestor.getBoundingClientRect();
top = Math.max(top, ancestorBounds.top);
left = Math.max(left, ancestorBounds.left);
bottom = Math.min(bottom, ancestorBounds.bottom);
right = Math.min(right, ancestorBounds.right);
}
scrollTop = top - hostElementBounds.top + hostElement.scrollTop;
scrollLeft = left - hostElementBounds.left + hostElement.scrollLeft;
const height = Math.max(1, bottom - top);
const width = Math.max(1, right - left);
layout.viewportSize = {width, height};
layout.viewportScroll = {top: scrollTop, left: scrollLeft};
}
/**
* Styles the host element so that its size reflects the
* total size of all items.
*/
private _sizeHostElement(size?: ScrollSize | null) {
// Some browsers seem to crap out if the host element gets larger than
// a certain size, so we clamp it here (this value based on ad hoc
// testing in Chrome / Safari / Firefox Mac)
const max = 8200000;
const h = size && (size as HorizontalScrollSize).width ? Math.min(max, (size as HorizontalScrollSize).width) : 0;
const v = size && (size as VerticalScrollSize).height ? Math.min(max, (size as VerticalScrollSize).height) : 0;
if (this._isScroller) {
this._getSizer().style.transform = `translate(${h}px, ${v}px)`;
}
else {
const style = this._hostElement!.style;
(style.minWidth as string | null) = h ? `${h}px` : '100%';
(style.minHeight as string | null) = v ? `${v}px` : '100%';
}
}
/**
* Sets the top and left transform style of the children from the values in
* pos.
*/
private _positionChildren(pos: Array<Positions>) {
if (pos) {
const children = this._children;
Object.keys(pos).forEach((key) => {
const idx = (key as unknown as number) - this._first;
const child = children[idx];
if (child) {
const {top, left, width, height, xOffset, yOffset} = pos[key as unknown as number];
child.style.position = 'absolute';
child.style.boxSizing = 'border-box';
child.style.transform = `translate(${left}px, ${top}px)`;
if (width !== undefined) {
child.style.width = width + 'px';
}
if (height !== undefined) {
child.style.height = height + 'px';
}
(child.style.left as string | null) = xOffset === undefined ? null : xOffset + 'px';
(child.style.top as string | null) = yOffset === undefined ? null : yOffset + 'px';
}
});
}
}
private async _adjustRange(range: InternalRange) {
const {_first, _last, _firstVisible, _lastVisible} = this;
this._first = range.first;
this._last = range.last;
this._firstVisible = range.firstVisible;
this._lastVisible = range.lastVisible;
this._rangeChanged = (
this._rangeChanged ||
this._first !== _first ||
this._last !== _last
);
this._visibilityChanged = (
this._visibilityChanged ||
this._firstVisible !== _firstVisible ||
this._lastVisible !== _lastVisible
);
}
private _correctScrollError(err: {top: number, left: number}) {
const target = this._clippingAncestors[0];
if (target) {
target.scrollTop -= err.top;
target.scrollLeft -= err.left;
} else {
window.scroll(window.pageXOffset - err.left, window.pageYOffset - err.top);
}
}
/**
* Emits a rangechange event with the current first, last, firstVisible, and
* lastVisible.
*/
private _notifyRange() {
this._hostElement!.dispatchEvent(new RangeChangedEvent({ first: this._first, last: this._last }));
}
private _notifyVisibility() {
this._hostElement!.dispatchEvent(new VisibilityChangedEvent({ first: this._firstVisible, last: this._lastVisible }));
}
/**
* Render and update the view at the next opportunity with the given
* hostElement size.
*/
private _hostElementSizeChanged() {
this._schedule(this._updateLayout);
}
private async _observeMutations() {
if (!this._mutationsObserved) {
this._mutationsObserved = true;
this._mutationPromiseResolver!();
this._mutationPromise = new Promise(resolve => this._mutationPromiseResolver = resolve);
this._mutationsObserved = false;
}
}
// TODO (graynorton): Rethink how this works. Probably child loading is too specific
// to have dedicated support for; might want some more generic lifecycle hooks for
// layouts to use. Possibly handle measurement this way, too, or maybe that remains
// a first-class feature?
private _childLoaded() {
// this.requestRemeasure();
}
// This is the callback for the ResizeObserver that watches the
// virtualizer's children. We land here at the end of every virtualizer
// update cycle that results in changes to physical items, and we also
// end up here if one or more children change size independently of
// the virtualizer update cycle.
private _childrenSizeChanged(changes: ResizeObserverEntry[]) {
// Only measure if the layout requires it
if (this._layout!.measureChildren) {
for (const change of changes) {
this._toBeMeasured.set(change.target as HTMLElement, change.contentRect);
}
this._measureChildren();
}
// If this is the end of an update cycle, we need to reset some
// internal state. This should be a harmless no-op if we're handling
// an out-of-cycle ResizeObserver callback, so we don't need to
// distinguish between the two cases.
this._itemsChanged = false;
this._rangeChanged = false;
}
}
function getMargins(el: Element): Margins {
const style = window.getComputedStyle(el);
return {
marginTop: getMarginValue(style.marginTop),
marginRight: getMarginValue(style.marginRight),
marginBottom: getMarginValue(style.marginBottom),
marginLeft: getMarginValue(style.marginLeft),
};
}
function getMarginValue(value: string): number {
const float = value ? parseFloat(value) : NaN;
return Number.isNaN(float) ? 0 : float;
}
// TODO (graynorton): Deal with iframes?
function getParentElement(el: Element) {
if (el.parentElement !== null) {
return el.parentElement;
}
const parentNode = el.parentNode;
if (parentNode && parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
return (parentNode as ShadowRoot).host || null;
}
return null;
}
function getElementAncestors(el: Element, includeSelf=false) {
const ancestors = [];
let parent = includeSelf ? el : getParentElement(el);
while(parent !== null) {
ancestors.push(parent);
parent = getParentElement(parent);
}
return ancestors;
}
function getClippingAncestors(el: Element, includeSelf=false) {
return getElementAncestors(el, includeSelf)
.filter(a => getComputedStyle(a).overflow !== 'visible');
} | the_stack |
import {intersectEllipse, intersectRect} from "./intersect";
interface Point {
x: number;
y: number;
}
interface BBox extends Point {
width: number;
height: number;
}
interface D3Node extends BBox {
intersect: (p: Point) => Point
}
class D3Element {
private readonly _el: SVGElement
constructor(el: SVGElement) {
this._el = el;
}
node() {
return this._el;
}
attr(name: string, value: string | number) {
this._el.setAttribute(name, String(value))
return this;
}
insert(type: string, pos: string) {
const el = document.createElementNS('http://www.w3.org/2000/svg', type)
const el2 = this._el.insertBefore(el, this._el.querySelector(pos))
return new D3Element(el2)
}
}
function rect(parent: D3Element, bbox: BBox, node: D3Node, rounded = false) {
const shapeSvg = parent.insert("rect", ":first-child")
.attr("rx", rounded ? node.width / 8 : 3)
.attr("ry", rounded ? node.width / 8 : 3)
.attr("x", -bbox.width / 2)
.attr("y", -bbox.height / 2)
.attr("width", bbox.width)
.attr("height", bbox.height);
node.intersect = function (point) {
return intersectRect(node, point);
};
return shapeSvg;
}
function cylinder(parent: D3Element, bbox: BBox, node: D3Node) {
const w = bbox.width;
const rx = w / 2;
const ry = rx / (2.5 + w / 70);
const h = bbox.height;
const shape =
`M 0,${ry} a${rx},${ry} 0,0,0 ${w} 0 a ${rx},${ry} 0,0,0 ${-w} 0 l 0,${h - 2 * ry} a ${rx},${ry} 0,0,0 ${w} 0 l 0,${-h + 2 * ry}`;
const shapeSvg = parent
.attr('label-offset-y', 2 * ry)
.insert('path', ':first-child')
.attr('d', shape)
.attr('transform', 'translate(' + -w / 2 + ',' + -(h / 2) + ')');
node.intersect = function (point: Point) {
const pos = intersectRect(node, point)
let cy = node.y + node.height / 2 - ry
if (pos.y > cy)
return intersectEllipse({x: node.x, y: cy}, rx, ry, node, point)
cy = node.y - node.height / 2 + ry
if (pos.y < cy)
return intersectEllipse({x: node.x, y: cy}, rx, ry, node, point)
return pos;
};
return shapeSvg;
}
function person(parent: D3Element, bbox: BBox, node: D3Node) {
const w = bbox.width;
const h = bbox.height;
const shape =
`M ${.38 * w},${h / 3} A${w / 2},${h / 2} 0,0,0 0 ${h / 2}
L${w / 11},${h} L${w - w / 11},${h} L${w},${h / 2}
A${w / 2},${h / 2} 0,0,0 ${w - .38 * w} ${h / 3}
A${w / 6},${w / 6} 0,1,0 ${.38 * w} ${h / 3}`;
const shapeSvg = parent
.attr('label-offset-y', h * .4)
.insert('path', ':first-child')
.attr('d', shape)
.attr('transform', 'translate(' + -w / 2 + ',' + -(h / 2) + ')');
node.intersect = function (point: Point) {
const pos = intersectRect(node, point)
return pos;
};
return shapeSvg;
}
function _ellipse(parent: D3Element, bbox: BBox, node: D3Node, rx: number, ry: number) {
const shapeSvg = parent.insert("ellipse", ":first-child")
.attr("cx", 0)
.attr("cy", 0)
.attr('rx', rx)
.attr('ry', ry)
.attr("width", node.width)
.attr("height", node.height);
node.intersect = function (point) {
return intersectEllipse(node, rx, ry, node, point)
};
return shapeSvg;
}
function circle(parent: D3Element, bbox: BBox, node: D3Node) {
return _ellipse(parent, bbox, node, node.width / 2, node.width / 2)
}
function ellipse(parent: D3Element, bbox: BBox, node: D3Node) {
return _ellipse(parent, bbox, node, node.width * .55, node.width * .45)
}
function hexagon(parent: D3Element, bbox: BBox, node: D3Node) {
const sz = node.width / 2
// drawing a hexagon from polar coords
// [0,1,2,3,4,5,6].map(i=>`${Math.sin(Math.PI/3*i+Math.PI/6).toFixed(4)},${Math.cos(Math.PI/3*i+Math.PI/6).toFixed(4)}`).join(',')
const shapeSvg = parent.insert("polygon", ":first-child")
.attr("points",
[0.5000, 0.8660, 1.0000, 0.0000, 0.5000, -0.8660, -0.5000, -0.8660, -1.0000, -0.0000, -0.5000, 0.8660, 0.5000, 0.8660].map(n => n * sz).join(','))
.attr("width", node.width)
.attr("height", node.height);
node.intersect = function (point) {
return intersectEllipse(node, node.width / 2, node.width / 2, node, point)
};
return shapeSvg;
}
function component(parent: D3Element, bbox: BBox, node: D3Node) {
const dx = node.width / 10
const shapeSvg = parent.insert('g', ':first-child')
shapeSvg.insert("rect", ":first-child")
.attr("rx", 3).attr("ry", 3)
.attr("x", -node.width / 2 - dx)
.attr("y", -node.height / 2 + dx)
.attr("width", dx * 2)
.attr("height", dx);
shapeSvg.insert("rect", ":first-child")
.attr("rx", 3).attr("ry", 3)
.attr("x", -node.width / 2 - dx)
.attr("y", -node.height / 2 + dx * 2.5)
.attr("width", dx * 2)
.attr("height", dx);
shapeSvg.insert("rect", ":first-child")
.attr("rx", 3).attr("ry", 3)
.attr("x", -node.width / 2)
.attr("y", -node.height / 2)
.attr("width", node.width)
.attr("height", node.height);
node.intersect = function (point) {
return intersectRect({x: node.x - dx / 2, y: node.y, width: node.width + dx, height: node.height}, point);
};
return shapeSvg;
}
function folder(parent: D3Element, bbox: BBox, node: D3Node) {
const dy = node.width / 20
const shapeSvg = parent
.attr('label-offset-y', dy * 2)
.insert('g', ':first-child')
shapeSvg.insert("rect", ":first-child")
.attr("rx", 3).attr("ry", 3)
.attr("x", -node.width / 2)
.attr("y", -node.height / 2 + dy * 2)
.attr("width", node.width)
.attr("height", node.height - dy * 2);
shapeSvg.insert("path", ":first-child")
.attr('d', `M0,${-node.height / 2 + 2 * dy} l${dy},${-2 * dy} h${node.width / 2 - dy * 2} v${dy * 2}`)
node.intersect = function (point) {
return intersectRect({x: node.x, y: node.y + dy / 2, width: node.width, height: node.height + dy}, point);
};
return shapeSvg;
}
function mobiledevicelandscape(parent: D3Element, bbox: BBox, node: D3Node, rounded = false) {
const dx = node.width / 8
const r = node.width / 14
const shapeSvg = parent.insert('g', ':first-child')
shapeSvg.insert('path', ':first-child')
.attr('d', `M${-node.width / 2},${-node.height / 2} l0,${node.height} M${node.width / 2},${-node.height / 2} l0,${node.height}`)
shapeSvg.insert('circle', ':first-child')
.attr('cx', -node.width / 2 - dx / 2)
.attr('cy', 0)
.attr('r', r * .4)
shapeSvg.insert('rect', ':first-child')
.attr('x', node.width / 2 + dx / 2 - r * .2)
.attr('y', -r)
.attr('width', r * .4)
.attr('height', r * 2)
shapeSvg.insert("rect", ":first-child")
.attr("rx", r)
.attr("ry", r)
.attr("x", -bbox.width / 2 - dx)
.attr("y", -bbox.height / 2)
.attr("width", bbox.width + 2 * dx)
.attr("height", bbox.height);
node.intersect = function (point) {
return intersectRect({x: node.x, y: node.y, width: node.width + 2 * dx, height: node.height}, point);
};
return shapeSvg;
}
function mobiledeviceportrait(parent: D3Element, bbox: BBox, node: D3Node) {
const dy = node.width / 8
const r = node.width / 14
const shapeSvg = parent.insert('g', ':first-child')
shapeSvg.insert('path', ':first-child')
.attr('d', `M${-node.width / 2},${-node.height / 2} l${node.width},0 M${-node.width / 2},${node.height / 2} l${node.width},0`)
shapeSvg.insert('circle', ':first-child')
.attr('cx', 0)
.attr('cy', node.height / 2 + dy / 2)
.attr('r', r * .4)
shapeSvg.insert('rect', ':first-child')
.attr('x', -r)
.attr('y', -node.height / 2 - dy / 2 - r * .2)
.attr('width', r * 2)
.attr('height', r * .4)
shapeSvg.insert("rect", ":first-child")
.attr("rx", r)
.attr("ry", r)
.attr("x", -bbox.width / 2)
.attr("y", -bbox.height / 2 - dy)
.attr("width", bbox.width)
.attr("height", bbox.height + 2 * dy);
node.intersect = function (point) {
return intersectRect({x: node.x, y: node.y, width: node.width, height: node.height + 2 * dy}, point);
};
return shapeSvg;
}
function pipe(parent: D3Element, bbox: BBox, node: D3Node) {
const w = node.width;
const h = node.height;
const ry = h / 2;
const rx = ry / (2.5 + w / 70);
const shape =
`M${-rx},0
a${rx},${ry} 0,0,1 0,${h}
a${rx},${ry} 0,0,1 0,${-h}
l${w},0
a${rx},${ry} 0,0,1 0,${h}
l${-w},0`;
const shapeSvg = parent
.insert('path', ':first-child')
.attr('d', shape)
.attr('transform', 'translate(' + -w / 2 + ',' + -(h / 2) + ')');
node.intersect = function (point: Point) {
return intersectRect({x: node.x - rx, y: node.y, width: node.width + 2 * rx, height: node.height}, point)
};
return shapeSvg;
}
function robot(parent: D3Element, bbox: BBox, node: D3Node) {
const headW = node.width * .45
const r = node.width / 16
const dy = headW / 2 - r
const shapeSvg = parent
.attr('label-offset-y', headW)
.insert('g', ':first-child')
.attr('transform', 'translate(0,' + (headW / 4) + ')');
// head
shapeSvg.insert("rect", ":first-child")
.attr("rx", r).attr("ry", r)
.attr('x', -headW / 2)
.attr('y', -node.height / 2 - headW / 2)
.attr('width', headW)
.attr('height', headW)
// ears
shapeSvg.insert("path", ":first-child")
.attr('d', `
M${-headW / 2},${-node.height / 2 + r / 2} h-20 v-40 h20
M${headW / 2},${-node.height / 2 + r / 2} h20 v-40 h-20
`)
// body
shapeSvg.insert("rect", ":first-child")
.attr("rx", r).attr("ry", r)
.attr("x", -node.width / 2)
.attr("y", -node.height / 2 + dy)
.attr("width", node.width)
.attr("height", node.height - dy);
node.intersect = function (point) {
return intersectRect({x: node.x, y: node.y, width: node.width, height: node.height + headW / 2}, point);
};
return shapeSvg;
}
function webbrowser(parent: D3Element, bbox: BBox, node: D3Node) {
const dy = node.height / 8
const shapeSvg = parent
.attr('label-offset-y', dy)
.insert('g', ':first-child')
shapeSvg.insert("path", ":first-child")
.attr('d', `
M${-node.width / 2},${-node.height / 2 + dy} h${node.width}
M${-node.width / 2 + dy / 4},${-node.height / 2 + dy / 4} h${dy / 2} v${dy / 2} h${-dy / 2} z
M${-node.width / 2 + dy},${-node.height / 2 + dy / 4} h${node.width - dy - dy / 4} v${dy / 2} h${-node.width + dy + dy / 4} z
`)
shapeSvg.insert("rect", ":first-child")
.attr("rx", 3).attr("ry", 3)
.attr("x", -node.width / 2)
.attr("y", -node.height / 2)
.attr("width", node.width)
.attr("height", node.height);
node.intersect = function (point) {
return intersectRect(node, point);
};
return shapeSvg;
}
export const shapes: { [key: string]: (parent: SVGElement, node: D3Node) => SVGElement } = {
box: (parent: SVGElement, node: D3Node) => rect(new D3Element(parent), node, node).node(),
roundedbox: (parent: SVGElement, node: D3Node) => rect(new D3Element(parent), node, node, true).node(),
component: (parent: SVGElement, node: D3Node) => component(new D3Element(parent), node, node).node(),
cylinder: (parent: SVGElement, node: D3Node) => cylinder(new D3Element(parent), node, node).node(),
person: (parent: SVGElement, node: D3Node) => person(new D3Element(parent), node, node).node(),
circle: (parent: SVGElement, node: D3Node) => circle(new D3Element(parent), node, node).node(),
ellipse: (parent: SVGElement, node: D3Node) => ellipse(new D3Element(parent), node, node).node(),
hexagon: (parent: SVGElement, node: D3Node) => hexagon(new D3Element(parent), node, node).node(),
folder: (parent: SVGElement, node: D3Node) => folder(new D3Element(parent), node, node).node(),
mobiledevicelandscape: (parent: SVGElement, node: D3Node) => mobiledevicelandscape(new D3Element(parent), node, node).node(),
mobiledeviceportrait: (parent: SVGElement, node: D3Node) => mobiledeviceportrait(new D3Element(parent), node, node).node(),
mobiledevice: (parent: SVGElement, node: D3Node) => mobiledeviceportrait(new D3Element(parent), node, node).node(),
pipe: (parent: SVGElement, node: D3Node) => pipe(new D3Element(parent), node, node).node(),
robot: (parent: SVGElement, node: D3Node) => robot(new D3Element(parent), node, node).node(),
webbrowser: (parent: SVGElement, node: D3Node) => webbrowser(new D3Element(parent), node, node).node(),
} | the_stack |
import algoliasearchHelper from 'algoliasearch-helper';
import merge from '../mergeSearchParameters';
describe('mergeSearchParameters', () => {
it('overrides non-managed parameters', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
// Inherit
hitsPerPage: 2,
attributesToSnippet: ['description'],
// Overridden
query: 'Samsung',
attributesToHighlight: ['name'],
}),
algoliasearchHelper.SearchParameters.make({
// hitsPerPage: 2,
// attributesToSnippet: ['description'],
query: 'Apple',
attributesToHighlight: ['name', 'author'],
}),
algoliasearchHelper.SearchParameters.make({
// hitsPerPage: 2,
// attributesToSnippet: ['description'],
// attributesToHighlight: ['name', 'author'],
query: 'Apple iPhone',
distinct: true,
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
hitsPerPage: 2,
attributesToSnippet: ['description'],
attributesToHighlight: ['name', 'author'],
query: 'Apple iPhone',
distinct: true,
})
);
});
it('merges `facets` parameters', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
facets: ['brand'],
}),
algoliasearchHelper.SearchParameters.make({
facets: ['categories'],
}),
algoliasearchHelper.SearchParameters.make({
facets: ['brand', 'colors'],
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
facets: ['brand', 'categories', 'colors'],
})
);
});
it('merges `disjunctiveFacets` parameters', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['brand'],
}),
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['categories'],
}),
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['brand', 'colors'],
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['brand', 'categories', 'colors'],
})
);
});
it('merges `facetsRefinements` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
facets: ['brand'],
facetsRefinements: {
brand: ['Samsung'],
},
}),
algoliasearchHelper.SearchParameters.make({
facets: ['categories'],
facetsRefinements: {
categories: ['TVs'],
},
}),
algoliasearchHelper.SearchParameters.make({
facets: ['brand', 'colors'],
facetsRefinements: {
brand: ['Apple'],
colors: ['Red'],
},
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
facets: ['brand', 'categories', 'colors'],
facetsRefinements: {
brand: ['Apple'],
categories: ['TVs'],
colors: ['Red'],
},
})
);
});
it('merges `facetsExcludes` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
facets: ['brand'],
facetsExcludes: {
brand: ['Samsung'],
},
}),
algoliasearchHelper.SearchParameters.make({
facets: ['categories'],
facetsExcludes: {
categories: ['TVs'],
},
}),
algoliasearchHelper.SearchParameters.make({
facets: ['brand', 'colors'],
facetsExcludes: {
brand: ['Apple'],
colors: ['Red'],
},
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
facets: ['brand', 'categories', 'colors'],
facetsExcludes: {
brand: ['Apple'],
categories: ['TVs'],
colors: ['Red'],
},
})
);
});
it('merges `disjunctiveFacetsRefinements` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['brand'],
disjunctiveFacetsRefinements: {
brand: ['Samsung'],
},
}),
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['categories'],
disjunctiveFacetsRefinements: {
categories: ['TVs'],
},
}),
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['brand', 'colors'],
disjunctiveFacetsRefinements: {
brand: ['Apple'],
colors: ['Red'],
},
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
disjunctiveFacets: ['brand', 'categories', 'colors'],
disjunctiveFacetsRefinements: {
brand: ['Apple'],
categories: ['TVs'],
colors: ['Red'],
},
})
);
});
it('merges `numericRefinements` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
numericRefinements: {
price: {
'>=': [10],
'<=': [100],
},
},
}),
algoliasearchHelper.SearchParameters.make({
numericRefinements: {
rating: {
'>=': [3],
},
},
}),
algoliasearchHelper.SearchParameters.make({
numericRefinements: {
price: {
'>': [100],
},
vote: {
'>=': [50],
},
},
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
numericRefinements: {
price: {
'>': [100],
},
rating: {
'>=': [3],
},
vote: {
'>=': [50],
},
},
})
);
});
it('merges `tagRefinements` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
tagRefinements: ['brand'],
}),
algoliasearchHelper.SearchParameters.make({
tagRefinements: ['categories'],
}),
algoliasearchHelper.SearchParameters.make({
tagRefinements: ['brand', 'colors'],
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
tagRefinements: ['brand', 'categories', 'colors'],
})
);
});
it('merges `hierarchicalFacets` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'categories',
attributes: ['categories.lvl0', 'categories.lvl1'],
separator: ' > ',
},
],
}),
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'department',
attributes: ['department.lvl0', 'department.lvl1'],
separator: ' > ',
},
],
}),
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'categories',
attributes: ['topLevelCategories', 'subLevelCategories'],
separator: ' > ',
},
{
name: 'folders',
attributes: ['folders.lvl0', 'folders.lvl1'],
separator: ' > ',
},
],
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'categories',
attributes: ['topLevelCategories', 'subLevelCategories'],
separator: ' > ',
},
{
name: 'department',
attributes: ['department.lvl0', 'department.lvl1'],
separator: ' > ',
},
{
name: 'folders',
attributes: ['folders.lvl0', 'folders.lvl1'],
separator: ' > ',
},
],
})
);
});
it('merges `hierarchicalFacetsRefinements` parameters, overrides conflicts', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'categories',
attributes: ['categories.lvl0', 'categories.lvl1'],
separator: ' > ',
},
],
hierarchicalFacetsRefinements: {
categories: ['Appliances > Fans'],
},
}),
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'department',
attributes: ['department.lvl0', 'department.lvl1'],
separator: ' > ',
},
],
hierarchicalFacetsRefinements: {
department: ['Engineering > Squad'],
},
}),
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'categories',
attributes: ['topLevelCategories', 'subLevelCategories'],
separator: ' > ',
},
{
name: 'folders',
attributes: ['folders.lvl0', 'folders.lvl1'],
separator: ' > ',
},
],
hierarchicalFacetsRefinements: {
categories: ['Cell Phones > Prepaid Phones'],
folders: ['Music > Artist > Mike Miller'],
},
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
hierarchicalFacets: [
{
name: 'categories',
attributes: ['topLevelCategories', 'subLevelCategories'],
separator: ' > ',
},
{
name: 'department',
attributes: ['department.lvl0', 'department.lvl1'],
separator: ' > ',
},
{
name: 'folders',
attributes: ['folders.lvl0', 'folders.lvl1'],
separator: ' > ',
},
],
hierarchicalFacetsRefinements: {
categories: ['Cell Phones > Prepaid Phones'],
department: ['Engineering > Squad'],
folders: ['Music > Artist > Mike Miller'],
},
})
);
});
it('merges and dedupes `ruleContexts` parameters', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
ruleContexts: ['ais-genre-comedy'],
}),
algoliasearchHelper.SearchParameters.make({
ruleContexts: ['ais-genre-thriller', 'ais-genre-comedy'],
}),
algoliasearchHelper.SearchParameters.make({
ruleContexts: ['ais-rating-4'],
}),
algoliasearchHelper.SearchParameters.make({
ruleContexts: [],
})
);
expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
ruleContexts: [
'ais-genre-comedy',
'ais-genre-thriller',
'ais-rating-4',
],
})
);
});
}); | the_stack |
import { decodeAddress, encodeAddress, getApplicationAddress, isValidAddress, modelsv2 } from "algosdk";
import { RUNTIME_ERRORS } from "../errors/errors-list";
import { RuntimeError } from "../errors/runtime-errors";
import { Runtime } from "../index";
import { checkIndexBound, compareArray } from "../lib/compare";
import { ALGORAND_MAX_APP_ARGS_LEN, ALGORAND_MAX_TX_ACCOUNTS_LEN, ALGORAND_MAX_TX_ARRAY_LEN, DEFAULT_STACK_ELEM, MaxAppProgramCost, MaxTEALVersion } from "../lib/constants";
import { keyToBytes } from "../lib/parsing";
import { Stack } from "../lib/stack";
import { assertMaxCost, parser } from "../parser/parser";
import {
AccountStoreI, EncTx, ExecutionMode, Operator, SSCAttributesM,
StackElem, TEALStack, TxReceipt
} from "../types";
import { Op } from "./opcode";
import { Label } from "./opcode-list";
/**
* Interpreter parses and executes a TEAL code. Each transaction is using a new instance of
* interpreter and doesn't share the interpreter state. When executing the transaction
* we create a Context (`ctx`) and pass it to the interpreter. It encapsulates
* runtime state and the transaction group state (eg shared scratch space).
* Interpreter must not modify the `runtime` - the latter will be updated during the context
* commit phase once all transactions in the groups succeed.
*/
export class Interpreter {
readonly stack: TEALStack;
tealVersion: number; // LogicSigVersion
lineToCost: { [key: number]: number }; // { <lineNo>: <OpCost> } cost of each instruction by line
gas: number; // total gas cost of TEAL code
length: number; // total length of 'compiled' TEAL code
// local stores for a transaction.
bytecblock: Uint8Array[];
intcblock: BigInt[];
scratch: StackElem[];
// TEAL parsed code - instantiated during the execution phase.
instructions: Operator[];
instructionIndex: number;
runtime: Runtime;
// The call stack is separate from the data stack. Only callsub and retsub manipulate it.
// It is used to provide sub routine functionality
callStack: Stack<number>;
labelMap: Map<string, number>; // label string mapped to their respective indexes in instructions array
subTxn: EncTx | undefined; // "current" inner transaction
innerTxns: EncTx[]; // executed inner transactions
constructor () {
this.stack = new Stack<StackElem>();
this.tealVersion = 1; // LogicSigVersion = 1 by default (if not specified by pragma)
// total cost computed during code parsing, used in TEAL <= v3
this.gas = 0;
// gas cost of each line used in TEAL >=4 (we accumulate gas when executing the code).
this.lineToCost = {};
this.length = 0; // code length
this.bytecblock = [];
this.intcblock = [];
// scratch spece used
this.scratch = new Array(256).fill(DEFAULT_STACK_ELEM);
this.instructions = [];
this.instructionIndex = 0; // set instruction index to zero
this.runtime = <Runtime>{};
this.callStack = new Stack<number>();
this.labelMap = new Map<string, number>();
this.subTxn = undefined;
this.innerTxns = [];
}
/**
* Queries ASA Definitions data by assetID. Returns undefined if ASA is not deployed.
* @param assetId Asset Index
*/
getAssetDef (assetId: number): modelsv2.AssetParams | undefined {
const accountAddr = this.runtime.ctx.state.assetDefs.get(assetId);
if (!accountAddr) return undefined;
let account = this.runtime.ctx.state.accounts.get(accountAddr);
account = this.runtime.assertAccountDefined(accountAddr, account);
return account.createdAssets.get(assetId);
}
/**
* Queries app (SSCAttributesM) from state. Throws TEAL.APP_NOT_FOUND if app is not found.
* @param appID Application Index
*/
getApp (appID: number, line: number): SSCAttributesM {
return this.runtime.ctx.getApp(appID, line);
}
/**
* Beginning from TEALv4, user can directly pass address instead of index to Txn.Accounts.
* However, the address must still be present in tx.Accounts OR should be equal to Txn.Sender
* @param accountPk public key of account
* @param line line number in TEAL file
* https://developer.algorand.org/articles/introducing-algorand-virtual-machine-avm-09-release/
*/
private _getAccountFromAddr (accountPk: Uint8Array, line: number): AccountStoreI {
const txAccounts = this.runtime.ctx.tx.apat; // tx.Accounts array
const appID = this.runtime.ctx.tx.apid ?? 0;
if (this.tealVersion <= 3) {
// address can only be passed directly since tealv4
throw new RuntimeError(RUNTIME_ERRORS.TEAL.PRAGMA_VERSION_ERROR, {
expected: MaxTEALVersion,
got: this.tealVersion,
line: line
});
}
// address must still be present in tx.Accounts OR should be equal to Txn.Sender
const pkBuffer = Buffer.from(accountPk);
const addr = encodeAddress(pkBuffer);
if (!isValidAddress(addr)) { // invalid address
throw new RuntimeError(RUNTIME_ERRORS.TEAL.ADDR_NOT_VALID, {
address: addr,
line: line
});
}
if (
txAccounts?.find(buff => compareArray(Uint8Array.from(buff), accountPk)) !== undefined ||
compareArray(accountPk, Uint8Array.from(this.runtime.ctx.tx.snd)) ||
// since tealv5, currentApplicationAddress is also allowed (directly)
compareArray(accountPk, decodeAddress(getApplicationAddress(appID)).publicKey)
) {
const address = encodeAddress(pkBuffer);
const account = this.runtime.ctx.state.accounts.get(address);
return this.runtime.assertAccountDefined(address, account, line);
} else {
throw new RuntimeError(RUNTIME_ERRORS.TEAL.ADDR_NOT_FOUND_IN_TXN_ACCOUNT, {
address: encodeAddress(pkBuffer),
line: line
});
}
}
/**
* Queries account by accountIndex or `ctx.tx.snd` (if `accountIndex==0`).
* If account address is passed, then queries account by address.
* Throws exception if account is not found.
* @param accountRef index of account to fetch from account list
* @param line line number
* NOTE: index 0 represents txn sender account
*/
getAccount (accountRef: StackElem, line: number): AccountStoreI {
let account: AccountStoreI | undefined;
let address: string;
if (typeof accountRef === 'bigint') {
if (accountRef === 0n) {
address = encodeAddress(this.runtime.ctx.tx.snd);
account = this.runtime.ctx.state.accounts.get(address);
} else {
const accIndex = accountRef - 1n;
checkIndexBound(Number(accIndex), this.runtime.ctx.tx.apat ?? [], line);
let pkBuffer;
if (this.runtime.ctx.tx.apat) {
pkBuffer = this.runtime.ctx.tx.apat[Number(accIndex)];
} else {
throw new Error("pk Buffer not found");
}
address = encodeAddress(pkBuffer);
account = this.runtime.ctx.state.accounts.get(address);
}
} else {
return this._getAccountFromAddr(accountRef, line);
}
return this.runtime.assertAccountDefined(address, account, line);
}
/**
* Queries appIndex by app reference (offset to foreignApps array OR index directly)
* + Since TEALv4, any reference is supported (but it must be present in foreignApps array)
* + For older versions, if foreign === true, reference is treated as offset to foreignApps array,
* otherwise it is treated as a direct reference.
* @param appRef an offset to foreign app array OR appID
* @param foreign for older teal versions(<= 3), foreign bool represent if ref is
* treated as an offset/appIndex
* @param line line number
* https://developer.algorand.org/articles/introducing-algorand-virtual-machine-avm-09-release/
*/
getAppIDByReference (appRef: number, foreign: boolean, line: number, op: Op): number {
const foreignApps = this.runtime.ctx.tx.apfa ?? [];
if (this.tealVersion >= 4) {
// In recent versions (tealv >= 4), accept either kind of Application reference
if (appRef === 0) {
return this.runtime.ctx.tx.apid as number;
}
if (appRef <= foreignApps.length) {
return foreignApps[appRef - 1];
}
if (foreignApps.includes(appRef) || appRef === this.runtime.ctx.tx.apid) {
return appRef;
}
} else {
// Old rules
if (foreign) {
// In old versions, a foreign reference must be an index in ForeignApps or 0
if (appRef === 0) {
return this.runtime.ctx.tx.apid as number;
}
op.checkIndexBound(--appRef, foreignApps, line);
return foreignApps[appRef];
} else {
// Otherwise it's direct
return appRef;
}
}
throw new RuntimeError(RUNTIME_ERRORS.TEAL.INVALID_APP_REFERENCE, {
appRef: appRef,
line: line
});
}
/**
* Queries assetIndex by asset reference (offset to foreignAssets array OR index directly)
* + Since TEALv4, any reference is supported (but it must be present in foreign assets array)
* + For older versions, if foreign === true, reference is treated as offset to foreignAssets array,
* otherwise it is treated as a direct reference.
* @param assetRef an offset to foreign assets array OR assetID
* @param foreign for older teal versions(<= 3), foreign bool represent if
* ref is treated as an offset/assetIndex
* @param line line number
* https://developer.algorand.org/articles/introducing-algorand-virtual-machine-avm-09-release/
*/
getAssetIDByReference (assetRef: number, foreign: boolean, line: number, op: Op): number {
const appForeignAssets = this.runtime.ctx.tx.apas ?? [];
if (this.tealVersion >= 4) {
// In recent versions (tealv >= 4), accept either kind of ASA reference
if (assetRef < appForeignAssets.length) {
return appForeignAssets[assetRef];
}
if (appForeignAssets.includes(assetRef)) {
return assetRef;
}
} else {
// Old rules
if (foreign) {
// In old versions, a foreign reference must be an index in ForeignAssets
op.checkIndexBound(assetRef, appForeignAssets, line);
return appForeignAssets[assetRef];
} else {
// Otherwise it's direct
return assetRef;
}
}
throw new RuntimeError(RUNTIME_ERRORS.TEAL.INVALID_ASA_REFERENCE, {
assetRef: assetRef,
line: line
});
}
/**
* Queries application by application index. Returns undefined if app is not found.
* @param appID: current application id
* @param key: key to fetch value of from local state
*/
getGlobalState (appID: number, key: Uint8Array | string, line: number): StackElem | undefined {
const app = this.runtime.assertAppDefined(appID, this.getApp(appID, line), line);
const appGlobalState = app["global-state"];
const globalKey = keyToBytes(key);
return appGlobalState.get(globalKey.toString());
}
/**
* Updates app global state.
* Throws error if app is not found.
* @param appID: application id
* @param key: app global state key
* @param value: value associated with a key
*/
setGlobalState (appID: number, key: Uint8Array | string, value: StackElem, line: number): void {
if (!this.runtime.ctx.state.globalApps.has(appID)) {
throw new RuntimeError(RUNTIME_ERRORS.GENERAL.APP_NOT_FOUND, { appID: appID, line: line });
}
const accAddress = this.runtime.assertAddressDefined(
this.runtime.ctx.state.globalApps.get(appID));
let account = this.runtime.ctx.state.accounts.get(accAddress);
account = this.runtime.assertAccountDefined(accAddress, account);
account.setGlobalState(appID, key, value, line);
}
/**
* Description: moves instruction index to "label", throws error if label not found
* @param label: branch label
* @param line: line number
*/
jumpForward (label: string, line: number): void {
while (++this.instructionIndex < this.instructions.length) {
const instruction = this.instructions[this.instructionIndex];
if (instruction instanceof Label && instruction.label === label) {
// if next immediate op is also label, then keep continuing, otherwise return
for (; this.instructionIndex < this.instructions.length - 1; ++this.instructionIndex) {
const nextInstruction = this.instructions[this.instructionIndex + 1];
if (!(nextInstruction instanceof Label)) { break; }
}
return;
}
}
throw new RuntimeError(RUNTIME_ERRORS.TEAL.LABEL_NOT_FOUND, {
label: label,
line: line
});
}
/**
* Description: moves instruction index to "label", throws error if label not found
* @param label: branch label
* @param line: line number
*/
jumpToLabel (label: string, line: number): void {
const toInstructionIndex = this.labelMap.get(label);
if (toInstructionIndex === undefined) {
throw new RuntimeError(RUNTIME_ERRORS.TEAL.LABEL_NOT_FOUND, {
label: label,
line: line
});
}
let currentIndex = toInstructionIndex;
// if next immediate op is also label, then keep continuing, otherwise return
for (; currentIndex < this.instructions.length - 1; ++currentIndex) {
const nextInstruction = this.instructions[currentIndex + 1];
if (!(nextInstruction instanceof Label)) {
this.instructionIndex = currentIndex;
break;
}
}
}
/**
* logs TEALStack upto depth = debugStack to console
* @param instruction interpreter opcode instance
* @param debugStack max no. of elements to print from top of stack
*/
printStack (instruction: Operator, debugStack?: number): void {
if (!debugStack) { return; }
console.info("stack(depth = %s) for opcode %s at line %s:",
debugStack,
instruction.constructor.name,
instruction.line
);
const stack = this.stack.debug(debugStack);
for (const top of stack) { console.log(" %O", top); }
console.log("\n");
}
/**
* Maps labels with indexes according to instructions array
*/
mapLabelWithIndexes (): void {
this.instructions.forEach((instruction, idx) => {
if (instruction instanceof Label) {
this.labelMap.set(instruction.label, idx);
}
});
}
/* Assets transaction references (apps, assets, accounts) lengths are valid:
* 1. Application args are limited to max. size of 16.
* 2. The AVM limits the accounts array to no more than 4
* 3. Assets and application arrays combined and totaled with the accounts array can not exceed 8
* https://developer.algorand.org/articles/introducing-algorand-virtual-machine-avm-09-release/
*/
assertValidTxArray (): void {
const [appArgsLen, foreignAppsLen, foreignAssetsLen, txAccountsLen] = [
this.runtime.ctx.tx.apaa?.length ?? 0,
this.runtime.ctx.tx.apfa?.length ?? 0,
this.runtime.ctx.tx.apas?.length ?? 0,
this.runtime.ctx.tx.apat?.length ?? 0
];
if (appArgsLen > ALGORAND_MAX_APP_ARGS_LEN) {
throw new RuntimeError(RUNTIME_ERRORS.GENERAL.INVALID_APP_ARGS_LEN, {
len: appArgsLen,
max: ALGORAND_MAX_APP_ARGS_LEN
});
}
if (txAccountsLen > ALGORAND_MAX_TX_ACCOUNTS_LEN) {
throw new RuntimeError(RUNTIME_ERRORS.GENERAL.INVALID_TX_ACCOUNTS_LEN, {
len: txAccountsLen,
max: ALGORAND_MAX_TX_ACCOUNTS_LEN
});
}
const totalLen = txAccountsLen + foreignAppsLen + foreignAssetsLen;
if (totalLen > ALGORAND_MAX_TX_ARRAY_LEN) {
throw new RuntimeError(RUNTIME_ERRORS.GENERAL.MAX_REFERENCES_EXCEEDED, {
len: totalLen,
max: ALGORAND_MAX_TX_ARRAY_LEN
});
}
}
/**
* This function executes TEAL code after parsing
* @param program: teal code
* @param mode : execution mode of TEAL code (Stateless or Stateful)
* @param runtime : runtime object
* @param debugStack: if passed then TEAL Stack is logged to console after
* each opcode execution (upto depth = debugStack)
*/
execute (program: string, mode: ExecutionMode, runtime: Runtime, debugStack?: number): void {
const result = this.executeWithResult(program, mode, runtime, debugStack);
if (result !== undefined && typeof result === 'bigint' && result > 0n) {
return;
}
throw new RuntimeError(RUNTIME_ERRORS.TEAL.REJECTED_BY_LOGIC);
}
/**
* This function executes TEAL code after parsing and returns the result of the program.
* @param program: teal code
* @param mode : execution mode of TEAL code (smart signature or contract)
* @param runtime : runtime object
* @param debugStack: if passed then TEAL Stack is logged to console after
* each opcode execution (upto depth = debugStack)
* @returns The final result on the stack or undefined if nothing was on the stack.
* NOTE: program should fail if there is no result (stack is empty after the execution) or
* the result is zero.
*/
executeWithResult (program: string, mode: ExecutionMode, runtime: Runtime,
debugStack?: number): StackElem | undefined {
this.runtime = runtime;
this.instructions = parser(program, mode, this);
this.mapLabelWithIndexes();
if (mode === ExecutionMode.APPLICATION) { this.assertValidTxArray(); }
let dynamicCost = 0;
while (this.instructionIndex < this.instructions.length) {
const instruction = this.instructions[this.instructionIndex];
instruction.execute(this.stack);
const txReceipt = this.runtime.ctx.state.txReceipts.get(this.runtime.ctx.tx.txID) as TxReceipt;
// for teal version >= 4, cost is calculated dynamically at the time of execution
// for teal version < 4, cost is handled statically during parsing
dynamicCost += this.lineToCost[instruction.line];
if (this.tealVersion < 4) { txReceipt.gas = this.gas; }
if (this.tealVersion >= 4) {
if (mode === ExecutionMode.SIGNATURE) {
assertMaxCost(dynamicCost, mode);
txReceipt.gas = dynamicCost;
} else {
this.runtime.ctx.pooledApplCost += this.lineToCost[instruction.line];
const maxPooledApplCost = MaxAppProgramCost * this.runtime.ctx.gtxs.length;
assertMaxCost(this.runtime.ctx.pooledApplCost, ExecutionMode.APPLICATION, maxPooledApplCost);
txReceipt.gas = this.runtime.ctx.pooledApplCost;
}
}
this.printStack(instruction, debugStack);
this.instructionIndex++;
}
let result: StackElem | undefined;
if (this.stack.length() === 1) {
result = this.stack.pop();
}
return result;
}
} | the_stack |
import {
DiscordooProviders,
EventNames,
GlobalCachingPolicy,
IpcEvents,
IpcOpCodes,
otherCacheSymbol,
REST_DEFAULT_OPTIONS,
WS_DEFAULT_OPTIONS
} from '@src/constants'
import {
DiscordooError,
DiscordooSnowflake,
ReplaceType,
resolveDiscordooShards,
resolveDiscordShards,
ShardListResolvable,
version
} from '@src/utils'
import { CompletedLocalIpcOptions } from '@src/constants/sharding/CompletedLocalIpcOptions'
import { CompletedGatewayOptions } from '@src/gateway/interfaces/CompletedGatewayOptions'
import { ClientMessagesManager } from '@src/api/managers/messages/ClientMessagesManager'
import { ClientChannelsManager } from '@src/api/managers/channels/ClientChannelsManager'
import { ClientStickersManager } from '@src/api/managers/stickers/ClientStickersManager'
import { LOCAL_IPC_DEFAULT_OPTIONS } from '@src/constants/sharding/IpcDefaultOptions'
import { ClientGuildMembersManager } from '@src/api/managers/members/ClientGuildMembersManager'
import { CompletedCacheOptions } from '@src/cache/interfaces/CompletedCacheOptions'
import { ClientShardingMetadata } from '@src/core/client/ClientShardingMetadata'
import { CompletedRestOptions } from '@src/rest/interfaces/CompletedRestOptions'
import { CACHE_OPTIONS_KEYS_LENGTH } from '@src/cache/interfaces/CacheOptions'
import { ProviderConstructor } from '@src/core/providers/ProviderConstructor'
import { DefaultGatewayProvider } from '@src/gateway/DefaultGatewayProvider'
import { DefaultClientStack } from '@src/core/client/DefaultClientStack'
import { DefaultCacheProvider } from '@src/cache/DefaultCacheProvider'
import { DefaultRestProvider } from '@src/rest/DefaultRestProvider'
import { ClientInternals } from '@src/core/client/ClientInternals'
import { ClientMetadata } from '@src/core/client/ClientMetadata'
import { ClientOptions } from '@src/core/client/ClientOptions'
import { ClientActions } from '@src/core/client/ClientActions'
import {
ChannelCreateEvent,
ChannelDeleteEvent,
ChannelPinsUpdateEvent,
ChannelUpdateEvent,
ClientEvents,
MessageCreateEvent,
ThreadCreateEvent,
ThreadDeleteEvent,
ThreadListSyncEvent,
ThreadUpdateEvent
} from '@src/events'
import { UsersManager } from '@src/api/managers/UsersManager'
import { ClientRolesManager } from '@src/api/managers/roles'
import { GatewayManager } from '@src/gateway/GatewayManager'
import { GatewayShardsInfo } from '@discordoo/providers'
import { LocalIpcServer } from '@src/sharding/ipc/LocalIpcServer'
import { CacheManager } from '@src/cache/CacheManager'
import { RestManager } from '@src/rest/RestManager'
import { TypedEmitter } from 'tiny-typed-emitter'
import { GuildsManager } from '@src/api/managers'
import { Final } from '@src/utils/FinalDecorator'
import { IpcServerOptions } from '@src/sharding'
import { EntitiesUtil } from '@src/api/entities/EntitiesUtil'
import { ClientPresencesManager } from '@src/api/managers/presences'
import { ClientReactionsManager } from '@src/api/managers/reactions/ClientReactionsManager'
import { ClientPermissionOverwritesManager } from '@src/api/managers/overwrites/ClientPermissionOverwritesManager'
import { GuildCreateEvent } from '@src/events/GuildCreateEvent'
import { PresenceUpdateEvent } from '@src/events/PresenceUpdateEvent'
import { ClientQueues } from '@src/core/client/ClientQueues'
import { Collection } from '@discordoo/collection'
import { OtherCacheManager } from '@src/api/managers/OtherCacheManager'
import { ClientThreadMembersManager } from '@src/api/managers/members/ClientThreadMembersManager'
import { ShardConnectedEvent } from '@src/events/ShardConnectedEvent'
import { GuildMembersChunkEvent } from '@src/events/GuildMembersChunkEvent'
import { ClientEmojisManager } from '@src/api/managers/emoji/ClientEmojisManager'
import { ClientShardingApplication } from '@src/core/client/app/ClientShardingApplication'
import { BroadcastEvalOptions } from '@src/sharding/interfaces/ipc/BroadcastEvalOptions'
import { BroadcastOptions } from '@src/sharding/interfaces/ipc/BroadcastOptions'
import { fromJson, toJson } from '@src/utils/toJson'
import { evalWithoutScopeChain } from '@src/utils/evalWithoutScopeChain'
import {
IpcBroadcastEvalRequestPacket,
IpcBroadcastEvalResponsePacket,
IpcBroadcastMessagePacket
} from '@src/sharding/interfaces/ipc/IpcPackets'
import { deserializeError } from 'serialize-error'
import { is } from 'typescript-is'
/** Entry point for all of Discordoo. */
@Final(
'start',
'internals',
'guilds',
'users',
'messages',
'channels',
'stickers',
'members',
'roles',
'presences',
'reactions',
'overwrites',
otherCacheSymbol,
'token',
)
export class Client<ClientStack extends DefaultClientStack = DefaultClientStack>
// @ts-ignore because events can be redefined, and the typed emitter library doesn't like it.
extends TypedEmitter<ClientStack['events']> {
/** Token used by this client */
public readonly token: string
/** Internal things used by this client */
public readonly internals: ClientInternals<ClientStack>
/** Options passed to this client */
public readonly options: ClientOptions
/** Guilds manager for this client */
public readonly guilds: GuildsManager
/** Users manager for this client */
public readonly users: UsersManager
/** Messages manager for this client */
public readonly messages: ClientMessagesManager
/** Channels manager for this client */
public readonly channels: ClientChannelsManager
/** Stickers manager for this client */
public readonly stickers: ClientStickersManager
/** Members manager for this client */
public readonly members: ClientGuildMembersManager
/** Roles manager for this client */
public readonly roles: ClientRolesManager
/** Presences manager for this client */
public readonly presences: ClientPresencesManager
/** Reactions manager for this client */
public readonly reactions: ClientReactionsManager
/** Permissions Overwrites manager for this client */
public readonly overwrites: ClientPermissionOverwritesManager
/** Thread Members manager for this client */
public readonly threadMembers: ClientThreadMembersManager
/** Emojis manager for this client */
public readonly emojis: ClientEmojisManager
public readonly [otherCacheSymbol]: OtherCacheManager
#running = false
#shardsConnected = 0
public readyDate?: Date
constructor(token: string, options: ClientOptions = {}) {
super()
options.extenders?.forEach(extender => {
EntitiesUtil.extend(extender.entity, extender.extender)
})
this.token = token
this.options = options
const gatewayOptions: CompletedGatewayOptions = this._makeGatewayOptions()
const restOptions: CompletedRestOptions = this._makeRestOptions()
const cacheOptions: CompletedCacheOptions = this._makeCacheOptions()
const ipcOptions: CompletedLocalIpcOptions = this._makeLocalIpcOptions()
let restProvider: ProviderConstructor<ClientStack['rest']> = DefaultRestProvider
let cacheProvider: ProviderConstructor<ClientStack['cache']> = DefaultCacheProvider
let gatewayProvider: ProviderConstructor<ClientStack['gateway']> = DefaultGatewayProvider
let restProviderOptions, gatewayProviderOptions, cacheProviderOptions
const MANAGER_IPC = process.env.SHARDING_MANAGER_IPC ?? DiscordooSnowflake.generatePartial()
const INSTANCE_IPC = process.env.SHARDING_INSTANCE_IPC ?? DiscordooSnowflake.generatePartial()
this.options.providers?.forEach(provider => {
try {
switch (provider.provide) {
case DiscordooProviders.CACHE:
cacheProvider = provider.useClass
cacheProviderOptions = provider.useOptions
break
case DiscordooProviders.GATEWAY:
gatewayProvider = provider.useClass
gatewayProviderOptions = provider.useOptions
break
case DiscordooProviders.REST:
restProvider = provider.useClass
restProviderOptions = provider.useOptions
break
}
} catch (e) {
throw new DiscordooError('Client#constructor', 'one of providers threw error when initialized:', e)
}
})
const shardingMetadata: ClientShardingMetadata = {
MANAGER_IPC,
INSTANCE_IPC,
instance: parseInt(process.env.SHARDING_INSTANCE ?? '0'),
shards: gatewayOptions.shards,
totalShards: gatewayOptions.totalShards,
active: DiscordooSnowflake.deconstruct(MANAGER_IPC).shardId === DiscordooSnowflake.SHARDING_MANAGER_ID,
}
const rest = new RestManager<ClientStack['rest']>(
this,
restProvider,
{ restOptions, providerOptions: restProviderOptions }
)
const cache = new CacheManager<ClientStack['cache']>(
this,
cacheProvider,
{ cacheOptions, providerOptions: cacheProviderOptions }
)
const gateway = new GatewayManager<ClientStack['gateway']>(
this,
gatewayProvider,
{ gatewayOptions, providerOptions: gatewayProviderOptions }
)
const ipc = new LocalIpcServer(
this,
this._makeIpcServerOptions(ipcOptions, shardingMetadata)
)
const allCacheDisabled = (() => {
if (this.options.cache?.global?.policies.includes(GlobalCachingPolicy.NONE)) return true
const options = Object.entries(this.options.cache ?? {})
const total = options.length, defaultTotal = CACHE_OPTIONS_KEYS_LENGTH
if (total === 0 || total < defaultTotal) return false
let disabled = 0
for (const [ policy ] of options) {
if (policy.includes('none')) disabled++
}
return defaultTotal === disabled
})()
const clientMetadata: ClientMetadata = {
version,
shardingUsed: shardingMetadata.active,
restRateLimitsDisabled: restOptions.rateLimits.disable === true,
restVersion: restOptions.version,
gatewayVersion: gatewayOptions.version,
allCacheDisabled,
machinesShardingUsed: false // not supported yet
}
const actions = new ClientActions(this), events = new ClientEvents(this)
const queues: ClientQueues = {
members: new Collection(),
ready: new Collection()
}
this.internals = {
rest,
cache,
gateway,
sharding: shardingMetadata,
ipc,
actions,
events,
metadata: clientMetadata,
queues,
}
this.internals.events.register([
MessageCreateEvent, GuildCreateEvent, PresenceUpdateEvent, ShardConnectedEvent,
ChannelCreateEvent, ChannelUpdateEvent, ChannelDeleteEvent, ChannelPinsUpdateEvent,
ThreadCreateEvent, ThreadUpdateEvent, ThreadDeleteEvent, ThreadListSyncEvent,
GuildMembersChunkEvent,
]) // TODO
this.overwrites = new ClientPermissionOverwritesManager(this)
this.threadMembers = new ClientThreadMembersManager(this)
this[otherCacheSymbol] = new OtherCacheManager(this)
this.members = new ClientGuildMembersManager(this)
this.presences = new ClientPresencesManager(this)
this.reactions = new ClientReactionsManager(this)
this.messages = new ClientMessagesManager(this)
this.channels = new ClientChannelsManager(this)
this.stickers = new ClientStickersManager(this)
this.emojis = new ClientEmojisManager(this)
this.roles = new ClientRolesManager(this)
this.guilds = new GuildsManager(this)
this.users = new UsersManager(this)
}
async start(): Promise<Client<ClientStack>> {
if (this.#running) throw new DiscordooError('Client#start', 'Client already running.')
this.#running = true
let options: GatewayShardsInfo | undefined
if (this.internals.sharding.active) {
// sharding manager sends to us sharding information (shards - array of shards to serve)
const { d: { shards, total_shards: totalShards } } = await this.internals.ipc.serve()
this.internals.sharding.shards = shards
this.internals.sharding.totalShards = totalShards
options = {
shards,
totalShards,
}
}
await this.internals.gateway.init()
await this.internals.cache.init()
await this.internals.rest.init()
await this.internals.gateway.connect(options)
.then(async () => {
if (this.internals.sharding.active) await this.internals.ipc.send({
op: IpcOpCodes.DISPATCH,
t: IpcEvents.CONNECTED,
d: {
event_id: this.internals.sharding.INSTANCE_IPC,
}
})
})
.catch(async e => {
if (this.internals.sharding.active) await this.internals.ipc.send({
op: IpcOpCodes.ERROR,
d: {
event_id: this.internals.sharding.INSTANCE_IPC,
error: e
}
})
throw e
})
return new Promise(resolve => {
const interval: NodeJS.Timeout = setInterval(() => {
if (this._ready) {
// @ts-ignore
this.emit(EventNames.READY, { client: this })
clearInterval(interval)
this.readyDate = new Date()
resolve(this)
}
}, 1000) as any // HELLO JEST!! THIS IS FOR YOU.
})
}
get sharding(): ClientShardingApplication {
return {
client: this,
active: this.internals.sharding.active,
shards: this.internals.sharding.shards,
totalShards: this.internals.sharding.totalShards,
instance: this.internals.sharding.instance,
async eval<R = any, C = Record<any, any>>(
script: string | ((context: (C & { client: Client })) => any), options?: BroadcastEvalOptions
): Promise<R[]> {
const context = {
...options?.context ? toJson(options?.context) : {}
}
const type = typeof script
if (type !== 'string' && type !== 'function') {
throw new DiscordooError('ClientShardingApplication#eval', 'Script to eval must be function or string.')
}
const func = type === 'string'
? `(async (context) => { ${script} })`
: `(${script})`
if (!this.active) {
context.client = this.client
const result = await evalWithoutScopeChain(context, func)
return toJson([ result ])
} else {
const request: IpcBroadcastEvalRequestPacket = {
op: IpcOpCodes.DISPATCH,
t: IpcEvents.BROADCAST_EVAL,
d: {
event_id: this.client.internals.ipc.generate(),
script: func,
shards: resolveDiscordooShards(this.client, options?.instance ?? 'all'),
context,
}
}
return this.client.internals.ipc.send<IpcBroadcastEvalResponsePacket>(
request, { waitResponse: true }
)
.then(r => fromJson(r.d.result)) // convert bigint pointer to bigint
.catch(p => { throw p.d?.result ? deserializeError(p.d.result) : p })
}
},
send(message: string, options?: BroadcastOptions): unknown {
if (!is<string>(message)) {
throw new DiscordooError('ClientShardingApplication#broadcast', 'Message must be string.')
}
const shards = resolveDiscordooShards(this.client, options?.instance ?? 'all')
if (!this.active) {
if (shards.includes(this.instance)) {
this.client.emit('ipcMessage', {
from: this.instance,
message
})
}
} else {
const packet: IpcBroadcastMessagePacket = {
op: IpcOpCodes.DISPATCH,
t: IpcEvents.MESSAGE,
d: {
event_id: this.client.internals.ipc.generate(),
message,
shards,
from: this.instance
}
}
void this.client.internals.ipc.send(packet)
}
return undefined
}
}
}
get readyTimestamp(): number | undefined {
return this.readyDate?.getTime()
}
private _makeGatewayOptions(): CompletedGatewayOptions {
const options: ReplaceType<CompletedGatewayOptions, 'shards', ShardListResolvable> =
Object.assign(
{},
WS_DEFAULT_OPTIONS,
{ token: this.token },
this.options.gateway
)
const shards = resolveDiscordShards(options.shards)
const totalShards = shards.length
return {
...options,
shards,
totalShards,
}
}
private _makeRestOptions(): CompletedRestOptions {
return Object.assign(
{},
REST_DEFAULT_OPTIONS,
{ auth: `Bot ${this.token}` },
this.options.rest
)
}
private _makeCacheOptions(): CompletedCacheOptions {
return this.options.cache ?? {}
}
private _makeLocalIpcOptions(): CompletedLocalIpcOptions {
return Object.assign(
{},
LOCAL_IPC_DEFAULT_OPTIONS,
this.options.ipc
)
}
private _makeIpcServerOptions(completedOptions: CompletedLocalIpcOptions, metadata: ClientShardingMetadata): IpcServerOptions {
const { MANAGER_IPC, INSTANCE_IPC, instance } = metadata
return Object.assign(
{},
{ MANAGER_IPC, INSTANCE_IPC, instance },
{ config: completedOptions }
)
}
private get _ready(): boolean {
return this.#shardsConnected >= this.internals.sharding.shards.length
}
public _increaseConnected() {
this.#shardsConnected++
}
toJSON() {
return `[client ${this.constructor.name}]`
}
} | the_stack |
import * as html from "../ast/ast";
import * as i18n from "../ast/i18n_ast";
import {I18nError} from "../ast/parse_util";
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from "../ast/interpolation_config";
import {createI18nMessageFactory} from "./i18n";
import {Parser, ParseTreeResult} from "../ast/parser";
import {getHtmlTagDefinition} from "../ast/html_tags";
import {I18nMessagesById, PlaceholderMapper} from "../serializers/serializer";
import {MissingTranslationStrategy} from "@angular/core";
const _I18N_ATTR = "i18n";
export interface MessageMetadata {
meaning?: string;
description?: string;
id?: string;
}
export class HtmlParser extends Parser {
constructor(private interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
super(getHtmlTagDefinition);
}
parse(source: string, url: string, parseExpansionForms = false): ParseTreeResult {
return super.parse(source, url, parseExpansionForms, this.interpolationConfig);
}
/**
* Extract translatable messages from an html AST
*/
extractMessages(nodes: html.Node[]): ExtractionResult {
const visitor = new Visitor(["wrapper"]);
// Construct a single fake root element
const wrapper = new html.Element("wrapper", [], nodes, undefined!, undefined, undefined);
return visitor.extract(wrapper, this.interpolationConfig);
}
mergeTranslations(
nodes: html.Node[],
translations: TranslationBundle,
params: {[key: string]: any},
metadata?: MessageMetadata,
implicitTags: string[] = []
): ParseTreeResult {
const visitor = new Visitor(implicitTags);
// Construct a single fake root element
const wrapper = new html.Element("wrapper", [], nodes, undefined!, undefined, undefined);
return visitor.merge(wrapper, translations, this.interpolationConfig, params, metadata);
}
}
export class ExtractionResult {
constructor(public messages: i18n.Message[], public errors: I18nError[]) {}
}
/**
* A container for translated messages
*/
export class TranslationBundle {
private i18nToHtml: I18nToHtmlVisitor;
constructor(
private i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {},
public digest: (m: i18n.Message) => string,
interpolationConfig: InterpolationConfig,
missingTranslationStrategy: MissingTranslationStrategy,
public mapperFactory?: (m: i18n.Message) => PlaceholderMapper,
console?: Console
) {
this.i18nToHtml = new I18nToHtmlVisitor(
i18nNodesByMsgId,
digest,
mapperFactory!,
missingTranslationStrategy,
interpolationConfig,
console
);
}
// Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
static load(
content: string,
url: string,
digest: (message: i18n.Message) => string,
createNameMapper: (message: i18n.Message) => PlaceholderMapper | null,
loadFct: (content: string, url: string) => I18nMessagesById,
missingTranslationStrategy: MissingTranslationStrategy,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG
): TranslationBundle {
const i18nNodesByMsgId = loadFct(content, url);
const digestFn = (m: i18n.Message) => digest(m);
const mapperFactory = (m: i18n.Message) => createNameMapper(m)!;
return new TranslationBundle(
i18nNodesByMsgId,
digestFn,
interpolationConfig,
missingTranslationStrategy,
mapperFactory,
console
);
}
// Returns the translation as HTML nodes from the given source message.
get(srcMsg: i18n.Message, params): html.Node[] {
const htmlRes = this.i18nToHtml.convert(srcMsg, params);
if (htmlRes.errors.length) {
throw new Error(htmlRes.errors.join("\n"));
}
return htmlRes.nodes;
}
has(srcMsg: i18n.Message): boolean {
return this.digest(srcMsg) in this.i18nNodesByMsgId;
}
}
class I18nToHtmlVisitor implements i18n.Visitor {
private _srcMsg: i18n.Message;
private _contextStack: {msg: i18n.Message; mapper: (name: string) => string}[] = [];
private _errors: I18nError[] = [];
private _mapper: (name: string) => string;
private _params: {[key: string]: any};
private _paramKeys: string[];
constructor(
private _i18nNodesByMsgId: {[msgId: string]: i18n.Node[]} = {},
private _digest: (m: i18n.Message) => string,
private _mapperFactory: (m: i18n.Message) => PlaceholderMapper,
private _missingTranslationStrategy: MissingTranslationStrategy,
private _interpolationConfig?: InterpolationConfig,
private _console?: Console
) {}
convert(srcMsg: i18n.Message, params: {[key: string]: any}): {nodes: html.Node[]; errors: I18nError[]} {
this._contextStack.length = 0;
this._errors.length = 0;
this._params = params;
this._paramKeys = Object.keys(params);
// i18n to text
const text = this.convertToText(srcMsg);
// text to html
const url = srcMsg.nodes[0].sourceSpan.start.file.url;
const htmlParser = new HtmlParser().parse(text, url, true);
return {
nodes: htmlParser.rootNodes,
errors: [...this._errors, ...htmlParser.errors]
};
}
visitText(text: i18n.Text, context?: any): string {
return text.value;
}
visitContainer(container: i18n.Container, context?: any): any {
return container.children.map(n => n.visit(this)).join("");
}
visitIcu(icu: i18n.Icu, context?: any): any {
const cases = Object.keys(icu.cases).map(k => `${k} {${icu.cases[k].visit(this)}}`);
// TODO(vicb): Once all format switch to using expression placeholders
// we should throw when the placeholder is not in the source message
const exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression)
? this._srcMsg.placeholders[icu.expression]
: icu.expression;
return `{${exp}, ${icu.type}, ${cases.join(" ")}}`;
}
visitPlaceholder(ph: i18n.Placeholder, context?: any): string {
const phName = this._mapper(ph.name);
if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
return this.convertToValue(this._srcMsg.placeholders[phName]);
}
if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
return this.convertToText(this._srcMsg.placeholderToMessage[phName]);
}
this._addError(ph, `Unknown placeholder "${ph.name}"`);
return "";
}
// Loaded message contains only placeholders (vs tag and icu placeholders).
// However when a translation can not be found, we need to serialize the source message
// which can contain tag placeholders
visitTagPlaceholder(ph: i18n.TagPlaceholder, context?: any): string {
const tag = `${ph.tag}`;
const attrs = Object.keys(ph.attrs)
.map(name => `${name}="${ph.attrs[name]}"`)
.join(" ");
if (ph.isVoid) {
return `<${tag} ${attrs}/>`;
}
const children = ph.children.map((c: i18n.Node) => c.visit(this)).join("");
return `<${tag} ${attrs}>${children}</${tag}>`;
}
// Loaded message contains only placeholders (vs tag and icu placeholders).
// However when a translation can not be found, we need to serialize the source message
// which can contain tag placeholders
visitIcuPlaceholder(ph: i18n.IcuPlaceholder, context?: any): string {
// An ICU placeholder references the source message to be serialized
return this.convertToText(this._srcMsg.placeholderToMessage[ph.name]);
}
/**
* Convert a source message to a translated text string:
* - text nodes are replaced with their translation,
* - placeholders are replaced with their content,
* - ICU nodes are converted to ICU expressions.
*/
private convertToText(srcMsg: i18n.Message): string {
const id = this._digest(srcMsg);
const mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
let nodes: i18n.Node[];
this._contextStack.push({msg: this._srcMsg, mapper: this._mapper});
this._srcMsg = srcMsg;
if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
// When there is a translation use its nodes as the source
// And create a mapper to convert serialized placeholder names to internal names
nodes = this._i18nNodesByMsgId[id];
this._mapper = (name: string) => (mapper ? mapper.toInternalName(name)! : name);
} else {
// When no translation has been found
// - report an error / a warning / nothing,
// - use the nodes from the original message
// - placeholders are already internal and need no mapper
if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
this._addError(srcMsg.nodes[0], `Missing translation for message "${id}"`);
} else if (this._console && this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
this._console.warn(`Missing translation for message "${id}"`);
}
nodes = srcMsg.nodes;
this._mapper = (name: string) => name;
}
const text = nodes.map(node => node.visit(this)).join("");
const context = this._contextStack.pop()!;
this._srcMsg = context.msg;
this._mapper = context.mapper;
return text;
}
private convertToValue(placeholder: string): string {
const param = placeholder.replace(this._interpolationConfig.start, "").replace(this._interpolationConfig.end, "");
return this._paramKeys.indexOf(param) !== -1 ? this._params[param] : placeholder;
}
private _addError(el: i18n.Node, msg: string) {
this._errors.push(new I18nError(el.sourceSpan, msg));
}
}
enum VisitorMode {
Extract,
Merge
}
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class Visitor implements html.Visitor {
private depth: number;
// <el i18n>...</el>
private inI18nNode: boolean;
private inImplicitNode: boolean;
// <!--i18n-->...<!--/i18n-->
private inI18nBlock: boolean;
private blockChildren: html.Node[] = [];
private blockStartDepth: number;
// {<icu message>}
private inIcu: boolean;
// set to void 0 when not in a section
private msgCountAtSectionStart: number | undefined;
private errors: I18nError[];
private mode: VisitorMode;
// VisitorMode.Extract only
private messages: i18n.Message[];
// VisitorMode.Merge only
private translations: TranslationBundle;
private createI18nMessage: (msg: html.Node[], meaning: string, description: string, id: string) => i18n.Message;
private metadata: MessageMetadata;
private params: {[key: string]: any};
constructor(private _implicitTags: string[] = []) {}
/**
* Extracts the messages from the tree
*/
extract(node: html.Node, interpolationConfig: InterpolationConfig): ExtractionResult {
this.init(VisitorMode.Extract, interpolationConfig);
node.visit(this, null);
if (this.inI18nBlock) {
this._reportError(node, "Unclosed block");
}
return new ExtractionResult(this.messages, this.errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(
node: html.Node,
translations: TranslationBundle,
interpolationConfig: InterpolationConfig,
params: {[key: string]: any},
metadata: MessageMetadata = {}
): ParseTreeResult {
this.init(VisitorMode.Merge, interpolationConfig, params);
this.translations = translations;
this.metadata = metadata;
const translatedNode = node.visit(this, null);
if (this.inI18nBlock) {
this._reportError(node, "Unclosed block");
}
return new ParseTreeResult(translatedNode.children, this.errors);
}
visitExpansionCase(icuCase: html.ExpansionCase, context: any): any {
// Parse cases for translatable html attributes
const expression = html.visitAll(this, icuCase.expression, context);
if (this.mode === VisitorMode.Merge) {
return new html.ExpansionCase(
icuCase.value,
expression,
icuCase.sourceSpan,
icuCase.valueSourceSpan,
icuCase.expSourceSpan
);
}
}
visitExpansion(icu: html.Expansion, context: any): html.Expansion {
this.mayBeAddBlockChildren(icu);
const wasInIcu = this.inIcu;
if (!this.inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this.isInTranslatableSection) {
this.addMessage([icu]);
}
this.inIcu = true;
}
const cases = html.visitAll(this, icu.cases, context);
if (this.mode === VisitorMode.Merge) {
icu = new html.Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this.inIcu = wasInIcu;
return icu;
}
visitComment(comment: html.Comment, context: any): any {
return;
}
visitText(text: html.Text, context: any): html.Text {
if (this.isInTranslatableSection) {
this.mayBeAddBlockChildren(text);
}
return text;
}
visitElement(el: html.Element, context: any): html.Element | null {
this.mayBeAddBlockChildren(el);
this.depth++;
const wasInI18nNode = this.inI18nNode;
const wasInImplicitNode = this.inImplicitNode;
let childNodes: html.Node[] = [];
let translatedChildNodes: html.Node[] = undefined!;
// Extract:
// - top level nodes with the (implicit) "i18n" attribute if not already in a section
// - ICU messages
const i18nAttr = getI18nAttr(el);
const isImplicit = this._implicitTags.some(tag => el.name === tag) && !this.inIcu && !this.isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this.inImplicitNode = wasInImplicitNode || isImplicit;
if (!this.isInTranslatableSection && !this.inIcu) {
if (i18nAttr || isTopLevelImplicit) {
this.inI18nNode = true;
const message = this.addMessage(el.children, this.metadata)!;
translatedChildNodes = this.translateMessage(el, message);
}
if (this.mode === VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable) {
this.openTranslatableSection(el);
}
html.visitAll(this, el.children);
if (isTranslatable) {
this._closeTranslatableSection(el, el.children);
}
}
} else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(el, "Could not mark an element as translatable inside a translatable section");
}
if (this.mode === VisitorMode.Extract) {
// Descend into child nodes for extraction
html.visitAll(this, el.children);
}
}
if (this.mode === VisitorMode.Merge) {
const visitNodes = translatedChildNodes || el.children;
visitNodes.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this.isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
this.depth--;
this.inI18nNode = wasInI18nNode;
this.inImplicitNode = wasInImplicitNode;
if (this.mode === VisitorMode.Merge) {
return new html.Element(el.name, [], childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
}
return null;
}
visitAttribute(attribute: html.Attribute, context: any): any {
throw new Error("unreachable code");
}
private init(mode: VisitorMode, interpolationConfig: InterpolationConfig, params: {[key: string]: any} = {}): void {
this.mode = mode;
this.inI18nBlock = false;
this.inI18nNode = false;
this.depth = 0;
this.inIcu = false;
this.msgCountAtSectionStart = undefined;
this.errors = [];
this.messages = [];
this.inImplicitNode = false;
this.createI18nMessage = createI18nMessageFactory(interpolationConfig);
this.params = params;
}
// add a translatable message
private addMessage(ast: html.Node[], {meaning = "", description = "", id = ""} = {}): i18n.Message | null {
if (
ast.length === 0 ||
(ast.length === 1 && ast[0] instanceof html.Attribute && !(ast[0] as html.Attribute).value)
) {
// Do not create empty messages
return null;
}
const message = this.createI18nMessage(ast, meaning, description, id);
this.messages.push(message);
return message;
}
// Translates the given message given the `TranslationBundle`
// This is used for translating elements / blocks - see `_translateAttributes` for attributes
// no-op when called in extraction mode (returns [])
private translateMessage(el: html.Node, message: i18n.Message): html.Node[] {
if (message && this.mode === VisitorMode.Merge) {
const nodes = this.translations.get(message, this.params);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${this.translations.digest(message)}"`);
}
return [];
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
private mayBeAddBlockChildren(node: html.Node): void {
if (this.inI18nBlock && !this.inIcu && this.depth === this.blockStartDepth) {
this.blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_closeTranslatableSection`
*/
private openTranslatableSection(node: html.Node): void {
if (this.isInTranslatableSection) {
this._reportError(node, "Unexpected section start");
} else {
this.msgCountAtSectionStart = this.messages.length;
}
}
/**
* A translatable section could be:
* - the content of translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
private get isInTranslatableSection(): boolean {
return this.msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
private _closeTranslatableSection(node: html.Node, directChildren: html.Node[]): void {
if (!this.isInTranslatableSection) {
this._reportError(node, "Unexpected section end");
return;
}
const startIndex = this.msgCountAtSectionStart;
const significantChildren: number = directChildren.reduce(
(count: number, n: html.Node): number => count + (n instanceof html.Comment ? 0 : 1),
0
);
if (significantChildren === 1) {
for (let i = this.messages.length - 1; i >= startIndex!; i--) {
const ast = this.messages[i].nodes;
if (!(ast.length === 1 && ast[0] instanceof i18n.Text)) {
this.messages.splice(i, 1);
break;
}
}
}
this.msgCountAtSectionStart = undefined;
}
private _reportError(node: html.Node, msg: string): void {
this.errors.push(new I18nError(node.sourceSpan!, msg));
}
}
function getI18nAttr(p: html.Element): html.Attribute | null {
return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
} | the_stack |
import * as arrSort from "array-sort";
import { DocumentInterface } from "../interfaces";
const parseAndFind = (
query: Object = {},
options: any,
documents: any,
findOne: boolean = false
) => {
const docs = Object.values(documents);
let filteredDocs = [];
let skipped = 0;
const doSort = !!options.sort;
const sortFirst = !!(Object.keys(options)[0] === "sort");
const emptyQuery = Object.keys(query).length === 0;
options.skip = options.skip || 0;
const condition = (len) => (options.limit ? options.limit === len : false);
if (!findOne) {
if (emptyQuery) {
filteredDocs = docs;
if (doSort && sortFirst) {
Object.keys(options.sort).map((field, index) => {
filteredDocs = arrSort(filteredDocs, field, {
reverse: options.sort[field] === 1 ? false : true,
});
});
}
if (options.limit) {
filteredDocs = filteredDocs.splice(options.skip, options.limit);
} else {
filteredDocs = filteredDocs.splice(options.skip);
}
if (doSort && !sortFirst) {
Object.keys(options.sort).map((field, index) => {
filteredDocs = arrSort(filteredDocs, field, {
reverse: options.sort[field] === 1 ? false : true,
});
});
}
return filteredDocs;
} else {
if (doSort && sortFirst) {
for (let i = 0; i < docs.length; i++) {
if (evaluateQuery(docs[i], query)) {
filteredDocs.push(docs[i]);
}
}
Object.keys(options.sort).map((field, index) => {
filteredDocs = arrSort(index === 0 ? docs : filteredDocs, field, {
reverse: options.sort[field] === 1 ? false : true,
});
});
if (options.limit) {
filteredDocs = filteredDocs.splice(options.skip, options.limit);
} else {
filteredDocs = filteredDocs.splice(options.skip);
}
return filteredDocs;
} else {
for (let i = 0; i < docs.length; i++) {
if (evaluateQuery(docs[i], query)) {
if (skipped >= options.skip) {
filteredDocs.push(docs[i]);
}
if (condition(filteredDocs.length)) {
if (options.sort) {
Object.keys(options.sort).map((field, index) => {
filteredDocs = arrSort(
index === 0 ? docs : filteredDocs,
field,
{
reverse: options.sort[field] === 1 ? false : true,
}
);
});
}
return filteredDocs;
}
++skipped;
}
}
if (doSort && !sortFirst) {
Object.keys(options.sort).map((field, index) => {
filteredDocs = arrSort(index === 0 ? docs : filteredDocs, field, {
reverse: options.sort[field] === 1 ? false : true,
});
});
}
return filteredDocs;
}
}
} else {
if (emptyQuery) {
return docs[0];
}
for (let i = 0; i < docs.length; i++) {
if (evaluateQuery(docs[i], query)) {
return docs[i];
}
}
return null;
}
};
// Possible optimization
// https://docs.mongodb.com/manual/reference/operator/query/or/#or-clauses-and-indexes
/*
Possible queries
with operators
{
$and:
[
{ qty: { $lt: 20, $gt: 10 } },
{ age: { $lt: 20, $gt: 10 } },
{ bal: { $lt: 20, $gt: 10 } },
]
}
without operators
{
age: 10, bal: 50
}
{
pets: ["cat", "dog"], names: ["fluffy", "tommy"]
}
{
name: {"fname": "elon", "lname": "musk"},
companies: {"space": "spacex", "car": "tesla"}
}
mix
{
$and:
[
{ qty: { $lt: 20, $gt: 10 } },
{ age: 10 },
{ name: {"fname": "elon", "lname": "musk"} },
]
}
*/
/**
* Evaluates if a document satisfies a condition or not.
*
* @param {JSON Object} doc
* @param {JSON Object} query
* @returns {boolean}
*/
const evaluateQuery = (doc: any, query: any) => {
let res;
let killSwitch = true; // kills the main loop if set to false
const fields = Object.keys(query);
for (let j = 0; j < fields.length && killSwitch; j++) {
// check for comparison operators by "$"
if (fields[j][0] === "$") {
switch (fields[j]) {
case "$and":
/**
* $and:
[
{ qty: { $lt: 20, $gt: 10 } },
{ age: 10 },
{ bal: { $lt: 20, $gt: 10 } },
]
*/
res = true;
for (let i = 0; i < query[fields[j]].length; i++) {
if (!evaluateCondition(query[fields[j]][i], doc)) {
res = false;
break;
}
}
break;
case "$or":
/**
* $or:
[
{ qty: { $lt: 20, $gt: 10 } },
{ age: 10 },
{ bal: { $lt: 20, $gt: 10 } },
]
*/
res = false;
for (let i = 0; i < query[fields[j]].length; i++) {
if (evaluateCondition(query[fields[j]][i], doc)) {
res = true;
break;
}
}
break;
default:
throw new Error(`${fields[j]} comparison operator is not supported`);
}
}
// if not, then treat it as a doc field or single line operator query
// { fname: "vasa", lname: "develop" }
// { qty: { $lt: 20, $gt: 10 }, age: { $lt: 20, $gt: 10 } }
// TODO: Support updates via JSON typed field. Eg, "user.age"
else {
res = true;
for (let i = 0; i < fields.length; i++) {
const check: any = {};
check[fields[i]] = query[fields[i]];
if (!evaluateCondition(check, doc)) {
res = false;
killSwitch = false;
break;
}
}
}
}
return res;
};
/**
* Evaluates if a condition is satisfied by a specific field value.
*
* @param {JSON Object} condition
* @param {JSON Object} doc
* @returns {boolean}
*/
const evaluateCondition = (condition: any, doc: any) => {
let res = true;
Object.keys(condition).forEach((field) => {
//Check if condition[field] is a JSON object with keys having "$" character
if (
condition[field].constructor === Object &&
Object.keys(condition[field]).length > 0
) {
const logicConditions = Object.keys(condition[field]);
if (logicConditions[0][0] === "$") {
//{ qty: { $lt: 20, $gt: 10 } }
for (let i = 0; i < logicConditions.length && res; i++) {
switch (logicConditions[i]) {
case "$lt":
if (!lt(doc[field], condition[field][logicConditions[i]])) {
res = false;
}
break;
case "$gt":
if (!gt(doc[field], condition[field][logicConditions[i]])) {
res = false;
}
break;
case "$lte":
if (!lte(doc[field], condition[field][logicConditions[i]])) {
res = false;
}
break;
case "$gte":
if (!gte(doc[field], condition[field][logicConditions[i]])) {
res = false;
}
break;
default:
throw new Error(
`${logicConditions[i]} logical operator is not supported`
);
}
}
} else {
//{qty: {"fname": "vasa", "lname": "develop"}}
if (!jsonEqual(doc[field], condition[field])) {
res = false;
}
}
} else {
//{qty: [1,2]}
if (condition[field].constructor === Array) {
if (!arraysEqual(doc[field], condition[field])) {
res = false;
}
}
//{qty: {}}
else if (condition[field].constructor === Object) {
if (!jsonEqual(doc[field], condition[field])) {
res = false;
}
}
//{ qty: 30 }
//{qty: null}
else {
if (!(doc[field] === condition[field])) {
res = false;
}
}
}
});
return res;
};
// Comparison
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const eq = (argValue: any, comparisonValue: any) => {
return argValue === comparisonValue;
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const gt = (argValue: any, comparisonValue: any) => {
return argValue > comparisonValue;
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const gte = (argValue: any, comparisonValue: any) => {
return argValue >= comparisonValue;
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const inop = (argValue: any, comparisonValue: any) => {
throw new Error("Not yet implemented.");
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const lt = (argValue: any, comparisonValue: any) => {
return argValue < comparisonValue;
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const lte = (argValue: any, comparisonValue: any) => {
return argValue <= comparisonValue;
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const ne = (arg: any, val: any) => {
throw new Error("Not yet implemented.");
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const nin = (arg: any, val: any) => {
throw new Error("Not yet implemented.");
};
// Logical
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
//$and
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const not = (arg: any, val: any) => {
throw new Error("Not yet implemented.");
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const nor = (arg: any, val: any) => {
throw new Error("Not yet implemented.");
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
//$or
// Element
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const exists = (arg: any, val: any) => {
throw new Error("Not yet implemented.");
};
/**
*
* @param {JSON Object} query
* @param {Array} docs
*/
const type = (arg: any, val: any) => {
throw new Error("Not yet implemented.");
};
// Utility Functions
const arraysEqual = (a: any, b: any) => {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
// If you don't care about the order of the elements inside
// the array, you should sort both arrays here.
// Please note that calling sort on an array will modify that array.
// you might want to clone your array first.
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
};
function jsonEqual(a: any, b: any) {
return JSON.stringify(a) === JSON.stringify(b);
}
export { parseAndFind }; | the_stack |
import {
AfterContentInit,
Directive,
EventEmitter,
Input,
OnDestroy,
Output,
} from "@angular/core";
import {
DivIcon,
DragEndEvent,
Handler,
Icon,
LatLng,
LatLngLiteral,
LatLngTuple,
LeafletEvent,
LeafletMouseEvent,
Map,
Marker,
PopupEvent,
TooltipEvent,
} from "leaflet";
import { LayerGroupProvider } from "./layer-group.provider";
import { LayerProvider } from "./layer.provider";
import { MarkerProvider } from "./marker.provider";
/**
* Angular2 directive for markers of Leaflet.
*
* *You can use this directive in an Angular2 template after importing `YagaModule`.*
*
* How to use in a template:
* ```html
* <yaga-map>
* <yaga-marker
* [(draggable)]="..."
* [(display)]="..."
* [(opacity)]="..."
* [(lat)]="..."
* [(lng)]="..."
* [(position)]="..."
* [(zIndexOffset)]="..."
* [(icon)]="..."
*
* (dragend)="..."
* (dragstart)="..."
* (movestart)="..."
* (drag)="..."
* (moveend)="..."
* (add)="..."
* (remove)="..."
* (popupopen)="..."
* (popupclose)="..."
* (tooltipopen)="..."
* (tooltipclose)="..."
* (click)="..."
* (dblclick)="..."
* (mousedown)="..."
* (mouseover)="..."
* (mouseout)="..."
* (contextmenu)="..."
*
* [title]="..."
* [alt]="..."
* >
* </yaga-marker>
* </yaga-map>
* ```
*
* @link http://leafletjs.com/reference-1.2.0.html#marker Original Leaflet documentation
* @link https://leaflet-ng2.yagajs.org/latest/browser-test?grep=Marker%20Directive Unit-Test
* @link https://leaflet-ng2.yagajs.org/latest/coverage/lcov-report/lib/marker.directive.js.html
* Test coverage
* @link https://leaflet-ng2.yagajs.org/latest/typedoc/classes/marker.directive.js.html API documentation
* @example https://leaflet-ng2.yagajs.org/latest/examples/marker-directive/
*/
@Directive({
providers: [ LayerProvider, MarkerProvider ],
selector: "yaga-marker",
})
export class MarkerDirective extends Marker implements AfterContentInit, OnDestroy {
/**
* Two-Way bound property for the latlng-position of the geometry.
* Use it with `<yaga-marker [(position)]="someValue">`
* or `<yaga-marker (positionChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
@Output() public positionChange: EventEmitter<LatLng> = new EventEmitter();
/**
* Two-Way bound property for the latitude of the geometry.
* Use it with `<yaga-marker [(lat)]="someValue">`
* or `<yaga-marker (latChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
@Output() public latChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the longitude of the geometry.
* Use it with `<yaga-marker [(lng)]="someValue">`
* or `<yaga-marker (lngChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
@Output() public lngChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the opacity of the geometry.
* Use it with `<yaga-marker [(opacity)]="someValue">`
* or `<yaga-marker (opacityChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setopacity Original Leaflet documentation
*/
@Output() public opacityChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the display status of the geometry.
* Use it with `<yaga-marker [(display)]="someValue">`
* or `<yaga-marker (displayChange)="processEvent($event)">`
*/
@Output() public displayChange: EventEmitter<boolean> = new EventEmitter();
/**
* Two-Way bound property for the offset of the zIndex.
* Use it with `<yaga-marker [(zIndexOffset)]="someValue">`
* or `<yaga-marker (zIndexOffsetChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.3.0.html#marker-zindexoffset Original Leaflet documentation
*/
@Output() public zIndexOffsetChange: EventEmitter<number> = new EventEmitter();
/**
* Two-Way bound property for the draggable state.
* Use it with `<yaga-marker [(draggable)]="someValue">`
* or `<yaga-marker (draggableChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.3.0.html#marker-dragging Original Leaflet documentation
*/
@Output() public draggableChange: EventEmitter<boolean> = new EventEmitter();
/**
* Two-Way bound property for the icon.
* Use it with `<yaga-marker [(icon)]="someValue">`
* or `<yaga-marker (iconChange)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.3.0.html#marker-seticon Original Leaflet documentation
*/
@Output() public iconChange: EventEmitter<Icon | DivIcon> = new EventEmitter();
@Output() public tooltipOpenedChange: EventEmitter<boolean> = new EventEmitter();
@Output() public popupOpenedChange: EventEmitter<boolean> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-marker (dragend)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-dragend Original Leaflet documentation
*/
@Output("dragend") public dragendEvent: EventEmitter<DragEndEvent> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-marker (dragstart)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-dragstart Original Leaflet documentation
*/
@Output("dragstart") public dragstartEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-marker (movestart)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-movestart Original Leaflet documentation
*/
@Output("movestart") public movestartEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-marker (drag)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-drag Original Leaflet documentation
*/
@Output("drag") public dragEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-marker (moveend)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-moveend Original Leaflet documentation
*/
@Output("moveend") public moveendEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired add event.
* Use it with `<yaga-marker (add)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-add Original Leaflet documentation
*/
@Output("add") public addEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired remove event.
* Use it with `<yaga-marker (remove)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-remove Original Leaflet documentation
*/
@Output("remove") public removeEvent: EventEmitter<LeafletEvent> = new EventEmitter();
/**
* From leaflet fired popupopen event.
* Use it with `<yaga-marker (popupopen)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-popupopen Original Leaflet documentation
*/
@Output("popupopen") public popupopenEvent: EventEmitter<PopupEvent> = new EventEmitter();
/**
* From leaflet fired popupclose event.
* Use it with `<yaga-marker (popupclose)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-popupclose Original Leaflet documentation
*/
@Output("popupclose") public popupcloseEvent: EventEmitter<PopupEvent> = new EventEmitter();
/**
* From leaflet fired tooltipopen event.
* Use it with `<yaga-marker (tooltipopen)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-tooltipopen Original Leaflet documentation
*/
@Output("tooltipopen") public tooltipopenEvent: EventEmitter<TooltipEvent> = new EventEmitter();
/**
* From leaflet fired tooltipclose event.
* Use it with `<yaga-marker (tooltipclose)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-tooltipclose Original Leaflet documentation
*/
@Output("tooltipclose") public tooltipcloseEvent: EventEmitter<TooltipEvent> = new EventEmitter();
/**
* From leaflet fired click event.
* Use it with `<yaga-marker (click)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-click Original Leaflet documentation
*/
@Output("click") public clickEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired dblclick event.
* Use it with `<yaga-marker (dblclick)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-dblclick Original Leaflet documentation
*/
@Output("dblclick") public dblclickEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired mousedown event.
* Use it with `<yaga-marker (mousedown)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-mousedown Original Leaflet documentation
*/
@Output("mousedown") public mousedownEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired mouseover event.
* Use it with `<yaga-marker (mouseover)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-mouseover Original Leaflet documentation
*/
@Output("mouseover") public mouseoverEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired mouseout event.
* Use it with `<yaga-marker (mouseout)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-mouseout Original Leaflet documentation
*/
@Output("mouseout") public mouseoutEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* From leaflet fired contextmenu event.
* Use it with `<yaga-marker (contextmenu)="processEvent($event)">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-contextmenu Original Leaflet documentation
*/
@Output("contextmenu") public contextmenuEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter();
/**
* Internal property to stop further processing while it is not initialized
*/
private initialized: boolean = false;
constructor(
protected layerGroupProvider: LayerGroupProvider,
layerProvider: LayerProvider,
markerProvider: MarkerProvider,
) {
super([0, 0]);
layerProvider.ref = this;
markerProvider.ref = this;
this.layerGroupProvider.ref!.addLayer(this);
this.on("remove", () => {
this.displayChange.emit(false);
});
this.on("add", () => {
this.displayChange.emit(true);
});
this.on("drag", () => {
this.latChange.emit(this.getLatLng().lat);
this.lngChange.emit(this.getLatLng().lng);
this.positionChange.emit(this.getLatLng());
});
// Events
this.on("dragend", (event: LeafletEvent) => {
this.dragendEvent.emit(event as DragEndEvent);
});
this.on("dragstart", (event: LeafletEvent) => {
this.dragstartEvent.emit(event);
});
this.on("movestart", (event: LeafletEvent) => {
this.movestartEvent.emit(event);
});
this.on("drag", (event: LeafletEvent) => {
this.dragEvent.emit(event);
});
this.on("moveend", (event: LeafletEvent) => {
this.moveendEvent.emit(event);
});
this.on("add", (event: LeafletEvent) => {
this.addEvent.emit(event);
});
this.on("remove", (event: LeafletEvent) => {
this.removeEvent.emit(event);
});
this.on("popupopen", (event: LeafletEvent) => {
this.popupopenEvent.emit(event as PopupEvent);
this.popupOpenedChange.emit(true);
});
this.on("popupclose", (event: LeafletEvent) => {
this.popupcloseEvent.emit(event as PopupEvent);
this.popupOpenedChange.emit(false);
});
this.on("tooltipopen", (event: LeafletEvent) => {
this.tooltipopenEvent.emit(event as TooltipEvent);
this.tooltipOpenedChange.emit(true);
});
this.on("tooltipclose", (event: LeafletEvent) => {
this.tooltipcloseEvent.emit(event as TooltipEvent);
this.tooltipOpenedChange.emit(false);
});
this.on("click", (event: LeafletEvent) => {
this.clickEvent.emit(event as LeafletMouseEvent);
});
this.on("dblclick", (event: LeafletEvent) => {
this.dblclickEvent.emit(event as LeafletMouseEvent);
});
this.on("mousedown", (event: LeafletEvent) => {
this.mousedownEvent.emit(event as LeafletMouseEvent);
});
this.on("mouseover", (event: LeafletEvent) => {
this.mouseoverEvent.emit(event as LeafletMouseEvent);
});
this.on("mouseout", (event: LeafletEvent) => {
this.mouseoutEvent.emit(event as LeafletMouseEvent);
});
this.on("contextmenu", (event: LeafletEvent) => {
this.contextmenuEvent.emit(event as LeafletMouseEvent);
});
const oldDraggingEnable: () => any = this.dragging!.enable;
const oldDraggingDisable: () => any = this.dragging!.disable;
this.dragging!.enable = (): Handler => {
const val: Handler = oldDraggingEnable.call(this.dragging);
this.draggableChange.emit(true);
return val;
};
this.dragging!.disable = (): Handler => {
const val: Handler = oldDraggingDisable.call(this.dragging);
this.draggableChange.emit(false);
return val;
};
}
/**
* Internal method that provides the initialization of the directive
*/
public ngAfterContentInit(): void {
this.initialized = true; // Otherwise lng gets overwritten to 0
}
/**
* Internal method to provide the removal of the layer in Leaflet, when removing it from the Angular template
*/
public ngOnDestroy(): void {
this.removeFrom(this.layerGroupProvider.ref as Map);
}
/**
* Two-Way bound property for the display status of the layer.
* Use it with `<yaga-marker [(display)]="someValue">` or `<yaga-marker [display]="someValue">`
*/
@Input() public set display(val: boolean) {
const isDisplayed: boolean = this.display;
if (isDisplayed === val) {
return;
}
let pane: HTMLElement;
let container: HTMLElement;
let map: Map;
let events: any; // Dictionary of functions
let eventKeys: string[];
try {
pane = this.getPane() as HTMLElement;
container = this.getElement() as HTMLImageElement;
map = (this as any)._map;
events = this.getEvents!();
eventKeys = Object.keys(events);
} catch (err) {
/* istanbul ignore next */
return;
}
if (val) {
// show layer
pane.appendChild(container);
for (const eventKey of eventKeys) {
map.on(eventKey, events[eventKey], this);
}
} else {
// hide layer
pane.removeChild(container);
for (const eventKey of eventKeys) {
map.off(eventKey, events[eventKey], this);
}
}
}
public get display(): boolean {
let pane: HTMLElement;
let container: HTMLElement;
try {
pane = this.getPane() as HTMLElement;
container = this.getElement() as HTMLImageElement;
} catch (err) {
/* istanbul ignore next */
return false;
}
/* tslint:disable:prefer-for-of */
for (let i: number = 0; i < pane.children.length; i += 1) {
/* tslint:enable */
/* istanbul ignore else */
if (pane.children[i] === container) {
return true;
}
}
return false;
}
/**
* Derived method of the original setLatLng method.
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
public setLatLng(val: LatLng | LatLngLiteral | LatLngTuple): this {
super.setLatLng((val as any));
if (this.initialized) {
this.positionChange.emit(this.getLatLng());
this.latChange.emit(this.getLatLng().lat);
this.lngChange.emit(this.getLatLng().lng);
}
return this;
}
/**
* Two-Way bound property for the position of the marker.
* Use it with `<yaga-marker [(position)]="someValue">` or `<yaga-marker [position]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
@Input() public set position(val: LatLng) {
this.setLatLng(val);
}
public get position(): LatLng {
return this.getLatLng();
}
/**
* Two-Way bound property for the position of the marker.
* Use it with `<yaga-marker [(lat)]="someValue">` or `<yaga-marker [lat]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
@Input() public set lat(val: number) {
this.setLatLng([val, this.lng]);
}
public get lat(): number {
return this.getLatLng().lat;
}
/**
* Two-Way bound property for the position of the marker.
* Use it with `<yaga-marker [(lng)]="someValue">` or `<yaga-marker [lng]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setlatlng Original Leaflet documentation
*/
@Input() public set lng(val: number) {
this.setLatLng([this.lat, val]);
}
public get lng(): number {
return this.getLatLng().lng;
}
/**
* Derived method of the original setOpacity method.
* @link http://leafletjs.com/reference-1.2.0.html#marker-setopacity Original Leaflet documentation
*/
public setOpacity(val: number): this {
if (this.opacity === val) {
return this;
}
this.opacityChange.emit(val);
return super.setOpacity(val);
}
/**
* Two-Way bound property for the opacity of the marker.
* Use it with `<yaga-marker [(opacity)]="someValue">` or `<yaga-marker [opacity]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-setopacity Original Leaflet documentation
*/
@Input() public set opacity(val: number | undefined) {
if (val === undefined) {
val = 1;
}
this.setOpacity(val);
}
public get opacity(): number | undefined {
return this.options.opacity;
}
/**
* Two-Way bound property for the state of the popup.
* Use it with `<yaga-marker [(popupOpened)]="someValue">` or `<yaga-marker [popupOpened]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-openpopup Original Leaflet documentation
*/
@Input() public set popupOpened(val: boolean) {
if (val) {
// It would not work without timeout!
this.openPopup();
return;
}
this.closePopup();
}
public get popupOpened(): boolean {
return this.isPopupOpen();
}
/**
* Two-Way bound property for the state of the popup.
* Use it with `<yaga-marker [(tooltipOpened)]="someValue">` or `<yaga-marker [tooltipOpened]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-opentooltip Original Leaflet documentation
*/
@Input() public set tooltipOpened(val: boolean) {
if (val) {
this.openTooltip();
return;
}
this.closeTooltip();
}
public get tooltipOpened(): boolean {
return this.isTooltipOpen();
}
/**
* Derived method of the original setIcon method.
* @link http://leafletjs.com/reference-1.2.0.html#marker-seticon Original Leaflet documentation
*/
public setIcon(val: Icon | DivIcon): this {
super.setIcon(val);
this.iconChange.emit(val);
return this;
}
/**
* Two-Way bound property for the state of the popup.
* Use it with `<yaga-marker [(icon)]="someValue">` or `<yaga-marker [icon]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-seticon Original Leaflet documentation
*/
@Input() public set icon(val: Icon | DivIcon) {
this.setIcon(val);
}
public get icon(): Icon | DivIcon {
return this.options.icon!;
}
/**
* Two-Way bound property for the state of the dragging.
* Use it with `<yaga-marker [(draggable)]="someValue">` or `<yaga-marker [draggable]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-dragging Original Leaflet documentation
*/
@Input() public set draggable(val: boolean) {
if (val) {
this.dragging!.enable();
return;
}
this.dragging!.disable();
return;
}
public get draggable(): boolean {
return this.dragging!.enabled();
}
/**
* Derived method of the original setZIndexOffset method.
* @link http://leafletjs.com/reference-1.2.0.html#marker-zindexoffset Original Leaflet documentation
*/
public setZIndexOffset(val: number): this {
if (this.zIndexOffset === val) {
return this;
}
this.zIndexOffsetChange.emit(val);
return super.setZIndexOffset(val);
}
/**
* Two-Way bound property for the offset of the zIndex.
* Use it with `<yaga-marker [(draggable)]="someValue">` or `<yaga-marker [draggable]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-zindexoffset Original Leaflet documentation
*/
@Input() public set zIndexOffset(val: number) {
this.setZIndexOffset(val);
}
public get zIndexOffset(): number {
return this.options.zIndexOffset || 0;
}
/**
* Input for the title.
* Use it with `<yaga-marker [title]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-title Original Leaflet documentation
*/
@Input() public set title(val: string) {
this.options.title = val;
this.getElement()!.setAttribute("title", val);
}
public get title(): string {
return this.getElement()!.getAttribute("title") || "";
}
/**
* Input for the alternative text.
* Use it with `<yaga-marker [alt]="someValue">`
* @link http://leafletjs.com/reference-1.2.0.html#marker-title Original Leaflet documentation
*/
@Input() public set alt(val: string | undefined) {
this.options.alt = val;
if (typeof val === "string") {
this.getElement()!.setAttribute("alt", val);
return;
}
this.getElement()!.removeAttribute("alt");
}
public get alt(): string | undefined {
return this.getElement()!.getAttribute("alt") || undefined;
}
} | the_stack |
import {
ALL_CTORS,
booleanOrRandomValue,
DICT_UNIT_MUTATION_FNS,
LIST_UNIT_MUTATION_FNS,
randomArray,
randomAsyncSystemConfig,
randomBoolean,
randomClusterItems,
randomConfig,
randomMutation,
randomNumber,
randomNumOrStr,
randomString,
randomUnitCtor,
randomValidValue,
randomValue,
selectRandom,
somewhatValidConfig,
times,
} from './utils';
import {Configuration} from '../lib/configuration';
import {UnitConfig} from '../models/units';
import {GlobalConfig, LogLevel} from '../models/global-config';
import {Action} from '../lib/action';
import {UnitBase} from '../lib/abstract-unit-base';
import {AsyncSystem} from '../lib/async-system';
import {Cluster} from '../lib/cluster';
import {DictUnit} from '../lib/dict-unit';
import {GenericUnit} from '../lib/generic-unit';
import {ListUnit} from '../lib/list-unit';
import {ClusterItems} from '../models/cluster';
import {AsyncSystemConfig} from '../models/async-system';
import {logInfo, logWarn} from '../utils/logger';
import {isObject, NOOP} from '../utils/funcs';
const unitsConfigOptions: Array<keyof UnitConfig<any>> = [
'id',
'immutable',
'initialValue',
'cacheSize',
];
const asyncSystemConfigOptions: Array<keyof AsyncSystemConfig<any, any, any>> = [
'id',
'autoUpdatePendingValue',
'freezeQueryWhilePending',
'clearDataOnError',
'clearDataOnQuery',
'clearErrorOnData',
'clearErrorOnQuery',
'clearQueryOnData',
'clearQueryOnError',
'initialValue',
'UNITS',
'QUERY_UNIT',
'DATA_UNIT',
'ERROR_UNIT',
'PENDING_UNIT',
];
const globalConfigOptions: Array<keyof GlobalConfig> = [
'ENVIRONMENT',
'ACTION',
'UNITS',
'ASYNC_SYSTEM',
'CLUSTER',
'BOOL_UNIT',
'DICT_UNIT',
'GENERIC_UNIT',
'LIST_UNIT',
'NUM_UNIT',
'STRING_UNIT',
];
describe(
'Environment',
times(30, () => {
beforeAll(() => {
Configuration.reset();
});
describe('dev/prod modes', () => {
it('should be dev mode by default', () => {
if (randomBoolean()) {
Configuration.set(randomConfig(globalConfigOptions));
}
expect(Configuration.isDevMode()).toBe(true);
});
it('should enable prod mode', () => {
if (randomBoolean()) {
Configuration.set(randomConfig(globalConfigOptions));
}
Configuration.enableProdMode();
expect(Configuration.isDevMode()).toBe(false);
// need to disable it for other tests
// @ts-ignore
Configuration._isDevMode = true;
});
it('should disallow ENVIRONMENT configuration, when in prod mode', () => {
const ENVIRONMENT = {
checkUniqueId: randomBoolean(),
checkImmutability: randomBoolean(),
checkSerializability: randomBoolean(),
logLevel: selectRandom([LogLevel.NONE, LogLevel.INFO, LogLevel.WARN]),
};
if (randomBoolean()) {
Configuration.enableProdMode();
}
Configuration.set({ENVIRONMENT});
if (randomBoolean()) {
Configuration.enableProdMode();
}
if (Configuration.isDevMode()) {
expect(Configuration.ENVIRONMENT).toEqual(ENVIRONMENT);
} else {
expect(Configuration.ENVIRONMENT).toEqual({});
}
// need to disable it for other tests
// @ts-ignore
Configuration._isDevMode = true;
});
});
describe('checkUniqueId', () => {
let id: string;
let clusterItems: ClusterItems;
const createInstance = c => (c === Cluster ? new c(clusterItems, {id}) : new c({id}));
beforeEach(() => {
Configuration.set({ENVIRONMENT: {checkUniqueId: booleanOrRandomValue(0.8)}});
id = randomString();
clusterItems = randomClusterItems();
});
it('checks unique id', () => {
const ctor1 = selectRandom(ALL_CTORS);
const ctor2 = selectRandom(ALL_CTORS);
createInstance(ctor1);
if (Configuration.ENVIRONMENT.checkUniqueId === true) {
expect(() => createInstance(ctor1)).toThrowError();
expect(() => createInstance(ctor2)).toThrowError();
} else {
expect(() => createInstance(ctor1)).not.toThrowError();
expect(() => createInstance(ctor2)).not.toThrowError();
}
});
it('should not throw if instance created on same location', () => {
const ctor = selectRandom(ALL_CTORS);
Array(randomNumber(1, 5))
.fill(null)
.forEach(() => {
expect(() => createInstance(ctor)).not.toThrowError();
});
});
});
describe('checkImmutability', () => {
beforeEach(() => {
Configuration.set({ENVIRONMENT: {checkImmutability: booleanOrRandomValue(0.8)}});
});
it('checks Units', () => {
const unitCtor = randomUnitCtor();
const unit = new unitCtor(somewhatValidConfig(unitsConfigOptions, unitCtor, 1, 3));
let emittedValue;
unit.subscribe(v => (emittedValue = v));
if (randomBoolean()) {
unit.dispatch(randomValidValue(unit));
}
const nonPrimitiveValue = isObject(unit.value());
const nonPrimitiveEmittedValue = isObject(emittedValue);
if (nonPrimitiveValue && Configuration.ENVIRONMENT.checkImmutability === true) {
if (unit.config.immutable === true) {
expect(() => randomMutation(unit.value())).not.toThrowError();
expect(() => randomMutation(unit.rawValue())).toThrowError();
expect(() => unit.dispatch(v => randomMutation(v))).not.toThrowError();
} else {
expect(() => randomMutation(unit.rawValue())).toThrowError();
expect(() => unit.dispatch(v => randomMutation(v))).toThrowError();
expect(() => randomMutation(unit.value())).toThrowError();
}
if (nonPrimitiveEmittedValue && unit.config.immutable !== true) {
expect(() => randomMutation(emittedValue)).toThrowError();
} else {
expect(() => randomMutation(emittedValue)).not.toThrowError();
}
} else {
expect(() => randomMutation(unit.rawValue())).not.toThrowError();
expect(() => randomMutation(unit.value())).not.toThrowError();
expect(() => unit.dispatch(v => randomMutation(v))).not.toThrowError();
expect(() => randomMutation(emittedValue)).not.toThrowError();
}
});
it('checks Action', () => {
// Action's config is a subset of GenericUnit's config
const action = new Action(somewhatValidConfig(unitsConfigOptions, GenericUnit, 1, 3));
let emittedValue;
action.subscribe(v => (emittedValue = v));
if (randomBoolean()) {
action.dispatch(randomValue());
}
const nonPrimitiveValue = isObject(action.value());
const nonPrimitiveEmittedValue = isObject(emittedValue);
if (nonPrimitiveValue && Configuration.ENVIRONMENT.checkImmutability === true) {
expect(() => randomMutation(action.value())).toThrowError();
expect(() => action.dispatch(v => randomMutation(v))).toThrowError();
if (nonPrimitiveEmittedValue) {
expect(() => randomMutation(emittedValue)).toThrowError();
} else {
expect(() => randomMutation(emittedValue)).not.toThrowError();
}
} else {
expect(() => randomMutation(action.value())).not.toThrowError();
expect(() => action.dispatch(v => randomMutation(v))).not.toThrowError();
expect(() => randomMutation(emittedValue)).not.toThrowError();
}
});
it('checks AsyncSystem', () => {
// Action's config is a subset of GenericUnit's config
const system = new AsyncSystem(
randomAsyncSystemConfig(asyncSystemConfigOptions, unitsConfigOptions, 1, 3)
);
const {queryUnit, dataUnit, errorUnit, pendingUnit} = system;
let emittedValue;
system.subscribe(v => (emittedValue = v));
if (randomBoolean()) {
const unit = selectRandom([queryUnit, dataUnit, errorUnit, pendingUnit]);
unit.dispatch(randomValidValue(unit));
}
if (Configuration.ENVIRONMENT.checkImmutability === true) {
expect(() => randomMutation(system.value())).toThrowError();
expect(() => randomMutation(emittedValue)).toThrowError();
} else {
expect(() => randomMutation(system.value())).not.toThrowError();
expect(() => randomMutation(emittedValue)).not.toThrowError();
}
});
it('checks Cluster', () => {
const cluster = new Cluster(randomClusterItems());
let emittedValue;
cluster.subscribe(v => (emittedValue = v));
if (randomBoolean()) {
const unit = Object.values(cluster.items).find(o => o instanceof UnitBase) as UnitBase<
any
>;
if (unit) {
unit.dispatch(randomValidValue(unit));
}
}
if (Configuration.ENVIRONMENT.checkImmutability === true) {
expect(() => randomMutation(cluster.value())).toThrowError();
expect(() => randomMutation(emittedValue)).toThrowError();
} else {
expect(() => randomMutation(cluster.value())).not.toThrowError();
expect(() => randomMutation(emittedValue)).not.toThrowError();
}
});
});
describe('checkSerializability', () => {
const ctors = [GenericUnit, DictUnit, ListUnit];
let ctor: new (config?) => DictUnit<any> | ListUnit<any> | GenericUnit<any>;
let unit: DictUnit<any> | ListUnit<any> | GenericUnit<any>;
it('should not throw for serializable values', () => {
Configuration.set({
ENVIRONMENT: {checkSerializability: booleanOrRandomValue()},
});
ctor = selectRandom(ctors);
unit = new ctor(somewhatValidConfig(unitsConfigOptions, ctor, 1));
expect(() => unit.dispatch(randomValidValue(ctor))).not.toThrowError();
expect(() => unit.dispatch(() => randomValidValue(ctor))).not.toThrowError();
if (unit instanceof DictUnit) {
expect(() => selectRandom(DICT_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
expect(() => selectRandom(DICT_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
expect(() => selectRandom(DICT_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
expect(() => selectRandom(DICT_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
} else if (unit instanceof ListUnit) {
expect(() => selectRandom(LIST_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
expect(() => selectRandom(LIST_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
expect(() => selectRandom(LIST_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
expect(() => selectRandom(LIST_UNIT_MUTATION_FNS)(unit)).not.toThrowError();
}
});
it('should throw for non-serializable values', () => {
Configuration.set({ENVIRONMENT: {checkSerializability: true}});
ctor = selectRandom(ctors);
unit = new ctor({immutable: booleanOrRandomValue()});
class A {}
const nonSerializable = selectRandom([new A(), new Date(), new Map(), new Set(), () => {}]);
if (typeof nonSerializable !== 'function') {
expect(() => unit.dispatch(nonSerializable)).toThrowError();
}
expect(() => unit.dispatch(() => nonSerializable)).toThrowError();
if (ctor === DictUnit) {
const u = unit as DictUnit<any>;
expect(() => u.set(randomNumber(0, 10), nonSerializable)).toThrowError();
expect(() => u.assign({[randomNumOrStr()]: nonSerializable})).toThrowError();
return;
}
if (ctor === ListUnit) {
const u = unit as ListUnit<any>;
expect(() => u.push(nonSerializable)).toThrowError();
expect(() => u.unshift(nonSerializable)).toThrowError();
expect(() => u.splice(0, 0, nonSerializable)).toThrowError();
expect(() => u.set(randomNumber(0, 10), nonSerializable)).toThrowError();
expect(() => u.insert(randomNumber(0, 10), nonSerializable)).toThrowError();
}
});
});
describe('logLevel', () => {
it('should not log anything', () => {
const randVal = randomValue(1);
Configuration.set({ENVIRONMENT: {logLevel: randVal > 0 ? LogLevel.NONE : randVal}});
expect(logInfo(randomValue(1))).toBe(NOOP);
expect(logWarn(randomValue(1))).toBe(NOOP);
});
it('should only log warnings', () => {
Configuration.set({ENVIRONMENT: {logLevel: LogLevel.WARN}});
const messages = randomArray(1);
spyOn(console, 'warn');
expect(logInfo(randomValue(1))).toBe(NOOP);
logWarn(...(messages as [any, ...any[]]))();
expect(console.warn).toHaveBeenCalledWith(...messages);
});
it('should log info and warnings', () => {
Configuration.set({ENVIRONMENT: {logLevel: LogLevel.INFO}});
const messages = randomArray(1);
spyOn(console, 'info');
spyOn(console, 'warn');
logInfo(...(messages as [any, ...any[]]))();
logWarn(...(messages as [any, ...any[]]))();
// tslint:disable-next-line:no-console
expect(console.info).toHaveBeenCalledWith(...messages);
expect(console.warn).toHaveBeenCalledWith(...messages);
});
});
})
); | the_stack |
import lessTree from "@abmaonline/less-tree";
import fs from "fs";
import path from "path";
import recursive from "recursive-readdir";
import treeModel from "tree-model";
// const treeify = require('treeify');
// TODO turn into type?
interface IModel {
id: string;
type: string;
filePath: string;
isMissing: boolean;
children: IModel[];
}
export class StyleTree {
private jcrRootDir: string;
// TODO maybe init in constructor, but can we return promises from consturctor?
private rootNode!: treeModel.Node<IModel>; // definite assignment assertion: assigned in init() function
private tree = new treeModel();
// use with '/src/content/jcr_root'
constructor(relativeJcrPath: string) {
this.jcrRootDir = path.resolve(relativeJcrPath);
}
// === Class ===
public init() {
// const jcrRootDir = this.jcrRootDir;
const model: IModel = {
children: [],
filePath: "",
id: "",
isMissing: false,
type: "root"
};
// Start processing
const sw = Date.now();
return new Promise((resolve, reject) => {
recursive(this.jcrRootDir, (err, files) => {
console.log("Read file tree: " + (Date.now() - sw) + " ms");
// Does this work?
if (err) {
reject(err);
return;
}
let swInner = Date.now();
// `files` is an array of absolute file paths
const rootFilesRegex = /((css|js)\.txt|(\.content\.xml))$/i;
const contentXmlFilesRelative: string[] = [];
const jsTxtFilesRelative: string[] = [];
const cssTxtFilesRelative: string[] = [];
const otherFilesRelative: string[] = [];
files.forEach(filePath => {
// Make relative for jcrRootDir
const filePathRelative = path.relative(this.jcrRootDir, filePath);
let match;
// tslint:disable-next-line:no-conditional-assignment
if ((match = rootFilesRegex.exec(filePathRelative)) !== null) {
if (match[3]) {
contentXmlFilesRelative.push(filePathRelative);
} else if (match[2] === "css") {
cssTxtFilesRelative.push(filePathRelative);
} else if (match[2] === "js") {
jsTxtFilesRelative.push(filePathRelative);
} else {
otherFilesRelative.push(filePathRelative);
}
}
});
// console.log('time split', (Date.now() - swInner) / 1000);
swInner = Date.now();
cssTxtFilesRelative.forEach(cssTxtFileRelative => {
// Test if css.txt also has a clientlib definition, otherwise skip it
const contentFileRelative = path.join(
path.dirname(cssTxtFileRelative),
".content.xml"
);
if (contentXmlFilesRelative.indexOf(contentFileRelative) === -1) {
return;
}
const cssTxtModel = this.getCssTxtModel(cssTxtFileRelative);
model.children.push(cssTxtModel);
});
// console.log('time css files', (Date.now() - swInner) / 1000);
swInner = Date.now();
// Public?
this.rootNode = this.tree.parse(model);
// console.log('time tree parse', (Date.now() - swInner) / 1000);
// console.log(clientlib);
console.log("Build style tree: " + (Date.now() - sw) + " ms");
// console.log(clientlib.length, content.length, css.length, js.length, other.length);
// console.log(contentXmlFilesJcr.length, cssTxtFilesJcr.length, jsTxtFilesJcr.length, otherFilesJcr.length);
resolve();
});
});
}
public findClientlibs(filePathRelative: string) {
return this.findClientlibsInternal(this.rootNode, filePathRelative);
}
// === Other privates ===
private getCssTxtModel(cssTxtFileRelative: string): IModel {
const basePathRelative = path.dirname(cssTxtFileRelative);
// TODO css.txt is always pulled from the file system, so always present
// no need to handle new ones here?
// We probably need a reload on adding css.txt anyway?
// But how do we detect if a reload is happening and we also need to update our cache?
// Check if we can see this in browser sync?
const cssTxtModel: IModel = {
children: [],
filePath: cssTxtFileRelative,
id: cssTxtFileRelative,
isMissing: false,
type: "csstxt"
};
try {
// TODO create function that returns array of filenames, maybe make module?
const contents = fs.readFileSync(
path.join(this.jcrRootDir, cssTxtFileRelative),
"utf8"
);
const arrayOfLines = contents.match(/[^\r\n]+/g);
if (arrayOfLines && arrayOfLines.length > 0) {
let prefix = "";
arrayOfLines.forEach((line: string) => {
const baseMatch = /#base=(.*)/.exec(line);
if (baseMatch !== null) {
prefix = baseMatch[1];
} else {
const sourceLine = line.trim();
// Check if not commented out
if (sourceLine.indexOf("//") !== 0) {
// Test if 'absolute' within jcr:
// If so, make relative to root (otherwise it will start with X:\ on Windows)
// Otherwise prefix with relative path for css.txt and base-prefix
const sourceFileRelative = path.isAbsolute(sourceLine)
? path.relative(path.sep, sourceLine)
: path.join(basePathRelative, prefix, sourceLine);
const sourceModel = this.getSourceModel(sourceFileRelative);
cssTxtModel.children.push(sourceModel);
}
}
});
} else {
// console.log('empty file', cssTxtFileJcr);
}
} catch (err) {
cssTxtModel.isMissing = true;
}
return cssTxtModel;
}
private getSourceModel(sourceFileRelative: string): IModel {
sourceFileRelative = path.normalize(sourceFileRelative);
const sourceModel: IModel = {
children: [],
filePath: sourceFileRelative,
id: sourceFileRelative,
isMissing: false,
type: "source"
};
// TODO maybe add stats call to determine missing, but check performance
// we can also use files list from recursive?
// TODO also include css imports? But tricky with lessTree, since it always adds .less
// and css imports are bad practice anyway
if (path.extname(sourceFileRelative) === ".less") {
sourceModel.type = "less";
const newLessTree = this._getLessTree(sourceFileRelative);
const importModels = this.lessTree2Model(newLessTree);
// Skip root, since it is current source file
sourceModel.children = importModels.children;
sourceModel.isMissing = importModels.isMissing; // TODO still needed here?
}
return sourceModel;
}
private lessTree2Model(newLessTree: lessTree.LessTree): IModel {
const filePathRelative = path.relative(this.jcrRootDir, newLessTree.path);
const model: IModel = {
children: [],
filePath: filePathRelative,
id: filePathRelative,
isMissing: !newLessTree.contents,
type: "less-import"
};
if (newLessTree.children) {
newLessTree.children.forEach(child => {
const childModel = this.lessTree2Model(child);
model.children.push(childModel);
});
}
return model;
}
private findClientlibsInternal(
rootNode: treeModel.Node<IModel>,
filePathRelative: string
): string[] {
enum pathIndex {
root,
clientlib,
less,
import
}
const sw = Date.now();
// Reset cache
this._getLessTree("", true);
const clientlibCssPathsRelative: string[] = [];
const nodes = rootNode.all(
node => node.model.filePath === filePathRelative
);
nodes.forEach(node => {
// TODO use type for functionality
const nodePath = node.getPath();
if (nodePath && nodePath.length > pathIndex.clientlib) {
const clientlibNode = nodePath[pathIndex.clientlib];
const clientlibCss =
path.dirname(clientlibNode.model.filePath) + ".css";
if (clientlibCssPathsRelative.indexOf(clientlibCss) === -1) {
clientlibCssPathsRelative.push(clientlibCss);
}
}
if (node.hasChildren() || node.model.isMissing) {
this.updateClientlibs(rootNode, node);
}
});
// TODO do something for new css.txt?
if (nodes.length === 0 && path.basename(filePathRelative) === "css.txt") {
console.log("Missing css.txt, so add", filePathRelative);
this.updateClientlibs(rootNode, filePathRelative);
}
// console.log('time findClientlibs', (Date.now() - sw) / 1000);
// console.log(clientlibCssPaths);
return clientlibCssPathsRelative;
}
// TODO nicer way of handling new css.txt? It's own function maybe?
private updateClientlibs(
rootNode: treeModel.Node<IModel>,
node: treeModel.Node<IModel> | string
): IModel | undefined {
let newModel;
if (typeof node === "string") {
if (path.basename(node) === "css.txt") {
console.log("updateClientlibs add new csstxt");
newModel = this.getCssTxtModel(node);
}
} else {
if (["less", "less-import"].indexOf(node.model.type) > -1) {
// console.log('updateClientlibs less');
// TODO use cache for models, so we can reuse it if it was imported in
// multiple files
// Is cloning needed, would be nasty with children?
newModel = this.getSourceModel(node.model.filePath);
} else if (["csstxt"].indexOf(node.model.type) > -1) {
console.log("updateClientlibs csstxt");
newModel = this.getCssTxtModel(node.model.filePath);
}
// TODO walk newNode and return a list of all updated subs, so we can check for it before
// processing the next file and prevent double work
// We probably need the path in the tree for it, since the filename is also used in the
// other refs
// Make id's unique and use those?
// Maybe just update the model and generate tree again? But updating model sucks
// Or rebuild unique path based on parent chain + id?
// Ditch id all together, since confusing?
}
if (newModel) {
const newNode = this.tree.parse(newModel);
if (typeof node === "string") {
rootNode.addChild(newNode);
} else {
const parentNode = node.parent;
const index = node.getIndex();
node.drop();
if (parentNode) {
parentNode.addChildAtIndex(newNode, index);
}
}
return newModel;
}
}
// FOR TESTING
private copyFileSync(srcFile: string, destFile: string) {
let BUF_LENGTH;
let buff;
let bytesRead;
let fdr;
let fdw;
let pos;
BUF_LENGTH = 64 * 1024;
buff = new Buffer(BUF_LENGTH);
fdr = fs.openSync(srcFile, "r");
fdw = fs.openSync(destFile, "w");
bytesRead = 1;
pos = 0;
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
fs.writeSync(fdw, buff, 0, bytesRead);
pos += bytesRead;
}
fs.closeSync(fdr);
return fs.closeSync(fdw);
}
// === Private statics ===
private _getLessTree(
fileRelative: string,
resetCache?: boolean
): lessTree.LessTree {
resetCache = !!resetCache; // Cast to explicit boolean
// TODO make async and paralel
const tree = lessTree(
path.join(this.jcrRootDir, fileRelative),
this.jcrRootDir,
resetCache
);
return tree;
}
} | the_stack |
import {absoluteFrom, AbsoluteFsPath, getFileSystem, ReadonlyFileSystem} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {MockLogger} from '../../../src/ngtsc/logging/testing';
import {loadTestFiles} from '../../../src/ngtsc/testing';
import {NgccConfiguration, ProcessedNgccPackageConfig} from '../../src/packages/configuration';
import {EntryPoint, EntryPointJsonProperty, EntryPointPackageJson, getEntryPointFormat, getEntryPointInfo, IGNORED_ENTRY_POINT, INCOMPATIBLE_ENTRY_POINT, isEntryPoint, NO_ENTRY_POINT, SUPPORTED_FORMAT_PROPERTIES} from '../../src/packages/entry_point';
runInEachFileSystem(() => {
describe('getEntryPointInfo()', () => {
let SOME_PACKAGE: AbsoluteFsPath;
let _: typeof absoluteFrom;
let fs: ReadonlyFileSystem;
beforeEach(() => {
_ = absoluteFrom;
SOME_PACKAGE = _('/project/node_modules/some_package');
fs = getFileSystem();
});
it('should return an object containing absolute paths to the formats of the specified entry-point',
() => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/valid_entry_point/package.json'),
contents: createPackageJson('valid_entry_point')
},
{
name: _(
'/project/node_modules/some_package/valid_entry_point/valid_entry_point.metadata.json'),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/valid_entry_point'));
expect(entryPoint).toEqual({
name: 'some_package/valid_entry_point',
path: _('/project/node_modules/some_package/valid_entry_point'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: loadPackageJson(fs, '/project/node_modules/some_package/valid_entry_point'),
typings:
_(`/project/node_modules/some_package/valid_entry_point/valid_entry_point.d.ts`),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
it('should return an object containing repositoryUrl extracted from the package level package.json (defined as an object)',
() => {
const packagePath = '/project/node_modules/some_package';
loadTestFiles([
{
name: _(`${packagePath}/package.json`),
contents:
'{ "name": "some_package", "repository": { "url": "https://github.com/some_org/some_package" } }',
},
{
name: _(`${packagePath}/valid_entry_point/package.json`),
contents: createPackageJson('valid_entry_point')
},
{
name: _(`${packagePath}/valid_entry_point/valid_entry_point.metadata.json`),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE, _(`${packagePath}/valid_entry_point`));
expect(entryPoint).toEqual(jasmine.objectContaining({
repositoryUrl: 'https://github.com/some_org/some_package',
}));
});
it('should return an object containing repositoryUrl extracted from the package level package.json (defined as a string)',
() => {
const packagePath = '/project/node_modules/some_package';
loadTestFiles([
{
name: _(`${packagePath}/package.json`),
contents:
'{ "name": "some_package", "repository": "https://github.com/some_org/some_package" }',
},
{
name: _(`${packagePath}/valid_entry_point/package.json`),
contents: createPackageJson('valid_entry_point')
},
{
name: _(`${packagePath}/valid_entry_point/valid_entry_point.metadata.json`),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE, _(`${packagePath}/valid_entry_point`));
expect(entryPoint).toEqual(jasmine.objectContaining({
repositoryUrl: 'https://github.com/some_org/some_package',
}));
});
it('should return an object containing an empty repositoryUrl if the package level package.json does not define it',
() => {
const packagePath = '/project/node_modules/some_package';
loadTestFiles([
{
name: _(`${packagePath}/package.json`),
contents: '{ "name": "some_package" } }',
},
{
name: _(`${packagePath}/valid_entry_point/package.json`),
contents: createPackageJson('valid_entry_point')
},
{
name: _(`${packagePath}/valid_entry_point/valid_entry_point.metadata.json`),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE, _(`${packagePath}/valid_entry_point`));
expect(entryPoint).toEqual(jasmine.objectContaining({
repositoryUrl: '',
}));
});
it('should return `IGNORED_ENTRY_POINT` if configured to ignore the specified entry-point', () => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/valid_entry_point/package.json'),
contents: createPackageJson('valid_entry_point'),
},
{
name: _(
'/project/node_modules/some_package/valid_entry_point/valid_entry_point.metadata.json'),
contents: 'some meta data',
},
]);
const config = new NgccConfiguration(fs, _('/project'));
spyOn(config, 'getPackageConfig')
.and.returnValue(new ProcessedNgccPackageConfig(
fs, _('/project/node_modules/some_package'),
{entryPoints: {'./valid_entry_point': {ignore: true}}}));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/valid_entry_point'));
expect(entryPoint).toBe(IGNORED_ENTRY_POINT);
});
it('should retrieve the entry-point\'s version from the package\'s `package.json`', () => {
const entryPointPath = fs.join(SOME_PACKAGE, 'valid_entry_point');
loadTestFiles([
{
name: _('/project/ngcc.config.js'),
contents: `
module.exports = {
packages: {
'some_package@3': {
entryPoints: {valid_entry_point: {override: {packageVersion: '3'}}},
},
'some_package@2': {
entryPoints: {valid_entry_point: {override: {packageVersion: '2'}}},
},
'some_package@1': {
entryPoints: {valid_entry_point: {override: {packageVersion: '1'}}},
},
},
};
`,
},
{
name: fs.join(SOME_PACKAGE, 'package.json'),
contents: createPackageJson('', {version: '1.0.0'}),
},
{
name: fs.join(entryPointPath, 'package.json'),
contents: createPackageJson('valid_entry_point', {version: '2.0.0'}),
},
{
name: fs.join(entryPointPath, 'valid_entry_point.metadata.json'),
contents: 'some meta data',
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const info = getEntryPointInfo(fs, config, new MockLogger(), SOME_PACKAGE, entryPointPath) as
EntryPoint;
expect(info.packageJson).toEqual(jasmine.objectContaining({packageVersion: '1'}));
});
it('should use `null` for version if it cannot be retrieved from a `package.json`', () => {
const entryPointPath = fs.join(SOME_PACKAGE, 'valid_entry_point');
loadTestFiles([
{
name: _('/project/ngcc.config.js'),
contents: `
module.exports = {
packages: {
'some_package@3': {
entryPoints: {valid_entry_point: {override: {packageVersion: '3'}}},
},
'some_package@2': {
entryPoints: {valid_entry_point: {override: {packageVersion: '2'}}},
},
'some_package@1': {
entryPoints: {valid_entry_point: {override: {packageVersion: '1'}}},
},
},
};
`,
},
{
name: fs.join(SOME_PACKAGE, 'package.json'),
contents: createPackageJson(''),
},
{
name: fs.join(entryPointPath, 'package.json'),
contents: createPackageJson('valid_entry_point'),
},
{
name: fs.join(entryPointPath, 'valid_entry_point.metadata.json'),
contents: 'some meta data',
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const info = getEntryPointInfo(fs, config, new MockLogger(), SOME_PACKAGE, entryPointPath) as
EntryPoint;
expect(info.packageJson).toEqual(jasmine.objectContaining({packageVersion: '3'}));
});
it('should override the properties on package.json if the entry-point is configured', () => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/valid_entry_point/package.json'),
contents: createPackageJson('valid_entry_point'),
},
{
name: _(
'/project/node_modules/some_package/valid_entry_point/valid_entry_point.metadata.json'),
contents: 'some meta data',
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const override = {
typings: './some_other.d.ts',
esm2015: './some_other.js',
};
spyOn(config, 'getPackageConfig')
.and.returnValue(new ProcessedNgccPackageConfig(
fs, _('/project/node_modules/some_package'),
{entryPoints: {'./valid_entry_point': {override}}}));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/valid_entry_point'));
const overriddenPackageJson = {
...loadPackageJson(fs, '/project/node_modules/some_package/valid_entry_point'),
...override
};
expect(entryPoint).toEqual({
name: 'some_package/valid_entry_point',
path: _('/project/node_modules/some_package/valid_entry_point'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: overriddenPackageJson,
typings: _('/project/node_modules/some_package/valid_entry_point/some_other.d.ts'),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
it('should return `NO_ENTRY_POINT` if there is no package.json at the entry-point path', () => {
loadTestFiles([
{
name: _(
'/project/node_modules/some_package/missing_package_json/missing_package_json.metadata.json'),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/missing_package_json'));
expect(entryPoint).toBe(NO_ENTRY_POINT);
});
it('should return a configured entry-point if there is no package.json at the entry-point path',
() => {
loadTestFiles([
// no package.json!
{
name: _(
'/project/node_modules/some_package/missing_package_json/missing_package_json.metadata.json'),
contents: 'some meta data',
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const override =
JSON.parse(createPackageJson('missing_package_json', {excludes: ['name']})) as
Partial<EntryPointPackageJson>;
spyOn(config, 'getPackageConfig')
.and.returnValue(new ProcessedNgccPackageConfig(
fs, _('/project/node_modules/some_package/'),
{entryPoints: {'./missing_package_json': {override}}}));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/missing_package_json'));
expect(entryPoint).toEqual({
name: 'some_package/missing_package_json',
path: _('/project/node_modules/some_package/missing_package_json'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: {name: 'some_package/missing_package_json', ...override},
typings: _(
'/project/node_modules/some_package/missing_package_json/missing_package_json.d.ts'),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
[false, true].forEach(isScoped => {
const nameWithScope = (baseName: string) => `${isScoped ? '@some-scope/' : ''}${baseName}`;
const getPackageName = (packagePath: AbsoluteFsPath, entryPointPath: AbsoluteFsPath) => {
const config = new NgccConfiguration(fs, _('/project'));
const logger = new MockLogger();
const entryPoint = getEntryPointInfo(fs, config, logger, packagePath, entryPointPath);
if (!isEntryPoint(entryPoint)) {
return fail(`Expected an entry point but got ${entryPoint}`);
}
return entryPoint.packageName;
};
const setUpPackageWithEntryPointPackageJson =
(entryPointName: string, entryPointPath: AbsoluteFsPath) => {
// Ensure a `package.json` exists for the entry-point (containing `entryPointName`).
loadTestFiles([
{
name: fs.join(entryPointPath, 'package.json'),
contents: JSON.stringify({name: entryPointName, typings: './index.d.ts'}),
},
]);
};
const setUpPackageWithoutEntryPointPackageJson =
(packagePath: AbsoluteFsPath, entryPointPath: AbsoluteFsPath) => {
// Ensure there is an ngcc config for the entry-point providing a `typings` field to
// avoid returning `INCOMPATIBLE_ENTRY_POINT` (since there is no `package.json`).
loadTestFiles([
{
name: fs.join(packagePath, 'ngcc.config.js'),
contents: `
module.exports = {
entryPoints: {
'${fs.relative(packagePath, entryPointPath)}': {
override: {typings: './index.d.ts'},
},
},
};
`,
},
]);
};
describe(`should compute the containing ${isScoped ? 'scoped ' : ''}package's name`, () => {
it('for a primary entry-point with a `package.json`', () => {
const packagePath = _(`/project/node_modules/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = packagePath;
const expectedPackageName = nameWithScope('package-json-package-name');
setUpPackageWithEntryPointPackageJson(expectedPackageName, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a primary entry-point without a `package.json`', () => {
const packagePath = _(`/project/node_modules/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = packagePath;
const expectedPackageName = nameWithScope('on-disk-package-name');
setUpPackageWithoutEntryPointPackageJson(packagePath, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a secondary entry-point with a `package.json`', () => {
const packagePath = _(`/project/node_modules/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = fs.join(packagePath, 'some-entry-point');
const expectedPackageName = nameWithScope('package-json-package-name');
setUpPackageWithEntryPointPackageJson(
`${expectedPackageName}/some-entry-point`, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a secondary entry-point without a `package.json`', () => {
const packagePath = _(`/project/node_modules/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = fs.join(packagePath, 'some-entry-point');
const expectedPackageName = nameWithScope('on-disk-package-name');
setUpPackageWithoutEntryPointPackageJson(packagePath, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a primary entry-point without a `package.json` in nested `node_modules/`', () => {
const packagePath = _(`/project/node_modules/other-package/node_modules/${
nameWithScope('on-disk-package-name')}`);
const entryPointPath = packagePath;
const expectedPackageName = nameWithScope('on-disk-package-name');
setUpPackageWithoutEntryPointPackageJson(packagePath, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a secondary entry-point without a `package.json` in nested `node_modules/`', () => {
const packagePath = _(`/project/node_modules/other-package/node_modules/${
nameWithScope('on-disk-package-name')}`);
const entryPointPath = fs.join(packagePath, 'some-entry-point');
const expectedPackageName = nameWithScope('on-disk-package-name');
setUpPackageWithoutEntryPointPackageJson(packagePath, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a primary entry-point with a `package.json` outside `node_modules/`', () => {
const packagePath = _(`/project/libs/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = packagePath;
const expectedPackageName = nameWithScope('package-json-package-name');
setUpPackageWithEntryPointPackageJson(expectedPackageName, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a primary entry-point without a `package.json` outside `node_modules/`', () => {
const packagePath = _(`/project/libs/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = packagePath;
const expectedPackageName = nameWithScope('on-disk-package-name');
setUpPackageWithoutEntryPointPackageJson(packagePath, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a secondary entry-point with a `package.json` outside `node_modules/`', () => {
const packagePath = _(`/project/libs/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = fs.join(packagePath, 'some-entry-point');
const expectedPackageName = nameWithScope('package-json-package-name');
setUpPackageWithEntryPointPackageJson(expectedPackageName, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
it('for a secondary entry-point without a `package.json` outside `node_modules/`', () => {
const packagePath = _(`/project/libs/${nameWithScope('on-disk-package-name')}`);
const entryPointPath = fs.join(packagePath, 'some-entry-point');
const expectedPackageName = nameWithScope('on-disk-package-name');
setUpPackageWithoutEntryPointPackageJson(packagePath, entryPointPath);
expect(getPackageName(packagePath, entryPointPath)).toBe(expectedPackageName);
});
});
});
it('should return `INCOMPATIBLE_ENTRY_POINT` if there is no typings or types field in the package.json',
() => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/missing_typings/package.json'),
contents: createPackageJson('missing_typings', {excludes: ['typings']})
},
{
name: _(
'/project/node_modules/some_package/missing_typings/missing_typings.metadata.json'),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/missing_typings'));
expect(entryPoint).toBe(INCOMPATIBLE_ENTRY_POINT);
});
it('should return `INCOMPATIBLE_ENTRY_POINT` if the typings or types field is not a string in the package.json',
() => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/typings_array/package.json'),
contents: createPackageJson('typings_array', {typingsIsArray: true})
},
{
name: _(
'/project/node_modules/some_package/typings_array/missing_typings.metadata.json'),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/typings_array'));
expect(entryPoint).toBe(INCOMPATIBLE_ENTRY_POINT);
});
for (let prop of SUPPORTED_FORMAT_PROPERTIES) {
// Ignore the UMD format
if (prop === 'main' || prop === 'browser') continue;
// Let's give 'module' a specific path, otherwise compute it based on the property.
const typingsPath = prop === 'module' ? 'index' : `${prop}/missing_typings`;
it(`should return an object if it can guess the typings path from the "${prop}" field`,
() => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/missing_typings/package.json'),
contents: createPackageJson('missing_typings', {excludes: ['typings']}),
},
{
name: _(`/project/node_modules/some_package/missing_typings/${
typingsPath}.metadata.json`),
contents: 'some meta data',
},
{
name: _(`/project/node_modules/some_package/missing_typings/${typingsPath}.d.ts`),
contents: '// some typings file',
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/missing_typings'));
expect(entryPoint).toEqual({
name: 'some_package/missing_typings',
path: _('/project/node_modules/some_package/missing_typings'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: loadPackageJson(fs, '/project/node_modules/some_package/missing_typings'),
typings: _(`/project/node_modules/some_package/missing_typings/${typingsPath}.d.ts`),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
}
it('should return an object with `compiledByAngular` set to false if there is no metadata.json file next to the typing file',
() => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/missing_metadata/package.json'),
contents: createPackageJson('missing_metadata')
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/missing_metadata'));
expect(entryPoint).toEqual({
name: 'some_package/missing_metadata',
path: _('/project/node_modules/some_package/missing_metadata'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: loadPackageJson(fs, '/project/node_modules/some_package/missing_metadata'),
typings: _(`/project/node_modules/some_package/missing_metadata/missing_metadata.d.ts`),
compiledByAngular: false,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
it('should return an object with `compiledByAngular` set to true if there is no metadata.json file but the entry-point has a configuration',
() => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/missing_metadata/package.json'),
contents: createPackageJson('missing_metadata'),
},
// no metadata.json!
]);
const config = new NgccConfiguration(fs, _('/project'));
spyOn(config, 'getPackageConfig')
.and.returnValue(new ProcessedNgccPackageConfig(
fs, _('/project/node_modules/some_package'),
{entryPoints: {'./missing_metadata': {}}}));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/missing_metadata'));
expect(entryPoint).toEqual({
name: 'some_package/missing_metadata',
path: _('/project/node_modules/some_package/missing_metadata'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: loadPackageJson(fs, '/project/node_modules/some_package/missing_metadata'),
typings: _('/project/node_modules/some_package/missing_metadata/missing_metadata.d.ts'),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
it('should work if the typings field is named `types', () => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/types_rather_than_typings/package.json'),
contents: createPackageJson('types_rather_than_typings', {typingsProp: 'types'})
},
{
name: _(
'/project/node_modules/some_package/types_rather_than_typings/types_rather_than_typings.metadata.json'),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/types_rather_than_typings'));
expect(entryPoint).toEqual({
name: 'some_package/types_rather_than_typings',
path: _('/project/node_modules/some_package/types_rather_than_typings'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson:
loadPackageJson(fs, '/project/node_modules/some_package/types_rather_than_typings'),
typings: _(
`/project/node_modules/some_package/types_rather_than_typings/types_rather_than_typings.d.ts`),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
it('should work with Angular Material style package.json', () => {
loadTestFiles([
{
name: _('/project/node_modules/some_package/material_style/package.json'),
contents: `{
"name": "some_package/material_style",
"typings": "./material_style.d.ts",
"main": "./bundles/material_style.umd.js",
"module": "./esm5/material_style.es5.js",
"es2015": "./esm2015/material_style.js"
}`
},
{
name: _('/project/node_modules/some_package/material_style/material_style.metadata.json'),
contents: 'some meta data'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/material_style'));
expect(entryPoint).toEqual({
name: 'some_package/material_style',
path: _('/project/node_modules/some_package/material_style'),
packageName: 'some_package',
packagePath: SOME_PACKAGE,
repositoryUrl: '',
packageJson: loadPackageJson(fs, '/project/node_modules/some_package/material_style'),
typings: _(`/project/node_modules/some_package/material_style/material_style.d.ts`),
compiledByAngular: true,
ignoreMissingDependencies: false,
generateDeepReexports: false,
});
});
it('should return `INCOMPATIBLE_ENTRY_POINT` if the package.json is not valid JSON', () => {
loadTestFiles([
// package.json might not be a valid JSON
// for example, @schematics/angular contains a package.json blueprint
// with unexpected symbols
{
name: _('/project/node_modules/some_package/unexpected_symbols/package.json'),
contents: '{"devDependencies": {<% if (!minimal) { %>"@types/jasmine": "~2.8.8" <% } %>}}'
},
]);
const config = new NgccConfiguration(fs, _('/project'));
const entryPoint = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/unexpected_symbols'));
expect(entryPoint).toBe(INCOMPATIBLE_ENTRY_POINT);
});
});
describe('getEntryPointFormat()', () => {
let SOME_PACKAGE: AbsoluteFsPath;
let _: typeof absoluteFrom;
let fs: ReadonlyFileSystem;
let entryPoint: EntryPoint;
beforeEach(() => {
_ = absoluteFrom;
SOME_PACKAGE = _('/project/node_modules/some_package');
fs = getFileSystem();
loadTestFiles([{
name: _('/project/node_modules/some_package/valid_entry_point/package.json'),
contents: createPackageJson('valid_entry_point')
}]);
const config = new NgccConfiguration(fs, _('/project'));
const result = getEntryPointInfo(
fs, config, new MockLogger(), SOME_PACKAGE,
_('/project/node_modules/some_package/valid_entry_point'));
if (!isEntryPoint(result)) {
return fail(`Expected an entry point but got ${result}`);
}
entryPoint = result;
});
it('should return `esm2015` format for `fesm2015` property', () => {
expect(getEntryPointFormat(fs, entryPoint, 'fesm2015')).toBe('esm2015');
});
it('should return `esm5` format for `fesm5` property', () => {
expect(getEntryPointFormat(fs, entryPoint, 'fesm5')).toBe('esm5');
});
it('should return `esm2015` format for `es2015` property', () => {
expect(getEntryPointFormat(fs, entryPoint, 'es2015')).toBe('esm2015');
});
it('should return `esm2015` format for `esm2015` property', () => {
expect(getEntryPointFormat(fs, entryPoint, 'esm2015')).toBe('esm2015');
});
it('should return `esm5` format for `esm5` property', () => {
expect(getEntryPointFormat(fs, entryPoint, 'esm5')).toBe('esm5');
});
it('should return `esm5` format for `module` property', () => {
expect(getEntryPointFormat(fs, entryPoint, 'module')).toBe('esm5');
});
it('should return `esm2015` format for `module` property if it points to esm2015 output',
() => {
entryPoint.packageJson['module'] = '../fesm2015/valid-entry-point.js';
expect(getEntryPointFormat(fs, entryPoint, 'module')).toBe('esm2015');
});
(['browser', 'main'] as EntryPointJsonProperty[]).forEach(browserOrMain => {
it('should return `esm5` for `' + browserOrMain +
'` if the file contains import or export statements',
() => {
const name = _(
'/project/node_modules/some_package/valid_entry_point/bundles/valid_entry_point/index.js');
loadTestFiles([{name, contents: `import * as core from '@angular/core;`}]);
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('esm5');
loadTestFiles([{name, contents: `import {Component} from '@angular/core;`}]);
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('esm5');
loadTestFiles([{name, contents: `export function foo() {}`}]);
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('esm5');
loadTestFiles([{name, contents: `export * from 'abc';`}]);
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('esm5');
});
it('should return `umd` for `' + browserOrMain +
'` if the file contains a UMD wrapper function',
() => {
loadTestFiles([{
name: _(
'/project/node_modules/some_package/valid_entry_point/bundles/valid_entry_point/index.js'),
contents: `
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) :
typeof define === 'function' && define.amd ? define('@angular/common', ['exports', '@angular/core'], factory) :
(global = global || self, factory((global.ng = global.ng || {}, global.ng.common = {}), global.ng.core));
}(this, function (exports, core) { 'use strict'; }));
`
}]);
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('umd');
});
it('should return `commonjs` for `' + browserOrMain +
'` if the file does not contain a UMD wrapper function',
() => {
loadTestFiles([{
name: _(
'/project/node_modules/some_package/valid_entry_point/bundles/valid_entry_point/index.js'),
contents: `
const core = require('@angular/core);
module.exports = {};
`
}]);
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('commonjs');
});
it('should resolve the format path with suitable postfixes', () => {
loadTestFiles([{
name: _(
'/project/node_modules/some_package/valid_entry_point/bundles/valid_entry_point/index.js'),
contents: `
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) :
typeof define === 'function' && define.amd ? define('@angular/common', ['exports', '@angular/core'], factory) :
(global = global || self, factory((global.ng = global.ng || {}, global.ng.common = {}), global.ng.core));
}(this, function (exports, core) { 'use strict'; }));
`
}]);
entryPoint.packageJson.main = './bundles/valid_entry_point/index';
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('umd');
entryPoint.packageJson.main = './bundles/valid_entry_point';
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('umd');
});
it('should match alternate UMD format', () => {
// Note that in this format, instead of the whole wrapper being enclosed in parentheses,
// only the wrapper function is enclosed and the call is not inside the parentheses.
loadTestFiles([{
name: _(
'/project/node_modules/some_package/valid_entry_point/bundles/valid_entry_point/index.js'),
contents: `
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) :
typeof define === 'function' && define.amd ? define('@angular/common', ['exports', '@angular/core'], factory) :
(global = global || self, factory((global.ng = global.ng || {}, global.ng.common = {}), global.ng.core));
})(this, function (exports, core) { 'use strict'; });
`
}]);
entryPoint.packageJson.main = './bundles/valid_entry_point';
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('umd');
});
it('should detect UMD even if the wrapper function is not of a supported format', () => {
// In order to correctly process UMD, we require that at least one CommonJS variant is
// present. However, for the purposes of detecting the module format, it should not matter
// what the body of the wrapper function looks like.
loadTestFiles([{
name: _(
'/project/node_modules/some_package/valid_entry_point/bundles/valid_entry_point/index.js'),
contents: `
(function (global, factory) {
// This is not a supported format for the wrapper function body, but it should still
// be detected as UMD (since it is closer to UMD than any other of the supported
// formats).
typeof define === 'function' && define.amd ? define([], factory) : factory();
})(this, function () { 'use strict'; });
`,
}]);
entryPoint.packageJson.main = './bundles/valid_entry_point';
expect(getEntryPointFormat(fs, entryPoint, browserOrMain)).toBe('umd');
});
});
it('should return `undefined` if the `browser` property is not a string', () => {
entryPoint.packageJson.browser = {} as any;
expect(getEntryPointFormat(fs, entryPoint, 'browser')).toBeUndefined();
});
});
});
export function createPackageJson(
entryPointName: string, {excludes, typingsProp = 'typings', typingsIsArray, version}: {
excludes?: string[],
typingsProp?: string,
typingsIsArray?: boolean,
version?: string
} = {}): string {
const packageJson: EntryPointPackageJson = {
name: (entryPointName === '') ? 'some_package' : `some_package/${entryPointName}`,
version,
[typingsProp]: typingsIsArray ? [`./${entryPointName}.d.ts`] : `./${entryPointName}.d.ts`,
fesm2015: `./fesm2015/${entryPointName}.js`,
esm2015: `./esm2015/${entryPointName}.js`,
es2015: `./es2015/${entryPointName}.js`,
fesm5: `./fesm5/${entryPointName}.js`,
esm5: `./esm5/${entryPointName}.js`,
main: `./bundles/${entryPointName}/index.js`,
browser: `./bundles/${entryPointName}/index.js`,
module: './index.js',
};
if (excludes) {
excludes.forEach(exclude => delete packageJson[exclude]);
}
return JSON.stringify(packageJson);
}
export function loadPackageJson(fs: ReadonlyFileSystem, packagePath: string) {
return JSON.parse(fs.readFile(fs.resolve(packagePath + '/package.json'))) as
EntryPointPackageJson;
} | the_stack |
import { ContainerIterator, BaseType, Pair } from "../Base/Base";
import { TreeIterator, TreeNode } from "../Base/Tree";
export interface MapType<K, V> extends BaseType {
/**
* @return Iterator pointing to the begin element.
*/
begin: () => ContainerIterator<Pair<K, V>>;
/**
* @return Iterator pointing to the super end like c++.
*/
end: () => ContainerIterator<Pair<K, V>>;
/**
* @return Iterator pointing to the end element.
*/
rBegin: () => ContainerIterator<Pair<K, V>>;
/**
* @return Iterator pointing to the super begin like c++.
*/
rEnd: () => ContainerIterator<Pair<K, V>>;
/**
* @return The first element.
*/
front: () => Pair<K, V> | undefined;
/**
* @return The last element.
*/
back: () => Pair<K, V> | undefined;
forEach: (callback: (element: Pair<K, V>, index: number) => void) => void;
/**
* @param element The element you want to find.
* @return Iterator pointing to the element if found, or super end if not found.
*/
find: (key: K) => ContainerIterator<Pair<K, V>>;
/**
* @return An iterator to the first element not less than the given key.
*/
lowerBound: (key: K) => ContainerIterator<Pair<K, V>>;
/**
* @return An iterator to the first element greater than the given key.
*/
upperBound: (key: K) => ContainerIterator<Pair<K, V>>;
/**
* @return An iterator to the first element not greater than the given key.
*/
reverseLowerBound: (key: K) => ContainerIterator<Pair<K, V>>;
/**
* @return An iterator to the first element less than the given key.
*/
reverseUpperBound: (key: K) => ContainerIterator<Pair<K, V>>;
/**
* Gets the key and value of the element at the specified position.
*/
getElementByPos: (pos: number) => Pair<K, V>;
/**
* Gets the value of the element of the specified key.
*/
getElementByKey: (key: K) => V | undefined;
/**
* Insert a new key-value pair or set value by key.
*/
setElement: (key: K, value: V) => void;
/**
* Removes the elements at the specified position.
*/
eraseElementByPos: (pos: number) => void;
/**
* Removes the elements of the specified key.
*/
eraseElementByKey: (key: K) => void;
/**
* @return An iterator point to the next iterator.
* Removes element by iterator.
*/
eraseElementByIterator: (iter: ContainerIterator<Pair<K, V>>) => ContainerIterator<Pair<K, V>>;
/**
* Union the other Set to self.
*/
union: (other: MapType<K, V>) => void;
/**
* @return The height of the RB-tree.
*/
getHeight: () => number;
/**
* Using for 'for...of' syntax like Array.
*/
[Symbol.iterator]: () => Generator<Pair<K, V>, void, undefined>;
}
function Map<K, V>(this: MapType<K, V>, container: { forEach: (callback: (element: Pair<K, V>) => void) => void } = [], cmp: (x: K, y: K) => number) {
cmp = cmp || ((x, y) => {
if (x < y) return -1;
if (x > y) return 1;
return 0;
});
let len = 0;
let root = new TreeNode<K, V>();
root.color = TreeNode.TreeNodeColorType.black;
const header = new TreeNode<K, V>();
header.parent = root;
root.parent = header;
this.size = function () {
return len;
};
this.empty = function () {
return len === 0;
};
this.clear = function () {
len = 0;
root.key = root.value = undefined;
root.leftChild = root.rightChild = root.brother = undefined;
header.leftChild = header.rightChild = undefined;
};
this.begin = function () {
return new TreeIterator(header.leftChild || header, header);
}
this.end = function () {
return new TreeIterator(header, header);
}
this.rBegin = function () {
return new TreeIterator(header.rightChild || header, header);
}
this.rEnd = function () {
return new TreeIterator(header, header);
}
const findSubTreeMinNode: (curNode: TreeNode<K, V>) => TreeNode<K, V> = function (curNode: TreeNode<K, V>) {
if (!curNode || curNode.key === undefined) throw new Error("unknown error");
return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;
};
const findSubTreeMaxNode: (curNode: TreeNode<K, V>) => TreeNode<K, V> = function (curNode: TreeNode<K, V>) {
if (!curNode || curNode.key === undefined) throw new Error("unknown error");
return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;
};
this.front = function () {
if (this.empty()) return undefined;
const minNode = header.leftChild;
if (!minNode || minNode.key === undefined || minNode.value === undefined) throw new Error("unknown error");
return {
key: minNode.key,
value: minNode.value
};
};
this.back = function () {
if (this.empty()) return undefined;
const maxNode = header.rightChild;
if (!maxNode || maxNode.key === undefined || maxNode.value === undefined) throw new Error("unknown error");
return {
key: maxNode.key,
value: maxNode.value
};
};
this.forEach = function (callback: (element: Pair<K, V>, index: number) => void) {
let index = 0;
for (const pair of this) callback(pair, index++);
};
this.getElementByPos = function (pos: number) {
if (pos < 0 || pos >= this.size()) throw new Error("pos must more than 0 and less than set's size");
let index = 0;
for (const pair of this) {
if (index === pos) return pair;
++index;
}
throw new Error("unknown Error");
};
const _lowerBound: (curNode: TreeNode<K, V> | undefined, key: K) => TreeNode<K, V> | undefined = (curNode: TreeNode<K, V> | undefined, key: K) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult === 0) return curNode;
if (cmpResult < 0) return _lowerBound(curNode.rightChild, key);
const resNode = _lowerBound(curNode.leftChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.lowerBound = function (key: K) {
const resNode = _lowerBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const _upperBound: (curNode: TreeNode<K, V> | undefined, key: K) => TreeNode<K, V> | undefined = (curNode: TreeNode<K, V> | undefined, key: K) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult <= 0) return _upperBound(curNode.rightChild, key);
const resNode = _upperBound(curNode.leftChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.upperBound = function (key: K) {
const resNode = _upperBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const _reverseLowerBound: (curNode: TreeNode<K, V> | undefined, key: K) => TreeNode<K, V> | undefined = (curNode: TreeNode<K, V> | undefined, key: K) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult === 0) return curNode;
if (cmpResult > 0) return _reverseLowerBound(curNode.leftChild, key);
const resNode = _reverseLowerBound(curNode.rightChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.reverseLowerBound = function (key: K) {
const resNode = _reverseLowerBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const _reverseUpperBound: (curNode: TreeNode<K, V> | undefined, key: K) => TreeNode<K, V> | undefined = (curNode: TreeNode<K, V> | undefined, key: K) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult >= 0) return _reverseUpperBound(curNode.leftChild, key);
const resNode = _reverseUpperBound(curNode.rightChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.reverseUpperBound = function (key: K) {
const resNode = _reverseUpperBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const eraseNodeSelfBalance = function (curNode: TreeNode<K, V>) {
const parentNode = curNode.parent;
if (!parentNode || parentNode === header) {
if (curNode === root) return;
throw new Error("unknown error");
}
if (curNode.color === TreeNode.TreeNodeColorType.red) {
curNode.color = TreeNode.TreeNodeColorType.black;
return;
}
const brotherNode = curNode.brother;
if (!brotherNode) throw new Error("unknown error");
if (curNode === parentNode.leftChild) {
if (brotherNode.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.black;
parentNode.color = TreeNode.TreeNodeColorType.red;
const newRoot = parentNode.rotateLeft();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if (brotherNode.color === TreeNode.TreeNodeColorType.black) {
if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = parentNode.color;
parentNode.color = TreeNode.TreeNodeColorType.black;
if (brotherNode.rightChild) brotherNode.rightChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = parentNode.rotateLeft();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
curNode.color = TreeNode.TreeNodeColorType.black;
} else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
if (brotherNode.leftChild) brotherNode.leftChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = brotherNode.rotateRight();
if (root === brotherNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode.TreeNodeColorType.black)) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
eraseNodeSelfBalance(parentNode);
}
}
} else if (curNode === parentNode.rightChild) {
if (brotherNode.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.black;
parentNode.color = TreeNode.TreeNodeColorType.red;
const newRoot = parentNode.rotateRight();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if (brotherNode.color === TreeNode.TreeNodeColorType.black) {
if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = parentNode.color;
parentNode.color = TreeNode.TreeNodeColorType.black;
if (brotherNode.leftChild) brotherNode.leftChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = parentNode.rotateRight();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
curNode.color = TreeNode.TreeNodeColorType.black;
} else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
if (brotherNode.rightChild) brotherNode.rightChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = brotherNode.rotateLeft();
if (root === brotherNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode.TreeNodeColorType.black)) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
eraseNodeSelfBalance(parentNode);
}
}
}
};
const eraseNode = function (curNode: TreeNode<K, V>) {
let swapNode: TreeNode<K, V> = curNode;
while (swapNode.leftChild || swapNode.rightChild) {
if (swapNode.rightChild) {
swapNode = findSubTreeMinNode(swapNode.rightChild);
const tmpKey = curNode.key;
curNode.key = swapNode.key;
swapNode.key = tmpKey;
const tmpValue = curNode.value;
curNode.value = swapNode.value;
swapNode.value = tmpValue;
curNode = swapNode;
}
if (swapNode.leftChild) {
swapNode = findSubTreeMaxNode(swapNode.leftChild);
const tmpKey = curNode.key;
curNode.key = swapNode.key;
swapNode.key = tmpKey;
const tmpValue = curNode.value;
curNode.value = swapNode.value;
swapNode.value = tmpValue;
curNode = swapNode;
}
}
if (swapNode.key === undefined) throw new Error("unknown error");
if (header.leftChild && header.leftChild.key !== undefined && cmp(header.leftChild.key, swapNode.key) === 0) {
if (header.leftChild !== root) header.leftChild = header.leftChild?.parent;
else if (header.leftChild?.rightChild) header.leftChild = header.leftChild?.rightChild;
else header.leftChild = undefined;
}
if (header.rightChild && header.rightChild.key !== undefined && cmp(header.rightChild.key, swapNode.key) === 0) {
if (header.rightChild !== root) header.rightChild = header.rightChild?.parent;
else if (header.rightChild?.leftChild) header.rightChild = header.rightChild?.leftChild;
else header.rightChild = undefined;
}
eraseNodeSelfBalance(swapNode);
if (swapNode) swapNode.remove();
--len;
root.color = TreeNode.TreeNodeColorType.black;
};
const inOrderTraversal: (curNode: TreeNode<K, V> | undefined, callback: (curNode: TreeNode<K, V>) => boolean) => boolean = function (curNode: TreeNode<K, V> | undefined, callback: (curNode: TreeNode<K, V>) => boolean) {
if (!curNode || curNode.key === undefined) return false;
const ifReturn = inOrderTraversal(curNode.leftChild, callback);
if (ifReturn) return true;
if (callback(curNode)) return true;
return inOrderTraversal(curNode.rightChild, callback);
};
this.eraseElementByPos = function (pos: number) {
if (pos < 0 || pos >= len) throw new Error("pos must more than 0 and less than set's size");
let index = 0;
inOrderTraversal(root, curNode => {
if (pos === index) {
eraseNode(curNode);
return true;
}
++index;
return false;
});
};
this.eraseElementByKey = function (key: K) {
if (this.empty()) return;
const curNode = findElementPos(root, key);
if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, key) !== 0) return;
eraseNode(curNode);
};
const findInsertPos: (curNode: TreeNode<K, V>, key: K) => TreeNode<K, V> = function (curNode: TreeNode<K, V>, key: K) {
if (!curNode || curNode.key === undefined) throw new Error("unknown error");
const cmpResult = cmp(key, curNode.key);
if (cmpResult < 0) {
if (!curNode.leftChild) {
curNode.leftChild = new TreeNode<K, V>();
curNode.leftChild.parent = curNode;
curNode.leftChild.brother = curNode.rightChild;
if (curNode.rightChild) curNode.rightChild.brother = curNode.leftChild;
return curNode.leftChild;
}
return findInsertPos(curNode.leftChild, key);
} else if (cmpResult > 0) {
if (!curNode.rightChild) {
curNode.rightChild = new TreeNode<K, V>();
curNode.rightChild.parent = curNode;
curNode.rightChild.brother = curNode.leftChild;
if (curNode.leftChild) curNode.leftChild.brother = curNode.rightChild;
return curNode.rightChild;
}
return findInsertPos(curNode.rightChild, key);
}
return curNode;
};
const insertNodeSelfBalance = function (curNode: TreeNode<K, V>) {
const parentNode = curNode.parent;
if (!parentNode || parentNode === header) {
if (curNode === root) return;
throw new Error("unknown error");
}
if (parentNode.color === TreeNode.TreeNodeColorType.black) return;
if (parentNode.color === TreeNode.TreeNodeColorType.red) {
const uncleNode = parentNode.brother;
const grandParent = parentNode.parent;
if (!grandParent) throw new Error("unknown error");
if (uncleNode && uncleNode.color === TreeNode.TreeNodeColorType.red) {
uncleNode.color = parentNode.color = TreeNode.TreeNodeColorType.black;
grandParent.color = TreeNode.TreeNodeColorType.red;
insertNodeSelfBalance(grandParent);
} else if (!uncleNode || uncleNode.color === TreeNode.TreeNodeColorType.black) {
if (parentNode === grandParent.leftChild) {
if (curNode === parentNode.leftChild) {
parentNode.color = TreeNode.TreeNodeColorType.black;
grandParent.color = TreeNode.TreeNodeColorType.red;
const newRoot = grandParent.rotateRight();
if (grandParent === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
} else if (curNode === parentNode.rightChild) {
const newRoot = parentNode.rotateLeft();
if (parentNode === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
insertNodeSelfBalance(parentNode);
}
} else if (parentNode === grandParent.rightChild) {
if (curNode === parentNode.leftChild) {
const newRoot = parentNode.rotateRight();
if (parentNode === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
insertNodeSelfBalance(parentNode);
} else if (curNode === parentNode.rightChild) {
parentNode.color = TreeNode.TreeNodeColorType.black;
grandParent.color = TreeNode.TreeNodeColorType.red;
const newRoot = grandParent.rotateLeft();
if (grandParent === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
}
}
}
}
};
this.setElement = function (key: K, value: V) {
if (key === null || key === undefined) {
throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
}
if (value === null || value === undefined) {
this.eraseElementByKey(key);
return;
}
if (this.empty()) {
++len;
root.key = key;
root.value = value;
root.color = TreeNode.TreeNodeColorType.black;
header.leftChild = root;
header.rightChild = root;
return;
}
const curNode = findInsertPos(root, key);
if (curNode.key !== undefined && cmp(curNode.key, key) === 0) {
curNode.value = value;
return;
}
++len;
curNode.key = key;
curNode.value = value;
if (header.leftChild === undefined || header.leftChild.key === undefined || cmp(header.leftChild.key, key) > 0) {
header.leftChild = curNode;
}
if (header.rightChild === undefined || header.rightChild.key === undefined || cmp(header.rightChild.key, key) < 0) {
header.rightChild = curNode;
}
insertNodeSelfBalance(curNode);
root.color = TreeNode.TreeNodeColorType.black;
};
const findElementPos: (curNode: TreeNode<K, V> | undefined, key: K) => TreeNode<K, V> | undefined = function (curNode: TreeNode<K, V> | undefined, key: K) {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(key, curNode.key);
if (cmpResult < 0) return findElementPos(curNode.leftChild, key);
else if (cmpResult > 0) return findElementPos(curNode.rightChild, key);
return curNode;
};
this.find = function (key: K) {
const curNode = findElementPos(root, key);
if (curNode === undefined || curNode.key === undefined) return this.end();
return new TreeIterator(curNode, header);
};
this.getElementByKey = function (key: K) {
const curNode = findElementPos(root, key);
if (curNode?.key === undefined || curNode?.value === undefined) throw new Error("unknown error");
return curNode.value;
};
// waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).
// (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)
this.union = function (other: MapType<K, V>) {
other.forEach(({ key, value }) => this.setElement(key, value));
};
this.getHeight = function () {
if (this.empty()) return 0;
const traversal: (curNode: TreeNode<K, V> | undefined) => number = function (curNode: TreeNode<K, V> | undefined) {
if (!curNode) return 1;
return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;
};
return traversal(root);
};
if (typeof Symbol.iterator === 'symbol') {
const iterationFunc: (curNode: TreeNode<K, V> | undefined) => Generator<Pair<K, V>, void, undefined> = function* (curNode: TreeNode<K, V> | undefined) {
if (!curNode || curNode.key === undefined || curNode.value === undefined) return;
yield* iterationFunc(curNode.leftChild);
yield { key: curNode.key, value: curNode.value };
yield* iterationFunc(curNode.rightChild);
};
this[Symbol.iterator] = function () {
return iterationFunc(root);
};
}
container.forEach(({ key, value }) => this.setElement(key, value));
}
export default (Map as unknown as { new <K, V>(container?: { forEach: (callback: (element: Pair<K, V>) => void) => void }, cmp?: (x: K, y: K) => number): MapType<K, V> }); | the_stack |
declare namespace egret.sys {
/**
* @private
* @param channel
*/
function $pushSoundChannel(channel: SoundChannel): void;
/**
* @private
* @param channel
*/
function $popSoundChannel(channel: SoundChannel): boolean;
}
declare namespace egret {
/**
* The Sound class lets you work with sound in an application.
* The Sound class lets you create a Sound object, load and play an external audio file into that object.
* More detailed control of the sound is performed through the SoundChannel
*
* @event egret.Event.COMPLETE Dispatch when the audio resource is loaded and ready to play
* @event egret.IOErrorEvent.IO_ERROR Dispatch when the audio resource is failed to load
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/media/Sound.ts
* @language en_US
*/
/**
* Sound 允许您在应用程序中使用声音。使用 Sound 类可以创建 Sound 对象、将外部音频文件加载到该对象并播放该文件。
* 可通过 SoundChannel 对声音执行更精细的控制,如控制音量和监控播放进度。
* @see http://edn.egret.com/cn/docs/page/156 音频系统
*
* @event egret.Event.COMPLETE 音频加载完成时抛出
* @event egret.IOErrorEvent.IO_ERROR 音频加载失败时抛出
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/media/Sound.ts
* @language zh_CN
*/
interface Sound extends EventDispatcher {
/**
* Initiates loading of an external audio file from the specified URL.
* @param url Audio file URL
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 启动从指定 URL 加载外部音频文件的过程。
* @param url 需要加载的音频文件URL
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
load(url: string): void;
/**
* Generates a new SoundChannel object to play back the sound.
* @param startTime The initial position in seconds at which playback should start, (default = 0)
* @param loops Plays, the default value is 0. Greater than 0 to the number of plays, such as 1 to play 1, less than or equal to 0, to loop.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 生成一个新的 SoundChannel 对象来播放该声音。此方法返回 SoundChannel 对象,访问该对象可停止声音调整音量。
* @param startTime 应开始播放的初始位置(以秒为单位),默认值是 0
* @param loops 播放次数,默认值是 0,循环播放。 大于 0 为播放次数,如 1 为播放 1 次;小于等于 0,为循环播放。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
play(startTime?: number, loops?: number): SoundChannel;
/**
* Closes the stream, causing any download of data to cease
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 关闭该流,从而停止所有数据的下载。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
close(): void;
/**
* Type, default is egret.Sound.EFFECT.
* In the native and runtime environment, while only play a background music, sound length so as not to be too long.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 类型,默认为 egret.Sound.EFFECT。
* 在 native 和 runtime 环境下,背景音乐同时只能播放一个,音效长度尽量不要太长。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
type: string;
/**
* Length of the current sound (in seconds).
* @version Egret 2.4
* @platform Web,Native
* @readOnly
* @language en_US
*/
/**
* 当前声音的长度(以秒为单位)。
* @version Egret 2.4
* @platform Web,Native
* @readOnly
* @language zh_CN
*/
length: number;
}
/**
* @copy egret.Sound
*/
let Sound: {
/**
* Create Sound object, load an external audio file and play
* @param url Audio file URL, Sound will start to load the media if url is not empty
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 创建 Sound 对象、将外部音频文件加载到该对象并播放该文件
* @param url 需要加载的音频文件URL,如果指定了 url, Sound会立即开始加载指定的媒体文件
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
new (): Sound;
/**
* Background music
* @default "music"
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 背景音乐
* @default "music"
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
MUSIC: string;
/**
* EFFECT
* @default "effect"
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 音效
* @default "effect"
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
EFFECT: string;
};
}
declare namespace egret {
/**
* The Video class lets you work with video in an application.
* The Video class lets you create a Video object, load and play an external video file into that object.
* Note: On most mobile device, the video is playback in the full screen mode.<br/>
*
* @param url URL of the media to play, Video will start to load if the url is not empty
*
* @event egret.Event.COMPLETE Dispatch when the video resource is loaded and ready to play
* @event egret.Event.ENDED Dispatch when the video playback ended
* @event egret.IOErrorEvent.IO_ERROR when the video is failed to load
* @version Egret 2.4
* @platform Web
* @includeExample egret/media/Video.ts
* @language en_US
*/
/**
* Video 允许您在应用程序中使用视频。使用 Video 类可以创建 Video 对象、将外部视频文件加载到该对象并播放该文件。<br/>
* 注意: 在大多数移动设备中,视频是强制全屏播放的,所以你可以直接调用 play() 方法全屏播放视频,不用将它绘制在Stage中。
* @see http://edn.egret.com/cn/docs/page/657 视频系统
*
* @param url 要播放的视频的URL,如果url不为空,Video会立即加载这个视频
*
* @event egret.Event.COMPLETE 视频加载完成时抛出
* @event egret.Event.ENDED 视频播放完成时抛出
* @event egret.IOErrorEvent.IO_ERROR 视频加载失败时触发
* @version Egret 2.4
* @platform Web
* @includeExample egret/media/Video.ts
* @language zh_CN
*/
interface Video extends DisplayObject {
/**
* Initiates loading of an external video file from the specified URL.
* @param url Audio file URL
* * @param cache Should cache the video,only used in Native
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 启动从指定 URL 加载外部视频文件的过程。
* @param url 需要加载的视频文件URL
* @param cache 是否需要缓存到本地,只在 Native 上使用
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
load(url: string, cache?: boolean): void;
/**
* Play back the video.
* @param startTime The initial position in seconds at which playback should start, (default = 0)
* @param loop Defines should play the video again when the video is ended. (default = false)
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 播放该视频
* @param startTime 应开始播放的初始位置(以秒为单位),默认值是视频上次结束的位置
* @param loop 是否需要循环播放,默认值是 false
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
play(startTime?: number, loop?: boolean): any;
/**
* Closes the stream, causing any download of data to cease
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 关闭该流,从而停止所有数据的下载。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
close(): void;
/**
* The URL of the video you want to play.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 想要播放的视频的URL
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
src: string;
/**
* The URL of an image you want to display before the video is loaded or video cannot been draw on the canvas on some mobile device.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 视频加载前,或者在不支持将 video 画在 canvas 的设备上,想要显示的视频截图地址。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
poster: string;
/**
* Should play the video in fullscreen mode (default = true).
* Currently only supports full-screen mobile terminal web.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 是否全屏播放这个视频(默认值是 true)。
* 目前移动端 web 只支持全屏。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
fullscreen: boolean;
/**
* The volume, ranging from 0 (silent) to 1 (full volume).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 音量范围从 0(静音)至 1(最大音量)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
volume: number;
/**
* When the video is playing, the position property indicates
* in seconds the current point that is being played in the video file.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 当播放视频时,position 属性表示视频文件中当前播放的位置(以秒为单位)
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
position: number;
/**
* Pause the video playing.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 暂停播放。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
pause(): void;
/**
* Get bitmapData of the video file, you can use the video as bitmapData on the stage.
* Note: On most mobile device, the video is playback in the full screen mode.
* So you can just use the play() method instead of draw it on the Stage
* @version Egret 2.4
* @platform Web
* @language en_US
*/
/**
* 获取视频的 bitmapData, 你可以将视频绘制到舞台上。
* 注意: 在大多数移动设备中,视频是全屏播放的,所以你可以直接调用 play() 方法全屏播放视频,不用将它绘制在Stage中。
* @version Egret 2.4
* @platform Web
* @language zh_CN
*/
bitmapData?: BitmapData;
/**
* Whether current video is paused.
* @version Egret 2.4
* @platform Web,Native
* @readOnly
* @language en_US
*/
/**
* 当前视频是否在暂停状态。
* @version Egret 2.4
* @platform Web,Native
* @readOnly
* @language zh_CN
*/
paused: boolean;
/**
* Length of the current video (in seconds).
* @version Egret 3.0.8
* @platform Web,Native
* @readOnly
* @language en_US
*/
/**
* 当前视频的长度(以秒为单位)。
* @version Egret 3.0.8
* @platform Web,Native
* @readOnly
* @language zh_CN
*/
length: number;
}
/**
* @copy egret.Video
*/
let Video: {
new (url?: string, cache?: boolean): Video;
};
}
declare namespace egret {
/**
* The SoundChannel class controls a sound in an application.
* Every sound is assigned to a sound channel, and the application
* can have multiple sound channels that are mixed together.
* The SoundChannel class contains a stop() method, properties for
* set the volume of the channel
*
* @event egret.Event.SOUND_COMPLETE Dispatch when a sound has finished playing at last time
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/media/Sound.ts
* @language en_US
*/
/**
* SoundChannel 类控制应用程序中的声音。每个声音均分配给一个声道,而且应用程序可以具有混合在一起的多个声道。
* SoundChannel 类包含 stop() 方法、用于设置音量和监视播放进度的属性。
*
* @event egret.Event.SOUND_COMPLETE 音频最后一次播放完成时抛出
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/media/Sound.ts
* @language zh_CN
*/
interface SoundChannel extends IEventDispatcher {
/**
* The volume, ranging from 0 (silent) to 1 (full volume).
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 音量范围从 0(静音)至 1(最大音量)。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
volume: number;
/**
* When the sound is playing, the position property indicates
* in seconds the current point that is being played in the sound file.
* @version Egret 2.4
* @platform Web,Native
* @readOnly
* @language en_US
*/
/**
* 当播放声音时,position 属性表示声音文件中当前播放的位置(以秒为单位)
* @version Egret 2.4
* @platform Web,Native
* @readOnly
* @language zh_CN
*/
position: number;
/**
* Stops the sound playing in the channel.
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 停止在该声道中播放声音。
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
stop(): void;
}
}
declare namespace egret.web {
/**
* @private
* @inheritDoc
*/
class HtmlSound extends egret.EventDispatcher implements egret.Sound {
/**
* Background music
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 背景音乐
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static MUSIC: string;
/**
* EFFECT
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 音效
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static EFFECT: string;
/**
* @private
*/
type: string;
/**
* @private
*/
private url;
/**
* @private
*/
private originAudio;
/**
* @private
*/
private loaded;
/**
* @private
* @inheritDoc
*/
constructor();
readonly length: number;
/**
* @inheritDoc
*/
load(url: string): void;
/**
* @inheritDoc
*/
play(startTime?: number, loops?: number): SoundChannel;
/**
* @inheritDoc
*/
close(): void;
/**
* @private
*/
private static audios;
private static clearAudios;
static $clear(url: string): void;
static $pop(url: string): HTMLAudioElement;
static $recycle(url: string, audio: HTMLAudioElement): void;
}
}
declare namespace egret.web {
/**
* @private
* @inheritDoc
*/
class HtmlSoundChannel extends egret.EventDispatcher implements egret.SoundChannel {
/**
* @private
*/
$url: string;
/**
* @private
*/
$loops: number;
/**
* @private
*/
$startTime: number;
/**
* @private
*/
private audio;
private isStopped;
/**
* @private
*/
constructor(audio: HTMLAudioElement);
private canPlay;
$play(): void;
/**
* @private
*/
private onPlayEnd;
/**
* @private
* @inheritDoc
*/
stop(): void;
/**
* @private
*/
private _volume;
/**
* @private
* @inheritDoc
*/
/**
* @inheritDoc
*/
volume: number;
/**
* @private
* @inheritDoc
*/
readonly position: number;
}
}
/**
* @private
*/
interface AudioBufferSourceNodeEgret {
buffer: any;
context: any;
onended: Function;
stop(when?: number): void;
noteOff(when?: number): void;
addEventListener(type: string, listener: Function, useCapture?: boolean): any;
removeEventListener(type: string, listener: Function, useCapture?: boolean): any;
disconnect(): any;
}
declare namespace egret.web {
/**
* @private
*/
class WebAudioDecode {
/**
* @private
*/
static canUseWebAudio: any;
/**
* @private
*/
static ctx: any;
/**
* @private
*/
static decodeArr: any[];
/**
* @private
*/
private static isDecoding;
/**
* @private
*
*/
static decodeAudios(): void;
}
/**
* @private
* @inheritDoc
*/
class WebAudioSound extends egret.EventDispatcher implements egret.Sound {
/**
* Background music
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 背景音乐
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static MUSIC: string;
/**
* EFFECT
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 音效
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static EFFECT: string;
/**
* @private
*/
type: string;
/**
* @private
*/
private url;
/**
* @private
*/
private loaded;
/**
* @private
* @inheritDoc
*/
constructor();
/**
* @private
*/
private audioBuffer;
readonly length: number;
/**
* @inheritDoc
*/
load(url: string): void;
/**
* @inheritDoc
*/
play(startTime?: number, loops?: number): SoundChannel;
/**
* @inheritDoc
*/
close(): void;
}
}
declare namespace egret.web {
/**
* @private
* @inheritDoc
*/
class WebAudioSoundChannel extends egret.EventDispatcher implements egret.SoundChannel {
/**
* @private
*/
$url: string;
/**
* @private
*/
$loops: number;
/**
* @private
*/
$startTime: number;
/**
* @private
* audio音频对象
* @member {any} egret.Sound#audio
*/
$audioBuffer: AudioBuffer;
/**
* @private
*/
private gain;
/**
* @private
*/
private bufferSource;
/**
* @private
*/
private context;
private isStopped;
/**
* @private
*/
constructor();
/**
* @private
*/
private _currentTime;
/**
* @private
*/
private _volume;
$play(): void;
stop(): void;
/**
* @private
*/
private onPlayEnd;
/**
* @private
* @inheritDoc
*/
/**
* @inheritDoc
*/
volume: number;
/**
* @private
*/
private _startTime;
/**
* @private
* @inheritDoc
*/
readonly position: number;
}
}
declare namespace egret.web {
/**
* @private
* @inheritDoc
*/
class WebVideo extends egret.DisplayObject implements egret.Video {
/**
* @inheritDoc
*/
src: string;
/**
* @inheritDoc
*/
poster: string;
/**
* @private
*/
private posterData;
/**
* @private
*/
private video;
/**
* @private
*/
private loaded;
/**
* @private
*/
private closed;
/**
* @private
*/
private heightSet;
/**
* @private
*/
private widthSet;
/**
* @inheritDoc
*/
constructor(url?: string, cache?: boolean);
/**
* @inheritDoc
*/
load(url?: string, cache?: boolean): void;
private isPlayed;
/**
* @inheritDoc
*/
play(startTime?: number, loop?: boolean): void;
private checkFullScreen(playFullScreen);
private goFullscreen();
private setFullScreenMonitor(use);
private screenError();
private screenChanged;
private exitFullscreen();
/**
* @private
*
*/
private onVideoEnded();
/**
* @private
*
*/
private onVideoError();
/**
* @inheritDoc
*/
close(): void;
/**
* @inheritDoc
*/
pause(): void;
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
volume: number;
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
position: number;
private _fullscreen;
/**
* @inheritDoc
*/
/**
* @inheritDoc
*/
fullscreen: boolean;
private _bitmapData;
/**
* @inheritDoc
*/
readonly bitmapData: BitmapData;
private loadPoster();
/**
* @private
*
*/
private onVideoLoaded;
/**
* @private
*/
$measureContentBounds(bounds: Rectangle): void;
private getPlayWidth();
private getPlayHeight();
private markDirty();
/**
* @private
* 设置显示高度
*/
$setHeight(value: number): void;
/**
* @private
* 设置显示宽度
*/
$setWidth(value: number): void;
readonly paused: boolean;
/**
* @inheritDoc
*/
readonly length: number;
}
} | the_stack |
import { spawn, ChildProcess } from 'child_process';
import { ReadStream } from 'fs';
import { CancelablePromise } from '../../../tools/promise.cancelable';
import { EventEmitter } from 'events';
import { Readable, Writable } from 'stream';
import * as path from 'path';
import * as fs from 'fs';
import * as FS from '../../../tools/fs';
import Logger from '../../../tools/env.logger';
import guid from '../../../tools/tools.guid';
import ServicePaths from '../../../services/service.paths';
import NullWritableStream from '../../../classes/stream.writable.null';
import Transform from './transform.inspecting';
export interface IMapData {
map: { [key: number]: string[] };
stats: { [key: string]: number };
}
export interface IScaledMapData {
map: { [key: number]: { [key: string ]: number } };
stats: { [key: string]: number };
}
export interface IIndexAround {
before: number;
after: number;
}
type THandler = () => void;
export class OperationInspecting extends EventEmitter {
private _logger: Logger;
private _streamFile: string;
private _searchFile: string;
private _streamGuid: string;
private _cleaners: Map<string, THandler> = new Map();
private _readTo: number = 0;
private _readFrom: number = 0;
private _tasks: Map<string, CancelablePromise<void, void>> = new Map();
private _inspected: IMapData = {
stats: {},
map: {},
};
private _cached: {
hash: string;
cache: IScaledMapData | undefined;
lines: number[];
sorted: boolean;
} = {
hash: '',
cache: undefined,
lines: [],
sorted: false,
};
constructor(streamGuid: string, streamFile: string, searchFile: string) {
super();
this._streamGuid = streamGuid;
this._streamFile = streamFile;
this._searchFile = searchFile;
this._logger = new Logger(`Search operation: inspecting (${streamGuid})`);
}
public destroy() {
this.removeAllListeners();
}
public perform(regExp: RegExp): CancelablePromise<void, void> {
const taskId: string = guid();
const task: CancelablePromise<void, void> = new CancelablePromise<void, void>((resolve, reject, cancel, self) => {
// Listen cancel for case if it will be canceled while fs.stat
let canceled: boolean = false;
self.cancel(() => {
canceled = true;
this._clear(taskId);
});
FS.exist(this._streamFile).then((exists: boolean) => {
if (canceled) {
return;
}
if (!exists) {
return resolve(undefined);
}
if (this._readFrom >= this._readTo || isNaN(this._readFrom) || !isFinite(this._readFrom) || isNaN(this._readTo) || !isFinite(this._readTo)) {
return reject(new Error(`(inspecting) Cannot perform search because a range isn't correct: from = ${this._readFrom}; to = ${this._readTo}`));
}
// Start measuring
const measurer = this._logger.measure(`inspecting #${guid()}`);
// Create reader
const reader: ReadStream = fs.createReadStream(this._searchFile, { encoding: 'utf8', start: this._readFrom, end: this._readTo });
// Create writer
const writer: NullWritableStream = new NullWritableStream();
// Create transform
const transform = new Transform({});
// Create process
const process = spawn(ServicePaths.getRG(), this._getProcArgs(regExp, '-'), {
cwd: path.dirname(this._streamFile),
stdio: [ 'pipe', 'pipe', 'pipe' ],
detached: true,
});
// Pipe process with reader: reader -> ripgrep
reader.pipe(process.stdin);
// Pipe process with writer: ripgrep -> writer (NULL writer)
process.stdout.pipe(transform).pipe(writer);
// Handeling errors
[process, process.stdin, process.stdout, writer, reader].forEach((smth: NullWritableStream | ChildProcess | Readable | ReadStream | Writable) => {
smth.once('error', (error: Error) => {
if (!this._cleaners.has(taskId)) {
return;
}
this._logger.error(`Error during inspecting: ${error.message}`);
reject(error);
});
});
// Handeling finishing
process.once('close', () => {
this._store(regExp.source, transform.getLines());
resolve(undefined);
});
// Create cleaner
this._cleaners.set(taskId, () => {
// Kill process
process.removeAllListeners();
process.stdin.removeAllListeners();
process.stdin.end();
process.stdin.destroy();
process.stdout.removeAllListeners();
process.stdout.unpipe();
process.stdout.destroy();
process.kill();
// Stop reader
reader.removeAllListeners();
reader.close();
reader.destroy();
// Stop transform
transform.stop();
transform.removeAllListeners();
// Stop writer
writer.removeAllListeners();
// Remove cleaner
this._cleaners.delete(taskId);
// Measure spent time
measurer();
this._cleaners.delete(taskId);
this._tasks.delete(taskId);
this._logger.debug(`RG process is finished/killed (task ID: ${taskId})`);
});
}).catch((err: Error) => {
this._logger.warn(`Fail to check target file "${this._streamFile}" due error: ${err.message}`);
return resolve(undefined);
});
}).finally(this._clear.bind(this, taskId));
this._tasks.set(taskId, task);
return task;
}
public drop(): Promise<void> {
return new Promise((resolve) => {
Promise.all(Array.from(this._tasks.values()).map((task: CancelablePromise<void, void>) => {
return new Promise((canceled) => {
this._logger.warn(`Dropping search controller, while search operation is still in progress. Task will be dropped`);
task.after(() => {
canceled(undefined);
}).break();
});
})).finally(() => {
// Drop data
this._tasks.clear();
this._cleaners.clear();
this._readTo = 0;
this._readFrom = 0;
this._inspected = { map: {}, stats: {} };
this._cached = {
hash: '',
cache: undefined,
lines: [],
sorted: false,
};
resolve();
});
});
}
public setReadTo(read: number) {
this._readFrom = this._readTo;
this._readTo = read;
}
public getReadFrom(): number {
return this._readFrom;
}
public getMap(streamLength: number, factor: number, details: boolean, range?: { begin: number, end: number }): IScaledMapData {
const measurePostProcessing = this._logger.measure(`scaling`);
const hash: string = `${streamLength}.${factor}.${details}.${JSON.stringify(range)}.${JSON.stringify(this._inspected.stats)}`;
if (hash === this._cached.hash && this._cached.cache !== undefined) {
measurePostProcessing();
return this._cached.cache;
}
const scaled: IScaledMapData = {
map: {},
stats: this._inspected.stats,
};
if (range === undefined) {
const rate: number = Math.floor(streamLength / factor);
if (rate <= 1) {
for (let i = 1; i <= streamLength; i += 1) {
scaled.map[i] = {};
const ref = scaled.map[i];
if (this._inspected.map[i - 1] !== undefined) {
this._inspected.map[i - 1].forEach((match: string) => {
if (ref[match] === undefined) {
ref[match] = 1;
} else {
ref[match] += 1;
}
});
}
}
} else {
for (let i = 1; i <= factor; i += 1) {
scaled.map[i] = {};
const ref = scaled.map[i];
for (let j = (i - 1) * rate; j <= i * rate; j += 1) {
if (this._inspected.map[j] !== undefined) {
this._inspected.map[j].forEach((match: string) => {
if (ref[match] === undefined) {
ref[match] = 1;
} else {
ref[match] += 1;
}
});
if (!details) {
break;
}
}
}
}
}
} else {
const rangeLength: number = range.end - range.begin;
if (rangeLength < 0 || isNaN(rangeLength) || !isFinite(rangeLength)) {
this._logger.warn(`Invalid range to scale map correctly`);
return scaled;
}
const rate: number = Math.floor(rangeLength / factor);
if (rate <= 1) {
for (let i = 1; i <= rangeLength; i += 1) {
scaled.map[i] = {};
const ref = scaled.map[i];
const j = range.begin + i;
if (this._inspected.map[j - 1] !== undefined) {
this._inspected.map[j - 1].forEach((match: string) => {
if (ref[match] === undefined) {
ref[match] = 1;
} else {
ref[match] += 1;
}
});
}
}
} else {
for (let i = 1; i <= factor; i += 1) {
scaled.map[i] = {};
const ref = scaled.map[i];
for (let j = range.begin + (i - 1) * rate; j <= range.begin + i * rate; j += 1) {
if (j > range.end) {
break;
}
if (this._inspected.map[j] !== undefined) {
this._inspected.map[j].forEach((match: string) => {
if (ref[match] === undefined) {
ref[match] = 1;
} else {
ref[match] += 1;
}
});
if (!details) {
break;
}
}
}
}
}
}
this._cached.hash = hash;
this._cached.cache = scaled;
measurePostProcessing();
return scaled;
}
public getIndexAround(position: number): IIndexAround {
if (!this._cached.sorted) {
this._cached.lines = this._cached.lines.sort((a, b) => {
return a > b ? 1 : -1;
}).filter((item, pos, ary) => {
return !pos || item !== ary[pos - 1];
});
}
const luckyIndex: number = this._cached.lines.indexOf(position);
if (luckyIndex !== -1) {
return { before: luckyIndex, after: luckyIndex };
}
let diff: number = Infinity;
let index: number = -1;
for (let i = this._cached.lines.length - 1; i >= 0; i -= 1) {
if (Math.abs(this._cached.lines[i] - position) < diff) {
index = i;
diff = Math.abs(this._cached.lines[i] - position);
}
}
if (index === -1) {
return { before: -1, after: -1 };
} else if (index === 0) {
if (position < this._cached.lines[index]) {
return { before: -1, after: index };
} else {
return { before: index, after: index + 1 <= this._cached.lines.length - 1 ? index + 1 : -1 };
}
} else if (index === this._cached.lines.length - 1) {
if (position < this._cached.lines[index]) {
return { before: index - 1 >= 0 ? index - 1 : -1, after: index };
} else {
return { before: index, after: -1 };
}
} else {
if (position < this._cached.lines[index]) {
return { before: index - 1 >= 0 ? index - 1 : -1, after: index };
} else {
return { before: index, after: index + 1 <= this._cached.lines.length - 1 ? index + 1 : -1 };
}
}
}
private _store(request: string, matches: number[]) {
const measurePostProcessing = this._logger.measure(`mapping "${request}"`);
this._cached.lines = this._cached.lines.concat(matches);
this._cached.sorted = false;
this._inspected.stats[request] = this._inspected.stats[request] === undefined ? 0 : this._inspected.stats[request];
this._inspected.stats[request] += matches.length;
matches.forEach((line: number) => {
if (this._inspected.map[line] === undefined) {
this._inspected.map[line] = [request];
} else if (this._inspected.map[line].indexOf(request) === -1) {
this._inspected.map[line].push(request);
}
});
measurePostProcessing();
}
private _clear(id: string) {
const cleaner: THandler | undefined = this._cleaners.get(id);
if (cleaner !== undefined) {
cleaner();
}
}
private _isCaseInsensitive(reg: RegExp): boolean {
return reg.flags.includes('i') ? true : false;
}
private _getProcArgs(reg: RegExp, target: string): string[] {
// TODO: here also should be excluded possible matches with line index and tag in line of source file
const args = [
'-N',
'--text', // https://github.com/BurntSushi/ripgrep/issues/306 this issue is about a case, when not printable symble is in a file
'--pcre2',
this._isCaseInsensitive(reg) ? '-i' : '',
'-e',
reg.source,
target,
].filter(x => x !== '');
this._logger.env(`Next regular expresition will be used with ripgrep: ${reg}. Full command: rg ${args.join(' ')}`);
return args;
}
} | the_stack |
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { delay, of, throwError } from 'rxjs';
import { ArtemisTestModule } from '../../test.module';
import { ModelingSubmission } from 'app/entities/modeling-submission.model';
import { ActivatedRoute, ActivatedRouteSnapshot, convertToParamMap, Router } from '@angular/router';
import { ChangeDetectorRef, DebugElement } from '@angular/core';
import { MockComponent, MockModule, MockProvider } from 'ng-mocks';
import { ModelingEditorComponent } from 'app/exercises/modeling/shared/modeling-editor.component';
import { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';
import { StudentParticipation } from 'app/entities/participation/student-participation.model';
import { Result } from 'app/entities/result.model';
import { Feedback, FeedbackCorrectionError, FeedbackCorrectionErrorType, FeedbackType } from 'app/entities/feedback.model';
import { UMLModel } from '@ls1intum/apollon';
import { HttpResponse } from '@angular/common/http';
import { AlertService } from 'app/core/util/alert.service';
import { ExampleModelingSubmissionComponent } from 'app/exercises/modeling/manage/example-modeling/example-modeling-submission.component';
import { ExampleSubmissionService } from 'app/exercises/shared/example-submission/example-submission.service';
import { ExampleSubmission } from 'app/entities/example-submission.model';
import { ArtemisExampleModelingSubmissionRoutingModule } from 'app/exercises/modeling/manage/example-modeling/example-modeling-submission.route';
import { TutorParticipationService } from 'app/exercises/shared/dashboards/tutor/tutor-participation.service';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service';
import { MockTranslateService, TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';
import { TranslateService } from '@ngx-translate/core';
import { MockTranslateValuesDirective } from '../../helpers/mocks/directive/mock-translate-values.directive';
import { FaLayersComponent } from '@fortawesome/angular-fontawesome';
import { CollapsableAssessmentInstructionsComponent } from 'app/assessment/assessment-instructions/collapsable-assessment-instructions/collapsable-assessment-instructions.component';
import { MockRouter } from '../../helpers/mocks/mock-router';
import { ModelingAssessmentComponent } from 'app/exercises/modeling/assess/modeling-assessment.component';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { UnreferencedFeedbackComponent } from 'app/exercises/shared/unreferenced-feedback/unreferenced-feedback.component';
import { ScoreDisplayComponent } from 'app/shared/score-display/score-display.component';
import { FormsModule } from '@angular/forms';
describe('Example Modeling Submission Component', () => {
let comp: ExampleModelingSubmissionComponent;
let fixture: ComponentFixture<ExampleModelingSubmissionComponent>;
let debugElement: DebugElement;
let service: ExampleSubmissionService;
let alertService: AlertService;
let router: Router;
let route: ActivatedRoute;
const participation = new StudentParticipation();
participation.exercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);
participation.id = 1;
const submission = { id: 20, submitted: true, participation } as ModelingSubmission;
const exampleSubmission: ExampleSubmission = {
submission,
};
const exercise = {
id: 22,
diagramType: UMLDiagramType.ClassDiagram,
course: { id: 2 },
} as ModelingExercise;
const mockFeedbackWithReference = {
text: 'FeedbackWithReference',
referenceId: 'relationshipId',
reference: 'reference',
credits: 30,
correctionStatus: 'CORRECT',
} as Feedback;
const mockFeedbackWithoutReference = { text: 'FeedbackWithoutReference', credits: 30, type: FeedbackType.MANUAL_UNREFERENCED } as Feedback;
const mockFeedbackInvalid = { text: 'FeedbackInvalid', referenceId: '4', reference: 'reference', correctionStatus: FeedbackCorrectionErrorType.INCORRECT_SCORE };
const mockFeedbackCorrectionError = { reference: 'reference', type: FeedbackCorrectionErrorType.INCORRECT_SCORE } as FeedbackCorrectionError;
beforeEach(() => {
route = {
snapshot: {
paramMap: convertToParamMap({ exerciseId: '22', exampleSubmissionId: '35' }),
queryParamMap: convertToParamMap({ readOnly: 0, toComplete: 0 }),
},
} as ActivatedRoute;
TestBed.configureTestingModule({
imports: [ArtemisTestModule, MockModule(ArtemisExampleModelingSubmissionRoutingModule), TranslateTestingModule, FormsModule],
declarations: [
ExampleModelingSubmissionComponent,
ModelingAssessmentComponent,
MockComponent(ModelingEditorComponent),
MockTranslateValuesDirective,
MockComponent(FaLayersComponent),
MockComponent(CollapsableAssessmentInstructionsComponent),
MockComponent(UnreferencedFeedbackComponent),
MockComponent(ScoreDisplayComponent),
],
providers: [
MockProvider(ChangeDetectorRef),
MockProvider(ArtemisTranslatePipe),
{ provide: Router, useClass: MockRouter },
{ provide: ActivatedRoute, useValue: route },
{ provide: TranslateService, useClass: MockTranslateService },
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ExampleModelingSubmissionComponent);
comp = fixture.componentInstance;
debugElement = fixture.debugElement;
service = debugElement.injector.get(ExampleSubmissionService);
alertService = debugElement.injector.get(AlertService);
router = debugElement.injector.get(Router);
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should initialize', () => {
// GIVEN
jest.spyOn(service, 'get').mockReturnValue(of(new HttpResponse({ body: exampleSubmission })));
const exerciseService = debugElement.injector.get(ExerciseService);
jest.spyOn(exerciseService, 'find').mockReturnValue(of(new HttpResponse({ body: exercise })));
// WHEN
fixture.detectChanges();
// THEN
expect(comp).toBe(comp);
});
it('should handle a new submission', () => {
route.snapshot = { ...route.snapshot, paramMap: convertToParamMap({ exerciseId: '22', exampleSubmissionId: 'new' }) } as ActivatedRouteSnapshot;
// WHEN
fixture.detectChanges();
// THEN
expect(comp.isNewSubmission).toBeTrue();
expect(comp.exampleSubmission).toEqual(new ExampleSubmission());
});
it('should upsert a new modeling submission', () => {
// GIVEN
const alertSpy = jest.spyOn(alertService, 'success');
const serviceSpy = jest.spyOn(service, 'create').mockImplementation((newExampleSubmission) => of(new HttpResponse({ body: newExampleSubmission })));
comp.isNewSubmission = true;
comp.exercise = exercise;
// WHEN
fixture.detectChanges(); // Needed for @ViewChild to set fields.
comp.upsertExampleModelingSubmission();
// THEN
expect(comp.isNewSubmission).toBeFalse();
expect(serviceSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('artemisApp.modelingEditor.saveSuccessful');
});
it('should upsert an existing modeling submission', fakeAsync(() => {
// GIVEN
jest.spyOn(service, 'get').mockReturnValue(of(new HttpResponse({ body: exampleSubmission })));
const alertSpy = jest.spyOn(alertService, 'success');
const serviceSpy = jest.spyOn(service, 'update').mockImplementation((updatedExampleSubmission) => of(new HttpResponse({ body: updatedExampleSubmission })).pipe(delay(1)));
const modelingAssessmentService = debugElement.injector.get(ModelingAssessmentService);
const modelingAssessmentServiceSpy = jest.spyOn(modelingAssessmentService, 'saveExampleAssessment');
comp.isNewSubmission = false;
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
// WHEN
fixture.detectChanges();
comp.upsertExampleModelingSubmission();
// Ensure calls are not concurrent, new one should start after first one ends.
expect(serviceSpy).toHaveBeenCalledOnce();
tick(1);
// This service request should also start after the previous one ends.
expect(modelingAssessmentServiceSpy).toHaveBeenCalledTimes(0);
tick(1);
// THEN
expect(comp.isNewSubmission).toBeFalse();
expect(serviceSpy).toHaveBeenCalledTimes(2);
expect(modelingAssessmentServiceSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('artemisApp.modelingEditor.saveSuccessful');
}));
it('should check assessment', () => {
// GIVEN
const tutorParticipationService = debugElement.injector.get(TutorParticipationService);
const assessExampleSubmissionSpy = jest.spyOn(tutorParticipationService, 'assessExampleSubmission');
const exerciseId = 5;
comp.exampleSubmission = exampleSubmission;
comp.exerciseId = exerciseId;
// WHEN
comp.checkAssessment();
// THEN
expect(comp.assessmentsAreValid).toBeTrue();
expect(assessExampleSubmissionSpy).toHaveBeenCalledOnce();
expect(assessExampleSubmissionSpy).toHaveBeenCalledWith(exampleSubmission, exerciseId);
});
it('should check invalid assessment', () => {
// GIVEN
const alertSpy = jest.spyOn(alertService, 'error');
comp.exampleSubmission = exampleSubmission;
// WHEN
comp.onReferencedFeedbackChanged([mockFeedbackInvalid]);
comp.checkAssessment();
// THEN
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('artemisApp.modelingAssessment.invalidAssessments');
});
it('should read and understood', () => {
// GIVEN
const tutorParticipationService = debugElement.injector.get(TutorParticipationService);
jest.spyOn(tutorParticipationService, 'assessExampleSubmission').mockReturnValue(of(new HttpResponse({ body: {} })));
const alertSpy = jest.spyOn(alertService, 'success');
const routerSpy = jest.spyOn(router, 'navigate');
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
// WHEN
fixture.detectChanges();
comp.readAndUnderstood();
// THEN
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('artemisApp.exampleSubmission.readSuccessfully');
expect(routerSpy).toHaveBeenCalledOnce();
});
it('should handle referenced feedback change', () => {
// GIVEN
const feedbacks = [mockFeedbackWithReference];
comp.exercise = exercise;
// WHEN
comp.onReferencedFeedbackChanged(feedbacks);
// THEN
expect(comp.feedbackChanged).toBeTrue();
expect(comp.assessmentsAreValid).toBeTrue();
expect(comp.referencedFeedback).toEqual(feedbacks);
});
it('should handle unreferenced feedback change', () => {
// GIVEN
const feedbacks = [mockFeedbackWithoutReference];
comp.exercise = exercise;
// WHEN
comp.onUnReferencedFeedbackChanged(feedbacks);
// THEN
expect(comp.feedbackChanged).toBeTrue();
expect(comp.assessmentsAreValid).toBeTrue();
expect(comp.unreferencedFeedback).toEqual(feedbacks);
});
it('should show submission', () => {
// GIVEN
const feedbacks = [mockFeedbackWithReference];
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
// WHEN
comp.onReferencedFeedbackChanged(feedbacks);
comp.showSubmission();
// THEN
expect(comp.feedbackChanged).toBeFalse();
expect(comp.assessmentMode).toBeFalse();
expect(comp.totalScore).toBe(mockFeedbackWithReference.credits);
});
it('should create error alert if assessment is invalid', () => {
// GIVEN
const alertSpy = jest.spyOn(alertService, 'error');
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.referencedFeedback = [mockFeedbackInvalid];
// WHEN
comp.saveExampleAssessment();
// THEN
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('modelingAssessment.invalidAssessments');
});
it('should update assessment explanation and example assessment', () => {
// GIVEN
comp.exercise = exercise;
comp.exampleSubmission = { ...exampleSubmission, assessmentExplanation: 'Explanation of the assessment' };
comp.referencedFeedback = [mockFeedbackWithReference];
comp.unreferencedFeedback = [mockFeedbackWithoutReference];
const result = { id: 1 } as Result;
const alertSpy = jest.spyOn(alertService, 'success');
jest.spyOn(service, 'update').mockImplementation((updatedExampleSubmission) => of(new HttpResponse({ body: updatedExampleSubmission })));
const modelingAssessmentService = debugElement.injector.get(ModelingAssessmentService);
jest.spyOn(modelingAssessmentService, 'saveExampleAssessment').mockReturnValue(of(result));
// WHEN
comp.saveExampleAssessment();
// THEN
expect(comp.result).toBe(result);
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('modelingAssessmentEditor.messages.saveSuccessful');
});
it('should update assessment explanation but create error message on example assessment update failure', () => {
// GIVEN
comp.exercise = exercise;
comp.exampleSubmission = { ...exampleSubmission, assessmentExplanation: 'Explanation of the assessment' };
comp.referencedFeedback = [mockFeedbackWithReference, mockFeedbackWithoutReference];
const alertSpy = jest.spyOn(alertService, 'error');
jest.spyOn(service, 'update').mockImplementation((updatedExampleSubmission) => of(new HttpResponse({ body: updatedExampleSubmission })));
const modelingAssessmentService = debugElement.injector.get(ModelingAssessmentService);
jest.spyOn(modelingAssessmentService, 'saveExampleAssessment').mockReturnValue(throwError(() => ({ status: 404 })));
// WHEN
comp.saveExampleAssessment();
// THEN
expect(comp.result).toBe(undefined);
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('modelingAssessmentEditor.messages.saveFailed');
});
it('should mark all feedback correct', () => {
// GIVEN
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.referencedFeedback = [mockFeedbackInvalid];
comp.assessmentMode = true;
// WHEN
comp.showAssessment();
fixture.detectChanges();
const resultFeedbacksSetterSpy = jest.spyOn(comp.assessmentEditor, 'resultFeedbacks', 'set');
comp.markAllFeedbackToCorrect();
fixture.detectChanges();
// THEN
expect(comp.referencedFeedback.every((feedback) => feedback.correctionStatus === 'CORRECT')).toBeTrue();
expect(resultFeedbacksSetterSpy).toHaveBeenCalledOnce();
expect(resultFeedbacksSetterSpy).toHaveBeenCalledWith(comp.referencedFeedback);
});
it('should mark all feedback wrong', () => {
// GIVEN
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.referencedFeedback = [mockFeedbackInvalid];
comp.assessmentMode = true;
// WHEN
comp.showAssessment();
fixture.detectChanges();
const resultFeedbacksSetterSpy = jest.spyOn(comp.assessmentEditor, 'resultFeedbacks', 'set');
comp.markWrongFeedback([mockFeedbackCorrectionError]);
fixture.detectChanges();
// THEN
expect(comp.referencedFeedback[0].correctionStatus).toBe(mockFeedbackCorrectionError.type);
expect(resultFeedbacksSetterSpy).toHaveBeenCalledOnce();
expect(resultFeedbacksSetterSpy).toHaveBeenCalledWith(comp.referencedFeedback);
});
it('should create success alert on example assessment update', () => {
// GIVEN
const result = { id: 1 } as Result;
const modelingAssessmentService = debugElement.injector.get(ModelingAssessmentService);
jest.spyOn(modelingAssessmentService, 'saveExampleAssessment').mockReturnValue(of(result));
const alertSpy = jest.spyOn(alertService, 'success');
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.referencedFeedback = [mockFeedbackWithReference];
// WHEN
comp.saveExampleAssessment();
// THEN
comp.result = result;
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('modelingAssessmentEditor.messages.saveSuccessful');
});
it('should create error alert on example assessment update failure', () => {
// GIVEN
const modelingAssessmentService = debugElement.injector.get(ModelingAssessmentService);
jest.spyOn(modelingAssessmentService, 'saveExampleAssessment').mockReturnValue(throwError(() => ({ status: 404 })));
const alertSpy = jest.spyOn(alertService, 'error');
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
comp.referencedFeedback = [mockFeedbackWithReference];
// WHEN
comp.saveExampleAssessment();
// THEN
expect(alertSpy).toHaveBeenCalledOnce();
expect(alertSpy).toHaveBeenCalledWith('modelingAssessmentEditor.messages.saveFailed');
});
it('should handle explanation change', () => {
// GIVEN
const explanation = 'New Explanation';
// WHEN
comp.explanationChanged(explanation);
// THEN
expect(comp.explanationText).toBe(explanation);
});
it('should show assessment', () => {
// GIVEN
const model = {
version: '2.0.0',
type: 'ClassDiagram',
} as UMLModel;
const result = { id: 1 } as Result;
jest.spyOn(service, 'get').mockReturnValue(of(new HttpResponse({ body: exampleSubmission })));
const modelingAssessmentService = debugElement.injector.get(ModelingAssessmentService);
const assessmentSpy = jest.spyOn(modelingAssessmentService, 'getExampleAssessment').mockReturnValue(of(result));
comp.exercise = exercise;
comp.exampleSubmission = exampleSubmission;
// WHEN
fixture.detectChanges();
jest.spyOn(comp.modelingEditor, 'getCurrentModel').mockReturnValue(model);
comp.showAssessment();
// THEN
expect(assessmentSpy).toHaveBeenCalledOnce();
expect(comp.assessmentMode).toBeTrue();
expect(result.feedbacks).toEqual(comp.assessments);
});
}); | the_stack |
import { Editor } from 'mobiledoc-kit'
import Helpers from '../test-helpers'
import { MODIFIERS } from 'mobiledoc-kit/utils/key'
import { supportsSelectionExtend } from '../helpers/browsers'
import { CardData } from 'mobiledoc-kit/models/card-node'
import { AtomData } from 'mobiledoc-kit/models/atom-node'
import ListSection from 'mobiledoc-kit/models/list-section'
import Markerable from 'mobiledoc-kit/models/_markerable'
const test = Helpers.test
const cards: CardData[] = [
{
name: 'my-card',
type: 'dom',
render() {},
edit() {},
},
]
const atoms: AtomData[] = [
{
name: 'my-atom',
type: 'dom',
render() {
return document.createTextNode('my-atom')
},
},
]
let editor: Editor
let editorElement: HTMLElement
let editorOptions = { cards, atoms }
Helpers.module('Acceptance: Cursor Movement', {
beforeEach() {
editorElement = $('#editor')[0]
},
afterEach() {
if (editor) {
editor.destroy()
}
},
})
test('left arrow when at the end of a card moves the cursor across the card', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, cardSection }) => {
return post([cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardHead = editor.post.sections.head!.headPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor)
let { range } = editor
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardHead)
// On wrapper
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!, 2)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardHead)
})
test('left arrow when at the start of a card moves the cursor to the previous section', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, markupSection, cardSection }) => {
return post([markupSection('p'), cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let sectionTail = editor.post.sections.head!.tailPosition()
// Before zwnj
let sectionElement = editor.post.sections.tail!.renderNode.element!
Helpers.dom.moveCursorTo(editor, sectionElement.firstChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor)
let { range } = editor
assert.positionIsEqual(range.head, sectionTail)
assert.positionIsEqual(range.tail, sectionTail)
// After zwnj
Helpers.dom.moveCursorTo(editor, sectionElement.firstChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, sectionTail)
assert.positionIsEqual(range.tail, sectionTail)
})
test('left arrow when at the start of a card moves to previous list item', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, listSection, listItem, marker, cardSection }) => {
return post([listSection('ul', [listItem([marker('abc')])]), cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let itemTail = (editor.post.sections.head! as ListSection).items.head!.tailPosition()
// Before zwnj
let sectionElement = editor.post.sections.tail!.renderNode.element
Helpers.dom.moveCursorTo(editor, sectionElement!.firstChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor)
let { range } = editor
assert.positionIsEqual(range.head, itemTail)
assert.positionIsEqual(range.tail, itemTail)
// After zwnj
sectionElement = editor.post.sections.tail!.renderNode.element!
Helpers.dom.moveCursorTo(editor, sectionElement.firstChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, itemTail)
assert.positionIsEqual(range.tail, itemTail)
})
test('right arrow at start of card moves the cursor across the card', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, cardSection }) => {
return post([cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardTail = editor.post.sections.head!.tailPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.firstChild!, 0)
Helpers.dom.triggerRightArrowKey(editor)
let { range } = editor
assert.positionIsEqual(range.head, cardTail)
assert.positionIsEqual(range.tail, cardTail)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.firstChild!, 1)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, cardTail)
assert.positionIsEqual(range.tail, cardTail)
})
test('right arrow at end of card moves cursor to next section', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, markupSection, cardSection }) => {
return post([cardSection('my-card'), markupSection('p')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let sectionHead = editor.post.sections.tail!.headPosition()
// Before zwnj
let sectionElement = editor.post.sections.head!.renderNode.element!
Helpers.dom.moveCursorTo(editor, sectionElement.lastChild!, 0)
Helpers.dom.triggerRightArrowKey(editor)
let { range } = editor
assert.positionIsEqual(range.head, sectionHead)
assert.positionIsEqual(range.tail, sectionHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, sectionElement.lastChild!, 1)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
// On wrapper
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!, 2)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, sectionHead)
assert.positionIsEqual(range.tail, sectionHead)
})
test('right arrow at end of card moves cursor to next list item', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, listSection, listItem, marker, cardSection }) => {
return post([cardSection('my-card'), listSection('ul', [listItem([marker('abc')])])])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let itemHead = (editor.post.sections.tail as ListSection).items.head!.headPosition()
// Before zwnj
let sectionElement = editor.post.sections.head!.renderNode.element!
Helpers.dom.moveCursorTo(editor, sectionElement.lastChild!, 0)
Helpers.dom.triggerRightArrowKey(editor)
let { range } = editor
assert.positionIsEqual(range.head, itemHead)
assert.positionIsEqual(range.tail, itemHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, sectionElement.lastChild!, 1)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
assert.positionIsEqual(range.head, itemHead)
assert.positionIsEqual(range.tail, itemHead)
})
test('left arrow when at the head of an atom moves the cursor left off the atom', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, markupSection, marker, atom }) => {
return post([markupSection('p', [marker('aa'), atom('my-atom'), marker('cc')])])
})
editor = new Editor({ mobiledoc, atoms })
editor.render(editorElement)
let atomWrapper = (editor.post.sections.head! as Markerable).markers.objectAt(1)!.renderNode!.element!
// Before zwnj, assert moving left
Helpers.dom.moveCursorTo(editor, atomWrapper.lastChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor)
let range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 2, 'Cursor is positioned at offset 2')
// After zwnj, assert moving left
Helpers.dom.moveCursorTo(editor, atomWrapper.lastChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 2, 'Cursor is positioned at offset 2')
// On wrapper, assert moving left
Helpers.dom.moveCursorTo(editor, atomWrapper, 3)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 2, 'Cursor is positioned at offset 2')
// After wrapper, asseat moving left
Helpers.dom.moveCursorTo(editor, atomWrapper.nextSibling!, 0)
Helpers.dom.triggerLeftArrowKey(editor)
range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 2, 'Cursor is positioned at offset 2')
})
test('right arrow when at the head of an atom moves the cursor across the atom', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, markupSection, marker, atom }) => {
return post([markupSection('p', [marker('aa'), atom('my-atom'), marker('cc')])])
})
editor = new Editor({ mobiledoc, atoms })
editor.render(editorElement)
let atomWrapper = (editor.post.sections.head as Markerable).markers.objectAt(1)!.renderNode!.element!
// Before zwnj, assert moving right
Helpers.dom.moveCursorTo(editor, atomWrapper.firstChild!, 0)
Helpers.dom.triggerRightArrowKey(editor)
let range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 3, 'Cursor is positioned at offset 3')
// After zwnj, assert moving right
Helpers.dom.moveCursorTo(editor, atomWrapper.firstChild!, 1)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 3, 'Cursor is positioned at offset 3')
// On wrapper, assert moving right
Helpers.dom.moveCursorTo(editor, atomWrapper, 1)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 3, 'Cursor is positioned at offset 3')
// After wrapper, assert moving right
Helpers.dom.moveCursorTo(editor, atomWrapper.previousSibling!, 2)
Helpers.dom.triggerRightArrowKey(editor)
range = editor.range
assert.ok(range.head.section === editor.post.sections.head, 'Cursor is positioned on first section')
assert.equal(range.head.offset, 3, 'Cursor is positioned at offset 3')
})
test('left/right arrows moves cursor l-to-r and r-to-l across atom', assert => {
editor = Helpers.mobiledoc.renderInto(
editorElement,
({ post, markupSection, atom }) => {
return post([markupSection('p', [atom('my-atom', 'first')])])
},
editorOptions
)
editor.selectRange(editor.post.tailPosition())
Helpers.dom.triggerLeftArrowKey(editor)
assert.positionIsEqual(editor.range.head, editor.post.headPosition())
assert.positionIsEqual(editor.range.tail, editor.post.headPosition())
editor.selectRange(editor.post.headPosition())
Helpers.dom.triggerRightArrowKey(editor)
assert.positionIsEqual(editor.range.head, editor.post.tailPosition())
assert.positionIsEqual(editor.range.tail, editor.post.tailPosition())
})
test('left arrow at start atom moves to end of prev section', assert => {
editor = Helpers.mobiledoc.renderInto(
editorElement,
({ post, markupSection, marker, atom }) => {
return post([markupSection('p', [marker('abc')]), markupSection('p', [atom('my-atom', 'first')])])
},
editorOptions
)
editor.selectRange(editor.post.sections.tail!.headPosition())
Helpers.dom.triggerLeftArrowKey(editor)
assert.positionIsEqual(editor.range.head, editor.post.sections.head!.tailPosition())
})
test('right arrow at end of end atom moves to start of next section', assert => {
editor = Helpers.mobiledoc.renderInto(
editorElement,
({ post, markupSection, marker, atom }) => {
return post([markupSection('p', [atom('my-atom', 'first')]), markupSection('p', [marker('abc')])])
},
editorOptions
)
editor.selectRange(editor.post.sections.head!.tailPosition())
Helpers.dom.triggerRightArrowKey(editor)
assert.positionIsEqual(editor.range.head, editor.post.sections.tail!.headPosition())
})
Helpers.module('Acceptance: Cursor Movement w/ shift', {
beforeEach() {
editorElement = $('#editor')[0]
},
afterEach() {
if (editor) {
editor.destroy()
}
},
})
if (supportsSelectionExtend()) {
// FIXME: Older versions of IE do not support `extends` on selection
// objects, and thus cannot support highlighting left until we implement
// selections without native APIs.
test('left arrow when at the end of a card moves the selection across the card', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, cardSection }) => {
return post([cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardHead = editor.post.sections.head!.headPosition()
let cardTail = editor.post.sections.head!.tailPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
let { range } = editor
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardTail)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardTail)
// On wrapper
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!, 2)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardTail)
})
test('left arrow at start of card moves selection to prev section', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, markupSection, marker, cardSection }) => {
return post([markupSection('p', [marker('abc')]), cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardHead = editor.post.sections.tail!.headPosition()
let sectionTail = editor.post.sections.head!.tailPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.lastChild!.firstChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
let { range } = editor
assert.positionIsEqual(range.head, sectionTail)
assert.positionIsEqual(range.tail, cardHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.lastChild!.firstChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, sectionTail)
assert.positionIsEqual(range.tail, cardHead)
})
test('left arrow at start of card moves selection to prev list item', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, listSection, listItem, marker, cardSection }) => {
return post([listSection('ul', [listItem([marker('abc')])]), cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardHead = editor.post.sections.tail!.headPosition()
let sectionTail = (editor.post.sections.head as ListSection).items.head!.tailPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.lastChild!.firstChild!, 0)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
let { range } = editor
assert.positionIsEqual(range.head, sectionTail)
assert.positionIsEqual(range.tail, cardHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.lastChild!.firstChild!, 1)
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, sectionTail)
assert.positionIsEqual(range.tail, cardHead)
})
test('right arrow at start of card moves the cursor across the card', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, cardSection }) => {
return post([cardSection('my-card')])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardHead = editor.post.sections.head!.headPosition()
let cardTail = editor.post.sections.head!.tailPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.firstChild!, 0)
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
let { range } = editor
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardTail)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.firstChild!, 1)
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, cardHead)
assert.positionIsEqual(range.tail, cardTail)
})
test('right arrow at end of card moves to next section', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, markupSection, marker, cardSection }) => {
return post([cardSection('my-card'), markupSection('p', [marker('abc')])])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardTail = editor.post.sections.head!.tailPosition()
let sectionHead = editor.post.sections.tail!.headPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 0)
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
let { range } = editor
assert.positionIsEqual(range.head, cardTail)
assert.positionIsEqual(range.tail, sectionHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 1)
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, cardTail)
assert.positionIsEqual(range.tail, sectionHead)
})
test('right arrow at end of card moves to next list item', assert => {
let mobiledoc = Helpers.mobiledoc.build(({ post, listSection, listItem, marker, cardSection }) => {
return post([cardSection('my-card'), listSection('ul', [listItem([marker('abc')])])])
})
editor = new Editor({ mobiledoc, cards })
editor.render(editorElement)
let cardTail = editor.post.sections.head!.tailPosition()
let itemHead = (editor.post.sections.tail as ListSection).items.head!.headPosition()
// Before zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 0)
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
let { range } = editor
assert.positionIsEqual(range.head, cardTail)
assert.positionIsEqual(range.tail, itemHead)
// After zwnj
Helpers.dom.moveCursorTo(editor, editorElement.firstChild!.lastChild!, 1)
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
range = editor.range
assert.positionIsEqual(range.head, cardTail)
assert.positionIsEqual(range.tail, itemHead)
})
test('left/right arrows move selection l-to-r and r-to-l across atom', assert => {
editor = Helpers.mobiledoc.renderInto(
editorElement,
({ post, markupSection, atom }) => {
return post([markupSection('p', [atom('my-atom', 'first')])])
},
editorOptions
)
editor.selectRange(editor.post.tailPosition())
Helpers.dom.triggerLeftArrowKey(editor, MODIFIERS.SHIFT)
assert.positionIsEqual(editor.range.head, editor.post.headPosition())
assert.positionIsEqual(editor.range.tail, editor.post.tailPosition())
editor.selectRange(editor.post.headPosition())
Helpers.dom.triggerRightArrowKey(editor, MODIFIERS.SHIFT)
assert.positionIsEqual(editor.range.head, editor.post.headPosition())
assert.positionIsEqual(editor.range.tail, editor.post.tailPosition())
})
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_inventoryjournal_Information {
interface Tabs {
}
interface Body {
/** Work Order this product is allocated to */
msdyn_AllocatedToWorkOrder: DevKit.Controls.Lookup;
/** The Inventory Adjustment Product record related to this journal */
msdyn_InventoryAdjustmentProduct: DevKit.Controls.Lookup;
/** Shows the transaction type of this journal. */
msdyn_JournalType: DevKit.Controls.OptionSet;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Indicates the Journal reversed by this journal record */
msdyn_OriginatingJournal: DevKit.Controls.Lookup;
/** Product this journal relates to */
msdyn_Product: DevKit.Controls.Lookup;
/** The Purchase Order Product record related to this journal */
msdyn_PurchaseOrderProduct: DevKit.Controls.Lookup;
/** Unique identifier for Purchase Order Receipt Product associated with Inventory Journal. */
msdyn_PurchaseOrderReceiptProduct: DevKit.Controls.Lookup;
/** Enter the quantity affected. A positive quantity indicates the receipt of this product into the specified warehouse, whereas a negative indicates a withdrawal. */
msdyn_Quantity: DevKit.Controls.Double;
/** Indicates if this Journal reverses a previous journal record */
msdyn_Reversal: DevKit.Controls.Boolean;
/** The RMA Receipt Product record related to this journal */
msdyn_RMAReceiptProduct: DevKit.Controls.Lookup;
/** Shows the transaction type of this journal. */
msdyn_TransactionType: DevKit.Controls.OptionSet;
/** Unit of product used */
msdyn_Unit: DevKit.Controls.Lookup;
/** Warehouse affected by this transaction */
msdyn_Warehouse: DevKit.Controls.Lookup;
/** The Work Order Product record related to this journal */
msdyn_WorkOrderProduct: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Inventory Journal */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
navProcessSessions: DevKit.Controls.NavigationItem
}
}
class Formmsdyn_inventoryjournal_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_inventoryjournal_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_inventoryjournal_Information */
Body: DevKit.Formmsdyn_inventoryjournal_Information.Body;
/** The Footer section of form msdyn_inventoryjournal_Information */
Footer: DevKit.Formmsdyn_inventoryjournal_Information.Footer;
/** The Navigation of form msdyn_inventoryjournal_Information */
Navigation: DevKit.Formmsdyn_inventoryjournal_Information.Navigation;
}
class msdyn_inventoryjournalApi {
/**
* DynamicsCrm.DevKit msdyn_inventoryjournalApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Work Order this product is allocated to */
msdyn_AllocatedToWorkOrder: DevKit.WebApi.LookupValue;
/** For internal use only. */
msdyn_InternalFlags: DevKit.WebApi.StringValue;
/** The Inventory Adjustment Product record related to this journal */
msdyn_InventoryAdjustmentProduct: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_inventoryjournalId: DevKit.WebApi.GuidValue;
/** Shows the transaction type of this journal. */
msdyn_JournalType: DevKit.WebApi.OptionSetValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Indicates the Journal reversed by this journal record */
msdyn_OriginatingJournal: DevKit.WebApi.LookupValue;
/** Product this journal relates to */
msdyn_Product: DevKit.WebApi.LookupValue;
/** The Purchase Order Product record related to this journal */
msdyn_PurchaseOrderProduct: DevKit.WebApi.LookupValue;
/** Unique identifier for Purchase Order Receipt Product associated with Inventory Journal. */
msdyn_PurchaseOrderReceiptProduct: DevKit.WebApi.LookupValue;
/** Enter the quantity affected. A positive quantity indicates the receipt of this product into the specified warehouse, whereas a negative indicates a withdrawal. */
msdyn_Quantity: DevKit.WebApi.DoubleValue;
/** Indicates if this Journal reverses a previous journal record */
msdyn_Reversal: DevKit.WebApi.BooleanValue;
/** The RMA Receipt Product record related to this journal */
msdyn_RMAReceiptProduct: DevKit.WebApi.LookupValue;
/** Shows the transaction type of this journal. */
msdyn_TransactionType: DevKit.WebApi.OptionSetValue;
/** Unit of product used */
msdyn_Unit: DevKit.WebApi.LookupValue;
/** Warehouse affected by this transaction */
msdyn_Warehouse: DevKit.WebApi.LookupValue;
/** The Work Order Product record related to this journal */
msdyn_WorkOrderProduct: DevKit.WebApi.LookupValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Inventory Journal */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Inventory Journal */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_inventoryjournal {
enum msdyn_JournalType {
/** 690970002 */
Allocated,
/** 690970000 */
On_Hand,
/** 690970001 */
On_Order
}
enum msdyn_TransactionType {
/** 690970003 */
Inventory_Adjustment,
/** 690970004 */
Inventory_Transfer,
/** 690970006 */
Manual,
/** 690970000 */
Purchase_Order_Product,
/** 690970001 */
Purchase_Order_Receipt,
/** 690970005 */
RMA_Product,
/** 690970002 */
WO_Product
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {expect} from 'chai';
import {RunOutputOptions, RunOutputProcessor} from '../../../src/lib/util/RunOutputProcessor';
import {OUTPUT_FORMAT} from '../../../src/lib/RuleManager';
import {EngineExecutionSummary, RecombinedRuleResults} from '../../../src/types';
import {Messages} from '@salesforce/core';
import {UX} from '@salesforce/command';
import {AnyJson} from '@salesforce/ts-types';
import Sinon = require('sinon');
import fs = require('fs');
Messages.importMessagesDirectory(__dirname);
const runMessages = Messages.loadMessages('@salesforce/sfdx-scanner', 'run');
const FAKE_SUMMARY_MAP: Map<string, EngineExecutionSummary> = new Map();
FAKE_SUMMARY_MAP.set('pmd', {fileCount: 1, violationCount: 1});
FAKE_SUMMARY_MAP.set('eslint-typescript', {fileCount: 1, violationCount: 2});
const FAKE_TABLE_OUTPUT = {
"columns": [
"Location",
"Description",
"Category",
"URL"
],
"rows": [
{
"Location": "src/file-with-problems.ts:3",
"Rule": "no-unused-vars",
"Description": " 'UNUSED' is assigned a value but never used.",
"URL": "https://eslint.org/docs/rules/no-unused-vars",
"Category": "Variables",
"Severity": 2,
"Line": 3,
"Column": 7,
"Engine": "eslint-typescript"
},
{
"Location": "src/file-with-problems.ts:3",
"Rule": "@typescript-eslint/no-unused-vars",
"Description": " 'UNUSED' is assigned a value but never used.",
"URL": "https://github.com/typescript-eslint/typescript-eslint/blob/v2.33.0/packages/eslint-plugin/docs/rules/no-unused-vars.md",
"Category": "Variables",
"Severity": 2,
"Line": 3,
"Column": 7,
"Engine": "eslint-typescript"
},
{
"Location": "src/some-apex-file.cls:15",
"Rule": "EmptyIfStmt",
"Description": " Avoid empty 'if' statements",
"URL": "Who cares",
"Category": "Error Prone",
"Severity": 1,
"Line": 15,
"Column": 3,
"Engine": "pmd"
}
]
};
const FAKE_CSV_OUTPUT = `"Problem","File","Severity","Line","Column","Rule","Description","URL","Category","Engine"
"1","/Users/jfeingold/ts-sample-project/src/file-with-problems.ts","2","3","7","no-unused-vars","'UNUSED' is assigned a value but never used.","https://eslint.org/docs/rules/no-unused-vars","Variables","eslint-typescript"
"2","/Users/jfeingold/ts-sample-project/src/file-with-problems.ts","2","3","7","@typescript-eslint/no-unused-vars","'UNUSED' is assigned a value but never used.","https://github.com/typescript-eslint/typescript-eslint/blob/v2.33.0/packages/eslint-plugin/docs/rules/no-unused-vars.md","Variables","eslint-typescript"
"3","/Users/jfeingold/ts-sample-project/src/some-apex-file.cls","1","15","3","EmptyIfStmt","Avoid empty 'if' statements","Who cares","Error Prone","pmd"`;
const FAKE_JSON_OUTPUT = `[{
"engine": "eslint-typescript",
"fileName": "/Users/jfeingold/ts-sample-project/src/file-with-problems.ts",
"violations": [{
"line": 3,
"column": 7,
"severity": 2,
"message": "'UNUSED' is assigned a value but never used.",
"ruleName": "no-unused-vars",
"category": "Variables",
"url": "https://eslint.org/docs/rules/no-unused-vars"
}, {
"line": 3,
"column": 7,
"severity": 2,
"message": "'UNUSED' is assigned a value but never used.",
"ruleName": "@typescript-eslint/no-unused-vars",
"category": "Variables",
"url": "https://github.com/typescript-eslint/typescript-eslint/blob/v2.33.0/packages/eslint-plugin/docs/rules/no-unused-vars.md"
}]
}, {
"engine": "pmd",
"fileName": "/Users/jfeingold/ts-sample-project/src/some-apex-file.cls",
"violations": [{
"line": 15,
"column": 3,
"severity": 1,
"message": "Avoid empty 'if' statements",
"ruleName": "EmptyIfStmt",
"category": "Error Prone",
"url": "Who cares"
}]
}]`;
describe('RunOutputProcessor', () => {
let fakeFiles: {path; data}[] = [];
let testUx: UX = null;
let logSpy = null;
let tableSpy = null;
beforeEach(async () => {
testUx = await UX.create();
Sinon.createSandbox();
// Create spies for the various UX methods so we can see what's being passed to them.
logSpy = Sinon.spy(testUx, 'log');
tableSpy = Sinon.spy(testUx, 'table');
// Stub out fs.writeFileSync() so we can check what it's trying to do without letting it actually write anything.
fakeFiles = [];
Sinon.stub(fs, 'writeFileSync').callsFake((path, data) => {
fakeFiles.push({path, data});
});
});
afterEach(() => {
Sinon.restore();
});
describe('#processRunOutput()', () => {
describe('Writing to console', () => {
it('Empty results yield expected message', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.TABLE,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
const summaryMap: Map<string, EngineExecutionSummary> = new Map();
summaryMap.set('pmd', {fileCount: 0, violationCount: 0});
summaryMap.set('eslint', {fileCount: 0, violationCount: 0});
const fakeRes: RecombinedRuleResults = {minSev: 0, summaryMap, results: ''};
// THIS IS THE PART BEING TESTED.
const output: AnyJson = rop.processRunOutput(fakeRes);
// We expect that the message logged to the console and the message returned should both be the default
const expectedMsg = runMessages.getMessage('output.noViolationsDetected', ['pmd, eslint']);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.calledWith(logSpy, expectedMsg);
expect(output).to.equal(expectedMsg, 'Should have returned expected message');
});
describe('Test Case: Table', () => {
const fakeTableResults: RecombinedRuleResults = {minSev: 1, results: FAKE_TABLE_OUTPUT, summaryMap: FAKE_SUMMARY_MAP};
it('Table-type output should be followed by summary', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.TABLE,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
const output: AnyJson = rop.processRunOutput(fakeTableResults);
const expectedTableSummary = `${runMessages.getMessage('output.engineSummaryTemplate', ['pmd', 1, 1])}
${runMessages.getMessage('output.engineSummaryTemplate', ['eslint-typescript', 2, 1])}
${runMessages.getMessage('output.writtenToConsole')}`;
Sinon.assert.callCount(tableSpy, 1);
Sinon.assert.calledWith(tableSpy, FAKE_TABLE_OUTPUT.rows, FAKE_TABLE_OUTPUT.columns);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, expectedTableSummary);
expect(output).to.deep.equal(FAKE_TABLE_OUTPUT.rows, 'Should have returned the rows');
});
it('Throws exception on request when violations are found', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.TABLE,
violationsCauseException: true
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
try {
const output: AnyJson = rop.processRunOutput(fakeTableResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 1);
Sinon.assert.calledWith(tableSpy, FAKE_TABLE_OUTPUT.rows, FAKE_TABLE_OUTPUT.columns);
Sinon.assert.callCount(logSpy, 0);
const expectedTableSummary = `${runMessages.getMessage('output.engineSummaryTemplate', ['pmd', 1, 1])}
${runMessages.getMessage('output.engineSummaryTemplate', ['eslint-typescript', 2, 1])}
${runMessages.getMessage('output.sevDetectionSummary', [1])}
${runMessages.getMessage('output.writtenToConsole')}`;
expect(e.message).to.equal(expectedTableSummary, 'Exception message incorrectly formed');
}
});
it('Throws severity-based exception on request', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.TABLE,
severityForError: 1,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
try {
const output: AnyJson = rop.processRunOutput(fakeTableResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 1);
Sinon.assert.calledWith(tableSpy, FAKE_TABLE_OUTPUT.rows, FAKE_TABLE_OUTPUT.columns);
Sinon.assert.callCount(logSpy, 0);
const expectedTableSummary = `${runMessages.getMessage('output.engineSummaryTemplate', ['pmd', 1, 1])}
${runMessages.getMessage('output.engineSummaryTemplate', ['eslint-typescript', 2, 1])}
${runMessages.getMessage('output.sevThresholdSummary', [1])}
${runMessages.getMessage('output.writtenToConsole')}`;
expect(e.message).to.equal(expectedTableSummary, 'Exception message incorrectly formed');
}
});
});
describe('Test Case: CSV', () => {
const fakeCsvResults: RecombinedRuleResults = {minSev: 1, summaryMap: FAKE_SUMMARY_MAP, results: FAKE_CSV_OUTPUT};
// NOTE: This next test is based on the implementation of run-summary messages in W-8388246, which was known
// to be incomplete. When we flesh out that implementation with summaries for other formats, this test might
// need to change.
it('CSV-type output should NOT be followed by summary', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
const output: AnyJson = rop.processRunOutput(fakeCsvResults);
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, FAKE_CSV_OUTPUT);
expect(output).to.equal(FAKE_CSV_OUTPUT, 'CSV should be returned as a string');
});
it('Throws severity-based exception on request', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
severityForError: 2,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
try {
const output: AnyJson = rop.processRunOutput(fakeCsvResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, FAKE_CSV_OUTPUT);
expect(e.message).to.equal(runMessages.getMessage('output.sevThresholdSummary', [2]), 'Exception message incorrectly formed');
}
});
it('Throws exception on request when violations are found', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
violationsCauseException: true
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
try {
const output: AnyJson = rop.processRunOutput(fakeCsvResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, FAKE_CSV_OUTPUT);
expect(e.message).to.equal(runMessages.getMessage('output.sevDetectionSummary', [1]), 'Exception message incorrectly formed');
}
});
});
describe('Test Case: JSON', () => {
const fakeJsonResults: RecombinedRuleResults = {minSev: 1, summaryMap: FAKE_SUMMARY_MAP, results: FAKE_JSON_OUTPUT};
// NOTE: This next test is based on the implementation of run-summary messages in W-8388246, which was known
// to be incomplete. When we flesh out that implementation with summaries for other formats, this test might
// need to change.
it('JSON-type output should NOT be followed by summary', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.JSON,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED
const output: AnyJson = rop.processRunOutput(fakeJsonResults);
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, FAKE_JSON_OUTPUT);
expect(output).to.deep.equal(JSON.parse(FAKE_JSON_OUTPUT), 'JSON should be returned as a parsed object');
});
it('Throws exception on request when violations are found', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.JSON,
violationsCauseException: true
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED
try {
const output: AnyJson = rop.processRunOutput(fakeJsonResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, FAKE_JSON_OUTPUT);
expect(e.message).to.equal(runMessages.getMessage('output.sevDetectionSummary', [1]), 'Exception message incorrectly formed');
}
});
it('Throws severity-based exception on request', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.JSON,
severityForError: 1,
violationsCauseException: false
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED
try {
const output: AnyJson = rop.processRunOutput(fakeJsonResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, FAKE_JSON_OUTPUT);
expect(e.message).to.equal(runMessages.getMessage('output.sevThresholdSummary', [1]), 'Exception message incorrectly formed');
}
});
});
});
describe('Writing to file', () => {
const fakeFilePath = './some/path/to/a/file.csv';
it('Empty results yield expected message', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
violationsCauseException: false,
outfile: fakeFilePath
};
const rop = new RunOutputProcessor(opts, testUx);
const summaryMap: Map<string, EngineExecutionSummary> = new Map();
summaryMap.set('pmd', {fileCount: 0, violationCount: 0});
summaryMap.set('eslint', {fileCount: 0, violationCount: 0});
const fakeRes: RecombinedRuleResults = {minSev: 0, summaryMap, results: ''};
// THIS IS THE PART BEING TESTED.
const output: AnyJson = rop.processRunOutput(fakeRes);
// We expect that the message logged to the console and the message returned should both be the default
const expectedMsg = runMessages.getMessage('output.noViolationsDetected', ['pmd, eslint']);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.calledWith(logSpy, expectedMsg);
expect(fakeFiles.length).to.equal(0, 'No files should be created');
expect(output).to.equal(expectedMsg, 'Should have returned expected message');
});
describe('Test Case: CSV', () => {
const fakeCsvResults: RecombinedRuleResults = {minSev: 1, summaryMap: FAKE_SUMMARY_MAP, results: FAKE_CSV_OUTPUT};
it('Results are properly written to file', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
violationsCauseException: false,
outfile: fakeFilePath
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
const output: AnyJson = rop.processRunOutput(fakeCsvResults);
const expectedCsvSummary = `${runMessages.getMessage('output.engineSummaryTemplate', ['pmd', 1, 1])}
${runMessages.getMessage('output.engineSummaryTemplate', ['eslint-typescript', 2, 1])}
${runMessages.getMessage('output.writtenToOutFile', [fakeFilePath])}`;
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 1);
Sinon.assert.calledWith(logSpy, expectedCsvSummary);
expect(output).to.equal(expectedCsvSummary, 'Summary should be returned as final message');
expect(fakeFiles.length).to.equal(1, 'Should have tried to create one file');
expect(fakeFiles[0]).to.deep.equal({path: fakeFilePath, data: FAKE_CSV_OUTPUT}, 'File-write expectations defied');
});
it('Throws exception on request when violations are found', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
violationsCauseException: true,
outfile: fakeFilePath
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
try {
const output: AnyJson = rop.processRunOutput(fakeCsvResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 0);
expect(fakeFiles.length).to.equal(1, 'Should have tried to create one file');
expect(fakeFiles[0]).to.deep.equal({path: fakeFilePath, data: FAKE_CSV_OUTPUT}, 'File-write expectations defied');
const expectedCsvSummary = `${runMessages.getMessage('output.engineSummaryTemplate', ['pmd', 1, 1])}
${runMessages.getMessage('output.engineSummaryTemplate', ['eslint-typescript', 2, 1])}
${runMessages.getMessage('output.sevDetectionSummary', [1])}
${runMessages.getMessage('output.writtenToOutFile', [fakeFilePath])}`;
expect(e.message).to.equal(expectedCsvSummary, 'Summary was wrong');
}
});
it('Throws severity-based exception on request', async () => {
const opts: RunOutputOptions = {
format: OUTPUT_FORMAT.CSV,
severityForError: 1,
violationsCauseException: false,
outfile: fakeFilePath
};
const rop = new RunOutputProcessor(opts, testUx);
// THIS IS THE PART BEING TESTED.
try {
const output: AnyJson = rop.processRunOutput(fakeCsvResults);
expect(true).to.equal(false, `Unexpectedly returned ${output} instead of throwing error`);
} catch (e) {
Sinon.assert.callCount(tableSpy, 0);
Sinon.assert.callCount(logSpy, 0);
expect(fakeFiles.length).to.equal(1, 'Should have tried to create one file');
expect(fakeFiles[0]).to.deep.equal({path: fakeFilePath, data: FAKE_CSV_OUTPUT}, 'File-write expectations defied');
const expectedCsvSummary = `${runMessages.getMessage('output.engineSummaryTemplate', ['pmd', 1, 1])}
${runMessages.getMessage('output.engineSummaryTemplate', ['eslint-typescript', 2, 1])}
${runMessages.getMessage('output.sevThresholdSummary', [1])}
${runMessages.getMessage('output.writtenToOutFile', [fakeFilePath])}`;
expect(e.message).to.equal(expectedCsvSummary, 'Summary was wrong');
}
});
});
});
});
}); | the_stack |
import {
Cms,
FilterResult,
ScoreValue,
BasicField,
ScoreField,
SpecialField,
Category,
FilterFieldSet,
BooleanCmsProperty,
CategoryField,
Field,
PanelSettings,
FilterPreset,
} from "./Cms";
import deepcopy from "ts-deepcopy";
import CmsService from "./CmsService";
const FilterService = {
/**
* Filters the cms acoording to @param formProperties.
* Returns all cms, satisfactory boolean is set accordingly.
*/
filterCms: (
filterFields: FilterFieldSet,
cms: { [x: string]: Cms }
): FilterResult[] => {
let filterResults: FilterResult[] = [];
const specialFieldKeys = Object.keys(filterFields.special);
const cmsKeys = Object.keys(cms);
for (let cmsKey of cmsKeys) {
const currentCms: any = cms[cmsKey];
let has: FilterFieldSet = { basic: {}, special: {} };
let hasNot: FilterFieldSet = { basic: {}, special: {} };
let requiredPropertyCount = 0;
let hasRequiredPropertyCount = 0;
let niceToHavePropertyCount = 0;
let hasNiceToHavePropertyCount = 0;
let satisfactory: boolean = true;
for (const fieldKey of specialFieldKeys) {
const currentField = filterFields.special[fieldKey];
const currentCmsProperty = currentCms[fieldKey];
const requiredValues: any[] = currentField.values;
if (
currentCms[fieldKey] !== undefined &&
FilterService.getArrayIntersection(requiredValues, currentCmsProperty)
.length > 0
) {
has.special[fieldKey] = currentField;
} else {
hasNot.special[fieldKey] = currentField;
satisfactory = false;
}
}
const basicFieldKeys = Object.keys(filterFields.basic);
for (const fieldKey of basicFieldKeys) {
const currentField = filterFields.basic[fieldKey];
const currentCmsProperty = currentCms.properties[fieldKey];
if (CmsService.isScoreField(currentField)) {
if (isOfInterest(currentField)) {
const fieldIsRequired = isRequired(currentField);
fieldIsRequired
? requiredPropertyCount++
: niceToHavePropertyCount++;
if (cmsHasProperty(currentCmsProperty as BooleanCmsProperty)) {
has.basic[fieldKey] = currentField;
fieldIsRequired
? hasRequiredPropertyCount++
: hasNiceToHavePropertyCount++;
} else {
hasNot.basic[fieldKey] = currentField;
if (fieldIsRequired) satisfactory = false;
}
}
} else {
const hasCategoryField = {
name: currentField.name,
description: currentField.description,
} as CategoryField;
const hasNotCategoryField = Object.assign({}, hasCategoryField);
const subFieldKeys = CmsService.getKeysOfSubFields(currentField);
for (const subFieldKey of subFieldKeys) {
const currentSubField = currentField[subFieldKey] as ScoreField;
const currentCmsSubProperty = currentCmsProperty[
subFieldKey
] as BooleanCmsProperty;
if (isOfInterest(currentSubField)) {
const fieldIsRequired = isRequired(currentSubField);
fieldIsRequired
? requiredPropertyCount++
: niceToHavePropertyCount++;
if (cmsHasProperty(currentCmsSubProperty)) {
hasCategoryField[subFieldKey] = currentSubField;
fieldIsRequired
? hasRequiredPropertyCount++
: hasNiceToHavePropertyCount++;
} else {
hasNotCategoryField[subFieldKey] = currentSubField;
if (fieldIsRequired) satisfactory = false;
}
}
if (!categoryFieldIsEmpty(hasCategoryField)) {
has.basic[fieldKey] = hasCategoryField;
}
if (!categoryFieldIsEmpty(hasNotCategoryField)) {
hasNot.basic[fieldKey] = hasNotCategoryField;
}
}
}
}
filterResults.push({
cmsKey,
has,
hasNot,
hasRequiredShare:
requiredPropertyCount > 0
? hasRequiredPropertyCount / requiredPropertyCount
: -1,
hasNiceToHaveShare:
niceToHavePropertyCount > 0
? hasNiceToHavePropertyCount / niceToHavePropertyCount
: -1,
satisfactory,
});
}
filterResults = sortFilterResults(filterResults);
return filterResults;
},
getUnfilteredCms: (cms: { [x: string]: Cms }): FilterResult[] => {
const cmsKeys = Object.keys(cms);
return cmsKeys.map((cmsKey) => {
return {
cmsKey: cmsKey,
has: { basic: {}, special: {} },
hasRequiredShare: -1,
hasNiceToHaveShare: -1,
hasNot: { basic: {}, special: {} },
satisfactory: true,
};
});
},
getFilteredFilterFields: (
panelSettings: PanelSettings,
filterFields: { current: FilterFieldSet; untouched: FilterFieldSet }
): FilterFieldSet => {
if (
!panelSettings.showModifiedOnly &&
panelSettings.fieldFilterString.length === 0
) {
return filterFields.current;
}
const untouchedFields: FilterFieldSet = filterFields.untouched;
const workFields = deepcopy<FilterFieldSet>(filterFields.current);
if (panelSettings.showModifiedOnly) {
const specialFieldKeys = Object.keys(workFields.special);
specialFieldKeys.forEach((key: string) => {
const currentField = workFields.special[key];
const referenceField = untouchedFields.special[key];
if (arraysAreEqual(currentField.values, referenceField.values)) {
delete workFields.special[key];
}
});
const basicFieldKeys = Object.keys(workFields.basic);
for (const fieldKey of basicFieldKeys) {
const currentField = workFields.basic[fieldKey];
if (CmsService.isScoreField(currentField)) {
const untouchedField = untouchedFields.basic[fieldKey] as ScoreField;
if (currentField.value === untouchedField.value) {
delete workFields.basic[fieldKey];
}
} else {
const subFieldKeys = CmsService.getKeysOfSubFields(currentField);
for (const subFieldKey of subFieldKeys) {
const currentSubField = (workFields.basic[
fieldKey
] as CategoryField)[subFieldKey];
const untouchedSubField = (untouchedFields.basic[
fieldKey
] as CategoryField)[subFieldKey];
if (currentSubField.value === untouchedSubField.value) {
delete (workFields.basic[fieldKey] as CategoryField)[subFieldKey];
}
}
if (categoryFieldIsEmpty(workFields.basic[fieldKey])) {
delete workFields.basic[fieldKey];
}
}
}
}
const fieldFilterString = panelSettings.fieldFilterString;
if (fieldFilterString.length > 0) {
const specialFieldKeys = Object.keys(workFields.special);
specialFieldKeys.forEach((fieldKey: string) => {
const currentField = workFields.special[fieldKey];
if (!fieldNameContainsString(currentField, fieldFilterString)) {
delete workFields.special[fieldKey];
}
});
const basicFieldKeys = Object.keys(workFields.basic);
for (const fieldKey of basicFieldKeys) {
const currentField = workFields.basic[fieldKey];
if (CmsService.isScoreField(currentField)) {
if (!fieldNameContainsString(currentField, fieldFilterString)) {
delete workFields.basic[fieldKey];
}
} else {
if (!fieldNameContainsString(currentField, fieldFilterString)) {
// If category itself does not match the search string, filter the subProperties in the category
const subFieldKeys = CmsService.getKeysOfSubFields(currentField);
for (const subFieldKey of subFieldKeys) {
const currentSubField = (currentField as CategoryField)[
subFieldKey
];
if (
!fieldNameContainsString(currentSubField, fieldFilterString)
) {
delete (workFields.basic[fieldKey] as CategoryField)[
subFieldKey
];
}
}
if (categoryFieldIsEmpty(workFields.basic[fieldKey])) {
delete workFields.basic[fieldKey];
}
}
}
}
}
return workFields;
},
/**
* Initializes all non-special FieldProperties to FilterProperties by setting values accordingly
* @returns an object containing all properties with values set to Score.DONT_CARE
*/
initializeBasicFields: (basicFields: {
[x: string]: BasicField;
}): { [x: string]: BasicField } => {
const fields: { [x: string]: BasicField } = deepcopy<{
[x: string]: BasicField;
}>(basicFields);
const fieldKeys: string[] = Object.keys(fields);
for (const key of fieldKeys) {
const currentField = fields[key];
if (CmsService.isScoreField(currentField)) {
currentField.value = ScoreValue.DONT_CARE;
} else {
const subPropertyKeys = CmsService.getKeysOfSubFields(currentField);
for (const subKey of subPropertyKeys) {
const currentSubField = currentField[subKey] as ScoreField;
currentSubField.value = ScoreValue.DONT_CARE;
}
}
}
return fields;
},
initializeSpecialFields: (): { [x: string]: SpecialField } => {
const specialFields: { [x: string]: SpecialField } = {};
specialFields.category = {
name: "Allowed Categories",
description: "Which featureset is offered by the cms?",
values: Object.values(Category),
possibleValues: Object.values(Category),
};
return specialFields;
},
getArrayIntersection: (a: string[], b: string[]): string[] => {
return a.filter((value) => b.includes(value));
},
getPresetFilterFields: (
filterFields: FilterFieldSet,
preset: FilterPreset
): FilterFieldSet => {
const newFilter = deepcopy<FilterFieldSet>(filterFields);
const basic = newFilter.basic;
switch (preset) {
case FilterPreset.OPEN_SOURCE:
basic["openSource"].value = ScoreValue.REQUIRED;
basic["commercialSupportAvailable"].value = ScoreValue.NICE_TO_HAVE;
break;
case FilterPreset.CLOUD_SERVICE:
basic["cloudService"].value = ScoreValue.REQUIRED;
basic["cloudServiceHostedInEurope"].value = ScoreValue.NICE_TO_HAVE;
break;
case FilterPreset.ENTERPRISE:
newFilter.special["category"].values = [Category.Enterprise];
basic["commercialSupportAvailable"].value = ScoreValue.REQUIRED;
basic["openSource"].value = ScoreValue.NICE_TO_HAVE;
break;
case FilterPreset.DOCKER:
basic["onPremisesInstallation"].value = ScoreValue.REQUIRED;
basic["dockerSupport"].value = ScoreValue.REQUIRED;
break;
case FilterPreset.GRAPHQL:
const graphQl: CategoryField = basic["graphQl"];
graphQl["api"].value = ScoreValue.REQUIRED;
graphQl["mutations"].value = ScoreValue.NICE_TO_HAVE;
graphQl["subscriptions"].value = ScoreValue.NICE_TO_HAVE;
break;
default:
console.error(`No preset defined for ${preset}`);
}
return newFilter;
},
};
function sortFilterResults(filterResults: FilterResult[]): FilterResult[] {
filterResults.sort(function (x: FilterResult, y: FilterResult) {
if (x.satisfactory !== y.satisfactory) {
if (x.satisfactory) {
return -1;
} else {
return 1;
}
}
if (x.hasRequiredShare < y.hasRequiredShare) return 1;
if (x.hasRequiredShare > y.hasRequiredShare) return -1;
if (x.satisfactory && y.satisfactory) {
if (x.hasNiceToHaveShare < y.hasNiceToHaveShare) return 1;
if (x.hasNiceToHaveShare > y.hasNiceToHaveShare) return -1;
}
if (x.cmsKey > y.cmsKey) return 1;
if (x.cmsKey < y.cmsKey) return -1;
return 0;
});
return filterResults;
}
function isOfInterest(scoreField: ScoreField): boolean {
return (
scoreField.value === ScoreValue.REQUIRED ||
scoreField.value === ScoreValue.NICE_TO_HAVE
);
}
function isRequired(scoreField: ScoreField): boolean {
return scoreField.value === ScoreValue.REQUIRED;
}
function fieldNameContainsString(field: Field, str: string) {
return field.name.toUpperCase().includes(str.toUpperCase());
}
/**
* Checks if a CMS has a certain property
*/
function cmsHasProperty(cmsProperty: BooleanCmsProperty): boolean {
if (cmsProperty && cmsProperty.value) {
if (typeof cmsProperty.value === "boolean") {
return cmsProperty.value;
}
return true;
} else {
return false;
}
}
function categoryFieldIsEmpty(categoryProperty: CategoryField): boolean {
return CmsService.getKeysOfSubFields(categoryProperty).length === 0;
}
function arraysAreEqual(a: any[], b: any[]): boolean {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
export default FilterService; | the_stack |
import {Injectable} from '@angular/core';
import {
BaseType as D3BaseType,
ContainerElement as D3ContainerElement,
event as d3Event,
select as d3Select,
Selection as D3Selection
} from 'd3-selection';
import {ChartCommons} from '../../../../enums/chart-commons.enum';
import {ScaleLinear as D3ScaleLinear, ScaleTime as D3ScaleTime} from 'd3-scale';
import {TimeSeries} from '../../models/time-series.model';
import {getColorScheme} from '../../../../enums/color-scheme.enum';
import {SummaryLabel} from '../../models/summary-label.model';
import {take} from 'rxjs/operators';
import {EventResultSeriesDTO} from '../../models/event-result-series.model';
import {EventResultDataDTO} from '../../models/event-result-data.model';
import {TranslateService} from '@ngx-translate/core';
import {LineChartDrawService} from './line-chart-draw.service';
import {LineChartEventService} from './line-chart-event.service';
@Injectable({
providedIn: 'root'
})
export class LineChartLegendService {
private _legendGroupColumnWidth: number;
private _legendGroupColumns: number;
private _focusedLegendEntry: string;
private _legendDataMap: { [key: string]: { [key: string]: (boolean | string) } } = {};
constructor(private translationService: TranslateService,
private lineChartDrawService: LineChartDrawService,
private lineChartEventService: LineChartEventService) {
}
get legendDataMap(): { [p: string]: { [p: string]: boolean | string } } {
return this._legendDataMap;
}
/**
* Set the data for the legend after the incoming data is received
*/
setLegendData(incomingData: EventResultDataDTO): void {
if (incomingData.series.length === 0) {
return;
}
const labelDataMap = {};
const measurandInIdentifier: boolean = incomingData.summaryLabels.length === 0 ||
(incomingData.summaryLabels.length > 0 && incomingData.summaryLabels[0].key !== 'measurand');
const measurandGroups = Object.keys(incomingData.series);
measurandGroups.forEach((series: string) => {
incomingData.series[series].forEach((data: EventResultSeriesDTO) => {
if (measurandInIdentifier) {
data.identifier = this.translateMeasurand(data);
}
const key = this.generateKey(data);
labelDataMap[key] = {
text: data.identifier,
key: key,
show: true
};
});
});
this._legendDataMap = labelDataMap;
}
calculateLegendDimensions(width: number): number {
let maximumLabelWidth = 1;
const labels = Object.keys(this._legendDataMap);
d3Select('g#time-series-chart-legend')
.append('g')
.attr('id', 'renderToCalculateMaxWidth')
.selectAll('.renderToCalculateMaxWidth')
.data(labels)
.enter()
.append('text')
.attr('class', 'legend-text')
.text(datum => this._legendDataMap[datum].text)
.each((datum, index, groups) => {
Array.from(groups).forEach((text) => {
if (text) {
maximumLabelWidth = Math.max(maximumLabelWidth, text.getBoundingClientRect().width);
}
});
});
d3Select('g#renderToCalculateMaxWidth').remove();
this._legendGroupColumnWidth = maximumLabelWidth + ChartCommons.COLOR_PREVIEW_SIZE + 30;
this._legendGroupColumns = Math.floor(width / this._legendGroupColumnWidth);
if (this._legendGroupColumns < 1) {
this._legendGroupColumns = 1;
}
return Math.ceil(labels.length / this._legendGroupColumns) * ChartCommons.LABEL_HEIGHT + 30;
}
addLegendsToChart(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>,
xScale: D3ScaleTime<number, number>,
yScales: { [key: string]: D3ScaleLinear<number, number> },
data: { [key: string]: TimeSeries[] },
numberOfTimeSeries: number): void {
const legend: D3Selection<D3BaseType, {}, D3ContainerElement, {}> = d3Select('g#time-series-chart-legend');
legend.selectAll('.legend-entry').remove();
const legendEntry = legend.selectAll('.legend-entry').data(Object.keys(this._legendDataMap));
legendEntry.join(
enter => {
const legendElement = enter
.append('g')
.attr('class', 'legend-entry')
.style('opacity', (datum) => {
return (this._legendDataMap[datum].show) ? 1 : 0.2;
});
legendElement
.append('rect')
.attr('class', 'legend-rect')
.attr('height', ChartCommons.COLOR_PREVIEW_SIZE)
.attr('width', ChartCommons.COLOR_PREVIEW_SIZE)
.attr('rx', 2)
.attr('ry', 2)
.attr('fill', (key: string, index: number) => {
return getColorScheme()[(numberOfTimeSeries - index - 1) % getColorScheme().length];
});
legendElement
.append('text')
.attr('class', 'legend-text')
.attr('x', 15)
.attr('y', ChartCommons.COLOR_PREVIEW_SIZE)
.text(datum => this._legendDataMap[datum].text);
return legendElement;
},
update => update,
exit => exit
.transition()
.duration(ChartCommons.TRANSITION_DURATION)
.style('opacity', 0)
.remove()
)
.attr('transform', (_, index: number) => this.getLegendEntryPosition(index))
.on('click', (datum: string) =>
this.setSelectedLegendEntries(datum, chartContentContainer, xScale, yScales, data, numberOfTimeSeries));
}
setSummaryLabel(chart: D3Selection<D3BaseType, {}, D3ContainerElement, {}>,
summaryLabels: SummaryLabel[],
width: number): void {
const addSummaryLabel = (key: string, label: string, index: number): void => {
d3Select(`#summary-label-part${index}`)
.append('tspan')
.attr('id', `summary-label-part${index + 1}`)
.attr('class', 'summary-label-key')
.text(`${key}: `)
.append('tspan')
.attr('class', 'summary-label')
.text(label);
};
d3Select('g#header-group').selectAll('.summary-label-text').remove();
if (summaryLabels.length > 0) {
d3Select('#header-group')
.append('g')
.attr('class', 'summary-label-text')
.append('text')
.attr('id', 'summary-label-part0')
.attr('x', width / 2)
.attr('text-anchor', 'middle')
.attr('fill', '#555555');
summaryLabels.forEach((summaryLabel: SummaryLabel, index: number) => {
this.translationService
.get(`frontend.de.iteratec.osm.timeSeries.chart.label.${summaryLabel.key}`)
.pipe(take(1))
.subscribe((key: string) => {
if (summaryLabel.key === 'measurand') {
this.translationService
.get(`frontend.de.iteratec.isr.measurand.${summaryLabel.label}`)
.pipe(take(1))
.subscribe((label: string) => {
if (label.startsWith('frontend.de.iteratec.isr.measurand.')) {
label = summaryLabel.label;
}
label = index < summaryLabels.length - 1 ? `${label} | ` : label;
addSummaryLabel(key, label, index);
});
} else {
const label: string = index < summaryLabels.length - 1 ? `${summaryLabel.label} | ` : summaryLabel.label;
addSummaryLabel(key, label, index);
}
});
});
chart.selectAll('.summary-label-text').remove();
}
}
generateKey(data: EventResultSeriesDTO): string {
// remove every non alpha numeric character
const key: string = data.identifier.replace(/[^_a-zA-Z0-9-]/g, '');
// if first character is digit, replace it with '_'
const digitRegex = /[0-9]/;
if (digitRegex.test(key.charAt(0))) {
return key.replace(digitRegex, '_');
}
return key;
}
translateMeasurand(data: EventResultSeriesDTO): string {
const splitLabelList: string[] = data.identifier.split(' | ');
const splitLabel: string = this.translationService.instant(`frontend.de.iteratec.isr.measurand.${splitLabelList[0]}`);
if (!splitLabel.startsWith('frontend.de.iteratec.isr.measurand.')) {
splitLabelList[0] = splitLabel;
}
return splitLabelList.join(' | ');
}
private getLegendEntryPosition(index: number): string {
const x = index % this._legendGroupColumns * this._legendGroupColumnWidth;
const y = Math.floor(index / this._legendGroupColumns) * ChartCommons.LABEL_HEIGHT + 12;
return `translate(${x}, ${y})`;
}
private setSelectedLegendEntries(labelKey: string,
chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>,
xScale: D3ScaleTime<number, number>,
yScales: { [key: string]: D3ScaleLinear<number, number> },
data: { [key: string]: TimeSeries[] },
numberOfTimeSeries: number): void {
if (d3Event.metaKey || d3Event.ctrlKey) {
this._legendDataMap[labelKey].show = !this._legendDataMap[labelKey].show;
} else {
if (labelKey === this._focusedLegendEntry) {
Object.keys(this._legendDataMap).forEach((legend) => {
this._legendDataMap[legend].show = true;
});
this._focusedLegendEntry = '';
} else {
Object.keys(this._legendDataMap).forEach((legend) => {
if (legend === labelKey) {
this._legendDataMap[legend].show = true;
this._focusedLegendEntry = legend;
} else {
this._legendDataMap[legend].show = false;
}
});
}
}
Object.keys(yScales).forEach((key: string, index: number) => {
this.lineChartDrawService.addDataLinesToChart(
chartContentContainer, this.lineChartEventService.pointsSelection, xScale, yScales[key], data[key], this._legendDataMap, index);
});
// redraw legend
this.addLegendsToChart(chartContentContainer, xScale, yScales, data, numberOfTimeSeries);
}
} | the_stack |
import { WithoutNamespace } from "../tslite-bindings/.WithoutNamespace";
import { Map } from "../tslite-bindings/CourierRuntime";
import { WithCustomArrayTestId } from "../tslite-bindings/org.coursera.arrays.WithCustomArrayTestId";
import { WithCustomTypesArray } from "../tslite-bindings/org.coursera.arrays.WithCustomTypesArray";
import { WithCustomTypesArrayUnion } from "../tslite-bindings/org.coursera.arrays.WithCustomTypesArrayUnion";
import { WithPrimitivesArray } from "../tslite-bindings/org.coursera.arrays.WithPrimitivesArray";
import { WithRecordArray } from "../tslite-bindings/org.coursera.arrays.WithRecordArray";
import { BooleanId } from "../tslite-bindings/org.coursera.customtypes.BooleanId";
import { BoxedIntId } from "../tslite-bindings/org.coursera.customtypes.BoxedIntId";
import { ByteId } from "../tslite-bindings/org.coursera.customtypes.ByteId";
import { CaseClassCustomIntWrapper } from "../tslite-bindings/org.coursera.customtypes.CaseClassCustomIntWrapper";
import { CaseClassStringIdWrapper } from "../tslite-bindings/org.coursera.customtypes.CaseClassStringIdWrapper";
import { CharId } from "../tslite-bindings/org.coursera.customtypes.CharId";
import { CustomArrayTestId } from "../tslite-bindings/org.coursera.customtypes.CustomArrayTestId";
import { CustomInt } from "../tslite-bindings/org.coursera.customtypes.CustomInt";
import { CustomIntWrapper } from "../tslite-bindings/org.coursera.customtypes.CustomIntWrapper";
import { CustomMapTestKeyId } from "../tslite-bindings/org.coursera.customtypes.CustomMapTestKeyId";
import { CustomMapTestValueId } from "../tslite-bindings/org.coursera.customtypes.CustomMapTestValueId";
import { CustomRecord } from "../tslite-bindings/org.coursera.customtypes.CustomRecord";
import { CustomRecordTestId } from "../tslite-bindings/org.coursera.customtypes.CustomRecordTestId";
import { CustomUnionTestId } from "../tslite-bindings/org.coursera.customtypes.CustomUnionTestId";
import { DateTime } from "../tslite-bindings/org.coursera.customtypes.DateTime";
import { DoubleId } from "../tslite-bindings/org.coursera.customtypes.DoubleId";
import { FloatId } from "../tslite-bindings/org.coursera.customtypes.FloatId";
import { IntId } from "../tslite-bindings/org.coursera.customtypes.IntId";
import { LongId } from "../tslite-bindings/org.coursera.customtypes.LongId";
import { ShortId } from "../tslite-bindings/org.coursera.customtypes.ShortId";
import { StringId } from "../tslite-bindings/org.coursera.customtypes.StringId";
import { DeprecatedRecord } from "../tslite-bindings/org.coursera.deprecated.DeprecatedRecord";
import { EmptyEnum } from "../tslite-bindings/org.coursera.enums.EmptyEnum";
import { EnumProperties } from "../tslite-bindings/org.coursera.enums.EnumProperties";
import { Fruits } from "../tslite-bindings/org.coursera.enums.Fruits";
import { DefaultLiteralEscaping } from "../tslite-bindings/org.coursera.escaping.DefaultLiteralEscaping";
import { KeywordEscaping } from "../tslite-bindings/org.coursera.escaping.KeywordEscaping";
import { ReservedClassFieldEscaping } from "../tslite-bindings/org.coursera.escaping.ReservedClassFieldEscaping";
import { class$ } from "../tslite-bindings/org.coursera.escaping.class";
import { WithFixed8 } from "../tslite-bindings/org.coursera.fixed.WithFixed8";
import { Toggle } from "../tslite-bindings/org.coursera.maps.Toggle";
import { WithComplexTypesMap } from "../tslite-bindings/org.coursera.maps.WithComplexTypesMap";
import { WithComplexTypesMapUnion } from "../tslite-bindings/org.coursera.maps.WithComplexTypesMapUnion";
import { WithCustomMapTestIds } from "../tslite-bindings/org.coursera.maps.WithCustomMapTestIds";
import { WithCustomTypesMap } from "../tslite-bindings/org.coursera.maps.WithCustomTypesMap";
import { WithPrimitivesMap } from "../tslite-bindings/org.coursera.maps.WithPrimitivesMap";
import { WithTypedKeyMap } from "../tslite-bindings/org.coursera.maps.WithTypedKeyMap";
import { CourierFile } from "../tslite-bindings/org.coursera.records.CourierFile";
import { JsonTest } from "../tslite-bindings/org.coursera.records.JsonTest";
import { Message } from "../tslite-bindings/org.coursera.records.Message";
import { WithAnonymousUnionArray } from "../tslite-bindings/org.coursera.arrays.WithAnonymousUnionArray";
import { Note } from "../tslite-bindings/org.coursera.records.Note";
import { WithDateTime } from "../tslite-bindings/org.coursera.records.WithDateTime";
import { WithFlatTypedDefinition } from "../tslite-bindings/org.coursera.records.WithFlatTypedDefinition";
import { WithInclude } from "../tslite-bindings/org.coursera.records.WithInclude";
import { WithTypedDefinition } from "../tslite-bindings/org.coursera.records.WithTypedDefinition";
import { WithUnion } from "../tslite-bindings/org.coursera.records.WithUnion";
import { Fixed8 } from "../tslite-bindings/org.coursera.fixed.Fixed8";
import { class$ as EscapedClassRecord} from "../tslite-bindings/org.coursera.records.class";
import { Simple } from "../tslite-bindings/org.coursera.records.primitivestyle.Simple";
import { WithComplexTypes } from "../tslite-bindings/org.coursera.records.primitivestyle.WithComplexTypes";
import { WithPrimitives } from "../tslite-bindings/org.coursera.records.primitivestyle.WithPrimitives";
import { BooleanTyperef } from "../tslite-bindings/org.coursera.records.test.BooleanTyperef";
import { BytesTyperef } from "../tslite-bindings/org.coursera.records.test.BytesTyperef";
import { DoubleTyperef } from "../tslite-bindings/org.coursera.records.test.DoubleTyperef";
import { Empty } from "../tslite-bindings/org.coursera.records.test.Empty";
import { FloatTyperef } from "../tslite-bindings/org.coursera.records.test.FloatTyperef";
import { InlineOptionalRecord } from "../tslite-bindings/org.coursera.records.test.InlineOptionalRecord";
import { InlineRecord } from "../tslite-bindings/org.coursera.records.test.InlineRecord";
import { IntCustomType as TestIntCustomType } from "../tslite-bindings/org.coursera.records.test.IntCustomType";
import { IntTyperef as TestIntTyperef } from "../tslite-bindings/org.coursera.records.test.IntTyperef";
import { LongTyperef } from "../tslite-bindings/org.coursera.records.test.LongTyperef";
import { Message as TestMessage } from "../tslite-bindings/org.coursera.records.test.Message";
import { NumericDefaults } from "../tslite-bindings/org.coursera.records.test.NumericDefaults";
import { OptionalBooleanTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalBooleanTyperef";
import { OptionalBytesTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalBytesTyperef";
import { OptionalDoubleTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalDoubleTyperef";
import { OptionalFloatTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalFloatTyperef";
import { OptionalIntCustomType } from "../tslite-bindings/org.coursera.records.test.OptionalIntCustomType";
import { OptionalIntTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalIntTyperef";
import { OptionalLongTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalLongTyperef";
import { OptionalStringTyperef } from "../tslite-bindings/org.coursera.records.test.OptionalStringTyperef";
import { RecursivelyDefinedRecord } from "../tslite-bindings/org.coursera.records.test.RecursivelyDefinedRecord";
import { Simple as TestSimple } from "../tslite-bindings/org.coursera.records.test.Simple";
import { StringTyperef } from "../tslite-bindings/org.coursera.records.test.StringTyperef";
import { With22Fields } from "../tslite-bindings/org.coursera.records.test.With22Fields";
import { With23Fields } from "../tslite-bindings/org.coursera.records.test.With23Fields";
import { WithCaseClassCustomType } from "../tslite-bindings/org.coursera.records.test.WithCaseClassCustomType";
import { WithComplexTypeDefaults } from "../tslite-bindings/org.coursera.records.test.WithComplexTypeDefaults";
import { WithComplexTyperefs } from "../tslite-bindings/org.coursera.records.test.WithComplexTyperefs";
import { WithComplexTypes as TestWithComplexTypes } from "../tslite-bindings/org.coursera.records.test.WithComplexTypes";
import { WithCourierFile } from "../tslite-bindings/org.coursera.records.test.WithCourierFile";
import { WithCustomIntWrapper } from "../tslite-bindings/org.coursera.records.test.WithCustomIntWrapper";
import { WithCustomRecord } from "../tslite-bindings/org.coursera.records.test.WithCustomRecord";
import { WithCustomRecordTestId } from "../tslite-bindings/org.coursera.records.test.WithCustomRecordTestId";
import { WithDateTime as TestWithDateTime } from "../tslite-bindings/org.coursera.records.test.WithDateTime";
import { WithInclude as TestWithInclude } from "../tslite-bindings/org.coursera.records.test.WithInclude";
import { WithInlineRecord } from "../tslite-bindings/org.coursera.records.test.WithInlineRecord";
import { WithOmitField } from "../tslite-bindings/org.coursera.records.test.WithOmitField";
import { WithOptionalComplexTypeDefaults } from "../tslite-bindings/org.coursera.records.test.WithOptionalComplexTypeDefaults";
import { WithOptionalComplexTypes } from "../tslite-bindings/org.coursera.records.test.WithOptionalComplexTypes";
import { WithOptionalComplexTypesDefaultNone } from "../tslite-bindings/org.coursera.records.test.WithOptionalComplexTypesDefaultNone";
import { WithOptionalPrimitiveCustomTypes } from "../tslite-bindings/org.coursera.records.test.WithOptionalPrimitiveCustomTypes";
import { WithOptionalPrimitiveDefaultNone } from "../tslite-bindings/org.coursera.records.test.WithOptionalPrimitiveDefaultNone";
import { WithOptionalPrimitiveDefaults } from "../tslite-bindings/org.coursera.records.test.WithOptionalPrimitiveDefaults";
import { WithOptionalPrimitiveTyperefs } from "../tslite-bindings/org.coursera.records.test.WithOptionalPrimitiveTyperefs";
import { WithOptionalPrimitives } from "../tslite-bindings/org.coursera.records.test.WithOptionalPrimitives";
import { WithPrimitiveCustomTypes } from "../tslite-bindings/org.coursera.records.test.WithPrimitiveCustomTypes";
import { WithPrimitiveDefaults } from "../tslite-bindings/org.coursera.records.test.WithPrimitiveDefaults";
import { WithPrimitiveTyperefs } from "../tslite-bindings/org.coursera.records.test.WithPrimitiveTyperefs";
import { WithPrimitives as TestWithPrimitives } from "../tslite-bindings/org.coursera.records.test.WithPrimitives";
import { WithUnionWithInlineRecord } from "../tslite-bindings/org.coursera.records.test.WithUnionWithInlineRecord";
import { ArrayTyperef } from "../tslite-bindings/org.coursera.typerefs.ArrayTyperef";
import { EnumTyperef } from "../tslite-bindings/org.coursera.typerefs.EnumTyperef";
import { FlatTypedDefinition } from "../tslite-bindings/org.coursera.typerefs.FlatTypedDefinition";
import { InlineRecord as InlineRecordTypeRef } from "../tslite-bindings/org.coursera.typerefs.InlineRecord";
import { InlineRecord2 } from "../tslite-bindings/org.coursera.typerefs.InlineRecord2";
import { IntTyperef } from "../tslite-bindings/org.coursera.typerefs.IntTyperef";
import { MapTyperef } from "../tslite-bindings/org.coursera.typerefs.MapTyperef";
import { RecordTyperef } from "../tslite-bindings/org.coursera.typerefs.RecordTyperef";
import { TypedDefinition } from "../tslite-bindings/org.coursera.typerefs.TypedDefinition";
import { Union } from "../tslite-bindings/org.coursera.typerefs.Union";
import { UnionTyperef } from "../tslite-bindings/org.coursera.typerefs.UnionTyperef";
import { UnionWithInlineRecord } from "../tslite-bindings/org.coursera.typerefs.UnionWithInlineRecord";
import { IntCustomType } from "../tslite-bindings/org.coursera.unions.IntCustomType";
import { IntTyperef as IntTyperefUnion} from "../tslite-bindings/org.coursera.unions.IntTyperef";
import { WithComplexTypesUnion } from "../tslite-bindings/org.coursera.unions.WithComplexTypesUnion";
import { WithCustomUnionTestId } from "../tslite-bindings/org.coursera.unions.WithCustomUnionTestId";
import { WithEmptyUnion } from "../tslite-bindings/org.coursera.unions.WithEmptyUnion";
import { WithPrimitiveCustomTypesUnion } from "../tslite-bindings/org.coursera.unions.WithPrimitiveCustomTypesUnion";
import { WithPrimitiveTyperefsUnion } from "../tslite-bindings/org.coursera.unions.WithPrimitiveTyperefsUnion";
import { WithRecordCustomTypeUnion } from "../tslite-bindings/org.coursera.unions.WithRecordCustomTypeUnion";
import { Fortune } from "../tslite-bindings/org.example.Fortune";
import { FortuneCookie } from "../tslite-bindings/org.example.FortuneCookie";
import { FortuneTelling } from "../tslite-bindings/org.example.FortuneTelling";
import { MagicEightBall } from "../tslite-bindings/org.example.MagicEightBall";
import { MagicEightBallAnswer } from "../tslite-bindings/org.example.MagicEightBallAnswer";
import { TyperefExample } from "../tslite-bindings/org.example.TyperefExample";
import { DateTime as CommonDateTime } from "../tslite-bindings/org.example.common.DateTime";
import { Timestamp } from "../tslite-bindings/org.example.common.Timestamp";
import { DateTime as OtherDateTime } from "../tslite-bindings/org.example.other.DateTime";
import { record } from "../tslite-bindings/org.example.record";
import { WithPrimitivesUnion } from "../tslite-bindings/org.coursera.unions.WithPrimitivesUnion";
import * as ts from "typescript";
const fs = require('fs');
import CustomMatcherFactories = jasmine.CustomMatcherFactories;
import CompilerOptions = ts.CompilerOptions;
import TranspileOptions = ts.TranspileOptions;
import Diagnostic = ts.Diagnostic;
// Add a jasmine matcher that will attempt to compile a ts file and report
// any compilation errors
const toCompileMatcher: CustomMatcherFactories = {
toCompile: (util: any, customEqualityTesters: any) => {
return {
compare: (fileName: any, message:any) => {
const result: any = {};
var compilerOptions: CompilerOptions = {
project: "/Users/eboto/code/courier/typescript-lite/testsuite/tsconfig.json",
diagnostics: true
};
const program = ts.createProgram(
[fileName],
compilerOptions
);
const errors = program.getGlobalDiagnostics()
.concat(program.getSemanticDiagnostics())
.concat(program.getDeclarationDiagnostics())
.concat(program.getSyntacticDiagnostics());
const errorStr = errors.reduce((accum: any, err: Diagnostic) => {
const errFile = err.file;
const msgText = ts.flattenDiagnosticMessageText(err.messageText, "\n");
const nextAccum = accum + `\n${errFile.path}:${errFile.pos}\n${msgText}\n`;
return nextAccum;
}, "");
result.pass = (errors.length == 0);
if (!result.pass) {
result.message = `Compilation expectation failed: ${message} Error was: ${errorStr}`;
}
return result;
}
};
}
};
//
// Only test the runtime behavior of Unions
//
describe("Unions", () => {
it("should compile from correct javascript and unpack", () => {
const unionOfMessage: WithUnion = {
"value": {
"org.coursera.records.Message": {
"title": "title",
"body": "Hello, Courier."
}
}
};
const {note, message} = Union.unpack(unionOfMessage.value);
expect(note).toBeUndefined();
expect(message).not.toBeUndefined();
expect(message.title).toBe("title");
expect(message.body).toBe("Hello, Courier.");
});
it("should access all primitive unions properly", () => {
const keyShouldNotBeUndefined = (correctUnionKey: string) => (withUnion: WithPrimitivesUnion) => {
const union = withUnion.union;
const keys = Object.keys(union);
keys.forEach((key) => {
if (key == correctUnionKey) {
expect(union[key]).not.toBeUndefined(`Expected '${key}' not to be undefined in ${JSON.stringify(union)}`)
} else {
expect(union[key]).toBeUndefined(`Expected '${key}' to be defined in ${JSON.stringify(union)}. Only '${correctUnionKey}' was supposed to be defined.`);
}
});
};
const expectations = [
[wpu_int, keyShouldNotBeUndefined("int")],
[wpu_long, keyShouldNotBeUndefined("long")],
[wpu_float, keyShouldNotBeUndefined("float")],
[wpu_double, keyShouldNotBeUndefined("double")],
[wpu_bool, keyShouldNotBeUndefined("boolean")],
[wpu_string, keyShouldNotBeUndefined("string")],
[wpu_bytes, keyShouldNotBeUndefined("bytes")]
]
expectations.forEach((expectationData) => {
const [unionInstance, expectation] = expectationData;
(expectation as any)(unionInstance);
});
});
});
//
// Now attempt to compile our examples from src/compilation-failures. They should all fail.
//
describe("The typescript compiler", () => {
beforeEach(() => {
jasmine.addMatchers(toCompileMatcher);
});
const expectations = [
["should not allow unions with incorrect lookup keys", "union_bad-lookup-string.ts"],
["should not allow the body of the union to be malformed", "union_bad-body-content.ts"],
["should not allow records to have the wrong field type", "record_wrong-field-type.ts"],
["should not allow enums with a bad string value", "enum_bad-string.ts"],
["should not allow typerefs with the wrong root type", "typeref_wrong-type.ts"],
["should not allow the wrong type as the item of a primitive array", "array_bad-item-type.ts"],
["should not allow the wrong type as the item of an enum array", "array_bad-item-type-enum-expected.ts"],
["should not allow the wrong type as the value of a map", "map_bad-value-type.ts"]
];
expectations.forEach((expectationPair) => {
const [testCaseName, fileTest] = expectationPair;
it(testCaseName, () => {
expect(`src/compilation-failures/${fileTest}`).not.toCompile("It was expected to fail.");
})
});
});
describe("Enums", () => {
it("Should have successful accessors", () => {
const fruit1: Fruits = "APPLE";
expect(fruit1).toEqual(Fruits.APPLE);
expect(fruit1 == Fruits.APPLE).toBe(true);
});
it("Should have nice switch/case semantics", () => {
const fruit1: Fruits = "APPLE";
let result: string;
switch (fruit1) {
case "APPLE":
result = "It was an apple";
break;
case "PEAR":
result = "It was a pear";
break;
default:
result = "I don't know what it was.";
}
expect(result).toEqual("It was an apple");
switch (fruit1) {
case Fruits.APPLE:
result = "It's still an apple";
break;
default:
result = "Something else."
}
expect(result).toEqual("It's still an apple");
});
it("Should transcribe both the class-level and symbol-level documentation from the courier spec", () => {
const fruitsFile = fs.readFileSync("src/tslite-bindings/org.coursera.enums.Fruits.ts").toString();
const typeComment = "An enum dedicated to the finest of the food groups.";
const symbolComment = "An Apple.";
expect(fruitsFile).toContain(typeComment);
expect(fruitsFile).toContain(symbolComment);
});
it("Should be enumerated with the .all function", () => {
expect(Fruits.all).toEqual(["APPLE", "BANANA", "ORANGE", "PINEAPPLE"]);
});
});
//
// Now just declare a bunch of JSON types (sourced from courier/reference-suite/src/main/json.
//
// Compilation will fail if generation failed in compatibility with these known-good json types.
//
const customint: CustomInt = 1; // typerefs should work
const boolid: BooleanId = true;
const byteid: ByteId = "bytes just a string baby!";
const ref_of_a_ref: CustomIntWrapper = 1;
const fortune_fortuneCookie: Fortune = {
"telling": {
"org.example.FortuneCookie": {
"message": " a message",
"certainty": 0.1,
"luckyNumbers": [1, 2, 3]
}
},
"createdAt": "2015-01-01T00:00:00.000Z"
};
const fortune_magicEightBall: Fortune = {
"telling": {
"org.example.MagicEightBall": {
"question": "A question",
"answer": "IT_IS_CERTAIN"
}
},
"createdAt": "2015-01-01T00:00:00.000Z"
};
const fortuneCookie: FortuneCookie = {
"message": " a message",
"certainty": 0.1,
"luckyNumbers": [1, 2, 3]
};
const fortuneCookie_lackingOptional: FortuneCookie = {
"message": "a message",
"luckyNumbers": [1, 2, 3]
};
const kw_escaping: KeywordEscaping = {
"type" : "test"
};
const msg: Message = {
"title": "example title",
"body": "example body"
};
const rcfe: ReservedClassFieldEscaping = {
"data" : "dataText",
"schema": "schemaText",
"copy": "copyText",
"clone": "cloneText"
};
const simple: Simple = { "message": "simple message" };
const withComplexTypes: TestWithComplexTypes = {
"record": { "message": "record"},
"enum": "APPLE",
"union": { "org.coursera.records.test.Simple": { "message": "union" }},
"array": [1, 2],
"map": { "a": 1, "b": 2},
"complexMap": { "x": { "message": "complexMap"}},
"custom": 100
};
const wu: WithUnion = {
"value": {
"org.coursera.records.Message": {
"title": "title",
"body": "Hello, Courier."
}
}
};
const wctu_empty: WithComplexTypesUnion = {
"union" : {
"org.coursera.records.test.Empty" : { }
}
};
const wctu_enum: WithComplexTypesUnion = {
"union" : {
"org.coursera.enums.Fruits" : "APPLE"
}
};
const withCustomTypesArr: WithCustomTypesArray = {
"ints" : [ 1, 2, 3 ],
"arrays": [ [ { "message": "a1" } ] ],
"maps": [ { "a": { "message": "m1" } } ],
"unions": [
{ "int": 1 },
{ "string": "str" },
{ "org.coursera.records.test.Simple": { "message": "u1" }}
],
"fixed": [ "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007" ]
};
const wctm: WithCustomTypesMap = {
"ints" : {
"b" : 2,
"c" : 3,
"a" : 1
}
};
const wctm2: WithComplexTypesMap = {
"empties" : {
"b" : { },
"c" : { },
"a" : { }
},
"fruits" : {
"b" : "BANANA",
"c" : "ORANGE",
"a" : "APPLE"
},
"arrays" : {
"a": [ {"message": "v1"}, {"message": "v2"} ]
},
"maps": {
"o1": {
"i1": { "message": "o1i1" },
"i2": { "message": "o1i2" }
}
},
"unions": {
"a": { "int": 1 },
"b": { "string": "u1" }
},
"fixed": {
"a": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"
}
};
const wdt: TestWithDateTime = {
"createdAt": 1420070400000
};
const wp1: WithPrimitiveCustomTypes = {
"intField" : 1
};
const wpu: WithPrimitiveCustomTypesUnion = {
"union" : {
"int" : 1
}
};
const wp2: WithPrimitives = {
"floatField" : 3.3,
"doubleField" : 4.4,
"intField" : 1,
"bytesField" : "\u0000\u0001\u0002",
"longField" : 2,
"booleanField" : true,
"stringField" : "str"
};
const wpa: WithPrimitivesArray = {
"bytes" : [ "\u0000\u0001\u0002",
"\u0003\u0004\u0005" ],
"longs" : [ 10, 20, 30 ],
"strings" : [ "a", "b", "c" ],
"doubles" : [ 11.1, 22.2, 33.3 ],
"booleans" : [ false, true ],
"floats" : [ 1.1, 2.2, 3.3 ],
"ints" : [ 1, 2, 3 ]
};
const wpm: WithPrimitivesMap = {
"bytes" : {
"b" : "\u0003\u0004\u0005",
"c" : "\u0006\u0007\b",
"a" : "\u0000\u0001\u0002"
},
"longs" : {
"b" : 20,
"c" : 30,
"a" : 10
},
"strings" : {
"b" : "string2",
"c" : "string3",
"a" : "string1"
},
"doubles" : {
"b" : 22.2,
"c" : 33.3,
"a" : 11.1
},
"booleans" : {
"b" : false,
"c" : true,
"a" : true
},
"floats" : {
"b" : 2.2,
"c" : 3.3,
"a" : 1.1
},
"ints" : {
"b" : 2,
"c" : 3,
"a" : 1
}
};
const wtkm: WithTypedKeyMap = {
"ints" : { "1": "int" },
"longs" : { "2": "long" },
"floats" : { "3.14": "float" },
"doubles" : { "2.71": "double" },
"booleans" : { "true": "boolean" },
"strings" : { "key": "string" },
"bytes" : { "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007": "bytes" },
"record" : { "(message~key)": "record" },
"array" : { "List(1,2)": "array" },
"enum" : { "APPLE": "enum" },
"custom" : { "100": "custom" },
"fixed" : { "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007": "fixed" }
};
const wra: WithRecordArray = {
"empties" : [ { }, { }, { } ],
"fruits" : [ "APPLE", "BANANA", "ORANGE" ]
};
const wctu_array: WithComplexTypesUnion = {
"union" : {
"array" : [ { "message": "a1" } ] // TODO(eboto): Oops! Looks like it specified this in TS like arraySimple: union["Array<org.coursera.records.test.Simple>"]. It should have just been "array"
}
};
const wctu_map: WithComplexTypesUnion = {
"union" : {
"map" : { "a": { "message": "m1" } }
}
};
const wpu_long: WithPrimitivesUnion = {
"union" : {
"long" : 2
}
};
const wpu_bool: WithPrimitivesUnion = {
"union" : {
"boolean" : true
}
};
const wpu_string: WithPrimitivesUnion = {
"union" : {
"string" : "thestring"
}
};
const wpu_bytes: WithPrimitivesUnion = {
"union" : {
"bytes" : "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"
}
};
const wpu_str: WithPrimitivesUnion = {
"union" : {
"string" : "str"
}
};
const wpu_int: WithPrimitivesUnion = {
"union" : {
"int" : 1
}
};
const wpu_float: WithPrimitivesUnion = {
"union" : {
"float" : 3.0
}
};
const wpu_double: WithPrimitivesUnion = {
"union" : {
"double" : 4.0
}
};
/* TODO(eboto): This one fails. Why? What is a TypedDefinition?
const wtd: WithTypedDefinition = {
"value": {
"typeName": "message",
"definition": {
"title": "title",
"body": "Hello, Courier."
}
}
};
*/
/** TODO(eboto): Uncomment after support for flat type definitions
const wftd: WithFlatTypedDefinition = {
"value": {
"typeName": "message",
"title": "title",
"body": "Hello, Courier."
}
};
*/
/* TODO(eboto): This is not working because org.coursera.records.mutable.Simple doesn't exist. Ask jpbetz or saeta if this is actually meant to work.
const withCustomTypesArrMutable: WithCustomTypesArray = {
"ints" : [ 1, 2, 3 ],
"arrays": [ [ { "message": "a1" } ] ],
"maps": [ { "a": { "message": "m1" } } ],
"unions": [
{ "number": 1 },
{ "string": "str" },
{ "org.coursera.records.mutable.Simple": { "message": "u1" }}
],
"fixed": [ "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007" ]
}
*/ | the_stack |
import 'es6-promise/auto'; // polyfill Promise on IE
import {
BasicKeyHandler, BasicMouseHandler, BasicSelectionModel, CellRenderer,
DataGrid, DataModel, JSONModel, TextRenderer
} from '@phosphor/datagrid';
import {
DockPanel, StackedPanel, Widget
} from '@phosphor/widgets';
import '../style/index.css';
class LargeDataModel extends DataModel {
rowCount(region: DataModel.RowRegion): number {
return region === 'body' ? 1000000000000 : 2;
}
columnCount(region: DataModel.ColumnRegion): number {
return region === 'body' ? 1000000000000 : 3;
}
data(region: DataModel.CellRegion, row: number, column: number): any {
if (region === 'row-header') {
return `R: ${row}, ${column}`;
}
if (region === 'column-header') {
return `C: ${row}, ${column}`;
}
if (region === 'corner-header') {
return `N: ${row}, ${column}`;
}
return `(${row}, ${column})`;
}
}
class StreamingDataModel extends DataModel {
static createRow(n: number): number[] {
let row = new Array(n);
for (let i = 0; i < n; ++i) {
row[i] = Math.random();
}
return row;
}
constructor() {
super();
setInterval(this._tick, 250);
}
rowCount(region: DataModel.RowRegion): number {
return region === 'body' ? this._data.length : 1;
}
columnCount(region: DataModel.ColumnRegion): number {
return region === 'body' ? 50 : 1;
}
data(region: DataModel.CellRegion, row: number, column: number): any {
if (region === 'row-header') {
return `R: ${row}, ${column}`;
}
if (region === 'column-header') {
return `C: ${row}, ${column}`;
}
if (region === 'corner-header') {
return `N: ${row}, ${column}`;
}
return this._data[row][column];
}
private _tick = () => {
let nr = this.rowCount('body');
let nc = this.columnCount('body');
let r1 = Math.random();
let r2 = Math.random();
let i = Math.floor(r2 * nr);
if ((r1 < 0.45 && nr > 4) || nr >= 500) {
this._data.splice(i, 1);
this.emitChanged({ type: 'rows-removed', region: 'body', index: i, span: 1 });
} else {
this._data.splice(i, 0, StreamingDataModel.createRow(nc));
this.emitChanged({ type: 'rows-inserted', region: 'body', index: i, span: 1 });
}
};
private _data: number[][] = [];
}
class RandomDataModel extends DataModel {
static genPoint(): number {
return Math.random() * 10 - 2;
}
constructor(rowCount: number, columnCount: number) {
super();
let nr = this._rowCount = rowCount;
let nc = this._columnCount = columnCount;
for (let i = 0, n = nr * nc; i < n; ++i) {
this._data[i] = i / n;
}
setInterval(this._tick, 60);
}
rowCount(region: DataModel.RowRegion): number {
return region === 'body' ? this._rowCount : 1;
}
columnCount(region: DataModel.ColumnRegion): number {
return region === 'body' ? this._columnCount : 1;
}
data(region: DataModel.CellRegion, row: number, column: number): any {
if (region === 'row-header') {
return `R: ${row}, ${column}`;
}
if (region === 'column-header') {
return `C: ${row}, ${column}`;
}
if (region === 'corner-header') {
return `N: ${row}, ${column}`;
}
return this._data[row * this._columnCount + column];
}
private _tick = () => {
let nr = this._rowCount;
let nc = this._columnCount;
let i = Math.floor(Math.random() * (nr * nc - 1));
let r = Math.floor(i / nc);
let c = i - r * nc;
this._data[i] = (this._data[i] + Math.random()) % 1;
this.emitChanged({
type: 'cells-changed',
region: 'body',
row: r,
column: c,
rowSpan: 1,
columnSpan: 1
});
};
private _rowCount: number;
private _columnCount: number;
private _data: number[] = [];
}
const redGreenBlack: CellRenderer.ConfigFunc<string> = ({ value }) => {
if (value <= 1 / 3) {
return '#000000';
}
if (value <= 2 / 3) {
return '#FF0000';
}
return '#009B00';
};
const heatMapViridis: CellRenderer.ConfigFunc<string> = ({ value }) => {
let r = Math.floor(ViridisCM.red(value) * 255);
let g = Math.floor(ViridisCM.green(value) * 255);
let b = Math.floor(ViridisCM.blue(value) * 255);
return `rgb(${r}, ${g}, ${b})`;
};
const heatMapViridisInverse: CellRenderer.ConfigFunc<string> = ({ value }) => {
let r = Math.floor(255 - ViridisCM.red(value) * 255);
let g = Math.floor(255 - ViridisCM.green(value) * 255);
let b = Math.floor(255 - ViridisCM.blue(value) * 255);
return `rgb(${r}, ${g}, ${b})`;
};
function createWrapper(content: Widget, title: string): Widget {
let wrapper = new StackedPanel();
wrapper.addClass('content-wrapper');
wrapper.addWidget(content);
wrapper.title.label = title;
return wrapper;
}
function main(): void {
let model1 = new LargeDataModel();
let model2 = new StreamingDataModel();
let model3 = new RandomDataModel(15, 10);
let model4 = new RandomDataModel(80, 80);
let model5 = new JSONModel(Data.cars);
let blueStripeStyle: DataGrid.Style = {
...DataGrid.defaultStyle,
rowBackgroundColor: i => i % 2 === 0 ? 'rgba(138, 172, 200, 0.3)' : '',
columnBackgroundColor: i => i % 2 === 0 ? 'rgba(100, 100, 100, 0.1)' : ''
};
let brownStripeStyle: DataGrid.Style = {
...DataGrid.defaultStyle,
columnBackgroundColor: i => i % 2 === 0 ? 'rgba(165, 143, 53, 0.2)' : ''
};
let greenStripeStyle: DataGrid.Style = {
...DataGrid.defaultStyle,
rowBackgroundColor: i => i % 2 === 0 ? 'rgba(64, 115, 53, 0.2)' : ''
};
let lightSelectionStyle: DataGrid.Style = {
...DataGrid.defaultStyle,
selectionFillColor: 'rgba(255, 255, 255, 0.2)',
selectionBorderColor: 'white',
headerSelectionBorderColor: 'white',
cursorBorderColor: 'white'
};
let fgColorFloatRenderer = new TextRenderer({
font: 'bold 12px sans-serif',
textColor: redGreenBlack,
format: TextRenderer.formatFixed({ digits: 2 }),
horizontalAlignment: 'right'
});
let bgColorFloatRenderer = new TextRenderer({
textColor: heatMapViridisInverse,
backgroundColor: heatMapViridis,
format: TextRenderer.formatFixed({ digits: 2 }),
horizontalAlignment: 'right'
});
let grid1 = new DataGrid({ style: blueStripeStyle });
grid1.dataModel = model1;
grid1.keyHandler = new BasicKeyHandler();
grid1.mouseHandler = new BasicMouseHandler();
grid1.selectionModel = new BasicSelectionModel({ dataModel: model1 });
let grid2 = new DataGrid({ style: brownStripeStyle });
grid2.dataModel = model2;
grid2.keyHandler = new BasicKeyHandler();
grid2.mouseHandler = new BasicMouseHandler();
grid2.selectionModel = new BasicSelectionModel({
dataModel: model2,
selectionMode: 'column'
});
let grid3 = new DataGrid({ stretchLastColumn: true });
grid3.cellRenderers.update({ 'body': fgColorFloatRenderer });
grid3.dataModel = model3;
grid3.keyHandler = new BasicKeyHandler();
grid3.mouseHandler = new BasicMouseHandler();
grid3.selectionModel = new BasicSelectionModel({ dataModel: model3 });
let grid4 = new DataGrid({ style: lightSelectionStyle });
grid4.cellRenderers.update({ 'body': bgColorFloatRenderer });
grid4.dataModel = model4;
grid4.keyHandler = new BasicKeyHandler();
grid4.mouseHandler = new BasicMouseHandler();
grid4.selectionModel = new BasicSelectionModel({ dataModel: model4 });
let grid5 = new DataGrid({
style: greenStripeStyle,
defaultSizes: {
rowHeight: 32,
columnWidth: 128,
rowHeaderWidth: 64,
columnHeaderHeight: 32
}
});
grid5.dataModel = model5;
grid5.keyHandler = new BasicKeyHandler();
grid5.mouseHandler = new BasicMouseHandler();
grid5.selectionModel = new BasicSelectionModel({
dataModel: model5,
selectionMode: 'row'
});
let wrapper1 = createWrapper(grid1, 'Trillion Rows/Cols');
let wrapper2 = createWrapper(grid2, 'Streaming Rows');
let wrapper3 = createWrapper(grid3, 'Random Ticks 1');
let wrapper4 = createWrapper(grid4, 'Random Ticks 2');
let wrapper5 = createWrapper(grid5, 'JSON Data');
let dock = new DockPanel();
dock.id = 'dock';
dock.addWidget(wrapper1);
dock.addWidget(wrapper2, { mode: 'split-right', ref: wrapper1 });
dock.addWidget(wrapper3, { mode: 'split-bottom', ref: wrapper1 });
dock.addWidget(wrapper4, { mode: 'split-bottom', ref: wrapper2 });
dock.addWidget(wrapper5, { mode: 'split-bottom', ref: wrapper2 });
window.onresize = () => { dock.update(); };
Widget.attach(dock, document.body);
}
window.onload = main;
namespace ViridisCM {
// Color table from:
// https://github.com/matplotlib/matplotlib/blob/38be7aeaaac3691560aeadafe46722dda427ef47/lib/matplotlib/_cm_listed.py
const colorTable = [
[0.267004, 0.004874, 0.329415],
[0.268510, 0.009605, 0.335427],
[0.269944, 0.014625, 0.341379],
[0.271305, 0.019942, 0.347269],
[0.272594, 0.025563, 0.353093],
[0.273809, 0.031497, 0.358853],
[0.274952, 0.037752, 0.364543],
[0.276022, 0.044167, 0.370164],
[0.277018, 0.050344, 0.375715],
[0.277941, 0.056324, 0.381191],
[0.278791, 0.062145, 0.386592],
[0.279566, 0.067836, 0.391917],
[0.280267, 0.073417, 0.397163],
[0.280894, 0.078907, 0.402329],
[0.281446, 0.084320, 0.407414],
[0.281924, 0.089666, 0.412415],
[0.282327, 0.094955, 0.417331],
[0.282656, 0.100196, 0.422160],
[0.282910, 0.105393, 0.426902],
[0.283091, 0.110553, 0.431554],
[0.283197, 0.115680, 0.436115],
[0.283229, 0.120777, 0.440584],
[0.283187, 0.125848, 0.444960],
[0.283072, 0.130895, 0.449241],
[0.282884, 0.135920, 0.453427],
[0.282623, 0.140926, 0.457517],
[0.282290, 0.145912, 0.461510],
[0.281887, 0.150881, 0.465405],
[0.281412, 0.155834, 0.469201],
[0.280868, 0.160771, 0.472899],
[0.280255, 0.165693, 0.476498],
[0.279574, 0.170599, 0.479997],
[0.278826, 0.175490, 0.483397],
[0.278012, 0.180367, 0.486697],
[0.277134, 0.185228, 0.489898],
[0.276194, 0.190074, 0.493001],
[0.275191, 0.194905, 0.496005],
[0.274128, 0.199721, 0.498911],
[0.273006, 0.204520, 0.501721],
[0.271828, 0.209303, 0.504434],
[0.270595, 0.214069, 0.507052],
[0.269308, 0.218818, 0.509577],
[0.267968, 0.223549, 0.512008],
[0.266580, 0.228262, 0.514349],
[0.265145, 0.232956, 0.516599],
[0.263663, 0.237631, 0.518762],
[0.262138, 0.242286, 0.520837],
[0.260571, 0.246922, 0.522828],
[0.258965, 0.251537, 0.524736],
[0.257322, 0.256130, 0.526563],
[0.255645, 0.260703, 0.528312],
[0.253935, 0.265254, 0.529983],
[0.252194, 0.269783, 0.531579],
[0.250425, 0.274290, 0.533103],
[0.248629, 0.278775, 0.534556],
[0.246811, 0.283237, 0.535941],
[0.244972, 0.287675, 0.537260],
[0.243113, 0.292092, 0.538516],
[0.241237, 0.296485, 0.539709],
[0.239346, 0.300855, 0.540844],
[0.237441, 0.305202, 0.541921],
[0.235526, 0.309527, 0.542944],
[0.233603, 0.313828, 0.543914],
[0.231674, 0.318106, 0.544834],
[0.229739, 0.322361, 0.545706],
[0.227802, 0.326594, 0.546532],
[0.225863, 0.330805, 0.547314],
[0.223925, 0.334994, 0.548053],
[0.221989, 0.339161, 0.548752],
[0.220057, 0.343307, 0.549413],
[0.218130, 0.347432, 0.550038],
[0.216210, 0.351535, 0.550627],
[0.214298, 0.355619, 0.551184],
[0.212395, 0.359683, 0.551710],
[0.210503, 0.363727, 0.552206],
[0.208623, 0.367752, 0.552675],
[0.206756, 0.371758, 0.553117],
[0.204903, 0.375746, 0.553533],
[0.203063, 0.379716, 0.553925],
[0.201239, 0.383670, 0.554294],
[0.199430, 0.387607, 0.554642],
[0.197636, 0.391528, 0.554969],
[0.195860, 0.395433, 0.555276],
[0.194100, 0.399323, 0.555565],
[0.192357, 0.403199, 0.555836],
[0.190631, 0.407061, 0.556089],
[0.188923, 0.410910, 0.556326],
[0.187231, 0.414746, 0.556547],
[0.185556, 0.418570, 0.556753],
[0.183898, 0.422383, 0.556944],
[0.182256, 0.426184, 0.557120],
[0.180629, 0.429975, 0.557282],
[0.179019, 0.433756, 0.557430],
[0.177423, 0.437527, 0.557565],
[0.175841, 0.441290, 0.557685],
[0.174274, 0.445044, 0.557792],
[0.172719, 0.448791, 0.557885],
[0.171176, 0.452530, 0.557965],
[0.169646, 0.456262, 0.558030],
[0.168126, 0.459988, 0.558082],
[0.166617, 0.463708, 0.558119],
[0.165117, 0.467423, 0.558141],
[0.163625, 0.471133, 0.558148],
[0.162142, 0.474838, 0.558140],
[0.160665, 0.478540, 0.558115],
[0.159194, 0.482237, 0.558073],
[0.157729, 0.485932, 0.558013],
[0.156270, 0.489624, 0.557936],
[0.154815, 0.493313, 0.557840],
[0.153364, 0.497000, 0.557724],
[0.151918, 0.500685, 0.557587],
[0.150476, 0.504369, 0.557430],
[0.149039, 0.508051, 0.557250],
[0.147607, 0.511733, 0.557049],
[0.146180, 0.515413, 0.556823],
[0.144759, 0.519093, 0.556572],
[0.143343, 0.522773, 0.556295],
[0.141935, 0.526453, 0.555991],
[0.140536, 0.530132, 0.555659],
[0.139147, 0.533812, 0.555298],
[0.137770, 0.537492, 0.554906],
[0.136408, 0.541173, 0.554483],
[0.135066, 0.544853, 0.554029],
[0.133743, 0.548535, 0.553541],
[0.132444, 0.552216, 0.553018],
[0.131172, 0.555899, 0.552459],
[0.129933, 0.559582, 0.551864],
[0.128729, 0.563265, 0.551229],
[0.127568, 0.566949, 0.550556],
[0.126453, 0.570633, 0.549841],
[0.125394, 0.574318, 0.549086],
[0.124395, 0.578002, 0.548287],
[0.123463, 0.581687, 0.547445],
[0.122606, 0.585371, 0.546557],
[0.121831, 0.589055, 0.545623],
[0.121148, 0.592739, 0.544641],
[0.120565, 0.596422, 0.543611],
[0.120092, 0.600104, 0.542530],
[0.119738, 0.603785, 0.541400],
[0.119512, 0.607464, 0.540218],
[0.119423, 0.611141, 0.538982],
[0.119483, 0.614817, 0.537692],
[0.119699, 0.618490, 0.536347],
[0.120081, 0.622161, 0.534946],
[0.120638, 0.625828, 0.533488],
[0.121380, 0.629492, 0.531973],
[0.122312, 0.633153, 0.530398],
[0.123444, 0.636809, 0.528763],
[0.124780, 0.640461, 0.527068],
[0.126326, 0.644107, 0.525311],
[0.128087, 0.647749, 0.523491],
[0.130067, 0.651384, 0.521608],
[0.132268, 0.655014, 0.519661],
[0.134692, 0.658636, 0.517649],
[0.137339, 0.662252, 0.515571],
[0.140210, 0.665859, 0.513427],
[0.143303, 0.669459, 0.511215],
[0.146616, 0.673050, 0.508936],
[0.150148, 0.676631, 0.506589],
[0.153894, 0.680203, 0.504172],
[0.157851, 0.683765, 0.501686],
[0.162016, 0.687316, 0.499129],
[0.166383, 0.690856, 0.496502],
[0.170948, 0.694384, 0.493803],
[0.175707, 0.697900, 0.491033],
[0.180653, 0.701402, 0.488189],
[0.185783, 0.704891, 0.485273],
[0.191090, 0.708366, 0.482284],
[0.196571, 0.711827, 0.479221],
[0.202219, 0.715272, 0.476084],
[0.208030, 0.718701, 0.472873],
[0.214000, 0.722114, 0.469588],
[0.220124, 0.725509, 0.466226],
[0.226397, 0.728888, 0.462789],
[0.232815, 0.732247, 0.459277],
[0.239374, 0.735588, 0.455688],
[0.246070, 0.738910, 0.452024],
[0.252899, 0.742211, 0.448284],
[0.259857, 0.745492, 0.444467],
[0.266941, 0.748751, 0.440573],
[0.274149, 0.751988, 0.436601],
[0.281477, 0.755203, 0.432552],
[0.288921, 0.758394, 0.428426],
[0.296479, 0.761561, 0.424223],
[0.304148, 0.764704, 0.419943],
[0.311925, 0.767822, 0.415586],
[0.319809, 0.770914, 0.411152],
[0.327796, 0.773980, 0.406640],
[0.335885, 0.777018, 0.402049],
[0.344074, 0.780029, 0.397381],
[0.352360, 0.783011, 0.392636],
[0.360741, 0.785964, 0.387814],
[0.369214, 0.788888, 0.382914],
[0.377779, 0.791781, 0.377939],
[0.386433, 0.794644, 0.372886],
[0.395174, 0.797475, 0.367757],
[0.404001, 0.800275, 0.362552],
[0.412913, 0.803041, 0.357269],
[0.421908, 0.805774, 0.351910],
[0.430983, 0.808473, 0.346476],
[0.440137, 0.811138, 0.340967],
[0.449368, 0.813768, 0.335384],
[0.458674, 0.816363, 0.329727],
[0.468053, 0.818921, 0.323998],
[0.477504, 0.821444, 0.318195],
[0.487026, 0.823929, 0.312321],
[0.496615, 0.826376, 0.306377],
[0.506271, 0.828786, 0.300362],
[0.515992, 0.831158, 0.294279],
[0.525776, 0.833491, 0.288127],
[0.535621, 0.835785, 0.281908],
[0.545524, 0.838039, 0.275626],
[0.555484, 0.840254, 0.269281],
[0.565498, 0.842430, 0.262877],
[0.575563, 0.844566, 0.256415],
[0.585678, 0.846661, 0.249897],
[0.595839, 0.848717, 0.243329],
[0.606045, 0.850733, 0.236712],
[0.616293, 0.852709, 0.230052],
[0.626579, 0.854645, 0.223353],
[0.636902, 0.856542, 0.216620],
[0.647257, 0.858400, 0.209861],
[0.657642, 0.860219, 0.203082],
[0.668054, 0.861999, 0.196293],
[0.678489, 0.863742, 0.189503],
[0.688944, 0.865448, 0.182725],
[0.699415, 0.867117, 0.175971],
[0.709898, 0.868751, 0.169257],
[0.720391, 0.870350, 0.162603],
[0.730889, 0.871916, 0.156029],
[0.741388, 0.873449, 0.149561],
[0.751884, 0.874951, 0.143228],
[0.762373, 0.876424, 0.137064],
[0.772852, 0.877868, 0.131109],
[0.783315, 0.879285, 0.125405],
[0.793760, 0.880678, 0.120005],
[0.804182, 0.882046, 0.114965],
[0.814576, 0.883393, 0.110347],
[0.824940, 0.884720, 0.106217],
[0.835270, 0.886029, 0.102646],
[0.845561, 0.887322, 0.099702],
[0.855810, 0.888601, 0.097452],
[0.866013, 0.889868, 0.095953],
[0.876168, 0.891125, 0.095250],
[0.886271, 0.892374, 0.095374],
[0.896320, 0.893616, 0.096335],
[0.906311, 0.894855, 0.098125],
[0.916242, 0.896091, 0.100717],
[0.926106, 0.897330, 0.104071],
[0.935904, 0.898570, 0.108131],
[0.945636, 0.899815, 0.112838],
[0.955300, 0.901065, 0.118128],
[0.964894, 0.902323, 0.123941],
[0.974417, 0.903590, 0.130215],
[0.983868, 0.904867, 0.136897],
[0.993248, 0.906157, 0.143936]
];
export
function red(value: number): number {
return colorTable[getIndex(value)][0];
}
export
function green(value: number): number {
return colorTable[getIndex(value)][1];
}
export
function blue(value: number): number {
return colorTable[getIndex(value)][2];
}
function getIndex(value: number): number {
return Math.round(value * (colorTable.length - 1));
}
}
namespace Data {
export
const cars = {
"data": [
{
"Horsepower": 130.0,
"Origin": "USA",
"Miles_per_Gallon": 18.0,
"Name": "chevrolet chevelle malibu",
"index": 0,
"Acceleration": 12.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3504,
"Cylinders": 8,
"Displacement": 307.0
},
{
"Horsepower": 165.0,
"Origin": "USA",
"Miles_per_Gallon": 15.0,
"Name": "buick skylark 320",
"index": 1,
"Acceleration": 11.5,
"Year": "1970-01-01",
"Weight_in_lbs": 3693,
"Cylinders": 8,
"Displacement": 350.0
},
{
"Horsepower": 150.0,
"Origin": "USA",
"Miles_per_Gallon": 18.0,
"Name": "plymouth satellite",
"index": 2,
"Acceleration": 11.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3436,
"Cylinders": 8,
"Displacement": 318.0
},
{
"Horsepower": 150.0,
"Origin": "USA",
"Miles_per_Gallon": 16.0,
"Name": "amc rebel sst",
"index": 3,
"Acceleration": 12.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3433,
"Cylinders": 8,
"Displacement": 304.0
},
{
"Horsepower": 140.0,
"Origin": "USA",
"Miles_per_Gallon": 17.0,
"Name": "ford torino",
"index": 4,
"Acceleration": 10.5,
"Year": "1970-01-01",
"Weight_in_lbs": 3449,
"Cylinders": 8,
"Displacement": 302.0
},
{
"Horsepower": 198.0,
"Origin": "USA",
"Miles_per_Gallon": 15.0,
"Name": "ford galaxie 500",
"index": 5,
"Acceleration": 10.0,
"Year": "1970-01-01",
"Weight_in_lbs": 4341,
"Cylinders": 8,
"Displacement": 429.0
},
{
"Horsepower": 220.0,
"Origin": "USA",
"Miles_per_Gallon": 14.0,
"Name": "chevrolet impala",
"index": 6,
"Acceleration": 9.0,
"Year": "1970-01-01",
"Weight_in_lbs": 4354,
"Cylinders": 8,
"Displacement": 454.0
},
{
"Horsepower": 215.0,
"Origin": "USA",
"Miles_per_Gallon": 14.0,
"Name": "plymouth fury iii",
"index": 7,
"Acceleration": 8.5,
"Year": "1970-01-01",
"Weight_in_lbs": 4312,
"Cylinders": 8,
"Displacement": 440.0
},
{
"Horsepower": 225.0,
"Origin": "USA",
"Miles_per_Gallon": 14.0,
"Name": "pontiac catalina",
"index": 8,
"Acceleration": 10.0,
"Year": "1970-01-01",
"Weight_in_lbs": 4425,
"Cylinders": 8,
"Displacement": 455.0
},
{
"Horsepower": 190.0,
"Origin": "USA",
"Miles_per_Gallon": 15.0,
"Name": "amc ambassador dpl",
"index": 9,
"Acceleration": 8.5,
"Year": "1970-01-01",
"Weight_in_lbs": 3850,
"Cylinders": 8,
"Displacement": 390.0
},
{
"Horsepower": 115.0,
"Origin": "Europe",
"Miles_per_Gallon": null,
"Name": "citroen ds-21 pallas",
"index": 10,
"Acceleration": 17.5,
"Year": "1970-01-01",
"Weight_in_lbs": 3090,
"Cylinders": 4,
"Displacement": 133.0
},
{
"Horsepower": 165.0,
"Origin": "USA",
"Miles_per_Gallon": null,
"Name": "chevrolet chevelle concours (sw)",
"index": 11,
"Acceleration": 11.5,
"Year": "1970-01-01",
"Weight_in_lbs": 4142,
"Cylinders": 8,
"Displacement": 350.0
},
{
"Horsepower": 153.0,
"Origin": "USA",
"Miles_per_Gallon": null,
"Name": "ford torino (sw)",
"index": 12,
"Acceleration": 11.0,
"Year": "1970-01-01",
"Weight_in_lbs": 4034,
"Cylinders": 8,
"Displacement": 351.0
},
{
"Horsepower": 175.0,
"Origin": "USA",
"Miles_per_Gallon": null,
"Name": "plymouth satellite (sw)",
"index": 13,
"Acceleration": 10.5,
"Year": "1970-01-01",
"Weight_in_lbs": 4166,
"Cylinders": 8,
"Displacement": 383.0
},
{
"Horsepower": 175.0,
"Origin": "USA",
"Miles_per_Gallon": null,
"Name": "amc rebel sst (sw)",
"index": 14,
"Acceleration": 11.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3850,
"Cylinders": 8,
"Displacement": 360.0
},
{
"Horsepower": 170.0,
"Origin": "USA",
"Miles_per_Gallon": 15.0,
"Name": "dodge challenger se",
"index": 15,
"Acceleration": 10.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3563,
"Cylinders": 8,
"Displacement": 383.0
},
{
"Horsepower": 160.0,
"Origin": "USA",
"Miles_per_Gallon": 14.0,
"Name": "plymouth 'cuda 340",
"index": 16,
"Acceleration": 8.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3609,
"Cylinders": 8,
"Displacement": 340.0
},
{
"Horsepower": 140.0,
"Origin": "USA",
"Miles_per_Gallon": null,
"Name": "ford mustang boss 302",
"index": 17,
"Acceleration": 8.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3353,
"Cylinders": 8,
"Displacement": 302.0
},
{
"Horsepower": 150.0,
"Origin": "USA",
"Miles_per_Gallon": 15.0,
"Name": "chevrolet monte carlo",
"index": 18,
"Acceleration": 9.5,
"Year": "1970-01-01",
"Weight_in_lbs": 3761,
"Cylinders": 8,
"Displacement": 400.0
},
{
"Horsepower": 225.0,
"Origin": "USA",
"Miles_per_Gallon": 14.0,
"Name": "buick estate wagon (sw)",
"index": 19,
"Acceleration": 10.0,
"Year": "1970-01-01",
"Weight_in_lbs": 3086,
"Cylinders": 8,
"Displacement": 455.0
},
{
"Horsepower": 95.0,
"Origin": "Japan",
"Miles_per_Gallon": 24.0,
"Name": "toyota corona mark ii",
"index": 20,
"Acceleration": 15.0,
"Year": "1970-01-01",
"Weight_in_lbs": 2372,
"Cylinders": 4,
"Displacement": 113.0
},
{
"Horsepower": 95.0,
"Origin": "USA",
"Miles_per_Gallon": 22.0,
"Name": "plymouth duster",
"index": 21,
"Acceleration": 15.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2833,
"Cylinders": 6,
"Displacement": 198.0
},
{
"Horsepower": 97.0,
"Origin": "USA",
"Miles_per_Gallon": 18.0,
"Name": "amc hornet",
"index": 22,
"Acceleration": 15.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2774,
"Cylinders": 6,
"Displacement": 199.0
},
{
"Horsepower": 85.0,
"Origin": "USA",
"Miles_per_Gallon": 21.0,
"Name": "ford maverick",
"index": 23,
"Acceleration": 16.0,
"Year": "1970-01-01",
"Weight_in_lbs": 2587,
"Cylinders": 6,
"Displacement": 200.0
},
{
"Horsepower": 88.0,
"Origin": "Japan",
"Miles_per_Gallon": 27.0,
"Name": "datsun pl510",
"index": 24,
"Acceleration": 14.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2130,
"Cylinders": 4,
"Displacement": 97.0
},
{
"Horsepower": 46.0,
"Origin": "Europe",
"Miles_per_Gallon": 26.0,
"Name": "volkswagen 1131 deluxe sedan",
"index": 25,
"Acceleration": 20.5,
"Year": "1970-01-01",
"Weight_in_lbs": 1835,
"Cylinders": 4,
"Displacement": 97.0
},
{
"Horsepower": 87.0,
"Origin": "Europe",
"Miles_per_Gallon": 25.0,
"Name": "peugeot 504",
"index": 26,
"Acceleration": 17.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2672,
"Cylinders": 4,
"Displacement": 110.0
},
{
"Horsepower": 90.0,
"Origin": "Europe",
"Miles_per_Gallon": 24.0,
"Name": "audi 100 ls",
"index": 27,
"Acceleration": 14.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2430,
"Cylinders": 4,
"Displacement": 107.0
},
{
"Horsepower": 95.0,
"Origin": "Europe",
"Miles_per_Gallon": 25.0,
"Name": "saab 99e",
"index": 28,
"Acceleration": 17.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2375,
"Cylinders": 4,
"Displacement": 104.0
},
{
"Horsepower": 113.0,
"Origin": "Europe",
"Miles_per_Gallon": 26.0,
"Name": "bmw 2002",
"index": 29,
"Acceleration": 12.5,
"Year": "1970-01-01",
"Weight_in_lbs": 2234,
"Cylinders": 4,
"Displacement": 121.0
}
],
"schema": {
"primaryKey": [
"index"
],
"fields": [
{
"name": "index",
"type": "integer"
},
{
"name": "Acceleration",
"type": "number"
},
{
"name": "Cylinders",
"type": "integer"
},
{
"name": "Displacement",
"type": "number"
},
{
"name": "Horsepower",
"type": "number"
},
{
"name": "Miles_per_Gallon",
"type": "number"
},
{
"name": "Name",
"type": "string"
},
{
"name": "Origin",
"type": "string"
},
{
"name": "Weight_in_lbs",
"type": "integer"
},
{
"name": "Year",
"type": "string"
}
],
"pandas_version": "0.20.0"
}
}
} | the_stack |
* DescribeCallBackStatus请求参数结构体
*/
export interface DescribeCallBackStatusRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 回拨请求响应中返回的 callId
*/
CallId: string
/**
* 主叫号码
*/
Src?: string
/**
* 被叫号码
*/
Dst?: string
/**
* 通话最后状态:0:未知状态 1:主叫响铃中 2:主叫接听 3:被叫响铃中 4:正常通话中 5:通话结束
*/
CallStatus?: string
}
/**
* DescribeCallBackCdr请求参数结构体
*/
export interface DescribeCallBackCdrRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 回拨请求响应中返回的 callId,按 callId 查询该话单详细信息
*/
CallId?: string
/**
* 查询主叫用户产生的呼叫话单,如填空表示拉取这个时间段所有话单
*/
Src?: string
/**
* 话单开始时间戳
*/
StartTimeStamp?: string
/**
* 话单结束时间戳
*/
EndTimeStamp?: string
}
/**
* CreateCallBack请求参数结构体
*/
export interface CreateCallBackRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 主叫号码(必须为 11 位手机号,号码前加 0086,如 008613631686024)
*/
Src: string
/**
* 被叫号码(必须为 11 位手机或固话号码,号码前加 0086,如008613631686024,固话如:0086075586013388)
*/
Dst: string
/**
* 主叫显示系统分配的固话号码,如不填显示随机分配号码
*/
SrcDisplayNum?: string
/**
* 被叫显示系统分配的固话号码,如不填显示随机分配号码
*/
DstDisplayNum?: string
/**
* 是否录音,0 表示不录音,1 表示录音。默认为不录音
*/
Record?: string
/**
* 允许最大通话时间,不填默认为 30 分钟(单位:分钟)
*/
MaxAllowTime?: string
/**
* 主叫发起呼叫状态:1 被叫发起呼叫状态:256 主叫响铃状态:2 被叫响铃状态:512 主叫接听状态:4 被叫接听状态:1024 主叫拒绝接听状态:8 被叫拒绝接听状态:2048 主叫正常挂机状态:16 被叫正常挂机状态:4096 主叫呼叫异常:32 被叫呼叫异常:8192
例如:当值为 0:表示所有状态不需要推送;当值为 4:表示只要推送主叫接听状态;当值为 16191:表示所有状态都需要推送(上面所有值和)
*/
StatusFlag?: string
/**
* 状态回调通知地址,正式环境可以配置默认推送地址
*/
StatusUrl?: string
/**
* 话单回调通知地址,正式环境可以配置默认推送地址
*/
HangupUrl?: string
/**
* 录单 URL 回调通知地址,正式环境可以配置默认推送地址
*/
RecordUrl?: string
/**
* 业务应用 key,业务用该 key 可以区分内部业务或客户产品等,该 key 需保证在该 appId 下全局唯一,最大长度不超过 64 个字节,bizId 只能包含数字、字母。
*/
BizId?: string
/**
* 最后一次呼叫 callId,带上该字段以后,平台会参考该 callId 分配线路,优先不分配该 callId 通话线路(注:谨慎使用,这个会影响线路调度)
*/
LastCallId?: string
/**
* 结构体,主叫呼叫预处理操作,根据不同操作确认是否呼通被叫。如需使用,本结构体需要与 keyList 结构体配合使用,此时这两个参数都为必填项
*/
PreCallerHandle?: RreCallerHandle
/**
* 订单 ID,最大长度不超过64个字节,对于一些有订单状态 App 相关应用使用(如达人帮接入 App 应用),该字段只在帐单中带上,其它回调不附带该字段
*/
OrderId?: string
}
/**
* DeleteCallBack请求参数结构体
*/
export interface DeleteCallBackRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 回拨请求响应中返回的 callId
*/
CallId: string
/**
* 0:不管通话状态直接拆线(默认) 1:主叫响铃以后状态不拆线 2:主叫接听以后状态不拆线 3:被叫响铃以后状态不拆线 4:被叫接听以后状态不拆线
*/
CancelFlag?: string
}
/**
* GetVirtualNum返回参数结构体
*/
export interface GetVirtualNumResponse {
/**
* 错误码
*/
ErrorCode?: string
/**
* 绑定 ID,该 ID 全局唯一
注意:此字段可能返回 null,表示取不到有效值。
*/
BindId?: string
/**
* 中间号还剩引用计数,如果计数为 0 会解绑
注意:此字段可能返回 null,表示取不到有效值。
*/
RefNum?: string
/**
* 中间号
注意:此字段可能返回 null,表示取不到有效值。
*/
VirtualNum?: string
/**
* 错误原因
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DelVirtualNum返回参数结构体
*/
export interface DelVirtualNumResponse {
/**
* 错误码
*/
ErrorCode?: string
/**
* 错误信息
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 绑定 ID,该 ID 全局唯一
注意:此字段可能返回 null,表示取不到有效值。
*/
BindId?: string
/**
* 中间号还剩引用计数,如果计数为 0 会解绑
注意:此字段可能返回 null,表示取不到有效值。
*/
RefLeftNum?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 话单详情
*/
export interface CallBackCdr {
/**
* 呼叫通话 ID
*/
CallId: string
/**
* 主叫号码
*/
Src: string
/**
* 被叫号码
*/
Dst: string
/**
* 主叫呼叫开始时间
*/
StartSrcCallTime: string
/**
* 主叫响铃开始时间
*/
StartSrcRingTime: string
/**
* 主叫接听时间
*/
SrcAcceptTime: string
/**
* 被叫呼叫开始时间
*/
StartDstCallTime: string
/**
* 被叫响铃开始时间
*/
StartDstRingTime: string
/**
* 被叫接听时间
*/
DstAcceptTime: string
/**
* 用户挂机通话结束时间
*/
EndCallTime: string
/**
* 通话最后状态:0:未知状态 1:正常通话 2:主叫未接 3:主叫接听,被叫未接 4:主叫未接通 5:被叫未接通
*/
CallEndStatus: string
/**
* 通话计费时间
*/
Duration: string
/**
* 录音 URL,如果不录音或录音失败,该值为空
*/
RecordUrl: string
/**
* 通话类型(1: VOIP 2:IP TO PSTN 3: PSTN TO PSTN),如果话单中没有该字段,默认值为回拨 3 (PSTN TO PSTN)
注意:此字段可能返回 null,表示取不到有效值。
*/
CallType: string
/**
* 同回拨请求中的 bizId,如果回拨请求中带 bizId 会有该字段返回
注意:此字段可能返回 null,表示取不到有效值。
*/
BizId: string
/**
* 订单 ID,最大长度不超过 64 个字节,对于一些有订单状态 App 相关应用(如达人帮接入 App 应用),该字段只在帐单中带上,其它回调不附带该字段
注意:此字段可能返回 null,表示取不到有效值。
*/
OrderId: string
}
/**
* 结构体,主叫呼叫预处理操作,根据不同操作确认是否呼通被叫。如需使用,本结构体需要与 keyList 结构体配合使用,此时这两个参数都为必填项
*/
export interface RreCallerHandle {
/**
* 呼叫主叫以后,给主叫用户的语音提示,播放该提示时用户所有按键无效
*/
ReadPrompt: string
/**
* 可中断提示,播放该提示时,用户可以按键
*/
InterruptPrompt: string
/**
* 对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
*/
KeyList: Array<KeyList>
/**
* 最多重复播放次数,超过该次数拆线
*/
RepeatTimes: string
/**
* 用户按键回调通知地址,如果为空不回调
*/
KeyPressUrl: string
/**
* 提示音男声女声:1女声,2男声。默认女声
*/
PromptGender: string
}
/**
* DescribeCallerDisplayList请求参数结构体
*/
export interface DescribeCallerDisplayListRequest {
/**
* 业务appid
*/
BizAppId: string
}
/**
* DescribeCallerDisplayList返回参数结构体
*/
export interface DescribeCallerDisplayListResponse {
/**
* appid
注意:此字段可能返回 null,表示取不到有效值。
*/
AppId?: string
/**
* 主叫显号号码集合,codeList[0...*] 结构体数组,如果业务是主被叫互显,该字段为空
注意:此字段可能返回 null,表示取不到有效值。
*/
CodeList?: Array<CallBackPhoneCode>
/**
* 错误码
*/
ErrorCode?: string
/**
* 错误原因
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 回拨号码字段
*/
export interface CallBackPhoneCode {
/**
* 国家码,统一以 00 开头
*/
Nation: string
/**
* 号码(固话区号前加 0,如075586013388)
*/
Phone: string
}
/**
* CreateCallBack返回参数结构体
*/
export interface CreateCallBackResponse {
/**
* 话单id
注意:此字段可能返回 null,表示取不到有效值。
*/
CallId?: string
/**
* 主叫显示系统分配的固话号码
注意:此字段可能返回 null,表示取不到有效值。
*/
SrcDisplayNum?: string
/**
* 被叫显示系统分配的固话号码
注意:此字段可能返回 null,表示取不到有效值。
*/
DstDisplayNum?: string
/**
* 错误码
*/
ErrorCode?: string
/**
* 错误原因
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DelVirtualNum请求参数结构体
*/
export interface DelVirtualNumRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 双方号码 + 中间号绑定 ID,该 ID 全局唯一
*/
BindId: string
/**
* 应用二级业务 ID,bizId 需保证在该 appId 下全局唯一,最大长度不超过 16 个字节。
*/
BizId?: string
}
/**
* GetVirtualNum请求参数结构体
*/
export interface GetVirtualNumRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 被叫号码(号码前加 0086,如 008613631686024)
*/
Dst: string
/**
* 主叫号码(号码前加 0086,如 008613631686024),xb 模式下是不用填写,axb 模式下是必选
*/
Src?: string
/**
* {“accreditList”:[“008613631686024”,”008612345678910”]},主要用于 N-1 场景,号码绑定非共享是独占型,指定了 dst 独占中间号绑定,accreditList 表示这个列表成员可以拨打 dst 绑 定的中间号,默认值为空,表示所有号码都可以拨打独占型中间号绑定,最大集合不允许超过 30 个,仅适用于xb模式
*/
AccreditList?: Array<string>
/**
* 指定中间号(格式:008617013541251),如果该中间号已被使用则返回绑定失败。如果不带该字段则由腾讯侧从号码池里自动分配
*/
AssignVirtualNum?: string
/**
* 是否录音,0表示不录音,1表示录音。默认为不录音,注意如果需要录音回调,通话完成后需要等待一段时间,收到录音回调之后,再解绑中间号。
*/
Record?: string
/**
* 主被叫显号号码归属地,指定该参数说明显号归属该城市,如果没有该城市号码会随机选取一个城市或者后台配置返回107,返回码详见 《腾讯-中间号-城市id.xlsx》
*/
CityId?: string
/**
* 应用二级业务 ID,bizId 需保证在该 appId 下全局唯一,最大长度不超过 16 个字节。
*/
BizId?: string
/**
* 号码最大绑定时间,不填默认为 24 小时,最长绑定时间是168小时,单位秒
*/
MaxAssignTime?: string
/**
* 主叫发起呼叫状态:1
被叫发起呼叫状态:256
主叫响铃状态:2
被叫响铃状态:512
主叫接听状态:4
被叫接听状态:1024
主叫拒绝接听状态:8
被叫拒绝接听状态:2048
主叫正常挂机状态:16
被叫正常挂机状态:4096
主叫呼叫异常:32
被叫呼叫异常:8192
例如:
值为 0:表示所有状态不需要推送
值为 4:表示只要推送主叫接听状态
值为 16191:表示所有状态都需要推送(上面所有值和)
*/
StatusFlag?: string
/**
* 请填写statusFlag并设置值,状态回调通知地址,正式环境可以配置默认推送地址
*/
StatusUrl?: string
/**
* 话单回调通知地址,正式环境可以配置默认推送地址
*/
HangupUrl?: string
/**
* 录单 URL 回调通知地址,正式环境可以配置默认推送地址
*/
RecordUrl?: string
}
/**
* DeleteCallBack返回参数结构体
*/
export interface DeleteCallBackResponse {
/**
* 错误码
*/
ErrorCode?: string
/**
* 错误原因
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 话单id
注意:此字段可能返回 null,表示取不到有效值。
*/
CallId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* Get400Cdr请求参数结构体
*/
export interface Get400CdrRequest {
/**
* 业务appid
*/
BizAppId: string
/**
* 通话唯一标识 callId,即直拨呼叫响应中返回的 callId
*/
CallId?: string
/**
* 查询主叫用户产生的呼叫话单(0086开头),设置为空表示拉取该时间段的所有话单
*/
Src?: string
/**
* 话单开始时间戳
*/
StartTimeStamp?: string
/**
* 话单结束时间戳
*/
EndTimeStamp?: string
}
/**
* DescribeCallBackCdr返回参数结构体
*/
export interface DescribeCallBackCdrResponse {
/**
* 话单列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Cdr?: Array<CallBackCdr>
/**
* 偏移
注意:此字段可能返回 null,表示取不到有效值。
*/
Offset?: string
/**
* 错误码
注意:此字段可能返回 null,表示取不到有效值。
*/
ErrorCode?: string
/**
* 错误原因
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 对应按键操作,如果没有结构体里定义按键操作用户按键以后都从 interruptPrompt 重新播放
*/
export interface KeyList {
/**
* 用户按键(0-9、*、#、A-D)
*/
Key: string
/**
* 1: 呼通被叫 2:interruptPrompt 重播提示 3:拆线
*/
Operate: string
}
/**
* 直拨话单详情
*/
export interface VirturalNumCdr {
/**
* 呼叫通话 ID
*/
CallId: string
/**
* 双方号码 + 中间号绑定 ID,该 ID 全局唯一
*/
BindId: string
/**
* 主叫号码
*/
Src: string
/**
* 被叫号码
*/
Dst: string
/**
* 主叫通讯录直拨虚拟保护号码
*/
DstVirtualNum: string
/**
* 虚拟保护号码平台收到呼叫时间
*/
CallCenterAcceptTime: string
/**
* 被叫呼叫开始时间
*/
StartDstCallTime: string
/**
* 被叫响铃开始时间
*/
StartDstRingTime: string
/**
* 被叫接听时间
*/
DstAcceptTime: string
/**
* 用户挂机通话结束时间
*/
EndCallTime: string
/**
* 通话最后状态:0:未知状态 1:正常通话 2:查询呼叫转移被叫号异常 3:未接通 4:未接听 5:拒接挂断 6:关机 7:空号 8:通话中 9:欠费 10:运营商线路或平台异常
*/
CallEndStatus: string
/**
* 主叫接通虚拟保护号码到通话结束通话时间
*/
SrcDuration: string
/**
* 呼叫转接被叫接通到通话结束通话时间
*/
DstDuration: string
/**
* 录音 URL,如果不录音或录音失败,该值为空
*/
RecordUrl: string
}
/**
* Get400Cdr返回参数结构体
*/
export interface Get400CdrResponse {
/**
* 错误码
*/
ErrorCode?: string
/**
* 错误原因
注意:此字段可能返回 null,表示取不到有效值。
*/
Msg?: string
/**
* 偏移
注意:此字段可能返回 null,表示取不到有效值。
*/
Offset?: string
/**
* 话单列表
注意:此字段可能返回 null,表示取不到有效值。
*/
Cdr?: Array<VirturalNumCdr>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeCallBackStatus返回参数结构体
*/
export interface DescribeCallBackStatusResponse {
/**
* 错误码
*/
ErrorCode?: string
/**
* 错误信息
*/
Msg?: string
/**
* 业务appid
*/
AppId?: string
/**
* 回拨请求响应中返回的 callId
*/
CallId?: string
/**
* 主叫号码
*/
Src?: string
/**
* 被叫号码
*/
Dst?: string
/**
* 通话最后状态:0:未知状态 1:主叫响铃中 2:主叫接听 3:被叫响铃中 4:正常通话中 5:通话结束
*/
CallStatus?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
} | the_stack |
import * as ABIDecoder from "abi-decoder";
import * as _ from "lodash";
import * as omit from "lodash.omit";
import * as singleLineString from "single-line-string";
import * as Web3 from "web3";
// Utils
import { BigNumber } from "../../../utils/bignumber";
import { NULL_ADDRESS } from "../../../utils/constants";
import * as TransactionUtils from "../../../utils/transaction_utils";
import { Web3Utils } from "../../../utils/web3_utils";
// Apis
import { ContractsAPI } from "../../apis";
// Invariants
import { Assertions } from "../../invariants";
// Types
import { DebtOrderData, DebtRegistryEntry, RepaymentSchedule, TxData } from "../../types";
import { ERC721CollateralizedLoanTerms } from "./loan_terms";
import { SimpleInterestLoanTerms } from "../simple_interest_loan_terms";
import {
SimpleInterestLoanOrder,
SimpleInterestTermsContractParameters,
} from "../simple_interest_loan_adapter";
// Adapter
import { Adapter } from "../adapter";
// Wrappers
import { ERC721TokenContract } from "../../wrappers";
// Schema
import { erc721CollateralizedSimpleInterestLoanOrder } from "../../schemas/erc721_collateralized_simple_interest_loan_order_schema";
const TRANSFER_GAS_MAXIMUM = 200000;
// Extend order to include parameters necessary for an ERC721-collateralized terms contract.
export interface ERC721CollateralizedSimpleInterestLoanOrder extends SimpleInterestLoanOrder {
isEnumerable: boolean;
erc721Symbol: string;
// Can be an ID or an index.
tokenReference: BigNumber;
}
export interface ERC721CollateralizedTermsContractParameters {
isEnumerable: BigNumber;
erc721ContractIndex: BigNumber;
// Can be an ID or an index.
tokenReference: BigNumber;
}
export interface ERC721CollateralizedSimpleInterestTermsContractParameters
extends SimpleInterestTermsContractParameters,
ERC721CollateralizedTermsContractParameters {}
export const ERC721CollateralizerAdapterErrors = {
INVALID_CONTRACT_INDEX: (tokenIndex: BigNumber) =>
singleLineString`Invalid index for ERC721 Token Registry: ${tokenIndex.toString()}.`,
INVALID_IS_ENUMERABLE_FLAG: () =>
singleLineString`isEnumerable should be 0 (if false) or 1 (if true).`,
INVALID_TOKEN_REFERENCE: () =>
singleLineString`Token Reference must be a valid token index or token ID.`,
COLLATERAL_NOT_FOUND: (agreementId: string) =>
singleLineString`Collateral was not found for given agreement ID ${agreementId}. Make sure
that the agreement ID is correct, and that the collateral has not already
been withdrawn.`,
INVALID_DECIMAL_VALUE: () => singleLineString`Values cannot be expressed as decimals.`,
TOKEN_REFERENCE_EXCEEDS_MAXIMUM: () => singleLineString`Token reference exceeds maximum value.`,
MISMATCHED_TOKEN_SYMBOL: (tokenAddress: string, symbol: string) =>
singleLineString`Terms contract parameters are invalid for the given debt order.
Token at address ${tokenAddress} does not
correspond to specified token with symbol ${symbol}`,
MISMATCHED_TERMS_CONTRACT: (termsContractAddress: string) =>
singleLineString`Terms contract at address ${termsContractAddress} is not
a ERC721CollateralizedSimpleInterestTermsContract. As such, this adapter
will not interface with the terms contract as expected`,
TOKEN_REFERENCE_NOT_FOUND: (tokenReference: BigNumber) =>
singleLineString`Token not found with given reference: ${tokenReference.toString()}`,
COLLATERALIZER_APPROVAL_NOT_GRANTED: () =>
singleLineString`Collateralizer contract not granted approval for token transfer`,
DEBT_NOT_YET_REPAID: (agreementId: string) =>
singleLineString`Debt has not been fully repaid for loan with agreement ID ${agreementId}`,
LOAN_NOT_IN_DEFAULT: (agreementId: string) =>
singleLineString`Loan with agreement ID ${agreementId} is not currently in a state of default`,
};
export class ERC721CollateralizedSimpleInterestLoanAdapter implements Adapter {
private assert: Assertions;
private readonly contractsAPI: ContractsAPI;
private simpleInterestLoanTerms: SimpleInterestLoanTerms;
private collateralizedLoanTerms: ERC721CollateralizedLoanTerms;
private web3Utils: Web3Utils;
private web3: Web3;
public constructor(web3: Web3, contractsAPI: ContractsAPI) {
this.assert = new Assertions(web3, contractsAPI);
this.web3Utils = new Web3Utils(web3);
this.web3 = web3;
this.contractsAPI = contractsAPI;
this.simpleInterestLoanTerms = new SimpleInterestLoanTerms(web3, contractsAPI);
this.collateralizedLoanTerms = new ERC721CollateralizedLoanTerms(web3, contractsAPI);
}
public async toDebtOrder(
collateralizedSimpleInterestLoanOrder: ERC721CollateralizedSimpleInterestLoanOrder,
): Promise<DebtOrderData> {
this.assert.schema.erc721CollateralizedSimpleInterestLoanOrder(
"erc721CollateralizedSimpleInterestLoanOrder",
collateralizedSimpleInterestLoanOrder,
);
const {
// destructure simple interest loan order params.
principalTokenSymbol,
principalAmount,
interestRate,
amortizationUnit,
termLength,
// destructure erc721-collateralized loan order params.
isEnumerable,
erc721Symbol,
tokenReference,
} = collateralizedSimpleInterestLoanOrder;
const principalToken = await this.contractsAPI.loadTokenBySymbolAsync(principalTokenSymbol);
const principalTokenIndex = await this.contractsAPI.getTokenIndexBySymbolAsync(
principalTokenSymbol,
);
const erc721ContractIndex = await this.contractsAPI.getERC721IndexBySymbolAsync(
erc721Symbol,
);
const collateralizedContract = await this.contractsAPI.loadERC721CollateralizedSimpleInterestTermsContract();
let debtOrderData: DebtOrderData = omit(collateralizedSimpleInterestLoanOrder, [
// omit the simple interest parameters that will be packed
// into the `termsContractParameters`.
"principalTokenSymbol",
"interestRate",
"amortizationUnit",
"termLength",
// omit the collateralized parameters that will be packed into
// the `termsContractParameters`.
"erc721Symbol",
"tokenReference",
"isEnumerable",
]);
// Our final output is the perfect union of the packed simple interest params and the packed
// erc721-collateralized params.
const packedParams = this.packParameters(
{
principalTokenIndex,
principalAmount,
interestRate,
amortizationUnit,
termLength,
},
{
// We convert the isEnumerable var from boolean to bit flag.
isEnumerable: isEnumerable ? new BigNumber(1) : new BigNumber(0),
erc721ContractIndex,
tokenReference,
},
);
debtOrderData = {
...debtOrderData,
principalToken: principalToken.address,
termsContract: collateralizedContract.address,
termsContractParameters: packedParams,
};
return TransactionUtils.applyNetworkDefaults(debtOrderData, this.contractsAPI);
}
/**
* Validates that the basic invariants have been met for a given
* ERC721CollateralizedSimpleInterestLoanOrder.
*
* @param {ERC721CollateralizedSimpleInterestLoanOrder} loanOrder
* @returns {Promise<void>}
*/
public async validateAsync(loanOrder: ERC721CollateralizedSimpleInterestLoanOrder) {
const unpackedParams = this.unpackParameters(loanOrder.termsContractParameters);
await this.collateralizedLoanTerms.assertValidParams(unpackedParams);
await this.assertCollateralApprovalInvariantsAsync(loanOrder);
}
/**
* Given a valid debt order, returns a promise for a CollateralizedSimpleInterestLoanOrder,
* which includes the DebtOrder information as well as as the contract terms (see documentation
* on the `CollateralizedSimpleInterestLoanOrder` interface for more information.)
*
* @param {DebtOrderData} debtOrderData
* @returns {Promise<CollateralizedSimpleInterestLoanOrder>}
*/
public async fromDebtOrder(
debtOrderData: DebtOrderData,
): Promise<ERC721CollateralizedSimpleInterestLoanOrder> {
this.assert.schema.debtOrderWithTermsSpecified("debtOrder", debtOrderData);
const {
principalTokenIndex,
erc721ContractIndex,
isEnumerable,
...params
} = this.unpackParameters(debtOrderData.termsContractParameters);
const principalTokenSymbol = await this.contractsAPI.getTokenSymbolByIndexAsync(
principalTokenIndex,
);
const erc721Symbol = await this.contractsAPI.getERC721SymbolByIndexAsync(
erc721ContractIndex,
);
// Assert that the principal token corresponds to the symbol we've unpacked.
await this.assertERC20TokenCorrespondsToSymbol(
debtOrderData.principalToken,
principalTokenSymbol,
);
return {
...debtOrderData,
principalTokenSymbol,
...params,
// We convert the bit flag into a boolean.
isEnumerable: isEnumerable.toString() === "1",
erc721Symbol,
};
}
/**
* Given a valid DebtRegistryEntry, returns a CollateralizedSimpleInterestLoanOrder.
*
* @param {DebtRegistryEntry} entry
* @returns {Promise<CollateralizedSimpleInterestLoanOrder>}
*/
public async fromDebtRegistryEntry(
entry: DebtRegistryEntry,
): Promise<ERC721CollateralizedSimpleInterestLoanOrder> {
await this.assertIsERC721CollateralizedSimpleInterestTermsContract(entry.termsContract);
const {
principalTokenIndex,
erc721ContractIndex,
isEnumerable,
...params
} = this.unpackParameters(entry.termsContractParameters);
const principalTokenSymbol = await this.contractsAPI.getTokenSymbolByIndexAsync(
principalTokenIndex,
);
const erc721Symbol = await this.contractsAPI.getERC721SymbolByIndexAsync(
erc721ContractIndex,
);
const loanOrder: ERC721CollateralizedSimpleInterestLoanOrder = {
principalTokenSymbol,
erc721Symbol,
isEnumerable: isEnumerable.toString() === "1",
...params,
};
return loanOrder;
}
/**
* Given a valid DebtRegistryEntry, returns an array of repayment dates (as unix timestamps.)
*
* @example
* adapter.getRepaymentSchedule(debtEntry);
* => [1521506879]
*
* @param {DebtRegistryEntry} debtEntry
* @returns {number[]}
*/
public getRepaymentSchedule(debtEntry: DebtRegistryEntry): number[] {
const { termsContractParameters, issuanceBlockTimestamp } = debtEntry;
const { termLength, amortizationUnit } = this.unpackParameters(termsContractParameters);
return new RepaymentSchedule(
amortizationUnit,
termLength,
issuanceBlockTimestamp.toNumber(),
).toArray();
}
/**
* Seizes the collateral from the given debt agreement and
* transfers it to the debt agreement's beneficiary.
*
* @param {string} agreementId
* @param {TxData} options
* @returns {Promise<string>} The transaction's hash.
*/
public async seizeCollateralAsync(agreementId: string, options?: TxData): Promise<string> {
this.assert.schema.bytes32("agreementId", agreementId);
const defaultOptions = await this.getTxDefaultOptions();
const transactionOptions = _.assign(defaultOptions, options);
await this.assertDebtAgreementExists(agreementId);
await this.assertCollateralSeizeable(agreementId);
const collateralizerContract = await this.contractsAPI.loadERC721CollateralizerAsync();
return collateralizerContract.seizeCollateral.sendTransactionAsync(
agreementId,
transactionOptions,
);
}
/**
* Returns collateral to the debt agreement's original collateralizer
* if and only if the debt agreement's term has lapsed and
* the total expected repayment value has been repaid.
*
* @param {string} agreementId
* @param {TxData} options
* @returns {Promise<string>} The transaction's hash.
*/
public async returnCollateralAsync(agreementId: string, options?: TxData): Promise<string> {
this.assert.schema.bytes32("agreementId", agreementId);
await this.assertDebtAgreementExists(agreementId);
await this.assertCollateralReturnable(agreementId);
const defaultOptions = await this.getTxDefaultOptions();
const transactionOptions = _.assign(defaultOptions, options);
const collateralizerContract = await this.contractsAPI.loadERC721CollateralizerAsync();
return collateralizerContract.returnCollateral.sendTransactionAsync(
agreementId,
transactionOptions,
);
}
public unpackParameters(
termsContractParameters: string,
): ERC721CollateralizedSimpleInterestTermsContractParameters {
const simpleInterestParams = this.simpleInterestLoanTerms.unpackParameters(
termsContractParameters,
);
const collateralizedParams = this.collateralizedLoanTerms.unpackParameters(
termsContractParameters,
);
return {
...simpleInterestParams,
...collateralizedParams,
};
}
public packParameters(
simpleTermsParams: SimpleInterestTermsContractParameters,
collateralTermsParams: ERC721CollateralizedTermsContractParameters,
): string {
const packedSimpleInterestParams = this.simpleInterestLoanTerms.packParameters(
simpleTermsParams,
);
const packedCollateralizedParams = this.collateralizedLoanTerms.packParameters(
collateralTermsParams,
);
// Our final output is the perfect union of the packed simple interest params and the packed
// erc-721 collateralized params.
return packedSimpleInterestParams.substr(0, 39) + packedCollateralizedParams.substr(39, 27);
}
/**
* Given an agreement ID for a valid collateralized debt agreement, returns true if the
* collateral is returnable according to the terms of the agreement - I.E. the debt
* has been repaid, and the collateral has not already been withdrawn.
*
* @example
* await adapter.canReturnCollateral(
* "0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f"
* );
* => true
*
* @param {string} agreementId
* @returns {Promise<boolean>}
*/
public async canReturnCollateral(agreementId: string): Promise<boolean> {
try {
await this.assertCollateralReturnable(agreementId);
return true;
} catch (e) {
return false;
}
}
/**
* Given an agreement ID for a valid collateralized debt agreement, returns true if the
* collateral can be seized by the creditor, according to the terms of the agreement. Collateral
* is seizable if the collateral has not been withdrawn yet, and the loan has been in a state
* of default.
*
* @example
* await adapter.canSeizeCollateral(
* "0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f"
* );
* => true
*
* @param {string} agreementId
* @returns {Promise<boolean>}
*/
public async canSeizeCollateral(agreementId: string): Promise<boolean> {
try {
await this.assertCollateralSeizeable(agreementId);
return true;
} catch (e) {
return false;
}
}
/**
* Returns true if the collateral associated with the given agreement ID
* has already been seized or returned.
*
* @example
* await adapter.isCollateralWithdrawn(
* "0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f"
* );
* => true
*
* @param {string} agreementId
* @returns {Promise<boolean>}
*/
public async isCollateralWithdrawn(agreementId: string): Promise<boolean> {
const collateralizerContract = await this.contractsAPI.loadERC721CollateralizerAsync();
const debtorAddress = await collateralizerContract.agreementToDebtor.callAsync(agreementId);
return debtorAddress === NULL_ADDRESS;
}
/**
* Eventually returns true if the collateral associated with the given debt agreement ID
* was returned to the debtor.
*
* @example
* await adapter.isCollateralReturned("0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f")
* => true
*
* @param {string} agreementId
* @returns {Promise<boolean>}
*/
public async isCollateralReturned(agreementId: string): Promise<boolean> {
return this.eventEmittedForAgreement("CollateralReturned", agreementId);
}
/**
* Eventually returns true if the collateral associated with the given debt agreement ID
* was seized by the creditor.
*
* @example
* await adapter.isCollateralSeized("0x21eee309abd17832e55d231fb4147334081ed6da543d226c035d4b2420c68a7f")
* => true
*
* @param {string} agreementId
* @returns {Promise<boolean>}
*/
public async isCollateralSeized(agreementId: string): Promise<boolean> {
return this.eventEmittedForAgreement("CollateralSeized", agreementId);
}
private async eventEmittedForAgreement(
eventName: string,
agreementId: string,
): Promise<boolean> {
// Collateralizer contract is required for decoding logs.
const collateralizer = await this.contractsAPI.loadERC721CollateralizerAsync();
const collateralizerAddress = collateralizer.address;
return new Promise<boolean>((resolve, reject) => {
this.web3.eth
.filter({
address: collateralizerAddress,
fromBlock: 1,
toBlock: "latest",
topics: [null, agreementId, null],
})
.get((err, result) => {
if (err) {
reject(err);
}
ABIDecoder.addABI(collateralizer.abi);
const decodedResults = ABIDecoder.decodeLogs(result);
ABIDecoder.removeABI(collateralizer.abi);
const collateralReturnedEvent = _.find(decodedResults, (log: any) => {
const foundEvent = _.find(log.events, (event: any) => {
return event.name === "agreementID" && event.value === agreementId;
});
return log.name === eventName && foundEvent;
});
resolve(!_.isUndefined(collateralReturnedEvent));
});
});
}
private async assertERC20TokenCorrespondsToSymbol(
tokenAddress: string,
symbol: string,
): Promise<void> {
const doesTokenCorrespondToSymbol = await this.contractsAPI.doesTokenCorrespondToSymbol(
tokenAddress,
symbol,
);
if (!doesTokenCorrespondToSymbol) {
throw new Error(
ERC721CollateralizerAdapterErrors.MISMATCHED_TOKEN_SYMBOL(tokenAddress, symbol),
);
}
}
private async assertIsERC721CollateralizedSimpleInterestTermsContract(
termsContractAddress: string,
): Promise<void> {
const termsContract = await this.contractsAPI.loadERC721CollateralizedSimpleInterestTermsContract();
if (termsContractAddress !== termsContract.address) {
throw new Error(
ERC721CollateralizerAdapterErrors.MISMATCHED_TERMS_CONTRACT(termsContractAddress),
);
}
}
private async assertDebtAgreementExists(agreementId: string): Promise<void> {
const debtTokenContract = await this.contractsAPI.loadDebtTokenAsync();
return this.assert.debtAgreement.exists(
agreementId,
debtTokenContract,
ERC721CollateralizerAdapterErrors.COLLATERAL_NOT_FOUND(agreementId),
);
}
/**
* Collateral is seizable if the collateral has not been withdrawn yet, and the
* loan is in a state of default.
*
* @param {string} agreementId
* @returns {Promise<void>}
*/
private async assertCollateralSeizeable(agreementId: string): Promise<void> {
const debtRegistry = await this.contractsAPI.loadDebtRegistryAsync();
const [termsContract, termsContractParameters] = await debtRegistry.getTerms.callAsync(
agreementId,
);
const unpackedParams = this.unpackParameters(termsContractParameters);
await this.collateralizedLoanTerms.assertValidParams(unpackedParams);
await this.assertCollateralNotWithdrawn(agreementId);
await this.assertDefaulted(agreementId);
}
private async assertDefaulted(agreementId: string): Promise<void> {
const defaulted = await this.defaulted(agreementId);
if (!defaulted) {
throw new Error(ERC721CollateralizerAdapterErrors.LOAN_NOT_IN_DEFAULT(agreementId));
}
}
private async defaulted(agreementId: string): Promise<boolean> {
const termsContract = await this.contractsAPI.loadERC721CollateralizedSimpleInterestTermsContract();
const repaymentToDate = await termsContract.getValueRepaidToDate.callAsync(agreementId);
const currentTime = await this.web3Utils.getCurrentBlockTime();
const minimumRepayment = await termsContract.getExpectedRepaymentValue.callAsync(
agreementId,
new BigNumber(currentTime),
);
return repaymentToDate.lt(minimumRepayment);
}
/**
* Collateral is returnable if the debt is repaid, and the collateral has not yet
* been withdrawn.
*
* @param {string} agreementId
* @returns {Promise<void>}
*/
private async assertCollateralReturnable(agreementId: string): Promise<void> {
const debtRegistry = await this.contractsAPI.loadDebtRegistryAsync();
const [termsContract, termsContractParameters] = await debtRegistry.getTerms.callAsync(
agreementId,
);
const unpackedParams = this.unpackParameters(termsContractParameters);
await this.collateralizedLoanTerms.assertValidParams(unpackedParams);
await this.assertCollateralNotWithdrawn(agreementId);
await this.assertDebtRepaid(agreementId);
}
private async assertDebtRepaid(agreementId) {
const debtRepaid = await this.debtRepaid(agreementId);
if (!debtRepaid) {
throw new Error(ERC721CollateralizerAdapterErrors.DEBT_NOT_YET_REPAID(agreementId));
}
}
private async assertCollateralNotWithdrawn(agreementId) {
const collateralWithdrawn = await this.isCollateralWithdrawn(agreementId);
if (collateralWithdrawn) {
throw new Error(ERC721CollateralizerAdapterErrors.COLLATERAL_NOT_FOUND(agreementId));
}
}
private async assertCollateralApprovalInvariantsAsync(
order: ERC721CollateralizedSimpleInterestLoanOrder,
) {
const { erc721Symbol, tokenReference } = order;
const erc721Token: ERC721TokenContract = await this.contractsAPI.loadERC721BySymbolAsync(
erc721Symbol,
);
// Assert that the ERC721 Collateralizer has approval for transferring the asset.
const approved = await erc721Token.getApproved.callAsync(tokenReference);
const collateralizerContract = await this.contractsAPI.loadERC721CollateralizerAsync();
if (approved !== collateralizerContract.address) {
throw new Error(
ERC721CollateralizerAdapterErrors.COLLATERALIZER_APPROVAL_NOT_GRANTED(),
);
}
}
private async debtRepaid(agreementId: string): Promise<boolean> {
const termsContract = await this.contractsAPI.loadERC721CollateralizedSimpleInterestTermsContract();
const repaymentToDate = await termsContract.getValueRepaidToDate.callAsync(agreementId);
const termEnd = await termsContract.getTermEndTimestamp.callAsync(agreementId);
const expectedTotalRepayment = await termsContract.getExpectedRepaymentValue.callAsync(
agreementId,
termEnd,
);
return repaymentToDate.gte(expectedTotalRepayment);
}
private async getTxDefaultOptions(): Promise<object> {
const accounts = await this.web3Utils.getAvailableAddressesAsync();
return {
from: accounts[0],
gas: TRANSFER_GAS_MAXIMUM,
};
}
} | the_stack |
import * as OperationTypes from "./OperationTypes";
import {
createOperation,
ignoredArrayExpression,
ignoredStringLiteral,
getLastOperationTrackingResultCall,
ignoredNumericLiteral,
isInIdOfVariableDeclarator,
isInLeftPartOfAssignmentExpression,
trackingIdentifierIfExists,
ignoredCallExpression,
ignoreNode,
createSetMemoValue,
createGetMemoValue,
createGetMemoTrackingValue,
ignoredIdentifier,
ignoredObjectExpression,
skipPath,
initForBabel as initForBabelPH,
getTrackingIdentifier,
safelyGetVariableTrackingValue,
addLoc,
getGetGlobalCall,
getTrackingVarName,
createGetMemoArray
} from "./babelPluginHelpers";
import * as jsonToAst from "json-to-ast";
import { adjustColumnForEscapeSequences } from "./adjustColumnForEscapeSequences";
import OperationLog from "./helperFunctions/OperationLog";
import { ExecContext } from "./helperFunctions/ExecContext";
import { getJSONPathOffset } from "./getJSONPathOffset";
import CallExpression from "./operations/CallExpression";
import { MemberExpression } from "./operations/MemberExpression";
import ObjectExpression from "./operations/ObjectExpression";
import AssignmentExpression from "./operations/AssignmentExpression";
import traverseConcat from "./traverseConcat";
import * as MemoValueNames from "./MemoValueNames";
import { traverseDomOrigin } from "./traverseDomOrigin";
import { VERIFY } from "./config";
import { getElAttributeValueOrigin } from "./operations/domHelpers/addElOrigin";
import { safelyReadProperty, nullOnError } from "./util";
import * as FunctionNames from "./FunctionNames";
import * as sortBy from "lodash.sortby";
import { getShortExtraArgName, getShortArgName } from "./names";
function identifyTraverseFunction(operationLog, charIndex) {
return {
operationLog: operationLog.args.value,
charIndex
};
}
let t, babylon;
// This file is also imported into helperFunctions, i.e. FE code that can't load
// Babel dependencies
export function initForBabel(babelTypes, _babylon) {
t = babelTypes;
babylon = _babylon;
initForBabelPH(babelTypes);
}
interface TraversalStep {
charIndex: number;
operationLog: any;
}
function createNode(args, astArgs = null) {}
interface Shorthand {
getExec: any;
fnName: any;
visitor: any;
}
interface Operations {
[key: string]: {
argNames?: string[] | ((log: any) => string[]);
argIsArray?: boolean[] | ((log: any) => boolean[]);
createNode?: (args?: any, astArgs?: any, loc?: any) => any;
visitor?: any;
exec?: any;
// Sometimes (e.g. for string literals) we know the op result
// at compile time and can look it up for analysis later
canInferResult?: boolean | ((args: any, extraArgs: any) => boolean);
getArgumentsArray?: any;
shorthand?: Shorthand;
traverse?: (
operationLog: any,
charIndex: number,
options?: { optimistic: boolean; events?: any[] }
) => TraversalStep | undefined;
t?: any; // babel types
};
}
const leftArgName = getShortArgName("left");
const rightArgName = getShortArgName("right");
const operations: Operations = {
memberExpression: MemberExpression,
binaryExpression: {
canInferResult: function(args) {
const left = args[leftArgName];
const right = args[rightArgName];
if (!left[1] || !right[1]) {
return false;
}
if (typeof left[0] !== "string" || typeof right[0] !== "string") {
return false;
}
return true;
},
visitor(path) {
if (!["+", "-", "/", "*"].includes(path.node.operator)) {
return;
}
return this.createNode!(
{
[leftArgName]: [path.node.left, getLastOperationTrackingResultCall()],
[rightArgName]: [
path.node.right,
getLastOperationTrackingResultCall()
]
},
{ operator: ignoredStringLiteral(path.node.operator) },
path.node.loc
);
},
traverse(operationLog, charIndex, options?) {
const { operator } = operationLog.astArgs;
const { left, right } = operationLog.args;
const leftIsNumericLiteral = left.operation === "numericLiteral";
const rightIsNumericLiteral = right.operation === "numericLiteral";
const numericLiteralCount =
(leftIsNumericLiteral ? 1 : 0) + (rightIsNumericLiteral ? 1 : 0);
if (options && options.optimistic && numericLiteralCount === 1) {
// We can't be quite sure, but probably the user cares about the
// more complex value, not the simple hard coded value
const complexOperation = leftIsNumericLiteral ? right : left;
return {
isOptimistic: true,
charIndex,
operationLog: complexOperation
};
}
function looksLikeNumericConstant(operationLog) {
// remove: should be fixed now, fn params should store value even if untracked
// if (operationLog._result && operationLog._result.type === "undefined") {
// // mostly doing this because right now function paramters with a default value
// // don't get a tracking value...
// return true;
// }
if (typeof operationLog._result !== "number") {
return false;
}
return [0.1, 10, 100, 1000].includes(operationLog._result);
}
let leftLooksLikeNumericConstant = looksLikeNumericConstant(left);
let rightLooksLikeNumericConstant = looksLikeNumericConstant(right);
let numericConstantCount =
(leftLooksLikeNumericConstant ? 1 : 0) +
(rightLooksLikeNumericConstant ? 1 : 0);
if (
options &&
options.optimistic &&
numericConstantCount === 1 &&
left._result !== 0 &&
right._result !== 0
) {
const complexOperation = leftLooksLikeNumericConstant ? right : left;
return {
isOptimistic: true,
charIndex,
operationLog: complexOperation
};
}
if (operator == "+") {
let nextStep = traverseConcat(left, right, charIndex);
if (
nextStep &&
nextStep.operationLog &&
nextStep.operationLog._result === 0
) {
// Ignore step... traversal to number 0 usually isn't interesting
return undefined;
}
return nextStep;
} else {
console.log("todo binexp operator " + operator);
}
throw "aaa";
},
exec: function binaryExpressionExec(args, astArgs, ctx: ExecContext) {
const [left] = args[leftArgName];
const [right] = args[rightArgName];
var ret;
var { operator } = astArgs;
if (operator === "+") {
ret = left + right;
} else if (operator === "-") {
ret = left - right;
} else if (operator === "*") {
ret = left * right;
} else if (operator === "/") {
ret = left / right;
} else {
throw Error("unknown bin exp operator: " + operator);
}
return ret;
}
},
logicalExpression: {
visitor(path) {
if (path.node.operator === "||") {
return this.createNode!(
{
// always execute the left side
[leftArgName]: ignoreNode(
t.sequenceExpression([
createSetMemoValue(
MemoValueNames.lastOrLogicalExpressionResult,
path.node.left,
getLastOperationTrackingResultCall()
),
createGetMemoArray(MemoValueNames.lastOrLogicalExpressionResult)
])
),
// only execute the right side if left side is falsy
[rightArgName]: ignoreNode(
t.logicalExpression(
"&&",
ignoreNode(
t.unaryExpression(
"!",
createGetMemoValue(
MemoValueNames.lastOrLogicalExpressionResult
)
)
),
ignoredArrayExpression([
path.node.right,
getLastOperationTrackingResultCall()
])
)
)
},
{ operator: ignoredStringLiteral(path.node.operator) },
path.node.loc
);
}
},
traverse(operationLog, charIndex, options?) {
const { operator } = operationLog.astArgs;
const { left, right } = operationLog.args;
if (operator === "||") {
if (left.result.isTruthy()) {
return {
operationLog: left,
charIndex
};
} else {
return {
operationLog: right,
charIndex
};
}
}
},
exec: (args, astArgs, ctx: ExecContext) => {
const l = args[leftArgName];
const r = args[rightArgName];
// destructure here instead of using [l] = ... above,
// because false[0] is valid, but can't destructure false
const left = l[0];
const right = r[0];
var ret;
var { operator } = astArgs;
if (operator === "||") {
ret = left || right;
} else {
throw Error("unknown logical exp operator: " + operator);
}
return ret;
}
},
thisExpression: {
exec(args, astArgs, ctx: ExecContext) {
return args.value[0];
},
traverse: identifyTraverseFunction,
visitor(path) {
return this.createNode!(
{
value: [
ignoreNode(path.node),
ignoredCallExpression(
FunctionNames.getFunctionContextTrackingValue,
[]
)
]
},
{},
path.node.loc
);
}
},
conditionalExpression: {
exec: (args, astArgs, ctx: ExecContext) => {
return args.result[0];
},
traverse(operationLog, charIndex) {
return {
operationLog: operationLog.args.result,
charIndex
};
},
visitor(path) {
var saveTestValue = createSetMemoValue(
MemoValueNames.lastConditionalExpressionTest,
path.node.test,
getLastOperationTrackingResultCall()
);
var saveConsequentValue = createSetMemoValue(
MemoValueNames.lastConditionalExpressionResult,
path.node.consequent,
getLastOperationTrackingResultCall()
);
var saveAlernativeValue = createSetMemoValue(
MemoValueNames.lastConditionalExpressionResult,
path.node.alternate,
getLastOperationTrackingResultCall()
);
var operation = this.createNode!(
{
test: [
createGetMemoValue(MemoValueNames.lastConditionalExpressionTest),
createGetMemoTrackingValue(
MemoValueNames.lastConditionalExpressionTest
)
],
result: [
ignoreNode(
t.conditionalExpression(
createGetMemoValue(
MemoValueNames.lastConditionalExpressionTest
),
saveConsequentValue,
saveAlernativeValue
)
),
createGetMemoTrackingValue(
MemoValueNames.lastConditionalExpressionResult
)
]
},
{},
path.node.loc
);
path.replaceWith(t.sequenceExpression([saveTestValue, operation]));
}
},
genericOperation: {
traverse(operationLog, charIndex) {
if (!operationLog.runtimeArgs.next) {
return {
operationLog: null,
charIndex
};
}
return {
operationLog: operationLog.runtimeArgs.next,
charIndex: charIndex + (operationLog.runtimeArgs.adjustCharIndex || 0)
};
}
},
stringReplacement: {},
callExpression: CallExpression,
fn: {
exec: (args, astArgs, ctx) => {
return args[0];
}
},
newExpression: {
visitor(path) {
return operations.callExpression.visitor(path, true);
}
},
objectProperty: {
traverse(operationLog, charIndex) {
return {
operationLog: operationLog.args.propertyValue,
charIndex: charIndex
};
}
},
classDeclaration: {
visitor(path) {
// doesn't seem to have binding.kind, so can't just ignore it in
// safelyGetVariableTrackingValue -> make sure tracking var exists
path.insertAfter(
skipPath(
t.variableDeclaration("var", [
t.variableDeclarator(
t.identifier(getTrackingVarName(path.node.id.name))
)
])
)
);
}
},
objectExpression: ObjectExpression,
stringLiteral: {
canInferResult: true,
shorthand: {
fnName: "__str",
getExec: doOperation => {
return (value, loc) => {
return doOperation([value], undefined, loc);
};
},
visitor: (opArgs, astArgs, locAstNode) => {
const valueArg = opArgs[0];
return ignoredCallExpression("__str", [
ignoredArrayExpression(valueArg),
locAstNode
]);
}
},
argNames: ["value"],
visitor(path) {
if (path.parent.type === "ObjectProperty") {
return;
}
const value = path.node.value;
// Store on loc so it can be looked up later
path.node.loc.value = value;
return skipPath(
this.createNode!([[ignoredStringLiteral(value)]], {}, path.node.loc)
);
},
exec: function stringLiteralExec(args, astArgs, ctx: ExecContext) {
return args[0][0];
}
},
numericLiteral: {
shorthand: {
fnName: "__num",
getExec: doOperation => {
return (value, loc) => {
return doOperation([value], undefined, loc);
};
},
visitor: (opArgs, astArgs, locAstNode) => {
const valueArg = opArgs[0];
return ignoredCallExpression("__num", [
ignoredArrayExpression(valueArg),
locAstNode
]);
}
},
argNames: ["value"],
visitor(path) {
if (path.parent.type === "ObjectProperty") {
return;
}
const value = path.node.value;
return skipPath(
this.createNode!([[ignoredNumericLiteral(value)]], null, path.node.loc)
);
},
exec: (args, astArgs, ctx: ExecContext) => {
return args[0][0];
}
},
templateLiteral: {
exec: (args, astArgs, ctx: ExecContext, logData) => {
logData.extraArgs = {};
logData.runtimeArgs = {};
const expressionValues = ctx.getCurrentTemplateLiteralTrackingValues();
expressionValues.forEach((expressionValue, i) => {
logData.extraArgs[getShortExtraArgName("expression" + i)] = [
null,
expressionValue.trackingValue
];
logData.runtimeArgs["expression" + i + "Length"] =
expressionValue.valueLength;
});
return args.literal[0];
},
visitor(path) {
if (path.parentPath.node.type === "TaggedTemplateExpression") {
return;
}
let literalParts = [...path.node.expressions, ...path.node.quasis];
literalParts = sortBy(literalParts, p => {
const start = p.loc.start;
return start.line * 10000 + start.column;
});
const structure: any[] = literalParts.map(part => {
if (part.type === "TemplateElement") {
return ignoredObjectExpression({
type: ignoredStringLiteral("quasi"),
// cooked e.g. has escape sequences resolved
length: ignoredNumericLiteral(part.value.cooked.length)
});
} else {
return ignoredObjectExpression({
type: ignoredStringLiteral("expression")
});
}
});
const astArgs = {
structureParts: ignoredArrayExpression(structure)
};
path.node.expressions = path.node.expressions.map(expression => {
return ignoredCallExpression(
FunctionNames.saveTemplateLiteralExpressionTrackingValue,
[expression]
);
});
const args = {
// not sure why i need ignored array exp here?
literal: ignoredArrayExpression([ignoreNode(path.node), null])
};
return t.sequenceExpression([
ignoredCallExpression(FunctionNames.enterTemplateLiteral, []),
this.createNode!(args, astArgs, path.node.loc)
]);
},
traverse(operationLog, charIndex) {
const structureParts = operationLog.astArgs.structureParts;
let indexInString = 0;
let expressionIndex = 0;
for (var partIndex = 0; partIndex < structureParts.length; partIndex++) {
const structurePart = structureParts[partIndex];
let indexInStringAfter = indexInString;
if (structurePart.type === "quasi") {
indexInStringAfter += structurePart.length;
if (indexInStringAfter > charIndex) {
return {
charIndex: charIndex,
operationLog: null
};
}
} else {
const expressionTrackingValue =
operationLog.extraArgs["expression" + expressionIndex];
const expressionValueLength =
operationLog.runtimeArgs["expression" + expressionIndex + "Length"];
expressionIndex++;
indexInStringAfter += expressionValueLength;
if (indexInStringAfter > charIndex) {
return {
operationLog: expressionTrackingValue,
charIndex: charIndex - indexInString
};
}
}
indexInString = indexInStringAfter;
}
return {
operationLog: null,
charIndex
};
}
},
awaitExpression: {
visitor(path) {
const args = {
promise: [
createSetMemoValue(
"promiseForAwait",
path.node.argument,
getLastOperationTrackingResultCall()
),
createGetMemoTrackingValue("promiseForAwait")
],
result: [
ignoreNode(
this.t.awaitExpression(createGetMemoValue("promiseForAwait"))
)
]
};
return ignoreNode(this.createNode!(args, {}, path.node.loc));
},
exec(args, astArgs, ctx: ExecContext, logData) {
args.result[1] = ctx.getPromiseResolutionTrackingValue(args.promise[0]);
return args.result[0];
},
traverse(operationLog, charIndex) {
return {
operationLog: operationLog.args.result,
charIndex
};
}
},
unaryExpression: {
exec: (args, astArgs, ctx: ExecContext) => {
if (astArgs.operator === "-") {
return -args.argument[0];
} else if (astArgs.operator === "delete") {
const obj = args.object[0];
const propName = args.propName[0];
const ret = delete obj[propName];
if (typeof obj === "object") {
ctx.trackObjectPropertyAssignment(obj, propName, null, null);
}
return ret;
} else {
throw Error("unknown unary expression operator");
}
},
visitor(path) {
let args;
if (path.node.operator === "-") {
args = {
argument: [path.node.argument, getLastOperationTrackingResultCall()]
};
} else if (path.node.operator === "delete") {
let propName;
const arg = path.node.argument;
let object;
if (arg.type === "MemberExpression") {
object = arg.object;
if (arg.computed === true) {
propName = arg.property;
} else {
propName = addLoc(
this.t.stringLiteral(arg.property.name),
arg.property.loc
);
}
} else if (arg.type === "Identifier") {
// Deleting a global like this: delete someGlobal
propName = addLoc(ignoredStringLiteral(arg.name), arg.loc);
object = getGetGlobalCall();
} else {
console.log("unknown delete argument type: " + arg.type);
return;
}
args = {
object: [object, null],
propName: [propName, null]
};
} else {
return;
}
return this.createNode!(
args,
{
operator: ignoredStringLiteral(path.node.operator)
},
path.node.loc
);
}
},
arrayExpression: {
argNames: ["element"],
argIsArray: [true],
exec: function arrayExpressionExec(
args,
astArgs,
ctx: ExecContext,
logData: any
) {
const [elementsArg] = args;
let arr: any[] = [];
elementsArg.forEach((el, i) => {
const [value, trackingValue] = el;
arr.push(value);
const nameTrackingValue = ctx.createArrayIndexOperationLog(
i,
logData.loc
);
ctx.trackObjectPropertyAssignment(
arr,
i.toString(),
trackingValue,
nameTrackingValue
);
});
return arr;
},
visitor(path) {
const elements: any[] = [];
path.node.elements.forEach(el => {
if (
el /* check for el because it can be null if array has empty elements like [1,,3] */ &&
el.type === "SpreadElement"
) {
elements.push(
t.spreadElement(
ignoredCallExpression(FunctionNames.expandArrayForSpreadElement, [
el.argument
])
)
);
} else {
elements.push(
ignoredArrayExpression([el, getLastOperationTrackingResultCall()])
);
}
});
return this.createNode!([elements], null, path.node.loc);
}
},
returnStatement: {
argNames: ["returnValue"],
canInferResult: function(args) {
// return statement will always return returned value
return !!args[0][1];
},
exec: function returnStatementExec(
args,
astArgs,
ctx: ExecContext,
logData
) {
const [returnValueArg] = args;
ctx.lastReturnStatementResult = [returnValueArg[0], logData.index];
return returnValueArg[0];
},
traverse(operationLog, charIndex) {
return {
operationLog: operationLog.args.returnValue,
charIndex: charIndex
};
},
visitor(path) {
path.node.argument = this.createNode!(
[[path.node.argument, getLastOperationTrackingResultCall()]],
{},
path.node.loc
);
}
},
identifier: {
argNames: ["value"],
canInferResult: function(args) {
// identifier will always return same value as var value
return !!args[0][1];
},
shorthand: {
fnName: "__ident",
getExec: doOperation => {
return (value, loc) => {
return doOperation([value], undefined, loc);
};
},
visitor: (opArgs, astArgs, locAstNode) => {
if (astArgs && astArgs["isArguments"]) {
// __ident shorthand doesn't support astArgs
return null;
}
return ignoredCallExpression("__ident", [
ignoredArrayExpression(opArgs[0]),
locAstNode
]);
}
},
exec: function identifierExec(args, astArgs, ctx: ExecContext, logData) {
const [valueArg, allFnArgTrackingValuesArg] = args;
if (
astArgs &&
astArgs.isArguments &&
!ctx.objectHasPropertyTrackingData(valueArg[0])
) {
if (allFnArgTrackingValuesArg[0]) {
allFnArgTrackingValuesArg[0].forEach((trackingValue, i) => {
ctx.trackObjectPropertyAssignment(
valueArg[0],
i,
trackingValue,
ctx.createArrayIndexOperationLog(i, logData.loc)
);
});
} else {
if (VERIFY) {
console.log("no tracking values for arguments object");
}
}
}
return valueArg[0];
},
traverse: identifyTraverseFunction,
visitor(path) {
if (shouldSkipIdentifier(path)) {
return;
}
path.node.ignore = true;
let node = path.node;
let trackingIdentiferLookup = safelyGetVariableTrackingValue(
path.node.name,
path.scope
);
let astArgs: any = null;
const args: any = [[node, trackingIdentiferLookup]];
if (node.name === "arguments") {
astArgs = { isArguments: ignoreNode(t.booleanLiteral(true)) };
args.push([ignoredIdentifier("__allArgTV")]);
}
return skipPath(this.createNode!(args, astArgs, path.node.loc));
}
},
memexpAsLeftAssExp: {
canInferResult: true,
traverse(operationLog: OperationLog, charIndex: number) {
return {
operationLog: operationLog.extraArgs.propertyValue,
charIndex
};
}
},
splitResult: {
traverse(operationLog: OperationLog, charIndex) {
const { string, separator: separatorArg } = operationLog.args;
const originalString = string.result.primitive;
const separator = (separatorArg && separatorArg.result.primitive) || "";
console.log(
"TODO: actually capture the indices where the string came from at runtime"
);
return {
operationLog: operationLog.args.string,
charIndex:
originalString.indexOf(operationLog.result.primitive) + charIndex
};
}
},
matchResult: {
traverse(operationLog: OperationLog, charIndex) {
return {
operationLog: operationLog.args.input,
charIndex: operationLog.runtimeArgs.matchIndex + charIndex
};
}
},
execResult: {
traverse(operationLog: OperationLog, charIndex) {
return {
operationLog: operationLog.args.string,
charIndex: charIndex + operationLog.runtimeArgs.matchIndex
};
}
},
jsonParseResult: {
traverse(operationLog, charIndex) {
// This traversal method is inaccurate but still useful
// Ideally we should probably have a JSON parser
const valueReadFromJson = operationLog.result.primitive;
const json = operationLog.args.json.result.primitive;
const keyPath = operationLog.runtimeArgs.keyPath;
if (operationLog.runtimeArgs.isPrimitive) {
return {
operationLog: operationLog.args.json,
charIndex: charIndex + operationLog.runtimeArgs.charIndexAdjustment
};
}
const ast = jsonToAst(json, { loc: true });
const valueStart = getJSONPathOffset(
json,
ast,
keyPath,
operationLog.runtimeArgs.isKey
);
charIndex = adjustColumnForEscapeSequences(
json.slice(valueStart),
charIndex
);
charIndex += valueStart;
return {
operationLog: operationLog.args.json,
charIndex
};
}
},
readFileSyncResult: {
traverse(operationLog, charIndex, options) {
let absPath = operationLog.runtimeArgs.absPath;
let writeEvent = (options!.events || []).find(
e => e.type === "fileWrite" && e.absPath === absPath
);
if (!writeEvent) {
return {
operationLog: null,
charIndex
};
}
return {
operationLog: writeEvent.logIndex,
charIndex
};
}
},
arrayPattern: {
traverse(operationLog, charIndex) {
return {
operationLog: operationLog.args.value,
charIndex
};
}
},
arrayIndex: {},
assignmentExpression: AssignmentExpression,
objectAssignResult: {
traverse: identifyTraverseFunction
},
arraySlice: { traverse: identifyTraverseFunction },
arraySplice: { traverse: identifyTraverseFunction },
arrayConcat: {
traverse: identifyTraverseFunction
},
styleAssignment: {
traverse: (operationLog, charIndex) => {
const styleName = operationLog.args.styleName.result.primitive;
const styleNamePrefix = '="';
const styleNameText = styleNamePrefix + styleName + ": ";
if (charIndex < styleNameText.length) {
return {
operationLog: operationLog.args.styleName,
charIndex: Math.min(
Math.max(charIndex - styleNamePrefix.length, 0),
styleName.length
)
};
} else {
return {
operationLog: operationLog.args.styleValue,
charIndex: charIndex - styleNameText.length
};
}
}
},
htmlAdapter: {
traverse: (operationLog, charIndex) => {
return {
operationLog: operationLog.args.html,
charIndex: traverseDomOrigin(operationLog.runtimeArgs, charIndex)
};
}
}
};
export function eachArgumentInObject(args, operationName, fn) {
if (!args) {
return;
}
const operation = operations[operationName];
const isObjectExpression = operationName === OperationTypes.objectExpression;
if (isObjectExpression) {
// todo: this is an objexpression property not an obj expression itself, should be clarified
["value", "key"].forEach(key => {
fn(
args.value,
key,
newValue => {
args[key] = newValue;
},
newKey => {
if (newKey === key) {
return;
}
args[newKey] = args[key];
delete args.key;
}
);
});
} else {
Object.keys(args).forEach(key => {
fn(
args[key],
key,
newValue => (args[key] = newValue),
newKey => {
if (key === newKey) {
return;
}
args[newKey] = args[key];
delete args[key];
}
);
});
}
}
export function eachArgument(operationLog, fn) {
eachArgumentInObject(operationLog.args, operationLog.operation, fn);
if (operationLog.extraArgs) {
eachArgumentInObject(operationLog.extraArgs, operationLog.operation, fn);
}
}
Object.keys(operations).forEach(opName => {
const operation = operations[opName];
if (!OperationTypes[opName]!) {
throw Error("No op type: " + opName);
}
Object.defineProperty(operation, "t", {
get() {
return t;
}
});
Object.defineProperty(operation, "babylon", {
get() {
return babylon;
}
});
operation.createNode = function(args, astArgs, loc = null) {
const operation = createOperation(
OperationTypes[opName],
args,
astArgs,
loc,
operations[opName].shorthand || null
);
return operation;
};
operation.getArgumentsArray = function(operationLog) {
var ret: any[] = [];
eachArgument(operationLog, (arg, argName, updateValue) => {
ret.push({ arg: arg, argName });
});
return ret;
};
});
export default operations;
export function shouldSkipIdentifier(path) {
if (
[
"FunctionDeclaration",
"ArrowFunctionExpression",
"MemberExpression",
"ObjectProperty",
"CatchClause",
"ForOfStatement",
"ForInStatement",
"IfStatement",
"ForStatement",
"FunctionExpression",
"UpdateExpression",
"LabeledStatement",
"ContinueStatement",
"BreakStatement",
"ClassMethod",
"ClassProperty",
"ClassDeclaration",
"ClassExpression",
"AssignmentPattern",
"ArrayPattern",
"RestElement"
].includes(path.parent.type)
) {
return true;
}
if (
path.parent.type === "UnaryExpression" &&
path.parent.operator === "typeof"
) {
return true;
}
if (
isInLeftPartOfAssignmentExpression(path) ||
isInIdOfVariableDeclarator(path)
) {
return true;
}
return false;
} | the_stack |
import {flatbuffers} from 'flatbuffers';
/**
* @enum {number}
*/
export namespace onnxruntime.experimental.fbs {
export enum AttributeType {
UNDEFINED = 0,
FLOAT = 1,
INT = 2,
STRING = 3,
TENSOR = 4,
GRAPH = 5,
FLOATS = 6,
INTS = 7,
STRINGS = 8,
TENSORS = 9,
GRAPHS = 10,
SPARSE_TENSOR = 11,
SPARSE_TENSORS = 12
}
}
/**
* @enum {number}
*/
export namespace onnxruntime.experimental.fbs {
export enum DimensionValueType {UNKNOWN = 0, VALUE = 1, PARAM = 2}
}
/**
* @enum {number}
*/
export namespace onnxruntime.experimental.fbs {
export enum TensorDataType {
UNDEFINED = 0,
FLOAT = 1,
UINT8 = 2,
INT8 = 3,
UINT16 = 4,
INT16 = 5,
INT32 = 6,
INT64 = 7,
STRING = 8,
BOOL = 9,
FLOAT16 = 10,
DOUBLE = 11,
UINT32 = 12,
UINT64 = 13,
COMPLEX64 = 14,
COMPLEX128 = 15,
BFLOAT16 = 16
}
}
/**
* @enum {number}
*/
export namespace onnxruntime.experimental.fbs {
export enum NodeType {Primitive = 0, Fused = 1}
}
/**
* @enum {number}
*/
export namespace onnxruntime.experimental.fbs {
export enum TypeInfoValue {NONE = 0, tensor_type = 1, sequence_type = 2, map_type = 3}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Shape {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Shape
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Shape {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Shape= obj
* @returns Shape
*/
static getRootAsShape(bb: flatbuffers.ByteBuffer, obj?: Shape): Shape {
return (obj || new Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Shape= obj
* @returns Shape
*/
static getSizePrefixedRootAsShape(bb: flatbuffers.ByteBuffer, obj?: Shape): Shape {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.Dimension= obj
* @returns onnxruntime.experimental.fbs.Dimension
*/
dim(index: number, obj?: onnxruntime.experimental.fbs.Dimension): onnxruntime.experimental.fbs.Dimension|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? (obj || new onnxruntime.experimental.fbs.Dimension())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
dimLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startShape(builder: flatbuffers.Builder) {
builder.startObject(1);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset dimOffset
*/
static addDim(builder: flatbuffers.Builder, dimOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, dimOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createDimVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startDimVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endShape(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createShape(builder: flatbuffers.Builder, dimOffset: flatbuffers.Offset): flatbuffers.Offset {
Shape.startShape(builder);
Shape.addDim(builder, dimOffset);
return Shape.endShape(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Dimension {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Dimension
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Dimension {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Dimension= obj
* @returns Dimension
*/
static getRootAsDimension(bb: flatbuffers.ByteBuffer, obj?: Dimension): Dimension {
return (obj || new Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Dimension= obj
* @returns Dimension
*/
static getSizePrefixedRootAsDimension(bb: flatbuffers.ByteBuffer, obj?: Dimension): Dimension {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param onnxruntime.experimental.fbs.DimensionValue= obj
* @returns onnxruntime.experimental.fbs.DimensionValue|null
*/
value(obj?: onnxruntime.experimental.fbs.DimensionValue): onnxruntime.experimental.fbs.DimensionValue|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? (obj || new onnxruntime.experimental.fbs.DimensionValue())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
denotation(): string|null;
denotation(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
denotation(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Builder builder
*/
static startDimension(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset valueOffset
*/
static addValue(builder: flatbuffers.Builder, valueOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, valueOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset denotationOffset
*/
static addDenotation(builder: flatbuffers.Builder, denotationOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, denotationOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endDimension(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createDimension(
builder: flatbuffers.Builder, valueOffset: flatbuffers.Offset,
denotationOffset: flatbuffers.Offset): flatbuffers.Offset {
Dimension.startDimension(builder);
Dimension.addValue(builder, valueOffset);
Dimension.addDenotation(builder, denotationOffset);
return Dimension.endDimension(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class DimensionValue {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns DimensionValue
*/
__init(i: number, bb: flatbuffers.ByteBuffer): DimensionValue {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param DimensionValue= obj
* @returns DimensionValue
*/
static getRootAsDimensionValue(bb: flatbuffers.ByteBuffer, obj?: DimensionValue): DimensionValue {
return (obj || new DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param DimensionValue= obj
* @returns DimensionValue
*/
static getSizePrefixedRootAsDimensionValue(bb: flatbuffers.ByteBuffer, obj?: DimensionValue): DimensionValue {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @returns onnxruntime.experimental.fbs.DimensionValueType
*/
dimType(): onnxruntime.experimental.fbs.DimensionValueType {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? /** */ (this.bb!.readInt8(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.DimensionValueType.UNKNOWN;
}
/**
* @returns flatbuffers.Long
*/
dimValue(): flatbuffers.Long {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
dimParam(): string|null;
dimParam(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
dimParam(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Builder builder
*/
static startDimensionValue(builder: flatbuffers.Builder) {
builder.startObject(3);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.DimensionValueType dimType
*/
static addDimType(builder: flatbuffers.Builder, dimType: onnxruntime.experimental.fbs.DimensionValueType) {
builder.addFieldInt8(0, dimType, onnxruntime.experimental.fbs.DimensionValueType.UNKNOWN);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long dimValue
*/
static addDimValue(builder: flatbuffers.Builder, dimValue: flatbuffers.Long) {
builder.addFieldInt64(1, dimValue, builder.createLong(0, 0));
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset dimParamOffset
*/
static addDimParam(builder: flatbuffers.Builder, dimParamOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, dimParamOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endDimensionValue(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createDimensionValue(
builder: flatbuffers.Builder, dimType: onnxruntime.experimental.fbs.DimensionValueType,
dimValue: flatbuffers.Long, dimParamOffset: flatbuffers.Offset): flatbuffers.Offset {
DimensionValue.startDimensionValue(builder);
DimensionValue.addDimType(builder, dimType);
DimensionValue.addDimValue(builder, dimValue);
DimensionValue.addDimParam(builder, dimParamOffset);
return DimensionValue.endDimensionValue(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class TensorTypeAndShape {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns TensorTypeAndShape
*/
__init(i: number, bb: flatbuffers.ByteBuffer): TensorTypeAndShape {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param TensorTypeAndShape= obj
* @returns TensorTypeAndShape
*/
static getRootAsTensorTypeAndShape(bb: flatbuffers.ByteBuffer, obj?: TensorTypeAndShape): TensorTypeAndShape {
return (obj || new TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param TensorTypeAndShape= obj
* @returns TensorTypeAndShape
*/
static getSizePrefixedRootAsTensorTypeAndShape(bb: flatbuffers.ByteBuffer, obj?: TensorTypeAndShape):
TensorTypeAndShape {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @returns onnxruntime.experimental.fbs.TensorDataType
*/
elemType(): onnxruntime.experimental.fbs.TensorDataType {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? /** */ (this.bb!.readInt32(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
}
/**
* @param onnxruntime.experimental.fbs.Shape= obj
* @returns onnxruntime.experimental.fbs.Shape|null
*/
shape(obj?: onnxruntime.experimental.fbs.Shape): onnxruntime.experimental.fbs.Shape|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.Shape())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Builder builder
*/
static startTensorTypeAndShape(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.TensorDataType elemType
*/
static addElemType(builder: flatbuffers.Builder, elemType: onnxruntime.experimental.fbs.TensorDataType) {
builder.addFieldInt32(0, elemType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset shapeOffset
*/
static addShape(builder: flatbuffers.Builder, shapeOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, shapeOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endTensorTypeAndShape(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createTensorTypeAndShape(
builder: flatbuffers.Builder, elemType: onnxruntime.experimental.fbs.TensorDataType,
shapeOffset: flatbuffers.Offset): flatbuffers.Offset {
TensorTypeAndShape.startTensorTypeAndShape(builder);
TensorTypeAndShape.addElemType(builder, elemType);
TensorTypeAndShape.addShape(builder, shapeOffset);
return TensorTypeAndShape.endTensorTypeAndShape(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class MapType {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns MapType
*/
__init(i: number, bb: flatbuffers.ByteBuffer): MapType {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param MapType= obj
* @returns MapType
*/
static getRootAsMapType(bb: flatbuffers.ByteBuffer, obj?: MapType): MapType {
return (obj || new MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param MapType= obj
* @returns MapType
*/
static getSizePrefixedRootAsMapType(bb: flatbuffers.ByteBuffer, obj?: MapType): MapType {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @returns onnxruntime.experimental.fbs.TensorDataType
*/
keyType(): onnxruntime.experimental.fbs.TensorDataType {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? /** */ (this.bb!.readInt32(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
}
/**
* @param onnxruntime.experimental.fbs.TypeInfo= obj
* @returns onnxruntime.experimental.fbs.TypeInfo|null
*/
valueType(obj?: onnxruntime.experimental.fbs.TypeInfo): onnxruntime.experimental.fbs.TypeInfo|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Builder builder
*/
static startMapType(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.TensorDataType keyType
*/
static addKeyType(builder: flatbuffers.Builder, keyType: onnxruntime.experimental.fbs.TensorDataType) {
builder.addFieldInt32(0, keyType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset valueTypeOffset
*/
static addValueType(builder: flatbuffers.Builder, valueTypeOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, valueTypeOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endMapType(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createMapType(
builder: flatbuffers.Builder, keyType: onnxruntime.experimental.fbs.TensorDataType,
valueTypeOffset: flatbuffers.Offset): flatbuffers.Offset {
MapType.startMapType(builder);
MapType.addKeyType(builder, keyType);
MapType.addValueType(builder, valueTypeOffset);
return MapType.endMapType(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class SequenceType {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns SequenceType
*/
__init(i: number, bb: flatbuffers.ByteBuffer): SequenceType {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SequenceType= obj
* @returns SequenceType
*/
static getRootAsSequenceType(bb: flatbuffers.ByteBuffer, obj?: SequenceType): SequenceType {
return (obj || new SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SequenceType= obj
* @returns SequenceType
*/
static getSizePrefixedRootAsSequenceType(bb: flatbuffers.ByteBuffer, obj?: SequenceType): SequenceType {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param onnxruntime.experimental.fbs.TypeInfo= obj
* @returns onnxruntime.experimental.fbs.TypeInfo|null
*/
elemType(obj?: onnxruntime.experimental.fbs.TypeInfo): onnxruntime.experimental.fbs.TypeInfo|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Builder builder
*/
static startSequenceType(builder: flatbuffers.Builder) {
builder.startObject(1);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset elemTypeOffset
*/
static addElemType(builder: flatbuffers.Builder, elemTypeOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, elemTypeOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endSequenceType(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createSequenceType(builder: flatbuffers.Builder, elemTypeOffset: flatbuffers.Offset): flatbuffers.Offset {
SequenceType.startSequenceType(builder);
SequenceType.addElemType(builder, elemTypeOffset);
return SequenceType.endSequenceType(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class EdgeEnd {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns EdgeEnd
*/
__init(i: number, bb: flatbuffers.ByteBuffer): EdgeEnd {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @returns number
*/
nodeIndex(): number {
return this.bb!.readUint32(this.bb_pos);
}
/**
* @returns number
*/
srcArgIndex(): number {
return this.bb!.readInt32(this.bb_pos + 4);
}
/**
* @returns number
*/
dstArgIndex(): number {
return this.bb!.readInt32(this.bb_pos + 8);
}
/**
* @param flatbuffers.Builder builder
* @param number node_index
* @param number src_arg_index
* @param number dst_arg_index
* @returns flatbuffers.Offset
*/
static createEdgeEnd(
builder: flatbuffers.Builder, node_index: number, src_arg_index: number,
dst_arg_index: number): flatbuffers.Offset {
builder.prep(4, 12);
builder.writeInt32(dst_arg_index);
builder.writeInt32(src_arg_index);
builder.writeInt32(node_index);
return builder.offset();
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class NodeEdge {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns NodeEdge
*/
__init(i: number, bb: flatbuffers.ByteBuffer): NodeEdge {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param NodeEdge= obj
* @returns NodeEdge
*/
static getRootAsNodeEdge(bb: flatbuffers.ByteBuffer, obj?: NodeEdge): NodeEdge {
return (obj || new NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param NodeEdge= obj
* @returns NodeEdge
*/
static getSizePrefixedRootAsNodeEdge(bb: flatbuffers.ByteBuffer, obj?: NodeEdge): NodeEdge {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @returns number
*/
nodeIndex(): number {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.EdgeEnd= obj
* @returns onnxruntime.experimental.fbs.EdgeEnd
*/
inputEdges(index: number, obj?: onnxruntime.experimental.fbs.EdgeEnd): onnxruntime.experimental.fbs.EdgeEnd|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.EdgeEnd())
.__init(this.bb!.__vector(this.bb_pos + offset) + index * 12, this.bb!) :
null;
}
/**
* @returns number
*/
inputEdgesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.EdgeEnd= obj
* @returns onnxruntime.experimental.fbs.EdgeEnd
*/
outputEdges(index: number, obj?: onnxruntime.experimental.fbs.EdgeEnd): onnxruntime.experimental.fbs.EdgeEnd|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? (obj || new onnxruntime.experimental.fbs.EdgeEnd())
.__init(this.bb!.__vector(this.bb_pos + offset) + index * 12, this.bb!) :
null;
}
/**
* @returns number
*/
outputEdgesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startNodeEdge(builder: flatbuffers.Builder) {
builder.startObject(3);
}
/**
* @param flatbuffers.Builder builder
* @param number nodeIndex
*/
static addNodeIndex(builder: flatbuffers.Builder, nodeIndex: number) {
builder.addFieldInt32(0, nodeIndex, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset inputEdgesOffset
*/
static addInputEdges(builder: flatbuffers.Builder, inputEdgesOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, inputEdgesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startInputEdgesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(12, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset outputEdgesOffset
*/
static addOutputEdges(builder: flatbuffers.Builder, outputEdgesOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, outputEdgesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startOutputEdgesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(12, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endNodeEdge(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createNodeEdge(
builder: flatbuffers.Builder, nodeIndex: number, inputEdgesOffset: flatbuffers.Offset,
outputEdgesOffset: flatbuffers.Offset): flatbuffers.Offset {
NodeEdge.startNodeEdge(builder);
NodeEdge.addNodeIndex(builder, nodeIndex);
NodeEdge.addInputEdges(builder, inputEdgesOffset);
NodeEdge.addOutputEdges(builder, outputEdgesOffset);
return NodeEdge.endNodeEdge(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Node {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Node
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Node {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Node= obj
* @returns Node
*/
static getRootAsNode(bb: flatbuffers.ByteBuffer, obj?: Node): Node {
return (obj || new Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Node= obj
* @returns Node
*/
static getSizePrefixedRootAsNode(bb: flatbuffers.ByteBuffer, obj?: Node): Node {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
name(): string|null;
name(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
name(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
docString(): string|null;
docString(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
docString(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
domain(): string|null;
domain(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
domain(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @returns number
*/
sinceVersion(): number {
let offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0;
}
/**
* @returns number
*/
index(): number {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
opType(): string|null;
opType(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
opType(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @returns onnxruntime.experimental.fbs.NodeType
*/
type(): onnxruntime.experimental.fbs.NodeType {
let offset = this.bb!.__offset(this.bb_pos, 16);
return offset ? /** */ (this.bb!.readInt32(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.NodeType.Primitive;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
executionProviderType(): string|null;
executionProviderType(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
executionProviderType(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 18);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
inputs(index: number): string;
inputs(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
inputs(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 20);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
inputsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 20);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
outputs(index: number): string;
outputs(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
outputs(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 22);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
outputsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 22);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.Attribute= obj
* @returns onnxruntime.experimental.fbs.Attribute
*/
attributes(index: number, obj?: onnxruntime.experimental.fbs.Attribute): onnxruntime.experimental.fbs.Attribute
|null {
let offset = this.bb!.__offset(this.bb_pos, 24);
return offset ? (obj || new onnxruntime.experimental.fbs.Attribute())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
attributesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 24);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @returns number
*/
inputArgCounts(index: number): number|null {
let offset = this.bb!.__offset(this.bb_pos, 26);
return offset ? this.bb!.readInt32(this.bb!.__vector(this.bb_pos + offset) + index * 4) : 0;
}
/**
* @returns number
*/
inputArgCountsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 26);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @returns Int32Array
*/
inputArgCountsArray(): Int32Array|null {
let offset = this.bb!.__offset(this.bb_pos, 26);
return offset ?
new Int32Array(
this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset),
this.bb!.__vector_len(this.bb_pos + offset)) :
null;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
implicitInputs(index: number): string;
implicitInputs(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
implicitInputs(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 28);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
implicitInputsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 28);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startNode(builder: flatbuffers.Builder) {
builder.startObject(13);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nameOffset
*/
static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, nameOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset docStringOffset
*/
static addDocString(builder: flatbuffers.Builder, docStringOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, docStringOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset domainOffset
*/
static addDomain(builder: flatbuffers.Builder, domainOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, domainOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param number sinceVersion
*/
static addSinceVersion(builder: flatbuffers.Builder, sinceVersion: number) {
builder.addFieldInt32(3, sinceVersion, 0);
}
/**
* @param flatbuffers.Builder builder
* @param number index
*/
static addIndex(builder: flatbuffers.Builder, index: number) {
builder.addFieldInt32(4, index, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset opTypeOffset
*/
static addOpType(builder: flatbuffers.Builder, opTypeOffset: flatbuffers.Offset) {
builder.addFieldOffset(5, opTypeOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.NodeType type
*/
static addType(builder: flatbuffers.Builder, type: onnxruntime.experimental.fbs.NodeType) {
builder.addFieldInt32(6, type, onnxruntime.experimental.fbs.NodeType.Primitive);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset executionProviderTypeOffset
*/
static addExecutionProviderType(builder: flatbuffers.Builder, executionProviderTypeOffset: flatbuffers.Offset) {
builder.addFieldOffset(7, executionProviderTypeOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset inputsOffset
*/
static addInputs(builder: flatbuffers.Builder, inputsOffset: flatbuffers.Offset) {
builder.addFieldOffset(8, inputsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createInputsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startInputsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset outputsOffset
*/
static addOutputs(builder: flatbuffers.Builder, outputsOffset: flatbuffers.Offset) {
builder.addFieldOffset(9, outputsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createOutputsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startOutputsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset attributesOffset
*/
static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset) {
builder.addFieldOffset(10, attributesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startAttributesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset inputArgCountsOffset
*/
static addInputArgCounts(builder: flatbuffers.Builder, inputArgCountsOffset: flatbuffers.Offset) {
builder.addFieldOffset(11, inputArgCountsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<number> data
* @returns flatbuffers.Offset
*/
static createInputArgCountsVector(builder: flatbuffers.Builder, data: number[]|Uint8Array): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt32(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startInputArgCountsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset implicitInputsOffset
*/
static addImplicitInputs(builder: flatbuffers.Builder, implicitInputsOffset: flatbuffers.Offset) {
builder.addFieldOffset(12, implicitInputsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createImplicitInputsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startImplicitInputsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endNode(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createNode(
builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset, docStringOffset: flatbuffers.Offset,
domainOffset: flatbuffers.Offset, sinceVersion: number, index: number, opTypeOffset: flatbuffers.Offset,
type: onnxruntime.experimental.fbs.NodeType, executionProviderTypeOffset: flatbuffers.Offset,
inputsOffset: flatbuffers.Offset, outputsOffset: flatbuffers.Offset, attributesOffset: flatbuffers.Offset,
inputArgCountsOffset: flatbuffers.Offset, implicitInputsOffset: flatbuffers.Offset): flatbuffers.Offset {
Node.startNode(builder);
Node.addName(builder, nameOffset);
Node.addDocString(builder, docStringOffset);
Node.addDomain(builder, domainOffset);
Node.addSinceVersion(builder, sinceVersion);
Node.addIndex(builder, index);
Node.addOpType(builder, opTypeOffset);
Node.addType(builder, type);
Node.addExecutionProviderType(builder, executionProviderTypeOffset);
Node.addInputs(builder, inputsOffset);
Node.addOutputs(builder, outputsOffset);
Node.addAttributes(builder, attributesOffset);
Node.addInputArgCounts(builder, inputArgCountsOffset);
Node.addImplicitInputs(builder, implicitInputsOffset);
return Node.endNode(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class ValueInfo {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns ValueInfo
*/
__init(i: number, bb: flatbuffers.ByteBuffer): ValueInfo {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param ValueInfo= obj
* @returns ValueInfo
*/
static getRootAsValueInfo(bb: flatbuffers.ByteBuffer, obj?: ValueInfo): ValueInfo {
return (obj || new ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param ValueInfo= obj
* @returns ValueInfo
*/
static getSizePrefixedRootAsValueInfo(bb: flatbuffers.ByteBuffer, obj?: ValueInfo): ValueInfo {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
name(): string|null;
name(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
name(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
docString(): string|null;
docString(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
docString(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param onnxruntime.experimental.fbs.TypeInfo= obj
* @returns onnxruntime.experimental.fbs.TypeInfo|null
*/
type(obj?: onnxruntime.experimental.fbs.TypeInfo): onnxruntime.experimental.fbs.TypeInfo|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? (obj || new onnxruntime.experimental.fbs.TypeInfo())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Builder builder
*/
static startValueInfo(builder: flatbuffers.Builder) {
builder.startObject(3);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nameOffset
*/
static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, nameOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset docStringOffset
*/
static addDocString(builder: flatbuffers.Builder, docStringOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, docStringOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset typeOffset
*/
static addType(builder: flatbuffers.Builder, typeOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, typeOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endValueInfo(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createValueInfo(
builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset, docStringOffset: flatbuffers.Offset,
typeOffset: flatbuffers.Offset): flatbuffers.Offset {
ValueInfo.startValueInfo(builder);
ValueInfo.addName(builder, nameOffset);
ValueInfo.addDocString(builder, docStringOffset);
ValueInfo.addType(builder, typeOffset);
return ValueInfo.endValueInfo(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class TypeInfo {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns TypeInfo
*/
__init(i: number, bb: flatbuffers.ByteBuffer): TypeInfo {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param TypeInfo= obj
* @returns TypeInfo
*/
static getRootAsTypeInfo(bb: flatbuffers.ByteBuffer, obj?: TypeInfo): TypeInfo {
return (obj || new TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param TypeInfo= obj
* @returns TypeInfo
*/
static getSizePrefixedRootAsTypeInfo(bb: flatbuffers.ByteBuffer, obj?: TypeInfo): TypeInfo {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
denotation(): string|null;
denotation(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
denotation(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @returns onnxruntime.experimental.fbs.TypeInfoValue
*/
valueType(): onnxruntime.experimental.fbs.TypeInfoValue {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.TypeInfoValue.NONE;
}
/**
* @param flatbuffers.Table obj
* @returns ?flatbuffers.Table
*/
value<T extends flatbuffers.Table>(obj: T): T|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null;
}
/**
* @param flatbuffers.Builder builder
*/
static startTypeInfo(builder: flatbuffers.Builder) {
builder.startObject(3);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset denotationOffset
*/
static addDenotation(builder: flatbuffers.Builder, denotationOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, denotationOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.TypeInfoValue valueType
*/
static addValueType(builder: flatbuffers.Builder, valueType: onnxruntime.experimental.fbs.TypeInfoValue) {
builder.addFieldInt8(1, valueType, onnxruntime.experimental.fbs.TypeInfoValue.NONE);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset valueOffset
*/
static addValue(builder: flatbuffers.Builder, valueOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, valueOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endTypeInfo(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createTypeInfo(
builder: flatbuffers.Builder, denotationOffset: flatbuffers.Offset,
valueType: onnxruntime.experimental.fbs.TypeInfoValue, valueOffset: flatbuffers.Offset): flatbuffers.Offset {
TypeInfo.startTypeInfo(builder);
TypeInfo.addDenotation(builder, denotationOffset);
TypeInfo.addValueType(builder, valueType);
TypeInfo.addValue(builder, valueOffset);
return TypeInfo.endTypeInfo(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class OperatorSetId {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns OperatorSetId
*/
__init(i: number, bb: flatbuffers.ByteBuffer): OperatorSetId {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param OperatorSetId= obj
* @returns OperatorSetId
*/
static getRootAsOperatorSetId(bb: flatbuffers.ByteBuffer, obj?: OperatorSetId): OperatorSetId {
return (obj || new OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param OperatorSetId= obj
* @returns OperatorSetId
*/
static getSizePrefixedRootAsOperatorSetId(bb: flatbuffers.ByteBuffer, obj?: OperatorSetId): OperatorSetId {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
domain(): string|null;
domain(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
domain(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @returns flatbuffers.Long
*/
version(): flatbuffers.Long {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
}
/**
* @param flatbuffers.Builder builder
*/
static startOperatorSetId(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset domainOffset
*/
static addDomain(builder: flatbuffers.Builder, domainOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, domainOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long version
*/
static addVersion(builder: flatbuffers.Builder, version: flatbuffers.Long) {
builder.addFieldInt64(1, version, builder.createLong(0, 0));
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endOperatorSetId(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createOperatorSetId(
builder: flatbuffers.Builder, domainOffset: flatbuffers.Offset, version: flatbuffers.Long): flatbuffers.Offset {
OperatorSetId.startOperatorSetId(builder);
OperatorSetId.addDomain(builder, domainOffset);
OperatorSetId.addVersion(builder, version);
return OperatorSetId.endOperatorSetId(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Tensor {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Tensor
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Tensor {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Tensor= obj
* @returns Tensor
*/
static getRootAsTensor(bb: flatbuffers.ByteBuffer, obj?: Tensor): Tensor {
return (obj || new Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Tensor= obj
* @returns Tensor
*/
static getSizePrefixedRootAsTensor(bb: flatbuffers.ByteBuffer, obj?: Tensor): Tensor {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
name(): string|null;
name(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
name(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
docString(): string|null;
docString(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
docString(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param number index
* @returns flatbuffers.Long
*/
dims(index: number): flatbuffers.Long|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) :
this.bb!.createLong(0, 0);
}
/**
* @returns number
*/
dimsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @returns onnxruntime.experimental.fbs.TensorDataType
*/
dataType(): onnxruntime.experimental.fbs.TensorDataType {
let offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? /** */ (this.bb!.readInt32(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.TensorDataType.UNDEFINED;
}
/**
* @param number index
* @returns number
*/
rawData(index: number): number|null {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0;
}
/**
* @returns number
*/
rawDataLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @returns Uint8Array
*/
rawDataArray(): Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ?
new Uint8Array(
this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset),
this.bb!.__vector_len(this.bb_pos + offset)) :
null;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
stringData(index: number): string;
stringData(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
stringData(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
stringDataLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startTensor(builder: flatbuffers.Builder) {
builder.startObject(6);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nameOffset
*/
static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, nameOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset docStringOffset
*/
static addDocString(builder: flatbuffers.Builder, docStringOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, docStringOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset dimsOffset
*/
static addDims(builder: flatbuffers.Builder, dimsOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, dimsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Long> data
* @returns flatbuffers.Offset
*/
static createDimsVector(builder: flatbuffers.Builder, data: flatbuffers.Long[]): flatbuffers.Offset {
builder.startVector(8, data.length, 8);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt64(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startDimsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(8, numElems, 8);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.TensorDataType dataType
*/
static addDataType(builder: flatbuffers.Builder, dataType: onnxruntime.experimental.fbs.TensorDataType) {
builder.addFieldInt32(3, dataType, onnxruntime.experimental.fbs.TensorDataType.UNDEFINED);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset rawDataOffset
*/
static addRawData(builder: flatbuffers.Builder, rawDataOffset: flatbuffers.Offset) {
builder.addFieldOffset(4, rawDataOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<number> data
* @returns flatbuffers.Offset
*/
static createRawDataVector(builder: flatbuffers.Builder, data: number[]|Uint8Array): flatbuffers.Offset {
builder.startVector(1, data.length, 1);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt8(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startRawDataVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(1, numElems, 1);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset stringDataOffset
*/
static addStringData(builder: flatbuffers.Builder, stringDataOffset: flatbuffers.Offset) {
builder.addFieldOffset(5, stringDataOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createStringDataVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startStringDataVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endTensor(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createTensor(
builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset, docStringOffset: flatbuffers.Offset,
dimsOffset: flatbuffers.Offset, dataType: onnxruntime.experimental.fbs.TensorDataType,
rawDataOffset: flatbuffers.Offset, stringDataOffset: flatbuffers.Offset): flatbuffers.Offset {
Tensor.startTensor(builder);
Tensor.addName(builder, nameOffset);
Tensor.addDocString(builder, docStringOffset);
Tensor.addDims(builder, dimsOffset);
Tensor.addDataType(builder, dataType);
Tensor.addRawData(builder, rawDataOffset);
Tensor.addStringData(builder, stringDataOffset);
return Tensor.endTensor(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class SparseTensor {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns SparseTensor
*/
__init(i: number, bb: flatbuffers.ByteBuffer): SparseTensor {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SparseTensor= obj
* @returns SparseTensor
*/
static getRootAsSparseTensor(bb: flatbuffers.ByteBuffer, obj?: SparseTensor): SparseTensor {
return (obj || new SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SparseTensor= obj
* @returns SparseTensor
*/
static getSizePrefixedRootAsSparseTensor(bb: flatbuffers.ByteBuffer, obj?: SparseTensor): SparseTensor {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param onnxruntime.experimental.fbs.Tensor= obj
* @returns onnxruntime.experimental.fbs.Tensor|null
*/
values(obj?: onnxruntime.experimental.fbs.Tensor): onnxruntime.experimental.fbs.Tensor|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param onnxruntime.experimental.fbs.Tensor= obj
* @returns onnxruntime.experimental.fbs.Tensor|null
*/
indices(obj?: onnxruntime.experimental.fbs.Tensor): onnxruntime.experimental.fbs.Tensor|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param number index
* @returns flatbuffers.Long
*/
dims(index: number): flatbuffers.Long|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) :
this.bb!.createLong(0, 0);
}
/**
* @returns number
*/
dimsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startSparseTensor(builder: flatbuffers.Builder) {
builder.startObject(3);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset valuesOffset
*/
static addValues(builder: flatbuffers.Builder, valuesOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, valuesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset indicesOffset
*/
static addIndices(builder: flatbuffers.Builder, indicesOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, indicesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset dimsOffset
*/
static addDims(builder: flatbuffers.Builder, dimsOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, dimsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Long> data
* @returns flatbuffers.Offset
*/
static createDimsVector(builder: flatbuffers.Builder, data: flatbuffers.Long[]): flatbuffers.Offset {
builder.startVector(8, data.length, 8);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt64(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startDimsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(8, numElems, 8);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endSparseTensor(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createSparseTensor(
builder: flatbuffers.Builder, valuesOffset: flatbuffers.Offset, indicesOffset: flatbuffers.Offset,
dimsOffset: flatbuffers.Offset): flatbuffers.Offset {
SparseTensor.startSparseTensor(builder);
SparseTensor.addValues(builder, valuesOffset);
SparseTensor.addIndices(builder, indicesOffset);
SparseTensor.addDims(builder, dimsOffset);
return SparseTensor.endSparseTensor(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Attribute {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Attribute
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Attribute {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Attribute= obj
* @returns Attribute
*/
static getRootAsAttribute(bb: flatbuffers.ByteBuffer, obj?: Attribute): Attribute {
return (obj || new Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Attribute= obj
* @returns Attribute
*/
static getSizePrefixedRootAsAttribute(bb: flatbuffers.ByteBuffer, obj?: Attribute): Attribute {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
name(): string|null;
name(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
name(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
docString(): string|null;
docString(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
docString(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @returns onnxruntime.experimental.fbs.AttributeType
*/
type(): onnxruntime.experimental.fbs.AttributeType {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? /** */ (this.bb!.readInt32(this.bb_pos + offset)) :
onnxruntime.experimental.fbs.AttributeType.UNDEFINED;
}
/**
* @returns number
*/
f(): number {
let offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0;
}
/**
* @returns flatbuffers.Long
*/
i(): flatbuffers.Long {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
s(): string|null;
s(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
s(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param onnxruntime.experimental.fbs.Tensor= obj
* @returns onnxruntime.experimental.fbs.Tensor|null
*/
t(obj?: onnxruntime.experimental.fbs.Tensor): onnxruntime.experimental.fbs.Tensor|null {
let offset = this.bb!.__offset(this.bb_pos, 16);
return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param onnxruntime.experimental.fbs.Graph= obj
* @returns onnxruntime.experimental.fbs.Graph|null
*/
g(obj?: onnxruntime.experimental.fbs.Graph): onnxruntime.experimental.fbs.Graph|null {
let offset = this.bb!.__offset(this.bb_pos, 18);
return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param number index
* @returns number
*/
floats(index: number): number|null {
let offset = this.bb!.__offset(this.bb_pos, 20);
return offset ? this.bb!.readFloat32(this.bb!.__vector(this.bb_pos + offset) + index * 4) : 0;
}
/**
* @returns number
*/
floatsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 20);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @returns Float32Array
*/
floatsArray(): Float32Array|null {
let offset = this.bb!.__offset(this.bb_pos, 20);
return offset ?
new Float32Array(
this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset),
this.bb!.__vector_len(this.bb_pos + offset)) :
null;
}
/**
* @param number index
* @returns flatbuffers.Long
*/
ints(index: number): flatbuffers.Long|null {
let offset = this.bb!.__offset(this.bb_pos, 22);
return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) :
this.bb!.createLong(0, 0);
}
/**
* @returns number
*/
intsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 22);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
strings(index: number): string;
strings(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
strings(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 24);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
stringsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 24);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.Tensor= obj
* @returns onnxruntime.experimental.fbs.Tensor
*/
tensors(index: number, obj?: onnxruntime.experimental.fbs.Tensor): onnxruntime.experimental.fbs.Tensor|null {
let offset = this.bb!.__offset(this.bb_pos, 26);
return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
tensorsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 26);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.Graph= obj
* @returns onnxruntime.experimental.fbs.Graph
*/
graphs(index: number, obj?: onnxruntime.experimental.fbs.Graph): onnxruntime.experimental.fbs.Graph|null {
let offset = this.bb!.__offset(this.bb_pos, 28);
return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
graphsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 28);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startAttribute(builder: flatbuffers.Builder) {
builder.startObject(13);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nameOffset
*/
static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, nameOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset docStringOffset
*/
static addDocString(builder: flatbuffers.Builder, docStringOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, docStringOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param onnxruntime.experimental.fbs.AttributeType type
*/
static addType(builder: flatbuffers.Builder, type: onnxruntime.experimental.fbs.AttributeType) {
builder.addFieldInt32(2, type, onnxruntime.experimental.fbs.AttributeType.UNDEFINED);
}
/**
* @param flatbuffers.Builder builder
* @param number f
*/
static addF(builder: flatbuffers.Builder, f: number) {
builder.addFieldFloat32(3, f, 0.0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long i
*/
static addI(builder: flatbuffers.Builder, i: flatbuffers.Long) {
builder.addFieldInt64(4, i, builder.createLong(0, 0));
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset sOffset
*/
static addS(builder: flatbuffers.Builder, sOffset: flatbuffers.Offset) {
builder.addFieldOffset(5, sOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset tOffset
*/
static addT(builder: flatbuffers.Builder, tOffset: flatbuffers.Offset) {
builder.addFieldOffset(6, tOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset gOffset
*/
static addG(builder: flatbuffers.Builder, gOffset: flatbuffers.Offset) {
builder.addFieldOffset(7, gOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset floatsOffset
*/
static addFloats(builder: flatbuffers.Builder, floatsOffset: flatbuffers.Offset) {
builder.addFieldOffset(8, floatsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<number> data
* @returns flatbuffers.Offset
*/
static createFloatsVector(builder: flatbuffers.Builder, data: number[]|Uint8Array): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addFloat32(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startFloatsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset intsOffset
*/
static addInts(builder: flatbuffers.Builder, intsOffset: flatbuffers.Offset) {
builder.addFieldOffset(9, intsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Long> data
* @returns flatbuffers.Offset
*/
static createIntsVector(builder: flatbuffers.Builder, data: flatbuffers.Long[]): flatbuffers.Offset {
builder.startVector(8, data.length, 8);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt64(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startIntsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(8, numElems, 8);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset stringsOffset
*/
static addStrings(builder: flatbuffers.Builder, stringsOffset: flatbuffers.Offset) {
builder.addFieldOffset(10, stringsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createStringsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startStringsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset tensorsOffset
*/
static addTensors(builder: flatbuffers.Builder, tensorsOffset: flatbuffers.Offset) {
builder.addFieldOffset(11, tensorsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createTensorsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startTensorsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset graphsOffset
*/
static addGraphs(builder: flatbuffers.Builder, graphsOffset: flatbuffers.Offset) {
builder.addFieldOffset(12, graphsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createGraphsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startGraphsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endAttribute(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createAttribute(
builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset, docStringOffset: flatbuffers.Offset,
type: onnxruntime.experimental.fbs.AttributeType, f: number, i: flatbuffers.Long, sOffset: flatbuffers.Offset,
tOffset: flatbuffers.Offset, gOffset: flatbuffers.Offset, floatsOffset: flatbuffers.Offset,
intsOffset: flatbuffers.Offset, stringsOffset: flatbuffers.Offset, tensorsOffset: flatbuffers.Offset,
graphsOffset: flatbuffers.Offset): flatbuffers.Offset {
Attribute.startAttribute(builder);
Attribute.addName(builder, nameOffset);
Attribute.addDocString(builder, docStringOffset);
Attribute.addType(builder, type);
Attribute.addF(builder, f);
Attribute.addI(builder, i);
Attribute.addS(builder, sOffset);
Attribute.addT(builder, tOffset);
Attribute.addG(builder, gOffset);
Attribute.addFloats(builder, floatsOffset);
Attribute.addInts(builder, intsOffset);
Attribute.addStrings(builder, stringsOffset);
Attribute.addTensors(builder, tensorsOffset);
Attribute.addGraphs(builder, graphsOffset);
return Attribute.endAttribute(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Graph {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Graph
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Graph {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Graph= obj
* @returns Graph
*/
static getRootAsGraph(bb: flatbuffers.ByteBuffer, obj?: Graph): Graph {
return (obj || new Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Graph= obj
* @returns Graph
*/
static getSizePrefixedRootAsGraph(bb: flatbuffers.ByteBuffer, obj?: Graph): Graph {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.Tensor= obj
* @returns onnxruntime.experimental.fbs.Tensor
*/
initializers(index: number, obj?: onnxruntime.experimental.fbs.Tensor): onnxruntime.experimental.fbs.Tensor|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? (obj || new onnxruntime.experimental.fbs.Tensor())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
initializersLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.ValueInfo= obj
* @returns onnxruntime.experimental.fbs.ValueInfo
*/
nodeArgs(index: number, obj?: onnxruntime.experimental.fbs.ValueInfo): onnxruntime.experimental.fbs.ValueInfo|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.ValueInfo())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
nodeArgsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.Node= obj
* @returns onnxruntime.experimental.fbs.Node
*/
nodes(index: number, obj?: onnxruntime.experimental.fbs.Node): onnxruntime.experimental.fbs.Node|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? (obj || new onnxruntime.experimental.fbs.Node())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
nodesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @returns number
*/
maxNodeIndex(): number {
let offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.NodeEdge= obj
* @returns onnxruntime.experimental.fbs.NodeEdge
*/
nodeEdges(index: number, obj?: onnxruntime.experimental.fbs.NodeEdge): onnxruntime.experimental.fbs.NodeEdge|null {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? (obj || new onnxruntime.experimental.fbs.NodeEdge())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
nodeEdgesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
inputs(index: number): string;
inputs(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
inputs(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
inputsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array
*/
outputs(index: number): string;
outputs(index: number, optionalEncoding: flatbuffers.Encoding): string|Uint8Array;
outputs(index: number, optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 16);
return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
}
/**
* @returns number
*/
outputsLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 16);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.SparseTensor= obj
* @returns onnxruntime.experimental.fbs.SparseTensor
*/
sparseInitializers(index: number, obj?: onnxruntime.experimental.fbs.SparseTensor):
onnxruntime.experimental.fbs.SparseTensor|null {
let offset = this.bb!.__offset(this.bb_pos, 18);
return offset ? (obj || new onnxruntime.experimental.fbs.SparseTensor())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
sparseInitializersLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 18);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startGraph(builder: flatbuffers.Builder) {
builder.startObject(8);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset initializersOffset
*/
static addInitializers(builder: flatbuffers.Builder, initializersOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, initializersOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createInitializersVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startInitializersVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nodeArgsOffset
*/
static addNodeArgs(builder: flatbuffers.Builder, nodeArgsOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, nodeArgsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createNodeArgsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startNodeArgsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nodesOffset
*/
static addNodes(builder: flatbuffers.Builder, nodesOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, nodesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createNodesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startNodesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param number maxNodeIndex
*/
static addMaxNodeIndex(builder: flatbuffers.Builder, maxNodeIndex: number) {
builder.addFieldInt32(3, maxNodeIndex, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nodeEdgesOffset
*/
static addNodeEdges(builder: flatbuffers.Builder, nodeEdgesOffset: flatbuffers.Offset) {
builder.addFieldOffset(4, nodeEdgesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createNodeEdgesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startNodeEdgesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset inputsOffset
*/
static addInputs(builder: flatbuffers.Builder, inputsOffset: flatbuffers.Offset) {
builder.addFieldOffset(5, inputsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createInputsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startInputsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset outputsOffset
*/
static addOutputs(builder: flatbuffers.Builder, outputsOffset: flatbuffers.Offset) {
builder.addFieldOffset(6, outputsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createOutputsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startOutputsVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset sparseInitializersOffset
*/
static addSparseInitializers(builder: flatbuffers.Builder, sparseInitializersOffset: flatbuffers.Offset) {
builder.addFieldOffset(7, sparseInitializersOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createSparseInitializersVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]):
flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startSparseInitializersVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endGraph(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createGraph(
builder: flatbuffers.Builder, initializersOffset: flatbuffers.Offset, nodeArgsOffset: flatbuffers.Offset,
nodesOffset: flatbuffers.Offset, maxNodeIndex: number, nodeEdgesOffset: flatbuffers.Offset,
inputsOffset: flatbuffers.Offset, outputsOffset: flatbuffers.Offset,
sparseInitializersOffset: flatbuffers.Offset): flatbuffers.Offset {
Graph.startGraph(builder);
Graph.addInitializers(builder, initializersOffset);
Graph.addNodeArgs(builder, nodeArgsOffset);
Graph.addNodes(builder, nodesOffset);
Graph.addMaxNodeIndex(builder, maxNodeIndex);
Graph.addNodeEdges(builder, nodeEdgesOffset);
Graph.addInputs(builder, inputsOffset);
Graph.addOutputs(builder, outputsOffset);
Graph.addSparseInitializers(builder, sparseInitializersOffset);
return Graph.endGraph(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class Model {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Model
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Model {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Model= obj
* @returns Model
*/
static getRootAsModel(bb: flatbuffers.ByteBuffer, obj?: Model): Model {
return (obj || new Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param Model= obj
* @returns Model
*/
static getSizePrefixedRootAsModel(bb: flatbuffers.ByteBuffer, obj?: Model): Model {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @returns flatbuffers.Long
*/
irVersion(): flatbuffers.Long {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.OperatorSetId= obj
* @returns onnxruntime.experimental.fbs.OperatorSetId
*/
opsetImport(index: number, obj?: onnxruntime.experimental.fbs.OperatorSetId):
onnxruntime.experimental.fbs.OperatorSetId|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.OperatorSetId())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
opsetImportLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
producerName(): string|null;
producerName(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
producerName(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
producerVersion(): string|null;
producerVersion(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
producerVersion(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 10);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
domain(): string|null;
domain(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
domain(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 12);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @returns flatbuffers.Long
*/
modelVersion(): flatbuffers.Long {
let offset = this.bb!.__offset(this.bb_pos, 14);
return offset ? this.bb!.readInt64(this.bb_pos + offset) : this.bb!.createLong(0, 0);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
docString(): string|null;
docString(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
docString(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 16);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param onnxruntime.experimental.fbs.Graph= obj
* @returns onnxruntime.experimental.fbs.Graph|null
*/
graph(obj?: onnxruntime.experimental.fbs.Graph): onnxruntime.experimental.fbs.Graph|null {
let offset = this.bb!.__offset(this.bb_pos, 18);
return offset ? (obj || new onnxruntime.experimental.fbs.Graph())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
graphDocString(): string|null;
graphDocString(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
graphDocString(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 20);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param flatbuffers.Builder builder
*/
static startModel(builder: flatbuffers.Builder) {
builder.startObject(9);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long irVersion
*/
static addIrVersion(builder: flatbuffers.Builder, irVersion: flatbuffers.Long) {
builder.addFieldInt64(0, irVersion, builder.createLong(0, 0));
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset opsetImportOffset
*/
static addOpsetImport(builder: flatbuffers.Builder, opsetImportOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, opsetImportOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createOpsetImportVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startOpsetImportVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset producerNameOffset
*/
static addProducerName(builder: flatbuffers.Builder, producerNameOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, producerNameOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset producerVersionOffset
*/
static addProducerVersion(builder: flatbuffers.Builder, producerVersionOffset: flatbuffers.Offset) {
builder.addFieldOffset(3, producerVersionOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset domainOffset
*/
static addDomain(builder: flatbuffers.Builder, domainOffset: flatbuffers.Offset) {
builder.addFieldOffset(4, domainOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long modelVersion
*/
static addModelVersion(builder: flatbuffers.Builder, modelVersion: flatbuffers.Long) {
builder.addFieldInt64(5, modelVersion, builder.createLong(0, 0));
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset docStringOffset
*/
static addDocString(builder: flatbuffers.Builder, docStringOffset: flatbuffers.Offset) {
builder.addFieldOffset(6, docStringOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset graphOffset
*/
static addGraph(builder: flatbuffers.Builder, graphOffset: flatbuffers.Offset) {
builder.addFieldOffset(7, graphOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset graphDocStringOffset
*/
static addGraphDocString(builder: flatbuffers.Builder, graphDocStringOffset: flatbuffers.Offset) {
builder.addFieldOffset(8, graphDocStringOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endModel(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createModel(
builder: flatbuffers.Builder, irVersion: flatbuffers.Long, opsetImportOffset: flatbuffers.Offset,
producerNameOffset: flatbuffers.Offset, producerVersionOffset: flatbuffers.Offset,
domainOffset: flatbuffers.Offset, modelVersion: flatbuffers.Long, docStringOffset: flatbuffers.Offset,
graphOffset: flatbuffers.Offset, graphDocStringOffset: flatbuffers.Offset): flatbuffers.Offset {
Model.startModel(builder);
Model.addIrVersion(builder, irVersion);
Model.addOpsetImport(builder, opsetImportOffset);
Model.addProducerName(builder, producerNameOffset);
Model.addProducerVersion(builder, producerVersionOffset);
Model.addDomain(builder, domainOffset);
Model.addModelVersion(builder, modelVersion);
Model.addDocString(builder, docStringOffset);
Model.addGraph(builder, graphOffset);
Model.addGraphDocString(builder, graphDocStringOffset);
return Model.endModel(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class KernelCreateInfos {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns KernelCreateInfos
*/
__init(i: number, bb: flatbuffers.ByteBuffer): KernelCreateInfos {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param KernelCreateInfos= obj
* @returns KernelCreateInfos
*/
static getRootAsKernelCreateInfos(bb: flatbuffers.ByteBuffer, obj?: KernelCreateInfos): KernelCreateInfos {
return (obj || new KernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param KernelCreateInfos= obj
* @returns KernelCreateInfos
*/
static getSizePrefixedRootAsKernelCreateInfos(bb: flatbuffers.ByteBuffer, obj?: KernelCreateInfos):
KernelCreateInfos {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new KernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param number index
* @returns number
*/
nodeIndices(index: number): number|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.readUint32(this.bb!.__vector(this.bb_pos + offset) + index * 4) : 0;
}
/**
* @returns number
*/
nodeIndicesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @returns Uint32Array
*/
nodeIndicesArray(): Uint32Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ?
new Uint32Array(
this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset),
this.bb!.__vector_len(this.bb_pos + offset)) :
null;
}
/**
* @param number index
* @returns flatbuffers.Long
*/
kernelDefHashes(index: number): flatbuffers.Long|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) :
this.bb!.createLong(0, 0);
}
/**
* @returns number
*/
kernelDefHashesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startKernelCreateInfos(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nodeIndicesOffset
*/
static addNodeIndices(builder: flatbuffers.Builder, nodeIndicesOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, nodeIndicesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<number> data
* @returns flatbuffers.Offset
*/
static createNodeIndicesVector(builder: flatbuffers.Builder, data: number[]|Uint8Array): flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt32(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startNodeIndicesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset kernelDefHashesOffset
*/
static addKernelDefHashes(builder: flatbuffers.Builder, kernelDefHashesOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, kernelDefHashesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Long> data
* @returns flatbuffers.Offset
*/
static createKernelDefHashesVector(builder: flatbuffers.Builder, data: flatbuffers.Long[]): flatbuffers.Offset {
builder.startVector(8, data.length, 8);
for (let i = data.length - 1; i >= 0; i--) {
builder.addInt64(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startKernelDefHashesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(8, numElems, 8);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endKernelCreateInfos(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createKernelCreateInfos(
builder: flatbuffers.Builder, nodeIndicesOffset: flatbuffers.Offset,
kernelDefHashesOffset: flatbuffers.Offset): flatbuffers.Offset {
KernelCreateInfos.startKernelCreateInfos(builder);
KernelCreateInfos.addNodeIndices(builder, nodeIndicesOffset);
KernelCreateInfos.addKernelDefHashes(builder, kernelDefHashesOffset);
return KernelCreateInfos.endKernelCreateInfos(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class SubGraphSessionState {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns SubGraphSessionState
*/
__init(i: number, bb: flatbuffers.ByteBuffer): SubGraphSessionState {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SubGraphSessionState= obj
* @returns SubGraphSessionState
*/
static getRootAsSubGraphSessionState(bb: flatbuffers.ByteBuffer, obj?: SubGraphSessionState): SubGraphSessionState {
return (obj || new SubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SubGraphSessionState= obj
* @returns SubGraphSessionState
*/
static getSizePrefixedRootAsSubGraphSessionState(bb: flatbuffers.ByteBuffer, obj?: SubGraphSessionState):
SubGraphSessionState {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new SubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
graphId(): string|null;
graphId(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
graphId(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param onnxruntime.experimental.fbs.SessionState= obj
* @returns onnxruntime.experimental.fbs.SessionState|null
*/
sessionState(obj?: onnxruntime.experimental.fbs.SessionState): onnxruntime.experimental.fbs.SessionState|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.SessionState())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Builder builder
*/
static startSubGraphSessionState(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset graphIdOffset
*/
static addGraphId(builder: flatbuffers.Builder, graphIdOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, graphIdOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset sessionStateOffset
*/
static addSessionState(builder: flatbuffers.Builder, sessionStateOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, sessionStateOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endSubGraphSessionState(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
builder.requiredField(offset, 4); // graph_id
return offset;
}
static createSubGraphSessionState(
builder: flatbuffers.Builder, graphIdOffset: flatbuffers.Offset,
sessionStateOffset: flatbuffers.Offset): flatbuffers.Offset {
SubGraphSessionState.startSubGraphSessionState(builder);
SubGraphSessionState.addGraphId(builder, graphIdOffset);
SubGraphSessionState.addSessionState(builder, sessionStateOffset);
return SubGraphSessionState.endSubGraphSessionState(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class SessionState {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns SessionState
*/
__init(i: number, bb: flatbuffers.ByteBuffer): SessionState {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SessionState= obj
* @returns SessionState
*/
static getRootAsSessionState(bb: flatbuffers.ByteBuffer, obj?: SessionState): SessionState {
return (obj || new SessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param SessionState= obj
* @returns SessionState
*/
static getSizePrefixedRootAsSessionState(bb: flatbuffers.ByteBuffer, obj?: SessionState): SessionState {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new SessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param onnxruntime.experimental.fbs.KernelCreateInfos= obj
* @returns onnxruntime.experimental.fbs.KernelCreateInfos|null
*/
kernels(obj?: onnxruntime.experimental.fbs.KernelCreateInfos): onnxruntime.experimental.fbs.KernelCreateInfos|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? (obj || new onnxruntime.experimental.fbs.KernelCreateInfos())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param number index
* @param onnxruntime.experimental.fbs.SubGraphSessionState= obj
* @returns onnxruntime.experimental.fbs.SubGraphSessionState
*/
subGraphSessionStates(index: number, obj?: onnxruntime.experimental.fbs.SubGraphSessionState):
onnxruntime.experimental.fbs.SubGraphSessionState|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.SubGraphSessionState())
.__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) :
null;
}
/**
* @returns number
*/
subGraphSessionStatesLength(): number {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0;
}
/**
* @param flatbuffers.Builder builder
*/
static startSessionState(builder: flatbuffers.Builder) {
builder.startObject(2);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset kernelsOffset
*/
static addKernels(builder: flatbuffers.Builder, kernelsOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, kernelsOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset subGraphSessionStatesOffset
*/
static addSubGraphSessionStates(builder: flatbuffers.Builder, subGraphSessionStatesOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, subGraphSessionStatesOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createSubGraphSessionStatesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]):
flatbuffers.Offset {
builder.startVector(4, data.length, 4);
for (let i = data.length - 1; i >= 0; i--) {
builder.addOffset(data[i]);
}
return builder.endVector();
}
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startSubGraphSessionStatesVector(builder: flatbuffers.Builder, numElems: number) {
builder.startVector(4, numElems, 4);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endSessionState(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
static createSessionState(
builder: flatbuffers.Builder, kernelsOffset: flatbuffers.Offset,
subGraphSessionStatesOffset: flatbuffers.Offset): flatbuffers.Offset {
SessionState.startSessionState(builder);
SessionState.addKernels(builder, kernelsOffset);
SessionState.addSubGraphSessionStates(builder, subGraphSessionStatesOffset);
return SessionState.endSessionState(builder);
}
}
}
/**
* @constructor
*/
export namespace onnxruntime.experimental.fbs {
export class InferenceSession {
bb: flatbuffers.ByteBuffer|null = null;
bb_pos = 0;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns InferenceSession
*/
__init(i: number, bb: flatbuffers.ByteBuffer): InferenceSession {
this.bb_pos = i;
this.bb = bb;
return this;
}
/**
* @param flatbuffers.ByteBuffer bb
* @param InferenceSession= obj
* @returns InferenceSession
*/
static getRootAsInferenceSession(bb: flatbuffers.ByteBuffer, obj?: InferenceSession): InferenceSession {
return (obj || new InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @param InferenceSession= obj
* @returns InferenceSession
*/
static getSizePrefixedRootAsInferenceSession(bb: flatbuffers.ByteBuffer, obj?: InferenceSession): InferenceSession {
bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH);
return (obj || new InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
}
/**
* @param flatbuffers.ByteBuffer bb
* @returns boolean
*/
static bufferHasIdentifier(bb: flatbuffers.ByteBuffer): boolean {
return bb.__has_identifier('ORTM');
}
/**
* @param flatbuffers.Encoding= optionalEncoding
* @returns string|Uint8Array|null
*/
ortVersion(): string|null;
ortVersion(optionalEncoding: flatbuffers.Encoding): string|Uint8Array|null;
ortVersion(optionalEncoding?: any): string|Uint8Array|null {
let offset = this.bb!.__offset(this.bb_pos, 4);
return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null;
}
/**
* @param onnxruntime.experimental.fbs.Model= obj
* @returns onnxruntime.experimental.fbs.Model|null
*/
model(obj?: onnxruntime.experimental.fbs.Model): onnxruntime.experimental.fbs.Model|null {
let offset = this.bb!.__offset(this.bb_pos, 6);
return offset ? (obj || new onnxruntime.experimental.fbs.Model())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param onnxruntime.experimental.fbs.SessionState= obj
* @returns onnxruntime.experimental.fbs.SessionState|null
*/
sessionState(obj?: onnxruntime.experimental.fbs.SessionState): onnxruntime.experimental.fbs.SessionState|null {
let offset = this.bb!.__offset(this.bb_pos, 8);
return offset ? (obj || new onnxruntime.experimental.fbs.SessionState())
.__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) :
null;
}
/**
* @param flatbuffers.Builder builder
*/
static startInferenceSession(builder: flatbuffers.Builder) {
builder.startObject(3);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset ortVersionOffset
*/
static addOrtVersion(builder: flatbuffers.Builder, ortVersionOffset: flatbuffers.Offset) {
builder.addFieldOffset(0, ortVersionOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset modelOffset
*/
static addModel(builder: flatbuffers.Builder, modelOffset: flatbuffers.Offset) {
builder.addFieldOffset(1, modelOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset sessionStateOffset
*/
static addSessionState(builder: flatbuffers.Builder, sessionStateOffset: flatbuffers.Offset) {
builder.addFieldOffset(2, sessionStateOffset, 0);
}
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endInferenceSession(builder: flatbuffers.Builder): flatbuffers.Offset {
let offset = builder.endObject();
return offset;
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset offset
*/
static finishInferenceSessionBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset) {
builder.finish(offset, 'ORTM');
}
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset offset
*/
static finishSizePrefixedInferenceSessionBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset) {
builder.finish(offset, 'ORTM', true);
}
static createInferenceSession(
builder: flatbuffers.Builder, ortVersionOffset: flatbuffers.Offset, modelOffset: flatbuffers.Offset,
sessionStateOffset: flatbuffers.Offset): flatbuffers.Offset {
InferenceSession.startInferenceSession(builder);
InferenceSession.addOrtVersion(builder, ortVersionOffset);
InferenceSession.addModel(builder, modelOffset);
InferenceSession.addSessionState(builder, sessionStateOffset);
return InferenceSession.endInferenceSession(builder);
}
}
} | the_stack |
import * as React from 'react';
/**
* React Props interface
*/
interface ICommentHeaderProps {
/**
* Text comment to display
*
* @type string
*/
context: string;
/**
* State if the comment is edited
*
* @type boolean
*/
edited: boolean;
/**
* Tracks the state if the card is expanded
*
* @type boolean
*/
expanded: boolean;
/**
* Function to handle the CommentCard expanding
*
* @type void
*/
handleExpand: () => void;
/**
* Reverses resolve state
*
* @type: void
*/
handleResolve: () => void;
/**
* Handles expanding
*
* @type void
*/
handleShouldExpand: (state: boolean) => void;
/**
* Function to handle the CommentCard shrinking
*
* @type void
*/
handleShrink: () => void;
/**
* Tracks if cursor is hovering over card
*
* @type boolean
*/
hover: boolean;
/**
* State if is editing a comment
*
* @param key Type: string - key of what is being edited,
* for comment header it is the threadID
*/
isEditing(key: string): boolean;
/**
* Person name of comment
*
* @type string
*/
name: string;
/**
* URL to Person photo to display
*
* @type string
*/
photo: string;
/**
* Updates the comment value of a thread
*/
putThreadEdit(threadId: string, value: string): void;
/**
* Is the card resolved
*
* @type boolean
*/
resolved: boolean;
/**
* Handles setting the state of isEditing
*
* @param key Type: string - sets the state to the given key (threadId)
*/
setIsEditing(key: string): void;
/**
* Time stamp of comment
*
* @type string
*/
timestamp: string;
/**
* Id of the thread
*
* @type string
*/
threadId: string;
}
/**
* CommentHeader React States
*/
interface ICommentHeaderStates {
/**
* State of drop down menu
*/
moreOptionsOpened: boolean;
/**
* Text of the edit box
*/
editBox: string;
/**
* Tracks if the comment was edited when the edit button is clicked
*/
contextEdited: boolean;
/**
* Boolean to track if mouse is hovering over comment
*/
hover: boolean;
}
/**
* CommentHeader React Component
*/
export class CommentHeader extends React.Component<
ICommentHeaderProps,
ICommentHeaderStates
> {
/**
* Constructor
*
* @param props React props
*/
constructor(props: ICommentHeaderProps) {
super(props);
this.state = {
moreOptionsOpened: false,
editBox: '',
hover: false,
contextEdited: false
};
this.handleChangeEditBox = this.handleChangeEditBox.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.handleEditCancelButton = this.handleEditCancelButton.bind(this);
this.handleEditSaveButton = this.handleEditSaveButton.bind(this);
}
/**
* React render function
*/
render(): React.ReactNode {
return this.props.resolved ? (
<div style={this.styles['jp-commenting-thread-header-resolved']}>
<div
style={this.styles['jp-commenting-thread-header-upper-area-resolved']}
>
<div style={this.styles['jp-commenting-thread-header-photo-area']}>
<img
style={this.styles['jp-commenting-thread-header-photo-resolved']}
src={this.props.photo}
/>
</div>
<div style={this.styles['jp-commenting-thread-header-info-area']}>
<div style={this.styles['jp-commenting-thread-header-name-area']}>
<h1
style={this.styles['jp-commenting-thread-header-name-resolved']}
>
{this.props.name}
</h1>
</div>
<div
style={this.styles['jp-commenting-thread-header-timestamp-area']}
>
<p
style={
this.styles['jp-commenting-thread-header-timestamp-resolved']
}
>
{(this.props.edited &&
'Edited on: ' + this.getStyledTimeStamp()) ||
this.getStyledTimeStamp()}
</p>
</div>
</div>
{this.getCornerButton()}
</div>
<div style={this.styles['jp-commenting-annotation-area-resolved']}>
<p style={this.styles['jp-commenting-annotation-resolved']}>
{this.props.context.length >= 125 && !this.props.expanded
? this.props.context.slice(0, 125) + '...'
: this.props.context}
</p>
</div>
</div>
) : (
<div
style={this.styles['jp-commenting-thread-header']}
onMouseOver={() => this.handleMouseOver()}
onMouseLeave={() => this.handleMouseLeave()}
>
<div style={this.styles['jp-commenting-thread-header-upper-area']}>
<div style={this.styles['jp-commenting-thread-header-photo-area']}>
<img
style={this.styles['jp-commenting-thread-header-photo']}
src={this.props.photo}
/>
</div>
<div style={this.styles['jp-commenting-thread-header-info-area']}>
<div style={this.styles['jp-commenting-thread-header-name-area']}>
<h1 style={this.styles['jp-commenting-thread-header-name']}>
{this.props.name}
</h1>
</div>
<div
style={this.styles['jp-commenting-thread-header-timestamp-area']}
>
<p style={this.styles['jp-commenting-thread-header-timestamp']}>
{(this.props.edited &&
'Edited on: ' + this.getStyledTimeStamp()) ||
this.getStyledTimeStamp()}
</p>
{this.state.hover &&
!this.props.isEditing(this.props.threadId) &&
this.props.expanded && (
<div
style={this.styles['jp-commenting-annotation-more-area']}
>
<p style={this.styles['jp-commenting-annotation-more']}>
•
</p>
<a
style={this.styles['jp-commenting-annotation-more']}
className={'jp-commenting-clickable-text'}
onClick={() => {
this.setState({ editBox: '' });
this.props.setIsEditing(this.props.threadId);
}}
>
Edit
</a>
</div>
)}
</div>
</div>
{this.getCornerButton()}
</div>
<div style={this.styles['jp-commenting-annotation-area']}>
{this.props.isEditing(this.props.threadId) && this.props.expanded ? (
<textarea
className="jp-commenting-text-area"
id="editBox"
value={
this.state.editBox.trim() === ''
? this.state.contextEdited
? this.state.editBox
: this.props.context
: this.state.editBox
}
onChange={this.handleChangeEditBox}
onKeyPress={this.handleKeyPress}
/>
) : (
<p style={this.styles['jp-commenting-annotation']}>
{this.props.context.length >= 125 && !this.props.expanded
? this.props.context.slice(0, 125) + '...'
: this.props.context}
</p>
)}
{this.getEditButtons()}
</div>
</div>
);
}
/**
* Creates and returns resolve button
*
* @return Type: React.ReactNode
*/
getResolveButton(): React.ReactNode {
return (
<button
className="jp-commenting-button-blue"
type="button"
onClick={this.props.handleResolve}
onMouseEnter={() => this.props.handleShouldExpand(false)}
onMouseLeave={() => this.props.handleShouldExpand(true)}
>
Resolve
</button>
);
}
/**
* Creates and returns re-open button
*
* @type Type: React.ReactNode
*/
getReopenButton(): React.ReactNode {
return (
<button
className="jp-commenting-button-blue jp-commenting-button-resolved"
type="button"
onClick={this.props.handleResolve}
onMouseEnter={() => this.props.handleShouldExpand(false)}
onMouseLeave={() => this.props.handleShouldExpand(true)}
>
Re-open
</button>
);
}
/**
* Handles key events
*
* @param e Type: React.KeyboardEvent - keyboard event
*/
handleKeyPress(e: React.KeyboardEvent): void {
// Enables pressing enter key to save a comment
if (this.state.editBox.trim() !== '' && e.key === 'Enter' && !e.shiftKey) {
this.handleEditSaveButton();
document.getElementById('commentBox').blur();
}
}
/**
* Handles when the edit box changes
*
* @param e Type: React.ChangeEvent<HTMLTextAreaElement> - input box event
*/
handleChangeEditBox(e: React.ChangeEvent<HTMLTextAreaElement>): void {
this.setState({ editBox: e.target.value, contextEdited: true });
}
/**
* Handles clicking the save button
*/
handleEditSaveButton(): void {
this.props.putThreadEdit(this.props.threadId, this.state.editBox);
this.setState({ editBox: '', contextEdited: false });
this.props.setIsEditing('');
}
/**
* Handles states when cancel is pressed
*/
handleEditCancelButton(): void {
this.setState({ editBox: '', contextEdited: false });
this.props.setIsEditing('');
}
/**
* Returns the correct buttons for different state combinations
*
* @return Type: React.ReactNode - JSX with buttons
*/
getEditButtons(): React.ReactNode {
if (this.props.isEditing(this.props.threadId) && this.props.expanded) {
let element = document.getElementById('editBox') as HTMLTextAreaElement;
if (element !== null) {
// Focus editbox and set cursor to the end
element.focus();
element.setSelectionRange(element.value.length, element.value.length);
}
return (
<div
style={this.styles['jp-commenting-thread-header-edit-buttons-area']}
>
{this.getEditSaveButton()}
{this.getEditCancelButton()}
</div>
);
}
}
/**
* Creates and returns save button
*
* @return Type: React.ReactNode
*/
getEditSaveButton(): React.ReactNode {
return (
<button
onClick={this.handleEditSaveButton}
className="jp-commenting-button-blue"
type="button"
disabled={this.state.editBox.trim() === ''}
>
Save
</button>
);
}
/**
* Creates and returns cancel button
*
* @return Type: React.ReactNode
*/
getEditCancelButton(): React.ReactNode {
return (
<button
onClick={this.handleEditCancelButton}
className="jp-commenting-button-red"
type="button"
>
Cancel
</button>
);
}
/**
* Handles hover state when mouse is over comment header
*/
handleMouseOver(): void {
this.setState({ hover: true });
}
/**
* Handles hover state when mouse leaves comment header
*/
handleMouseLeave(): void {
this.setState({ hover: false });
}
/**
* Creates and returns the resolve or re-open button based on states
*
* @type React.ReactNode
*/
getCornerButton(): React.ReactNode {
if (this.props.hover && !this.props.expanded) {
return (
<div style={this.styles['jp-commenting-thread-header-button-area']}>
<div
style={
this.styles[
'jp-commenting-thread-header-resolve-reopen-button-area'
]
}
>
{!this.props.resolved
? this.getResolveButton()
: this.getReopenButton()}
</div>
</div>
);
} else if (this.props.expanded) {
return (
<div style={this.styles['jp-commenting-thread-header-button-area']}>
<div
style={
this.styles[
'jp-commenting-thread-header-resolve-reopen-button-area'
]
}
>
{!this.props.resolved
? this.getResolveButton()
: this.getReopenButton()}
</div>
</div>
);
} else {
return;
}
}
/**
* Styles and returns timestamp
*
* @type string
*/
getStyledTimeStamp(): string {
let serverTimeStamp = new Date(this.props.timestamp);
let localTimeStamp = serverTimeStamp.toLocaleString();
let fullDate = localTimeStamp.split(',')[0].split('/');
let fullTime = localTimeStamp.split(',')[1].split(':');
let timeIdentifier = fullTime[2].slice(3).toLowerCase();
let month: { [key: string]: String } = {
'1': 'Jan',
'2': 'Feb',
'3': 'Mar',
'4': 'Apr',
'5': 'May',
'6': 'Jun',
'7': 'Jul',
'8': 'Aug',
'9': 'Sep',
'10': 'Oct',
'11': 'Nov',
'12': 'Dec'
};
let timestamp =
month[fullDate[0]] +
' ' +
fullDate[1] +
fullTime[0] +
':' +
fullTime[1] +
timeIdentifier;
return timestamp;
}
/**
* CSS styles
*/
styles = {
'jp-commenting-thread-header': {
background: 'var(--jp-layout-color1)'
},
'jp-commenting-thread-header-resolved': {
background: 'var(--jp-layout-color2)'
},
'jp-commenting-thread-header-upper-area': {
display: 'flex',
flexDirection: 'row' as 'row',
boxSizing: 'border-box' as 'border-box',
padding: '4px',
background: 'var(--jp-layout-color1)'
},
'jp-commenting-thread-header-upper-area-resolved': {
display: 'flex',
flexDirection: 'row' as 'row',
boxSizing: 'border-box' as 'border-box',
padding: '4px',
background: 'var(--jp-layout-color2)'
},
'jp-commenting-thread-header-info-area': {
display: 'flex',
flexDirection: 'column' as 'column',
flexShrink: 1,
minWidth: '32px',
width: '100%',
paddingLeft: '4px',
boxSizing: 'border-box' as 'border-box'
},
'jp-commenting-thread-header-photo-area': {
display: 'flex'
},
'jp-commenting-thread-header-photo': {
height: '36px',
width: '36px',
borderRadius: 'var(--jp-border-radius)'
},
'jp-commenting-thread-header-photo-resolved': {
height: '36px',
width: '36px',
opacity: 0.5,
borderRadius: 'var(--jp-border-radius)'
},
'jp-commenting-thread-header-name-area': {
display: 'flex',
flexShrink: 1,
minWidth: '32px',
boxSizing: 'border-box' as 'border-box'
},
'jp-commenting-thread-header-name': {
fontSize: '13px',
color: 'var(--jp-ui-font-color1)',
fontWeight: 'bold' as 'bold',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
margin: '0px'
},
'jp-commenting-thread-header-edit-buttons-area': {
display: 'flex',
padding: '4px'
},
'jp-commenting-thread-header-name-resolved': {
fontSize: '13px',
color: 'var(--jp-ui-font-color2)',
fontWeight: 'bold' as 'bold',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
margin: '0px'
},
'jp-commenting-thread-header-timestamp-area': {
display: 'flex',
minWidth: '32px',
flexShrink: 1,
boxSizing: 'border-box' as 'border-box'
},
'jp-commenting-thread-header-timestamp': {
fontSize: 'var(--jp-ui-font-size0)',
color: 'var(--jp-ui-font-color1)',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis'
},
'jp-commenting-annotation-more-area': {
display: 'flex',
flexDirection: 'row' as 'row',
minWidth: '64px',
flexShrink: 1,
boxSizing: 'border-box' as 'border-box'
},
'jp-commenting-annotation-more': {
display: 'flex',
fontSize: 'var(--jp-ui-font-size0)',
paddingLeft: '4px',
color: 'var(--jp-ui-font-color1)'
},
'jp-commenting-thread-header-timestamp-resolved': {
fontSize: 'var(--jp-ui-font-size0)',
color: 'var(--jp-ui-font-color2)',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis'
},
'jp-commenting-annotation-area': {
display: 'flex',
flexDirection: 'column' as 'column',
maxHeight: '100%',
maxWidth: '350px',
boxSizing: 'border-box' as 'border-box',
paddingBottom: '4px',
paddingLeft: '4px',
paddingRight: '4px',
background: 'var(--jp-layout-color1)'
},
'jp-commenting-annotation': {
fontSize: 'var(--jp-content-font-size0)',
color: 'var(--jp-ui-font-color1)',
lineHeight: 'normal'
},
'jp-commenting-annotation-area-resolved': {
display: 'flex',
maxHeight: '100%',
maxWidth: '350px',
boxSizing: 'border-box' as 'border-box',
paddingBottom: '4px',
paddingLeft: '4px',
paddingRight: '4px',
background: 'var(--jp-layout-color2)'
},
'jp-commenting-annotation-resolved': {
fontSize: 'var(--jp-content-font-size0)',
color: 'var(--jp-ui-font-color2)',
lineHeight: 'normal'
},
'jp-commenting-thread-header-more-icon-area': {
display: 'flex',
paddingRight: '4px',
paddingLeft: '4px',
boxSizing: 'border-box' as 'border-box'
},
'jp-commenting-annotation-more-icon': {
backgroundSize: '16px',
margin: '0px',
minWidth: '16px',
minHeight: '16px',
boxSizing: 'border-box' as 'border-box'
},
'jp-commenting-thread-header-resolve-reopen-button-area': {
display: 'flex'
},
'jp-commenting-thread-header-button-area': {
display: 'flex',
minWidth: '72px',
maxHeight: '18px',
paddingRight: '4px',
paddingLeft: '4px',
boxSizing: 'border-box' as 'border-box'
}
};
} | the_stack |
import {createStore, createEvent, guard, Event} from 'effector'
const typecheck = '{global}'
test('wide union (should fail)', () => {
const trigger: Event<{a: 1} | {a: 2} | {a: 3}> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<{a: 1} | {a: 2}> = createEvent()
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target,
})
//@ts-expect-error
const result1: typeof target = guard({
clock: trigger,
filter: allow,
})
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target: [target],
})
//@ts-expect-error
const result2: [typeof target] = guard({
clock: trigger,
filter: allow,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ a: 1; } | { a: 2; }>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<{ a: 1; } | { a: 2; } | { a: 3; }>' is not assignable to type 'Event<{ a: 1; } | { a: 2; }>'.
Types of property 'watch' are incompatible.
Type '(watcher: (payload: { a: 1; } | { a: 2; } | { a: 3; }) => any) => Subscription' is not assignable to type '(watcher: (payload: { a: 1; } | { a: 2; }) => any) => Subscription'.
Types of parameters 'watcher' and 'watcher' are incompatible.
Types of parameters 'payload' and 'payload' are incompatible.
Type '{ a: 1; } | { a: 2; } | { a: 3; }' is not assignable to type '{ a: 1; } | { a: 2; }'.
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ a: 1; } | { a: 2; }>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<{ a: 1; } | { a: 2; } | { a: 3; }>' is not assignable to type '[Event<{ a: 1; } | { a: 2; }>]'.
"
`)
})
test('narrow union (should pass)', () => {
const trigger: Event<{a: 1} | {a: 2}> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<{a: 1} | {a: 2} | {a: 3}> = createEvent()
guard({
clock: trigger,
filter: allow,
target,
})
guard({
clock: trigger,
filter: allow,
target: [target],
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('unknown type in source (should fail)', () => {
const trigger: Event<unknown> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<string> = createEvent()
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target,
})
//@ts-expect-error
const result1: typeof target = guard({
clock: trigger,
filter: allow,
})
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target: [target],
})
//@ts-expect-error
const result2: [typeof target] = guard({
clock: trigger,
filter: allow,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<string>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<unknown>' is not assignable to type 'Event<string>'.
Types of property 'watch' are incompatible.
Type '(watcher: (payload: unknown) => any) => Subscription' is not assignable to type '(watcher: (payload: string) => any) => Subscription'.
Types of parameters 'watcher' and 'watcher' are incompatible.
Types of parameters 'payload' and 'payload' are incompatible.
Type 'unknown' is not assignable to type 'string'.
No overload matches this call.
The last overload gave the following error.
Type 'Event<string>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<unknown>' is not assignable to type '[Event<string>]'.
"
`)
})
test('unknown type in target (should pass)', () => {
const trigger: Event<string> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<unknown> = createEvent()
guard({
clock: trigger,
filter: allow,
target,
})
guard({
clock: trigger,
filter: allow,
target: [target],
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('optional props (should fail)', () => {
const trigger: Event<{a: 1; b?: 2}> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<{a: 1; b: 2}> = createEvent()
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target,
})
//@ts-expect-error
const result1: typeof target = guard({
clock: trigger,
filter: allow,
})
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target: [target],
})
//@ts-expect-error
const result2: [typeof target] = guard({
clock: trigger,
filter: allow,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ a: 1; b: 2; }>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<{ a: 1; b?: 2 | undefined; }>' is not assignable to type 'Event<{ a: 1; b: 2; }>'.
Types of property 'watch' are incompatible.
Type '(watcher: (payload: { a: 1; b?: 2 | undefined; }) => any) => Subscription' is not assignable to type '(watcher: (payload: { a: 1; b: 2; }) => any) => Subscription'.
Types of parameters 'watcher' and 'watcher' are incompatible.
Types of parameters 'payload' and 'payload' are incompatible.
Type '{ a: 1; b?: 2 | undefined; }' is not assignable to type '{ a: 1; b: 2; }'.
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ a: 1; b: 2; }>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<{ a: 1; b?: 2 | undefined; }>' is not assignable to type '[Event<{ a: 1; b: 2; }>]'.
"
`)
})
test('wide object (should pass)', () => {
const trigger: Event<{a: 1; b: 2}> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<{a: 1}> = createEvent()
guard({
clock: trigger,
filter: allow,
target,
})
guard({
clock: trigger,
filter: allow,
target: [target],
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('narrow object (should fail)', () => {
const trigger: Event<{a: 1; b: 2}> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<{a: 1; b: 2; c: 3}> = createEvent()
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target,
})
//@ts-expect-error
const result1: typeof target = guard({
clock: trigger,
filter: allow,
})
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target: [target],
})
//@ts-expect-error
const result2: [typeof target] = guard({
clock: trigger,
filter: allow,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ a: 1; b: 2; c: 3; }>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<{ a: 1; b: 2; }>' is not assignable to type 'Event<{ a: 1; b: 2; c: 3; }>'.
Types of property 'watch' are incompatible.
Type '(watcher: (payload: { a: 1; b: 2; }) => any) => Subscription' is not assignable to type '(watcher: (payload: { a: 1; b: 2; c: 3; }) => any) => Subscription'.
Types of parameters 'watcher' and 'watcher' are incompatible.
Types of parameters 'payload' and 'payload' are incompatible.
Type '{ a: 1; b: 2; }' is not assignable to type '{ a: 1; b: 2; c: 3; }'.
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ a: 1; b: 2; c: 3; }>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<{ a: 1; b: 2; }>' is not assignable to type '[Event<{ a: 1; b: 2; c: 3; }>]'.
"
`)
})
test('narrow object combined (should fail)', () => {
const foo = createStore('not enough')
const target = createEvent<{foo: string; bar: string}>()
guard({
source: {foo},
filter: () => true,
//@ts-expect-error
target,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<{ foo: string; bar: string; }>' is not assignable to type '\\"incompatible unit in target\\"'.
"
`)
})
test('wide tuple (should pass)', () => {
const trigger: Event<[1, 2, 3]> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<[1, 2]> = createEvent()
guard({
source: trigger,
filter: allow,
target,
})
guard({
source: trigger,
filter: allow,
target: [target],
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
})
test('narrow tuple (should fail)', () => {
const trigger: Event<[1, 2]> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<[1, 2, 3]> = createEvent()
guard({
source: trigger,
filter: allow,
//@ts-expect-error
target,
})
guard({
source: trigger,
filter: allow,
//@ts-expect-error
target: [target],
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<[1, 2, 3]>' is not assignable to type '\\"incompatible unit in target\\"'.
No overload matches this call.
The last overload gave the following error.
Type 'Event<[1, 2, 3]>' is not assignable to type '\\"incompatible unit in target\\"'.
"
`)
})
test('wide union in array (should fail)', () => {
const trigger: Event<Array<number | string | boolean>> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<Array<number | string>> = createEvent()
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target,
})
//@ts-expect-error
const result1: typeof target = guard({
clock: trigger,
filter: allow,
})
guard({
clock: trigger,
filter: allow,
//@ts-expect-error
target: [target],
})
//@ts-expect-error
const result2: [typeof target] = guard({
clock: trigger,
filter: allow,
})
expect(typecheck).toMatchInlineSnapshot(`
"
No overload matches this call.
The last overload gave the following error.
Type 'Event<(string | number)[]>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<(string | number | boolean)[]>' is not assignable to type 'Event<(string | number)[]>'.
Types of property 'watch' are incompatible.
Type '(watcher: (payload: (string | number | boolean)[]) => any) => Subscription' is not assignable to type '(watcher: (payload: (string | number)[]) => any) => Subscription'.
Types of parameters 'watcher' and 'watcher' are incompatible.
Types of parameters 'payload' and 'payload' are incompatible.
Type '(string | number | boolean)[]' is not assignable to type '(string | number)[]'.
No overload matches this call.
The last overload gave the following error.
Type 'Event<(string | number)[]>' is not assignable to type '\\"incompatible unit in target\\"'.
Type 'Event<(string | number | boolean)[]>' is not assignable to type '[Event<(string | number)[]>]'.
"
`)
})
test('narrow union in array (should pass)', () => {
const trigger: Event<Array<number | string>> = createEvent()
const allow = createStore<boolean>(true)
const target: Event<Array<number | string | boolean>> = createEvent()
guard({
clock: trigger,
filter: allow,
target,
})
guard({
clock: trigger,
filter: allow,
target: [target],
})
expect(typecheck).toMatchInlineSnapshot(`
"
no errors
"
`)
}) | the_stack |
import { Constants, Guild, Member, User, VoiceChannel, TextChannel, Message, Attachment, DiscordRESTError } from 'eris';
import { Inject, Service } from '@augu/lilith';
import { PunishmentType } from '../entities/PunishmentsEntity';
import { EmbedBuilder } from '../structures';
import type GuildEntity from '../entities/GuildEntity';
import type CaseEntity from '../entities/CaseEntity';
import TimeoutsManager from '../components/timeouts/Timeouts';
import Permissions from '../util/Permissions';
import { Logger } from 'tslog';
import Database from '../components/Database';
import Discord from '../components/Discord';
import ms = require('ms');
type MemberLike = Member | { id: string; guild: Guild };
export enum PunishmentEntryType {
WarningRemoved = 'Warning Removed',
WarningAdded = 'Warning Added',
VoiceUndeafen = 'Voice Undeafen',
VoiceUnmute = 'Voice Unmute',
VoiceMute = 'Voice Mute',
VoiceDeaf = 'Voice Deafen',
Unban = 'Unban',
Unmuted = 'Unmuted',
Muted = 'Muted',
Kicked = 'Kicked',
Banned = 'Banned',
}
interface ApplyPunishmentOptions {
attachments?: Attachment[];
moderator: User;
publish?: boolean;
reason?: string;
member: MemberLike;
soft?: boolean;
time?: number;
days?: number;
type: PunishmentType;
}
interface PublishModLogOptions {
warningsRemoved?: number | 'all';
warningsAdded?: number;
attachments?: string[];
moderator: User;
channel?: VoiceChannel;
reason?: string;
victim: User;
guild: Guild;
time?: number;
type: PunishmentEntryType;
}
interface ApplyGenericMuteOptions extends ApplyActionOptions {
moderator: User;
settings: GuildEntity;
}
interface ApplyActionOptions {
reason?: string;
member: Member;
guild: Guild;
time?: number;
self: Member;
}
interface ApplyGenericVoiceAction extends Exclude<ApplyActionOptions, 'guild' | 'time' | 'self'> {
statement: PublishModLogOptions;
moderator: User;
}
interface ApplyBanActionOptions extends ApplyActionOptions {
moderator: User;
soft: boolean;
days: number;
}
function stringifyDBType(type: PunishmentType): PunishmentEntryType | null {
switch (type) {
case PunishmentType.VoiceUndeafen:
return PunishmentEntryType.VoiceUndeafen;
case PunishmentType.VoiceUnmute:
return PunishmentEntryType.VoiceUnmute;
case PunishmentType.VoiceDeafen:
return PunishmentEntryType.VoiceDeaf;
case PunishmentType.VoiceMute:
return PunishmentEntryType.VoiceMute;
case PunishmentType.Unmute:
return PunishmentEntryType.Unmuted;
case PunishmentType.Unban:
return PunishmentEntryType.Unban;
case PunishmentType.Mute:
return PunishmentEntryType.Muted;
case PunishmentType.Kick:
return PunishmentEntryType.Kicked;
case PunishmentType.Ban:
return PunishmentEntryType.Banned;
default:
return null; // shouldn't come here but oh well
}
}
const emojis: { [P in PunishmentEntryType]: string } = {
[PunishmentEntryType.WarningRemoved]: ':pencil:',
[PunishmentEntryType.VoiceUndeafen]: ':speaking_head:',
[PunishmentEntryType.WarningAdded]: ':pencil:',
[PunishmentEntryType.VoiceUnmute]: ':loudspeaker:',
[PunishmentEntryType.VoiceMute]: ':mute:',
[PunishmentEntryType.VoiceDeaf]: ':mute:',
[PunishmentEntryType.Unmuted]: ':loudspeaker:',
[PunishmentEntryType.Kicked]: ':boot:',
[PunishmentEntryType.Banned]: ':hammer:',
[PunishmentEntryType.Unban]: ':bust_in_silhouette:',
[PunishmentEntryType.Muted]: ':mute:',
};
@Service({
priority: 1,
name: 'punishments',
})
export default class PunishmentService {
@Inject
private database!: Database;
@Inject
private discord!: Discord;
@Inject
private logger!: Logger;
private async resolveMember(member: MemberLike, rest: boolean = true) {
return member instanceof Member
? member
: member.guild.members.has(member.id)
? member.guild.members.get(member.id)!
: rest
? await this.discord.client
.getRESTGuildMember(member.guild.id, member.id)
.catch(() => new Member({ id: member.id }, member.guild, this.discord.client))
: new Member({ id: member.id }, member.guild, this.discord.client);
}
get timeouts(): TimeoutsManager {
return app.$ref(TimeoutsManager);
}
permissionsFor(type: PunishmentType) {
switch (type) {
case PunishmentType.Unmute:
case PunishmentType.Mute:
return Constants.Permissions.manageRoles;
case PunishmentType.VoiceUndeafen:
case PunishmentType.VoiceDeafen:
return Constants.Permissions.voiceDeafenMembers;
case PunishmentType.VoiceUnmute:
case PunishmentType.VoiceMute:
return Constants.Permissions.voiceMuteMembers;
case PunishmentType.Unban:
case PunishmentType.Ban:
return Constants.Permissions.banMembers;
case PunishmentType.Kick:
return Constants.Permissions.kickMembers;
default:
return 0n;
}
}
async createWarning(member: Member, reason?: string, amount?: number) {
const self = member.guild.members.get(this.discord.client.user.id)!;
const warnings = await this.database.warnings.getAll(member.guild.id, member.id);
const current = warnings.reduce((acc, curr) => acc + curr.amount, 0);
const count = amount !== undefined ? current + amount : current + 1;
if (count < 0) throw new RangeError('amount out of bounds');
const punishments = await this.database.punishments.getAll(member.guild.id);
const results = punishments.filter((x) => x.warnings === count);
await this.database.warnings.create({
guildID: member.guild.id,
reason,
amount: amount ?? 1,
userID: member.id,
});
// run the actual punishments
for (let i = 0; i < results.length; i++) {
const result = results[i];
await this.apply({
moderator: this.discord.client.users.get(this.discord.client.user.id)!,
publish: false,
member,
type: result.type,
});
}
const model = await this.database.cases.create({
attachments: [],
moderatorID: this.discord.client.user.id,
victimID: member.id,
guildID: member.guild.id,
reason,
soft: false,
type: PunishmentType.WarningAdded,
});
return results.length > 0
? Promise.resolve()
: this.publishToModLog(
{
warningsAdded: amount ?? 1,
moderator: self.user,
reason,
victim: member.user,
guild: member.guild,
type: PunishmentEntryType.WarningAdded,
},
model
);
}
async removeWarning(member: Member, reason?: string, amount?: number | 'all') {
const self = member.guild.members.get(this.discord.client.user.id)!;
const warnings = await this.database.warnings.getAll(member.guild.id, member.id);
if (warnings.length === 0) throw new SyntaxError("user doesn't have any punishments to be removed");
const count = warnings.reduce((acc, curr) => acc + curr.amount, 0);
if (amount === 'all') {
await this.database.warnings.clean(member.guild.id, member.id);
const model = await this.database.cases.create({
attachments: [],
moderatorID: this.discord.client.user.id,
victimID: member.id,
guildID: member.guild.id,
reason,
type: PunishmentType.WarningRemoved,
});
return this.publishToModLog(
{
warningsRemoved: 'all',
moderator: self.user,
victim: member.user,
reason,
guild: member.guild,
type: PunishmentEntryType.WarningRemoved,
},
model
);
} else {
const model = await this.database.cases.create({
attachments: [],
moderatorID: this.discord.client.user.id,
victimID: member.id,
guildID: member.guild.id,
reason,
type: PunishmentType.WarningRemoved,
});
await this.database.warnings.create({
guildID: member.guild.id,
userID: member.user.id,
amount: -1,
reason,
});
return this.publishToModLog(
{
warningsRemoved: count,
moderator: self.user,
victim: member.user,
reason,
guild: member.guild,
type: PunishmentEntryType.WarningRemoved,
},
model
);
}
}
async apply({ attachments, moderator, publish, reason, member, soft, type, days, time }: ApplyPunishmentOptions) {
this.logger.info(
`Told to apply punishment ${type} on member ${member.id}${reason ? `, with reason: ${reason}` : ''}${
publish ? ', publishing to modlog!' : ''
}`
);
const settings = await this.database.guilds.get(member.guild.id);
const self = member.guild.members.get(this.discord.client.user.id)!;
if (
(member instanceof Member && !Permissions.isMemberAbove(self, member)) ||
(BigInt(self.permissions.allow) & this.permissionsFor(type)) === 0n
)
return;
let user!: Member;
if (type === PunishmentType.Unban || (type === PunishmentType.Ban && member.guild.members.has(member.id))) {
user = await this.resolveMember(member, false);
} else {
user = await this.resolveMember(member, true);
}
const modlogStatement: PublishModLogOptions = {
attachments: attachments?.map((s) => s.url) ?? [],
moderator,
reason,
victim: user.user,
guild: member.guild,
type: stringifyDBType(type)!,
time,
};
switch (type) {
case PunishmentType.Ban:
await this.applyBan({
moderator,
member: user,
reason,
guild: member.guild,
self,
days: days ?? 7,
soft: soft === true,
time,
});
break;
case PunishmentType.Kick:
await user.kick(reason ? encodeURIComponent(reason) : 'No reason was specified.');
break;
case PunishmentType.Mute:
await this.applyMute({
moderator,
settings,
member: user,
reason,
guild: member.guild,
self,
time,
});
break;
case PunishmentType.Unban:
await member.guild.unbanMember(member.id, reason ? encodeURIComponent(reason) : 'No reason was specified.');
break;
case PunishmentType.Unmute:
await this.applyUnmute({
moderator,
settings,
member: user,
reason,
guild: member.guild,
self,
time,
});
break;
case PunishmentType.VoiceMute:
await this.applyVoiceMute({
moderator,
statement: modlogStatement,
member: user,
reason,
guild: member.guild,
self,
time,
});
break;
case PunishmentType.VoiceDeafen:
await this.applyVoiceDeafen({
moderator,
statement: modlogStatement,
member: user,
reason,
guild: member.guild,
self,
time,
});
break;
case PunishmentType.VoiceUnmute:
await this.applyVoiceUnmute({
moderator,
statement: modlogStatement,
member: user,
reason,
guild: member.guild,
self,
});
break;
case PunishmentType.VoiceUndeafen:
await this.applyVoiceUndeafen({
moderator,
statement: modlogStatement,
member: user,
reason,
guild: member.guild,
self,
});
break;
}
const model = await this.database.cases.create({
attachments: attachments?.slice(0, 5).map((v) => v.url) ?? [],
moderatorID: moderator.id,
victimID: member.id,
guildID: member.guild.id,
reason,
soft: soft === true,
time,
type,
});
if (publish) {
await this.publishToModLog(modlogStatement, model);
}
}
private async applyBan({ moderator, reason, member, guild, days, soft, time }: ApplyBanActionOptions) {
await guild.banMember(member.id, days, reason);
if (soft) await guild.unbanMember(member.id, reason);
if (!soft && time !== undefined && time > 0) {
if (this.timeouts.state !== 'connected')
this.logger.warn('Timeouts service is not connected! Will relay once done...');
await this.timeouts.apply({
moderator: moderator.id,
victim: member.id,
guild: guild.id,
type: PunishmentType.Unban,
time,
});
}
}
private async applyUnmute({ settings, reason, member, guild }: ApplyGenericMuteOptions) {
const role = guild.roles.get(settings.mutedRoleID!)!;
if (member.roles.includes(role.id))
await member.removeRole(role.id, reason ? encodeURIComponent(reason) : 'No reason was specified.');
}
private async applyMute({ moderator, settings, reason, member, guild, time }: ApplyGenericMuteOptions) {
const roleID = await this.getOrCreateMutedRole(guild, settings);
if (reason) reason = encodeURIComponent(reason);
if (!member.roles.includes(roleID)) {
await member.addRole(roleID, reason ?? 'No reason was specified.');
}
if (time !== undefined && time > 0) {
if (this.timeouts.state !== 'connected')
this.logger.warn('Timeouts service is not connected! Will relay once done...');
await this.timeouts.apply({
moderator: moderator.id,
victim: member.id,
guild: guild.id,
type: PunishmentType.Unmute,
time,
});
}
}
private async applyVoiceMute({ moderator, reason, member, guild, statement, time }: ApplyGenericVoiceAction) {
if (reason) reason = encodeURIComponent(reason);
if (member.voiceState.channelID !== null && !member.voiceState.mute)
await member.edit({ mute: true }, reason ?? 'No reason was specified.');
statement.channel = (await this.discord.client.getRESTChannel(member.voiceState.channelID!)) as VoiceChannel;
if (time !== undefined && time > 0) {
if (this.timeouts.state !== 'connected')
this.logger.warn('Timeouts service is not connected! Will relay once done...');
await this.timeouts.apply({
moderator: moderator.id,
victim: member.id,
guild: guild.id,
type: PunishmentType.VoiceUnmute,
time,
});
}
}
private async applyVoiceDeafen({ moderator, reason, member, guild, statement, time }: ApplyGenericVoiceAction) {
if (reason) reason = encodeURIComponent(reason);
if (member.voiceState.channelID !== null && !member.voiceState.deaf)
await member.edit({ deaf: true }, reason ?? 'No reason was specified.');
statement.channel = (await this.discord.client.getRESTChannel(member.voiceState.channelID!)) as VoiceChannel;
if (time !== undefined && time > 0) {
if (this.timeouts.state !== 'connected')
this.logger.warn('Timeouts service is not connected! Will relay once done...');
await this.timeouts.apply({
moderator: moderator.id,
victim: member.id,
guild: guild.id,
type: PunishmentType.VoiceUndeafen,
time,
});
}
}
private async applyVoiceUnmute({ reason, member, statement }: ApplyGenericVoiceAction) {
if (reason) reason = encodeURIComponent(reason);
if (member.voiceState !== undefined && member.voiceState.mute)
await member.edit({ mute: false }, reason ?? 'No reason was specified.');
statement.channel = (await this.discord.client.getRESTChannel(member.voiceState.channelID!)) as VoiceChannel;
}
private async applyVoiceUndeafen({ reason, member, statement }: ApplyGenericVoiceAction) {
if (reason) reason = encodeURIComponent(reason);
if (member.voiceState !== undefined && member.voiceState.deaf)
await member.edit({ deaf: false }, reason ?? 'No reason was specified.');
statement.channel = (await this.discord.client.getRESTChannel(member.voiceState.channelID!)) as VoiceChannel;
}
private async publishToModLog(
{
warningsRemoved,
warningsAdded,
moderator,
attachments,
channel,
reason,
victim,
guild,
time,
type,
}: PublishModLogOptions,
caseModel: CaseEntity
) {
const settings = await this.database.guilds.get(guild.id);
if (!settings.modlogChannelID) return;
const modlog = guild.channels.get(settings.modlogChannelID) as TextChannel;
if (!modlog) return;
if (
!modlog.permissionsOf(this.discord.client.user.id).has('sendMessages') ||
!modlog.permissionsOf(this.discord.client.user.id).has('embedLinks')
)
return;
const embed = this.getModLogEmbed(caseModel.index, {
attachments,
warningsRemoved,
warningsAdded,
moderator,
channel,
reason,
victim,
guild,
time,
type: stringifyDBType(caseModel.type)!,
}).build();
const content = `**[** ${emojis[type] ?? ':question:'} **~** Case #**${caseModel.index}** (${type}) ]`;
const message = await modlog.createMessage({
embed,
content,
});
await this.database.cases.update(guild.id, caseModel.index, {
messageID: message.id,
});
}
async editModLog(model: CaseEntity, message: Message) {
const warningRemovedField = message.embeds[0].fields?.find((field) => field.name.includes('Warnings Removed'));
const warningsAddField = message.embeds[0].fields?.find((field) => field.name.includes('Warnings Added'));
const obj: Record<string, any> = {};
if (warningsAddField !== undefined) obj.warningsAdded = Number(warningsAddField.value);
if (warningRemovedField !== undefined)
obj.warningsRemoved = warningRemovedField.value === 'All' ? 'All' : Number(warningRemovedField.value);
return message.edit({
content: `**[** ${emojis[stringifyDBType(model.type)!] ?? ':question:'} ~ Case #**${model.index}** (${
stringifyDBType(model.type) ?? '... unknown ...'
}) **]**`,
embed: this.getModLogEmbed(model.index, {
moderator: this.discord.client.users.get(model.moderatorID)!,
victim: this.discord.client.users.get(model.victimID)!,
reason: model.reason,
guild: this.discord.client.guilds.get(model.guildID)!,
time: model.time !== undefined ? Number(model.time) : undefined,
type: stringifyDBType(model.type)!,
...obj,
}).build(),
});
}
private async getOrCreateMutedRole(guild: Guild, settings: GuildEntity) {
let muteRole = settings.mutedRoleID;
if (muteRole) return muteRole;
let role = guild.roles.find((x) => x.name.toLowerCase() === 'muted');
if (!role) {
role = await guild.createRole(
{
mentionable: false,
permissions: 0,
hoist: false,
name: 'Muted',
},
`[${this.discord.client.user.username}#${this.discord.client.user.discriminator}] Created "Muted" role`
);
muteRole = role.id;
const topRole = Permissions.getTopRole(guild.members.get(this.discord.client.user.id)!);
if (topRole !== undefined) {
await role.editPosition(topRole.position - 1);
for (const channel of guild.channels.values()) {
const permissions = channel.permissionsOf(this.discord.client.user.id);
if (permissions.has('manageChannels'))
await channel.editPermission(
/* overwriteID */ role.id,
/* allowed */ 0,
/* denied */ Constants.Permissions.sendMessages,
/* type */ 0,
/* reason */ `[${this.discord.client.user.username}#${this.discord.client.user.discriminator}] Overrided permissions for new Muted role`
);
}
}
}
await this.database.guilds.update(guild.id, { mutedRoleID: role.id });
return role.id;
}
getModLogEmbed(
caseID: number,
{ warningsRemoved, warningsAdded, attachments, moderator, channel, reason, victim, time }: PublishModLogOptions
) {
const embed = new EmbedBuilder()
.setColor(0xdaa2c6)
.setAuthor(
`${victim.username}#${victim.discriminator} (${victim.id})`,
undefined,
victim.dynamicAvatarURL('png', 1024)
)
.addField('• Moderator', `${moderator.username}#${moderator.discriminator} (${moderator.id})`, true);
const _reason =
reason !== undefined
? Array.isArray(reason)
? reason.join(' ')
: reason
: `
• No reason was provided. Use \`reason ${caseID} <reason>\` to update it!
`;
const _attachments = attachments?.map((url, index) => `• [**\`Attachment #${index}\`**](${url})`).join('\n') ?? '';
embed.setDescription([_reason, _attachments]);
if (warningsRemoved !== undefined)
embed.addField('• Warnings Removed', warningsRemoved === 'all' ? 'All' : warningsRemoved.toString(), true);
if (warningsAdded !== undefined) embed.addField('• Warnings Added', warningsAdded.toString(), true);
if (channel !== undefined) embed.addField('• Voice Channel', `${channel.name} (${channel.id})`, true);
if (time !== undefined || time !== null) {
try {
embed.addField('• Time', ms(time!, { long: true }), true);
} catch {
// ignore since fuck you
}
}
return embed;
}
} | the_stack |
export type Bounds = readonly [number, number];
export type BiIndex = readonly [number, number];
type CostFn<T, U> = (o?: T, m?: U) => number;
/**
* An alignment between two related sequences.
*
* Consider this alignment between two strings:
*
* .. code-block:: text
*
* |it's| |aligned!|
* | \ \ |
* |it is| |aligned|
*
* An alignment stores all the indices that are known to correspond between the original and modified sequences. For
* the above example, it would be
*
* .. code-block:: ts
*
* let a = new Alignment([
* [0, 0],
* [4, 5],
* [5, 6],
* [13, 13],
* ]);
*
* Alignments can be used to answer questions like, "what's the smallest range of the original sequence that is
* guaranteed to contain this part of the modified sequence?" For example, the range `(0, 5)` ("it is") is known to
* match the range `(0, 4)` ("it's") of the original sequence.
*
* .. code-block:: ts
*
* console.log(a.original_bounds(0, 5));
* // [0, 4]
*
* Results may be imprecise if the alignment is too course to match the exact inputs:
*
* .. code-block:: ts
*
* console.log(a.original_bounds(0, 2));
* // [0, 4]
*
* A more granular alignment like this:
*
* .. code-block:: text
*
* |i|t|'s| |a|l|i|g|n|e|d|!|
* | | | \ \ \ \ \ \ \ \ \ /
* |i|t| is| |a|l|i|g|n|e|d|
*
* .. code-block:: ts
*
* a = new Alignment([
* [0, 0], [1, 1], [2, 2], [4, 5], [5, 6], [6, 7], [7, 8],
* [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 13],
* ]);
*
* Can be more precise:
*
* .. code-block:: ts
*
* console.log(a.original_bounds(0, 2));
* // [0, 2]
*/
export default class Alignment {
/** The pairs of aligned indices in this alignment. */
readonly values: readonly BiIndex[];
/** The number of entries in this alignment. */
readonly length: number;
/**
* Create a new Alignment.
*
* @param values
* The pairs of indices to align. Each element should be a pair destructurable as `[x, y]`, where `x` is
* the original sequence position and `y` is the modified sequence position.
*/
constructor(values: Iterable<BiIndex>) {
const copy: BiIndex[] = [];
for (const [o, m] of values) {
if (copy.length > 0) {
const [oPrev, mPrev] = copy[copy.length - 1];
if (o < oPrev) {
throw new Error("Original sequence position moved backwards")
} else if (m < mPrev) {
throw new Error("Modified sequence position moved backwards")
} else if (o === oPrev && m === mPrev) {
continue;
}
}
copy.push(Object.freeze([o, m] as BiIndex));
}
if (copy.length === 0) {
throw new Error("No sequence positions to align");
}
this.values = Object.freeze(copy);
this.length = copy.length;
Object.freeze(this);
}
/**
* Create an identity alignment of the given size, which maps all intervals to themselves.
*
* @param size
* The size of the sequences to align.
* @returns
* The identity alignment for the bounds [0, `size`].
*/
static identity(size: number): Alignment;
/**
* Create an identity alignment between the given bounds.
*
* @param start
* The first index to align.
* @param end
* The last index to align.
* @returns
* The identity alignment for the bounds [`start`, `end`].
*/
static identity(start: number, end: number): Alignment;
/**
* Create an identity alignment with the given bounds.
*
* @param bounds
* The bounds of the alignment (e.g. ``[1, 5]``).
* @returns
* The identity alignment for the given bounds.
*/
static identity(bounds: Bounds): Alignment;
static identity(start: number | Bounds, end?: number): Alignment {
if (typeof(start) !== "number") {
end = start[1];
start = start[0];
}
if (end === undefined) {
end = start;
start = 0;
}
const values: BiIndex[] = [];
for (let i = start; i <= end; ++i) {
values.push([i, i]);
}
return new Alignment(values);
}
/**
* Infer the alignment between two sequences with the lowest edit distance.
*
* Warning: this operation has time complexity ``O(N*M)``, where `N` and `M` are the lengths of the original and
* modified sequences, and so should only be used for relatively short sequences.
*
* @param original
* The original sequence.
* @param modified
* The modified sequence.
* @param costFn
* A function returning the cost of performing an edit. `costFn(a, b)` returns the cost of replacing `a`
* with `b`. `costFn(a, undefined)` returns the cost of deleting `a`, and `costFn(undefined, b)` returns
* the cost of inserting `b`. By default, all operations have cost 1 except replacing identical elements,
* which has cost 0.
* @returns
* The inferred alignment.
*/
static infer<T, U>(original: Iterable<T>, modified: Iterable<U>, costFn?: CostFn<T, U>): Alignment {
if (costFn === undefined) {
costFn = (o, m) => Number(o !== m);
}
let oArray = original instanceof Array ? original : Array.from(original);
let mArray = modified instanceof Array ? modified : Array.from(modified);
if (oArray.length < mArray.length) {
let result = this._inferRecursive(mArray, oArray, (m, o) => costFn!(o, m));
return new Alignment(result).inverse();
} else {
let result = this._inferRecursive(oArray, mArray, costFn);
return new Alignment(result);
}
}
/**
* Hirschberg's algorithm for computing optimal alignments in linear space.
*
* https://en.wikipedia.org/wiki/Hirschberg's_algorithm
*/
private static _inferRecursive<T, U>(original: T[], modified: U[], costFn: CostFn<T, U>): BiIndex[] {
if (original.length <= 1 || modified.length <= 1) {
return this._inferMatrix(original, modified, costFn);
}
const oMid = original.length >> 1;
const oLeft = original.slice(0, oMid);
const oRight = original.slice(oMid);
const lCosts = this._inferCosts(oLeft, modified, costFn);
const oRightRev = oRight.slice();
oRightRev.reverse();
const modifiedRev = modified.slice();
modifiedRev.reverse();
const rCosts = this._inferCosts(oRightRev, modifiedRev, costFn);
rCosts.reverse();
let mMid = -1, best = Infinity;
for (let i = 0; i < lCosts.length; ++i) {
const score = lCosts[i] + rCosts[i];
if (score < best) {
mMid = i;
best = score;
}
}
const mLeft = modified.slice(0, mMid);
const mRight = modified.slice(mMid);
const left = this._inferRecursive(oLeft, mLeft, costFn);
const right = this._inferRecursive(oRight, mRight, costFn);
for (const [o, m] of right) {
left.push([o + oMid, m + mMid]);
}
return left;
}
/**
* The Needleman–Wunsch or Wagner–Fischer algorithm. Here we use it in a way that only computes the final row of
* costs, without finding the alignment itself. Hirschberg's algorithm uses it as a subroutine to find the optimal
* alignment in less than O(N*M) space.
*
* https://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm
* https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm
*/
private static _inferCosts<T, U>(original: T[], modified: U[], costFn: CostFn<T, U>): number[] {
let row = [0];
for (let i = 0; i < modified.length; ++i) {
const cost = row[i] + costFn(undefined, modified[i]);
row.push(cost);
}
let prev = Array(row.length);
prev.fill(0);
for (const o of original) {
[prev, row] = [row, prev];
row[0] = prev[0] + costFn(o, undefined);
for (let i = 0; i < modified.length; ++i) {
const m = modified[i];
const subCost = prev[i] + costFn(o, m);
const delCost = prev[i + 1] + costFn(o, undefined);
const insCost = row[i] + costFn(undefined, m);
row[i + 1] = Math.min(subCost, delCost, insCost);
}
}
return row;
}
/**
* The Needleman–Wunsch or Wagner–Fischer algorithm, using the entire matrix to compute the optimal alignment.
*/
private static _inferMatrix<T, U>(original: T[], modified: U[], costFn: CostFn<T, U>): BiIndex[] {
const row = [{cost: 0, i: -1, j: -1}];
for (let j = 0; j < modified.length; ++j) {
const m = modified[j];
row.push({cost: row[j].cost + costFn(undefined, m), i: 0, j: j});
}
const matrix = [row];
for (let i = 0; i < original.length; ++i) {
const o = original[i];
const prev = matrix[i];
const row = [{cost: prev[0].cost + costFn(o, undefined), i: i, j: 0}];
for (let j = 0; j < modified.length; ++j) {
const m = modified[j];
let cost = prev[j].cost + costFn(o, m);
let x = i, y = j;
const delCost = prev[j + 1].cost + costFn(o, undefined);
if (delCost < cost) {
cost = delCost;
x = i;
y = j + 1;
}
const insCost = row[j].cost + costFn(undefined, m);
if (insCost < cost) {
cost = insCost;
x = i + 1;
y = j;
}
row.push({cost: cost, i: x, j: y});
}
matrix.push(row);
}
const result: BiIndex[] = [];
let i = matrix.length - 1;
let j = matrix[i].length - 1;
while (i >= 0) {
result.push([i, j]);
({i, j} = matrix[i][j]);
}
result.reverse();
return result;
}
/**
* Extract a slice of this alignment.
*
* @param start
* The position to start from.
* @param end
* The position to end at.
* @returns
* The requested slice as a new `Alignment`.
*/
slice(start?: number, end?: number): Alignment {
return new Alignment(this.values.slice(start, end));
}
/**
* Binary search for computing corresponding bounds.
*
* @param which
* Which side of the sequence to search (0 for original, 1 for modified).
* @param start
* The start of the span to map.
* @param end
* The end of the span to map.
* @returns
* The indices in `this.values` that contain the given range.
*/
private _search(which: number, start: number, end: number): Bounds {
let first = 0, limit = this.length;
while (first < limit) {
const mid = first + ((limit - first) >> 2);
if (this.values[mid][which] <= start) {
first = mid + 1;
} else {
limit = mid;
}
}
if (first === 0) {
throw new RangeError("Start index too small");
}
--first;
let last = first;
limit = this.length;
while (last < limit) {
const mid = last + ((limit - last) >> 2);
if (this.values[mid][which] < end) {
last = mid + 1;
} else {
limit = mid;
}
}
if (last === this.length) {
throw new RangeError("End index too large");
}
return [first, last];
}
/**
* Shared implementation of `originalBounds()` and `modifiedBounds()`.
*
* @param which
* Which side of the sequence to search (0 for original, 1 for modified).
* @param start
* The start of the span to map.
* @param end
* The end of the span to map.
* @returns
* The corresponding span in the other sequence (`1 - which`).
*/
private _bounds(which: number, start?: number | Bounds, end?: number): Bounds {
if (start === undefined) {
return [
this.values[0][1 - which],
this.values[this.length - 1][1 - which],
];
} else if (typeof(start) !== "number") {
end = start[1];
start = start[0];
}
if (end === undefined) {
end = this.values[this.length - 1][which];
}
const [first, last] = this._search(which, start, end);
return [this.values[first][1 - which], this.values[last][1 - which]];
}
/**
* @returns
* The bounds of the original sequence.
*/
originalBounds(): Bounds;
/**
* Maps a subrange of the modified sequence to the original sequence.
*
* @param start
* The start of the span in the modified sequence.
* @param end
* The end of the span in the modified sequence.
* @returns
* The bounds of the corresponding span in the original sequence.
*/
originalBounds(start: number, end: number): Bounds;
/**
* Maps a subrange of the modified sequence to the original sequence.
*
* @param bounds
* The bounds of the span in the modified sequence.
* @returns
* The bounds of the corresponding span in the original sequence.
*/
originalBounds(bounds: Bounds): Bounds;
originalBounds(start?: number | Bounds, end?: number): Bounds {
return this._bounds(1, start, end);
}
/**
* @returns
* The bounds of the modified sequence.
*/
modifiedBounds(): Bounds;
/**
* Maps a subrange of the original sequence to the modified sequence.
*
* @param start
* The start of the span in the original sequence.
* @param end
* The end of the span in the original sequence.
* @returns
* The bounds of the corresponding span in the modified sequence.
*/
modifiedBounds(start: number, end: number): Bounds;
/**
* Maps a subrange of the original sequence to the modified sequence.
*
* @param bounds
* The bounds of the span in the original sequence.
* @returns
* The bounds of the corresponding span in the modified sequence.
*/
modifiedBounds(bounds: Bounds): Bounds;
modifiedBounds(start?: number | Bounds, end?: number): Bounds {
return this._bounds(0, start, end);
}
/**
* Shared implementation of `sliceByOriginal()` and `sliceByModified()`.
*
* @param which
* Which side of the sequence to slice by (0 for original, 1 for modified).
* @param start
* The start of the span to map.
* @param end
* The end of the span to map.
* @returns
* The requested slice of this alignment.
*/
private _sliceBy(which: number, start: number | Bounds, end?: number): Alignment {
if (typeof(start) !== "number") {
end = start[1];
start = start[0];
}
if (end === undefined) {
end = this.values[this.length - 1][which];
}
const [first, last] = this._search(which, start, end);
const values = this.values.slice(first, last + 1);
for (const i in values) {
const v = values[i].slice() as [number, number];
v[which] = Math.max(start, Math.min(v[which], end));
values[i] = v;
}
return new Alignment(values);
}
/**
* Slice this alignment by a span of the original sequence.
*
* @param start
* The start of the span in the original sequence.
* @param end
* The end of the span in the original sequence.
* @returns
* The requested slice of this alignment.
*/
sliceByOriginal(start: number, end: number): Alignment;
/**
* Slice this alignment by a span of the original sequence.
*
* @param bounds
* The bounds of the span in the original sequence.
* @returns
* The requested slice of this alignment.
*/
sliceByOriginal(bounds: Bounds): Alignment;
sliceByOriginal(start: number | Bounds, end?: number): Alignment {
return this._sliceBy(0, start, end);
}
/**
* Slice this alignment by a span of the modified sequence.
*
* @param start
* The start of the span in the modified sequence.
* @param end
* The end of the span in the modified sequence.
* @returns
* The requested slice of this alignment.
*/
sliceByModified(start: number, end: number): Alignment;
/**
* Slice this alignment by a span of the modified sequence.
*
* @param bounds
* The bounds of the span in the modified sequence.
* @returns
* The requested slice of this alignment.
*/
sliceByModified(bounds: Bounds): Alignment;
sliceByModified(start: number | Bounds, end?: number): Alignment {
return this._sliceBy(1, start, end);
}
/**
* Shift this alignment.
*
* @param deltaO
* The distance to shift the original sequence.
* @param deltaM
* The distance to shift the modified sequence.
* @returns
* An alignment with all the positions shifted by the given amounts.
*/
shift(deltaO: number, deltaM: number): Alignment {
const shifted: BiIndex[] = this.values.map(([o, m]) => [o + deltaO, m + deltaM]);
return new Alignment(shifted);
}
/**
* Concatenate this alignment together with one or more others.
*/
concat(...others: Alignment[]): Alignment {
const values = this.values.slice();
for (const other of others) {
values.push(...other.values);
}
return new Alignment(values);
}
/**
* @returns
* An alignment equivalent to applying `this` first, then `other`.
*/
compose(other: Alignment): Alignment {
const [mf, ml] = this.modifiedBounds();
const [of, ol] = other.originalBounds();
if (mf !== of || ml !== ol) {
throw new RangeError("Incompatible alignments");
}
const values: BiIndex[] = [];
let i = 0, iMax = this.length;
let j = 0, jMax = other.length;
while (i < iMax) {
while (this.values[i][1] > other.values[j][0]) {
++j;
}
while (this.values[i][1] < other.values[j][0] && this.values[i + 1][1] <= other.values[j][0]) {
++i;
}
values.push([this.values[i][0], other.values[j][1]]);
while (i + 1 < iMax && this.values[i][0] === this.values[i + 1][0]) {
++i;
}
let needsUpper = false;
while (j + 1 < jMax && this.values[i][1] >= other.values[j + 1][0]) {
needsUpper = true;
++j;
}
if (needsUpper) {
values.push([this.values[i][0], other.values[j][1]]);
}
++i;
}
return new Alignment(values);
}
/**
* @returns
* The inverse of this alignment, from the modified to the original sequence.
*/
inverse(): Alignment {
return new Alignment(this.values.map(([o, m]) => [m, o]));
}
/**
* @returns
* Whether this alignment is the same as `other`.
*/
equals(other: Alignment): boolean {
if (this.length != other.length) {
return false;
}
for (let i = 0; i < this.length; ++i) {
const [to, tm] = this.values[i];
const [oo, om] = other.values[i];
if (to != oo || tm != om) {
return false;
}
}
return true;
}
} | the_stack |
import BigNumber from 'bignumber.js';
import Web3 from 'web3';
import { TransactionConfig, TransactionReceipt } from 'web3-core';
import { AbiExamples } from '../../abi-examples';
import { ContractContext as TokenContractContext } from './generated-typings/token-contract';
import { ContractContext as UniswapExchangeContractContext } from './generated-typings/uniswap-exchange-contract';
import { ContractContext as UniswapFactoryContractContext } from './generated-typings/uniswap-factory-contract';
const mockEthereumAddress = '0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b';
const web3 = new Web3(
'https://mainnet.infura.io/v3/280bb5b627394709938a7cc0b71a4a58'
);
class UniswapStronglyTypedExample {
// 0.5%
private readonly SLIPPAGE = 0.05;
// trade lasts for 15 minutes before it expiries
private readonly TRADE_DEADLINE_SECONDS = 15 * 60;
private _factoryContract: UniswapFactoryContractContext = this.buildUniswapFactoryContract();
constructor() {}
/**
* Gets how much token they will get for their trade minus all fees
* @param ethAmount The eth amount
*/
public async getTokenTradeAmountEthToErc20(
ethAmount: BigNumber
): Promise<BigNumber> {
const exchangeContract = await this.getExchangeContractForToken(
AbiExamples.funContractAddress
);
const price = await exchangeContract.methods
.getEthToTokenInputPrice(web3.utils.toWei(ethAmount.toFixed(), 'ether'))
.call();
this.logUniswapOutput(`Got the eth to token input price - ${price}`);
// Uniswap class - Got the eth to token input price - 102465873454
const tokenAmount = new BigNumber(price).shiftedBy(
AbiExamples.funDecimalPlaces * -1
);
this.logUniswapOutput(`Got the fun token amount - ${tokenAmount}`);
// Uniswap class - Got the fun token amount - 1024.65873454
// add some slippage
const tokenAmountWithSlippage = tokenAmount.minus(
tokenAmount.times(this.SLIPPAGE).toFixed()
);
this.logUniswapOutput(
`Fun token amount with the slippage taken off - ${tokenAmountWithSlippage.toFixed()}`
);
// Uniswap class - Fun token amount with the slippage taken off - 973.425797813
return tokenAmountWithSlippage;
}
/**
* Get max amount of fun tokens you can buy
*/
public async maxAmountOfTokensToBuy() {
const exchangeAddress = await this.getExchangeAddress(
AbiExamples.funContractAddress
);
const tokenContract = this.getTokenContract(AbiExamples.funContractAddress);
const tokenReserveRaw = await tokenContract.methods
.balanceOf(exchangeAddress)
.call();
this.logUniswapOutput(
`Got the token reserve raw value - ${tokenReserveRaw}`
);
// Uniswap class - Got the token reserve raw value - 1868161858283796
const tokenReserve = new BigNumber(tokenReserveRaw).shiftedBy(
AbiExamples.funDecimalPlaces * -1
);
this.logUniswapOutput(
`Token reserve raw value formatted to fun decimal places - ${tokenReserve}`
);
// Uniswap class - Token reserve raw value formatted to fun decimal places - 18681618.58283796
return tokenReserve;
}
/**
* Make the trade encoding the data and sending the transaction
* @param ethAmount The eth amount
* @param minTokens The min tokens
*/
public async tradeWithBuildingTransactionConfig(
ethAmount: BigNumber,
minTokens: BigNumber
): Promise<string> {
const exchangeAddress = await this.getExchangeAddress(
AbiExamples.funContractAddress
);
const exchangeContract = this.getExchangeContractForTokenByExchangeAddress(
exchangeAddress
);
// you can build the data up like this if you want?
const data = exchangeContract.methods
.ethToTokenSwapInput(
web3.utils.toHex(minTokens as any),
this.generateTradeDeadlineUnixTime()
)
.encodeABI();
this.logUniswapOutput(`Encoded abi and generated data ${data}`);
// Uniswap class - Encoded abi and generated data 0xf39b5b9b0000000000000000000000000000000000000000000000000000000000000384000000000000000000000000000000000000000000000000000000005eac075c
// and build up a `TransactionConfig`
const transactionConfig: TransactionConfig = {
from: mockEthereumAddress,
to: exchangeAddress,
data,
value: web3.utils.toWei(ethAmount.toFixed(), 'ether'),
gas: web3.utils.numberToHex(21912),
};
this.logUniswapOutput(
`Transaction config built up ${JSON.stringify(transactionConfig)}`
);
// Uniswap class - Transaction config built up {"from":"0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b","to":"0x60a87cC7Fca7E53867facB79DA73181B1bB4238B","data":"0xf39b5b9b0000000000000000000000000000000000000000000000000000000000000384000000000000000000000000000000000000000000000000000000005eac075c","value":"10000000000000000"}
// obviously if your using a wallet provider do your standard
// web3.eth.sendTransaction :)
const signedTransaction = await web3.eth.accounts.signTransaction(
transactionConfig,
'0x0123456789012345678901234567890123456789012345678901234567890123'
);
// and send it through web3...
// not actually going to send here as we have no private keys
// but if you were using metamask or other wallet providers it would trigger a signer
// this is merely an example
const transactionReceipt = (await web3.eth.sendSignedTransaction(
signedTransaction.rawTransaction!
)) as TransactionReceipt;
this.logUniswapOutput(
`Transaction sent ${transactionReceipt.transactionHash}`
);
// Uniswap class - Transaction sent 0x972c2155137efecb126dc5f4f72fb451753eab8f5fce45aad73e00861ae27fe1
return transactionReceipt.transactionHash;
}
/**
* Make the trade using the promi events way
* @param ethAmount The eth amount
* @param minTokens The min tokens
*/
public async tradeWithPromiEvents(
ethAmount: BigNumber,
minTokens: BigNumber
): Promise<string> {
const exchangeAddress = await this.getExchangeAddress(
AbiExamples.funContractAddress
);
const exchangeContract = this.getExchangeContractForTokenByExchangeAddress(
exchangeAddress
);
// You can send straight away
// using the promi events to do this
// again all typings will show for you
const transactionHash: string = await new Promise((resolve, reject) => {
exchangeContract.methods
.ethToTokenSwapInput(
web3.utils.toHex(minTokens as any),
this.generateTradeDeadlineUnixTime()
)
.send({
from: mockEthereumAddress,
value: web3.utils.toWei(ethAmount.toFixed(), 'ether'),
})
.once('transactionHash', (hash) => {
console.log(`Transaction hash - ${hash}`);
// Uniswap class - Transaction hash 0xcd1067f21622fb55b609c1248011dcb6237dd6c3981a44792d38f016a102e7b1
resolve(hash);
})
.on('error', async (error) => {
reject(error);
})
.catch((error) => {
reject(error);
});
});
this.logUniswapOutput(`Transaction sent ${transactionHash}`);
// Uniswap class - Transaction sent 0xcd1067f21622fb55b609c1248011dcb6237dd6c3981a44792d38f016a102e7b1
return transactionHash;
}
/**
* Generates the trade dateline unix time
*/
private generateTradeDeadlineUnixTime(): string {
const timestamp =
((new Date().getTime() / 1e3) | 0) + this.TRADE_DEADLINE_SECONDS;
return timestamp.toString();
}
/**
* Get the exchange contract for the token
* @param erc20TokenContract The erc20 token contract
*/
private async getExchangeContractForToken(
erc20TokenContract: string
): Promise<UniswapExchangeContractContext> {
const exchangeAddress = await this.getExchangeAddress(erc20TokenContract);
return this.getExchangeContractForTokenByExchangeAddress(exchangeAddress);
}
/**
* Gets the exchange address for the erc20 token contract
* @param erc20TokenContract The erc20 token contract
*/
private async getExchangeAddress(
erc20TokenContract: string
): Promise<string> {
const exchangeAddress = await this._factoryContract.methods
.getExchange(erc20TokenContract)
.call();
this.logUniswapOutput(`Got the exchange address - ${exchangeAddress}`);
// Uniswap class - Got the exchange address - 0x60a87cC7Fca7E53867facB79DA73181B1bB4238B
return exchangeAddress;
}
/**
* Get the token contract for the erc20 token
* @param erc20TokenContract The erc20 token contract
*/
private getTokenContract(erc20TokenContract: string): TokenContractContext {
// Has to cast to unknown as we have made some typings changes to the
// contract interfaces which conflicts with `web3` typings.
// This all work great but the compiler gets confused.
// Casting to unknown first then the `TokenContractContext` solves this.
return (new web3.eth.Contract(
AbiExamples.tokenAbi,
erc20TokenContract
) as unknown) as TokenContractContext;
}
/**
* Get the exchange contract from the exchange address
* @param exchangeAddress The exchange address
*/
private getExchangeContractForTokenByExchangeAddress(
exchangeAddress: string
): UniswapExchangeContractContext {
// Has to cast to unknown as we have made some typings changes to the
// contract interfaces which conflicts with `web3` typings.
// This all work great but the compiler gets confused.
// Casting to unknown first then the `UniswapExchangeContractContext` solves this.
return (new web3.eth.Contract(
AbiExamples.uniswapExchangeAbi,
exchangeAddress
) as unknown) as UniswapExchangeContractContext;
}
/**
* Build the uniswap factory contract instance
*/
private buildUniswapFactoryContract(): UniswapFactoryContractContext {
// Has to cast to unknown as we have made some typings changes to the
// contract interfaces which conflicts with `web3` typings.
// This all work great but the compiler gets confused.
// Casting to unknown first then the `UniswapFactoryContractContext` solves this.
return (new web3.eth.Contract(
AbiExamples.uniswapFactoryAbi,
AbiExamples.uniswapFactoryAddress
) as unknown) as UniswapFactoryContractContext;
}
/**
* So you can tell what is the internal log or the example log when you run it
* @param message The message
*/
private logUniswapOutput(message: string): void {
console.log(`Uniswap class - ${message}`);
}
}
const example = async () => {
const ethAmount = new BigNumber('0.01'); // 0.01 eth;
const uniswap = new UniswapStronglyTypedExample();
// get the max tokens
const maxTokens = await uniswap.maxAmountOfTokensToBuy();
console.log(maxTokens.toFixed());
// 18681618.58283796
const getTokenTrade = await uniswap.getTokenTradeAmountEthToErc20(ethAmount);
console.log(getTokenTrade.toFixed());
// 973.425797813
/**
* PLEASE NOTE:
*
* The below code is an example in how you would sign the transaction with the typings.
* If you run this script just using `node ./dist/web3/uniswap-example/uniswap-contract-strongly-typed-example.js
* it will not work and throw errors in the trade calls as you don't have a wallet connected to it aka no private key :)
*
*/
const tradeWithBuildingTransactionConfig = await uniswap.tradeWithBuildingTransactionConfig(
ethAmount,
new BigNumber('900')
);
console.log(tradeWithBuildingTransactionConfig);
// 0x972c2155137efecb126dc5f4f72fb451753eab8f5fce45aad73e00861ae27fe1
const trade = await uniswap.tradeWithPromiEvents(
ethAmount,
new BigNumber('900')
);
console.log(trade);
// 0xcd1067f21622fb55b609c1248011dcb6237dd6c3981a44792d38f016a102e7b1
};
example(); | the_stack |
import {
focusFirstSiblingOf,
focusLastSiblingOf,
focusNextSiblingOf,
focusPreviousSiblingOf,
getClosestAccordion,
getSiblingButtons,
} from './focus';
describe('focus', () => {
function createTree(innerHTML: string): DocumentFragment {
const template = document.createElement('template');
// tslint:disable-next-line: no-inner-html
template.innerHTML = innerHTML.trim();
return template.content;
}
describe('getClosestAccordion', () => {
it('gets an ancestral accordion element', () => {
const tree = createTree(`
<div data-accordion-component="Accordion" id="parent">
<div id="child">Child</div>
</div>
`);
const child = tree.querySelector('#child');
const parent = tree.querySelector('#parent');
// Predicate
if (
!(child instanceof HTMLElement && parent instanceof HTMLElement)
) {
throw new Error('child or parent not found');
}
// Matter
expect(getClosestAccordion(child)).toEqual(parent);
});
it('only gets the nearest ancestral accordion element when there are more than one', () => {
const tree = createTree(`
<div data-accordion-component="Accordion">
<div data-accordion-component="Accordion" id="parent">
<div id="child">Child</div>
</div>
</div>
`);
const child = tree.querySelector('#child');
const parent = tree.querySelector('#parent');
// Predicate
if (
!(child instanceof HTMLElement && parent instanceof HTMLElement)
) {
throw new Error('child or parent not found');
}
// Matter
expect(getClosestAccordion(child)).toEqual(parent);
});
it('recurses through intermediary elements', () => {
const tree = createTree(`
<div data-accordion-component="Accordion" id="parent">
<div>
<div>
<div id="child">Child</div>
</div>
</div>
</div>
`);
const child = tree.querySelector('#child');
const parent = tree.querySelector('#parent');
// Predicate
if (
!(child instanceof HTMLElement && parent instanceof HTMLElement)
) {
throw new Error('child or parent not found');
}
expect(getClosestAccordion(child)).toEqual(parent);
});
});
describe('getSiblingButtons', () => {
it('returns adjacent siblings', () => {
const tree = createTree(`
<div data-accordion-component="Accordion" id="parent">
<div data-accordion-component="AccordionItemButton">Button</div>
<div data-accordion-component="AccordionItemButton">Button</div>
<div data-accordion-component="AccordionItemButton">Button</div>
</div>
`);
const button = tree.querySelector(
'[data-accordion-component="AccordionItemButton"]',
);
// Predicate
if (!(button instanceof HTMLElement)) {
throw new Error('button not found');
}
// Matter
expect(getSiblingButtons(button)).toHaveLength(3);
});
it('returns nested siblings', () => {
const tree = createTree(`
<div data-accordion-component="Accordion" id="parent">
<div>
<div data-accordion-component="AccordionItemButton">Button</div>
</div>
<div data-accordion-component="AccordionItemButton">Button</div>
<div data-accordion-component="AccordionItemButton">Button</div>
</div>
`);
const button = tree.querySelector(
'[data-accordion-component="AccordionItemButton"]',
);
// Predicate
if (!(button instanceof HTMLElement)) {
throw new Error('button not found');
}
// Matter
expect(getSiblingButtons(button)).toHaveLength(3);
});
it('doesn‘t return buttons "above" the accordion', () => {
const tree = createTree(`
<div data-accordion-component="AccordionItemButton">
<div data-accordion-component="Accordion" id="parent">
<div data-accordion-component="AccordionItemButton" id="first">Button</div>
<div data-accordion-component="AccordionItemButton">Button</div>
</div>
</div>
`);
const button = tree.querySelector('#first');
// Predicate
if (!(button instanceof HTMLElement)) {
throw new Error('button not found');
}
// Matter
expect(getSiblingButtons(button)).toHaveLength(2);
});
});
describe('focusFirstSiblingOf', () => {
it('focuses the first button in document flow', () => {
const tree = createTree(`
<div data-accordion-component="Accordion">
<div data-accordion-component="AccordionItemButton" tabindex="0" id="1"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="2"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="3"></div>
</div>
`);
const [firstButton, secondButton, thirdButton] = Array.from(
tree.querySelectorAll(
'[data-accordion-component="AccordionItemButton"]',
),
);
// Predicate
if (
!(
firstButton instanceof HTMLElement &&
secondButton instanceof HTMLElement &&
thirdButton instanceof HTMLElement
)
) {
throw new Error('buttons not found');
}
thirdButton.focus();
expect(document.activeElement).toBe(thirdButton);
// Matter
focusFirstSiblingOf(thirdButton);
expect(document.activeElement).toBe(firstButton);
});
});
describe('focusLastSiblingOf', () => {
it('focuses the last button in document flow', () => {
const tree = createTree(`
<div data-accordion-component="Accordion">
<div data-accordion-component="AccordionItemButton" tabindex="0" id="1"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="2"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="3"></div>
</div>
`);
const [
firstButton,
secondButton,
thirdButton,
]: HTMLElement[] = Array.from(
tree.querySelectorAll(
'[data-accordion-component="AccordionItemButton"]',
),
);
// Predicate
if (
!(
firstButton instanceof HTMLElement &&
secondButton instanceof HTMLElement &&
thirdButton instanceof HTMLElement
)
) {
throw new Error('buttons not found');
}
firstButton.focus();
expect(document.activeElement).toBe(firstButton);
// Matter
focusLastSiblingOf(firstButton);
expect(document.activeElement).toBe(thirdButton);
});
});
describe('focusNextSiblingOf', () => {
it('focuses the next button in document flow', () => {
const tree = createTree(`
<div data-accordion-component="Accordion">
<div data-accordion-component="AccordionItemButton" tabindex="0" id="1"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="2"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="3"></div>
</div>
`);
const [
firstButton,
secondButton,
thirdButton,
]: HTMLElement[] = Array.from(
tree.querySelectorAll(
'[data-accordion-component="AccordionItemButton"]',
),
);
// Predicate
if (
!(
firstButton instanceof HTMLElement &&
secondButton instanceof HTMLElement &&
thirdButton instanceof HTMLElement
)
) {
throw new Error('buttons not found');
}
firstButton.focus();
expect(document.activeElement).toBe(firstButton);
// Matter
focusNextSiblingOf(firstButton);
expect(document.activeElement).toBe(secondButton);
});
});
describe('focusPreviousSiblingOf', () => {
it('focuses the previous button in document flow', () => {
const tree = createTree(`
<div data-accordion-component="Accordion">
<div data-accordion-component="AccordionItemButton" tabindex="0" id="1"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="2"></div>
<div data-accordion-component="AccordionItemButton" tabindex="0" id="3"></div>
</div>
`);
const [
firstButton,
secondButton,
thirdButton,
]: HTMLElement[] = Array.from(
tree.querySelectorAll(
'[data-accordion-component="AccordionItemButton"]',
),
);
// Predicate
if (
!(
firstButton instanceof HTMLElement &&
secondButton instanceof HTMLElement &&
thirdButton instanceof HTMLElement
)
) {
throw new Error('buttons not found');
}
thirdButton.focus();
expect(document.activeElement).toBe(thirdButton);
// Matter
focusPreviousSiblingOf(thirdButton);
expect(document.activeElement).toBe(secondButton);
});
});
}); | the_stack |
import { AvlTreeIndex, TreeNode } from "../../src/avl_index";
import { IRangedIndexRequest, RangedIndexFactoryMap, IRangedIndex } from "../../src/ranged_indexes";
import { CreateJavascriptComparator, ComparatorMap, ILokiComparer } from "../../src/comparators";
import { Loki } from "../../src/loki";
import { Doc } from "../../../common/types";
describe("avl tree index tests", () => {
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const count = 100;
let cmp = CreateJavascriptComparator<string>();
// setup utility function for random string generation
let genRandomVal = () => {
let text = "";
for (let i = 0; i < 20; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
// setup utility function to shuffle array
let shuffle = (array: any[]) => {
let currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
let reverseString = (str: string) => {
let splitString = str.split("");
let reverseArray = splitString.reverse();
let joinArray = reverseArray.join("");
return joinArray;
};
beforeEach(() => {
});
it("avl population works", () => {
let avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "smith");
avl.insert(2, "patterson");
avl.insert(3, "albertson");
avl.insert(4, "gilbertson");
avl.insert(5, "yannitz");
avl.insert(6, "harrison");
avl.insert(7, "livingstone");
avl.insert(8, "gilbertson");
avl.insert(9, "lapierre");
// get all sorted ids (since not passing an IRangeRequest)
let result: number[] = avl.rangeRequest();
// verify number of elements is accurate
expect(result.length).toEqual(9);
// verify ordering is correct
expect(result[0]).toEqual(3);
// handle the duplicate
expect(result[1] === 4 || result[1] === 8).toEqual(true);
expect(result[2] === 4 || result[2] === 8).toEqual(true);
expect(result[1] !== result[2]).toEqual(true);
// resume asserting order of remaining
expect(result[3]).toEqual(6);
expect(result[4]).toEqual(9);
expect(result[5]).toEqual(7);
expect(result[6]).toEqual(2);
expect(result[7]).toEqual(1);
expect(result[8]).toEqual(5);
});
it("avl population stress test works", () => {
let avl = new AvlTreeIndex<string>("rand", cmp);
let idbuf: number[] = [];
let rnd: string;
// Populate avl and retain values
for (let idx = 0; idx < count; idx++) {
rnd = genRandomVal();
idbuf.push(idx + 1);
avl.insert(idx + 1, rnd);
}
expect(idbuf.length).toEqual(count);
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(count);
// suffle id array and then sequentially update index vals
shuffle(idbuf);
for (let id of idbuf) {
avl.update(id, genRandomVal());
}
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(count);
});
it("avl maintenance (unique vals) stress test works", () => {
let idbuf: number[] = [];
let rnd: string;
let avl = new AvlTreeIndex<string>("last", cmp);
// insert random values into avl and retain values using numeric id greater than 0
for (let idx = 1; idx <= count; idx++) {
idbuf.push(idx);
rnd = genRandomVal();
avl.insert(idx, rnd);
}
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(count);
// now update every value in the index to a different random value
shuffle(idbuf);
for (let id of idbuf) {
let urnd = genRandomVal();
avl.update(id, urnd);
}
// make sure the index is still valid
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(count);
shuffle(idbuf);
for (let id of idbuf) {
avl.remove(id);
expect(avl.validateIndex()).toEqual(true);
}
});
it("avl maintenance with dups stress test works", () => {
let idbuf: number[] = [];
let valbuf: string[] = [];
let rnd: string;
let avl = new AvlTreeIndex<string>("last", cmp);
// insert random values into avl and retain values using numeric id greater than 0
for (let idx = 1; idx <= count; idx++) {
idbuf.push(idx);
rnd = genRandomVal();
valbuf.push(rnd);
avl.insert(idx, rnd);
}
shuffle(idbuf);
// now insert duplicate values for all previous inserted values
for (let idx = 0; idx < count; idx++) {
avl.insert(count + idx + 1, valbuf[idx]);
}
// make sure the index is still valid
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(count * 2);
});
it("avl maintenance with dups and removes stress", () => {
let idbuf: number[] = [];
let valbuf: string[] = [];
let rnd: string;
let avl = new AvlTreeIndex<string>("last", cmp);
// insert random values into avl and retain values using numeric id greater than 0
for (let idx = 0; idx < count; idx++) {
idbuf.push(idx + 1);
rnd = genRandomVal();
valbuf.push(rnd);
avl.insert(idx + 1, rnd);
}
// now insert duplicate values for all previous inserted values
for (let idx = 0; idx < count; idx++) {
idbuf.push(count + idx + 1);
avl.insert(count + idx + 1, valbuf[idx]);
// verify siblings
if (avl.nodes[idx + 1].siblings.length !== 1) {
throw new Error("wrong number of siblings");
}
if (avl.nodes[count + idx + 1].siblings.length !== 0) {
throw new Error("wrong number of siblings");
}
if (avl.nodes[count + idx + 1].parent !== idx + 1) {
throw new Error("incorrectly parented sibling");
}
}
// make sure the index is still valid
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(count * 2);
shuffle(idbuf);
for (let idx = 0; idx < idbuf.length; idx++) {
avl.remove(idbuf[idx]);
}
// make sure the index is still valid
expect(avl.validateIndex()).toEqual(true);
expect(avl.rangeRequest().length).toEqual(0);
});
it("insert rotation balancing check", () => {
// left heavy involving apex
// insert s,p,a
// expect p(a)(s)
let avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "smith");
avl.insert(2, "patterson");
avl.insert(3, "albertson");
expect(avl.apex).toEqual(2);
expect(avl.nodes[avl.apex].height).toEqual(1);
expect(avl.nodes[avl.apex].balance).toEqual(0);
expect(avl.nodes[avl.apex].left).toEqual(3);
expect(avl.nodes[avl.apex].right).toEqual(1);
expect(avl.nodes[1].height).toEqual(0);
expect(avl.nodes[1].balance).toEqual(0);
expect(avl.nodes[3].height).toEqual(0);
expect(avl.nodes[3].balance).toEqual(0);
// right heavy involving apex
// insert a,p,s
// expect p(a)(s)
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(3, "albertson");
avl.insert(2, "patterson");
avl.insert(1, "smith");
expect(avl.apex).toEqual(2);
expect(avl.nodes[avl.apex].left).toEqual(3);
expect(avl.nodes[avl.apex].right).toEqual(1);
// double right heavy
// insert order : s,p,a,g,h
// expect final = p(g(a)(h))(s)
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "smith");
avl.insert(2, "patterson");
avl.insert(3, "albertson");
avl.insert(4, "gilbertson");
avl.insert(6, "harrison");
expect(avl.apex).toEqual(2);
expect(avl.nodes[avl.apex].left).toEqual(4);
expect(avl.nodes[avl.apex].right).toEqual(1);
expect(avl.nodes[4].left).toEqual(3);
expect(avl.nodes[4].right).toEqual(6);
// right-left heavy
// insert order : s,p,a,g,d
// expect final : p(d(a)(g))(s)
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "smith");
avl.insert(2, "patterson");
avl.insert(3, "albertson");
avl.insert(4, "gilbertson");
avl.insert(6, "donaldson");
expect(avl.apex).toEqual(2);
expect(avl.nodes[avl.apex].left).toEqual(6);
expect(avl.nodes[avl.apex].right).toEqual(1);
expect(avl.nodes[6].left).toEqual(3);
expect(avl.nodes[6].right).toEqual(4);
// double left heavy
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "patterson");
avl.insert(2, "gilbertson");
avl.insert(3, "smith");
avl.insert(4, "donaldson");
avl.insert(5, "albertson");
expect(avl.apex).toEqual(1);
expect(avl.nodes[1].left).toEqual(4);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[4].left).toEqual(5);
expect(avl.nodes[4].right).toEqual(2);
// left right heavy
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "patterson");
avl.insert(2, "gilbertson");
avl.insert(3, "smith");
avl.insert(4, "albertson");
avl.insert(5, "donaldson");
expect(avl.apex).toEqual(1);
expect(avl.nodes[1].left).toEqual(5);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[5].left).toEqual(4);
expect(avl.nodes[5].right).toEqual(2);
});
it("remove leafs, causing rotation to rebalance", () => {
let avl = new AvlTreeIndex<string>("last", cmp);
// double left heavy involving remove
// interim tree p (g (d)(h)) (s ()(t))
// remove t (removing right leaf)
// final expect g (d (a)(f)) (p (h)(s)))
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "patterson");
avl.insert(2, "gilbertson");
avl.insert(3, "smith");
avl.insert(4, "donaldson");
avl.insert(5, "harrison");
avl.insert(6, "thompson"); // keep balanced during next 2 inserts
avl.insert(7, "albertson");
avl.insert(8, "fiset");
expect(avl.apex).toEqual(1);
expect(avl.nodes[1].left).toEqual(2);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[2].left).toEqual(4);
expect(avl.nodes[2].right).toEqual(5);
avl.remove(6); // make tree double left heavy
expect(avl.apex).toEqual(2);
expect(avl.nodes[2].left).toEqual(4);
expect(avl.nodes[2].right).toEqual(1);
expect(avl.nodes[1].left).toEqual(5);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[4].left).toEqual(7);
expect(avl.nodes[4].right).toEqual(8);
// double right heavy involving remove
// interim tree g (d (a)()) (p (l) (t (s)(w)))
// remove a (remove left leaf)
// final tree p (g (d)(l)) (t (s)(w))
avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "gilbertson");
avl.insert(2, "donaldson");
avl.insert(3, "patterson");
avl.insert(4, "albertson"); // later leaf to remove
avl.insert(5, "lapierre");
avl.insert(6, "thompson");
avl.insert(7, "smith");
avl.insert(8, "williams");
expect(avl.apex).toEqual(1);
expect(avl.nodes[1].left).toEqual(2);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[3].left).toEqual(5);
expect(avl.nodes[3].right).toEqual(6);
avl.remove(4); // make tree double right heavy
expect(avl.apex).toEqual(3);
expect(avl.nodes[3].left).toEqual(1);
expect(avl.nodes[3].right).toEqual(6);
expect(avl.nodes[1].left).toEqual(2);
expect(avl.nodes[1].right).toEqual(5);
expect(avl.nodes[6].left).toEqual(7);
expect(avl.nodes[6].right).toEqual(8);
});
// verify that we use in-order predecessor
// predecessor may have 0-1 children
// this test will use predecessor with no children
it("remove rotation where node has two children and tree is left heavy", () => {
// interim tree p (g (d)(h)) (s) root balance = -1
let avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "patterson");
avl.insert(2, "gilbertson");
avl.insert(3, "smith");
avl.insert(4, "donaldson");
avl.insert(5, "harrison");
expect(avl.apex).toEqual(1);
expect(avl.nodes[1].left).toEqual(2);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[2].left).toEqual(4);
expect(avl.nodes[2].right).toEqual(5);
expect(avl.nodes[3].left).toEqual(null);
expect(avl.nodes[3].right).toEqual(null);
// remove root which has two children and that root is left heavy...
// it will use in-order predecessor (h) to reduce chance of rotation
// new tree should be h (g (d)()) (s)
avl.remove(1);
expect(avl.apex).toEqual(5);
expect(avl.nodes[5].left).toEqual(2);
expect(avl.nodes[5].right).toEqual(3);
expect(avl.nodes[2].left).toEqual(4);
expect(avl.nodes[2].right).toEqual(null);
expect(avl.nodes[3].left).toEqual(null);
expect(avl.nodes[3].right).toEqual(null);
});
// verify that we use in-order successor
// succecessor may have 0-1 children
// this test will use successor with no children
it("remove rotation where node has two children and tree is right heavy", () => {
// interim tree g (d) (p (h)(t)) root balance = +1
let avl = new AvlTreeIndex<string>("last", cmp);
avl.insert(1, "gilbertson");
avl.insert(2, "donaldson");
avl.insert(3, "patterson");
avl.insert(4, "harrison");
avl.insert(5, "thompson");
expect(avl.apex).toEqual(1);
expect(avl.nodes[1].left).toEqual(2);
expect(avl.nodes[1].right).toEqual(3);
expect(avl.nodes[2].left).toEqual(null);
expect(avl.nodes[2].right).toEqual(null);
expect(avl.nodes[3].left).toEqual(4);
expect(avl.nodes[3].right).toEqual(5);
// remove root which has two children and that root is right heavy...
// it will use in-order predecessor (h) to reduce chance of rotation
// new tree should be h (g (d)()) (s)
avl.remove(1);
expect(avl.apex).toEqual(4);
expect(avl.nodes[4].left).toEqual(2);
expect(avl.nodes[4].right).toEqual(3);
expect(avl.nodes[2].left).toEqual(null);
expect(avl.nodes[2].right).toEqual(null);
expect(avl.nodes[3].left).toEqual(null);
expect(avl.nodes[3].right).toEqual(5);
});
it("avl $eq rangeRequest works", () => {
let idbuf: number[] = [];
let valbuf: string[] = [];
let rnd: string;
let avl = new AvlTreeIndex<string>("asdf", cmp);
// insert random values into avl and retain values using numeric id greater than 0
for (let idx = 1; idx <= count; idx++) {
idbuf.push(idx);
rnd = genRandomVal();
valbuf.push(rnd);
avl.insert(idx, rnd);
}
for (let idx = 1; idx <= count; idx++) {
idbuf.push(count + idx);
avl.insert(count + idx, valbuf[idx - 1]);
}
for (let idx = 1; idx <= count; idx++) {
let matches = avl.rangeRequest({
op: "$eq",
val: valbuf[idx - 1]
});
expect(matches.length).toEqual(2);
}
});
it("avl $lt rangeRequest works", () => {
let avl = new AvlTreeIndex<string>("test", cmp);
avl.insert(1, "dsa"); // should be in results
avl.insert(2, "xja");
avl.insert(3, "asd"); // should be in results
avl.insert(4, "gfd"); // not in results since op is $lt
avl.insert(5, "ert"); // should be in results
avl.insert(6, "mnb");
avl.insert(7, "vbn");
avl.insert(8, "rty");
avl.insert(9, "zxc");
let result: number[] = avl.rangeRequest({ op: "$lt", val: "gfd" });
expect(result.length).toEqual(3);
expect(result[0]).toEqual(3);
expect(result[1]).toEqual(1);
expect(result[2]).toEqual(5);
});
it("avl $lte rangeRequest works", () => {
let avl = new AvlTreeIndex<string>("test", cmp);
avl.insert(1, "dsa"); // should be in results
avl.insert(2, "xja");
avl.insert(3, "asd"); // should be in results
avl.insert(4, "gfd"); // should be in results
avl.insert(5, "ert"); // should be in results
avl.insert(6, "mnb");
avl.insert(7, "vbn");
avl.insert(8, "rty");
avl.insert(9, "zxc");
let result: number[] = avl.rangeRequest({ op: "$lte", val: "gfd" });
expect(result.length).toEqual(4);
expect(result[0]).toEqual(3);
expect(result[1]).toEqual(1);
expect(result[2]).toEqual(5);
expect(result[3]).toEqual(4);
});
it("avl $gt rangeRequest works", () => {
let avl = new AvlTreeIndex<string>("test", cmp);
avl.insert(1, "dsa");
avl.insert(2, "xja"); // should be in results
avl.insert(3, "asd");
avl.insert(4, "gfd");
avl.insert(5, "ert");
avl.insert(6, "mnb"); // should -not- be in results since op is $gt
avl.insert(7, "vbn"); // should be in results
avl.insert(8, "rty"); // should be in results
avl.insert(9, "zxc"); // should be in results
let result: number[] = avl.rangeRequest({ op: "$gt", val: "mnb" });
expect(result.length).toEqual(4);
expect(result[0]).toEqual(8);
expect(result[1]).toEqual(7);
expect(result[2]).toEqual(2);
expect(result[3]).toEqual(9);
});
it("avl $gte rangeRequest works", () => {
let avl = new AvlTreeIndex<string>("test", cmp);
avl.insert(1, "dsa");
avl.insert(2, "xja"); // should be in results
avl.insert(3, "asd");
avl.insert(4, "gfd");
avl.insert(5, "ert");
avl.insert(6, "mnb"); // should be in results
avl.insert(7, "vbn"); // should be in results
avl.insert(8, "rty"); // should be in results
avl.insert(9, "zxc"); // should be in results
let result: number[] = avl.rangeRequest({ op: "$gte", val: "mnb" });
expect(result.length).toEqual(5);
expect(result[0]).toEqual(6);
expect(result[1]).toEqual(8);
expect(result[2]).toEqual(7);
expect(result[3]).toEqual(2);
expect(result[4]).toEqual(9);
});
it("avl $between rangeRequest works", () => {
let avl = new AvlTreeIndex<string>("test", cmp);
avl.insert(1, "dsa");
avl.insert(2, "xja");
avl.insert(3, "asd");
avl.insert(4, "gfd"); // should be in results
avl.insert(5, "ert");
avl.insert(6, "mnb"); // should be in results
avl.insert(7, "vbn"); // should be in results
avl.insert(8, "rty"); // should be in results
avl.insert(9, "zxc");
let result: number[] = avl.rangeRequest({ op: "$between", val: "gfd", high: "vbn" });
expect(result.length).toEqual(4);
expect(result[0]).toEqual(4);
expect(result[1]).toEqual(6);
expect(result[2]).toEqual(8);
expect(result[3]).toEqual(7);
});
it("collection find ops on avl index work", () => {
interface TestUserType {
name: string;
age: number;
location: string;
}
const db = new Loki("idxtest");
const items = db.addCollection<TestUserType>("users", {
rangedIndexes: {
name: { indexTypeName: "avl", comparatorName: "js" }
}
});
items.insert([
{ name: "patterson", age: 10, location: "a" },
{ name: "gilbertson", age: 20, location: "b" },
{ name: "smith", age: 30, location: "c" },
{ name: "donaldson", age: 40, location: "d" },
{ name: "harrison", age: 50, location: "e" },
{ name: "thompson", age: 60, location: "f" },
{ name: "albertson", age: 70, location: "g" },
{ name: "fiset", age: 80, location: "h" }
]);
// $eq
let results: TestUserType[] = items.find({ name: "donaldson" });
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("donaldson");
expect(results[0].age).toEqual(40);
expect(results[0].location).toEqual("d");
// $lt
results = items.find({ name: { $lt: "giraffe" } });
expect(results.length).toEqual(4);
expect(results[0].name).toEqual("albertson");
expect(results[1].name).toEqual("donaldson");
expect(results[2].name).toEqual("fiset");
expect(results[3].name).toEqual("gilbertson");
// $lte
results = items.find({ name: { $lte: "fiset" } });
expect(results.length).toEqual(3);
expect(results[0].name).toEqual("albertson");
expect(results[1].name).toEqual("donaldson");
expect(results[2].name).toEqual("fiset");
// $gt
results = items.find({ name: { $gt: "giraffe" } });
expect(results.length).toEqual(4);
expect(results[0].name).toEqual("harrison");
expect(results[1].name).toEqual("patterson");
expect(results[2].name).toEqual("smith");
expect(results[3].name).toEqual("thompson");
// $gte
results = items.find({ name: { $gte: "patterson" } });
expect(results.length).toEqual(3);
expect(results[0].name).toEqual("patterson");
expect(results[1].name).toEqual("smith");
expect(results[2].name).toEqual("thompson");
// $between
results = items.find({ name: { $between: ["faraday", "samuel"] } });
expect(results.length).toEqual(4);
expect(results[0].name).toEqual("fiset");
expect(results[1].name).toEqual("gilbertson");
expect(results[2].name).toEqual("harrison");
expect(results[3].name).toEqual("patterson");
});
it("update works on collection with avl index", () => {
interface TestUserType {
name: string;
age: number;
location: string;
}
const db = new Loki("idxtest");
const items = db.addCollection<TestUserType>("users", {
rangedIndexes: {
name: { indexTypeName: "avl", comparatorName: "js" }
}
});
items.insert([
{ name: "patterson", age: 10, location: "a" },
{ name: "gilbertson", age: 20, location: "b" },
{ name: "smith", age: 30, location: "c" },
{ name: "donaldson", age: 40, location: "d" },
{ name: "harrison", age: 50, location: "e" },
{ name: "thompson", age: 60, location: "f" },
{ name: "albertson", age: 70, location: "g" },
]);
items.chain().update((o: Doc<TestUserType>) => { o.name = reverseString(o.name); return o; });
let result = items.find({ name: { $lte: "nosk" } });
expect(result.length).toEqual(3);
expect(result[0].name).toEqual("htims");
expect(result[1].name).toEqual("nosdlanod");
expect(result[2].name).toEqual("nosirrah");
// using weak filter to return all docs ordered by our index
result = items.find({ name: { $gte: "a" } });
expect(result.length).toEqual(7);
expect(result[0].name).toEqual("htims");
expect(result[1].name).toEqual("nosdlanod");
expect(result[2].name).toEqual("nosirrah");
expect(result[3].name).toEqual("nospmoht");
expect(result[4].name).toEqual("nosrettap");
expect(result[5].name).toEqual("nostrebla");
expect(result[6].name).toEqual("nostreblig");
});
it("remove works on collection with avl index", () => {
interface TestUserType {
name: string;
age: number;
location: string;
}
const db = new Loki("idxtest");
const items = db.addCollection<TestUserType>("users", {
rangedIndexes: {
name: { indexTypeName: "avl", comparatorName: "js" }
}
});
items.insert([
{ name: "patterson", age: 10, location: "a" },
{ name: "gilbertson", age: 20, location: "b" },
{ name: "smith", age: 30, location: "c" },
{ name: "donaldson", age: 40, location: "d" },
{ name: "harrison", age: 50, location: "e" },
{ name: "thompson", age: 60, location: "f" },
{ name: "albertson", age: 70, location: "g" },
]);
items.chain().find({ name: { $lte: "goldman" } }).remove();
let result = items.find({ name: { $lte: "samuels" } });
expect(result.length).toEqual(2);
expect(result[0].name).toEqual("harrison");
expect(result[1].name).toEqual("patterson");
});
it("simplesort works on collection with avl index", () => {
interface TestUserType {
name: string;
age: number;
location: string;
}
const db = new Loki("idxtest");
const items = db.addCollection<TestUserType>("users", {
rangedIndexes: {
name: { indexTypeName: "avl", comparatorName: "js" }
}
});
items.insert([
{ name: "patterson", age: 10, location: "a" },
{ name: "gilbertson", age: 20, location: "b" },
{ name: "smith", age: 30, location: "c" },
{ name: "donaldson", age: 40, location: "d" },
{ name: "harrison", age: 50, location: "e" },
{ name: "thompson", age: 60, location: "f" },
{ name: "albertson", age: 70, location: "g" },
]);
let result: TestUserType[] = items.chain().simplesort("name").data();
expect(result.length).toEqual(7);
expect(result[0].name).toEqual("albertson");
expect(result[1].name).toEqual("donaldson");
expect(result[2].name).toEqual("gilbertson");
expect(result[3].name).toEqual("harrison");
expect(result[4].name).toEqual("patterson");
expect(result[5].name).toEqual("smith");
expect(result[6].name).toEqual("thompson");
});
it("comparator and ranged index maps can be injected into", () => {
let cmp = (a: any, b: any) => {
if (a > b) return 1;
if (a === b) return 0;
return -1;
};
// not really a functional ranged index, should have constructor accepting comparator
class customRangedIndex<T> implements IRangedIndex<T> {
public name: string;
public comparator: ILokiComparer<T>;
constructor(name: string, comparator: ILokiComparer<T>) {
this.name = name;
this.comparator = comparator;
}
insert(id: number, val: T) {
if (!id || !val) throw new Error("");
return;
}
update(id: number, val: T) {
if (!id || val === null) throw new Error("");
return;
}
remove(id: number) {
if (!id) throw new Error("");
return;
}
restore(tree: any) {
if (!tree) throw new Error("");
return;
}
backup() {
return this;
}
rangeRequest(range?: IRangedIndexRequest<T>) {
if (range === null) {
// return everything
return <number[]> [];
}
return <number[]> [];
}
validateIndex() {
return true;
}
}
let myCustomIndexFactory = (name: string, cmp: ILokiComparer<any>) => { return new customRangedIndex<any>(name, cmp); };
let db = new Loki("test.db", {
comparatorMap: {
"FastNumeric": cmp
},
rangedIndexFactoryMap: {
"MyCustomRangedIndex": myCustomIndexFactory
}
});
expect(db instanceof Loki).toEqual(true);
// verify they are registered into (global for now) comparator and rangedindex factory maps
expect(ComparatorMap.hasOwnProperty("FastNumeric")).toEqual(true);
expect(typeof ComparatorMap["FastNumeric"]).toEqual("function");
expect(RangedIndexFactoryMap.hasOwnProperty("MyCustomRangedIndex")).toEqual(true);
expect(typeof RangedIndexFactoryMap["MyCustomRangedIndex"]).toEqual("function");
});
it("nested property with avl index work", () => {
interface TestUserType {
user: {
name: string;
age: number;
location: string;
};
}
const db = new Loki("idxtest");
const items = db.addCollection<TestUserType, { "user.name": string }>("users", {
rangedIndexes: {
"user.name": { indexTypeName: "avl", comparatorName: "js" }
},
nestedProperties: ["user.name"]
});
items.insert([
{ user: { name: "patterson", age: 10, location: "a" } },
{ user: { name: "gilbertson", age: 20, location: "b" } },
{ user: { name: "smith", age: 30, location: "c" } },
{ user: { name: "donaldson", age: 40, location: "d" } },
{ user: { name: "harrison", age: 50, location: "e" } },
{ user: { name: "thompson", age: 60, location: "f" } },
{ user: { name: "albertson", age: 70, location: "g" } },
{ user: { name: "fiset", age: 80, location: "h" } }
]);
// $eq
let results: TestUserType[] = items.find({ "user.name": "donaldson" });
expect(results.length).toEqual(1);
expect(results[0].user.name).toEqual("donaldson");
expect(results[0].user.age).toEqual(40);
expect(results[0].user.location).toEqual("d");
// $lt
results = items.find({ "user.name": { $lt: "giraffe" } });
expect(results.length).toEqual(4);
expect(results[0].user.name).toEqual("albertson");
expect(results[1].user.name).toEqual("donaldson");
expect(results[2].user.name).toEqual("fiset");
expect(results[3].user.name).toEqual("gilbertson");
// $lte
results = items.find({ "user.name": { $lte: "fiset" } });
expect(results.length).toEqual(3);
expect(results[0].user.name).toEqual("albertson");
expect(results[1].user.name).toEqual("donaldson");
expect(results[2].user.name).toEqual("fiset");
// $gt
results = items.find({ "user.name": { $gt: "giraffe" } });
expect(results.length).toEqual(4);
expect(results[0].user.name).toEqual("harrison");
expect(results[1].user.name).toEqual("patterson");
expect(results[2].user.name).toEqual("smith");
expect(results[3].user.name).toEqual("thompson");
// $gte
results = items.find({ "user.name": { $gte: "patterson" } });
expect(results.length).toEqual(3);
expect(results[0].user.name).toEqual("patterson");
expect(results[1].user.name).toEqual("smith");
expect(results[2].user.name).toEqual("thompson");
// $between
results = items.find({ "user.name": { $between: ["faraday", "samuel"] } });
expect(results.length).toEqual(4);
expect(results[0].user.name).toEqual("fiset");
expect(results[1].user.name).toEqual("gilbertson");
expect(results[2].user.name).toEqual("harrison");
expect(results[3].user.name).toEqual("patterson");
// simplesort
results = items.chain().simplesort("user.name").data();
expect(results.length).toEqual(8);
expect(results[0].user.name).toEqual("albertson");
expect(results[1].user.name).toEqual("donaldson");
expect(results[2].user.name).toEqual("fiset");
expect(results[3].user.name).toEqual("gilbertson");
expect(results[4].user.name).toEqual("harrison");
expect(results[5].user.name).toEqual("patterson");
expect(results[6].user.name).toEqual("smith");
expect(results[7].user.name).toEqual("thompson");
// remove
items.chain().find({ "user.name": { $lte: "goldman" } }).remove();
results = items.find({ "user.name": { $lte: "samuels" } });
expect(results.length).toEqual(2);
expect(results[0].user.name).toEqual("harrison");
expect(results[1].user.name).toEqual("patterson");
// update
items.chain().update((o) => { o.user.name = reverseString(o.user.name); return o; });
results = items.find({ "user.name": { $gte: "nork" } });
expect(results.length).toEqual(3);
expect(results[0].user.name).toEqual("nosirrah");
expect(results[1].user.name).toEqual("nospmoht");
expect(results[2].user.name).toEqual("nosrettap");
});
it("avl index raises exceptions where appropriate", () => {
let cmp: ILokiComparer<any> = (a: any, b: any) => { return (a > b) ? -1 : 0; };
let avl = new AvlTreeIndex("test", cmp);
// if inserting val <= 0, expect an error to be thrown
expect(() => avl.insert(0, "test")).toThrow(new Error("avl index ids are required to be numbers greater than zero"));
// if comparator returns value other than -1, 0, or 1, expect an error to be thrown
let node1: TreeNode<any> = {
id: 0, value: 0, parent: null, balance: 0, height: 0, left: null, right: null, siblings: []
};
let node2: TreeNode<any> = {
id: 0, value: 0, parent: null, balance: 0, height: 0, left: null, right: null, siblings: []
};
let icmp = (a: any, b: any) => { return (a > b) ? -2 : 2; };
cmp = icmp as any as ILokiComparer<any>;
avl.comparator = cmp;
expect(() => avl.insertNode(node1, node2)).toThrow(new Error("Invalid comparator result"));
// attempting to remove a node from an avl tree which has no index should throw error
avl.apex = null;
expect(() => avl.remove(1)).toThrow(new Error("remove() : attempting remove when tree has no apex"));
});
}); | the_stack |
import { assert } from "chai";
import seedrandom = require("seedrandom");
import { LWWCVariable, CRDTApp, PrimitiveCRDT, CRDTMeta } from "../../src";
import {
Optional,
ManualBatchingStrategy,
pseudoRandomReplicaID,
Pre,
MessageMeta,
CollabEvent,
CollabEventsRecord,
} from "@collabs/core";
interface MetaEvent extends CollabEvent {
message: string;
crdtMeta: CRDTMeta;
}
interface MetaEventsRecord extends CollabEventsRecord {
Meta: MetaEvent;
}
class MetaInspector extends PrimitiveCRDT<MetaEventsRecord> {
sendCRDT(
message: string,
requests?: {
automatic?: boolean;
vectorClockEntries?: Iterable<string>;
wallClockTime?: boolean;
lamportTimestamp?: boolean;
all?: boolean;
}
): void {
super.sendCRDT(message, requests);
}
protected receiveCRDT(
message: string | Uint8Array,
meta: MessageMeta,
crdtMeta: CRDTMeta
): void {
this.emit("Meta", { meta, message: <string>message, crdtMeta });
}
save(): Uint8Array {
return new Uint8Array();
}
load(_saveData: Optional<Uint8Array>): void {}
canGC(): boolean {
throw new Error("Method not implemented.");
}
}
function assertMetaEvent(
e: MetaEvent | null,
message: string,
sender: string,
senderCounter: number,
wallClockTime: number | null,
lamportTimestamp: number | null,
vc: [replicaID: string, entry: number][]
) {
assert.isNotNull(e);
assert.strictEqual(e!.message, message);
const crdtMeta = e!.crdtMeta;
assert.strictEqual(crdtMeta.sender, sender);
assert.strictEqual(crdtMeta.senderCounter, senderCounter);
assert.strictEqual(crdtMeta.wallClockTime, wallClockTime);
assert.strictEqual(crdtMeta.lamportTimestamp, lamportTimestamp);
for (const [replicaID, entry] of vc) {
assert.strictEqual(crdtMeta.vectorClockGet(replicaID), entry);
}
}
describe("CRDTMetaLayer", () => {
for (const causalityGuaranteed of [true, false]) {
describe(`causalityGuaranteed: ${causalityGuaranteed}`, () => {
let alice: CRDTApp;
let bob: CRDTApp;
let aliceID: string;
let bobID: string;
let aliceMessage: Uint8Array | null = null;
let bobMessage: Uint8Array | null = null;
let rng: seedrandom.prng;
beforeEach(() => {
rng = seedrandom("42");
alice = new CRDTApp({
batchingStrategy: new ManualBatchingStrategy(),
causalityGuaranteed,
debugReplicaID: pseudoRandomReplicaID(rng),
});
aliceID = alice.runtime.replicaID;
alice.on("Send", (e) => {
aliceMessage = e.message;
});
bob = new CRDTApp({
batchingStrategy: new ManualBatchingStrategy(),
causalityGuaranteed,
debugReplicaID: pseudoRandomReplicaID(rng),
});
bobID = bob.runtime.replicaID;
bob.on("Send", (e) => {
bobMessage = e.message;
});
});
function load() {
alice.load(Optional.empty());
bob.load(Optional.empty());
}
describe("no batching", () => {
it("delivers messages immediately", () => {
const aliceVariable = alice.registerCollab(
"variable",
Pre(LWWCVariable)(0)
);
const bobVariable = bob.registerCollab(
"variable",
Pre(LWWCVariable)(0)
);
load();
assert.strictEqual(aliceVariable.value, 0);
assert.strictEqual(bobVariable.value, 0);
aliceVariable.value = 3;
alice.commitBatch();
assert.isNotNull(aliceMessage);
assert.strictEqual(aliceVariable.value, 3);
assert.strictEqual(bobVariable.value, 0);
bob.receive(aliceMessage!);
assert.strictEqual(bobVariable.value, 3);
aliceMessage = null;
bobVariable.value = 5;
bob.commitBatch();
assert.isNotNull(bobMessage);
assert.strictEqual(aliceVariable.value, 3);
assert.strictEqual(bobVariable.value, 5);
alice.receive(bobMessage!);
assert.strictEqual(aliceVariable.value, 5);
assert.strictEqual(bobVariable.value, 5);
bobMessage = null;
aliceVariable.value = 10;
alice.commitBatch();
assert.isNotNull(aliceMessage);
bobVariable.value = 11;
bob.commitBatch();
assert.isNotNull(bobMessage);
assert.strictEqual(aliceVariable.value, 10);
assert.strictEqual(bobVariable.value, 11);
alice.receive(bobMessage!);
bob.receive(aliceMessage!);
assert.strictEqual(bobVariable.value, aliceVariable.value);
});
describe("CRDTMeta", () => {
let aliceInspector: MetaInspector;
let bobInspector: MetaInspector;
let aliceEvent: MetaEvent | null = null;
let bobEvent: MetaEvent | null = null;
beforeEach(() => {
aliceInspector = alice.registerCollab(
"inspector",
Pre(MetaInspector)()
);
bobInspector = bob.registerCollab(
"inspector",
Pre(MetaInspector)()
);
aliceInspector.on("Meta", (e) => {
aliceEvent = e;
});
bobInspector.on("Meta", (e) => {
bobEvent = e;
});
load();
});
it("requests nothing", () => {
// Own receipts.
aliceInspector.sendCRDT("1");
assertMetaEvent(aliceEvent, "1", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
bobInspector.sendCRDT("2");
assertMetaEvent(bobEvent, "2", bobID, 1, null, null, [
[aliceID, 0],
[bobID, 1],
]);
// Commit batch doesn't change own receipts.
alice.commitBatch();
bob.commitBatch();
assert.strictEqual(aliceEvent!.message, "1");
assert.strictEqual(bobEvent!.message, "2");
// Other receipts.
alice.receive(bobMessage!);
bob.receive(aliceMessage!);
assertMetaEvent(aliceEvent, "2", bobID, 1, null, null, [
[aliceID, 0],
[bobID, 1],
]);
assertMetaEvent(bobEvent, "1", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
// If causalityGuaranteed, we shouldn't get extra
// VC entries, even though there are two maximal
// causal predecessors.
aliceInspector.sendCRDT("3");
assertMetaEvent(aliceEvent, "3", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, causalityGuaranteed ? 0 : 1],
]);
alice.commitBatch();
bob.receive(aliceMessage!);
assertMetaEvent(bobEvent, "3", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, causalityGuaranteed ? 0 : 1],
]);
});
it("requests wallClockTime", () => {
// Own receipts.
aliceInspector.sendCRDT("1", { wallClockTime: true });
assert.isNotNull(aliceEvent!.crdtMeta.wallClockTime);
assertMetaEvent(
aliceEvent,
"1",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, 0],
]
);
// Commit batch doesn't change own receipts.
alice.commitBatch();
assert.strictEqual(aliceEvent!.message, "1");
// Other receipts.
bob.receive(aliceMessage!);
assertMetaEvent(
bobEvent,
"1",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, 0],
]
);
// Next message doesn't still have wallClockTime.
aliceInspector.sendCRDT("2");
assertMetaEvent(aliceEvent, "2", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 0],
]);
alice.commitBatch();
bob.receive(aliceMessage!);
assertMetaEvent(bobEvent, "2", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 0],
]);
});
it.skip("requests lamportTimestamp", () => {
// TODO
});
it("requests VC", () => {
aliceInspector.sendCRDT("1");
alice.commitBatch();
bob.receive(aliceMessage!);
// Own receipts.
bobInspector.sendCRDT("2", { vectorClockEntries: [aliceID] });
assertMetaEvent(bobEvent, "2", bobID, 1, null, null, [
[aliceID, 1],
[bobID, 1],
]);
// Commit batch doesn't change own receipts.
bob.commitBatch();
assert.strictEqual(bobEvent!.message, "2");
// Other receipts.
alice.receive(bobMessage!);
assertMetaEvent(aliceEvent, "2", bobID, 1, null, null, [
[aliceID, 1],
[bobID, 1],
]);
// Next message doesn't still have alice's VC entry,
// even if !causalityGuaranteed, since it's not
// causally maximal anymore.
bobInspector.sendCRDT("3");
assertMetaEvent(bobEvent, "3", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
bob.commitBatch();
alice.receive(bobMessage!);
assertMetaEvent(aliceEvent, "3", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
});
it("requests all", () => {
aliceInspector.sendCRDT("1");
alice.commitBatch();
bob.receive(aliceMessage!);
// Own receipts.
bobInspector.sendCRDT("2", { all: true });
assert.isNotNull(bobEvent!.crdtMeta.wallClockTime);
assertMetaEvent(
bobEvent,
"2",
bobID,
1,
bobEvent!.crdtMeta.wallClockTime,
1,
[
[aliceID, 1],
[bobID, 1],
]
);
// Commit batch doesn't change own receipts.
bob.commitBatch();
assert.strictEqual(bobEvent!.message, "2");
// Other receipts.
alice.receive(bobMessage!);
assertMetaEvent(
aliceEvent,
"2",
bobID,
1,
bobEvent!.crdtMeta.wallClockTime,
1,
[
[aliceID, 1],
[bobID, 1],
]
);
// Next message doesn't still have metadata.
bobInspector.sendCRDT("3");
assertMetaEvent(bobEvent, "3", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
bob.commitBatch();
alice.receive(bobMessage!);
assertMetaEvent(aliceEvent, "3", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
});
it("requests automatic", () => {
aliceInspector.sendCRDT("1");
alice.commitBatch();
bob.receive(aliceMessage!);
// Request all, but automatically.
// Own receipts.
const off = bobInspector.on("Meta", (e) => {
assert.isNotNull(e.crdtMeta.wallClockTime);
assert.isNotNull(e.crdtMeta.lamportTimestamp);
assert.strictEqual(e.crdtMeta.vectorClockGet(aliceID), 1);
// Requesting random extra VC entry is safe.
assert.strictEqual(e.crdtMeta.vectorClockGet("fakeID"), 0);
});
bobInspector.sendCRDT("2", { automatic: true });
off();
assert.isNotNull(bobEvent!.crdtMeta.wallClockTime);
assertMetaEvent(
bobEvent,
"2",
bobID,
1,
bobEvent!.crdtMeta.wallClockTime,
1,
[
[aliceID, 1],
[bobID, 1],
["fakeID", 0],
]
);
// Commit batch doesn't change own receipts.
bob.commitBatch();
assert.strictEqual(bobEvent!.message, "2");
// Other receipts.
alice.receive(bobMessage!);
assertMetaEvent(
aliceEvent,
"2",
bobID,
1,
bobEvent!.crdtMeta.wallClockTime,
1,
[
[aliceID, 1],
[bobID, 1],
["fakeID", 0],
]
);
// Next message doesn't still have metadata.
bobInspector.sendCRDT("3");
assertMetaEvent(bobEvent, "3", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
bob.commitBatch();
alice.receive(bobMessage!);
assertMetaEvent(aliceEvent, "3", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
});
});
});
describe("transaction", () => {
let aliceInspector: MetaInspector;
let bobInspector: MetaInspector;
let aliceEvent: MetaEvent | null = null;
let bobEvent: MetaEvent | null = null;
beforeEach(() => {
aliceInspector = alice.registerCollab(
"inspector",
Pre(MetaInspector)()
);
bobInspector = bob.registerCollab("inspector", Pre(MetaInspector)());
aliceInspector.on("Meta", (e) => {
aliceEvent = e;
});
bobInspector.on("Meta", (e) => {
bobEvent = e;
});
load();
});
it("reuses CRDTMeta", () => {
aliceInspector.sendCRDT("1");
assert.isNotNull(aliceEvent);
assert.strictEqual(aliceEvent!.message, "1");
const aliceMeta1 = aliceEvent!.crdtMeta;
aliceEvent = null;
for (let i = 2; i < 10; i++) {
aliceInspector.sendCRDT(i + "");
assert.isNotNull(aliceEvent);
assert.strictEqual(aliceEvent!.message, i + "");
assert.strictEqual(aliceEvent!.crdtMeta, aliceMeta1);
// Recall that senderCounter doesn't change (stays 1).
assertMetaEvent(aliceEvent!, i + "", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
aliceEvent = null;
}
// Send to bob.
// Make sure he receives all messages (1 through 9),
// and they all have === CRDTMeta.
alice.commitBatch();
let j = 1;
let bobMeta1: CRDTMeta;
bobInspector.on("Meta", (e) => {
assert.strictEqual(e.message, j + "");
if (j === 1) {
bobMeta1 = e.crdtMeta;
} else {
assert.strictEqual(e.crdtMeta, bobMeta1);
}
assertMetaEvent(bobEvent!, j + "", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
j++;
});
bob.receive(aliceMessage!);
assert.strictEqual(j, 10);
});
it("changes CRDTMeta across batches", () => {
// First batch (pre).
for (let i = 0; i < 10; i++) {
aliceInspector.sendCRDT("pre" + i);
}
const aliceMetaPre = aliceEvent!.crdtMeta;
alice.commitBatch();
bob.receive(aliceMessage!);
const bobMetaPre = bobEvent!.crdtMeta;
// Second batch.
aliceInspector.sendCRDT("1");
assert.isNotNull(aliceEvent);
assert.strictEqual(aliceEvent!.message, "1");
const aliceMeta1 = aliceEvent!.crdtMeta;
assert.notStrictEqual(aliceMeta1, aliceMetaPre);
aliceEvent = null;
for (let i = 2; i < 10; i++) {
aliceInspector.sendCRDT(i + "");
assert.isNotNull(aliceEvent);
assert.strictEqual(aliceEvent!.message, i + "");
assert.strictEqual(aliceEvent!.crdtMeta, aliceMeta1);
// Recall that senderCounter doesn't change (stays 1).
assertMetaEvent(aliceEvent!, i + "", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 0],
]);
aliceEvent = null;
}
// Send to bob.
// Make sure he receives all messages (1 through 9),
// and they all have === CRDTMeta.
alice.commitBatch();
let j = 1;
let bobMeta1: CRDTMeta;
bobInspector.on("Meta", (e) => {
assert.strictEqual(e.message, j + "");
if (j === 1) {
bobMeta1 = e.crdtMeta;
assert.notStrictEqual(bobMeta1, bobMetaPre);
} else {
assert.strictEqual(e.crdtMeta, bobMeta1);
}
assertMetaEvent(bobEvent!, j + "", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 0],
]);
j++;
});
bob.receive(aliceMessage!);
assert.strictEqual(j, 10);
});
it("merges requests", () => {
bobInspector.sendCRDT("pre");
bob.commitBatch();
alice.receive(bobMessage!);
// First message in transaction requests
// wallClockTime only.
aliceInspector.sendCRDT("1", { wallClockTime: true });
assert.isNotNull(aliceEvent!.crdtMeta.wallClockTime);
assertMetaEvent(
aliceEvent,
"1",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, causalityGuaranteed ? 0 : 1],
]
);
// Second message in transaction requests
// lamportTimestamp and bob's VC entry only.
// However, wallClockTime will still be there.
aliceInspector.sendCRDT("2", {
lamportTimestamp: true,
vectorClockEntries: [bobID],
});
assert.isNotNull(aliceEvent!.crdtMeta.wallClockTime);
assertMetaEvent(
aliceEvent,
"2",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
1,
[
[aliceID, 1],
[bobID, 1],
]
);
// Deliver to bob. He should see the merged
// metadata for both messages.
alice.commitBatch();
let j = 1;
bobInspector.on("Meta", (e) => {
assert.strictEqual(e.message, j + "");
assertMetaEvent(
bobEvent!,
j + "",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
1,
[
[aliceID, 1],
[bobID, 1],
]
);
j++;
});
bob.receive(aliceMessage!);
assert.strictEqual(j, 3);
});
it("toggles automatic requests", () => {
bobInspector.sendCRDT("pre");
bob.commitBatch();
alice.receive(bobMessage!);
// Start the transaction with automatic on.
// The first message automatically requests wallClockTime.
{
const off = aliceInspector.on("Meta", (e) => {
assert.isNotNull(e.crdtMeta.wallClockTime);
assert.isNotNull(e.crdtMeta.wallClockTime);
off();
});
}
aliceInspector.sendCRDT("1", { automatic: true });
assert.isNotNull(aliceEvent!.crdtMeta.wallClockTime);
assertMetaEvent(
aliceEvent,
"1",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, causalityGuaranteed ? 0 : 1],
]
);
// The next message should have automatic off.
// It reads lamportTimestamp but shouldn't
// request it.
{
const off = aliceInspector.on("Meta", (e) => {
assert.isNull(e.crdtMeta.lamportTimestamp);
assert.isNull(e.crdtMeta.lamportTimestamp);
off();
});
}
aliceInspector.sendCRDT("2", {});
assert.isNull(aliceEvent!.crdtMeta.lamportTimestamp);
assertMetaEvent(
aliceEvent,
"2",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, causalityGuaranteed ? 0 : 1],
]
);
// The next message is automatic again.
// It requests bob's VC entry.
{
const off = aliceInspector.on("Meta", (e) => {
assert.strictEqual(e.crdtMeta.vectorClockGet(bobID), 1);
assert.strictEqual(e.crdtMeta.vectorClockGet(bobID), 1);
off();
});
}
aliceInspector.sendCRDT("3", { automatic: true });
assertMetaEvent(
aliceEvent,
"3",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, 1],
]
);
// Bob should see only the automatically requested
// fields.
alice.commitBatch();
bob.receive(aliceMessage!);
assertMetaEvent(
bobEvent,
"3",
aliceID,
1,
aliceEvent!.crdtMeta.wallClockTime,
null,
[
[aliceID, 1],
[bobID, 1],
]
);
// The next batch should have automatic off.
// It reads lamportTimestamp but shouldn't
// request it.
{
const off = aliceInspector.on("Meta", (e) => {
assert.isNull(e.crdtMeta.lamportTimestamp);
assert.isNull(e.crdtMeta.lamportTimestamp);
off();
});
}
aliceInspector.sendCRDT("4", {});
assert.isNull(aliceEvent!.crdtMeta.lamportTimestamp);
assertMetaEvent(aliceEvent, "4", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 0],
]);
// Bob should see the same.
alice.commitBatch();
bob.receive(aliceMessage!);
assertMetaEvent(bobEvent, "4", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 0],
]);
});
it("ends due to received message", () => {
bobInspector.sendCRDT("interrupt");
bob.commitBatch();
// Not sent yet.
// First transaction, two messages.
aliceInspector.sendCRDT("1");
assertMetaEvent(aliceEvent, "1", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
const aliceMeta1 = aliceEvent!.crdtMeta;
aliceInspector.sendCRDT("2");
assertMetaEvent(aliceEvent, "2", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
assert.strictEqual(aliceEvent!.crdtMeta, aliceMeta1);
// Interrupt batch with received message.
alice.receive(bobMessage!);
// Second transaction, two messages.
aliceInspector.sendCRDT("3", { vectorClockEntries: [bobID] });
assertMetaEvent(aliceEvent, "3", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 1],
]);
const aliceMeta3 = aliceEvent!.crdtMeta;
aliceInspector.sendCRDT("4");
assertMetaEvent(aliceEvent, "4", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 1],
]);
assert.strictEqual(aliceEvent!.crdtMeta, aliceMeta3);
// Bob should see the same.
alice.commitBatch();
let j = 1;
let bobMeta1!: CRDTMeta;
let bobMeta3!: CRDTMeta;
bobInspector.on("Meta", (e) => {
switch (j) {
case 1:
assertMetaEvent(e, "1", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
bobMeta1 = e.crdtMeta;
break;
case 2:
assertMetaEvent(e, "2", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
assert.strictEqual(e.crdtMeta, bobMeta1);
break;
case 3:
assertMetaEvent(e, "3", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 1],
]);
bobMeta3 = bobEvent!.crdtMeta;
break;
case 4:
assertMetaEvent(e, "4", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 1],
]);
assert.strictEqual(bobEvent!.crdtMeta, bobMeta3);
break;
default:
assert.fail(j + "");
}
j++;
});
bob.receive(aliceMessage!);
assert.strictEqual(j, 5);
});
if (!causalityGuaranteed) {
it("doesn't end due to out-of-order receipt", () => {
bobInspector.sendCRDT("not received");
bob.commitBatch();
const bobMessage1 = bobMessage!;
bobInspector.sendCRDT("interrupt");
bob.commitBatch();
aliceInspector.sendCRDT("1");
assertMetaEvent(aliceEvent, "1", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
const aliceMeta1 = aliceEvent!.crdtMeta;
// Receive out-of-order message.
alice.receive(bobMessage!);
// Should still be in the same transaction.
aliceInspector.sendCRDT("2");
assertMetaEvent(aliceEvent, "2", aliceID, 1, null, null, [
[aliceID, 1],
[bobID, 0],
]);
assert.strictEqual(aliceEvent!.crdtMeta, aliceMeta1);
// Now receive predecessor. This should
// deliver both messages and start a new transaction.
alice.receive(bobMessage1);
assertMetaEvent(aliceEvent, "interrupt", bobID, 2, null, null, [
[aliceID, 0],
[bobID, 2],
]);
aliceInspector.sendCRDT("3");
assertMetaEvent(aliceEvent, "3", aliceID, 2, null, null, [
[aliceID, 2],
[bobID, 2],
]);
assert.notStrictEqual(aliceEvent!.crdtMeta, aliceMeta1);
});
}
});
describe("batch", () => {
let aliceInspector: MetaInspector;
let bobInspector: MetaInspector;
let aliceEvent: MetaEvent | null = null;
let bobEvent: MetaEvent | null = null;
beforeEach(() => {
aliceInspector = alice.registerCollab(
"inspector",
Pre(MetaInspector)()
);
bobInspector = bob.registerCollab("inspector", Pre(MetaInspector)());
aliceInspector.on("Meta", (e) => {
aliceEvent = e;
});
bobInspector.on("Meta", (e) => {
bobEvent = e;
});
load();
});
it("handles multiple transactions", () => {
const bobMessages: Uint8Array[] = [];
for (let i = 1; i <= 5; i++) {
// i messages in this batch/transaction.
for (let j = 1; j <= i; j++) {
bobInspector.sendCRDT("bob" + i + j);
}
bob.commitBatch();
bobMessages.push(bobMessage!);
}
for (let i = 1; i <= 5; i++) {
// Start a new transaction.
alice.receive(bobMessages[i - 1]);
let aliceMeta!: CRDTMeta;
// 6 - i messages in this transaction.
for (let j = 1; j <= 6 - i; j++) {
aliceInspector.sendCRDT("alice" + i + j);
assertMetaEvent(
aliceEvent,
"alice" + i + j,
aliceID,
i,
null,
null,
[
[aliceID, i],
[bobID, causalityGuaranteed ? 0 : i],
]
);
if (j === 1) {
aliceMeta = aliceEvent!.crdtMeta;
} else {
assert.strictEqual(aliceEvent!.crdtMeta, aliceMeta);
}
}
}
// Send all of alice's messages as one batch.
alice.commitBatch();
let i = 1; // transaction number
let j = 1; // message within transaction j
let transactionMeta!: CRDTMeta;
bobInspector.on("Meta", (e) => {
assertMetaEvent(e, "alice" + i + j, aliceID, i, null, null, [
[aliceID, i],
[bobID, causalityGuaranteed ? 0 : i],
]);
if (j === 1) {
transactionMeta = e.crdtMeta;
} else {
assert.strictEqual(e.crdtMeta, transactionMeta);
}
j++;
if (j > 6 - i) {
i++;
j = 1;
}
});
bob.receive(aliceMessage!);
assert.strictEqual(i, 6);
assert.strictEqual(j, 1);
});
if (!causalityGuaranteed) {
it("delivers transactions when ready", () => {
const bobMessages: Uint8Array[] = [];
for (let i = 1; i <= 5; i++) {
// i messages in this batch/transaction.
for (let j = 1; j <= i; j++) {
bobInspector.sendCRDT("bob" + i + j);
}
bob.commitBatch();
bobMessages.push(bobMessage!);
}
for (let i = 1; i <= 5; i++) {
// Start a new transaction.
alice.receive(bobMessages[i - 1]);
// 6 - i messages in this transaction.
for (let j = 1; j <= 6 - i; j++) {
aliceInspector.sendCRDT("alice" + i + j);
}
}
// Send all of alice's messages as one batch.
alice.commitBatch();
// Now deliver alice's batch to a new user,
// charlie. As bob's messages are delivered,
// charlie should process those together with
// the newly-ready transaction from alice's batch.
// Init charlie.
const charlie = new CRDTApp({
batchingStrategy: new ManualBatchingStrategy(),
causalityGuaranteed,
debugReplicaID: pseudoRandomReplicaID(rng),
});
const charlieID = charlie.runtime.replicaID;
const charlieInspector = charlie.registerCollab(
"inspector",
Pre(MetaInspector)()
);
let charlieEvent: MetaEvent | null = null;
charlieInspector.on("Meta", (e) => {
charlieEvent = e;
});
charlie.load(Optional.empty());
// Receive alice's batch. Nothing is ready yet.
charlie.receive(aliceMessage!);
assert.isNull(charlieEvent);
// Receive bob's messages one by one.
// Each one makes readies one of alice's transactions.
let j = 1;
let turn: "alice" | "bob" | "done" = "alice";
for (let i = 1; i <= 5; i++) {
// We expect to see i messages in the same
// transaction from bob, then 6 - i messages
// in the same transaction from alice.
let transactionMeta!: CRDTMeta;
const off = charlieInspector.on("Meta", (e) => {
if (j === 1) {
transactionMeta = e.crdtMeta;
} else {
assert.strictEqual(e.crdtMeta, transactionMeta);
}
if (turn === "bob") {
assertMetaEvent(e, "bob" + i + j, bobID, i, null, null, [
[bobID, i],
[aliceID, 0],
]);
j++;
if (j > i) {
j = 1;
turn = "alice";
}
} else if (turn === "alice") {
assertMetaEvent(e, "alice" + i + j, aliceID, i, null, null, [
[bobID, i],
[aliceID, i],
]);
j++;
if (j > 6 - i) {
j = 1;
turn = "done";
}
} else {
assert.fail("turn = done");
}
});
charlie.receive(bobMessages[i - 1]);
off();
}
assert.strictEqual(turn, "done");
assert.strictEqual(j, 1);
// Charlie's VC should now be 5, 5.
charlieInspector.sendCRDT("charlie", {
vectorClockEntries: [aliceID, bobID],
});
assertMetaEvent(charlieEvent, "charlie", charlieID, 1, null, null, [
[charlieID, 1],
[aliceID, 5],
[bobID, 5],
]);
});
}
});
});
}
});
// TODOs:
// - Check restriction to causally maximal entries only.
// - Check causality works in general (tested before, but worth checking now that we've changed it to causally maximal entries only).
// - Saving. In particular, causal buffer saving, and
// delivers messages afterwards once ready.
// - Redelivered messages are ignored, even when causalityGuaranteed. In particular, echoing your own messages. | the_stack |
import {promises as fs, constants as fsConstants} from 'fs';
import * as path from 'path';
import test, {after, before} from 'ava';
import sinon from 'sinon';
import {OutputOptions, rollup, RollupOutput} from 'rollup';
import * as sassJs from 'sass';
import sass from '../src/index';
import {SassOptions} from "../src/types";
import {error} from "../src/utils";
const repoRoot = path.join(__dirname, '../'),
tmpDir = path.join(repoRoot, '.tests-output/'),
sassOptions = {
outputStyle: 'compressed',
} as SassOptions,
baseConfig = {
plugins: [
sass({
options: sassOptions,
}),
],
},
generateOptions = {
format: 'es',
} as OutputOptions,
outputOptions = {
format: 'es',
file: path.join(tmpDir, 'bundle.js'),
},
squash = str => str.trim().replace(/[\n\r\f]/g, ''),
reverse = str => str.split('').reverse().join(''),
unwrap = output => output[0].code;
let expectA, expectB, expectC, expectD, expectE;
before(async () => {
const mkDir = () => fs.mkdir(tmpDir);
await fs.rmdir(tmpDir, {recursive: true})
.then(mkDir, mkDir)
.then(() => Promise.all([
'test/assets/expect_a.css',
'test/assets/expect_b.css',
'test/assets/expect_c.css',
'test/assets/expect_d.css',
'test/assets/expect_e.css'
]
.map(xs => fs.readFile(xs).then(buff => buff.toString()))
))
.then(([a, b, c, d, e]) => {
expectA = squash(a);
expectB = squash(b);
expectC = squash(c);
expectD = squash(d);
expectE = squash(e);
});
});
test('should import *.scss and *.sass files', async t => {
const outputBundle = await rollup({
...baseConfig,
input: 'test/fixtures/basic/index.js',
}),
{output} = await outputBundle.generate({
format: 'es',
file: path.join(tmpDir, 'import_scss_and_sass.js')
}),
rslt = squash(unwrap(output));
t.true([expectA, expectB, expectC].every(xs => rslt.includes(xs)));
});
test('should compress the dest CSS', async t => {
const outputBundle = await rollup({
...baseConfig,
input: 'test/fixtures/compress/index.js',
}),
{output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(expectD) > -1);
});
test('should custom importer works', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/custom-importer/index.js',
plugins: [
sass({
options: {
...sassOptions,
importer: [
(url, prev, done) => {
done({
file: url.replace('${name}', 'actual_a'),
});
},
],
}
}),
],
}),
{output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(expectA) > -1);
});
test('should support options.data', async t => {
const jsVars = {
color_red: 'red',
};
const scssVars = Object.keys(jsVars).reduce((prev, key) => `${prev}$${key}:${jsVars[key]};`, '');
const outputBundle = await rollup({
input: 'test/fixtures/data/index.js',
plugins: [
sass({
options: {
...sassOptions,
data: scssVars,
},
}),
],
});
const {output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(expectE) > -1);
});
test('should insert CSS into head tag', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/insert/index.js',
plugins: [
sass({
insert: true,
options: sassOptions,
}),
],
}),
{output} = await outputBundle.generate(generateOptions);
t.true(unwrap(output).includes('___$insertStyle("body{color:red}");'));
t.true(unwrap(output).includes('___$insertStyle("body{color:green}");'));
});
test('should support output as function', async t => {
const outputSpy = sinon.spy(),
file = path.join(tmpDir, 'import_scss_and_sass.js'),
outputBundle = await rollup({
input: 'test/fixtures/output-function/index.js',
plugins: [
sass({
output: outputSpy,
options: sassOptions,
}),
],
}),
expectedSpyArg = squash(`${expectA}${expectB}`);
await outputBundle.write({...outputOptions, file} as OutputOptions);
await fs.readFile(file)
.then(rslt => t.true(squash(rslt.toString()) === ''))
.then(() => t.true(
outputSpy.calledWith(expectedSpyArg),
`\`outputSpy\` should've been called with \`${expectedSpyArg}\`. `+
`Spy called with \`${outputSpy.args[0][0]}\`, other args ` +
`${JSON.stringify(outputSpy.args[0].slice(1))}`
))
.catch(() => t.true(false, `Trouble reading back written file "${file}".`));
});
test('should support output as (non-previously existent) path', async t => {
const outputStylePath = path.join(tmpDir, 'output-path/style.css'),
outputBundle = await rollup({
input: 'test/fixtures/output-path/index.js',
plugins: [
sass({
output: outputStylePath,
options: sassOptions,
}),
],
}),
filePath = path.join(tmpDir, 'support_output_prev-non-exist.js');
await outputBundle.write({...outputOptions, file: filePath} as OutputOptions);
await fs.readFile(filePath)
.then((rslt) => {
t.is(squash(rslt.toString()), '');
})
.then(() => fs.readFile(outputStylePath))
.then((rslt) => {
t.not(squash(rslt.toString()).indexOf(expectA), -1);
t.not(squash(rslt.toString()).indexOf(expectB), -1);
});
});
test('should support output as true', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/output-true/index.js',
plugins: [
sass({
output: true,
options: sassOptions,
}),
],
}),
filePath = path.join(tmpDir, 'support-output-as-true.js');
await outputBundle.write({...outputOptions, file: filePath} as OutputOptions);
await fs.readFile(filePath)
.then(rslt => t.is(squash(rslt.toString()), ''))
.then(() => fs.readFile(filePath.replace('.js', '.css')))
.then(rslt => squash(rslt.toString()))
.then(rslt => {
t.not(rslt.indexOf(expectA), -1);
t.not(rslt.indexOf(expectB), -1);
});
});
test('should processor return as string', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/processor-string/index.js',
plugins: [
sass({
processor: css => reverse(css),
options: sassOptions,
}),
],
}),
{output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(reverse(expectA)) > -1);
t.true(squash(unwrap(output)).indexOf(reverse(expectB)) > -1);
});
test('should processor return as object', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/processor-object/index.js',
plugins: [
sass({
processor(css) {
return {
css,
foo: 'foo',
bar: 'bar',
};
},
options: sassOptions,
}),
],
});
const {output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(expectA) > -1);
t.true(squash(unwrap(output)).indexOf(expectB) > -1);
t.true(squash(unwrap(output)).indexOf('foo') > -1);
t.true(squash(unwrap(output)).indexOf('bar') > -1);
});
test('should processor return as promise', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/processor-promise/index.js',
plugins: [
sass({
processor: (css) => new Promise(resolve =>
setTimeout(() => resolve(css), 100)),
options: sassOptions,
}),
],
}),
{output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(expectA) > -1);
t.true(squash(unwrap(output)).indexOf(expectB) > -1);
});
test('should processor throw error', async t => {
await t.throwsAsync(async () => rollup({
input: 'test/fixtures/processor-error/index.js',
plugins: [
sass({
// @ts-ignore
processor: () => ({}),
options: sassOptions,
}),
],
}), {
message: 'You need to return the styles using the `css` property. See https://github.com/differui/rollup-plugin-sass#processor',
});
});
test('should resolve ~ as node_modules', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/import/index.js',
plugins: [
sass({
options: sassOptions,
}),
],
});
const {output} = await outputBundle.generate(generateOptions);
t.true(squash(unwrap(output)).indexOf(expectA) > -1);
t.true(squash(unwrap(output)).indexOf(expectB) > -1);
t.true(squash(unwrap(output)).indexOf(expectC) > -1);
});
test('should resolve ~ as node_modules and output javascript modules', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/import/index.js',
plugins: [
sass({
options: sassOptions,
}),
],
}),
outputFilePath = path.join(tmpDir, 'import_scss_and_sass.es.js'),
outputFilePath2 = path.join(tmpDir, 'import_scss_and_sass.cjs.js'),
expectedInOutput = `${expectA + expectB + expectC}`,
{output} = await outputBundle.generate(generateOptions),
outputRslt = squash(unwrap(output));
t.true(outputRslt.includes(expectedInOutput),
`${JSON.stringify(outputRslt)}.includes(\`${expectedInOutput}\`)`);
// Test 'es' module output
// ----
await Promise.all([
outputBundle.write({
format: 'es',
file: outputFilePath
})
.then(() => fs.readFile(outputFilePath))
.then(data => {
const rslt = squash(data.toString());
// Ensure content exist in output file
t.true(rslt.includes(expectedInOutput),
`${JSON.stringify(rslt)}.includes(\`${expectedInOutput}\`)`)
}),
// Test 'cjs' module output
// ----
outputBundle.write({
format: 'cjs',
file: outputFilePath2
})
.then(() => fs.readFile(outputFilePath2))
.then(data => {
const rslt = squash(data.toString());
// Ensure content exist in output file
t.true(rslt.includes(expectedInOutput),
`${JSON.stringify(rslt)}.includes(\`${expectedInOutput}\`)`)
})
]);
});
test('should support options.runtime', async t => {
const outputBundle = await rollup({
input: 'test/fixtures/runtime/index.js',
plugins: [
sass({
runtime: sassJs,
options: sassOptions,
}),
],
}),
{output} = await outputBundle.generate(generateOptions),
rslt = squash(unwrap(output));
t.true([expectA, expectB, expectC].every(xs => rslt.includes(xs)));
});
test('When `sourcemap` isn\'t set adjacent source map files should not be output, and ' +
'rollup output chunk shouldn\'t contain a `map` entry', async t => {
const outputFilePath = path.join(tmpDir, 'with-no-adjacent-source-map.js'),
bundle = await rollup({
input: 'test/fixtures/basic/index.js',
plugins: [
sass({
options: sassOptions
}),
],
}),
sourceMapFilePath = `${outputFilePath}.map`;
// Run test
await bundle.write({file: outputFilePath, format: 'esm'})
.then((rslt: RollupOutput): Promise<any> => {
// Check for output chunk
t.true(rslt && rslt.output && !!rslt.output.length, 'output should contain an output chunk');
// Check absence of 'map' entry in chunk
t.true(rslt.output[0].map === null || rslt.output[0].map === undefined,
'output chunk\'s `map` property should not be set. It should equal `null` or `undefined`');
// Check for absence of source map file
return fs.access(sourceMapFilePath, fsConstants.R_OK)
.then(() => t.false(true, `'${sourceMapFilePath}' should not exist.`),
() => t.true(true)
);
});
});
test('When `sourcemap` is set, to `true`, adjacent source map file should be output, and ' +
'rollup output chunk should contain `map` entry', async t => {
const outputFilePath = path.join(tmpDir, 'with-adjacent-source-map.js'),
bundle = await rollup({
input: 'test/fixtures/basic/index.js',
plugins: [
sass({
options: sassOptions
}),
],
}),
sourceMapFilePath = `${outputFilePath}.map`;
await bundle.write({file: outputFilePath, sourcemap: true, format: 'esm'})
.then((rslt: RollupOutput): Promise<any> => {
// Check for output chunk
t.true(rslt && rslt.output && !!rslt.output.length, 'output should contain an output chunk');
// Check for 'map' entry in chunk
t.true(!!rslt.output[0].map, 'rollup output output chunk\'s `map` property should be set');
// Check for source map file
return fs.readFile(sourceMapFilePath)
.then(contents => {
t.true(!!contents.toString(), `${sourceMapFilePath} should have been written.`);
});
});
});
after(async (): Promise<any> => {
return fs.rmdir(tmpDir, {recursive: true})
.catch(error);
}); | the_stack |
import React, {useEffect, useRef, useState} from "react";
import Editor, {useMonaco} from "@monaco-editor/react";
import EventEmitter from "eventemitter3";
import * as monaco from 'monaco-editor'
import {BufferLike, ResponseDataDetailed} from "webdav/web";
import {Uri} from "monaco-editor";
import {isBinaryJs, getEncodingJs} from './textorbinary'
import isEqual from 'lodash/isEqual';
import {FileTreeEntry, SaveFileArgs} from "../typedefs";
type Monaco = typeof monaco
type MonacoTheme = monaco.editor.IStandaloneThemeData
type MonacoEditor = monaco.editor.IStandaloneCodeEditor
type MonacoEditorOptions = monaco.editor.IStandaloneEditorConstructionOptions
type Props = {
emitter: EventEmitter<string | symbol, any>;
}
type loadFileResult = {
filename: string,
response: Buffer | ArrayBuffer | string | ResponseDataDetailed<BufferLike | string>,
}
export const MultiFileEditor = ({emitter}: Props) => {
const editorRef = useRef<MonacoEditor>();
const monacoRef = useRef<Monaco>();
const [getRerender, setRerender] = useState(false);
const [isEditorReady, setIsEditorReady] = useState(false);
const [getCurrentModel, setCurrentModel] = useState<Uri>();
const [getOpenFiles, setOpenFiles] = React.useState<string[]>([])
useEffect(() => {
const handleFileLoaded = (data: loadFileResult) => {
const qbuffer = Buffer.from(data.response);
if (isBinaryJs(qbuffer)) {
alert("file is binary so cannot be edited")
return
}
const encoding = getEncodingJs(qbuffer)
// The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
var dataView = new DataView(data.response as ArrayBuffer);
// The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
var decoder = new TextDecoder(encoding);
var decodedString = decoder.decode(dataView);
setCurrentModel(monaco.Uri.file(data.filename))
// How to dynamically set language according to file extension in monaco editor?
// https://stackoverflow.com/a/57074528/627492
if (!!monacoRef.current && !!monacoRef.current.editor) {
monacoRef.current.editor.createModel(
decodedString,
undefined, // language
monaco.Uri.file(data.filename) // uri
)
setCurrentModel(monaco.Uri.file(data.filename))
}
}
emitter.addListener("ON_FILE_LOADED", handleFileLoaded)
return () => {
emitter.removeListener("ON_FILE_LOADED", handleFileLoaded)
}
}, [emitter])
function handleEditorWillMount(monaco: Monaco) {
// here is the monaco instance
// do something before editor is mounted
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
}
function handleEditorDidMount(editor: MonacoEditor, monaco: Monaco) {
// here is another way to get monaco instance
// you can also store it in `useRef` for further usage
monacoRef.current = monaco;
editorRef.current = editor;
// clear existing models
monacoRef.current.editor.getModels().forEach(model => model.dispose());
//monacoRef.current.editor.createModel(indexMD, "markdown", "urn:index.md");
//monacoRef.current.editor.createModel(indexCSS, "css", "urn:index.css");
monacoRef.current.languages.typescript.javascriptDefaults.setEagerModelSync(
true
);
setIsEditorReady(true);
}
useEffect(() => {
const handleOnSelectFile = (filename: string | undefined) => {
alert("dead code?")
if (filename === undefined) {
// no file is selected - this happens for example when a file is deleted
return
}
if (monacoRef.current === undefined) return
// if there's no current model then load
if (getCurrentModel === undefined) {
emitter.emit("DO_LOAD_FILE", filename)
return
}
const found = monacoRef.current.editor.getModels().find(
(model) => {
//return model.uri.path === getSelectedTab
return model.uri.path === filename
}
)
// if this file is already loaded in the editor, set as selected file else load file
if (found === undefined) {
emitter.emit("DO_LOAD_FILE", filename)
} else {
//setSelectedTab(filename)
setCurrentModel(monaco.Uri.file(filename))
}
}
emitter.addListener("ON_SELECT_FILE", handleOnSelectFile)
return () => {
emitter.removeListener("ON_SELECT_FILE", handleOnSelectFile)
}
}, [emitter, getCurrentModel])
useEffect(() => {
// ensure getCurrentModel is valid
// set the current model/tab to the first model
if (monacoRef.current === undefined) return
// if undefined, set to first model
if (getCurrentModel === undefined) {
monacoRef.current.editor.getModels().forEach((model) => {
setCurrentModel(model.uri)
})
return
}
// check if getCurrentModel is in the models
const found = monacoRef.current.editor.getModels().find(
(model) => {
return model.uri.path === getCurrentModel.path
}
)
// if not found then getCurrentModel is no longer valid, set it to the first model
if (!found) {
monacoRef.current.editor.getModels().forEach((model) => {
setCurrentModel(model.uri)
})
}
}, [getCurrentModel])
useEffect(() => {
// when a file is deleted we close any tab that contains that file
// when a directory is deleted we close any tab that contains a file below that directory
const closeTabsOfDeletedFiles = async (fileTreeEntry: FileTreeEntry) => {
if (monacoRef.current === undefined) return
// close tabs of the file or the directory
monacoRef.current.editor.getModels().forEach((model) => {
if (model.uri.path === fileTreeEntry.filePath) {
if (getCurrentModel !== undefined) {
if (model.uri.path === getCurrentModel.path) {
setCurrentModel(undefined)
}
}
model.dispose()
}
if (fileTreeEntry.type === "directory") {
if (model.uri.path.startsWith(`${fileTreeEntry.filePath}/`)) {
/* if (getCurrentModel !== undefined) {
if (model.uri.path === getCurrentModel.path) {
setCurrentModel(undefined)
}
}*/
model.dispose()
}
}
setRerender((prev) => !prev)
});
}
emitter.addListener("ON_FILE_OR_DIRECTORY_DELETED", closeTabsOfDeletedFiles)
return () => {
emitter.removeListener("ON_FILE_OR_DIRECTORY_DELETED", closeTabsOfDeletedFiles)
}
}, [emitter, getCurrentModel])
useEffect(() => {
if (getCurrentModel === undefined) return
if (!isEditorReady) return
if (editorRef.current === undefined) return
if (monacoRef.current === undefined) return
editorRef.current.setModel(monacoRef.current.editor.getModel(getCurrentModel))
}, [isEditorReady, getCurrentModel]);
let openFiles: string[] = [];
if (!!monacoRef.current) {
for (const item of monacoRef.current.editor.getModels()) {
openFiles.push(item.uri.path)
}
}
useEffect(() => {
if (getCurrentModel === undefined) return
if (!isEditorReady) return
if (editorRef.current === undefined) return
if (monacoRef.current === undefined) return
// update parent component state holding open files
setOpenFiles((prev) => {
if (!isEqual(prev, openFiles)) {
emitter.emit("ON_OPEN_FILES_CHANGED", openFiles)
return openFiles
} else {
return prev
}
})
}, [setOpenFiles, getOpenFiles, openFiles, emitter]);
const doSave = () => {
if (!!getCurrentModel) {
if (!!monacoRef.current) {
if (!!monacoRef.current.editor) {
const model = monacoRef.current.editor.getModel(getCurrentModel)
if (!!model) {
const args: SaveFileArgs = {
filepath: getCurrentModel.path,
data: model.getValue(),
}
emitter.emit("DO_SAVE_FILE", args)
console.log("done")
}
}
}
}
}
const mouseDownHandler = (e: React.MouseEvent<HTMLSpanElement, MouseEvent>, itemUriPath: string) => {
// handle middle mouse button click on tab to close it.
if (e.button === 1) {
closeTab(e, itemUriPath)
}
}
const closeTab = (e: React.MouseEvent<HTMLSpanElement, MouseEvent>, itemUriPath: string) => {
// if we don't stop propagation then the click event goes to the file and sets it as the currentModel
e.stopPropagation()
if (monacoRef.current === undefined) return
if (getCurrentModel !== undefined) {
if (itemUriPath === getCurrentModel.path) {
setCurrentModel(undefined)
}
}
monacoRef.current.editor.getModels().forEach((model) => {
console.log("model")
console.log(model)
if (model.uri.path === itemUriPath) {
model.dispose()
}
setRerender((prev) => !prev)
});
}
const Tabs = () => {
let rv = []
if (monacoRef.current === undefined) return null
if (getCurrentModel === undefined) return null
for (const item of monacoRef.current.editor.getModels()) {
if (item.uri !== undefined) {
// these three lines determine if the same file name with a different path is open
// if so, then we display the3 full path. if not, then we display only the filename on the tab.
let filenameToDisplay: string = item.uri.path.split("/").pop() ?? ""
const found = getOpenFiles.filter((filename) => filenameToDisplay === filename.split("/").pop())
if (found.length > 1) {
filenameToDisplay = item.uri.path
}
rv.push(
<li key={item.uri.toString()}
className="nav-item"
style={{
"borderRadius": 0,
"borderTop": `4px solid ${(item.uri.path === getCurrentModel.path) ? " #5bc0de" : " lightgray"}`,
"marginRight": "10px",
"marginTop": "10px",
}}>
<a className={`nav-link ${(item.uri.path === getCurrentModel.path) && "active"}`}
style={{"borderRadius": 0}}
data-bs-toggle="tab"
onMouseDown={(e) => mouseDownHandler(e, item.uri.path)}
onClick={() => setCurrentModel(monaco.Uri.file(item.uri.path))}
>
{filenameToDisplay}
<span
className="close"
style={{
"marginLeft": "24px",
"marginRight": "8px",
"fontWeight": "bolder",
"color": "gray",
}}
onClick={(e) => closeTab(e, item.uri.path)}
onMouseOver={(e) => e.currentTarget.style.color = "white"}
onMouseOut={(e) => e.currentTarget.style.color = "gray"}
>X</span>
</a>
</li>
)
}
}
return (
<ul className="nav nav-tabs p2" style={{"paddingLeft": "10px"}}>
{rv}
</ul>
)
}
console.log("getCurrentModel")
console.log(getCurrentModel)
return (
<div>
{(getCurrentModel) &&
<>
<style>
{`
.smallbutton {
background-color: #444857;
border-radius: 2px;
border-style: dotted;
border-width: 1px;
color: #cccccc;
cursor: pointer;
display: inline-block;
font-size: 1em;
font-weight: normal !important;
line-height: 1.2;
margin: 0 3px 0 0;
padding: 2px 7px;
position: relative;
text-align: center;
text-decoration: none !important;
text-overflow: ellipsis;
text-shadow: none;
white-space: nowrap;
}
.smallbutton:hover {
background-color: #5c5e73;
color: white;
}
`}
</style>
<div>
<Tabs/>
</div>
{!!getCurrentModel &&
<div style={{
"backgroundColor": "#343539",
"padding": "4px",
"paddingLeft": "10px",
"color": "white",
}}>
<button
style={{
"lineHeight": 1,
}}
onClick={doSave}
className="btn btn-success">Save
</button>
{getCurrentModel.path}
</div>
}
</>
}
<Editor
options={{"fontSize": 16}}
height="80vh"
theme="vs-dark"
beforeMount={handleEditorWillMount}
onMount={handleEditorDidMount}/>
</div>
);
} | the_stack |
import {Component, OnInit, OnDestroy} from '@angular/core';
import {ICourse} from '../../../../../../../shared/models/ICourse';
import {ILecture} from '../../../../../../../shared/models/ILecture';
import {ILectureCreate} from '../../../../../../../shared/models/ILectureCreate';
import {CourseService, LectureService, NotificationService} from '../../../shared/services/data.service';
import {ShowProgressService} from 'app/shared/services/show-progress.service';
import {DialogService} from '../../../shared/services/dialog.service';
import {UserService} from '../../../shared/services/user.service';
import {MatSnackBar} from '@angular/material';
import {DragulaService} from 'ng2-dragula';
import {ActivatedRoute, Router} from '@angular/router';
import {DataSharingService} from '../../../shared/services/data-sharing.service';
import {Subject} from 'rxjs/Subject';
@Component({
selector: 'app-course-manage-content',
templateUrl: './course-manage-content.component.html',
styleUrls: ['./course-manage-content.component.scss']
})
export class CourseManageContentComponent implements OnInit, OnDestroy {
course: ICourse;
fabOpen = false;
onCloseAllForms = new Subject();
onReloadCourse = new Subject();
constructor(private route: ActivatedRoute,
private router: Router,
private lectureService: LectureService,
private courseService: CourseService,
private showProgress: ShowProgressService,
private snackBar: MatSnackBar,
private dialogService: DialogService,
private dragulaService: DragulaService,
public userService: UserService,
private dataSharingService: DataSharingService,
private notificationService: NotificationService) {
// setup subjects
this.dataSharingService.setDataForKey('onCloseAllForms', this.onCloseAllForms);
this.onCloseAllForms.asObservable().subscribe(() => this.closeAllForms());
this.dataSharingService.setDataForKey('onReloadCourse', this.onReloadCourse);
this.onReloadCourse.asObservable().subscribe(async (resolve: Function) => {
await this.reloadCourse();
return resolve();
});
// setup course object
const course = this.dataSharingService.getDataForKey('course');
if (course) {
this.course = course;
this.setOpenedLectureAndUnit();
this.setAddLectureIfPresent();
this.setAddUnitIfPresent();
} else {
this.getCourse();
}
}
ngOnInit() {
// Make items only draggable by dragging the handle
this.dragulaService.setOptions('lectures', {
moves: (el, container, handle) => {
return handle.classList.contains('lecture-drag-handle');
}
});
this.dragulaService.setOptions('units', {
moves: (el, container, handle) => {
return handle.classList.contains('unit-drag-handle');
}
});
this.dragulaService.dropModel.subscribe((value) => {
const [bagName, element, target, container] = value;
switch (bagName) {
case 'lectures':
this.updateLectureOrder();
break;
case 'units':
// Update current lecture
this.updateUnitOrder();
// When dragging to another lecture we need to update the other lecture too
if (target.dataset.lectureId) {
this.updateUnitOrder(target.dataset.lectureId);
}
break;
}
});
}
ngOnDestroy() {
this.dragulaService.destroy('lectures');
this.dragulaService.destroy('units');
}
isInMode(lecture, create) {
return this.dataSharingService.getDataForKey(`${lecture}-${create}-mode`) || false;
}
isLectureOpen() {
return this.dataSharingService.getDataForKey('openLectureId') !== null;
}
getCourse() {
this.route.parent.parent.params.subscribe(params => {
const courseId = params['id'];
this.courseService.readCourseToEdit(courseId).then(
(course: ICourse) => {
this.course = course;
this.dataSharingService.setDataForKey('course', this.course);
this.setOpenedLectureAndUnit();
this.setAddLectureIfPresent();
this.setAddUnitIfPresent();
}, (error) => {
this.snackBar.open('Couldn\'t load Course-Item', '', {duration: 3000});
});
});
}
setOpenedLectureAndUnit() {
this.route.params.subscribe((params) => {
const lectureId = params['lecture'];
if (!lectureId) {
this.dataSharingService.setDataForKey('openLectureId', null);
return;
}
const lecture = this.course.lectures.find(lec => lec._id === lectureId);
if (!lecture) {
// invalid lecture, discard and navigate to root
return this.route.url.subscribe(segments => {
const path = segments.map(() => '../').join('') || '';
this.router.navigate([path], {relativeTo: this.route});
});
}
this.dataSharingService.setDataForKey('openLectureId', lecture._id);
const unitId = params['unit'];
if (!unitId) {
this.dataSharingService.setDataForKey('unit-edit-mode', false);
this.dataSharingService.setDataForKey('unit-edit-element', null);
return;
}
const openUnit = lecture.units.find(unit => unit._id === unitId);
if (!openUnit) {
// invalid unit, discard and navigate to lecture
return this.route.url.subscribe(segments => {
let path = segments.map(() => '../').join('') || '';
path += `lecture/${lectureId}`;
this.router.navigate([path], {relativeTo: this.route});
});
}
this.dataSharingService.setDataForKey('unit-edit-mode', true);
this.dataSharingService.setDataForKey('unit-edit-element', openUnit);
});
}
setAddLectureIfPresent() {
this.route.url.subscribe(segments => {
if (!segments.length) {
this.dataSharingService.setDataForKey('lecture-create-mode', false);
return;
}
if (segments.length === 2 && segments[0].path === 'lecture' && segments[1].path === 'add') {
this.dataSharingService.setDataForKey('lecture-create-mode', true);
}
});
}
setAddUnitIfPresent() {
this.route.url.subscribe(segments => {
if (!segments.length) {
this.dataSharingService.setDataForKey('unit-create-mode', false);
this.dataSharingService.setDataForKey('unit-create-type', null);
return;
}
const url = segments.map(segment => segment.path).join('/');
if (url.indexOf('/unit/add/') !== -1) {
const type = segments[segments.length - 1].path; // last segment is type
this.dataSharingService.setDataForKey('unit-create-mode', true);
this.dataSharingService.setDataForKey('unit-create-type', type);
}
});
}
updateLectureOrder() {
this.courseService.updateItem({
'_id': this.course._id,
'lectures': this.course.lectures.map((lecture) => lecture._id)
});
}
updateUnitOrder(id: string = null) {
if (!id) {
id = this.dataSharingService.getDataForKey('openLectureId');
}
const lecture = this.course.lectures.find(l => l._id === id);
if (!lecture) {
return;
}
this.lectureService.updateItem({
'_id': lecture._id,
'units': lecture.units.map((unit) => unit._id)
});
}
async createLecture({name, description}: {name: string, description: string}) {
const newLecture = await this.lectureService.createItem<ILectureCreate, ILecture>({
courseId: this.course._id, name, description
});
this.dataSharingService.setDataForKey('lecture-create-mode', false);
await this.notificationService.createItem({
targetId: newLecture._id,
targetType: 'lecture',
text: 'Course ' + this.course.name + ' has a new lecture.'
});
await this.reloadCourse();
}
async reloadCourse() {
try {
this.course = await this.courseService.readCourseToEdit(this.course._id);
this.dataSharingService.setDataForKey('course', this.course);
} catch (err) {
this.snackBar.open('Couldn\'t reload Course', '', {duration: 3000});
}
return this.showProgress.toggleLoadingGlobal(false);
}
onImportLecture = () => {
this.dialogService
.chooseFile('Choose a lecture.json to import',
'/api/import/lecture/' + this.course._id)
.subscribe(res => {
if (res.success) {
this.reloadCourse();
// This does not work as expected
this.dataSharingService.setDataForKey('unit-edit-element', res.result);
this.dataSharingService.setDataForKey('unit-edit-mode', true);
this.snackBar.open('Lecture successfully imported', '', {duration: 3000});
} else if (res.result) {
this.snackBar.open(res.error.message, '', {duration: 3000});
}
});
}
onAddLecture() {
this.onCloseAllForms.next();
this.dataSharingService.setDataForKey('openLectureId', null);
this.dataSharingService.setDataForKey('lecture-create-mode', true);
this.route.url.subscribe(segments => {
let path = segments.map(() => '../').join('') || '';
path += 'lecture/add';
this.router.navigate([path], {relativeTo: this.route});
});
}
onAddUnit = (type: string) => {
this.onCloseAllForms.next();
this.dataSharingService.setDataForKey('unit-create-mode', true);
this.dataSharingService.setDataForKey('unit-create-type', type);
const lectureId = this.dataSharingService.getDataForKey('openLectureId');
this.route.url.subscribe(segments => {
let path = segments.map(() => '../').join('') || '';
path += `lecture/${lectureId}/unit/add/${type}`;
this.router.navigate([path], {relativeTo: this.route});
});
}
onImportUnit = () => {
const openLectureId = this.dataSharingService.getDataForKey('openLectureId');
this.dialogService
.chooseFile('Choose a unit.json to import',
'/api/import/unit/' + this.course._id + '/' + openLectureId)
.subscribe(async res => {
if (res.success) {
this.reloadCourse();
// This does not work as expected
const lecture = res.result;
this.dataSharingService.setDataForKey('openLectureId', lecture._id);
this.dataSharingService.setDataForKey('lecture-edit-mode', true);
this.snackBar.open('Unit successfully imported', '', {duration: 3000});
} else if (res.result) {
this.snackBar.open(res.error.message, '', {duration: 3000});
}
});
}
closeFab = () => {
this.fabOpen = false;
}
onFabClick = () => {
this.fabOpen = !this.fabOpen;
}
closeAddLecture = () => {
this.dataSharingService.setDataForKey('lecture-create-mode', false);
}
private closeAllForms() {
this.closeFab();
this.closeAddLecture();
}
} | the_stack |
import { normalizePath, utils } from '@neo-one/utils';
import _ from 'lodash';
import { currentDirectory } from './constants';
import { FileSystem } from './filesystem';
// tslint:disable
interface FileSystemEntries {
readonly files: readonly string[];
readonly directories: readonly string[];
}
interface WildcardMatcher {
singleAsteriskRegexFragment: string;
doubleAsteriskRegexFragment: string;
replaceWildcardCharacter: (match: string) => string;
}
function replaceWildcardCharacter(match: string, singleAsteriskRegexFragment: string) {
return match === '*' ? singleAsteriskRegexFragment : match === '?' ? '[^/]' : '\\' + match;
}
const commonPackageFolders: readonly string[] = ['node_modules', 'bower_components', 'jspm_packages'];
const implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join('|')})(/|$))`;
const filesMatcher: WildcardMatcher = {
/**
* Matches any single directory segment unless it is the last segment and a .min.js file
* Breakdown:
* [^./] # matches everything up to the first . character (excluding directory separators)
* (\\.(?!min\\.js$))? # matches . characters but not if they are part of the .min.js file extension
*/
singleAsteriskRegexFragment: '([^./]|(\\.(?!min\\.js$))?)*',
/**
* Regex for the ** wildcard. Matches any number of subdirectories. When used for including
* files or directories, does not match subdirectories that start with a . character
*/
doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`,
replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment),
};
const directoriesMatcher: WildcardMatcher = {
singleAsteriskRegexFragment: '[^/]*',
/**
* Regex for the ** wildcard. Matches any number of subdirectories. When used for including
* files or directories, does not match subdirectories that start with a . character
*/
doubleAsteriskRegexFragment: `(/${implicitExcludePathRegexPattern}[^/.][^/]*)*?`,
replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment),
};
const excludeMatcher: WildcardMatcher = {
singleAsteriskRegexFragment: '[^/]*',
doubleAsteriskRegexFragment: '(/.+?)?',
replaceWildcardCharacter: (match) => replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment),
};
const wildcardMatchers = {
files: filesMatcher,
directories: directoriesMatcher,
exclude: excludeMatcher,
};
const directorySeparator = '/';
const altDirectorySeparator = '\\';
const urlSchemeSeparator = '://';
const backslashRegExp = /\\/g;
/**
* Normalize path separators.
*/
function normalizeSlashes(path: string): string {
return path.replace(backslashRegExp, directorySeparator);
}
function isVolumeCharacter(charCode: number) {
return (
(charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) ||
(charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z)
);
}
function getEncodedRootLength(path: string): number {
if (!path) return 0;
const ch0 = path.charCodeAt(0);
// POSIX or UNC
if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) {
if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\")
const p1 = path.indexOf(ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2);
if (p1 < 0) return path.length; // UNC: "//server" or "\\server"
return p1 + 1; // UNC: "//server/" or "\\server\"
}
// DOS
if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) {
const ch2 = path.charCodeAt(2);
if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\"
if (path.length === 2) return 2; // DOS: "c:" (but not "c:d")
}
// URL
const schemeEnd = path.indexOf(urlSchemeSeparator);
if (schemeEnd !== -1) {
const authorityStart = schemeEnd + urlSchemeSeparator.length;
const authorityEnd = path.indexOf(directorySeparator, authorityStart);
if (authorityEnd !== -1) {
// URL: "file:///", "file://server/", "file://server/path"
// For local "file" URLs, include the leading DOS volume (if present).
// Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
// special case interpreted as "the machine from which the URL is being interpreted".
const scheme = path.slice(0, schemeEnd);
const authority = path.slice(authorityStart, authorityEnd);
if (
scheme === 'file' &&
(authority === '' || authority === 'localhost') &&
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))
) {
const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
if (volumeSeparatorEnd !== -1) {
if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) {
// URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
return ~(volumeSeparatorEnd + 1);
}
if (volumeSeparatorEnd === path.length) {
// URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
// but not "file:///c:d" or "file:///c%3ad"
return ~volumeSeparatorEnd;
}
}
}
return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
return ~path.length; // URL: "file://server", "http://server"
}
// relative
return 0;
}
function getFileUrlVolumeSeparatorEnd(url: string, start: number) {
const ch0 = url.charCodeAt(start);
if (ch0 === CharacterCodes.colon) return start + 1;
if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) {
const ch2 = url.charCodeAt(start + 2);
if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3;
}
return -1;
}
export function combinePaths(path: string, ...paths: (string | undefined)[]): string {
if (path) path = normalizeSlashes(path);
for (let relativePath of paths) {
if (!relativePath) continue;
relativePath = normalizeSlashes(relativePath);
if (!path || getRootLength(relativePath) !== 0) {
path = relativePath;
} else {
path = ensureTrailingDirectorySeparator(path) + relativePath;
}
}
return path;
}
function ensureTrailingDirectorySeparator(path: string): string;
function ensureTrailingDirectorySeparator(path: string) {
if (!hasTrailingDirectorySeparator(path)) {
return path + directorySeparator;
}
return path;
}
enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 0x7f,
lineFeed = 0x0a, // \n
carriageReturn = 0x0d, // \r
lineSeparator = 0x2028,
paragraphSeparator = 0x2029,
nextLine = 0x0085,
// Unicode 3.0 space characters
space = 0x0020, // " "
nonBreakingSpace = 0x00a0, //
enQuad = 0x2000,
emQuad = 0x2001,
enSpace = 0x2002,
emSpace = 0x2003,
threePerEmSpace = 0x2004,
fourPerEmSpace = 0x2005,
sixPerEmSpace = 0x2006,
figureSpace = 0x2007,
punctuationSpace = 0x2008,
thinSpace = 0x2009,
hairSpace = 0x200a,
zeroWidthSpace = 0x200b,
narrowNoBreakSpace = 0x202f,
ideographicSpace = 0x3000,
mathematicalSpace = 0x205f,
ogham = 0x1680,
_ = 0x5f,
$ = 0x24,
_0 = 0x30,
_1 = 0x31,
_2 = 0x32,
_3 = 0x33,
_4 = 0x34,
_5 = 0x35,
_6 = 0x36,
_7 = 0x37,
_8 = 0x38,
_9 = 0x39,
a = 0x61,
b = 0x62,
c = 0x63,
d = 0x64,
e = 0x65,
f = 0x66,
g = 0x67,
h = 0x68,
i = 0x69,
j = 0x6a,
k = 0x6b,
l = 0x6c,
m = 0x6d,
n = 0x6e,
o = 0x6f,
p = 0x70,
q = 0x71,
r = 0x72,
s = 0x73,
t = 0x74,
u = 0x75,
v = 0x76,
w = 0x77,
x = 0x78,
y = 0x79,
z = 0x7a,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4a,
K = 0x4b,
L = 0x4c,
M = 0x4d,
N = 0x4e,
O = 0x4f,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5a,
ampersand = 0x26, // &
asterisk = 0x2a, // *
at = 0x40, // @
backslash = 0x5c, // \
backtick = 0x60, // `
bar = 0x7c, // |
caret = 0x5e, // ^
closeBrace = 0x7d, // }
closeBracket = 0x5d, // ]
closeParen = 0x29, // )
colon = 0x3a, // :
comma = 0x2c, // ,
dot = 0x2e, // .
doubleQuote = 0x22, // "
equals = 0x3d, // =
exclamation = 0x21, // !
greaterThan = 0x3e, // >
hash = 0x23, // #
lessThan = 0x3c, // <
minus = 0x2d, // -
openBrace = 0x7b, // {
openBracket = 0x5b, // [
openParen = 0x28, // (
percent = 0x25, // %
plus = 0x2b, // +
question = 0x3f, // ?
semicolon = 0x3b, // ;
singleQuote = 0x27, // '
slash = 0x2f, // /
tilde = 0x7e, // ~
backspace = 0x08, // \b
formFeed = 0x0c, // \f
byteOrderMark = 0xfeff,
tab = 0x09, // \t
verticalTab = 0x0b, // \v
}
function hasTrailingDirectorySeparator(path: string) {
if (path.length === 0) return false;
const ch = path.charCodeAt(path.length - 1);
return ch === CharacterCodes.slash || ch === CharacterCodes.backslash;
}
function getRootLength(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength < 0 ? ~rootLength : rootLength;
}
function getRegularExpressionForWildcard(
specs: readonly string[] | undefined,
basePath: string,
usage: 'files' | 'directories' | 'exclude',
): string | undefined {
const patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
if (!patterns || !patterns.length) {
return undefined;
}
const pattern = patterns.map((pattern) => `(${pattern})`).join('|');
// If excluding, match "foo/bar/baz...", but if including, only allow "foo".
const terminator = usage === 'exclude' ? '($|/)' : '$';
return `^(${pattern})${terminator}`;
}
function getRegularExpressionsForWildcards(
specs: readonly string[] | undefined,
basePath: string,
usage: 'files' | 'directories' | 'exclude',
): string[] | undefined {
if (specs === undefined || specs.length === 0) {
return undefined;
}
return _.flatMap(
specs,
(spec) => spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]),
).filter(utils.notNull);
}
function reducePathComponents(components: readonly string[]) {
if (!_.some(components)) return [];
const reduced = [components[0]];
for (let i = 1; i < components.length; i++) {
const component = components[i];
if (!component) continue;
if (component === '.') continue;
if (component === '..') {
if (reduced.length > 1) {
if (reduced[reduced.length - 1] !== '..') {
reduced.pop();
continue;
}
} else if (reduced[0]) continue;
}
reduced.push(component);
}
return reduced;
}
function getPathComponents(path: string, currentDirectory = '') {
path = combinePaths(currentDirectory, path);
const rootLength = getRootLength(path);
return pathComponents(path, rootLength);
}
function pathComponents(path: string, rootLength: number) {
const root = path.substring(0, rootLength);
const rest = path.substring(rootLength).split(directorySeparator);
if (rest.length && !_.last(rest)) rest.pop();
return [root, ...rest];
}
function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
export function removeTrailingDirectorySeparator(path: string): string;
export function removeTrailingDirectorySeparator(path: string) {
if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
function isImplicitGlob(lastPathComponent: string): boolean {
return !/[.*?]/.test(lastPathComponent);
}
const reservedCharacterPattern = /[^\w\s\/]/g;
function getSubPatternFromSpec(
spec: string,
basePath: string,
usage: 'files' | 'directories' | 'exclude',
{ singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter }: WildcardMatcher,
): string | undefined {
let subpattern = '';
let hasWrittenComponent = false;
const components = getNormalizedPathComponents(spec, basePath);
const lastComponent = _.last(components);
if (lastComponent === undefined) {
return undefined;
}
if (usage !== 'exclude' && lastComponent === '**') {
return undefined;
}
// getNormalizedPathComponents includes the separator for the root component.
// We need to remove to create our regex correctly.
components[0] = removeTrailingDirectorySeparator(components[0]);
if (isImplicitGlob(lastComponent)) {
components.push('**', '*');
}
let optionalCount = 0;
for (let component of components) {
if (component === '**') {
subpattern += doubleAsteriskRegexFragment;
} else {
if (usage === 'directories') {
subpattern += '(';
optionalCount++;
}
if (hasWrittenComponent) {
subpattern += directorySeparator;
}
if (usage !== 'exclude') {
let componentPattern = '';
// The * and ? wildcards should not match directories or files that start with . if they
// appear first in a component. Dotted directories and files can be included explicitly
// like so: **/.*/.*
if (component.charCodeAt(0) === CharacterCodes.asterisk) {
componentPattern += '([^./]' + singleAsteriskRegexFragment + ')?';
component = component.substr(1);
} else if (component.charCodeAt(0) === CharacterCodes.question) {
componentPattern += '[^./]';
component = component.substr(1);
}
componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
// Patterns should not include subfolders like node_modules unless they are
// explicitly included as part of the path.
//
// As an optimization, if the component pattern is the same as the component,
// then there definitely were no wildcard characters and we do not need to
// add the exclusion pattern.
if (componentPattern !== component) {
subpattern += implicitExcludePathRegexPattern;
}
subpattern += componentPattern;
} else {
subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
}
}
hasWrittenComponent = true;
}
while (optionalCount > 0) {
subpattern += ')?';
optionalCount--;
}
return subpattern;
}
interface FileMatcherPatterns {
/** One pattern for each "include" spec. */
includeFilePatterns: readonly string[] | undefined;
/** One pattern matching one of any of the "include" specs. */
includeFilePattern: string | undefined;
includeDirectoryPattern: string | undefined;
excludePattern: string | undefined;
basePaths: readonly string[];
}
function getFileMatcherPatterns(
pathIn: string,
excludes: readonly string[] | undefined,
includes: readonly string[] | undefined,
useCaseSensitiveFileNames: boolean,
currentDirectoryIn: string,
): FileMatcherPatterns {
const path = normalizePath(pathIn);
const currentDirectory = normalizePath(currentDirectoryIn);
const absolutePath = combinePaths(currentDirectory, path);
const includeFilePatterns = getRegularExpressionsForWildcards(includes, absolutePath, 'files');
return {
includeFilePatterns:
includeFilePatterns === undefined ? undefined : _.map(includeFilePatterns, (pattern) => `^${pattern}$`),
includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, 'files'),
includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, 'directories'),
excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, 'exclude'),
basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames),
};
}
function isRootedDiskPath(path: string) {
return getEncodedRootLength(path) > 0;
}
function hasExtension(fileName: string): boolean {
return getBaseFileName(fileName).includes('.');
}
function getAnyExtensionFromPathWorker(
path: string,
extensions: string | readonly string[],
stringEqualityComparer: (a: string, b: string) => boolean,
) {
if (typeof extensions === 'string') extensions = [extensions];
for (let extension of extensions) {
if (!extension.startsWith('.')) extension = '.' + extension;
if (path.length >= extension.length && path.charAt(path.length - extension.length) === '.') {
const pathExtension = path.slice(path.length - extension.length);
if (stringEqualityComparer(pathExtension, extension)) {
return pathExtension;
}
}
}
return '';
}
/**
* Compare the equality of two strings using a case-sensitive ordinal comparison.
*
* Case-sensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point after applying `toUpperCase` to each string. We always map both
* strings to their upper-case form as some unicode characters do not properly round-trip to
* lowercase (such as `ẞ` (German sharp capital s)).
*/
function equateStringsCaseInsensitive(a: string, b: string) {
return a === b || (a !== undefined && b !== undefined && a.toUpperCase() === b.toUpperCase());
}
/**
* Compare the equality of two strings using a case-sensitive ordinal comparison.
*
* Case-sensitive comparisons compare both strings one code-point at a time using the
* integer value of each code-point.
*/
function equateStringsCaseSensitive(a: string, b: string) {
return equateValues(a, b);
}
function equateValues<T>(a: T, b: T) {
return a === b;
}
function getAnyExtensionFromPath(path: string): string;
function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string {
// Retrieves any string from the final "." onwards from a base file name.
// Unlike extensionFromPath, which throws an exception on unrecognized extensions.
if (extensions) {
return getAnyExtensionFromPathWorker(
path,
extensions,
ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive,
);
}
const baseFileName = getBaseFileName(path);
const extensionIndex = baseFileName.lastIndexOf('.');
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
return '';
}
export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
path = normalizeSlashes(path);
// if the path provided is itself the root, then it has not file name.
const rootLength = getRootLength(path);
if (rootLength === path.length) return '';
// return the trailing portion of the path starting after the last (non-terminal) directory
// separator but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1));
const extension =
extensions !== undefined && ignoreCase !== undefined
? getAnyExtensionFromPath(name, extensions, ignoreCase)
: undefined;
return extension ? name.slice(0, name.length - extension.length) : name;
}
function getIncludeBasePath(absolute: string): string {
let wildcardOffset = absolute.indexOf('*');
if (wildcardOffset < 0) {
wildcardOffset = absolute.indexOf('?');
}
if (wildcardOffset < 0) {
// No "*" or "?" in the path
return !hasExtension(absolute) ? absolute : removeTrailingDirectorySeparator(getDirectoryPath(absolute));
}
return absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset));
}
export function getDirectoryPath(path: string): string {
path = normalizeSlashes(path);
// If the path provided is itself the root, then return it.
const rootLength = getRootLength(path);
if (rootLength === path.length) return path;
// return the leading portion of the path up to the last (non-terminal) directory separator
// but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator)));
}
enum Comparison {
LessThan = -1,
EqualTo = 0,
GreaterThan = 1,
}
export function compareStringsCaseInsensitive(a: string, b: string) {
if (a === b) return Comparison.EqualTo;
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
a = a.toUpperCase();
b = b.toUpperCase();
return a < b ? Comparison.LessThan : a > b ? Comparison.GreaterThan : Comparison.EqualTo;
}
/**
* Compare two strings using a case-sensitive ordinal comparison.
*
* Ordinal comparisons are based on the difference between the unicode code points of both
* strings. Characters with multiple unicode representations are considered unequal. Ordinal
* comparisons provide predictable ordering, but place "a" after "B".
*
* Case-sensitive comparisons compare both strings one code-point at a time using the integer
* value of each code-point.
*/
export function compareStringsCaseSensitive(a: string | undefined, b: string | undefined): Comparison {
return compareComparableValues(a, b);
}
function compareComparableValues(a: string | undefined, b: string | undefined): Comparison;
function compareComparableValues(a: number | undefined, b: number | undefined): Comparison;
function compareComparableValues(a: string | number | undefined, b: string | number | undefined) {
return a === b
? Comparison.EqualTo
: a === undefined
? Comparison.LessThan
: b === undefined
? Comparison.GreaterThan
: a < b
? Comparison.LessThan
: Comparison.GreaterThan;
}
function getStringComparer(ignoreCase?: boolean) {
return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
}
export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === 'string') {
parent = combinePaths(currentDirectory, parent);
child = combinePaths(currentDirectory, child);
} else if (typeof currentDirectory === 'boolean') {
ignoreCase = currentDirectory;
}
if (parent === undefined || child === undefined) return false;
if (parent === child) return true;
const parentComponents = reducePathComponents(getPathComponents(parent));
const childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (let i = 0; i < parentComponents.length; i++) {
const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
}
return true;
}
function getBasePaths(
path: string,
includes: readonly string[] | undefined,
useCaseSensitiveFileNames: boolean,
): string[] {
// Storage for our results in the form of literal paths (e.g. the paths as written by the user).
const basePaths: string[] = [path];
if (includes) {
// Storage for literal base paths amongst the include patterns.
const includeBasePaths: string[] = [];
for (const include of includes) {
// We also need to check the relative paths by converting them to absolute and normalizing
// in case they escape the base path (e.g "..\somedirectory")
const absolute: string = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include));
// Append the literal and canonical candidate base paths.
includeBasePaths.push(getIncludeBasePath(absolute));
}
// Sort the offsets array using either the literal or canonical path representations.
includeBasePaths.sort(getStringComparer(!useCaseSensitiveFileNames));
// Iterate over each include base path and include unique base paths that are not a
// subpath of an existing base path
for (const includeBasePath of includeBasePaths) {
if (basePaths.every((basePath) => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) {
basePaths.push(includeBasePath);
}
}
}
return basePaths;
}
function getRegexFromPattern(pattern: string, useCaseSensitiveFileNames: boolean): RegExp {
return new RegExp(pattern, useCaseSensitiveFileNames ? '' : 'i');
}
type Comparer<T> = (a: T, b: T) => Comparison;
function sort<T>(array: readonly T[], comparer: Comparer<T>): T[] {
return array.slice().sort(comparer);
}
function findIndex<T>(
array: readonly T[],
predicate: (element: T, index: number) => boolean,
startIndex?: number,
): number {
for (let i = startIndex || 0; i < array.length; i++) {
if (predicate(array[i], i)) {
return i;
}
}
return -1;
}
function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
export function fileExtensionIs(path: string, extension: string): boolean {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
}
}
return false;
}
export function matchFiles(
pathIn: string,
extensions: readonly string[] | undefined,
excludes: readonly string[] | undefined,
includes: readonly string[] | undefined,
useCaseSensitiveFileNames: boolean,
currentDirectoryIn: string,
depth: number | undefined,
getFileSystemEntries: (path: string) => FileSystemEntries,
): string[] {
const path = normalizePath(pathIn);
const currentDirectory = normalizePath(currentDirectoryIn);
const patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
const includeFileRegexes =
patterns.includeFilePatterns &&
patterns.includeFilePatterns.map((pattern) => getRegexFromPattern(pattern, useCaseSensitiveFileNames));
const includeDirectoryRegex =
patterns.includeDirectoryPattern &&
getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
const excludeRegex =
patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
// Associate an array of results with each include regex. This keeps results in order of the "include" order.
// If there are no "includes", then just put everything in results[0].
const results: string[][] = includeFileRegexes ? includeFileRegexes.map(() => []) : [[]];
for (const basePath of patterns.basePaths) {
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
}
return _.flatten<string>(results);
function visitDirectory(path: string, absolutePath: string, depth: number | undefined) {
const { files, directories } = getFileSystemEntries(path);
for (const current of sort<string>(files, compareStringsCaseSensitive)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if (extensions && !fileExtensionIsOneOf(name, extensions)) continue;
if (excludeRegex && excludeRegex.test(absoluteName)) continue;
if (!includeFileRegexes) {
results[0].push(name);
} else {
const includeIndex = findIndex(includeFileRegexes, (re) => re.test(absoluteName));
if (includeIndex !== -1) {
results[includeIndex].push(name);
}
}
}
if (depth !== undefined) {
depth--;
if (depth === 0) {
return;
}
}
for (const current of sort<string>(directories, compareStringsCaseSensitive)) {
const name = combinePaths(path, current);
const absoluteName = combinePaths(absolutePath, current);
if (
(!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
(!excludeRegex || !excludeRegex.test(absoluteName))
) {
visitDirectory(name, absoluteName, depth);
}
}
}
}
const emptyFileSystemEntries: FileSystemEntries = {
files: [],
directories: [],
};
enum FileSystemEntryKind {
File,
Directory,
}
// tslint:disable-next-line export-name
export const createFSHost = (fs: FileSystem) => {
const useCaseSensitiveFileNames = true;
return {
readFile,
readDirectory,
fileExists,
directoryExists,
getDirectories,
getCurrentDirectory: () => currentDirectory,
};
function getDirectories(path: string): string[] {
if (!directoryExists(path)) {
return [];
}
return _.filter<string>(fs.readdirSync(path), (dir: string) =>
fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory),
);
}
function fileSystemEntryExists(path: string, entryKind: FileSystemEntryKind): boolean {
try {
const stat = fs.statSync(path);
switch (entryKind) {
case FileSystemEntryKind.File:
return stat.isFile();
case FileSystemEntryKind.Directory:
return stat.isDirectory();
default:
return false;
}
} catch {
return false;
}
}
function readFile(fileName: string, encoding?: string): string | undefined {
if (!fileExists(fileName)) {
return undefined;
}
return fs.readFileSync(fileName);
}
function readDirectory(
path: string,
extensions?: readonly string[],
excludes?: readonly string[],
includes?: readonly string[],
depth?: number,
): string[] {
return matchFiles(
path,
extensions,
excludes,
includes,
useCaseSensitiveFileNames,
currentDirectory,
depth,
getAccessibleFileSystemEntries,
);
}
function fileExists(path: string): boolean {
return fileSystemEntryExists(path, FileSystemEntryKind.File);
}
function directoryExists(path: string): boolean {
const res = fileSystemEntryExists(path, FileSystemEntryKind.Directory);
return res;
}
function getAccessibleFileSystemEntries(path: string): FileSystemEntries {
try {
const entries = fs
.readdirSync(path || '/')
.slice()
.sort();
const files: string[] = [];
const directories: string[] = [];
for (const entry of entries) {
// This is necessary because on some file system node fails to exclude
// "." and "..". See https://github.com/nodejs/node/issues/4002
if (entry === '.' || entry === '..') {
continue;
}
const name = combinePaths(path, entry);
let stat: any;
try {
stat = fs.statSync(name);
} catch (e) {
continue;
}
if (stat.isFile()) {
files.push(entry);
} else if (stat.isDirectory()) {
directories.push(entry);
}
}
return { files, directories };
} catch (e) {
return emptyFileSystemEntries;
}
}
}; | the_stack |
import { getDatabase } from './';
import {
HASMANY as HasMany,
HASONE as HasOne,
INTEGER as Integer,
BELONGSTO as BelongsTo,
BELONGSTOMANY as BelongsToMany,
} from '../fields';
import { DataTypes } from 'sequelize';
import Database from '..';
let db: Database;
beforeEach(() => {
db = getDatabase();
});
afterEach(() => {
db.close();
});
describe('associations', () => {
describe('hasOne', () => {
it('should be defaults', async () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasone',
name: 'foo',
},
],
});
const field: HasOne = db.getTable('bars').getField('foo');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.sourceKey).toBe('id');
});
it('should be ok when the association table is defined later', async () => {
db.table({
name: 'bars',
fields: [
{
type: 'hasone',
name: 'foo',
},
],
});
db.table({
name: 'foos',
});
const field: HasOne = db.getTable('bars').getField('foo');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.sourceKey).toBe('id');
});
it('should be custom when target is defined', () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasone',
name: 'foo2',
target: 'foos',
},
],
});
const field: HasOne = db.getTable('bars').getField('foo2');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.sourceKey).toBe('id');
});
it('should be custom when sourceKey is defined', () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasone',
name: 'foo',
sourceKey: 'sid',
},
],
});
const field: HasOne = db.getTable('bars').getField('foo');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_sid');
expect(field.options.sourceKey).toBe('sid');
});
it('should be integer type when the column of sourceKey does not exist', () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasone',
name: 'foo',
sourceKey: 'sid',
},
],
});
const field: HasOne = db.getTable('bars').getField('foo');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_sid');
expect(field.options.sourceKey).toBe('sid');
const sourceKeyColumn: Integer = db.getTable('bars').getField('sid');
expect(sourceKeyColumn).toBeInstanceOf(Integer);
expect(sourceKeyColumn.options.unique).toBe(true);
});
});
describe('hasMany', () => {
it('should be defaults', async () => {
db.table({
name: 'foo',
});
db.table({
name: 'bar',
fields: [
{
type: 'hasMany',
name: 'foo',
},
],
});
const field: HasMany = db.getTable('bar').getField('foo');
expect(field.options.target).toBe('foo');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.sourceKey).toBe('id');
});
it('should be ok when the association table is defined later', async () => {
db.table({
name: 'bars',
fields: [
{
type: 'hasMany',
name: 'foos',
},
],
});
db.table({
name: 'foos',
});
const field: HasMany = db.getTable('bars').getField('foos');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.sourceKey).toBe('id');
});
it('should be custom when target is defined', () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasMany',
name: 'foo2',
target: 'foos',
},
],
});
const field: HasMany = db.getTable('bars').getField('foo2');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.sourceKey).toBe('id');
});
it('should be custom when sourceKey is defined', () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasMany',
name: 'foos',
sourceKey: 'sid',
},
],
});
const field: HasMany = db.getTable('bars').getField('foos');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_sid');
expect(field.options.sourceKey).toBe('sid');
});
it('should be integer type when the column of sourceKey does not exist', () => {
db.table({
name: 'foos',
});
db.table({
name: 'bars',
fields: [
{
type: 'hasMany',
name: 'foos',
sourceKey: 'sid',
},
],
});
const field: HasMany = db.getTable('bars').getField('foos');
expect(field.options.target).toBe('foos');
expect(field.options.foreignKey).toBe('bar_sid');
expect(field.options.sourceKey).toBe('sid');
const sourceKeyColumn: Integer = db.getTable('bars').getField('sid');
expect(sourceKeyColumn).toBeInstanceOf(Integer);
expect(sourceKeyColumn.options.unique).toBe(true);
});
});
describe('belongsTo', () => {
it('should be custom foreignKey', async () => {
db.table({
name: 'bars',
fields: [
{
type: 'belongsTo',
name: 'foo',
},
],
});
db.table({
name: 'foos',
});
const field: BelongsTo = db.getTable('bars').getField('foo');
expect(field.options.targetKey).toBe('id');
expect(field.options.foreignKey).toBe('foo_id');
});
it('should be custom foreignKey', async () => {
db.table({
name: 'bars',
fields: [
{
type: 'belongsTo',
name: 'custom_foo',
target: 'foos',
},
],
});
db.table({
name: 'foos',
});
const field: BelongsTo = db.getTable('bars').getField('custom_foo');
expect(field.options.targetKey).toBe('id');
expect(field.options.foreignKey).toBe('custom_foo_id');
});
it('should be custom primaryKey', () => {
db.table({
name: 'foos',
fields: [
{
type: 'integer',
name: 'fid',
primaryKey: true,
autoIncrement: true,
}
],
});
db.table({
name: 'bars',
fields: [
{
type: 'belongsTo',
name: 'foo',
},
],
});
const field: BelongsTo = db.getTable('bars').getField('foo');
expect(field.options.target).toBe('foos');
expect(field.options.targetKey).toBe('fid');
expect(field.options.foreignKey).toBe('foo_fid');
});
it('should be custom primaryKey', () => {
db.table({
name: 'bars',
fields: [
{
type: 'belongsTo',
name: 'foo',
},
],
});
db.table({
name: 'foos',
fields: [
{
type: 'integer',
name: 'fid',
primaryKey: true,
autoIncrement: true,
}
],
});
const field: BelongsTo = db.getTable('bars').getField('foo');
expect(field.options.target).toBe('foos');
expect(field.options.targetKey).toBe('fid');
expect(field.options.foreignKey).toBe('foo_fid');
});
it('should throw error', () => {
db.table({
name: 'foos',
});
expect(() => {
db.table({
name: 'bars',
fields: [
{
type: 'belongsTo',
name: 'foo',
targetKey: 'fid',
},
],
});
}).toThrow('Unknown attribute "fid" passed as targetKey, define this attribute on model "foos" first')
});
it('should be ok when the association table is defined later', async () => {
db.table({
name: 'bars',
fields: [
{
type: 'belongsTo',
name: 'foo',
targetKey: 'fid',
},
],
});
db.table({
name: 'foos',
fields: [
{
type: 'integer',
name: 'fid',
},
],
});
const field: BelongsTo = db.getTable('bars').getField('foo');
expect(field.options.targetKey).toBe('fid');
expect(field.options.foreignKey).toBe('foo_fid');
});
it('should work', async () => {
db.table({
name: 'rows',
fields: [
{
type: 'string',
name: 'name',
unique: true,
},
{
type: 'hasMany',
name: 'columns',
sourceKey: 'name',
}
],
});
db.table({
name: 'columns',
fields: [
{
type: 'belongsTo',
name: 'row',
targetKey: 'name',
},
{
type: 'string',
name: 'name',
}
],
});
const f1: BelongsTo = db.getTable('columns').getField('row');
expect(f1.options.foreignKey).toBe('row_name');
const f2: HasMany = db.getTable('rows').getField('columns');
expect(f2.options.foreignKey).toBe('row_name');
});
});
describe('belongsToMany', () => {
it('should be defaults', async () => {
db.table({
name: 'foos',
fields: [
{
type: 'belongsToMany',
name: 'bars',
},
],
});
db.table({
name: 'bars_foos',
fields: [
{
type: 'string',
name: 'name',
},
],
});
db.table({
name: 'bars',
fields: [
{
type: 'belongsToMany',
name: 'foos',
},
],
});
// console.log(db.getModel('bars_foos').rawAttributes);
// await db.sync({
// force: true,
// });
let field: BelongsToMany;
field = db.getTable('bars').getField('foos');
expect(field.options.target).toBe('foos');
expect(field.options.through).toBe('bars_foos');
expect(field.options.sourceKey).toBe('id');
expect(field.options.foreignKey).toBe('bar_id');
expect(field.options.targetKey).toBe('id');
expect(field.options.otherKey).toBe('foo_id');
field = db.getTable('foos').getField('bars');
expect(field.options.target).toBe('bars');
expect(field.options.through).toBe('bars_foos');
expect(field.options.sourceKey).toBe('id');
expect(field.options.foreignKey).toBe('foo_id');
expect(field.options.targetKey).toBe('id');
expect(field.options.otherKey).toBe('bar_id');
expect(db.getModel('foos').associations.bars).toBeDefined();
expect(db.getModel('bars').associations.foos).toBeDefined();
});
it('should be correct when use custom primary key', async () => {
db.table({
name: 'foos',
fields: [
{
type: 'integer',
autoIncrement: true,
name: 'fid',
primaryKey: true,
},
{
type: 'belongsToMany',
name: 'bars',
},
],
});
db.table({
name: 'bars',
fields: [
{
type: 'integer',
autoIncrement: true,
name: 'bid',
primaryKey: true,
},
{
type: 'belongsToMany',
name: 'foos',
},
],
});
// await db.sync({force: true});
// await db.sequelize.close();
let field: BelongsToMany;
field = db.getTable('bars').getField('foos');
expect(field.options.target).toBe('foos');
expect(field.options.through).toBe('bars_foos');
expect(field.options.sourceKey).toBe('bid');
expect(field.options.foreignKey).toBe('bar_bid');
expect(field.options.targetKey).toBe('fid');
expect(field.options.otherKey).toBe('foo_fid');
field = db.getTable('foos').getField('bars');
expect(field.options.target).toBe('bars');
expect(field.options.through).toBe('bars_foos');
expect(field.options.sourceKey).toBe('fid');
expect(field.options.foreignKey).toBe('foo_fid');
expect(field.options.targetKey).toBe('bid');
expect(field.options.otherKey).toBe('bar_bid');
expect(db.getModel('foos').associations.bars).toBeDefined();
expect(db.getModel('bars').associations.foos).toBeDefined();
const { foos: barAssociation } = db.getModel('bars').associations as any;
expect(barAssociation.target.name).toBe('foos');
expect(barAssociation.through.model.name).toBe('bars_foos');
expect(barAssociation.sourceKey).toBe('bid');
expect(barAssociation.foreignKey).toBe('bar_bid');
expect(barAssociation.targetKey).toBe('fid');
expect(barAssociation.otherKey).toBe('foo_fid');
const { bars: fooAssociation } = db.getModel('foos').associations as any;
expect(fooAssociation.target.name).toBe('bars');
expect(fooAssociation.through.model.name).toBe('bars_foos');
expect(fooAssociation.sourceKey).toBe('fid');
expect(fooAssociation.foreignKey).toBe('foo_fid');
expect(fooAssociation.targetKey).toBe('bid');
expect(fooAssociation.otherKey).toBe('bar_bid');
});
it('through be defined after source and target', async () => {
db.table({
name: 'foos',
fields: [
{
type: 'belongsToMany',
name: 'bars',
},
],
});
db.table({
name: 'bars',
fields: [
{
type: 'belongsToMany',
name: 'foos',
},
],
});
db.table({
name: 'bars_foos',
fields: [
{
type: 'string',
name: 'name',
},
],
});
// await db.sync({
// force: true,
// });
const Through = db.getModel('bars_foos');
expect(Through.rawAttributes.name).toBeDefined();
expect(Through.rawAttributes.foo_id).toBeDefined();
expect(Through.rawAttributes.bar_id).toBeDefined();
});
it('through be defined after source', async () => {
db.table({
name: 'foos',
fields: [
{
type: 'belongsToMany',
name: 'bars',
},
],
});
db.table({
name: 'bars_foos',
fields: [
{
type: 'string',
name: 'name',
},
],
});
db.table({
name: 'bars',
fields: [
{
type: 'belongsToMany',
name: 'foos',
},
],
});
// await db.sync({
// force: true,
// });
const Through = db.getModel('bars_foos');
expect(Through.rawAttributes.name).toBeDefined();
expect(Through.rawAttributes.foo_id).toBeDefined();
expect(Through.rawAttributes.bar_id).toBeDefined();
});
it('#', () => {
db.table({
name: 'posts',
fields: [
{
type: 'string',
name: 'slug',
unique: true,
},
{
type: 'belongsToMany',
name: 'tags',
sourceKey: 'slug',
targetKey: 'name',
},
],
});
db.table({
name: 'tags',
fields: [
{
type: 'string',
name: 'name',
unique: true,
},
{
type: 'belongsToMany',
name: 'posts',
sourceKey: 'name',
targetKey: 'slug',
},
],
});
const f1: BelongsToMany = db.getTable('posts').getField('tags');
expect(f1.options).toEqual({
target: 'tags',
through: 'posts_tags',
sourceKey: 'slug',
foreignKey: 'post_slug',
type: 'belongsToMany',
name: 'tags',
targetKey: 'name',
otherKey: 'tag_name'
});
const f2: BelongsToMany = db.getTable('tags').getField('posts');
expect(f2.options).toEqual({
target: 'posts',
through: 'posts_tags',
sourceKey: 'name',
foreignKey: 'tag_name',
type: 'belongsToMany',
name: 'posts',
targetKey: 'slug',
otherKey: 'post_slug'
});
});
});
it('should be defined', () => {
db.table({
name: 'bars',
fields: [
{
type: 'string',
name: 'foo_name',
},
{
type: 'belongsTo',
name: 'foo',
foreignKey: 'foo_name',
targetKey: 'name',
}
],
})
db.table({
name: 'foos',
fields: [
{
type: 'string',
name: 'name',
unique: true,
},
{
type: 'hasMany',
name: 'bars',
sourceKey: 'name',
foreignKey: 'foo_name'
},
],
});
});
}); | the_stack |
import AWS = require('aws-sdk');
import type * as dynamodb from '@aws-cdk/aws-dynamodb';
import type * as iam from '@aws-cdk/aws-iam';
import type * as cdk from '@aws-cdk/core';
import { any, array, map, optional, string, Type, TypeShape, Value } from '@punchcard/shape';
import { DDB, Mapper, TableClient } from '@punchcard/shape-dynamodb';
import { $if, call, DataSourceBindCallback, DataSourceProps, DataSourceType, getState, VAny, VBool, VExpression, VInteger, VList, VMap, VNothing, VObject, VString, VTL, vtl } from '../appsync';
import { Build } from '../core/build';
import { CDK } from '../core/cdk';
import { Construct, Scope } from '../core/construct';
import { Dependency } from '../core/dependency';
import { Resource } from '../core/resource';
import { Run } from '../core/run';
import { ConditionExpression } from './dsl/condition';
import { DynamoExpr } from './dsl/dynamo-expr';
import { DynamoDSL } from './dsl/dynamo-repr';
import { PutRequest } from './dsl/put-request';
import { toAttributeValueJson } from './dsl/to-attribute-value';
import { UpdateRequest } from './dsl/update-request';
import { Event } from './event';
import { query, QueryRequest, QueryResponse } from './query-request';
import { Index } from './table-index';
import { Stream } from './table-stream';
import { getKeyNames, keyType } from './util';
/**
* Subset of the CDK's DynamoDB TableProps that can be overriden.
*/
export interface TableOverrideProps extends Omit<dynamodb.TableProps, 'partitionKey' | 'sortKey'> {}
export interface BaseTableProps {
/**
* Override the table infrastructure props.
*
* Example:
* ```ts
* new DynamoDB.Table(scope, 'Table', {
* tableProps: CDK.map(({dynamodb}) => ({
* billingMode: dynamodb.BillingMode.PAY_PER_REQUEST
* }))
* });
* ```
*/
tableProps?: Build<TableOverrideProps>
}
/**
* TableProps for creating a new DynamoDB Table.
*
* @typeparam DataType type of data in the Table.
* @typeparam Key partition and optional sort keys of the Table (members of DataType)
*/
export interface TableProps<DataType extends TypeShape, Key extends DDB.KeyOf<DataType>> extends BaseTableProps {
/**
* Type of data in the Table.
*/
data: DataType;
/**
* Partition and (optional) Sort Key of the Table.
*/
key: Key;
}
/**
* Represents a DynamoDB Table.
*
* The data in a table is desciberd with a Record:
* ```ts
* class Data extends Record({
* a: integer,
* b: number,
* c: timestamp,
* d: map(string),
* }) {}
* ```
*
* Then, when creating a table, you can specify just a partition key:
* ```ts
* const table = new DynamoDB.Table(stack, 'table', {
* data: Data,
* key: {
* partition: 'a'
* }
* });
* ```
*
* ... or a partition and sort key:
* ```ts
* const table = new DynamoDB.Table(stack, 'table', {
* data: Data,
* key: {
* partition: 'a',
* sort: 'b'
* }
* });
* ```
*
* Use in a Function:
* ```ts
* new Lambda.Function(stack, 'id', {
* depends: table.readAccess()
* }, async (request, table) => {
* // partitio key only
* await table.get({
* a: 'partition key'
* });
*
* // if sort key provided:
* await table.get({
* a: 'partition key',
* b: 'sort key'
* });
*
* // etc.
* })
* ```
*
* @typeparam DataType type of data in the Table.
* @typeparam Key either a hash key (string literal) or hash+sort key ([string, string] tuple)
*/
export class Table<DataType extends TypeShape, Key extends DDB.KeyOf<DataType>> extends Construct implements Resource<dynamodb.Table> {
/**
* The DynamoDB Table Construct.
*/
public readonly resource: Build<dynamodb.Table>;
/**
* RecordShape of data in the table.
*/
public readonly dataType: DataType;
public readonly valueMapper: Mapper<DataType>;
public readonly keyMapper: Mapper<any>;
public readonly attributeValuesMapper: Mapper<any>;
private streamViewType: dynamodb.StreamViewType;
/**
* The table's key (hash key, or hash+sort key pair).
*/
public readonly key: Key;
private _keyShape: TypeShape; // cache
private get keyShape() {
if (!this._keyShape) {
const keyMembers: any = {
[this.key.partition]: this.dataType.Members[this.key.partition as any]
};
if (this.key.sort) {
keyMembers[this.key.sort] = this.dataType.Members[this.key.sort as any];
}
this._keyShape = Type(keyMembers);
}
return this._keyShape;
}
private _attributeValuesShape: TypeShape; // cache
private get attributeValuesShape() {
if (!this._attributeValuesShape) {
const keyShape = this.keyShape;
const attributeValues = {
...this.dataType.Members
};
Object.keys(keyShape.Members).forEach(k => delete attributeValues[k]);
this._attributeValuesShape = Type(attributeValues);
}
return this._attributeValuesShape;
}
constructor(scope: Scope, id: string, props: TableProps<DataType, Key>) {
super(scope, id);
this.dataType = props.data;
this.key = props.key;
const [partitionKeyName, sortKeyName] = getKeyNames<DataType>(props.key);
this.valueMapper = Mapper.of(this.dataType);
this.keyMapper = Mapper.of(this.keyShape);
this.attributeValuesMapper = Mapper.of(this.attributeValuesShape);
this.resource = CDK.chain(({dynamodb}) => Scope.resolve(scope).map(scope => {
const extraTableProps = props.tableProps ? Build.resolve(props.tableProps) : {};
const dataType = this.dataType;
return new dynamodb.Table(scope, id, {
// default to pay per request - better
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
...extraTableProps,
partitionKey: {
name: partitionKeyName,
type: keyType((dataType.Members as any)[partitionKeyName])
},
sortKey: sortKeyName ? {
name: sortKeyName,
type: keyType((dataType.Members as any)[sortKeyName])
} : undefined,
stream: this.streamViewType as any
});
}));
}
public get(key: KeyGraphQLRepr<DataType, Key>, props?: Table.DataSourceProps): VTL<VObject.Of<DataType>> {
const GetItemRequest = Type({
version: string,
operation: string,
key: this.keyShape
});
const request = VObject.fromExpr(GetItemRequest, VExpression.json({
version: '2017-02-28',
operation: 'GetItem',
key: toAttributeValueJson(this.keyShape, key)
}));
return call(this.dataSourceProps((table, role) => table.grantReadData(role), props), request, this.dataType);
}
public *put(putRequest: PutRequest<DataType>, props?: Table.DataSourceProps): VTL<VObject.Of<DataType>> {
const {
condition,
expressionNames,
expressionValues
} = yield* this.initConditionExpression();
const fields = this.fieldDsl();
if (putRequest.condition) {
yield* putRequest.condition(fields);
}
// TODO: address redundancy between this and `get`.
const PutItemRequest = Type({
version: string,
operation: string,
key: this.keyShape,
attributeValues: this.attributeValuesShape,
condition: optional(ConditionExpression)
});
const request = VObject.fromExpr(PutItemRequest, VExpression.json({
version: '2017-02-28',
operation: 'PutItem',
key: toAttributeValueJson(this.keyShape, putRequest.item),
attributeValues: toAttributeValueJson(this.attributeValuesShape, putRequest.item),
condition: yield* this.compileConditionExpression(condition, expressionNames, expressionValues)
}));
return yield* call(this.dataSourceProps((table, role) => table.grantWriteData(role), props), request, this.dataType);
}
public *update(request: UpdateRequest<DataType, Key>, props?: DataSourceProps): VTL<VObject.Of<DataType>> {
// TODO: https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html#aws-appsync-resolver-mapping-template-reference-dynamodb-condition-handling
const {
condition,
expressionNames,
expressionValues
} = yield* this.initConditionExpression();
const ADD = yield* stringList('$ADD');
const DELETE = yield* stringList('$DELETE');
const SET = yield* stringList('$SET');
const fields = this.fieldDsl();
if (request.condition) {
yield* request.condition(fields);
}
yield* request.transaction(fields);
const UpdateItemRequest = Type({
version: string,
operation: string,
key: this.keyShape,
update: Type({
expression: string,
expressionNames: map(string),
expressionValues: map(any)
}),
condition: optional(ConditionExpression)
});
const expression = yield* vtl(string, {
local: true,
id: '$EXPRESSION'
})``;
for (const [name, list] of Object.entries({
SET,
ADD,
DELETE
})) {
(yield* getState()).writeLine();
yield* vtl`## DynamoDB Update Expressions - ${name}`;
yield* $if(VBool.not(list.isEmpty()), function*() {
yield* vtl`#set(${expression} = "${expression} ${name} #foreach($item in ${list})$item#if($foreach.hasNext), #end#end")`;
});
}
const updateRequest = VObject.fromExpr(UpdateItemRequest, VExpression.json({
version: '2017-02-28',
operation: 'UpdateItem',
key: toAttributeValueJson(this.keyShape, request.key),
update: {
expression,
expressionNames,
expressionValues
},
condition: yield* this.compileConditionExpression(condition, expressionNames, expressionValues)
}));
return yield* call(
this.dataSourceProps((table, role) => table.grantWriteData(role), props),
updateRequest,
this.dataType
);
}
public *query<Q extends QueryRequest<DataType, Key>>(request: Q, props?: DataSourceProps): VTL<QueryResponse<Q, DataType, Key>> {
return yield* query({
dataType: this.dataType,
key: this.key,
keyShape: this.keyShape,
request,
dataSourceProps: this.dataSourceProps((table, role) => table.grantReadData(role), props)
});
}
private fieldDsl() {
const fields: any = {};
for (const [name, field] of Object.entries(this.dataType.Members)) {
fields[name] = DynamoDSL.of(field, new DynamoExpr.Reference(undefined, field, name));
}
return fields;
}
private *compileConditionExpression(
condition: VList<VString>,
expressionNames: VMap<VString>,
expressionValues: VMap<VAny>
) {
return yield* $if(VBool.not(condition.isEmpty()), function*() {
yield* vtl`#set($conditionExpression = "#foreach($item in ${condition})($item)#if($foreach.hasNext) and #end#end")`;
return yield* VObject.of(ConditionExpression, {
expression: new VString(VExpression.text('$conditionExpression')),
expressionNames,
expressionValues
});
});
}
private *initConditionExpression() {
const condition = yield* stringList('$CONDITION');
// map of id -> attribute-value
const expressionValues = yield* vtl(map(any), {
local: true,
id: '$VALUES'
})`{}`;
// map of name -> id
const expressionNames = yield* vtl(map(string), {
local: true,
id: '$NAMES'
})`{}`;
return {
condition,
expressionValues,
expressionNames
};
}
/**
* Return an AppSync DataSource for this Table.
* @param props
*/
public dataSourceProps(grant: (table: dynamodb.Table, role: iam.IRole) => void, props?: Table.DataSourceProps): Build<DataSourceBindCallback> {
return Build.concat(
CDK,
this.resource,
props?.serviceRole || Build.of(undefined)
).map(([cdk, table, serviceRole]) => (scope: cdk.Construct, id: string) => {
const role = serviceRole || new cdk.iam.Role(scope, `${id}:Role`, {
assumedBy: new cdk.iam.ServicePrincipal('appsync')
});
grant(table, role);
return {
type: DataSourceType.AMAZON_DYNAMODB,
dynamoDbConfig: {
awsRegion: table.stack.region,
tableName: table.tableName,
useCallerCredentials: props?.useCallerCredentials
},
description: props?.description,
// TODO: are we sure we want to auto-create an IAM Role?
serviceRoleArn: role.roleArn
};
});
}
/**
* Project this table to a subset of its properties.
*
* Best done by "Picking" properties from the table's RecordType:
* ```ts
* class TableData extends Record({
* a: string,
* b: string,
* c: string,
* d: string,
* }) {}
* const table = new DynamoDB.Table(.., {
* data: TableData,
* // etc.
* }});
*
* const TableProjection extends TableData.Pick(['a', 'b']) {}
*
* table.projectTo(TableProjection)
* ```
* @param projection type of projected data (subset of the Table's properties)
*/
public projectTo<Projection extends TypeShape>(projection: AssertValidProjection<DataType, Projection>): Projected<this, Projection> {
return new Projected(this, projection) as any;
}
public stream(type: 'KEYS_ONLY' | 'NEW_AND_OLD_IMAGES' | 'NEW_IMAGE' | 'OLD_IMAGE' = 'NEW_AND_OLD_IMAGES'): Stream<{
keys: DDB.KeyValue<DataType, Key>;
oldImage?: Value.Of<DataType>;
newImage?: Value.Of<DataType>;
event: Value.Of<typeof Event.Payload>
}, []> {
if (this.streamViewType) {
throw new Error(`stream already configured to ${this.streamViewType}`);
}
this.streamViewType = type as dynamodb.StreamViewType ;
const keyMapper = this.keyMapper;
const valueMapper = this.valueMapper;
class Root extends Stream<{
keys: DDB.KeyValue<DataType, Key>;
oldImage?: Value.Of<DataType>;
newImage?: Value.Of<DataType>;
event: Value.Of<typeof Event.Payload>
}, []> {
/**
* Bottom of the recursive async generator - returns the records
* parsed and validated out of the DynamoDBEvent.
*
* @param event payload of DynamoDB event
*/
public async *run(event: Event.Payload) {
for (const record of event.Records) {
const keys = keyMapper.read({M: record.dynamodb.Keys!});
const newImage = record.dynamodb.NewImage ? valueMapper.read({M: record.dynamodb.NewImage!}) : undefined;
const oldImage = record.dynamodb.OldImage ? valueMapper.read({M: record.dynamodb.OldImage!}) : undefined;
yield {
keys,
newImage: {
...keys,
...newImage
},
oldImage: {
...keys,
...oldImage
},
event
};
}
}
}
return new Root(this, undefined as any, {
depends: [],
handle: i => i
});
}
/**
* Creates a global index that projects ALL attributes.
*
* To create a projected gobal index, first call `projectTo` on this table.
*
* @param props Global Index props such as name and key information.
*/
public globalIndex<IndexKey extends DDB.KeyOf<DataType>>(
props: Index.GlobalProps<DataType, IndexKey>):
Index.Of<this, DataType, IndexKey> {
return new Index({
indexType: 'global',
indexName: props.indexName,
key: props.key,
projection: this.dataType,
sourceTable: this
}) as any;
}
/**
* Take a *read-only* dependency on this table.
*/
public readAccess(): Dependency<Table.ReadOnly<DataType, Key>> {
return this.dependency((t, g) => t.grantReadData(g));
}
/**
* Take a *read-write* dependency on this table.
*/
public readWriteAccess(): Dependency<Table.ReadWrite<DataType, Key>> {
return this.dependency((t, g) => t.grantReadWriteData(g));
}
/**
* Take a *write-only* dependency on this table.
*/
public writeAccess(): Dependency<Table.WriteOnly<DataType, Key>> {
return this.dependency((t, g) => t.grantWriteData(g));
}
/**
* Take a *full-access* dependency on this table.
*
* TODO: return type of Table.FullAccessClient?
*/
public fullAccess(): Dependency<Table.ReadWrite<DataType, Key>> {
return this.dependency((t, g) => t.grantFullAccess(g));
}
private dependency(grant: (table: dynamodb.Table, grantable: iam.IGrantable) => void): Dependency<TableClient<DataType, Key>> {
return {
install: this.resource.map(table => (ns, grantable) => {
ns.set('tableName', table.tableName);
grant(table, grantable);
}),
bootstrap: Run.of(async (ns, cache) =>
new TableClient({
data: this.dataType,
key: this.key as any,
tableName: ns.get('tableName'),
client: cache.getOrCreate('aws:dynamodb', () => new AWS.DynamoDB())
}))
};
}
}
export type KeyGraphQLRepr<DataType extends TypeShape, K extends DDB.KeyOf<DataType>> = {
[k in Extract<K[keyof K], string>]: VObject.Of<DataType['Members'][k]>;
};
export namespace Table {
export interface DataSourceProps {
description?: string;
serviceRole?: Build<iam.IRole>;
/**
* @default - false
*/
useCallerCredentials?: boolean;
}
export function NewType<DataType extends TypeShape, Key extends DDB.KeyOf<DataType>>(
input: {
data: DataType,
key: Key
}): Construct.Class<Table<DataType, Key>, BaseTableProps> {
return class extends Table<DataType, Key> {
constructor(scope: Scope, id: string, props: BaseTableProps) {
super(scope, id, {
...props,
...input
});
}
} as any;
}
/**
* A DynamoDB Table with read-only permissions.
*
* Unavailable methods: `put`, `putBatch`, `delete`, `update`.
*/
export interface ReadOnly<A extends TypeShape, K extends DDB.KeyOf<A>> extends Omit<TableClient<A, K>, 'put' | 'batchPut' | 'delete' | 'update'> {}
/**
* A DynamoDB Table with write-only permissions.
*
* Unavailable methods: `batchGet`, `get`, `scan`, `query`
*/
export interface WriteOnly<A extends TypeShape, K extends DDB.KeyOf<A>> extends Omit<TableClient<A, K>, 'batchGet' | 'get' | 'scan' | 'query'> {}
/**
* A DynamODB Table with read and write permissions.
*/
export interface ReadWrite<A extends TypeShape, K extends DDB.KeyOf<A>> extends TableClient<A, K> {}
}
export namespace Table {
export type Data<T extends Table<any, any>> = T extends Table<infer D, any> ? D : never;
export type Key<T extends Table<any, any>> = T extends Table<any, infer K> ? K : never;
}
function* stringList(id: string) {
return yield* vtl(array(string), {
local: true,
id
})`[]`;
}
type AssertValidProjection<T extends TypeShape, P extends TypeShape> = T['Members'] extends P['Members'] ? P : never;
/**
* Represents a Projection of some DynamoDB Table.
*
* Used to build projected Secondary Indexes or (todo) Streams.
*
* @typeparam SourceTable the projected table
* @typeparam Projection the type of projected data
*/
export class Projected<SourceTable extends Table<any, any>, Projection extends TypeShape> {
constructor(public readonly sourceTable: SourceTable, public readonly projection: Projection) {}
public globalIndex<IndexKey extends DDB.KeyOf<Projection>>(
props: Index.GlobalProps<Projection, IndexKey>):
Index.Of<SourceTable, Projection, IndexKey> {
return new Index({
indexName: props.indexName,
indexType: 'global',
key: props.key,
projection: this.projection,
sourceTable: this.sourceTable
}) as any;
}
} | the_stack |
import StateBlock from 'markdown-it/lib/rules_block/state_block'
import { Nesting } from 'markdown-it/lib/token'
import MarkdownIt from 'markdown-it'
function getLine(state: StateBlock, line: number) {
const pos = state.bMarks[line] + state.blkIndent
const max = state.eMarks[line]
return state.src.substr(pos, max - pos)
}
function escapedSplit(
str: string,
openDelims: string[],
closeDelims: string[],
) {
const result = []
let pos = 0
const max = str.length
let ch
let escapes = 0
let lastPos = 0
let backTicked = false
let lastBackTick = 0
let lastDelim = 0
let delimed = -1
let openDelimIdx = -1
let closeDelimIdx = -1
ch = str.charCodeAt(pos)
// Def map for matching open/close delimiter sequence with str@pos
function delimMaskMap(e: string) {
return str.substring(pos, pos + e.length) === e
}
while (pos < max) {
openDelimIdx = openDelims.map(delimMaskMap).indexOf(true)
closeDelimIdx = closeDelims.map(delimMaskMap).indexOf(true)
if (!backTicked) {
if (openDelimIdx > -1 && escapes % 2 === 0 && delimed === -1) {
delimed = openDelimIdx
lastDelim = pos + openDelims[openDelimIdx].length - 1
pos += openDelims[openDelimIdx].length - 1
} else if (
closeDelimIdx > -1 &&
escapes % 2 === 0 &&
delimed === closeDelimIdx
) {
delimed = -1
lastDelim = pos + closeDelims[closeDelimIdx].length - 1
pos += closeDelims[closeDelimIdx].length - 1
}
}
if (ch === 0x60 /* ` */) {
if (backTicked) {
// make \` close code sequence, but not open it;
// the reason is: `\` is correct code block
backTicked = false
lastBackTick = pos
} else if (escapes % 2 === 0) {
backTicked = true
lastBackTick = pos
}
} else if (
ch === 0x7c /* | */ &&
escapes % 2 === 0 &&
delimed === -1 &&
!backTicked
) {
result.push(str.substring(lastPos, pos))
lastPos = pos + 1
}
if (ch === 0x5c /* \ */) {
escapes++
} else {
escapes = 0
}
pos++
// If there was an un-closed delimiter sequence, go back to just after
// the last delimiter sequence, but as if it was a normal character
if (pos === max && delimed > -1) {
delimed = -1
pos = lastDelim + 1
}
// If there was an un-closed backtick, go back to just after
// the last backtick, but as if it was a normal character
if (pos === max && backTicked) {
backTicked = false
pos = lastBackTick + 1
}
ch = str.charCodeAt(pos)
}
result.push(str.substring(lastPos))
return result
}
function table(
openDelims: string[],
closeDelims: string[],
caption: boolean,
state: StateBlock,
startLine: number,
endLine: number,
silent: any,
) {
let ch
let lineText
let pos
let i
let nextLine
let columns
let columnCount
let token
let aligns
let t
let tableLines
let tbodyLines
let captionParsed: ReturnType<typeof parse_caption> | undefined
// should have at least two lines
if (startLine + 2 > endLine) {
return false
}
if (caption) {
captionParsed = parse_caption(state, startLine)
if (captionParsed) {
startLine = captionParsed.nextLine
}
}
nextLine = startLine + 1
if (state.sCount[nextLine] < state.blkIndent) {
return false
}
// if it's indented more than 3 spaces, it should be a code block
if (state.sCount[nextLine] - state.blkIndent >= 4) {
return false
}
// first character of the second line should be '|', '-', ':',
// and no other characters are allowed but spaces;
// basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp
pos = state.bMarks[nextLine] + state.tShift[nextLine]
if (pos >= state.eMarks[nextLine]) {
return false
}
ch = state.src.charCodeAt(pos++)
if (ch !== 0x7c /* | */ && ch !== 0x2d /* - */ && ch !== 0x3a /* : */) {
return false
}
while (pos < state.eMarks[nextLine]) {
ch = state.src.charCodeAt(pos)
if (
ch !== 0x7c /* | */ &&
ch !== 0x2d /* - */ &&
ch !== 0x3a /* : */ &&
!state.md.utils.isSpace(ch)
) {
return false
}
pos++
}
lineText = getLine(state, startLine + 1)
columns = lineText.split('|')
aligns = []
for (i = 0; i < columns.length; i++) {
t = columns[i].trim()
if (!t) {
// allow empty columns before and after table, but not in between columns;
// e.g. allow ` |---| `, disallow ` ---||--- `
if (i === 0 || i === columns.length - 1) {
continue
} else {
return false
}
}
if (!/^:?-+:?$/.test(t)) {
return false
}
if (t.charCodeAt(t.length - 1) === 0x3a /* : */) {
aligns.push(t.charCodeAt(0) === 0x3a /* : */ ? 'center' : 'right')
} else if (t.charCodeAt(0) === 0x3a /* : */) {
aligns.push('left')
} else {
aligns.push('')
}
}
lineText = getLine(state, startLine).trim()
if (lineText.indexOf('|') === -1) {
return false
}
if (state.sCount[startLine] - state.blkIndent >= 4) {
return false
}
columns = escapedSplit(
lineText.replace(/^\||\|$/g, ''),
openDelims,
closeDelims,
)
// header row will define an amount of columns in the entire table,
// and align row shouldn't be smaller than that (the rest of the rows can)
columnCount = columns.length
if (columnCount > aligns.length) {
return false
}
if (silent) {
return true
}
token = state.push('table_open', 'table', 1)
token.map = [startLine, 0]
tableLines = token.map
token = state.push('thead_open', 'thead', 1)
token.map = [startLine, startLine + 1]
token = state.push('tr_open', 'tr', 1)
token.map = [startLine, startLine + 1]
for (i = 0; i < columns.length; i++) {
token = state.push('th_open', 'th', 1)
token.map = [startLine, startLine + 1]
if (aligns[i]) {
token.attrs = [['style', 'text-align:' + aligns[i]]]
}
token = state.push('inline', '', 0)
token.content = columns[i].trim()
token.map = [startLine, startLine + 1]
token.children = []
token = state.push('th_close', 'th', -1)
}
token = state.push('tr_close', 'tr', -1)
token = state.push('thead_close', 'thead', -1)
token = state.push('tbody_open', 'tbody', 1)
token.map = [startLine + 2, 0]
tbodyLines = token.map
for (nextLine = startLine + 2; nextLine < endLine; nextLine++) {
if (state.sCount[nextLine] < state.blkIndent) {
break
}
lineText = getLine(state, nextLine).trim()
if (lineText.indexOf('|') === -1) {
break
}
if (state.sCount[nextLine] - state.blkIndent >= 4) {
break
}
columns = escapedSplit(
lineText.replace(/^\||\|$/g, ''),
openDelims,
closeDelims,
)
token = state.push('tr_open', 'tr', 1)
for (i = 0; i < columnCount; i++) {
token = state.push('td_open', 'td', 1)
if (aligns[i]) {
token.attrs = [['style', 'text-align:' + aligns[i]]]
}
token = state.push('inline', '', 0)
token.content = columns[i] ? columns[i].trim() : ''
token.children = []
token = state.push('td_close', 'td', -1)
}
token = state.push('tr_close', 'tr', -1)
}
token = state.push('tbody_close', 'tbody', -1)
if (caption) {
if (!captionParsed) {
captionParsed = parse_caption(state, nextLine)
if (captionParsed) nextLine = captionParsed.nextLine
}
if (captionParsed) {
pushTokens(state, captionParsed.tokens)
}
}
token = state.push('table_close', 'table', -1)
tableLines[1] = tbodyLines[1] = nextLine
state.line = nextLine
return true
}
interface TempToken {
args: [string, string, Nesting]
props: { [key: string]: any }
}
function parse_caption(
state: StateBlock,
startLine: number,
):
| false
| {
nextLine: number
tokens: TempToken[]
} {
let nextLine = startLine
const pos = state.bMarks[nextLine] + state.tShift[nextLine]
if (!state.src.slice(pos).match(/^\s*\w*:/)) return false
let bpos = state.bMarks[nextLine] + state.tShift[nextLine]
let epos = state.eMarks[nextLine]
let line = state.src.slice(bpos, epos)
while (line.match(/^\s*$/)) {
nextLine++
bpos = state.bMarks[nextLine] + state.tShift[nextLine]
epos = state.eMarks[nextLine]
line = state.src.slice(bpos, epos)
}
if (state.sCount[nextLine] - state.blkIndent >= 4) return false
while (state.src.charCodeAt(bpos) !== 0x3a /*:*/) bpos++
const inlinePos = bpos + 1
const beginLine = nextLine
let cepos
while (!line.match(/^\s*$/)) {
cepos = state.eMarks[nextLine]
nextLine++
bpos = state.bMarks[nextLine] + state.tShift[nextLine]
epos = state.eMarks[nextLine]
line = state.src.slice(bpos, epos)
}
const inlineEnd = cepos
const endLine = nextLine - 1
const tokens: TempToken[] = []
tokens.push({
args: ['caption_open', 'caption', 1],
props: { map: [beginLine, endLine] },
})
tokens.push({
args: ['inline', '', 0],
props: {
content: state.src.slice(inlinePos, inlineEnd),
children: [],
},
})
tokens.push({
args: ['caption_close', 'caption', -1],
props: {
content: state.src.slice(inlinePos, inlineEnd),
children: [],
},
})
while (line.match(/^\s*$/)) {
nextLine++
bpos = state.bMarks[nextLine] + state.tShift[nextLine]
epos = state.eMarks[nextLine]
line = state.src.slice(bpos, epos)
}
return {
nextLine,
tokens,
}
}
function pushTokens(
state: StateBlock,
tokens: Exclude<ReturnType<typeof parse_caption>, false>['tokens'],
) {
for (const tok of tokens) {
const token = state.push(...tok.args)
for (const [k, v] of Object.entries(tok.props)) {
token[k] = v as any
}
}
}
export function makeTable(md: MarkdownIt, options: Options = {}) {
const openDelims = options?.inlineDelim
? options.inlineDelim.map((i) => i[0])
: []
const closeDelims = options?.inlineDelim
? options.inlineDelim.map((i) => i[1])
: []
const parser = table.bind(null, openDelims, closeDelims, !!options?.caption)
md.block.ruler.at('table', parser, {
alt: ['paragraph', 'reference'],
})
}
export interface Options {
inlineDelim?: [[string, string]]
caption?: boolean
} | the_stack |
import { v4 as uuid } from "uuid";
import produce, { Draft } from "immer";
import { Graph, Api, Model, Rbac } from "../../types";
import {
graphTypes,
getOrphanedLocalKeyIds,
getOrphanedRecoveryKeyIds,
getAppRoleEnvironmentRolesByComposite,
getIncludedAppRolesByComposite,
getLocalKeysByEnvironmentId,
getEnvironmentsByRoleId,
getServersByEnvironmentId,
getDeleteAppAssociations,
getDeleteGroupAssociations,
getDeleteBlockAssociations,
getDeleteEnvironmentAssociations,
getDeleteKeyableParentAssociations,
getEnvironmentsByEnvParentId,
} from ".";
import * as R from "ramda";
import { pickDefined } from "../utils/object";
import { indexBy, groupBy } from "../utils/array";
import { log } from "../utils/logger";
import { getOrg } from "./base";
export const getDeleteAppProducer =
<T extends Graph.Graph = Graph.Graph>(
id: string,
now: number
): Graph.Producer<T> =>
(graphDraft) => {
getDeleteGraphObjectsProducer(
[id, ...getDeleteAppAssociations(graphDraft, id).map(R.prop("id"))],
now
)(graphDraft);
},
getDeleteBlockProducer =
<T extends Graph.Graph = Graph.Graph>(
id: string,
now: number
): Graph.Producer<T> =>
(graphDraft) => {
getDeleteGraphObjectsProducer(
[id, ...getDeleteBlockAssociations(graphDraft, id).map(R.prop("id"))],
now
)(graphDraft);
},
getDeleteGroupProducer =
<T extends Graph.Graph>(id: string, now: number): Graph.Producer<T> =>
(graphDraft) => {
getDeleteGraphObjectsProducer(
[id, ...getDeleteGroupAssociations(graphDraft, id).map(R.prop("id"))],
now
)(graphDraft);
},
getDeleteEnvironmentProducer =
<T extends Graph.Graph>(id: string, now: number): Graph.Producer<T> =>
(graphDraft) => {
getDeleteGraphObjectsProducer(
[
id,
...getDeleteEnvironmentAssociations(graphDraft, id).map(R.prop("id")),
],
now
)(graphDraft);
},
getDeleteKeyableParentProducer =
<T extends Graph.Graph>(id: string, now: number): Graph.Producer<T> =>
(graphDraft) => {
getDeleteGraphObjectsProducer(
[
id,
...getDeleteKeyableParentAssociations(graphDraft, id).map(
R.prop("id")
),
],
now
)(graphDraft);
},
getDeleteGraphObjectsProducer =
<T extends Graph.Graph>(ids: string[], now: number) =>
(graphDraft: Draft<T>) => {
let deletedServerEnvkeys = 0;
for (let id of ids) {
const obj = graphDraft[id];
if (
obj.type == "generatedEnvkey" &&
obj.keyableParentType == "server"
) {
deletedServerEnvkeys++;
}
graphDraft[id].deletedAt = now;
}
if (deletedServerEnvkeys > 0) {
const org = getOrg(graphDraft) as Draft<Model.Org>;
org.serverEnvkeyCount -= deletedServerEnvkeys;
org.updatedAt = now;
}
},
deleteGraphObjects = <T extends Graph.Graph>(
graph: T,
ids: string[],
now: number
) => produce(graph, getDeleteGraphObjectsProducer<T>(ids, now)),
getDeleteExpiredAuthObjectsProducer =
<T extends Graph.Graph>(graph: T, now: number) =>
(graphDraft: Draft<T>) => {
// for invites and deviceGrants, we want to keep only the latest expired object per user, and delete any older ones
const expiredFilterFn = ({
acceptedAt,
expiresAt,
deletedAt,
}: Model.Invite | Model.DeviceGrant) =>
!acceptedAt && !deletedAt && now >= expiresAt;
const byType = graphTypes(graph),
authObjects: {
[userId: string]: (Model.DeviceGrant | Model.Invite)[];
}[] = [
groupBy(R.prop("inviteeId"), byType.invites.filter(expiredFilterFn)),
groupBy(
R.prop("granteeId"),
byType.deviceGrants.filter(expiredFilterFn)
),
],
toDeleteIds = R.flatten(
authObjects.map((objectsByUserId) =>
R.flatten(
Object.values<string>(
R.map(
(objects) =>
R.tail(
R.sortBy(({ expiresAt }) => -expiresAt, objects)
).map(R.prop("id")),
objectsByUserId
)
)
)
)
);
getDeleteGraphObjectsProducer(toDeleteIds, now)(graphDraft);
},
deleteExpiredAuthObjects = <T extends Graph.Graph>(graph: T, now: number) =>
produce(graph, getDeleteExpiredAuthObjectsProducer<T>(graph, now)),
getUpdateOrgRoleProducer =
<T extends Graph.Graph>(
params: Omit<
Api.Net.ApiParamTypes["RbacUpdateOrgRole"],
keyof Api.Net.EnvParams
>,
now: number
): Graph.Producer<Draft<T>> =>
(graphDraft) => {
const orgRole = graphDraft[params.id] as Rbac.OrgRole;
let toUpdate = params as Partial<Rbac.OrgRole>;
if (orgRole.isDefault) {
toUpdate = pickDefined(["name", "description"], toUpdate);
}
(graphDraft as Draft<Graph.Graph>)[orgRole.id] = {
...orgRole,
...toUpdate,
updatedAt: now,
} as Rbac.OrgRole;
if (params.canBeManagedByOrgRoleIds) {
for (let managingOrgRoleId of params.canBeManagedByOrgRoleIds) {
const managingOrgRoleDraft = graphDraft[
managingOrgRoleId
] as Rbac.OrgRole;
if (
!managingOrgRoleDraft.canManageAllOrgRoles &&
!managingOrgRoleDraft.canManageOrgRoleIds.includes(orgRole.id)
) {
managingOrgRoleDraft.canManageOrgRoleIds.push(orgRole.id);
managingOrgRoleDraft.updatedAt = now;
}
}
}
if (params.canBeInvitedByOrgRoleIds) {
for (let invitingOrgRoleId of params.canBeInvitedByOrgRoleIds) {
const invitingOrgRoleDraft = graphDraft[
invitingOrgRoleId
] as Rbac.OrgRole;
if (
!invitingOrgRoleDraft.canInviteAllOrgRoles &&
!invitingOrgRoleDraft.canInviteOrgRoleIds.includes(orgRole.id)
) {
invitingOrgRoleDraft.canInviteOrgRoleIds.push(orgRole.id);
invitingOrgRoleDraft.updatedAt = now;
}
}
}
const orphanedLocalKeyIds = getOrphanedLocalKeyIds(graphDraft);
if (orphanedLocalKeyIds.length > 0) {
getDeleteGraphObjectsProducer(orphanedLocalKeyIds, now)(graphDraft);
}
const orphanedRecoveryKeyIds = getOrphanedRecoveryKeyIds(graphDraft);
if (orphanedRecoveryKeyIds.length > 0) {
getDeleteGraphObjectsProducer(orphanedRecoveryKeyIds, now)(graphDraft);
}
},
getUpdateAppRoleProducer =
<T extends Graph.Graph>(
params: Omit<
Api.Net.ApiParamTypes["RbacUpdateAppRole"],
keyof Api.Net.EnvParams
>,
now: number
): Graph.Producer<T> =>
(graphDraft) => {
const appRole = graphDraft[params.id] as Rbac.AppRole,
keys = (
appRole.isDefault
? ["name", "description"]
: [
"name",
"description",
"defaultAllApps",
"canInviteAllAppRoles",
"canManageAppRoleIds",
"canInviteAppRoleIds",
"hasFullEnvironmentPermissions",
"permissions",
"extendsRoleId",
"addPermissions",
"removePermissions",
]
).filter((k) => k in params) as (keyof typeof params)[];
(graphDraft as Draft<Graph.Graph>)[appRole.id] = {
...appRole,
...pickDefined(keys, params),
updatedAt: now,
} as Rbac.AppRole;
if (!appRole.isDefault && params.canBeManagedByAppRoleIds) {
for (let managingAppRoleId of params.canBeManagedByAppRoleIds) {
const managingAppRoleDraft = graphDraft[
managingAppRoleId
] as Rbac.AppRole;
if (!managingAppRoleDraft.canManageAppRoleIds.includes(appRole.id)) {
managingAppRoleDraft.canManageAppRoleIds.push(appRole.id);
managingAppRoleDraft.updatedAt = now;
}
}
}
if (!appRole.isDefault && params.canBeInvitedByAppRoleIds) {
for (let invitingAppRoleId of params.canBeInvitedByAppRoleIds) {
const invitingAppRoleDraft = graphDraft[
invitingAppRoleId
] as Rbac.AppRole;
if (!invitingAppRoleDraft.canInviteAppRoleIds.includes(appRole.id)) {
invitingAppRoleDraft.canInviteAppRoleIds.push(appRole.id);
invitingAppRoleDraft.updatedAt = now;
}
}
}
if (params.appRoleEnvironmentRoles) {
for (let environmentRoleId in params.appRoleEnvironmentRoles) {
const appRoleEnvironmentRole = getAppRoleEnvironmentRolesByComposite(
graphDraft
)[
[appRole.id, environmentRoleId].join("|")
] as Rbac.AppRoleEnvironmentRole,
updatedPermissions =
params.appRoleEnvironmentRoles[environmentRoleId];
if (
!R.equals(
R.clone(appRoleEnvironmentRole.permissions).sort(),
R.clone(updatedPermissions).sort()
)
) {
(graphDraft as Draft<Graph.Graph>)[appRoleEnvironmentRole.id] = {
...appRoleEnvironmentRole,
permissions: updatedPermissions,
updatedAt: now,
};
}
}
}
if (
!appRole.isDefault &&
!appRole.defaultAllApps &&
"defaultAllApps" in params &&
params.defaultAllApps
) {
// add included app roles
const apps = graphTypes(graphDraft).apps;
for (let app of apps) {
const existing =
getIncludedAppRolesByComposite(graphDraft)[
[appRole.id, app.id].join("|")
];
if (!existing) {
const id = uuid(),
includedAppRole: Model.IncludedAppRole = {
type: "includedAppRole",
id,
appRoleId: appRole.id,
appId: app.id,
createdAt: now,
updatedAt: now,
};
(graphDraft as Draft<Graph.Graph>)[includedAppRole.id] =
includedAppRole;
}
}
}
if (!appRole.isDefault) {
const orphanedLocalKeyIds = getOrphanedLocalKeyIds(graphDraft);
if (orphanedLocalKeyIds) {
getDeleteGraphObjectsProducer(orphanedLocalKeyIds, now)(graphDraft);
}
}
},
getUpdateEnvironmentRoleProducer =
<T extends Graph.Graph>(
params: Omit<
Api.Net.ApiParamTypes["RbacUpdateEnvironmentRole"],
keyof Api.Net.EnvParams
>,
now: number
): Graph.Producer<T> =>
(graphDraft) => {
const environmentRole = graphDraft[params.id] as Rbac.EnvironmentRole,
keys = [
"name",
"description",
"hasLocalKeys",
"hasServers",
"defaultAllApps",
"defaultAllBlocks",
"settings",
].filter((k) => k in params) as (keyof typeof params)[];
(graphDraft as Graph.Graph)[environmentRole.id] = {
...environmentRole,
...pickDefined(keys, params),
updatedAt: now,
} as Rbac.EnvironmentRole;
if (
!environmentRole.isDefault &&
!environmentRole.defaultAllApps &&
params.defaultAllApps
) {
// add app environments
graphTypes(graphDraft).apps.forEach((app) => {
const existingEnvironmentForRole = indexBy(
R.prop("environmentRoleId"),
getEnvironmentsByEnvParentId(graphDraft)[app.id] ?? []
)[environmentRole.id];
if (!existingEnvironmentForRole) {
const id = uuid(),
environment: Model.Environment = {
type: "environment",
id,
envParentId: app.id,
environmentRoleId: environmentRole.id,
envUpdatedAt: now,
isSub: false,
settings: {},
createdAt: now,
updatedAt: now,
};
(graphDraft as Graph.Graph)[environment.id] = environment;
}
});
}
if (
!environmentRole.isDefault &&
!environmentRole.defaultAllBlocks &&
params.defaultAllBlocks
) {
// add block environments
graphTypes(graphDraft).blocks.forEach((block) => {
const existingEnvironmentForRole = indexBy(
R.prop("environmentRoleId"),
getEnvironmentsByEnvParentId(graphDraft)[block.id] ?? []
)[environmentRole.id];
if (!existingEnvironmentForRole) {
const id = uuid(),
environment: Model.Environment = {
type: "environment",
id,
envParentId: block.id,
environmentRoleId: environmentRole.id,
envUpdatedAt: now,
isSub: false,
settings: {},
createdAt: now,
updatedAt: now,
};
(graphDraft as Graph.Graph)[environment.id] = environment;
}
});
}
if (params.appRoleEnvironmentRoles) {
for (let appRoleId in params.appRoleEnvironmentRoles) {
const appRole = graphDraft[appRoleId] as Rbac.AppRole;
if (appRole.hasFullEnvironmentPermissions) {
continue;
}
const appRoleEnvironmentRole = getAppRoleEnvironmentRolesByComposite(
graphDraft
)[
[appRoleId, environmentRole.id].join("|")
] as Rbac.AppRoleEnvironmentRole,
updatedPermissions = params.appRoleEnvironmentRoles[appRoleId];
if (
!R.equals(
R.clone(appRoleEnvironmentRole.permissions).sort(),
R.clone(updatedPermissions).sort()
)
) {
(graphDraft as Graph.Graph)[appRoleEnvironmentRole.id] = {
...appRoleEnvironmentRole,
permissions: updatedPermissions,
updatedAt: now,
};
}
}
}
let toDeleteIds: string[] = [];
if (
environmentRole.hasLocalKeys &&
"hasLocalKeys" in params &&
!params.hasLocalKeys
) {
// delete all connected local keys
const localKeysByEnvironmentId =
getLocalKeysByEnvironmentId(graphDraft),
environments =
getEnvironmentsByRoleId(graphDraft)[environmentRole.id] || [];
for (let environment of environments) {
const localKeys = localKeysByEnvironmentId[environment.id] || [];
toDeleteIds = toDeleteIds.concat(localKeys.map(R.prop("id")));
}
}
if (
environmentRole.hasServers &&
"hasServers" in params &&
!params.hasServers
) {
// delete all connected servers
const serversByEnvironmentId = getServersByEnvironmentId(graphDraft),
environments =
getEnvironmentsByRoleId(graphDraft)[environmentRole.id] || [];
for (let environment of environments) {
const servers = serversByEnvironmentId[environment.id] || [];
toDeleteIds = toDeleteIds.concat(servers.map(R.prop("id")));
}
}
if (toDeleteIds.length > 0) {
getDeleteGraphObjectsProducer(toDeleteIds, now)(graphDraft);
}
return graphDraft;
}; | the_stack |
import { animationFrameScheduler, fromEvent, interval, NEVER, Observable } from 'rxjs';
import { distinctUntilChanged, map, switchMap, tap } from 'rxjs/operators';
import { ktdNormalizePassiveListenerOptions } from './passive-listeners';
import { getMutableClientRect } from './client-rect';
import { ktdNoEmit } from './operators';
/**
* Proximity, as a ratio to width/height at which to start auto-scrolling.
* The value comes from trying it out manually until it feels right.
*/
const SCROLL_PROXIMITY_THRESHOLD = 0.05;
/** Vertical direction in which we can auto-scroll. */
const enum AutoScrollVerticalDirection {NONE, UP, DOWN}
/** Horizontal direction in which we can auto-scroll. */
const enum AutoScrollHorizontalDirection {NONE, LEFT, RIGHT}
export interface KtdScrollPosition {
top: number;
left: number;
}
/**
* Increments the vertical scroll position of a node.
* @param node Node whose scroll position should change.
* @param amount Amount of pixels that the `node` should be scrolled.
*/
function incrementVerticalScroll(node: HTMLElement | Window, amount: number) {
if (node === window) {
(node as Window).scrollBy(0, amount);
} else {
// Ideally we could use `Element.scrollBy` here as well, but IE and Edge don't support it.
(node as HTMLElement).scrollTop += amount;
}
}
/**
* Increments the horizontal scroll position of a node.
* @param node Node whose scroll position should change.
* @param amount Amount of pixels that the `node` should be scrolled.
*/
function incrementHorizontalScroll(node: HTMLElement | Window, amount: number) {
if (node === window) {
(node as Window).scrollBy(amount, 0);
} else {
// Ideally we could use `Element.scrollBy` here as well, but IE and Edge don't support it.
(node as HTMLElement).scrollLeft += amount;
}
}
/**
* Gets whether the vertical auto-scroll direction of a node.
* @param clientRect Dimensions of the node.
* @param pointerY Position of the user's pointer along the y axis.
*/
function getVerticalScrollDirection(clientRect: ClientRect, pointerY: number) {
const {top, bottom, height} = clientRect;
const yThreshold = height * SCROLL_PROXIMITY_THRESHOLD;
if (pointerY >= top - yThreshold && pointerY <= top + yThreshold) {
return AutoScrollVerticalDirection.UP;
} else if (pointerY >= bottom - yThreshold && pointerY <= bottom + yThreshold) {
return AutoScrollVerticalDirection.DOWN;
}
return AutoScrollVerticalDirection.NONE;
}
/**
* Gets whether the horizontal auto-scroll direction of a node.
* @param clientRect Dimensions of the node.
* @param pointerX Position of the user's pointer along the x axis.
*/
function getHorizontalScrollDirection(clientRect: ClientRect, pointerX: number) {
const {left, right, width} = clientRect;
const xThreshold = width * SCROLL_PROXIMITY_THRESHOLD;
if (pointerX >= left - xThreshold && pointerX <= left + xThreshold) {
return AutoScrollHorizontalDirection.LEFT;
} else if (pointerX >= right - xThreshold && pointerX <= right + xThreshold) {
return AutoScrollHorizontalDirection.RIGHT;
}
return AutoScrollHorizontalDirection.NONE;
}
/**
* Returns an observable that schedules a loop and apply scroll on the scrollNode into the specified direction/s.
* This observable doesn't emit, it just performs the 'scroll' side effect.
* @param scrollNode, node where the scroll would be applied.
* @param verticalScrollDirection, vertical direction of the scroll.
* @param horizontalScrollDirection, horizontal direction of the scroll.
* @param scrollStep, scroll step in CSS pixels that would be applied in every loop.
*/
function scrollToDirectionInterval$(scrollNode: HTMLElement | Window, verticalScrollDirection: AutoScrollVerticalDirection, horizontalScrollDirection: AutoScrollHorizontalDirection, scrollStep: number = 2) {
return interval(0, animationFrameScheduler)
.pipe(
tap(() => {
if (verticalScrollDirection === AutoScrollVerticalDirection.UP) {
incrementVerticalScroll(scrollNode, -scrollStep);
} else if (verticalScrollDirection === AutoScrollVerticalDirection.DOWN) {
incrementVerticalScroll(scrollNode, scrollStep);
}
if (horizontalScrollDirection === AutoScrollHorizontalDirection.LEFT) {
incrementHorizontalScroll(scrollNode, -scrollStep);
} else if (horizontalScrollDirection === AutoScrollHorizontalDirection.RIGHT) {
incrementHorizontalScroll(scrollNode, scrollStep);
}
}),
ktdNoEmit()
);
}
export interface KtdScrollIfNearElementOptions {
scrollStep?: number;
disableVertical?: boolean;
disableHorizontal?: boolean;
}
/**
* Given a source$ observable with pointer location, scroll the scrollNode if the pointer is near to it.
* This observable doesn't emit, it just performs a 'scroll' side effect.
* @param scrollableParent, parent node in which the scroll would be performed.
* @param options, configuration options.
*/
export function ktdScrollIfNearElementClientRect$(scrollableParent: HTMLElement | Document, options?: KtdScrollIfNearElementOptions): (source$: Observable<{ pointerX: number, pointerY: number }>) => Observable<any> {
let scrollNode: Window | HTMLElement;
let scrollableParentClientRect: ClientRect;
let scrollableParentScrollWidth: number;
if (scrollableParent === document) {
scrollNode = document.defaultView as Window;
const {width, height} = getViewportSize();
scrollableParentClientRect = {width, height, top: 0, right: width, bottom: height, left: 0};
scrollableParentScrollWidth = getDocumentScrollWidth();
} else {
scrollNode = scrollableParent as HTMLElement;
scrollableParentClientRect = getMutableClientRect(scrollableParent as HTMLElement);
scrollableParentScrollWidth = (scrollableParent as HTMLElement).scrollWidth;
}
/**
* IMPORTANT: By design, only let scroll horizontal if the scrollable parent has explicitly an scroll horizontal.
* This layout solution is not designed in mind to have any scroll horizontal, but exceptionally we allow it in this
* specific use case.
*/
options = options || {};
if (options.disableHorizontal == null && scrollableParentScrollWidth <= scrollableParentClientRect.width) {
options.disableHorizontal = true;
}
return (source$) => source$.pipe(
map(({pointerX, pointerY}) => {
let verticalScrollDirection = getVerticalScrollDirection(scrollableParentClientRect, pointerY);
let horizontalScrollDirection = getHorizontalScrollDirection(scrollableParentClientRect, pointerX);
// Check if scroll directions are disabled.
if (options?.disableVertical) {
verticalScrollDirection = AutoScrollVerticalDirection.NONE;
}
if (options?.disableHorizontal) {
horizontalScrollDirection = AutoScrollHorizontalDirection.NONE;
}
return {verticalScrollDirection, horizontalScrollDirection};
}),
distinctUntilChanged((prev, actual) => {
return prev.verticalScrollDirection === actual.verticalScrollDirection
&& prev.horizontalScrollDirection === actual.horizontalScrollDirection;
}),
switchMap(({verticalScrollDirection, horizontalScrollDirection}) => {
if (verticalScrollDirection || horizontalScrollDirection) {
return scrollToDirectionInterval$(scrollNode, verticalScrollDirection, horizontalScrollDirection, options?.scrollStep);
} else {
return NEVER;
}
})
);
}
/**
* Emits on EVERY scroll event and returns the accumulated scroll offset relative to the initial scroll position.
* @param scrollableParent, node in which scroll events would be listened.
*/
export function ktdGetScrollTotalRelativeDifference$(scrollableParent: HTMLElement | Document): Observable<{ top: number, left: number }> {
let scrollInitialPosition;
// Calculate initial scroll position
if (scrollableParent === document) {
scrollInitialPosition = getViewportScrollPosition();
} else {
scrollInitialPosition = {
top: (scrollableParent as HTMLElement).scrollTop,
left: (scrollableParent as HTMLElement).scrollLeft
};
}
return fromEvent(scrollableParent, 'scroll', ktdNormalizePassiveListenerOptions({capture: true}) as AddEventListenerOptions).pipe(
map(() => {
let newTop: number;
let newLeft: number;
if (scrollableParent === document) {
const viewportScrollPosition = getViewportScrollPosition();
newTop = viewportScrollPosition.top;
newLeft = viewportScrollPosition.left;
} else {
newTop = (scrollableParent as HTMLElement).scrollTop;
newLeft = (scrollableParent as HTMLElement).scrollLeft;
}
const topDifference = scrollInitialPosition.top - newTop;
const leftDifference = scrollInitialPosition.left - newLeft;
return {top: topDifference, left: leftDifference};
})
);
}
/** Returns the viewport's width and height. */
function getViewportSize(): { width: number, height: number } {
const _window = document.defaultView || window;
return {
width: _window.innerWidth,
height: _window.innerHeight
};
}
/** Gets a ClientRect for the viewport's bounds. */
function getViewportRect(): ClientRect {
// Use the document element's bounding rect rather than the window scroll properties
// (e.g. pageYOffset, scrollY) due to in issue in Chrome and IE where window scroll
// properties and client coordinates (boundingClientRect, clientX/Y, etc.) are in different
// conceptual viewports. Under most circumstances these viewports are equivalent, but they
// can disagree when the page is pinch-zoomed (on devices that support touch).
// See https://bugs.chromium.org/p/chromium/issues/detail?id=489206#c4
// We use the documentElement instead of the body because, by default (without a css reset)
// browsers typically give the document body an 8px margin, which is not included in
// getBoundingClientRect().
const scrollPosition = getViewportScrollPosition();
const {width, height} = getViewportSize();
return {
top: scrollPosition.top,
left: scrollPosition.left,
bottom: scrollPosition.top + height,
right: scrollPosition.left + width,
height,
width,
};
}
/** Gets the (top, left) scroll position of the viewport. */
function getViewportScrollPosition(): { top: number, left: number } {
// The top-left-corner of the viewport is determined by the scroll position of the document
// body, normally just (scrollLeft, scrollTop). However, Chrome and Firefox disagree about
// whether `document.body` or `document.documentElement` is the scrolled element, so reading
// `scrollTop` and `scrollLeft` is inconsistent. However, using the bounding rect of
// `document.documentElement` works consistently, where the `top` and `left` values will
// equal negative the scroll position.
const windowRef = document.defaultView || window;
const documentElement = document.documentElement!;
const documentRect = documentElement.getBoundingClientRect();
const top = -documentRect.top || document.body.scrollTop || windowRef.scrollY ||
documentElement.scrollTop || 0;
const left = -documentRect.left || document.body.scrollLeft || windowRef.scrollX ||
documentElement.scrollLeft || 0;
return {top, left};
}
/** Returns the document scroll width */
function getDocumentScrollWidth() {
return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth);
} | the_stack |
import * as inquirer from "inquirer";
import * as path from "path";
import { BaseTemplateManager } from "../templates";
import {
Component, Config, ControlExtraConfigType, ControlExtraConfiguration, Framework,
FrameworkId, ProjectLibrary, ProjectTemplate, Template
} from "../types";
import { App, ChoiceItem, GoogleAnalytics, ProjectConfig, Util } from "../util";
import { Task, TaskRunner, WIZARD_BACK_OPTION } from "./TaskRunner";
export abstract class BasePromptSession {
protected config: Config;
constructor(protected templateManager: BaseTemplateManager) { }
/**
* Start questions session for project creation
*/
public async start() {
GoogleAnalytics.post({
t: "screenview",
cd: "Wizard"
});
let projLibrary: ProjectLibrary;
let theme: string;
this.config = ProjectConfig.getConfig();
const defaultProjName = "IG Project";
if (ProjectConfig.hasLocalConfig() && !this.config.project.isShowcase) {
projLibrary = this.templateManager.getProjectLibrary(this.config.project.framework, this.config.project.projectType);
theme = this.config.project.theme;
} else {
Util.log(""); /* new line */
const projectName = await this.getUserInput({
type: "input",
name: "projectName",
message: "Enter a name for your project:",
default: Util.getAvailableName(defaultProjName, true),
validate: this.nameIsValid
});
const frameRes: string = await this.getUserInput({
type: "list",
name: "framework",
message: "Choose framework:",
choices: this.getFrameworkNames(),
default: "jQuery"
});
const framework = this.templateManager.getFrameworkByName(frameRes);
// app name validation???
projLibrary = await this.getProjectLibrary(framework);
const projTemplate = await this.getProjectTemplate(projLibrary);
// project options:
theme = await this.getTheme(projLibrary);
Util.log(" Generating project structure.");
const config = projTemplate.generateConfig(projectName, theme);
for (const templatePath of projTemplate.templatePaths) {
await Util.processTemplates(templatePath, path.join(process.cwd(), projectName),
config, projTemplate.delimiters, false);
}
Util.log(Util.greenCheck() + " Project structure generated.");
if (!this.config.skipGit) {
Util.gitInit(process.cwd(), projectName);
}
// move cwd to project folder
process.chdir(projectName);
}
await this.chooseActionLoop(projLibrary);
//TODO: restore cwd?
}
/**
* Starts a loop of 'Choose an action' questions
* @param projectLibrary The framework to use
* @param theme Theme to use
*/
public async chooseActionLoop(projectLibrary: ProjectLibrary) {
const taskContext: PromptTaskContext = { projectLibrary };
const runner = new TaskRunner(taskContext);
runner.addTask(this.chooseActionTask);
while (!runner.done) {
await runner.run();
}
}
/** Install packages and run project */
protected abstract completeAndRun(port?: number);
/** Upgrade packages to use private Infragistics feed */
protected abstract upgradePackages();
/**
* Get user name and set template's extra configurations if any
* @param projectLibrary to add component to
* @param component to get template for
*/
protected abstract templateSelectedTask(type?: "component" | "view"): Task<PromptTaskContext>;
/**
* Gets the user input according to provided `options`.Returns directly if single choice is provided.
* @param options to use for the user input
* @param withBackChoice Add a "Back" option to choices list
*/
protected async getUserInput(options: IUserInputOptions, withBackChoice: boolean = false): Promise<string> {
if (options.choices) {
if (options.choices.length < 2) {
// single choice to return:
let choice = options.choices[0];
choice = choice.value || choice;
this.logAutoSelected(options, choice);
return choice;
}
if (withBackChoice) {
options.choices.push(WIZARD_BACK_OPTION);
}
options.choices = this.addSeparators(options.choices);
}
const userInput = await inquirer.prompt(options);
const result = userInput[options.name] as string;
// post to GA everything but 'Back' user choice
if (!withBackChoice || result !== WIZARD_BACK_OPTION) {
GoogleAnalytics.post({
t: "event",
ec: "$ig wizard",
el: options.message,
ea: `${options.name}: ${result}`
});
} else {
GoogleAnalytics.post({
t: "event",
ec: "$ig wizard",
el: result,
ea: `Back from ${options.name}`
});
}
return result;
}
/**
* Check if provided @param name is valid for project name
* @param name the name to check
* @param checkFolder check if folder with this name already exists
*/
protected nameIsValid(name: string, checkFolder = true): boolean {
if (!Util.isAlphanumericExt(name)) {
Util.log(""); /* new line */
Util.error(`Name '${name}' is not valid. `
+ "Name should start with a letter and can also contain numbers, dashes and spaces.",
"red");
return false;
}
if (checkFolder && Util.directoryExists(name)) {
Util.log(""); /* new line */
Util.error(`Folder "${name}" already exists!`, "red");
return false;
}
return true;
}
/** Returns the framework names, potentially filtered by config */
protected getFrameworkNames(): string[] {
let frameworksNames: string[] = [];
if (
this.config.stepByStep &&
this.config.stepByStep.frameworks &&
this.config.stepByStep.frameworks.length
) {
this.config.stepByStep.frameworks.forEach(x => {
const framework = this.templateManager.getFrameworkById(x);
if (framework) {
frameworksNames.push(framework.name);
}
});
}
if (!frameworksNames.length) {
// no config or wrong projTypes array:
frameworksNames = this.templateManager.getFrameworkNames();
}
return frameworksNames;
}
/**
* Gets the project library from the user input, or default if provided @param framework has single project library
* @param framework to get project library for
*/
protected async getProjectLibrary(framework: Framework): Promise<ProjectLibrary> {
let projectLibrary: ProjectLibrary;
const projectLibraries = this.getProjectLibNames(framework);
const projectRes = await this.getUserInput({
type: "list",
name: "projectType",
message: "Choose the type of project:",
choices: projectLibraries
});
projectLibrary = this.templateManager.getProjectLibraryByName(framework, projectRes);
return projectLibrary;
}
/**
* Gets project template from user input, or default if provided `projectLibrary` has a single template
* @param projectLibrary to get theme for
*/
protected async getProjectTemplate(projectLibrary: ProjectLibrary): Promise<ProjectTemplate> {
let projTemplate: ProjectTemplate;
const componentNameRes = await this.getUserInput({
type: "list",
name: "projTemplate",
message: "Choose project template:",
choices: Util.formatChoices(projectLibrary.projects)
});
projTemplate = projectLibrary.projects.find(x => x.name === componentNameRes);
return projTemplate;
}
/**
* Gets the theme from the user input, or default if provided @param projectLibrary has a single theme
* @param projectLibrary to get theme for
*/
protected async getTheme(projectLibrary: ProjectLibrary): Promise<string> {
let theme: string;
theme = await this.getUserInput({
type: "list",
name: "theme",
message: "Choose the theme for the project:",
choices: projectLibrary.themes,
default: projectLibrary.themes[0]
});
return theme;
}
/**
* Prompt user for template name with appropriate default
* @param template template to get name for
* @param type type of the name question
*/
protected async chooseTemplateName(template: Template, type: "component" | "view" = "component") {
const config = ProjectConfig.getConfig();
const availableDefaultName = Util.getAvailableName(template.name, false,
config.project.framework, config.project.projectType);
const templateName = await this.getUserInput({
type: "input",
name: `${type === "component" ? type : "customView"}Name`,
message: `Name your ${type}:`,
default: availableDefaultName,
validate: (input: string) => {
// TODO: GA post?
const name = Util.nameFromPath(input);
return this.nameIsValid(name, false);
}
});
return templateName;
}
/** Create prompts from template extra configuration and assign user answers to the template */
protected async customizeTemplateTask(template: Template) {
const extraPrompt: any[] = this.createQuestions(template.getExtraConfiguration());
const extraConfigAnswers = await inquirer.prompt(extraPrompt);
const extraConfig = this.parseAnswers(extraConfigAnswers);
GoogleAnalytics.post({
t: "event",
ec: "$ig wizard",
el: "Extra configuration:",
ea: `extra configuration: ${JSON.stringify(extraConfig)}`
});
template.setExtraConfiguration(extraConfig);
}
/**
* Returns a new array with inquirer.Separator() added between items
* @param array The original array to add separator to
*/
private addSeparators(array: any[]): any[] {
const newArray = [];
for (let i = 0; i < array.length; i++) {
newArray.push(array[i]);
if (i + 1 < array.length) {
newArray.push(new inquirer.Separator());
}
}
if (array.length > 4) {
// additional separator after last item for lists that wrap around
newArray.push(new inquirer.Separator(new Array(15).join("=")));
}
return newArray;
}
/**
* Generate questions from extra configuration array
* @param extraConfig
*/
private createQuestions(extraConfig: ControlExtraConfiguration[]): any {
const result = [];
for (const element of extraConfig) {
const currExtraConfig = {};
switch (element.type) {
case ControlExtraConfigType.Choice:
currExtraConfig["type"] = "list";
break;
case ControlExtraConfigType.MultiChoice:
currExtraConfig["type"] = "checkbox";
break;
case ControlExtraConfigType.Value:
default:
currExtraConfig["type"] = "input";
break;
}
currExtraConfig["default"] = element.default;
currExtraConfig["message"] = element.message;
currExtraConfig["name"] = element.key;
currExtraConfig["choices"] = element.choices;
result.push(currExtraConfig);
}
return result;
}
/**
* Conversion placeholder
* @param answers
*/
private parseAnswers(answers: {}): {} {
return answers;
}
/**
* Task to pick action and load consecutive tasks
* @param projectLibrary to add component to
*/
private chooseActionTask: Task<PromptTaskContext> = async (runner, context) => {
Util.log(""); /* new line */
const action: string = await this.getUserInput({
type: "list",
name: "action",
message: "Choose an action:",
choices: this.generateActionChoices(context.projectLibrary),
default: "Complete & Run"
});
runner.clearPending();
switch (action) {
/* istanbul ignore next */
case "Add all":
// internal testing only
runner.addTask(async (_runner, _context) => {
const templateTask = this.templateSelectedTask();
for (const template of _context.projectLibrary.templates) {
_context.template = template;
await templateTask(_runner, _context);
}
return true;
});
runner.addTask(run => Promise.resolve(run.resetTasks()));
break;
case "Add component":
runner.addTask(this.getComponentGroupTask);
runner.addTask(this.getComponentTask);
runner.addTask(this.getTemplateTask);
runner.addTask(this.templateSelectedTask());
runner.addTask(run => Promise.resolve(run.resetTasks()));
break;
case "Add scenario":
runner.addTask(this.getCustomViewTask);
runner.addTask(this.templateSelectedTask("view"));
runner.addTask(run => Promise.resolve(run.resetTasks()));
break;
case "Complete & Run":
const config = ProjectConfig.localConfig();
if (config.project.framework === "angular" &&
config.project.projectType === "igx-ts" &&
!config.packagesInstalled) {
// TODO: should we add check if there are paid components at all
Util.log("The project will be created using a Trial version of Ignite UI for Angular.");
Util.log("You can always run the upgrade-packages command once it's created.");
const shouldUpgrade = await this.getUserInput({
type: "list",
name: "shouldUpgrade",
message: "Would you like to upgrade to the licensed feed now?",
choices: [
{ value: "yes", name: "Yes (requires active subscription)", short: "Yes" },
{ value: "no", name: "Skip for now", short: "Skip" }
],
default: "yes"
});
if (shouldUpgrade === "yes") {
await this.upgradePackages();
}
}
const defaultPort = config.project.defaultPort;
const port = await this.getUserInput({
type: "input",
name: "port",
message: "Choose app host port:",
default: defaultPort,
validate: (input: string) => {
if (!Number(input)) {
Util.log(""); /* new line */
Util.error(`port should be a number. Input valid port or use the suggested default port`, "red");
return false;
}
return true;
}
});
config.project.defaultPort = parseInt(port, 10);
ProjectConfig.setConfig(config);
await this.completeAndRun(config.project.defaultPort);
break;
}
return true;
}
/**
* Get component group from user input
* @param projectLibrary to add component to
*/
private getComponentGroupTask: Task<PromptTaskContext> = async (_runner, context) => {
const groups = context.projectLibrary.getComponentGroupNames();
const groupRes: string = await this.getUserInput({
type: "list",
name: "componentGroup",
message: "Choose a group:",
choices: Util.formatChoices(context.projectLibrary.getComponentGroups()),
default: groups.find(x => x.includes("Grids")) || groups[0]
}, true);
if (groupRes === WIZARD_BACK_OPTION) {
return WIZARD_BACK_OPTION;
}
context.group = groupRes;
return true;
}
/**
* Get component in the selected components group
* @param projectLibrary to add component to
* @param groupName to chose components from
*/
private getComponentTask: Task<PromptTaskContext> = async (_runner, context) => {
const componentNameRes = await this.getUserInput({
type: "list",
name: "component",
message: "Choose a component:",
choices: Util.formatChoices(context.projectLibrary.getComponentsByGroup(context.group))
}, true);
if (componentNameRes === WIZARD_BACK_OPTION) {
return WIZARD_BACK_OPTION;
}
context.component = context.projectLibrary.getComponentByName(componentNameRes);
return true;
}
/**
* Get template for selected component
* @param projectLibrary to add component to
* @param component to get template for
*/
private getTemplateTask: Task<PromptTaskContext> = async (_runner, context) => {
let selectedTemplate: Template;
const templates: Template[] = context.component.templates;
const templateRes = await this.getUserInput({
type: "list",
name: "template",
message: "Choose one:",
choices: Util.formatChoices(templates)
}, true);
if (templateRes === WIZARD_BACK_OPTION) {
return WIZARD_BACK_OPTION;
}
selectedTemplate = templates.find((value, i, obj) => {
return value.name === templateRes;
});
if (selectedTemplate) {
context.template = selectedTemplate;
return true;
}
return false;
}
/**
* Get template for custom view from user input
* @param projectLibrary to add component to
* @param theme to use to style the project
*/
private getCustomViewTask: Task<PromptTaskContext> = async (_runner, context) => {
const customTemplates: Template[] = context.projectLibrary.getCustomTemplates();
const customTemplateNameRes = await this.getUserInput({
type: "list",
name: "customTemplate",
message: "Choose custom view:",
choices: Util.formatChoices(customTemplates)
}, true);
if (customTemplateNameRes === WIZARD_BACK_OPTION) {
return WIZARD_BACK_OPTION;
}
const selectedTemplate = customTemplates.find((value, i, obj) => {
return customTemplateNameRes === value.name;
});
if (selectedTemplate) {
context.template = selectedTemplate;
return true;
}
return false;
}
private logAutoSelected(options: IUserInputOptions, choice: any) {
let text;
switch (options.name) {
case "framework":
text = ` Framework`;
break;
case "projectType":
text = ` Project type`;
break;
case "projTemplate":
text = ` Proj Template`;
break;
case "theme":
text = ` Theme`;
break;
default:
return;
//TODO: text = ` ${options.name}`;
}
GoogleAnalytics.post({
t: "event",
ec: "$ig wizard",
el: options.message,
ea: `${options.name}: ${choice}`
});
Util.log(`${text}: ${choice}`);
}
/** Returns the projectLibraries names, potentially filtered by config */
private getProjectLibNames(framework: Framework): string[] {
let projectLibraries: string[] = [];
const frameworkConfig = this.config.stepByStep && this.config.stepByStep[framework.id as FrameworkId];
if (frameworkConfig && frameworkConfig.projTypes && frameworkConfig.projTypes.length) {
frameworkConfig.projTypes.forEach(x => {
const projLib = framework.projectLibraries.find(p => p.projectType === x);
if (projLib) {
projectLibraries.push(projLib.name);
}
});
}
if (!projectLibraries.length) {
// no config or wrong projTypes array:
projectLibraries = this.templateManager.getProjectLibraryNames(framework.id);
}
return projectLibraries;
}
/**
* Generates a list of options for chooseActionLoop
* @param projectLibrary to generate options for
*/
private generateActionChoices(projectLibrary: ProjectLibrary): Array<{}> {
const actionChoices: ChoiceItem[] = [
{ name: "Complete & Run", description: "install packages and run in the default browser" }
];
/* istanbul ignore next */
if (App.testMode) {
// internal testing only
actionChoices.push({ name: "Add all", description: "add all components/views" });
}
if (projectLibrary.components.length > 0) {
actionChoices.push({ name: "Add component", description: "add a specific component view (e.g a grid)" });
}
if (projectLibrary.getCustomTemplateNames().length > 0) {
actionChoices.push({ name: "Add scenario", description: "add a predefined scenario view (e.g grid or dashboard)" });
}
return Util.formatChoices(actionChoices, 10);
}
}
/** Options for User Input */
export interface IUserInputOptions {
type: string;
name: string;
message: string;
choices?: any[];
default?: any;
validate?: (input: string) => string | boolean;
}
/** Context type for prompt tasks */
export interface PromptTaskContext {
projectLibrary: ProjectLibrary;
group?: string;
component?: Component;
template?: Template;
name?: string;
} | the_stack |
import { Value, Tag, valueTag, CompressedJSON } from "./CompressedJSON";
import { assertNever, defined, panic, assert } from "../support/Support";
import { TypeBuilder } from "../TypeBuilder";
import { UnionBuilder, UnionAccumulator } from "../UnionBuilder";
import {
ClassProperty,
transformedStringTypeTargetTypeKindsMap,
UnionType,
ClassType,
MapType,
ArrayType
} from "../Type";
import { TypeAttributes, emptyTypeAttributes } from "../attributes/TypeAttributes";
import { StringTypes, inferTransformedStringTypeKindForString } from "../attributes/StringTypes";
import { TypeRef, derefTypeRef } from "../TypeGraph";
import { messageError } from "../Messages";
import { nullableFromUnion } from "../TypeUtils";
// This should be the recursive type
// Value[] | NestedValueArray[]
// but TypeScript doesn't support that.
export type NestedValueArray = any;
function forEachArrayInNestedValueArray(va: NestedValueArray, f: (va: Value[]) => void): void {
if (va.length === 0) {
return;
}
if (Array.isArray(va[0])) {
for (const x of va) {
forEachArrayInNestedValueArray(x, f);
}
} else {
f(va);
}
}
function forEachValueInNestedValueArray(va: NestedValueArray, f: (v: Value) => void): void {
forEachArrayInNestedValueArray(va, a => {
for (const x of a) {
f(x);
}
});
}
class InferenceUnionBuilder extends UnionBuilder<TypeBuilder, NestedValueArray, NestedValueArray> {
constructor(
typeBuilder: TypeBuilder,
private readonly _typeInference: TypeInference,
private readonly _fixed: boolean
) {
super(typeBuilder);
}
protected makeObject(
objects: NestedValueArray,
typeAttributes: TypeAttributes,
forwardingRef: TypeRef | undefined
): TypeRef {
return this._typeInference.inferClassType(typeAttributes, objects, this._fixed, forwardingRef);
}
protected makeArray(
arrays: NestedValueArray,
typeAttributes: TypeAttributes,
forwardingRef: TypeRef | undefined
): TypeRef {
return this.typeBuilder.getArrayType(
typeAttributes,
this._typeInference.inferType(emptyTypeAttributes, arrays, this._fixed, forwardingRef)
);
}
}
function canBeEnumCase(_s: string): boolean {
return true;
}
export type Accumulator = UnionAccumulator<NestedValueArray, NestedValueArray>;
export class TypeInference {
private _refIntersections: [TypeRef, string[]][] | undefined;
constructor(
private readonly _cjson: CompressedJSON<unknown>,
private readonly _typeBuilder: TypeBuilder,
private readonly _inferMaps: boolean,
private readonly _inferEnums: boolean
) {}
addValuesToAccumulator(valueArray: NestedValueArray, accumulator: Accumulator): void {
forEachValueInNestedValueArray(valueArray, value => {
const t = valueTag(value);
switch (t) {
case Tag.Null:
accumulator.addPrimitive("null", emptyTypeAttributes);
break;
case Tag.False:
case Tag.True:
accumulator.addPrimitive("bool", emptyTypeAttributes);
break;
case Tag.Integer:
accumulator.addPrimitive("integer", emptyTypeAttributes);
break;
case Tag.Double:
accumulator.addPrimitive("double", emptyTypeAttributes);
break;
case Tag.InternedString:
if (this._inferEnums) {
const s = this._cjson.getStringForValue(value);
if (canBeEnumCase(s)) {
accumulator.addStringCase(s, 1, emptyTypeAttributes);
} else {
accumulator.addStringType("string", emptyTypeAttributes);
}
} else {
accumulator.addStringType("string", emptyTypeAttributes);
}
break;
case Tag.UninternedString:
accumulator.addStringType("string", emptyTypeAttributes);
break;
case Tag.Object:
accumulator.addObject(this._cjson.getObjectForValue(value), emptyTypeAttributes);
break;
case Tag.Array:
accumulator.addArray(this._cjson.getArrayForValue(value), emptyTypeAttributes);
break;
case Tag.StringFormat: {
const kind = this._cjson.getStringFormatTypeKind(value);
accumulator.addStringType(
"string",
emptyTypeAttributes,
new StringTypes(new Map(), new Set([kind]))
);
break;
}
case Tag.TransformedString: {
const s = this._cjson.getStringForValue(value);
const kind = inferTransformedStringTypeKindForString(s, this._cjson.dateTimeRecognizer);
if (kind === undefined) {
return panic("TransformedString does not have a kind");
}
const producer = defined(transformedStringTypeTargetTypeKindsMap.get(kind)).attributesProducer;
if (producer === undefined) {
return panic("TransformedString does not have attribute producer");
}
accumulator.addStringType("string", producer(s), new StringTypes(new Map(), new Set([kind])));
break;
}
default:
return assertNever(t);
}
});
}
inferType(
typeAttributes: TypeAttributes,
valueArray: NestedValueArray,
fixed: boolean,
forwardingRef?: TypeRef
): TypeRef {
const accumulator = this.accumulatorForArray(valueArray);
return this.makeTypeFromAccumulator(accumulator, typeAttributes, fixed, forwardingRef);
}
private resolveRef(ref: string, topLevel: TypeRef): TypeRef {
if (!ref.startsWith("#/")) {
return messageError("InferenceJSONReferenceNotRooted", { reference: ref });
}
const parts = ref.split("/").slice(1);
const graph = this._typeBuilder.typeGraph;
let tref = topLevel;
for (const part of parts) {
let t = derefTypeRef(tref, graph);
if (t instanceof UnionType) {
const nullable = nullableFromUnion(t);
if (nullable === null) {
// FIXME: handle unions
return messageError("InferenceJSONReferenceToUnion", { reference: ref });
}
t = nullable;
}
if (t instanceof ClassType) {
const cp = t.getProperties().get(part);
if (cp === undefined) {
return messageError("InferenceJSONReferenceWrongProperty", { reference: ref });
}
tref = cp.typeRef;
} else if (t instanceof MapType) {
tref = t.values.typeRef;
} else if (t instanceof ArrayType) {
if (part.match("^[0-9]+$") === null) {
return messageError("InferenceJSONReferenceInvalidArrayIndex", { reference: ref });
}
tref = t.items.typeRef;
} else {
return messageError("InferenceJSONReferenceWrongProperty", { reference: ref });
}
}
return tref;
}
inferTopLevelType(typeAttributes: TypeAttributes, valueArray: NestedValueArray, fixed: boolean): TypeRef {
assert(this._refIntersections === undefined, "Didn't reset ref intersections - nested invocations?");
if (this._cjson.handleRefs) {
this._refIntersections = [];
}
const topLevel = this.inferType(typeAttributes, valueArray, fixed);
if (this._cjson.handleRefs) {
for (const [tref, refs] of defined(this._refIntersections)) {
const resolved = refs.map(r => this.resolveRef(r, topLevel));
this._typeBuilder.setSetOperationMembers(tref, new Set(resolved));
}
this._refIntersections = undefined;
}
return topLevel;
}
accumulatorForArray(valueArray: NestedValueArray): Accumulator {
const accumulator = new UnionAccumulator<NestedValueArray, NestedValueArray>(true);
this.addValuesToAccumulator(valueArray, accumulator);
return accumulator;
}
makeTypeFromAccumulator(
accumulator: Accumulator,
typeAttributes: TypeAttributes,
fixed: boolean,
forwardingRef?: TypeRef
): TypeRef {
const unionBuilder = new InferenceUnionBuilder(this._typeBuilder, this, fixed);
return unionBuilder.buildUnion(accumulator, false, typeAttributes, forwardingRef);
}
inferClassType(
typeAttributes: TypeAttributes,
objects: NestedValueArray,
fixed: boolean,
forwardingRef?: TypeRef
): TypeRef {
const propertyNames: string[] = [];
const propertyValues: { [name: string]: Value[] } = {};
forEachArrayInNestedValueArray(objects, arr => {
for (let i = 0; i < arr.length; i += 2) {
const key = this._cjson.getStringForValue(arr[i]);
const value = arr[i + 1];
if (!Object.prototype.hasOwnProperty.call(propertyValues, key)) {
propertyNames.push(key);
propertyValues[key] = [];
}
propertyValues[key].push(value);
}
});
if (this._cjson.handleRefs && propertyNames.length === 1 && propertyNames[0] === "$ref") {
const values = propertyValues["$ref"];
if (values.every(v => valueTag(v) === Tag.InternedString)) {
const allRefs = values.map(v => this._cjson.getStringForValue(v));
// FIXME: Add is-ref attribute
const tref = this._typeBuilder.getUniqueIntersectionType(typeAttributes, undefined);
defined(this._refIntersections).push([tref, allRefs]);
return tref;
}
}
if (this._inferMaps && propertyNames.length > 500) {
const accumulator = new UnionAccumulator<NestedValueArray, NestedValueArray>(true);
for (const key of propertyNames) {
this.addValuesToAccumulator(propertyValues[key], accumulator);
}
const values = this.makeTypeFromAccumulator(accumulator, emptyTypeAttributes, fixed);
return this._typeBuilder.getMapType(typeAttributes, values, forwardingRef);
}
const properties = new Map<string, ClassProperty>();
for (const key of propertyNames) {
const values = propertyValues[key];
const t = this.inferType(emptyTypeAttributes, values, false);
const isOptional = values.length < objects.length;
properties.set(key, this._typeBuilder.makeClassProperty(t, isOptional));
}
if (fixed) {
return this._typeBuilder.getUniqueClassType(typeAttributes, true, properties, forwardingRef);
} else {
return this._typeBuilder.getClassType(typeAttributes, properties, forwardingRef);
}
}
} | the_stack |
import kleur from 'kleur';
import ora from 'ora';
import type { OutputAsset, OutputChunk, RollupOutput } from 'rollup';
import {
ensureLeadingSlash,
HeadAttrsConfig,
HeadConfig,
removeEndingSlash,
removeLeadingSlash,
ServerEntryModule,
ServerPage,
SiteOptions,
} from '../../../../shared';
import { fs, path } from '../../../utils';
import { logger, LoggerIcon } from '../../../utils/logger';
import type { App } from '../../App';
import { resolvePages } from '../../create/resolvePages';
import { bundle } from './bundle';
export async function build(app: App): Promise<void> {
const startTime = Date.now();
const spinner = ora();
logger.info(kleur.bold(kleur.cyan(`vitebook@${app.version}\n`)));
// Resolve pages
spinner.start(kleur.bold('Resolving pages...'));
await resolvePages(app, 'add');
spinner.stop();
const includesHomePage = () => app.pages.find((page) => page.route === '/');
if (app.pages.length === 0) {
logger.info(kleur.bold(`❓ No pages were resolved\n`));
return;
}
// Render pages
spinner.start(
kleur.bold(
`Rendering ${app.pages.length + (includesHomePage() ? 0 : 1)} pages...`,
),
);
try {
const [clientBundle] = await bundle(app);
const APP_CHUNK = clientBundle.output.find(
(chunk) => chunk.type === 'chunk' && chunk.isEntry,
) as OutputChunk;
const CSS_CHUNK = clientBundle.output.find(
(chunk) => chunk.type === 'asset' && chunk.fileName.endsWith('.css'),
) as OutputAsset;
const HTML_TEMPLATE = (
await fs.readFile(app.dirs.config.resolve('index.html'), 'utf-8')
).replace('{{ version }}', app.version);
const SSR_MANIFEST = JSON.parse(
await fs.readFile(app.dirs.out.resolve('ssr-manifest.json'), 'utf-8'),
);
const serverEntryPath = app.dirs.out.resolve('server', 'entry-server.cjs');
await fs.rename(
app.dirs.out.resolve(
'server',
path.changeExt(path.basename(app.client.entry.server), 'js'),
),
serverEntryPath,
);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { render } = require(app.dirs.out.resolve(
'server',
serverEntryPath,
)) as ServerEntryModule;
// Include home page so it's rendered (if not included).
if (!includesHomePage()) {
// @ts-expect-error - only the route is required
app.pages.unshift({ route: '/' });
}
for (const page of app.pages) {
const { context, html, head } = await render(page);
const stylesheetLinks = [CSS_CHUNK.fileName]
.map((fileName) => createLinkTag(app, 'stylesheet', fileName))
.filter((tag) => tag.length > 0)
.join('\n ');
const pageImports = resolvePageImports(
app,
page,
clientBundle,
APP_CHUNK,
);
const manifestImports = resolveImportsFromManifest(
context.modules,
SSR_MANIFEST,
);
const preloadLinks = Array.from(
new Set([...manifestImports, ...pageImports.imports]),
)
.map((fileName) => createPreloadTag(app, fileName))
.join('\n ');
const prefetchLinks = pageImports.dynamicImports
.map((fileName) => createLinkTag(app, 'prefetch', fileName))
.join('\n ');
const headTags = [
addSocialTags(app.site.options, page, context.head)
.map(renderHeadTag)
.join('\n '),
head,
stylesheetLinks,
preloadLinks,
prefetchLinks,
]
.filter((t) => t.length > 0)
.join('\n ');
const appScriptTag = `<script type="module" src="${app.site.options.baseUrl}${APP_CHUNK.fileName}" defer></script>`;
const pageHtml = HTML_TEMPLATE.replace('{{ lang }}', context.lang)
.replace(`<!--@vitebook/head-->`, headTags)
.replace(`<!--@vitebook/app-->`, html)
.replace('<!--@vitebook/body-->', appScriptTag);
const decodedRoute = decodeURI(page.route);
const filePath = decodedRoute === '/' ? '/index.html' : decodedRoute;
const outputPath = app.dirs.out.resolve(filePath.slice(1));
await fs.ensureFile(outputPath);
await fs.writeFile(outputPath, pageHtml);
}
if (!app.env.isDebug) {
await fs.remove(app.dirs.out.resolve('server'));
await fs.unlink(app.dirs.out.resolve('ssr-manifest.json'));
}
} catch (e) {
spinner.stopAndPersist({
symbol: LoggerIcon.Error,
});
throw e;
} finally {
// ...
}
spinner.stopAndPersist({
symbol: LoggerIcon.Success,
text: kleur.bold(`Rendered ${kleur.underline(app.pages.length)} pages`),
});
logRoutes(app);
const endTime = ((Date.now() - startTime) / 1000).toFixed(2);
const speedIcon = {
2: '🤯',
4: '🏎️',
6: '🏃',
10: '🐌',
Infinity: '⚰️',
};
logger.success(
kleur.bold(
`${LoggerIcon.Success} Build complete in ${kleur.bold(
kleur.underline(`${endTime}s`),
)} ${speedIcon[Object.keys(speedIcon).find((t) => endTime <= t)!]}`,
),
);
const pkgManager = guessPackageManager(app);
const previewCommand = await findPreviewScriptName(app);
logger.success(
kleur.bold(
`\n⚡ ${
previewCommand
? `Run \`${
pkgManager === 'npm' ? 'npm run' : pkgManager
} ${previewCommand}\` to serve production build`
: 'Ready for preview'
}\n`,
),
);
}
function logRoutes(app: App) {
const logs: string[] = [''];
app.pages.forEach((page) => {
logs.push(
kleur.white(
`- ${removeLeadingSlash(
page.route === '/' ? 'index.html' : decodeURI(page.route),
)} ${kleur.dim(
page.rootPath ? `(${removeLeadingSlash(page.rootPath)})` : '',
)}`,
),
);
});
logger.info(logs.join('\n'), '\n');
}
function guessPackageManager(app: App): 'npm' | 'yarn' | 'pnpm' {
if (fs.existsSync(app.dirs.root.resolve('pnpm-lock.yaml'))) {
return 'pnpm';
}
if (fs.existsSync(app.dirs.root.resolve('yarn.lock'))) {
return 'yarn';
}
return 'npm';
}
async function findPreviewScriptName(app: App): Promise<string | undefined> {
try {
const packageJson = app.dirs.root.resolve('package.json');
if (fs.existsSync(packageJson)) {
const content = (await fs.readFile(packageJson)).toString();
const json = JSON.parse(content);
const script = Object.keys(json.scripts ?? {}).find((script) => {
return json.scripts[script].includes('vitebook preview');
});
return script;
}
} catch (e) {
//
}
return undefined;
}
function createLinkTag(app: App, rel: string, fileName?: string) {
if (!fileName) return '';
const base = removeEndingSlash(app.site.options.baseUrl);
const href = `${base}${ensureLeadingSlash(fileName)}`;
return `<link rel="${rel}" href="${href}">`;
}
function createPreloadTag(app: App, fileName?: string) {
if (!fileName) return '';
const base = removeEndingSlash(app.site.options.baseUrl);
const href = `${base}${ensureLeadingSlash(fileName)}`;
if (fileName.endsWith('.js')) {
return `<link rel="modulepreload" crossorigin href="${href}">`;
} else if (fileName.endsWith('.css')) {
return `<link rel="stylesheet" href="${href}">`;
} else if (fileName.endsWith('.woff')) {
return ` <link rel="preload" href="${href}" as="font" type="font/woff" crossorigin>`;
} else if (fileName.endsWith('.woff2')) {
return ` <link rel="preload" href="${href}" as="font" type="font/woff2" crossorigin>`;
} else if (fileName.endsWith('.gif')) {
return ` <link rel="preload" href="${href}" as="image" type="image/gif">`;
} else if (fileName.endsWith('.jpg') || fileName.endsWith('.jpeg')) {
return ` <link rel="preload" href="${href}" as="image" type="image/jpeg">`;
} else if (fileName.endsWith('.png')) {
return ` <link rel="preload" href="${href}" as="image" type="image/png">`;
}
return '';
}
function resolveImportsFromManifest(
modules: Set<string>,
manifest: Record<string, string[]>,
) {
const imports = new Set<string>();
for (const filename of modules) {
manifest[filename]?.forEach((file) => {
imports.add(file);
});
}
return Array.from(imports);
}
function resolvePageImports(
app: App,
page: ServerPage,
clientBundle: RollupOutput,
appChunk: OutputChunk,
) {
const srcPath = fs.realpathSync(app.dirs.root.relative(page.rootPath ?? ''));
const pageChunk = clientBundle.output.find(
(chunk) => chunk.type === 'chunk' && chunk.facadeModuleId === srcPath,
) as OutputChunk;
return {
imports: Array.from(
new Set([...appChunk.imports, ...(pageChunk?.imports ?? [])]),
),
dynamicImports: Array.from(
new Set([
// Needs to be filtered.
// ...appChunk.dynamicImports,
...(pageChunk?.dynamicImports ?? []),
]),
),
};
}
function renderHeadTag([tag, attrs, innerHTML = '']: HeadConfig): string {
const openTag = `<${tag}${renderHeadAttrs(attrs)}>`;
if (tag === 'link' || tag === 'meta' || tag === 'base') {
return openTag;
}
return `${openTag}${innerHTML}</${tag}>`;
}
function renderHeadAttrs(attrs: HeadAttrsConfig): string {
return Object.entries(attrs)
.filter((item): item is [string, string | true] => item[1] !== false)
.map(([key, value]) =>
value === true ? ` ${key}` : ` ${key}="${attrs[key]}"`,
)
.join('');
}
function addSocialTags(
site: SiteOptions,
page: ServerPage,
head: HeadConfig[],
): HeadConfig[] {
const pageTitle: string =
head.find((tag) => tag[0] === 'title')?.[2] ?? site.title;
const pageDescription: string =
(head.find(
(tag) => tag[0] === 'meta' && tag[1]?.name === 'description',
)?.[1]?.content as string) ?? site.description;
const tags: HeadConfig[] = [
['meta', { property: 'og:site_name', content: site.title }],
['meta', { property: 'og:title', content: pageTitle }],
['meta', { property: 'og:description', content: pageDescription }],
['meta', { property: 'twitter:title', content: pageTitle }],
['meta', { property: 'twitter:description', content: pageDescription }],
];
head.push(
...tags.filter(
(tag) =>
!head.some(
(headTag) =>
headTag[0] === 'meta' && headTag[1]?.property === tag[1].property,
),
),
);
return head;
} | the_stack |
import {
AppInstanceJson,
JSONSerializer,
GenericConditionalTransferAppName,
ConditionalTransferAppNames,
} from "@connext/types";
import { getSignerAddressFromPublicIdentifier, safeJsonParse } from "@connext/utils";
import { constants } from "ethers";
import { EntityRepository, Repository } from "typeorm";
import { AppInstance, AppType } from "./appInstance.entity";
const { HashZero } = constants;
export const AppInstanceSerializer: JSONSerializer<AppInstance, AppInstanceJson> = class {
static toJSON(app: AppInstance): AppInstanceJson | undefined {
if (!app) {
return undefined;
}
const json: AppInstanceJson = {
appDefinition: app.appDefinition,
abiEncodings: {
stateEncoding: app.stateEncoding,
actionEncoding: app.actionEncoding,
},
appSeqNo: app.appSeqNo,
defaultTimeout: app.defaultTimeout,
identityHash: app.identityHash,
latestState: app.latestState,
stateTimeout: app.stateTimeout,
latestVersionNumber: app.latestVersionNumber,
multisigAddress: app.channel.multisigAddress,
outcomeType: app.outcomeType,
initiatorIdentifier: app.initiatorIdentifier,
responderIdentifier: app.responderIdentifier,
outcomeInterpreterParameters: safeJsonParse(app.outcomeInterpreterParameters),
meta: app.meta,
initiatorDeposit: (app.initiatorDeposit || 0).toString(),
initiatorDepositAssetId: app.initiatorDepositAssetId,
responderDeposit: (app.responderDeposit || 0).toString(),
responderDepositAssetId: app.responderDepositAssetId,
};
return json;
}
};
@EntityRepository(AppInstance)
export class AppInstanceRepository extends Repository<AppInstance> {
findByIdentityHash(identityHash: string): Promise<AppInstance | undefined> {
return this.findOne({
where: { identityHash },
relations: ["channel"],
});
}
async findByIdentityHashOrThrow(identityHash: string): Promise<AppInstance> {
const app = await this.findByIdentityHash(identityHash);
if (!app) {
throw new Error(`Could not find app with identity hash ${identityHash}`);
}
return app;
}
findByMultisigAddressAndType(multisigAddress: string, type: AppType): Promise<AppInstance[]> {
return this.createQueryBuilder("app_instances")
.leftJoinAndSelect(
"app_instances.channel",
"channel",
"channel.multisigAddress = :multisigAddress",
{ multisigAddress },
)
.where("app_instance.type = :type", { type })
.getMany();
}
findByIdentityHashAndType(identityHash: string, type: AppType): Promise<AppInstance | undefined> {
return this.findOne({
where: { identityHash, type },
relations: ["channel"],
});
}
async getAppProposal(appIdentityHash: string): Promise<AppInstanceJson | undefined> {
const app = await this.findByIdentityHashAndType(appIdentityHash, AppType.PROPOSAL);
return AppInstanceSerializer.toJSON(app);
}
async getFreeBalance(multisigAddress: string): Promise<AppInstanceJson | undefined> {
const [app] = await this.findByMultisigAddressAndType(multisigAddress, AppType.FREE_BALANCE);
return app && AppInstanceSerializer.toJSON(app);
}
async getAppInstance(appIdentityHash: string): Promise<AppInstanceJson | undefined> {
const app = await this.findByIdentityHashAndType(appIdentityHash, AppType.INSTANCE);
return AppInstanceSerializer.toJSON(app);
}
async findInstalledAppsByAppDefinition(
multisigAddress: string,
appDefinition: string,
): Promise<AppInstance[]> {
return this.createQueryBuilder("app_instances")
.leftJoinAndSelect("app_instances.channel", "channel")
.where("channel.multisigAddress = :multisigAddress", { multisigAddress })
.where("app_instances.type = :type", { type: AppType.INSTANCE })
.andWhere("app_instances.appDefinition = :appDefinition", { appDefinition })
.getMany();
}
async findTransferAppsByAppDefinitionPaymentIdAndType(
paymentId: string,
appDefinition: string,
type: AppType = AppType.INSTANCE,
): Promise<AppInstance[]> {
const res = await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.andWhere(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere("app_instance.type = :type", { type })
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
.getMany();
return res;
}
findTransferAppByPaymentIdAndSender<
T extends ConditionalTransferAppNames = typeof GenericConditionalTransferAppName
>(paymentId: string, senderSignerAddress: string): Promise<AppInstance<T> | undefined> {
return this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.where(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",0,"to"}' = '"${senderSignerAddress}"'`,
)
.getOne() as Promise<AppInstance<T> | undefined>;
}
async findTransferAppByAppDefinitionPaymentIdAndSender(
paymentId: string,
senderIdentifier: string,
appDefinition: string,
): Promise<AppInstance | undefined> {
const senderAddress = getSignerAddressFromPublicIdentifier(senderIdentifier);
return await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.andWhere(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",0,"to"}' = '"${senderAddress}"'`,
)
.getOne();
}
async findTransferAppByAppDefinitionPaymentIdAndReceiver(
paymentId: string,
receiverIdentifier: string,
appDefinition: string,
): Promise<AppInstance | undefined> {
const receiverAddress = getSignerAddressFromPublicIdentifier(receiverIdentifier);
return await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.andWhere(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
// receiver is recipient
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",1,"to"}' = '"${receiverAddress}"'`,
)
.getOne();
}
findTransferAppsByChannelUserIdentifierAndReceiver<
T extends ConditionalTransferAppNames = typeof GenericConditionalTransferAppName
>(userIdentifier: string, receiverSignerAddress: string): Promise<AppInstance<T>[] | []> {
return this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.where("channel.userIdentifier = :userIdentifier", { userIdentifier })
.andWhere(`app_instance."meta"::JSONB #> '{ "paymentId" }' IS NOT NULL`)
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",1,"to"}' = '"${receiverSignerAddress}"'`,
)
.getMany() as Promise<AppInstance<T>[] | []>;
}
findTransferAppByPaymentIdAndReceiver<
T extends ConditionalTransferAppNames = typeof GenericConditionalTransferAppName
>(paymentId: string, receiverSignerAddress: string): Promise<AppInstance<T> | undefined> {
return this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.where(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",1,"to"}' = '"${receiverSignerAddress}"'`,
)
.getOne() as Promise<AppInstance<T>>;
}
async findRedeemedTransferAppByAppDefinitionPaymentIdFromNode(
paymentId: string,
nodeSignerAddress: string,
appDefinition: string,
): Promise<AppInstance | undefined> {
const res = await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
// if uninstalled, redeemed
.andWhere("app_instance.type = :type", { type: AppType.UNINSTALLED })
.andWhere(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
// node is sender
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",0,"to"}' = '"${nodeSignerAddress}"'`,
)
.getOne();
return res;
}
async findActiveTransferAppsByAppDefinitionToRecipient(
recipientIdentifier: string,
nodeSignerAddress: string,
appDefinition: string,
): Promise<AppInstance[]> {
const res = await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.andWhere("app_instance.type = :type", { type: AppType.INSTANCE })
// node is receiver of transfer
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",1,"to"}' = '"${nodeSignerAddress}"'`,
)
// meta for transfer recipient
.andWhere(`app_instance."meta"::JSONB @> '{"recipient":"${recipientIdentifier}"}'`)
// preImage is HashZero
.andWhere(`app_instance."latestState"::JSONB @> '{"preImage": "${HashZero}"}'`)
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
.getMany();
return res;
}
async findActiveTransferAppsByAppDefinitionFromSenderToNode(
senderSignerAddress: string,
nodeSignerAddress: string,
appDefinition: string,
): Promise<AppInstance[]> {
const res = await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.andWhere("app_instance.type = :type", { type: AppType.INSTANCE })
// sender is sender of transfer
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",0,"to"}' = '"${senderSignerAddress}"'`,
)
// node is receiver of transfer
.andWhere(
`app_instance."latestState"::JSONB #> '{"coinTransfers",1,"to"}' = '"${nodeSignerAddress}"'`,
)
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
// preimage can be HashZero or empty, if its HashZero, then the
// node should takeAction + uninstall. if its not HashZero, then
// the node should just uninstall. If the node has completed the
// transfer, then the type would be AppType.UNINSTALLED
.getMany();
return res;
}
async findTransferAppsByAppDefinitionAndPaymentId(
paymentId: string,
appDefinition: string,
): Promise<AppInstance[]> {
const res = await this.createQueryBuilder("app_instance")
.leftJoinAndSelect("app_instance.channel", "channel")
.leftJoinAndSelect("app_instance.transfer", "transfer")
.andWhere(`app_instance."meta"::JSONB @> '{ "paymentId": "${paymentId}" }'`)
.andWhere("app_instance.appDefinition = :appDefinition", { appDefinition })
.getMany();
return res;
}
} | the_stack |
import { Memoize } from '../src';
function sleep(time: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
describe('@Memoize()', () => {
// Date.now() is a bit too deterministic, as tests run so fast
// and use the same timestamp. We use a counter to increase uniqueness.
let count = 0;
class Test {
spy: jest.Mock;
constructor(spy: jest.Mock) {
this.spy = spy;
}
@Memoize()
get getter(): number {
this.spy();
return Date.now() + this.inc();
}
@Memoize()
noArgs(): number {
this.spy();
return Date.now() + this.inc();
}
@Memoize()
oneArg(a: string): string {
this.spy();
return a.toUpperCase();
}
@Memoize()
manyArgs(a: string, b: number, c: boolean): string {
this.spy();
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
return a + b + c;
}
@Memoize()
restArgs(...args: unknown[]): number {
this.spy();
return Date.now() + this.inc();
}
inc(): number {
count += 1;
return count;
}
}
it('errors if applied to a class', () => {
expect(() => {
// @ts-expect-error Allow decorator here
@Memoize()
class TestClass {}
return TestClass;
}).toThrowErrorMatchingSnapshot();
});
it('errors if applied to a property', () => {
expect(
() =>
class TestProp {
// @ts-expect-error Allow decorator here
@Memoize()
value = 123;
},
).toThrowErrorMatchingSnapshot();
});
it('errors if `cache` is not a map', () => {
expect(() => {
class TestClass {
// @ts-expect-error Allow decorator here
@Memoize({ cache: {} })
test() {}
}
return TestClass;
}).toThrowErrorMatchingSnapshot();
});
it('errors if `expires` is not a number', () => {
expect(() => {
class TestClass {
// @ts-expect-error Invalid type
@Memoize({ expires: 'abc' })
test() {}
}
return TestClass;
}).toThrowErrorMatchingSnapshot();
});
it('errors if `expires` is negative', () => {
expect(() => {
class TestClass {
@Memoize({ expires: -123 })
test() {}
}
return TestClass;
}).toThrowErrorMatchingSnapshot();
});
it('errors if `hasher` is not a function', () => {
expect(() => {
class TestClass {
// @ts-expect-error Invalid type
@Memoize({ hasher: 123 })
test() {}
}
return TestClass;
}).toThrowErrorMatchingSnapshot();
});
it('doesnt leak to separate instances', () => {
const spy1 = jest.fn();
const spy2 = jest.fn();
const a = new Test(spy1);
const b = new Test(spy2);
a.noArgs();
b.noArgs();
expect(spy1).toHaveBeenCalledTimes(1);
expect(spy2).toHaveBeenCalledTimes(1);
expect(a).not.toBe(b);
});
it('caches result for getters', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.getter;
const b = test.getter;
const c = test.getter;
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
});
it('caches result for 0 arguments', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.noArgs();
const b = test.noArgs();
const c = test.noArgs();
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
});
it('caches result for 1 argument', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.oneArg('abc');
const b = test.oneArg('abc');
const c = test.oneArg('abc');
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
const d = test.oneArg('xyz');
const e = test.oneArg('xyz');
expect(spy).toHaveBeenCalledTimes(2);
expect(d).not.toBe(a);
expect(e).toBe(d);
});
it('caches result for many arguments', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.manyArgs('abc', 1, true);
const b = test.manyArgs('abc', 1, true);
const c = test.manyArgs('abc', 1, true);
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
const d = test.manyArgs('abc', 1, false);
const e = test.manyArgs('abc', 2, true);
const f = test.manyArgs('xyz', 1, true);
const g = test.manyArgs('abc', 1, true);
expect(spy).toHaveBeenCalledTimes(4);
expect(d).not.toBe(a);
expect(e).not.toBe(a);
expect(f).not.toBe(a);
expect(g).toBe(a);
});
it('caches result for rest arguments', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.restArgs('abc', 1, true, {});
const b = test.restArgs('abc', 1, true, {});
const c = test.restArgs('abc', 1, true, {});
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
const d = test.restArgs('abc');
const e = test.restArgs('abc', 3);
const f = test.restArgs('xyz', 1, true, {}, []);
const g = test.restArgs('abc', 1, true, {});
expect(spy).toHaveBeenCalledTimes(4);
expect(d).not.toBe(a);
expect(e).not.toBe(a);
expect(f).not.toBe(a);
expect(g).toBe(a);
});
it('returns cache for same object argument structure', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.restArgs({ foo: 123 });
const b = test.restArgs({ foo: 123 });
const c = test.restArgs({ foo: 123 });
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
const d = test.restArgs({ foo: 456 });
const e = test.restArgs({ foo: 456 });
const f = test.restArgs({ bar: 'abc' });
expect(spy).toHaveBeenCalledTimes(3);
expect(d).not.toBe(a);
expect(e).toBe(d);
expect(f).not.toBe(a);
expect(f).not.toBe(e);
});
it('returns cache for same array argument structure', () => {
const spy = jest.fn();
const test = new Test(spy);
const a = test.restArgs([123]);
const b = test.restArgs([123]);
const c = test.restArgs([123]);
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
const d = test.restArgs([456]);
const e = test.restArgs([456]);
const f = test.restArgs(['abc']);
expect(spy).toHaveBeenCalledTimes(3);
expect(d).not.toBe(a);
expect(e).toBe(d);
expect(f).not.toBe(a);
expect(f).not.toBe(e);
});
describe('cache map', () => {
it('can provide a custom cache map', () => {
const spy = jest.fn();
const cache = new Map();
cache.set('[]', { value: 'pre-cached value' });
class TestCache {
@Memoize({ cache })
method() {
spy();
return 'value';
}
}
const test = new TestCache();
const a = test.method();
const b = test.method();
const c = test.method();
expect(spy).toHaveBeenCalledTimes(0);
expect(a).toBe('pre-cached value');
expect(b).toBe(a);
expect(c).toBe(a);
});
});
describe('hash function', () => {
function hasher() {
return 'always same key';
}
it('can provide a custom hash function', () => {
const spy = jest.fn();
class TestHash {
@Memoize({ hasher })
method(...args: unknown[]) {
spy();
return Date.now();
}
}
const test = new TestHash();
// Differents args (cache key), but same results
const a = test.method(1, 2, 3);
const b = test.method('a', 'b', 'c');
const c = test.method(1, 'a');
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
});
it('can provide a custom hash function by passing it directly to the decorator', () => {
const spy = jest.fn();
class TestHash {
@Memoize(hasher)
method(...args: unknown[]) {
spy();
return Date.now();
}
}
const test = new TestHash();
// Differents args (cache key), but same results
const a = test.method(1, 2, 3);
const b = test.method('a', 'b', 'c');
const c = test.method(1, 'a');
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
});
});
describe('expirations', () => {
it('will bypass cache when an expiration time has passed', async () => {
const spy = jest.fn();
class TestExpires {
@Memoize({ expires: 100 })
method() {
spy();
return Date.now();
}
}
const test = new TestExpires();
const a = test.method();
const b = test.method();
const c = test.method();
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
await sleep(110);
const d = test.method();
const e = test.method();
const f = test.method();
expect(spy).toHaveBeenCalledTimes(2);
expect(d).not.toBe(a);
expect(e).toBe(d);
expect(f).toBe(d);
});
});
describe('async/promises', () => {
class TestAsync extends Test {
@Memoize()
async resolvedPromise() {
this.spy();
const value = await Promise.resolve(Date.now());
return value;
}
@Memoize()
async rejectedPromise(): Promise<unknown> {
this.spy();
await Promise.resolve(Date.now());
throw new Error('Failed!');
}
}
it('caches and reuses the same promise', async () => {
const spy = jest.fn();
const test = new TestAsync(spy);
const a = test.resolvedPromise();
const b = test.resolvedPromise();
const c = test.resolvedPromise();
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
const result = await a;
await expect(b).resolves.toBe(result);
await expect(c).resolves.toBe(result);
const another = await test.resolvedPromise();
expect(spy).toHaveBeenCalledTimes(1);
expect(another).toBe(result);
});
it('deletes the cache if promise is rejected', async () => {
expect.assertions(4);
const spy = jest.fn();
const test = new TestAsync(spy);
const a = test.rejectedPromise();
const b = test.rejectedPromise();
const c = test.rejectedPromise();
expect(spy).toHaveBeenCalledTimes(1);
expect(b).toBe(a);
expect(c).toBe(a);
try {
const result = await a;
// Should not run
await expect(b).resolves.toBe(result);
await expect(c).resolves.toBe(result);
} catch {
// Ignore
}
try {
await test.rejectedPromise();
} catch {
expect(spy).toHaveBeenCalledTimes(2);
}
});
});
}); | the_stack |
import FeatureNameStatistics from 'goog:proto.featureStatistics.FeatureNameStatistics';
import Histogram from 'goog:proto.featureStatistics.Histogram';
import * as fsg from '../feature_statistics_generator';
const {expect} = chai;
describe('generateStats', () => {
it('handles null data', () => {
const stats = fsg.generateStats();
expect(stats.getNumExamples()).to.equal(0);
});
it('picks dominant data type', () => {
const items: fsg.DataPoint[] = [];
const numItem: fsg.DataPoint = {};
numItem['f1'] = 1;
items.push(numItem);
for (let i = 0; i < 5; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = 'string';
items.push(item);
}
const stats = fsg.generateStats(items);
const feature = stats.getFeaturesList()![0];
expect(feature.getType()).to.equal(FeatureNameStatistics.Type.STRING);
expect(feature.getNumStats()).to.not.be.null;
});
it('detects integers', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 5; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = i;
items.push(item);
}
const stats = fsg.generateStats(items);
const feature = stats.getFeaturesList()![0];
expect(feature.getType()).to.equal(FeatureNameStatistics.Type.INT);
});
it('detects floats', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 5; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = i;
items.push(item);
}
const floatItem: fsg.DataPoint = {};
floatItem['f1'] = 1.1;
items.push(floatItem);
const stats = fsg.generateStats(items);
const feature = stats.getFeaturesList()![0];
expect(feature.getType()).to.equal(FeatureNameStatistics.Type.FLOAT);
});
it('handles data', () => {
const items: fsg.DataPoint[] = [];
const item: fsg.DataPoint = {};
item['f1'] = 1;
item['f2'] = 'hello';
items.push(item);
const stats = fsg.generateStats(items);
expect(stats.getNumExamples()).to.equal(1);
});
it('handles data with missing entries', () => {
const items: fsg.DataPoint[] = [];
const item: fsg.DataPoint = {};
item['f1'] = 1;
items.push(item);
const item2: fsg.DataPoint = {};
item2['f2'] = 'hello';
items.push(item2);
const stats = fsg.generateStats(items);
expect(stats.getNumExamples()).to.equal(2);
});
it('handles numeric data', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 500; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = i;
items.push(item);
}
const item: fsg.DataPoint = {};
item['f1'] = 0;
items.push(item);
const stats = fsg.generateStats(items);
expect(stats.getNumExamples()).to.equal(501);
const numStats = stats.getFeaturesList()![0].getNumStats()!;
expect(numStats.getMin()).to.equal(0);
expect(numStats.getMax()).to.equal(499);
expect(numStats.getMean()).to.be.within(249.001, 249.003);
expect(numStats.getStdDev()).to.be.within(144.766, 144.768);
expect(numStats.getMedian()).to.be.within(248.99, 249.01);
expect(numStats.getNumZeros()).to.equal(2);
expect(numStats.getHistogramsList().length).to.equal(2);
expect(numStats.getHistogramsList()![0].getType())
.to.equal(Histogram.HistogramType.STANDARD);
let hist = numStats.getHistogramsList()![0].getBucketsList()!;
expect(hist.length).to.equal(10);
expect(hist[0].getSampleCount()).to.equal(51);
expect(hist[0].getLowValue()).to.equal(0);
expect(hist[0].getHighValue()).to.equal(49.9);
expect(hist[9].getSampleCount()).to.equal(50);
expect(hist[9].getLowValue()).to.be.within(449.099, 449.101);
expect(hist[9].getHighValue()).to.equal(499);
expect(numStats.getHistogramsList()![1].getType())
.to.equal(Histogram.HistogramType.QUANTILES);
hist = numStats.getHistogramsList()![1].getBucketsList()!;
expect(hist.length).to.equal(10);
expect(hist[0].getSampleCount()).to.equal(50.1);
expect(hist[0].getLowValue()).to.equal(0);
expect(hist[0].getHighValue()).to.equal(49);
expect(hist[9].getSampleCount()).to.equal(50.1);
expect(hist[9].getLowValue()).to.equal(449);
expect(hist[9].getHighValue()).to.equal(499);
});
it('handles inf values', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 500; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = i;
items.push(item);
}
const item: fsg.DataPoint = {};
item['f1'] = Infinity;
items.push(item);
const item2: fsg.DataPoint = {};
item2['f1'] = -Infinity;
items.push(item2);
const stats = fsg.generateStats(items);
expect(stats.getNumExamples()).to.equal(502);
const numStats = stats.getFeaturesList()![0].getNumStats()!;
expect(numStats.getMin()).to.equal(-Infinity);
expect(numStats.getMax()).to.equal(Infinity);
expect(numStats.getMean()).to.be.NaN;
expect(numStats.getStdDev()).to.be.NaN;
expect(numStats.getHistogramsList().length).to.equal(2);
expect(numStats.getHistogramsList()![0].getType())
.to.equal(Histogram.HistogramType.STANDARD);
const hist = numStats.getHistogramsList()![0].getBucketsList()!;
expect(hist.length).to.equal(10);
expect(hist[0].getLowValue()).to.equal(-Infinity);
expect(hist[0].getSampleCount()).to.equal(51);
expect(hist[9].getHighValue()).to.equal(Infinity);
expect(hist[9].getSampleCount()).to.equal(51);
});
it('calculates correct quantiles', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 50; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = i;
items.push(item);
const itemConst: fsg.DataPoint = {};
itemConst['f1'] = 100;
items.push(itemConst);
}
const stats = fsg.generateStats(items);
expect(stats.getNumExamples()).to.equal(100);
const numStats = stats.getFeaturesList()![0].getNumStats()!;
expect(numStats.getHistogramsList()![1].getType())
.to.equal(Histogram.HistogramType.QUANTILES);
const hist = numStats.getHistogramsList()![1].getBucketsList()!;
expect(hist.length).to.equal(10);
expect(hist[0].getSampleCount()).to.equal(10);
expect(hist[0].getLowValue()).to.equal(0);
expect(hist[0].getHighValue()).to.equal(9.9);
expect(hist[9].getSampleCount()).to.equal(10);
expect(hist[9].getLowValue()).to.equal(100);
expect(hist[9].getHighValue()).to.equal(100);
});
it('handles string data', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 500; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = i % 2 === 0 ? 'popular' : i < 150 ? 'third' : 'second';
items.push(item);
}
const stats = fsg.generateStats(items);
expect(stats.getNumExamples()).to.equal(500);
const stringStats = stats.getFeaturesList()![0].getStringStats()!;
expect(stringStats.getUnique()).to.equal(3);
expect(stringStats.getAvgLength()).to.equal(6.35);
const topVals = stringStats.getTopValuesList()!;
expect(topVals.length).to.equal(1);
expect(topVals[0].getValue()).to.equal('popular');
expect(topVals[0].getFrequency()).to.equal(250);
const hist = stringStats.getRankHistogram()!.getBucketsList()!;
expect(hist.length).to.equal(3);
expect(hist[0].getSampleCount()).to.equal(250);
expect(hist[0].getLabel()).to.equal('popular');
expect(hist[0].getLowRank()).to.equal(0);
expect(hist[0].getHighRank()).to.equal(0);
expect(hist[2].getSampleCount()).to.equal(75);
expect(hist[2].getLowRank()).to.equal(2);
expect(hist[2].getHighRank()).to.equal(2);
});
it('generates correct common stats for strings', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 10; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = 'test';
items.push(item);
}
const missingItem: fsg.DataPoint = {};
missingItem['f2'] = 'f1 is missing';
items.push(missingItem);
const stats = fsg.generateStats(items);
let common = stats.getFeaturesList()![0].getStringStats()!.getCommonStats()!;
expect(common.getMinNumValues()).to.equal(1);
expect(common.getMaxNumValues()).to.equal(1);
expect(common.getAvgNumValues()).to.equal(1);
expect(common.getNumMissing()).to.equal(1);
expect(common.getNumNonMissing()).to.equal(10);
expect(common.getNumValuesHistogram()!.getType())
.to.equal(Histogram.HistogramType.QUANTILES);
const hist = common.getNumValuesHistogram()!.getBucketsList()!;
expect(hist.length).to.equal(10);
expect(hist[0].getSampleCount()).to.equal(1);
expect(hist[0].getLowValue()).to.equal(1);
expect(hist[0].getHighValue()).to.equal(1);
expect(hist[9].getSampleCount()).to.equal(1);
expect(hist[9].getLowValue()).to.equal(1);
expect(hist[9].getHighValue()).to.equal(1);
common = stats.getFeaturesList()![1].getStringStats()!.getCommonStats()!;
expect(common.getNumMissing()).to.equal(10);
expect(common.getNumNonMissing()).to.equal(1);
});
it('generates correct common stats for nums', () => {
const items: fsg.DataPoint[] = [];
for (let i = 0; i < 10; ++i) {
const item: fsg.DataPoint = {};
item['f1'] = 1;
items.push(item);
}
const missingItem: fsg.DataPoint = {};
missingItem['f2'] = 2;
items.push(missingItem);
const stats = fsg.generateStats(items);
let common = stats.getFeaturesList()![0].getNumStats()!.getCommonStats()!;
expect(common.getMinNumValues()).to.equal(1);
expect(common.getMaxNumValues()).to.equal(1);
expect(common.getAvgNumValues()).to.equal(1);
expect(common.getNumMissing()).to.equal(1);
expect(common.getNumNonMissing()).to.equal(10);
expect(common.getNumValuesHistogram()!.getType())
.to.equal(Histogram.HistogramType.QUANTILES);
const hist = common.getNumValuesHistogram()!.getBucketsList()!;
expect(hist.length).to.equal(10);
expect(hist[0].getSampleCount()).to.equal(1);
expect(hist[0].getLowValue()).to.equal(1);
expect(hist[0].getHighValue()).to.equal(1);
expect(hist[9].getSampleCount()).to.equal(1);
expect(hist[9].getLowValue()).to.equal(1);
expect(hist[9].getHighValue()).to.equal(1);
common = stats.getFeaturesList()![1].getNumStats()!.getCommonStats()!;
expect(common.getNumMissing()).to.equal(10);
expect(common.getNumNonMissing()).to.equal(1);
});
});
describe('getStatsProto', () => {
it('handles empty array', () => {
const stats = fsg.getStatsProto([]);
expect(stats.getDatasetsList().length).to.equal(0);
});
it('handles multiple datasets', () => {
const items1: fsg.DataPoint[] = [];
const item1: fsg.DataPoint = {};
item1['f1'] = 1;
items1.push(item1);
const items2: fsg.DataPoint[] = [];
const item2: fsg.DataPoint = {};
item2['f1'] = 1;
items2.push(item2);
const stats = fsg.getStatsProto([
{data: items1, name: 'train'},
{data: items2, name: 'test'}]);
const list = stats.getDatasetsList();
expect(list.length).to.equal(2);
expect(list[0].getName()).to.equal('train');
expect(list[1].getName()).to.equal('test');
});
}); | the_stack |
import * as fs from "fs";
import * as path from "path";
import * as url from "url";
import { MultiError, VError } from "verror";
import * as http from "http";
import * as https from "https";
import "source-map-support/register";
import { IDisposable } from "../../src/Types/Contracts";
import { RavenTestDriver } from "../TestDriver";
import { RavenServerLocator } from "../TestDriver/RavenServerLocator";
import { IDocumentStore } from "../../src/Documents/IDocumentStore";
import { getError, throwError } from "../../src/Exceptions";
import { IAuthOptions } from "../../src/Auth/AuthOptions";
import * as os from "os";
import "../../src/Utility/Polyfills";
import {
CreateDatabaseOperation,
DatabaseRecord,
DeleteDatabasesOperation, DocumentConventions, DocumentSession,
DocumentStore, DocumentType, getAllNodesFromTopology, GetClusterTopologyCommand, GetDatabaseRecordOperation,
IDocumentSession, ServerNode
} from "../../src";
import * as rimraf from "rimraf";
import { ChildProcess } from "child_process";
import { TypeUtil } from "../../src/Utility/TypeUtil";
import * as BluebirdPromise from "bluebird";
import { getLogger } from "../../src/Utility/LogUtil";
import { AdminJsConsoleOperation } from "./AdminJsConsoleOperation";
import { Stopwatch } from "../../src/Utility/Stopwatch";
import { delay } from "../../src/Utility/PromiseUtil";
import moment = require("moment");
const log = getLogger({ module: "TestDriver" });
// logOnUncaughtAndUnhandled();
function logOnUncaughtAndUnhandled() {
process.on("unhandledRejection", (...args) => {
// tslint:disable-next-line:no-console
console.log(...args);
});
process.on("uncaughtException", (...args) => {
// tslint:disable-next-line:no-console
console.log(...args);
});
}
class TestServiceLocator extends RavenServerLocator {
public getCommandArguments() {
const cliOpts = [
"--ServerUrl=http://127.0.0.1:0",
"--ServerUrl.Tcp=tcp://127.0.0.1:38884",
"--Features.Availability=Experimental"
];
return cliOpts;
}
}
class TestSecuredServiceLocator extends RavenServerLocator {
public static ENV_SERVER_CA_PATH = "RAVENDB_TEST_CA_PATH";
public static ENV_SERVER_CERTIFICATE_PATH = "RAVENDB_TEST_SERVER_CERTIFICATE_PATH";
public static ENV_HTTPS_SERVER_URL = "RAVENDB_TEST_HTTPS_SERVER_URL";
public static ENV_CLIENT_CERT_PATH = "RAVENDB_TEST_CLIENT_CERT_PATH";
public static ENV_CLIENT_CERT_PASSPHRASE = "RAVENDB_TEST_CLIENT_CERT_PASSPHRASE";
public getCommandArguments() {
const certPath = this.getServerCertificatePath();
if (!certPath) {
throwError("InvalidOperationException", "Unable to find RavenDB server certificate path. " +
"Please make sure " + TestSecuredServiceLocator.ENV_SERVER_CERTIFICATE_PATH
+ " environment variable is set and valid " + "(current value = " + certPath + ")");
}
return [
"--Security.Certificate.Path=" + certPath,
"--ServerUrl=" + this._getHttpsServerUrl(),
"--ServerUrl.Tcp=" + this._getHttpsServerTcpUrl(),
"--Features.Availability=Experimental"
];
}
private _getHttpsServerUrl() {
const httpsServerUrl = process.env[TestSecuredServiceLocator.ENV_HTTPS_SERVER_URL];
if (!httpsServerUrl) {
throwError("InvalidArgumentException",
"Unable to find RavenDB https server url. " +
"Please make sure " + TestSecuredServiceLocator.ENV_HTTPS_SERVER_URL
+ " environment variable is set and is valid " +
"(current value = " + httpsServerUrl + ")");
}
return httpsServerUrl;
}
private _getHttpsServerTcpUrl() {
const https = this._getHttpsServerUrl();
return "tcp://" + url.parse(https).hostname + ":38882";
}
public getServerCertificatePath() {
return path.resolve(process.env[TestSecuredServiceLocator.ENV_SERVER_CERTIFICATE_PATH]);
}
public getClientAuthOptions(): IAuthOptions {
const clientCertPath = process.env[TestSecuredServiceLocator.ENV_CLIENT_CERT_PATH];
const clientCertPass = process.env[TestSecuredServiceLocator.ENV_CLIENT_CERT_PASSPHRASE];
const serverCaCertPath = process.env[TestSecuredServiceLocator.ENV_SERVER_CA_PATH];
if (!clientCertPath) {
return {
certificate: fs.readFileSync(this.getServerCertificatePath()),
type: "pfx"
};
}
return {
type: "pem",
certificate: fs.readFileSync(clientCertPath, "utf-8"),
password: clientCertPass,
ca: fs.readFileSync(serverCaCertPath, "utf-8"),
};
}
}
export class RavenTestContext extends RavenTestDriver implements IDisposable {
public static isRunningOnWindows = os.platform() === "win32";
public static isPullRequest = !process.env["RAVEN_License"];
private readonly _locator: RavenServerLocator;
private readonly _securedLocator: RavenServerLocator;
private static _globalServer: IDocumentStore;
private static _globalServerProcess: ChildProcess;
private static _globalSecuredServer: IDocumentStore;
private static _globalSecuredServerProcess: ChildProcess;
private _documentStores: Set<IDocumentStore> = new Set();
private static _index: number = 0;
public constructor() {
super();
this._locator = new TestServiceLocator();
this._securedLocator = new TestSecuredServiceLocator();
}
private _customizeDbRecord: (dbRecord: DatabaseRecord) => void = TypeUtil.NOOP;
private _customizeStore: (store: DocumentStore) => Promise<void> = TypeUtil.ASYNC_NOOP;
public set customizeDbRecord(customizeDbRecord: (dbRecord: DatabaseRecord) => void) {
this._customizeDbRecord = customizeDbRecord;
}
public get customizeDbRecord() {
return this._customizeDbRecord;
}
public set customizeStore(customizeStore: (store: DocumentStore) => Promise<void>) {
this._customizeStore = customizeStore;
}
public get customizeStore() {
return this._customizeStore;
}
public getSecuredDocumentStore(): Promise<DocumentStore>;
public getSecuredDocumentStore(database?): Promise<DocumentStore> {
return this.getDocumentStore(database, true, null);
}
private async _runServer(secured: boolean) {
let childProcess: ChildProcess;
const store = await this._runServerInternal(this._getLocator(secured), p => childProcess = p, s => {
if (secured) {
s.authOptions = this._securedLocator.getClientAuthOptions();
}
});
RavenTestContext._setGlobalServerProcess(secured, childProcess);
if (secured) {
RavenTestContext._globalSecuredServer = store;
} else {
RavenTestContext._globalServer = store;
}
return store;
}
private _getLocator(secured: boolean) {
return secured ? this._securedLocator : this._locator;
}
private static _getGlobalServer(secured: boolean) {
return secured ? this._globalSecuredServer : this._globalServer;
}
private static _getGlobalProcess(secured: boolean) {
return secured ? this._globalSecuredServerProcess : this._globalServerProcess;
}
private static _setGlobalServerProcess(secured: boolean, p: ChildProcess) {
if (secured) {
this._globalSecuredServerProcess = p;
} else {
this._globalServerProcess = p;
}
}
private static _killGlobalServerProcess(secured: boolean): void {
let p: ChildProcess;
// tslint:disable-next-line:prefer-const
let store;
if (secured) {
p = this._globalSecuredServerProcess;
this._globalSecuredServerProcess = null;
if (this._globalSecuredServer) {
this._globalSecuredServer.dispose();
this._globalSecuredServer = null;
}
} else {
p = this._globalServerProcess;
this._globalServerProcess = null;
if (this._globalServer) {
this._globalServer.dispose();
this._globalServer = null;
}
}
new BluebirdPromise(resolve => {
if (store) {
store.on("executorsDisposed", () => resolve());
} else {
resolve();
}
})
.timeout(2000)
.finally(() => {
this._killProcess(p);
});
if (store) {
store.dispose();
}
}
public utcToday() {
return moment().utc().startOf("day");
}
public async waitForDocument<T extends object>(documentInfo: DocumentType<T>,
store: IDocumentStore,
docId: string,
predicate: (value: T) => void = null,
timeout: number = 10_000) {
const sw = Stopwatch.createStarted();
let ex: Error;
while (sw.elapsed < timeout) {
const session = store.openSession(store.database);
try {
const doc = await session.load(docId, documentInfo);
if (doc) {
if (!predicate || predicate(doc)) {
return true;
}
}
} catch (e) {
ex = e;
}
await delay(100);
}
return false;
}
public async getDocumentStore(): Promise<DocumentStore>;
public async getDocumentStore(database: string): Promise<DocumentStore>;
public async getDocumentStore(database: string, secured: boolean): Promise<DocumentStore>;
public async getDocumentStore(
database: string, secured: boolean, waitForIndexingTimeoutInMs?: number): Promise<DocumentStore>;
public async getDocumentStore(
database = "test_db", secured = false, waitForIndexingTimeoutInMs: number = null): Promise<DocumentStore> {
const databaseName = database + "_" + (++RavenTestContext._index);
log.info(`getDocumentStore for db ${ database }.`);
let documentStore: IDocumentStore;
if (!RavenTestContext._getGlobalServer(secured)) {
await this._runServer(secured);
}
documentStore = RavenTestContext._getGlobalServer(secured);
const databaseRecord: DatabaseRecord = { databaseName };
if (this._customizeDbRecord) {
this._customizeDbRecord(databaseRecord);
}
const createDatabaseOperation = new CreateDatabaseOperation(databaseRecord);
const createDatabaseResult = await documentStore.maintenance.server.send(createDatabaseOperation);
const store = new DocumentStore(documentStore.urls, databaseName);
if (secured) {
store.authOptions = this._securedLocator.getClientAuthOptions();
}
if (this._customizeStore) {
await this._customizeStore(store);
}
store.initialize();
(store as IDocumentStore)
.once("afterDispose", async (callback) => {
if (!this._documentStores.has(store)) {
callback();
return;
}
try {
await store.maintenance.server.send(new DeleteDatabasesOperation({
databaseNames: [store.database],
hardDelete: true
}));
log.info(`Database ${store.database} deleted.`);
} catch (err) {
if (err.name === "DatabaseDoesNotExistException"
|| err.name === "NoLeaderException") {
return;
}
if (store.isDisposed() || !RavenTestContext._getGlobalProcess(secured)) {
return;
}
throwError("TestDriverTearDownError",
`Error deleting database ${ store.database }.`, err);
} finally {
callback();
}
});
await this._setupDatabase(store);
if (!TypeUtil.isNullOrUndefined(waitForIndexingTimeoutInMs)) {
await this.waitForIndexing(store);
}
this._documentStores.add(store);
return store;
}
public static setupServer(): RavenTestContext {
return new RavenTestContext();
}
public dispose(): void {
log.info("Dispose.");
if (this._disposed) {
return;
}
this._disposed = true;
const STORE_DISPOSAL_TIMEOUT = 10000;
const storeDisposalPromises = [...this._documentStores].map(async (store) => {
try {
const result = new BluebirdPromise((resolve) => {
store.once("executorsDisposed", () => {
resolve();
});
})
.timeout(STORE_DISPOSAL_TIMEOUT)
.then(() => null);
store.dispose();
return result;
} catch (err) {
return getError("TestDriverTeardownError", "Error disposing document store", err);
}
});
BluebirdPromise.all(storeDisposalPromises)
.then((errors) => {
const anyErrors = errors.filter(x => !!x);
if (anyErrors.length) {
throw new MultiError(anyErrors);
}
})
.then(() => {
if (RavenTestContext._globalSecuredServer) {
RavenTestContext._globalSecuredServer.dispose();
}
if (RavenTestContext._globalServer) {
RavenTestContext._globalServer.dispose();
}
})
.finally(() => {
RavenTestContext._killGlobalServerProcess(true);
RavenTestContext._killGlobalServerProcess(false);
});
}
}
class TestCloudServiceLocator extends RavenServerLocator {
private static readonly _defaultParams = {
ServerUrl: "http://127.0.0.1:0",
"Features.Availability": "Experimental"
};
private _extraParams: object = {};
public constructor(extraParams: Record<string, string> = {}) {
super();
this._extraParams = extraParams;
}
getCommandArguments(): string[] {
const items = Object.assign({}, TestCloudServiceLocator._defaultParams, this._extraParams);
return Object.keys(items)
.map(key => "--" + key + "=" + items[key]);
}
}
export class ClusterTestContext extends RavenTestDriver implements IDisposable {
private _toDispose: IDisposable[] = [];
private _dbCounter = 1;
public getDatabaseName(): string {
return "db_" + (++this._dbCounter);
}
public async createRaftCluster(numberOfNodes: number, customSettings: Record<string, string> = {}) {
const cluster = new ClusterController();
cluster.nodes = [];
customSettings = {
"Cluster.ElectionTimeoutInMs": "3000",
...customSettings
}
const allowedNodeTags = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
const leaderIndex = 0;
const leaderNodeTag = allowedNodeTags[leaderIndex];
for (let i = 0 ; i < numberOfNodes; i++) {
let process: ChildProcess;
const store = await this._runServerInternal(new TestCloudServiceLocator(customSettings), p => process = p, null);
const clusterNode = new ClusterNode();
clusterNode.serverProcess = process;
clusterNode.store = store;
clusterNode.url = store.urls[0];
clusterNode.nodeTag = allowedNodeTags[i];
clusterNode.leader = i === leaderIndex;
cluster.nodes.push(clusterNode);
}
await cluster.executeJsScript(leaderNodeTag, "server.ServerStore.EnsureNotPassiveAsync(null, \"" + leaderNodeTag + "\").Wait();");
if (numberOfNodes > 1) {
// add nodes to cluster
for (let i = 0; i < numberOfNodes; i++) {
if (i === leaderIndex) {
continue;
}
const nodeTag = allowedNodeTags[i];
const url = cluster.nodes[i].url;
await cluster.executeJsScript(leaderNodeTag, "server.ServerStore.ValidateFixedPort = false;" +
"server.ServerStore.AddNodeToClusterAsync(\"" + url + "\", \"" + nodeTag + "\", false, false, server.ServerStore.ServerShutdown).Wait();");
await cluster.executeJsScript(nodeTag, "server.ServerStore.WaitForTopology(0, server.ServerStore.ServerShutdown).Wait();");
}
}
// wait for license to activate
for (const node of cluster.nodes) {
await this.waitForValue(
async () => {
const response = await cluster.executeJsScript(node.nodeTag, "return server.ServerStore.LicenseManager.LicenseStatus.Type !== 'Invalid'");
return response.result;
}, true, {
timeout: 30_000
});
}
return cluster;
}
public async waitForDocumentInCluster<T extends object>(documentInfo: DocumentType<T>,
session: DocumentSession,
docId: string,
predicate: (value: T) => boolean,
timeout: number) {
const nodes = session.requestExecutor.getTopologyNodes();
const stores = this._getDocumentStores(nodes, true);
return this._waitForDocumentInClusterInternal(documentInfo, docId, predicate, timeout, stores);
}
private async _waitForDocumentInClusterInternal<T extends object>(documentInfo: DocumentType<T>, docId: string, predicate: (value: T) => boolean,
timeout: number, stores: DocumentStore[]) {
for (const store of stores) {
await this.waitForDocument(documentInfo, store, docId, predicate, timeout);
}
return true;
}
public async waitForDocument<T extends object>(documentInfo: DocumentType<T>,
store: IDocumentStore,
docId: string,
predicate: (value: T) => void = null,
timeout: number = 10_000) {
const sw = Stopwatch.createStarted();
let ex: Error;
while (sw.elapsed < timeout) {
const session = store.openSession(store.database);
try {
const doc = await session.load(docId, documentInfo);
if (doc) {
if (!predicate || predicate(doc)) {
return true;
}
}
} catch (e) {
ex = e;
}
await delay(100);
}
return false;
}
private _getDocumentStores(nodes: ServerNode[], disableTopologyUpdates: boolean) {
const stores: DocumentStore[] = [];
for (const node of nodes) {
const store = new DocumentStore(node.url, node.database);
store.conventions.disableTopologyUpdates = disableTopologyUpdates;
store.initialize();
stores.push(store);
this._toDispose.push(store);
}
return stores;
}
public async waitForIndexingInTheCluster(store: IDocumentStore, dbName: string, timeout: number) {
const record = await store.maintenance.server.send(new GetDatabaseRecordOperation(dbName || store.database));
for (const nodeTag of getAllNodesFromTopology(record.topology)) {
await this.waitForIndexing(store, dbName, timeout, true, nodeTag);
}
}
dispose(): void {
for (const disposable of this._toDispose) {
try {
disposable.dispose()
} catch {
// ignore
}
}
}
}
class ClusterController implements IDisposable {
public nodes: ClusterNode[];
public async executeJsScript(nodeTag: string, script: string) {
const targetNode = this.getNodeByTag(nodeTag);
const store = new DocumentStore(targetNode.url, null);
try {
store.conventions.disableTopologyUpdates = true;
store.initialize();
return await store.maintenance.server.send(new AdminJsConsoleOperation(script));
} finally {
store.dispose();
}
}
public async executeJsScriptRaw(nodeTag: string, script: string) {
const targetNode = this.getNodeByTag(nodeTag);
const jsConsole = new AdminJsConsoleOperation(script);
const command = jsConsole.getCommand(new DocumentConventions());
const serverNode = new ServerNode({
url: targetNode.url
});
const request = command.createRequest(serverNode);
const store = new DocumentStore(targetNode.url, "_");
try {
store.initialize();
const httpAgent = store.getRequestExecutor().getHttpAgent();
const responseAndStream = await command.send(httpAgent, request);
await command.processResponse(null, responseAndStream.response, responseAndStream.bodyStream, request.uri);
return command.result;
} finally {
store.dispose();
}
}
public getNodeByUrl(url: string) {
return this.nodes.find(x => x.url === url)
|| throwError("InvalidOperationException", "Unable to find node with url: " + url);
}
public getWorkingServer(): ClusterNode {
return this.nodes.find(x => !x.disposed)
|| throwError("InvalidOperationException", "Unable to find working server");
}
public getNodeByTag(nodeTag: string) {
const node = this.nodes.find(x => x.nodeTag === nodeTag);
if (!node) {
throwError("InvalidArgumentException", "Unable to find node with tag: " + nodeTag);
}
return node;
}
public async getCurrentLeader(store: IDocumentStore) {
const command = new GetClusterTopologyCommand();
await store.getRequestExecutor().execute(command);
return command.result.leader;
}
public async disposeServer(nodeTag: string) {
try {
this.getNodeByTag(nodeTag).disposed = true;
await this.executeJsScriptRaw(nodeTag, "server.Dispose()");
} catch {
// we likely throw as server won't be able to respond
}
}
public getInitialLeader() {
return this.nodes.find(x => x.leader);
}
public async createDatabase(databaseName: string, replicationFactor: number, leaderUrl: string);
public async createDatabase(databaseRecord: DatabaseRecord, replicationFactor: number, leaderUrl: string);
public async createDatabase(databaseRecordOrName: DatabaseRecord | string, replicationFactor: number, leaderUrl: string) {
const databaseRecord: DatabaseRecord = TypeUtil.isString(databaseRecordOrName)
? { databaseName: databaseRecordOrName }
: databaseRecordOrName;
const store = new DocumentStore(leaderUrl, databaseRecord.databaseName);
try {
store.initialize();
const putResult = await store.maintenance.server.send(new CreateDatabaseOperation(databaseRecord, replicationFactor));
for (const node of this.nodes) {
await this.executeJsScript(node.nodeTag, "server.ServerStore.Cluster.WaitForIndexNotification(\"" + putResult.raftCommandIndex + "\").Wait()");
}
return putResult;
} finally {
store.dispose();
}
}
public dispose() {
for (const node of this.nodes) {
try {
node.serverProcess.kill("SIGKILL");
} catch {
// ignore
}
}
}
}
class ClusterNode {
public nodeTag: string;
public url: string;
public leader: boolean;
public store: IDocumentStore;
public serverProcess: ChildProcess;
public disposed: boolean;
}
export async function disposeTestDocumentStore(store: IDocumentStore) {
if (!store) {
return;
}
return new Promise<void>(resolve => {
if (store) {
store.once("executorsDisposed", () => resolve());
store.dispose();
}
});
}
export let testContext: RavenTestContext;
setupRavenDbTestContext();
export let clusterTestContext: ClusterTestContext;
// tslint:disable:no-console
function checkAgent(agentName: string, agent: http.Agent) {
const reqKeys = Object.keys(agent.requests);
if (reqKeys.length) {
console.log(`${agentName} dangling requests: ${reqKeys}`);
}
const sockKeys = Object.keys(agent.sockets);
if (sockKeys.length) {
console.log(`${agentName} dangling sockets: ${sockKeys}`);
}
}
function setupRavenDbTestContext() {
before(() => {
testContext = RavenTestContext.setupServer();
});
afterEach(function () {
if (this.currentTest && this.currentTest.state === "failed") {
console.error(VError.fullStack(this.currentTest.err));
}
});
after(() => {
testContext.dispose();
process.on("beforeExit", () => {
checkAgent("http", http.globalAgent);
checkAgent("https", https.globalAgent);
});
});
return testContext;
}
// tslint:enable:no-console
export async function storeNewDoc(
session: IDocumentSession, data: object, id: string, clazz: any) {
const order = Object.assign(new clazz(), data);
await session.store(order, id);
return order;
}
export class TemporaryDirContext implements IDisposable {
public tempDir: string;
constructor() {
this.tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "rdb-node-"));
}
dispose(): void {
rimraf.sync(this.tempDir);
}
} | the_stack |
import React, { useState, useMemo } from 'react'
import styled from 'styled-components'
import {
FieldContract,
IndexComponentProps,
ResourceContract
} from '@tensei/components'
import { useParams, useHistory, Link } from 'react-router-dom'
import { EuiSpacer } from '@tensei/eui/lib/components/spacer'
import { EuiPopover } from '@tensei/eui/lib/components/popover'
import { EuiFieldText } from '@tensei/eui/lib/components/form/field_text'
import { EuiFlexItem, EuiFlexGroup } from '@tensei/eui/lib/components/flex'
import { EuiButtonEmpty, EuiButton } from '@tensei/eui/lib/components/button'
import {
EuiBasicTable,
EuiBasicTableProps,
EuiBasicTableColumn,
EuiTableActionsColumnType,
CriteriaWithPagination
} from '@tensei/eui/lib/components/basic_table'
import {
EuiContextMenu,
EuiContextMenuPanelDescriptor
} from '@tensei/eui/lib/components/context_menu'
import { EuiConfirmModal } from '@tensei/eui/lib/components/modal/confirm_modal'
import { useGeneratedHtmlId } from '@tensei/eui/lib/services/accessibility'
import { EuiFieldSearch } from '@tensei/eui/lib/components/form/field_search'
import { DashboardLayout } from '../../components/dashboard/layout'
import { useEffect } from 'react'
import {
useResourceStore,
filterClauses,
FilterClause,
ActiveFilter
} from '../../../store/resource'
import { EuiTitle } from '@tensei/eui/lib/components/title'
import { useToastStore } from '../../../store/toast'
import { debounce } from 'throttle-debounce'
import { Filter } from '@tensei/common/config'
const PageWrapper = styled.div`
width: 100%;
padding: 40px;
margin-bottom: 40px;
`
const HeaderContainer = styled.div`
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
height: 54px;
`
const SearchAndFilterContainer = styled.div`
gap: 0.75rem;
display: flex;
width: 50%;
align-items: center;
`
const FilterContent = styled.div`
padding: 1rem;
`
const FilterActions = styled.div`
margin-top: 1rem;
display: flex;
align-items: center;
justify-content: space-between;
`
const TableWrapper = styled.div`
display: flex;
flex-direction: column;
`
const DeleteButtonContainer = styled.div`
display: flex;
align-self: flex-end;
`
type FieldWithPanelId = FieldContract & {
panel: string
}
const FilterValue: React.FunctionComponent<{
field: FieldContract
filterClause: FilterClause
onCancel: () => void
onApply: (value: any) => void
}> = ({ onApply, onCancel }) => {
const [value, setValue] = useState('')
return (
<FilterContent>
<EuiFieldText
placeholder="Example: 43"
onChange={event => setValue(event.target.value)}
/>
<FilterActions>
<EuiButtonEmpty size="s" color="danger" onClick={() => onCancel()}>
Cancel
</EuiButtonEmpty>
<EuiButton size="s" fill onClick={() => onApply(value)}>
Apply
</EuiButton>
</FilterActions>
</FilterContent>
)
}
interface FilterListProps {
resource: ResourceContract
applyFilter: (filter: ActiveFilter) => void
}
export const FilterList: React.FunctionComponent<FilterListProps> = ({
applyFilter,
resource
}) => {
const [open, setOpen] = useState(false)
const [filterDropdown, setFilterDropdown] = useState<Boolean>()
const contextMenuPopoverId = useGeneratedHtmlId({
prefix: 'contextMenuPopover'
})
const onApply = (field: FieldContract, clause: FilterClause, value: any) => {
applyFilter({
field,
clause,
value
})
setOpen(false)
}
const panels: EuiContextMenuPanelDescriptor[] = useMemo(() => {
// For now, we won't support filtering by relationship fields.
const fields =
resource?.fields.filter(
field =>
!field.isRelationshipField && !field.isVirtual && field.isSearchable
) || []
const getClausesForField = (field: FieldContract) => {
// Checking field type, find all the clauses that apply to this field.
// For example, integer, decimal, float, number field types should only
// be shown clauses with type of "number".
return filterClauses
}
fields.length ? setFilterDropdown(true) : setFilterDropdown(false)
return [
{
id: 0,
title: 'Select a field',
items: [
...fields.map((field, idx) => ({
name: field.name,
panel: `where-${field.databaseField}-${idx}`
}))
]
},
...fields.map((field, idx) => ({
id: `where-${field.databaseField}-${idx}`,
width: 350,
title: `Filter ${resource?.label?.toLowerCase()} where ${field?.name?.toLowerCase()}:`,
items: [
...getClausesForField(field).map((clause, clauseIdx) => ({
name: clause.name,
panel: `filter-value-${field.databaseField}-${clauseIdx}-${idx}`
}))
]
})),
...fields
.map((field, idx) =>
getClausesForField(field).map((clause, clauseIdx) => ({
id: `filter-value-${field.databaseField}-${clauseIdx}-${idx}`,
title: `Filter ${resource?.label?.toLowerCase()} where ${field?.name?.toLowerCase()} ${clause.name.toLowerCase()}:`,
width: 400,
content: (
<FilterValue
field={field}
filterClause={clause}
onCancel={() => setOpen(false)}
onApply={value => onApply(field, clause, value)}
/>
)
}))
)
.flat()
]
}, [resource])
return filterDropdown ? (
<EuiPopover
isOpen={open}
id={contextMenuPopoverId}
panelPaddingSize="none"
closePopover={() => setOpen(false)}
anchorPosition="downCenter"
button={
<EuiButtonEmpty
iconSide="right"
iconType="arrowDown"
onClick={() => setOpen(true)}
>
Filters
</EuiButtonEmpty>
}
>
<EuiContextMenu initialPanelId={0} panels={panels}></EuiContextMenu>
</EuiPopover>
) : null
}
interface MetaData {
page: number
pageCount: number
perPage: number
total: number
}
interface TableProps {
search: string
hideSelection?: boolean
inFlyout?: boolean
actions?: EuiTableActionsColumnType<any>['actions']
resource: ResourceContract
filters: ActiveFilter[]
applyFilter: (filter: ActiveFilter) => void
onSelect?: (rows: any[]) => void
}
export const Table: React.FunctionComponent<TableProps> = ({
search,
filters,
resource,
onSelect,
hideSelection,
inFlyout,
actions
}) => {
const { fetchTableData, deleteTableData } = useResourceStore()
const [pageSize, setPageSize] = useState(resource?.perPageOptions[0])
const [pageIndex, setPageIndex] = useState(0)
const [loading, setLoading] = useState(true)
const [selectedItems, setSelectedItems] = useState<any[]>([])
const [sortField, setSortField] = useState('')
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
const [items, setItems] = useState([])
const [metaData, setMetaData] = useState<MetaData>()
const [itemsSelectedForDelete, setItemsSelectedForDelete] = useState<
string[]
>([])
const [isModalVisible, setIsModalVisible] = useState(false)
const [deleteButtonLoading, setDeleteButtonLoading] = useState(false)
const { push } = useHistory()
useEffect(() => {
onSelect?.(selectedItems)
}, [selectedItems])
const getData = async () => {
const params = {
page: pageIndex + 1,
perPage: pageSize,
sort: `${sortField}:${sortDirection}`,
sortField,
search: search,
filters
}
setLoading(true)
const [data, error] = await fetchTableData(resource, params)
if (!error) {
setItems(data?.data.data)
setMetaData(data?.data.meta)
setLoading(false)
}
setLoading(false) // if there is an error so it doesn't load forever
}
useEffect(() => {
getData()
}, [resource, pageIndex, pageSize, sortField, sortDirection, search, filters])
const { toast } = useToastStore()
const deleteItem = async () => {
if (itemsSelectedForDelete.length === 0) return
const [response, error] = await deleteTableData(
resource,
itemsSelectedForDelete
)
if (!error) {
if (selectedItems.length > 1) {
toast(
'Deleted',
<p>Selected {resource?.slugPlural} have been deleted successfully</p>
)
getData()
return
}
toast(
'Deleted',
<p>{resource?.name.toLowerCase()} has been deleted successfully</p>
)
getData()
} else {
toast('Failed to delete', <p>An error occured, please try again.</p>)
}
}
const columns: EuiBasicTableColumn<any>[] = useMemo(() => {
return [
...(resource?.fields
.filter(field => field.showOnIndex)
.map(field => {
const Component: React.FC<IndexComponentProps> =
window.Tensei.components.index[field.component.index] ||
window.Tensei.components.index['Text']
return {
field: field.databaseField,
name: field.name,
sortable: field.isSortable,
truncateText: true,
render: (value: any, record: any) => (
<Component
value={value}
field={field}
values={record}
resource={resource}
/>
)
}
}) || []),
{
name: 'Actions',
actions: inFlyout
? actions || []
: [
{
name: 'Edit',
description: 'Edit this item',
icon: 'pencil',
type: 'icon',
onClick: item => {
push(
window.Tensei.getPath(
`resources/${resource?.slugPlural}/${item.id}/edit`
)
)
}
},
{
name: 'Delete',
description: 'Delete this item',
icon: 'trash',
type: 'icon',
color: 'danger',
onClick: item => {
setIsModalVisible(true)
setItemsSelectedForDelete([item.id])
}
}
]
}
]
}, [resource])
const ConfirmDeleteModal = () => {
const closeModal = () => setIsModalVisible(false)
if (isModalVisible) {
return (
<EuiConfirmModal
title={`Do you want to delete ${
selectedItems.length > 1
? `these ${resource?.slugPlural}?`
: `this ${resource?.name.toLowerCase()}?`
}
`}
onCancel={closeModal}
onConfirm={async () => {
setDeleteButtonLoading(true)
await deleteItem()
setDeleteButtonLoading(false)
closeModal()
}}
cancelButtonText="Cancel"
confirmButtonText={`Delete ${
selectedItems.length > 1
? resource?.slugPlural
: resource?.name.toLowerCase()
}`}
isLoading={deleteButtonLoading}
buttonColor="danger"
defaultFocusedButton="confirm"
>
<p>
You’re about to permanently delete
{selectedItems.length > 1
? ` these ${resource?.slugPlural}`
: ` this ${resource?.name.toLowerCase()}`}
</p>
<p>Are you sure you want to do this?</p>
</EuiConfirmModal>
)
} else {
return null
}
}
const pagination: EuiBasicTableProps<any>['pagination'] = {
pageIndex,
pageSize: pageSize!,
totalItemCount: metaData?.total!,
pageSizeOptions: resource?.perPageOptions
}
const onTableChange = ({ page, sort }: CriteriaWithPagination<any>) => {
setPageIndex(page.index)
setPageSize(page.size)
setSortDirection(sort?.direction!)
setSortField(sort?.field as string)
}
return (
<>
{selectedItems.length ? (
<>
<DeleteButtonContainer>
<EuiButton
onClick={() => {
const items: string[] = selectedItems.map(item => item.id)
setItemsSelectedForDelete([...items])
setIsModalVisible(true)
}}
color="danger"
size="s"
>
Delete {selectedItems.length} item
{selectedItems.length > 1 ? 's' : ''}
</EuiButton>
</DeleteButtonContainer>
</>
) : null}
<EuiBasicTable
items={items}
itemId={'id'}
columns={columns}
hasActions={true}
loading={loading}
selection={
hideSelection
? undefined
: {
selectable: () => true,
onSelectionChange: setSelectedItems,
selectableMessage: selectable =>
selectable ? '' : 'Cannot select this product.'
}
}
isSelectable={true}
sorting={{
sort: {
field: sortField,
direction: sortDirection
}
}}
pagination={pagination}
onChange={onTableChange}
/>
<ConfirmDeleteModal />
</>
)
}
export const ResourceView: React.FunctionComponent = () => {
const { push } = useHistory()
const { resource, findResource } = useResourceStore()
const { resource: resourceSlug } = useParams<{
resource: string
}>()
useEffect(() => {
const found = findResource(resourceSlug)
if (!found) {
push(window.Tensei.getPath(''))
}
}, [resourceSlug])
return (
<>
<DashboardLayout.Topbar>
<EuiTitle size="xs">
<h3>{resource?.namePlural}</h3>
</EuiTitle>
<Link to={window.Tensei.getPath(`resources/${resourceSlug}/create`)}>
<EuiButton fill iconType={'plus'}>
Create {resource?.name?.toLowerCase()}
</EuiButton>
</Link>
</DashboardLayout.Topbar>
<DashboardLayout.Content>
<PageWrapper>
{resource ? <Resource resource={resource} /> : <p>Loading ...</p>}
</PageWrapper>
</DashboardLayout.Content>
</>
)
}
interface ResourceProps {
resource: ResourceContract
tableProps?: Partial<TableProps>
}
export const Resource: React.FunctionComponent<ResourceProps> = ({
resource,
tableProps
}) => {
const [filters, setFilters] = useState<ActiveFilter[]>([])
function clearFilter(filter: ActiveFilter) {
setFilters(
filters.filter(
activeFilter =>
activeFilter.field.databaseField !== filter.field.databaseField
)
)
}
function applyFilter(filter: ActiveFilter) {
setFilters([...filters, filter])
}
const [search, setsearch] = useState('')
const onSearchChange = debounce(500, false, (value: string) => {
setsearch(value)
})
return (
<TableWrapper>
<HeaderContainer>
<SearchAndFilterContainer>
<EuiFieldSearch
placeholder={`Search ${resource.label.toLowerCase()}`}
onChange={event => {
onSearchChange(event.target.value)
}}
/>
<FilterList applyFilter={applyFilter} resource={resource} />
</SearchAndFilterContainer>
</HeaderContainer>
<EuiSpacer size="m" />
<EuiFlexGroup gutterSize="s" alignItems="center">
{filters.map((filter, idx) => (
<EuiFlexItem grow={false} key={idx}>
<EuiButton
color="primary"
onClick={() => {
clearFilter(filter)
}}
>
{filter.field.name} {''}
{filter.clause.name} {filter.value}
</EuiButton>
</EuiFlexItem>
))}
</EuiFlexGroup>
<EuiSpacer size="m" />
<Table
search={search}
filters={filters}
applyFilter={applyFilter}
resource={resource}
{...tableProps}
/>
</TableWrapper>
)
} | the_stack |
/*!
* Copyright (c) 2020 Ron Buckton (rbuckton@chronicles.org)
*
* This file is licensed to you under the terms of the MIT License, found in the LICENSE file
* in the root of this repository or package.
*/
import { Cancelable } from "@esfx/cancelable";
import { SyntaxKind } from "./tokens";
import { Symbol, SymbolKind, SymbolTable } from "./symbols";
import { SourceFile, Production, Parameter, Node, Declaration, Identifier } from "./nodes";
/** {@docCategory Bind} */
export class BindingTable {
public readonly globals: SymbolTable = new SymbolTable();
private _nodeParents: Map<Node, Node> | undefined;
private _nodeSymbols: Map<Node, Symbol> | undefined;
private _symbolDeclarations: Map<Symbol, Set<Declaration>> | undefined;
private _symbolReferences: Map<Symbol, Set<Node>> | undefined;
private _symbolLocals: Map<Symbol, SymbolTable> | undefined;
/**
* Gets a value indicating whether this `BindingTable` is empty.
*/
public get isEmpty() {
return !this._nodeParents
&& !this._nodeSymbols
&& !this._symbolReferences
&& !this._symbolLocals
&& !this._symbolDeclarations
&& this.globals.isEmpty;
}
/**
* Returns whether the provided `Node` has a parent.
*/
public hasParent(node: Node | undefined): boolean {
return node && this._nodeParents ? this._nodeParents.has(node) : false;
}
/**
* Gets the parent of the provided `Node`.
*/
public getParent(node: Node | undefined): Node | undefined {
return node && this._nodeParents?.get(node);
}
/**
* Gets the nearest ancestor of `node` with the provided `kind`.
*/
public getAncestor(node: Node | undefined, kind: SyntaxKind): Node | undefined {
for (let parent = this.getParent(node); parent; parent = this.getParent(parent)) {
if (parent.kind === kind) {
return parent;
}
}
return undefined;
}
/**
* Gets the `SourceFile` containing `node`.
*/
public getSourceFile(node: Node | undefined): SourceFile | undefined {
return node?.kind === SyntaxKind.SourceFile ? node as SourceFile :
this.getAncestor(node, SyntaxKind.SourceFile) as SourceFile | undefined;
}
/**
* Returns whether `node` has been bound to a `Symbol`.
*/
public hasSymbol(node: Node | undefined): boolean {
return node && this._nodeSymbols ? this._nodeSymbols.has(node) : false;
}
/**
* Gets the `Symbol` bound to `node`.
*/
public getSymbol(node: Node | undefined): Symbol | undefined {
return node && this._nodeSymbols?.get(node);
}
/**
* Resolves a `Symbol` for the provided `name` at the given `location` that has the provided `meaning`.
*/
public resolveSymbol(location: Node | undefined, name: string | undefined, meaning: SymbolKind): Symbol | undefined {
if (this._symbolLocals && name) {
while (location) {
if (location.kind === SyntaxKind.SourceFile) {
const result = this.globals.resolveSymbol(name, meaning);
if (result) return result;
break;
}
const symbol = this.getSymbol(location);
const locals = symbol ? this._symbolLocals.get(symbol) : undefined;
const result = locals?.resolveSymbol(name, meaning);
if (result) return result;
location = this.getParent(location);
}
}
return undefined;
}
/**
* Gets the declarations for the provided `symbol`.
*/
public getDeclarations(symbol: Symbol | undefined): (SourceFile | Production | Parameter)[] {
const declarations = symbol && this._symbolDeclarations?.get(symbol);
return declarations ? [...declarations] : [];
}
/**
* Gets the references to the provided `symbol`.
*/
public getReferences(symbol: Symbol | undefined): Node[] {
const references = symbol && this._symbolReferences?.get(symbol);
return references ? [...references] : [];
}
/* @internal */
public _copyFrom(other: BindingTable) {
if (other === this || other.isEmpty) return;
this.globals.copyFrom(other.globals);
if (other._nodeParents) {
this._nodeParents ??= new Map();
for (const [node, parent] of other._nodeParents) {
this._nodeParents.set(node, parent);
}
}
if (other._nodeSymbols) {
this._nodeSymbols ??= new Map();
for (const [node, symbol] of other._nodeSymbols) {
this._nodeSymbols.set(node, symbol);
}
}
if (other._symbolDeclarations) {
this._symbolDeclarations ??= new Map();
for (const [symbol, otherDeclarations] of other._symbolDeclarations) {
let declarations = this._symbolDeclarations.get(symbol);
if (!declarations) this._symbolDeclarations.set(symbol, declarations = new Set());
for (const declaration of otherDeclarations) {
declarations.add(declaration);
}
}
}
if (other._symbolReferences) {
this._symbolReferences ??= new Map();
for (const [symbol, otherReferences] of other._symbolReferences) {
let references = this._symbolReferences.get(symbol);
if (!references) this._symbolReferences.set(symbol, references = new Set());
for (const reference of otherReferences) {
references.add(reference);
}
}
}
if (other._symbolLocals) {
this._symbolLocals ??= new Map();
for (const [symbol, otherLocals] of other._symbolLocals) {
let locals = this._symbolLocals.get(symbol);
if (!locals) this._symbolLocals.set(symbol, locals = new SymbolTable());
locals.copyFrom(otherLocals);
}
}
}
/* @internal */
public _setParent(node: Node | undefined, parent: Node | undefined): void {
if (node && parent) {
this._nodeParents ??= new Map();
this._nodeParents.set(node, parent);
}
}
/* @internal */
public _setSymbol(node: Identifier | undefined, symbol: Symbol | undefined): void {
if (node && symbol) {
this._setSymbolForNode(node, symbol);
this._addReferenceToSymbol(symbol, node);
}
}
/* @internal */
public _addDeclarationToSymbol(symbol: Symbol | undefined, node: SourceFile | Production | Parameter | undefined): void {
if (symbol && node) {
this._symbolDeclarations ??= new Map();
let declarations = this._symbolDeclarations.get(symbol);
if (!declarations) this._symbolDeclarations.set(symbol, declarations = new Set());
declarations.add(node);
this._setSymbolForNode(node, symbol);
if (node.kind !== SyntaxKind.SourceFile) {
this._addReferenceToSymbol(symbol, node.name);
}
}
}
/* @internal */
public _getScope(container: Symbol): SymbolTable {
this._symbolLocals ??= new Map();
let scope = this._symbolLocals.get(container);
if (!scope) this._symbolLocals.set(container, scope = new SymbolTable());
return scope;
}
private _setSymbolForNode(node: Node, symbol: Symbol): void {
this._nodeSymbols ??= new Map();
this._nodeSymbols.set(node, symbol);
}
private _addReferenceToSymbol(symbol: Symbol, node: Node): void {
this._symbolReferences ??= new Map();
let references = this._symbolReferences.get(symbol);
if (!references) this._symbolReferences.set(symbol, references = new Set());
references.add(node);
}
}
/** {@docCategory Bind} */
export class Binder {
private _parentNode: Node | undefined;
private _parentSymbol: Symbol | undefined;
/**
* Binds a `SourceFile` in the provided `BindingTable`.
*/
public bindSourceFile(file: SourceFile, bindings: BindingTable, cancelable?: Cancelable): void {
Cancelable.throwIfSignaled(cancelable);
if (bindings.globals.resolveSymbol(file.filename, SymbolKind.SourceFile)) {
// skip files that have already been bound.
return;
}
const fileBindings = new BindingTable();
const scope = fileBindings.globals;
const symbol = this._declareSymbol(fileBindings, scope, file.filename, file, SymbolKind.SourceFile);
this._bindChildren(fileBindings, file, symbol, scope);
bindings._copyFrom(fileBindings);
}
private _bindProduction(bindings: BindingTable, scope: SymbolTable, node: Production): void {
const symbol = this._declareSymbol(bindings, scope, node.name.text, node, SymbolKind.Production);
const newScope = bindings._getScope(symbol);
this._bindChildren(bindings, node, symbol, newScope);
}
private _bindParameter(bindings: BindingTable, scope: SymbolTable, node: Parameter): void {
const symbol = this._declareSymbol(bindings, scope, node.name.text, node, SymbolKind.Parameter);
this._bindChildren(bindings, node, symbol, scope);
}
private _bindChildren(bindings: BindingTable, parentNode: Node, parentSymbol: Symbol | undefined, scope: SymbolTable): void {
const saveParentNode = this._parentNode;
const saveParentSymbol = this._parentSymbol;
this._parentNode = parentNode;
this._parentSymbol = parentSymbol;
for (const child of parentNode.children()) {
this._bind(bindings, scope, child);
}
this._parentSymbol = saveParentSymbol;
this._parentNode = saveParentNode;
}
private _bind(bindings: BindingTable, scope: SymbolTable, node: Node): void {
if (node) {
bindings._setParent(node, this._parentNode);
switch (node.kind) {
case SyntaxKind.Production:
this._bindProduction(bindings, scope, <Production>node);
break;
case SyntaxKind.Parameter:
this._bindParameter(bindings, scope, <Parameter>node);
break;
default:
this._bindChildren(bindings, node, this._parentSymbol, scope);
break;
}
}
}
private _declareSymbol(bindings: BindingTable, scope: SymbolTable, name: string | undefined, declaration: SourceFile | Production | Parameter, kind: SymbolKind): Symbol {
const symbol = scope.declareSymbol(name, kind, this._parentSymbol);
bindings._addDeclarationToSymbol(symbol, declaration);
return symbol;
}
} | the_stack |
import * as monacoApi from 'monaco-editor';
import stripComments from './utils/strip-comments';
import { createPlugin } from './plugin-api';
declare module 'monaco-editor' {
namespace editor {
// interface IStandaloneCodeEditor {
// addSelectAction: (action: IQuickSelectAction) => monacoApi.IDisposable;
// }
export function setTheme(
themeName: string | monacoApi.editor.IStandaloneThemeData
): void;
export function getTheme(
themeName: string
): monacoApi.editor.IStandaloneThemeData | null;
export function getDefinedThemes(): {
[key: string]: monacoApi.editor.IStandaloneThemeData;
};
export function defineThemes(themes: {
[key: string]: monacoApi.editor.IStandaloneThemeData;
}): void;
export function onDidChangeTheme(
listener: (theme: {
name: string;
theme: monacoApi.editor.IStandaloneThemeData;
}) => void
): monacoApi.IDisposable;
}
}
export default createPlugin(
{ name: 'core.themes', dependencies: ['core.editors'] },
(monaco) => {
const setTheme = monaco.editor.setTheme;
const definedThemes = {};
const _onDidChangeTheme = new monaco.Emitter<{
name: string;
theme: monacoApi.editor.IStandaloneThemeData;
}>();
monaco.editor.onDidChangeTheme = _onDidChangeTheme.event;
let defineTheme = monaco.editor.defineTheme;
monaco.editor.defineTheme = (name, theme) => {
defineTheme(name, theme);
definedThemes[name] = theme;
};
monaco.editor.setTheme = (
theme: string | monacoApi.editor.IStandaloneThemeData
) => {
if (typeof theme === 'string') {
try {
const resolvedTheme = JSON.parse(stripComments(theme));
if (typeof resolvedTheme === 'object' && resolvedTheme?.colors) {
monaco.editor.setTheme(resolvedTheme);
return;
} else {
console.log('[monaco] setting theme:', theme);
setTheme(theme);
_onDidChangeTheme.fire({
name: theme,
theme: definedThemes[theme],
});
}
} catch (e) {
console.log('[monaco] setting theme:', theme);
setTheme(theme);
_onDidChangeTheme.fire({
name: theme,
theme: definedThemes[theme],
});
}
} else if (typeof theme === 'object') {
try {
monaco.editor.defineTheme('custom', theme);
console.log('[monaco] setting theme:', theme);
setTheme('custom');
_onDidChangeTheme.fire({ name: 'custom', theme });
} catch (e) {
console.warn(`[monaco] error setting theme: ${e}`);
}
}
};
monaco.editor.getDefinedThemes = () => {
return definedThemes;
};
monaco.editor.defineThemes = (themes) => {
Object.keys(themes).forEach((themeName) => {
monaco.editor.defineTheme(
themeName,
themes[themeName as keyof typeof themes]
);
});
};
monaco.editor.getTheme = (themeName) => {
return monaco.editor.getFocusedEditor()?.['_themeService'];
};
}
);
// function setupThemes(
// monaco: typeof monacoApi,
// // editor: monacoApi.editor.IStandaloneCodeEditor,
// themes: any
// ) {
// // const allThemes = {
// // // ...defaultThemes,
// // ...themes,
// // };
// // Object.keys(allThemes).forEach((themeName) => {
// // monaco.editor.defineTheme(
// // themeName,
// // allThemes[themeName as keyof typeof allThemes]
// // );
// // });
// // editor.addSelectAction({
// // id: 'editor.action.selectTheme',
// // label: 'Preferences: Color Theme',
// // choices: () => Object.keys(themeNames),
// // runChoice: (choice, mode, ctx, api) => {
// // if (mode === 0) {
// // api.editor.setTheme(themeNames[choice]);
// // } else if (mode === 1) {
// // api.editor.setTheme(themeNames[choice]);
// // }
// // },
// // runAction: function (editor: any, api: any) {
// // const _this: any = this;
// // const currentTheme = editor._themeService._theme.themeName;
// // console.log(currentTheme);
// // const controller = _this.getController(editor);
// // const oldDestroy = controller.widget.quickOpenWidget.callbacks.onCancel;
// // controller.widget.quickOpenWidget.callbacks.onCancel = function () {
// // debugger;
// // monaco.editor.setTheme(currentTheme);
// // oldDestroy();
// // };
// // console.log(
// // controller,
// // controller.widget.quickOpenWidget.callbacks.onCancel,
// // this
// // );
// // _this.show(editor);
// // return Promise.resolve();
// // },
// // });
// }
// // A list of color names:
// 'foreground' // Overall foreground color. This color is only used if not overridden by a component.
// 'errorForeground' // Overall foreground color for error messages. This color is only used if not overridden by a component.
// 'descriptionForeground' // Foreground color for description text providing additional information, for example for a label.
// 'focusBorder' // Overall border color for focused elements. This color is only used if not overridden by a component.
// 'contrastBorder' // An extra border around elements to separate them from others for greater contrast.
// 'contrastActiveBorder' // An extra border around active elements to separate them from others for greater contrast.
// 'selection.background' // The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor.
// 'textSeparator.foreground' // Color for text separators.
// 'textLink.foreground' // Foreground color for links in text.
// 'textLink.activeForeground' // Foreground color for active links in text.
// 'textPreformat.foreground' // Foreground color for preformatted text segments.
// 'textBlockQuote.background' // Background color for block quotes in text.
// 'textBlockQuote.border' // Border color for block quotes in text.
// 'textCodeBlock.background' // Background color for code blocks in text.
// 'widget.shadow' // Shadow color of widgets such as find/replace inside the editor.
// 'input.background' // Input box background.
// 'input.foreground' // Input box foreground.
// 'input.border' // Input box border.
// 'inputOption.activeBorder' // Border color of activated options in input fields.
// 'input.placeholderForeground' // Input box foreground color for placeholder text.
// 'inputValidation.infoBackground' // Input validation background color for information severity.
// 'inputValidation.infoBorder' // Input validation border color for information severity.
// 'inputValidation.warningBackground' // Input validation background color for information warning.
// 'inputValidation.warningBorder' // Input validation border color for warning severity.
// 'inputValidation.errorBackground' // Input validation background color for error severity.
// 'inputValidation.errorBorder' // Input validation border color for error severity.
// 'dropdown.background' // Dropdown background.
// 'dropdown.foreground' // Dropdown foreground.
// 'dropdown.border' // Dropdown border.
// 'list.focusBackground' // List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.
// 'list.focusForeground' // List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.
// 'list.activeSelectionBackground' // List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.
// 'list.activeSelectionForeground' // List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not.
// 'list.inactiveSelectionBackground' // List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.
// 'list.inactiveSelectionForeground' // List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not.
// 'list.hoverBackground' // List/Tree background when hovering over items using the mouse.
// 'list.hoverForeground' // List/Tree foreground when hovering over items using the mouse.
// 'list.dropBackground' // List/Tree drag and drop background when moving items around using the mouse.
// 'list.highlightForeground' // List/Tree foreground color of the match highlights when searching inside the list/tree.
// 'pickerGroup.foreground' // Quick picker color for grouping labels.
// 'pickerGroup.border' // Quick picker color for grouping borders.
// 'button.foreground' // Button foreground color.
// 'button.background' // Button background color.
// 'button.hoverBackground' // Button background color when hovering.
// 'badge.background' // Badge background color. Badges are small information labels, e.g. for search results count.
// 'badge.foreground' // Badge foreground color. Badges are small information labels, e.g. for search results count.
// 'scrollbar.shadow' // Scrollbar shadow to indicate that the view is scrolled.
// 'scrollbarSlider.background' // Slider background color.
// 'scrollbarSlider.hoverBackground' // Slider background color when hovering.
// 'scrollbarSlider.activeBackground' // Slider background color when active.
// 'progressBar.background' // Background color of the progress bar that can show for long running operations.
// 'editor.background' // Editor background color.
// 'editor.foreground' // Editor default foreground color.
// 'editorWidget.background' // Background color of editor widgets, such as find/replace.
// 'editorWidget.border' // Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget.
// 'editor.selectionBackground' // Color of the editor selection.
// 'editor.selectionForeground' // Color of the selected text for high contrast.
// 'editor.inactiveSelectionBackground' // Color of the selection in an inactive editor.
// 'editor.selectionHighlightBackground' // Color for regions with the same content as the selection.
// 'editor.findMatchBackground' // Color of the current search match.
// 'editor.findMatchHighlightBackground' // Color of the other search matches.
// 'editor.findRangeHighlightBackground' // Color the range limiting the search.
// 'editor.hoverHighlightBackground' // Highlight below the word for which a hover is shown.
// 'editorHoverWidget.background' // Background color of the editor hover.
// 'editorHoverWidget.border' // Border color of the editor hover.
// 'editorLink.activeForeground' // Color of active links.
// 'diffEditor.insertedTextBackground' // Background color for text that got inserted.
// 'diffEditor.removedTextBackground' // Background color for text that got removed.
// 'diffEditor.insertedTextBorder' // Outline color for the text that got inserted.
// 'diffEditor.removedTextBorder' // Outline color for text that got removed.
// 'editorOverviewRuler.currentContentForeground' // Current overview ruler foreground for inline merge-conflicts.
// 'editorOverviewRuler.incomingContentForeground' // Incoming overview ruler foreground for inline merge-conflicts.
// 'editorOverviewRuler.commonContentForeground' // Common ancestor overview ruler foreground for inline merge-conflicts.
// 'editor.lineHighlightBackground' // Background color for the highlight of line at the cursor position.
// 'editor.lineHighlightBorder' // Background color for the border around the line at the cursor position.
// 'editor.rangeHighlightBackground' // Background color of highlighted ranges, like by quick open and find features.
// 'editorCursor.foreground' // Color of the editor cursor.
// 'editorWhitespace.foreground' // Color of whitespace characters in the editor.
// 'editorIndentGuide.background' // Color of the editor indentation guides.
// 'editorLineNumber.foreground' // Color of editor line numbers.
// 'editorRuler.foreground' // Color of the editor rulers.
// 'editorCodeLens.foreground' // Foreground color of editor code lenses
// 'editorBracketMatch.background' // Background color behind matching brackets
// 'editorBracketMatch.border' // Color for matching brackets boxes
// 'editorOverviewRuler.border' // Color of the overview ruler border.
// 'editorGutter.background' // Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.
// 'editorError.foreground' // Foreground color of error squigglies in the editor.
// 'editorError.border' // Border color of error squigglies in the editor.
// 'editorWarning.foreground' // Foreground color of warning squigglies in the editor.
// 'editorWarning.border' // Border color of warning squigglies in the editor.
// 'editorMarkerNavigationError.background' // Editor marker navigation widget error color.
// 'editorMarkerNavigationWarning.background' // Editor marker navigation widget warning color.
// 'editorMarkerNavigation.background' // Editor marker navigation widget background.
// 'editorSuggestWidget.background' // Background color of the suggest widget.
// 'editorSuggestWidget.border' // Border color of the suggest widget.
// 'editorSuggestWidget.foreground' // Foreground color of the suggest widget.
// 'editorSuggestWidget.selectedBackground' // Background color of the selected entry in the suggest widget.
// 'editorSuggestWidget.highlightForeground' // Color of the match highlights in the suggest widget.
// 'editor.wordHighlightBackground' // Background color of a symbol during read-access, like reading a variable.
// 'editor.wordHighlightStrongBackground' // Background color of a symbol during write-access, like writing to a variable.
// 'peekViewTitle.background' // Background color of the peek view title area.
// 'peekViewTitleLabel.foreground' // Color of the peek view title.
// 'peekViewTitleDescription.foreground' // Color of the peek view title info.
// 'peekView.border' // Color of the peek view borders and arrow.
// 'peekViewResult.background' // Background color of the peek view result list.
// 'peekViewResult.lineForeground' // Foreground color for line nodes in the peek view result list.
// 'peekViewResult.fileForeground' // Foreground color for file nodes in the peek view result list.
// 'peekViewResult.selectionBackground' // Background color of the selected entry in the peek view result list.
// 'peekViewResult.selectionForeground' // Foreground color of the selected entry in the peek view result list.
// 'peekViewEditor.background' // Background color of the peek view editor.
// 'peekViewEditorGutter.background' // Background color of the gutter in the peek view editor.
// 'peekViewResult.matchHighlightBackground' // Match highlight color in the peek view result list.
// 'peekViewEditor.matchHighlightBackground' // Match highlight color in the peek view editor. | the_stack |
declare module "vscode" {
/**
* Namespace for testing functionality. Tests are published by registering
* {@link TestController} instances, then adding {@link TestItem TestItems}.
* Controllers may also describe how to run tests by creating one or more
* {@link TestRunProfile} instances.
*/
export namespace tests {
/**
* Creates a new test controller.
*
* @param id Identifier for the controller, must be globally unique.
* @param label A human-readable label for the controller.
* @returns An instance of the {@link TestController}.
*/
export function createTestController(
id: string,
label: string
): TestController;
//#region Test Observer
/**
* Requests that tests be run by their controller.
* @param run Run options to use.
* @param token Cancellation token for the test run
*/
export function runTests(run: TestRunRequest, token?: CancellationToken): Thenable<void>;
/**
* Returns an observer that watches and can request tests.
*/
export function createTestObserver(): TestObserver;
/**
* List of test results stored by the editor, sorted in descending
* order by their `completedAt` time.
*/
export const testResults: ReadonlyArray<TestRunResult>;
/**
* Event that fires when the {@link testResults} array is updated.
*/
export const onDidChangeTestResults: Event<void>;
//#endregion
}
/**
* The kind of executions that {@link TestRunProfile TestRunProfiles} control.
*/
export enum TestRunProfileKind {
Run = 1,
Debug = 2,
Coverage = 3,
}
/**
* A TestRunProfile describes one way to execute tests in a {@link TestController}.
*/
export interface TestRunProfile {
/**
* Label shown to the user in the UI.
*
* Note that the label has some significance if the user requests that
* tests be re-run in a certain way. For example, if tests were run
* normally and the user requests to re-run them in debug mode, the editor
* will attempt use a configuration with the same label of the `Debug`
* kind. If there is no such configuration, the default will be used.
*/
label: string;
/**
* Configures what kind of execution this profile controls. If there
* are no profiles for a kind, it will not be available in the UI.
*/
readonly kind: TestRunProfileKind;
/**
* Controls whether this profile is the default action that will
* be taken when its kind is actioned. For example, if the user clicks
* the generic "run all" button, then the default profile for
* {@link TestRunProfileKind.Run} will be executed, although the
* user can configure this.
*/
isDefault: boolean;
/**
* Associated tag for the profile. If this is set, only {@link TestItem}
* instances with the same tag will be eligible to execute in this profile.
*/
tag: TestTag | undefined;
/**
* If this method is present, a configuration gear will be present in the
* UI, and this method will be invoked when it's clicked. When called,
* you can take other editor actions, such as showing a quick pick or
* opening a configuration file.
*/
configureHandler: (() => void) | undefined;
/**
* Handler called to start a test run. When invoked, the function should call
* {@link TestController.createTestRun} at least once, and all test runs
* associated with the request should be created before the function returns
* or the returned promise is resolved.
*
* @param request Request information for the test run.
* @param cancellationToken Token that signals the used asked to abort the
* test run. If cancellation is requested on this token, all {@link TestRun}
* instances associated with the request will be
* automatically cancelled as well.
*/
runHandler: (
request: TestRunRequest,
token: CancellationToken
) => Thenable<void> | void;
/**
* Deletes the run profile.
*/
dispose(): void;
}
/**
* Entry point to discover and execute tests. It contains {@link TestController.items} which
* are used to populate the editor UI, and is associated with
* {@link TestController.createRunProfile run profiles} to allow
* for tests to be executed.
*/
export interface TestController {
/**
* The id of the controller passed in {@link vscode.tests.createTestController}.
* This must be globally unique.
*/
readonly id: string;
/**
* Human-readable label for the test controller.
*/
label: string;
/**
* A collection of "top-level" {@link TestItem} instances, which can in
* turn have their own {@link TestItem.children children} to form the
* "test tree."
*
* The extension controls when to add tests. For example, extensions should
* add tests for a file when {@link vscode.workspace.onDidOpenTextDocument}
* fires in order for decorations for tests within a file to be visible.
*
* However, the editor may sometimes explicitly request children using the
* {@link resolveHandler} See the documentation on that method for more details.
*/
readonly items: TestItemCollection;
/**
* Creates a profile used for running tests. Extensions must create
* at least one profile in order for tests to be run.
* @param label A human-readable label for this profile.
* @param kind Configures what kind of execution this profile manages.
* @param runHandler Function called to start a test run.
* @param isDefault Whether this is the default action for its kind.
* @param tag Profile test tag.
* @returns An instance of a {@link TestRunProfile}, which is automatically
* associated with this controller.
*/
createRunProfile(
label: string,
kind: TestRunProfileKind,
runHandler: (
request: TestRunRequest,
token: CancellationToken
) => Thenable<void> | void,
isDefault?: boolean,
tag?: TestTag
): TestRunProfile;
/**
* A function provided by the extension that the editor may call to request
* children of a test item, if the {@link TestItem.canResolveChildren} is
* `true`. When called, the item should discover children and call
* {@link vscode.tests.createTestItem} as children are discovered.
*
* Generally the extension manages the lifecycle of test items, but under
* certain conditions the editor may request the children of a specific
* item to be loaded. For example, if the user requests to re-run tests
* after reloading the editor, the editor may need to call this method
* to resolve the previously-run tests.
*
* The item in the explorer will automatically be marked as "busy" until
* the function returns or the returned thenable resolves.
*
* @param item An unresolved test item for which children are being
* requested, or `undefined` to resolve the controller's initial {@link items}.
*/
resolveHandler?: (item: TestItem | undefined) => Thenable<void> | void;
/**
* Creates a {@link TestRun}. This should be called by the
* {@link TestRunProfile} when a request is made to execute tests, and may
* also be called if a test run is detected externally. Once created, tests
* that are included in the request will be moved into the queued state.
*
* All runs created using the same `request` instance will be grouped
* together. This is useful if, for example, a single suite of tests is
* run on multiple platforms.
*
* @param request Test run request. Only tests inside the `include` may be
* modified, and tests in its `exclude` are ignored.
* @param name The human-readable name of the run. This can be used to
* disambiguate multiple sets of results in a test run. It is useful if
* tests are run across multiple platforms, for example.
* @param persist Whether the results created by the run should be
* persisted in the editor. This may be false if the results are coming from
* a file already saved externally, such as a coverage information file.
* @returns An instance of the {@link TestRun}. It will be considered "running"
* from the moment this method is invoked until {@link TestRun.end} is called.
*/
createTestRun(
request: TestRunRequest,
name?: string,
persist?: boolean
): TestRun;
/**
* Creates a new managed {@link TestItem} instance. It can be added into
* the {@link TestItem.children} of an existing item, or into the
* {@link TestController.items}.
*
* @param id Identifier for the TestItem. The test item's ID must be unique
* in the {@link TestItemCollection} it's added to.
* @param label Human-readable label of the test item.
* @param uri URI this TestItem is associated with. May be a file or directory.
*/
createTestItem(id: string, label: string, uri?: Uri): TestItem;
/**
* Unregisters the test controller, disposing of its associated tests
* and unpersisted results.
*/
dispose(): void;
}
/**
* A TestRunRequest is a precursor to a {@link TestRun}, which in turn is
* created by passing a request to {@link tests.runTests}. The TestRunRequest
* contains information about which tests should be run, which should not be
* run, and how they are run (via the {@link profile}).
*
* In general, TestRunRequests are created by the editor and pass to
* {@link TestRunProfile.runHandler}, however you can also create test
* requests and runs outside of the `runHandler`.
*/
export class TestRunRequest {
/**
* A filter for specific tests to run. If given, the extension should run
* all of the included tests and all their children, excluding any tests
* that appear in {@link TestRunRequest.exclude}. If this property is
* undefined, then the extension should simply run all tests.
*
* The process of running tests should resolve the children of any test
* items who have not yet been resolved.
*/
readonly include: TestItem[] | undefined;
/**
* An array of tests the user has marked as excluded from the test included
* in this run; exclusions should apply after inclusions.
*
* May be omitted if no exclusions were requested. Test controllers should
* not run excluded tests or any children of excluded tests.
*/
readonly exclude: TestItem[] | undefined;
/**
* The profile used for this request. This will always be defined
* for requests issued from the editor UI, though extensions may
* programmatically create requests not associated with any profile.
*/
readonly profile: TestRunProfile | undefined;
/**
* @param tests Array of specific tests to run, or undefined to run all tests
* @param exclude An array of tests to exclude from the run.
* @param profile The run profile used for this request.
*/
constructor(
include?: readonly TestItem[],
exclude?: readonly TestItem[],
profile?: TestRunProfile
);
}
/**
* Tags can be associated with {@link TestItem TestItems} and
* {@link TestRunProfile TestRunProfiles}. A profile with a tag can only
* execute tests that include that tag in their {@link TestItem.tags} array.
*/
export class TestTag {
/**
* ID of the test tag. `TestTag` instances with the same ID are considered
* to be identical.
*/
readonly id: string;
/**
* Creates a new TestTag instance.
* @param id ID of the test tag.
*/
constructor(id: string);
}
/**
* Options given to {@link TestController.runTests}
*/
export interface TestRun {
/**
* The human-readable name of the run. This can be used to
* disambiguate multiple sets of results in a test run. It is useful if
* tests are run across multiple platforms, for example.
*/
readonly name: string | undefined;
/**
* A cancellation token which will be triggered when the test run is
* canceled from the UI.
*/
readonly token: CancellationToken;
/**
* Whether the test run will be persisted across reloads by the editor.
*/
readonly isPersisted: boolean;
/**
* Indicates a test is queued for later execution.
* @param test Test item to update.
*/
enqueued(test: TestItem): void;
/**
* Indicates a test has started running.
* @param test Test item to update.
*/
started(test: TestItem): void;
/**
* Indicates a test has been skipped.
* @param test Test item to update.
*/
skipped(test: TestItem): void;
/**
* Indicates a test has failed. You should pass one or more
* {@link TestMessage TestMessages} to describe the failure.
* @param test Test item to update.
* @param messages Messages associated with the test failure.
* @param duration How long the test took to execute, in milliseconds.
*/
failed(
test: TestItem,
message: TestMessage | readonly TestMessage[],
duration?: number
): void;
/**
* Indicates a test has errored. You should pass one or more
* {@link TestMessage TestMessages} to describe the failure. This differs
* from the "failed" state in that it indicates a test that couldn't be
* executed at all, from a compilation error for example.
* @param test Test item to update.
* @param messages Messages associated with the test failure.
* @param duration How long the test took to execute, in milliseconds.
*/
errored(
test: TestItem,
message: TestMessage | readonly TestMessage[],
duration?: number
): void;
/**
* Indicates a test has passed.
* @param test Test item to update.
* @param duration How long the test took to execute, in milliseconds.
*/
passed(test: TestItem, duration?: number): void;
/**
* Appends raw output from the test runner. On the user's request, the
* output will be displayed in a terminal. ANSI escape sequences,
* such as colors and text styles, are supported.
*
* @param output Output text to append.
* @param location Indicate that the output was logged at the given
* location.
* @param test Test item to associate the output with.
*/
appendOutput(output: string, location?: Location, test?: TestItem): void;
/**
* Signals that the end of the test run. Any tests included in the run whose
* states have not been updated will have their state reset.
*/
end(): void;
}
/**
* Collection of test items, found in {@link TestItem.children} and
* {@link TestController.items}.
*/
export interface TestItemCollection {
/**
* Gets the number of items in the collection.
*/
readonly size: number;
/**
* Replaces the items stored by the collection.
* @param items Items to store.
*/
replace(items: readonly TestItem[]): void;
/**
* Iterate over each entry in this collection.
*
* @param callback Function to execute for each entry.
* @param thisArg The `this` context used when invoking the handler function.
*/
forEach(
callback: (item: TestItem, collection: TestItemCollection) => unknown,
thisArg?: unknown
): void;
/**
* Adds the test item to the children. If an item with the same ID already
* exists, it'll be replaced.
* @param items Item to add.
*/
add(item: TestItem): void;
/**
* Removes a single test item from the collection.
* @param itemId Item ID to delete.
*/
delete(itemId: string): void;
/**
* Efficiently gets a test item by ID, if it exists, in the children.
* @param itemId Item ID to get.
* @returns The found item or undefined if it does not exist.
*/
get(itemId: string): TestItem | undefined;
}
/**
* An item shown in the "test explorer" view.
*
* A `TestItem` can represent either a test suite or a test itself, since
* they both have similar capabilities.
*/
export interface TestItem {
/**
* Identifier for the `TestItem`. This is used to correlate
* test results and tests in the document with those in the workspace
* (test explorer). This cannot change for the lifetime of the `TestItem`,
* and must be unique among its parent's direct children.
*/
readonly id: string;
/**
* URI this `TestItem` is associated with. May be a file or directory.
*/
readonly uri: Uri | undefined;
/**
* The children of this test item. For a test suite, this may contain the
* individual test cases or nested suites.
*/
readonly children: TestItemCollection;
/**
* The parent of this item. It's set automatically, and is undefined
* top-level items in the {@link TestController.items} and for items that
* aren't yet included in another item's {@link children}.
*/
readonly parent: TestItem | undefined;
/**
* Tags associated with this test item. May be used in combination with
* {@link TestRunProfile.tags}, or simply as an organizational feature.
*/
tags: readonly TestTag[];
/**
* Indicates whether this test item may have children discovered by resolving.
*
* If true, this item is shown as expandable in the Test Explorer view and
* expanding the item will cause {@link TestController.resolveHandler}
* to be invoked with the item.
*
* Default to `false`.
*/
canResolveChildren: boolean;
/**
* Controls whether the item is shown as "busy" in the Test Explorer view.
* This is useful for showing status while discovering children.
*
* Defaults to `false`.
*/
busy: boolean;
/**
* Display name describing the test case.
*/
label: string;
/**
* Optional description that appears next to the label.
*/
description?: string;
/**
* Location of the test item in its {@link uri}.
*
* This is only meaningful if the `uri` points to a file.
*/
range: Range | undefined;
/**
* Optional error encountered while loading the test.
*
* Note that this is not a test result and should only be used to represent errors in
* test discovery, such as syntax errors.
*/
error: string | MarkdownString | undefined;
/**
* Marks the test as outdated. This can happen as a result of file changes,
* for example. In "auto run" mode, tests that are outdated will be
* automatically rerun after a short delay. Invoking this on a
* test with children will mark the entire subtree as outdated.
*
* Extensions should generally not override this method.
*/
// todo@api still unsure about this
invalidateResults(): void;
}
/**
* Message associated with the test state. Can be linked to a specific
* source range -- useful for assertion failures, for example.
*/
export class TestMessage {
/**
* Human-readable message text to display.
*/
message: string | MarkdownString;
/**
* Expected test output. If given with {@link actualOutput}, a diff view will be shown.
*/
expectedOutput?: string;
/**
* Actual test output. If given with {@link expectedOutput}, a diff view will be shown.
*/
actualOutput?: string;
/**
* Associated file location.
*/
location?: Location;
/**
* Creates a new TestMessage that will present as a diff in the editor.
* @param message Message to display to the user.
* @param expected Expected output.
* @param actual Actual output.
*/
static diff(
message: string | MarkdownString,
expected: string,
actual: string
): TestMessage;
/**
* Creates a new TestMessage instance.
* @param message The message to show to the user.
*/
constructor(message: string | MarkdownString);
}
//#region Test Observer
export interface TestObserver {
/**
* List of tests returned by test provider for files in the workspace.
*/
readonly tests: ReadonlyArray<TestItem>;
/**
* An event that fires when an existing test in the collection changes, or
* null if a top-level test was added or removed. When fired, the consumer
* should check the test item and all its children for changes.
*/
readonly onDidChangeTest: Event<TestsChangeEvent>;
/**
* Dispose of the observer, allowing the editor to eventually tell test
* providers that they no longer need to update tests.
*/
dispose(): void;
}
export interface TestsChangeEvent {
/**
* List of all tests that are newly added.
*/
readonly added: ReadonlyArray<TestItem>;
/**
* List of existing tests that have updated.
*/
readonly updated: ReadonlyArray<TestItem>;
/**
* List of existing tests that have been removed.
*/
readonly removed: ReadonlyArray<TestItem>;
}
/**
* A test item is an item shown in the "test explorer" view. It encompasses
* both a suite and a test, since they have almost or identical capabilities.
*/
export interface TestItem {
/**
* Marks the test as outdated. This can happen as a result of file changes,
* for example. In "auto run" mode, tests that are outdated will be
* automatically rerun after a short delay. Invoking this on a
* test with children will mark the entire subtree as outdated.
*
* Extensions should generally not override this method.
*/
// todo@api still unsure about this
invalidateResults(): void;
}
/**
* TestResults can be provided to the editor in {@link tests.publishTestResult},
* or read from it in {@link tests.testResults}.
*
* The results contain a 'snapshot' of the tests at the point when the test
* run is complete. Therefore, information such as its {@link Range} may be
* out of date. If the test still exists in the workspace, consumers can use
* its `id` to correlate the result instance with the living test.
*/
export interface TestRunResult {
/**
* Unix milliseconds timestamp at which the test run was completed.
*/
readonly completedAt: number;
/**
* Optional raw output from the test run.
*/
readonly output?: string;
/**
* List of test results. The items in this array are the items that
* were passed in the {@link tests.runTests} method.
*/
readonly results: ReadonlyArray<Readonly<TestResultSnapshot>>;
}
/**
* A {@link TestItem}-like interface with an associated result, which appear
* or can be provided in {@link TestResult} interfaces.
*/
export interface TestResultSnapshot {
/**
* Unique identifier that matches that of the associated TestItem.
* This is used to correlate test results and tests in the document with
* those in the workspace (test explorer).
*/
readonly id: string;
/**
* Parent of this item.
*/
readonly parent?: TestResultSnapshot;
/**
* URI this TestItem is associated with. May be a file or file.
*/
readonly uri?: Uri;
/**
* Display name describing the test case.
*/
readonly label: string;
/**
* Optional description that appears next to the label.
*/
readonly description?: string;
/**
* Location of the test item in its `uri`. This is only meaningful if the
* `uri` points to a file.
*/
readonly range?: Range;
/**
* State of the test in each task. In the common case, a test will only
* be executed in a single task and the length of this array will be 1.
*/
readonly taskStates: ReadonlyArray<TestSnapshotTaskState>;
/**
* Optional list of nested tests for this item.
*/
readonly children: Readonly<TestResultSnapshot>[];
}
export interface TestSnapshotTaskState {
/**
* Current result of the test.
*/
readonly state: TestResultState;
/**
* The number of milliseconds the test took to run. This is set once the
* `state` is `Passed`, `Failed`, or `Errored`.
*/
readonly duration?: number;
/**
* Associated test run message. Can, for example, contain assertion
* failure information if the test fails.
*/
readonly messages: ReadonlyArray<TestMessage>;
}
/**
* Possible states of tests in a test run.
*/
export enum TestResultState {
// Test will be run, but is not currently running.
Queued = 1,
// Test is currently running
Running = 2,
// Test run has passed
Passed = 3,
// Test run has failed (on an assertion)
Failed = 4,
// Test run has been skipped
Skipped = 5,
// Test run failed for some other reason (compilation error, timeout, etc)
Errored = 6
}
//#endregion
//#region Test Coverage
export interface TestRun {
/**
* Test coverage provider for this result. An extension can defer setting
* this until after a run is complete and coverage is available.
*/
coverageProvider?: TestCoverageProvider
// ...
}
/**
* Provides information about test coverage for a test result.
* Methods on the provider will not be called until the test run is complete
*/
export interface TestCoverageProvider<T extends FileCoverage = FileCoverage> {
/**
* Returns coverage information for all files involved in the test run.
* @param token A cancellation token.
* @return Coverage metadata for all files involved in the test.
*/
provideFileCoverage(token: CancellationToken): ProviderResult<T[]>;
/**
* Give a FileCoverage to fill in more data, namely {@link FileCoverage.detailedCoverage}.
* The editor will only resolve a FileCoverage once, and onyl if detailedCoverage
* is undefined.
*
* @param coverage A coverage object obtained from {@link provideFileCoverage}
* @param token A cancellation token.
* @return The resolved file coverage, or a thenable that resolves to one. It
* is OK to return the given `coverage`. When no result is returned, the
* given `coverage` will be used.
*/
resolveFileCoverage?(coverage: T, token: CancellationToken): ProviderResult<T>;
}
/**
* A class that contains information about a covered resource. A count can
* be give for lines, branches, and functions in a file.
*/
export class CoveredCount {
/**
* Number of items covered in the file.
*/
covered: number;
/**
* Total number of covered items in the file.
*/
total: number;
/**
* @param covered Value for {@link CovereredCount.covered}
* @param total Value for {@link CovereredCount.total}
*/
constructor(covered: number, total: number);
}
/**
* Contains coverage metadata for a file.
*/
export class FileCoverage {
/**
* File URI.
*/
readonly uri: Uri;
/**
* Statement coverage information. If the reporter does not provide statement
* coverage information, this can instead be used to represent line coverage.
*/
statementCoverage: CoveredCount;
/**
* Branch coverage information.
*/
branchCoverage?: CoveredCount;
/**
* Function coverage information.
*/
functionCoverage?: CoveredCount;
/**
* Detailed, per-statement coverage. If this is undefined, the editor will
* call {@link TestCoverageProvider.resolveFileCoverage} when necessary.
*/
detailedCoverage?: DetailedCoverage[];
/**
* Creates a {@link FileCoverage} instance with counts filled in from
* the coverage details.
* @param uri Covered file URI
* @param detailed Detailed coverage information
*/
static fromDetails(uri: Uri, details: readonly DetailedCoverage[]): FileCoverage;
/**
* @param uri Covered file URI
* @param statementCoverage Statement coverage information. If the reporter
* does not provide statement coverage information, this can instead be
* used to represent line coverage.
* @param branchCoverage Branch coverage information
* @param functionCoverage Function coverage information
*/
constructor(
uri: Uri,
statementCoverage: CoveredCount,
branchCoverage?: CoveredCount,
functionCoverage?: CoveredCount,
);
}
/**
* Contains coverage information for a single statement or line.
*/
export class StatementCoverage {
/**
* The number of times this statement was executed. If zero, the
* statement will be marked as un-covered.
*/
executionCount: number;
/**
* Statement location.
*/
location: Position | Range;
/**
* Coverage from branches of this line or statement. If it's not a
* conditional, this will be empty.
*/
branches: BranchCoverage[];
/**
* @param location The statement position.
* @param executionCount The number of times this statement was
* executed. If zero, the statement will be marked as un-covered.
* @param branches Coverage from branches of this line. If it's not a
* conditional, this should be omitted.
*/
constructor(executionCount: number, location: Position | Range, branches?: BranchCoverage[]);
}
/**
* Contains coverage information for a branch of a {@link StatementCoverage}.
*/
export class BranchCoverage {
/**
* The number of times this branch was executed. If zero, the
* branch will be marked as un-covered.
*/
executionCount: number;
/**
* Branch location.
*/
location?: Position | Range;
/**
* @param executionCount The number of times this branch was executed.
* @param location The branch position.
*/
constructor(executionCount: number, location?: Position | Range);
}
/**
* Contains coverage information for a function or method.
*/
export class FunctionCoverage {
/**
* The number of times this function was executed. If zero, the
* function will be marked as un-covered.
*/
executionCount: number;
/**
* Function location.
*/
location: Position | Range;
/**
* @param executionCount The number of times this function was executed.
* @param location The function position.
*/
constructor(executionCount: number, location: Position | Range);
}
export type DetailedCoverage = StatementCoverage | FunctionCoverage;
//#endregion
} | the_stack |
/// <reference path="API.ts" />
// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX
namespace bws.packer.demo
{
export class Application
extends React.Component<{}, {}>
{
private instances: InstanceFormArray;
private wrappers: WrapperArray;
private result: WrapperArray;
/* -----------------------------------------------------------
CONSTRUCTORS
----------------------------------------------------------- */
/**
* Default Constructor.
*/
public constructor()
{
super();
this.instances = new InstanceFormArray();
this.wrappers = new WrapperArray();
this.result = new WrapperArray();
// INITIAL, EXMAPLE DATA
this.wrappers.push
(
new Wrapper("Large", 1000, 40, 40, 15, 0),
new Wrapper("Medium", 700, 20, 20, 10, 0),
new Wrapper("Small", 500, 15, 15, 8, 0)
);
this.instances.push
(
new InstanceForm(new Product("Eraser", 1, 2, 5), 15),
new InstanceForm(new Product("Book", 15, 30, 3), 15),
new InstanceForm(new Product("Drink", 3, 3, 10), 15),
new InstanceForm(new Product("Umbrella", 5, 5, 20), 15),
new InstanceForm(new Product("Notebook-Box", 30, 40, 4), 15),
new InstanceForm(new Product("Tablet-Box", 20, 28, 2), 15)
);
}
/* -----------------------------------------------------------
PROCEDURES
----------------------------------------------------------- */
public pack(): void
{
let packer_form: PackerForm = new PackerForm(this.instances, this.wrappers);
/////
// FIND THE OPTIMIZED SOLUTION
/////
let packer: Packer = packer_form.toPacker();
let result: WrapperArray;
try
{
result = packer.optimize();
}
catch (exception)
{
alert(exception.what());
return;
}
this.result.assign(result.begin(), result.end());
/////
// DRAW THE 1ST WRAPPER
/////
if (this.result.empty() == true)
return;
this.drawWrapper(this.result.front());
(this.refs["tabNavigator"] as flex.TabNavigator).setState({ selectedIndex: 1 });
}
public drawWrapper(wrapper: Wrapper, index: number = wrapper.size()): void
{
// INITIALIZE
let div: HTMLDivElement = document.getElementById("wrapper_viewer") as HTMLDivElement;
let canvas: HTMLCanvasElement = this.wrapper_to_canvas(wrapper, index); // DRAW
// PRINT
if (div.hasChildNodes() == true)
div.removeChild(div.childNodes[0]);
div.appendChild(canvas);
}
/* -----------------------------------------------------------
RENDERERS
----------------------------------------------------------- */
private scene: THREE.Scene = null;
private renderer: THREE.WebGLRenderer = null;
private camera: THREE.PerspectiveCamera = null;
private trackball: THREE.TrackballControls = null;
private mouse: THREE.Vector2 = null;
private static WRAPPER_BOUNDARY_THICKNESS: number = 0.5;
private static WRAP_BOUNDARY_THICKNESS: number = 0.1;
public render(): JSX.Element
{
let ret: JSX.Element =
<div>
<div style={{width: "100%", height: "100%", fontSize: 12}}>
<flex.TabNavigator ref="tabNavigator"
style={{ width: 400, height: "100%", float: "left" }}>
<flex.NavigatorContent label="First Tab">
<ItemEditor application={this}
instances={this.instances} wrappers={this.wrappers} />
</flex.NavigatorContent>
<flex.NavigatorContent label="Second Tab">
<ResultViewer application={this}
wrappers={this.result} />
</flex.NavigatorContent>
</flex.TabNavigator>
<div id="wrapper_viewer" style={{height: "100%", overflow: "hidden"}}>
</div>
</div>
<div style={{position: "absolute", right: 10, bottom: 10}}>
<a href="http://redprinting.co.kr/" target="_blank">
<img src="images/redprinting_logo.png"
width="250" />
</a>
</div>
</div>;
return ret;
}
private wrapper_to_canvas(wrapper: Wrapper, index: number): HTMLCanvasElement
{
// ---------------------------------------
// CONSTRUCTS
// ---------------------------------------
// SCENE AND GEOMETRY
this.scene = new THREE.Scene();
let geometry: THREE.BoxGeometry = new THREE.BoxGeometry(1, 1, 1);
// BOUNDARY LINES
for (let i: number = 1; i <= 12; i++)
{
let boundaryLine: THREE.Mesh =
new THREE.Mesh
(
geometry,
new THREE.MeshPhongMaterial
({
color: 0xFFFFFF, shading: THREE.FlatShading,
vertexColors: THREE.VertexColors, shininess: 0
})
);
let width: number, height: number, length: number;
let x: number, y: number, z: number;
// SCALE
switch (i)
{
case 1: case 3: case 9: case 12:
width = wrapper.getWidth() + 2 * Application.WRAPPER_BOUNDARY_THICKNESS;
height = Application.WRAPPER_BOUNDARY_THICKNESS;
length = Application.WRAPPER_BOUNDARY_THICKNESS;
break;
case 2: case 4: case 10: case 11: case 10:
height = wrapper.getHeight() + 2 * Application.WRAPPER_BOUNDARY_THICKNESS;
width = Application.WRAPPER_BOUNDARY_THICKNESS;
length = Application.WRAPPER_BOUNDARY_THICKNESS;
break;
default: // 5, 6, 7, 8
length = wrapper.getLength() + 2 * Application.WRAPPER_BOUNDARY_THICKNESS;
width = Application.WRAPPER_BOUNDARY_THICKNESS;
height = Application.WRAPPER_BOUNDARY_THICKNESS;
break;
}
// X
switch (i)
{
case 4: case 6: case 8: case 11:
x = wrapper.getWidth() + Application.WRAPPER_BOUNDARY_THICKNESS;
break;
default:
x = -Application.WRAPPER_BOUNDARY_THICKNESS;
break;
}
// Y
switch (i)
{
case 3: case 7: case 8: case 12:
y = wrapper.getHeight();
break;
default:
y = -Application.WRAPPER_BOUNDARY_THICKNESS;
break;
}
// Z
switch (i)
{
case 9: case 10: case 11: case 12:
z = wrapper.getLength() + Application.WRAPPER_BOUNDARY_THICKNESS;
break;
default:
z = -Application.WRAPPER_BOUNDARY_THICKNESS;
break;
}
// SET POSITION AND SCALE
boundaryLine.scale.set(width, height, length);
boundaryLine.position.set(x + width / 2, y + height / 2, z + length / 2);
this.scene.add(boundaryLine);
}
// CHILDREN (PACKED) INSTANCES
for (let i: number = 0; i < Math.min(index, wrapper.size()); i++)
{
// 1st to 11th: boundaries, 12th: shape
let objects: std.Vector<THREE.Object3D> = this.wrap_to_display_objects(wrapper.at(i), geometry);
for (let j: number = 0; j < objects.size(); j++)
this.scene.add(objects.at(j));
}
// LIGHTS
let ambientLight: THREE.AmbientLight = new THREE.AmbientLight(0x555555);
//let spotLight: THREE.SpotLight = new THREE.SpotLight(0xFFFFFF, 1.5);
//spotLight.position.set(0, 500, 2000);
this.scene.add(ambientLight);
//this.scene.add(spotLight);
// ---------------------------------------
// CAMERA, TRACKBALL AND MOUSE
// ---------------------------------------
if (this.camera == null) // LAZY CREATION
{
this.camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
this.camera.position.z = wrapper.size() * 5;
this.trackball = new THREE.TrackballControls(this.camera);
this.trackball.rotateSpeed = 10;
this.trackball.zoomSpeed = 1.2;
this.trackball.panSpeed = 0.8;
this.trackball.noZoom = false;
this.trackball.noPan = false;
this.trackball.staticMoving = true;
this.trackball.dynamicDampingFactor = 0.3;
this.mouse = new THREE.Vector2();
// RENDERER
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setClearColor(0xFFFFFF);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setSize(window.innerWidth * .75, window.innerHeight);
this.renderer.sortObjects = false;
this.renderer.domElement.addEventListener("mousemove", this.handle_mouse_move.bind(this));
this.animate();
}
// ---------------------------------------
// RETURNS AN HTML_ELEMENT OF THE RENDERER
// ---------------------------------------
return this.renderer.domElement;
}
private wrap_to_display_objects(wrap: Wrap, geometry: THREE.Geometry): std.Vector<THREE.Object3D>
{
let objects: std.Vector<THREE.Object3D> = new std.Vector<THREE.Object3D>();
// ---------------------------------------
// BOUNDARIES
// ---------------------------------------
for (let i: number = 1; i <= 12; i++)
{
let boundaryLine: THREE.Mesh =
new THREE.Mesh
(
geometry,
new THREE.MeshPhongMaterial
({
color: 0xFF0000, shading: THREE.FlatShading,
vertexColors: THREE.VertexColors, shininess: 0
})
);
let width: number, height: number, length: number;
let x: number, y: number, z: number;
// SCALE
switch (i)
{
case 1: case 3: case 9: case 12:
width = wrap.getLayoutWidth();
height = Application.WRAP_BOUNDARY_THICKNESS;
length = Application.WRAP_BOUNDARY_THICKNESS;
break;
case 2: case 4: case 10: case 11: case 10:
height = wrap.getLayoutHeight();
width = Application.WRAP_BOUNDARY_THICKNESS;
length = Application.WRAP_BOUNDARY_THICKNESS;
break;
default: // 5, 6, 7, 8
length = wrap.getLength();
width = Application.WRAP_BOUNDARY_THICKNESS;
height = Application.WRAP_BOUNDARY_THICKNESS;
break;
}
// X
switch (i)
{
case 4: case 6: case 8: case 11:
x = wrap.getX() + wrap.getLayoutWidth() - Application.WRAP_BOUNDARY_THICKNESS;
break;
default:
x = wrap.getX();
break;
}
// Y
switch (i)
{
case 3: case 7: case 8: case 12:
y = wrap.getY() + wrap.getLayoutHeight() - Application.WRAP_BOUNDARY_THICKNESS;
break;
default:
y = wrap.getY();
break;
}
// Z
switch (i)
{
case 9: case 10: case 11: case 12:
z = wrap.getZ() + wrap.getLength() - Application.WRAP_BOUNDARY_THICKNESS;
break;
default:
z = wrap.getZ();
break;
}
// SET POSITION AND SCALE
boundaryLine.scale.set(width, height, length);
boundaryLine.position.set(x + width / 2, y + height / 2, z + length / 2);
objects.push_back(boundaryLine);
}
// ---------------------------------------
// SHAPE
// ---------------------------------------
if ((wrap as any).color_ == undefined)
(wrap as any).color_ = Math.random() * 0xFFFFFF;
let shape: THREE.Mesh = new THREE.Mesh
(
geometry,
new THREE.MeshLambertMaterial
({
color: (wrap as any).color_,
opacity: 0.5,
transparent: true
})
);
shape.scale.set(wrap.getLayoutWidth(), wrap.getLayoutHeight(), wrap.getLength());
shape.position.set
(
wrap.getX() + wrap.getLayoutWidth() / 2,
wrap.getY() + wrap.getLayoutHeight() / 2,
wrap.getZ() + wrap.getLength() / 2
);
objects.push_back(shape);
return objects;
}
private handle_mouse_move(event: MouseEvent): void
{
this.mouse.x = event.clientX;
this.mouse.y = event.clientY;
}
private animate(): void
{
requestAnimationFrame(this.animate.bind(this));
this.render_three();
}
private render_three(): void
{
this.trackball.update();
this.renderer.render(this.scene, this.camera);
}
/* -----------------------------------------------------------
MAIN FUNCTIONS
----------------------------------------------------------- */
public static main(): void
{
ReactDOM.render(<Application />, document.body);
}
}
} | the_stack |
export const SET_LOCALE = "SET_LOCALE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_LOCALE = "SET_LOCALE"
export const SET_FALLBACK_LOCALE = "SET_FALLBACK_LOCALE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_FALLBACK_LOCALE = "SET_FALLBACK_LOCALE"
export const RECEIVE_DATA_TABLES = "RECEIVE_DATA_TABLES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_DATA_TABLES = "RECEIVE_DATA_TABLES"
export const SET_SECTION = "SET_SECTION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SECTION = "SET_SECTION"
export const SET_TAB = "SET_TAB"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TAB = "SET_TAB"
export const RECEIVE_IMPORTED_HERO = "RECEIVE_IMPORTED_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_IMPORTED_HERO = "RECEIVE_IMPORTED_HERO"
export const RECEIVE_INITIAL_DATA = "RECEIVE_INITIAL_DATA"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_INITIAL_DATA = "RECEIVE_INITIAL_DATA"
export const SET_LOADING_DONE = "SET_LOADING_DONE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_LOADING_DONE = "SET_LOADING_DONE"
export const SET_LOADING_DONE_WITH_ERROR = "SET_LOADING_DONE_WITH_ERROR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_LOADING_DONE_WITH_ERROR = "SET_LOADING_DONE_WITH_ERROR"
export const SET_UPDATE_DOWNLOAD_PROGRESS = "SET_UPDATE_DOWNLOAD_PROGRESS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_UPDATE_DOWNLOAD_PROGRESS = "SET_UPDATE_DOWNLOAD_PROGRESS"
export const REQUEST_LOGIN = "REQUEST_LOGIN"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_LOGIN = "REQUEST_LOGIN"
export const RECEIVE_LOGIN = "RECEIVE_LOGIN"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_LOGIN = "RECEIVE_LOGIN"
export const REQUEST_LOGOUT = "REQUEST_LOGOUT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_LOGOUT = "REQUEST_LOGOUT"
export const RECEIVE_LOGOUT = "RECEIVE_LOGOUT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_LOGOUT = "RECEIVE_LOGOUT"
export const REQUEST_REGISTRATION = "REQUEST_REGISTRATION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_REGISTRATION = "REQUEST_REGISTRATION"
export const RECEIVE_REGISTRATION = "RECEIVE_REGISTRATION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_REGISTRATION = "RECEIVE_REGISTRATION"
export const REQUEST_NEW_USERNAME = "REQUEST_NEW_USERNAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_NEW_USERNAME = "REQUEST_NEW_USERNAME"
export const RECEIVE_NEW_USERNAME = "RECEIVE_NEW_USERNAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_NEW_USERNAME = "RECEIVE_NEW_USERNAME"
export const REQUEST_USER_DELETION = "REQUEST_USER_DELETION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_USER_DELETION = "REQUEST_USER_DELETION"
export const RECEIVE_USER_DELETION = "RECEIVE_USER_DELETION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_USER_DELETION = "RECEIVE_USER_DELETION"
export const REQUEST_PASSWORD_RESET = "REQUEST_PASSWORD_RESET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_PASSWORD_RESET = "REQUEST_PASSWORD_RESET"
export const RECEIVE_PASSWORD_RESET = "RECEIVE_PASSWORD_RESET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_PASSWORD_RESET = "RECEIVE_PASSWORD_RESET"
export const REQUEST_USERNAME = "REQUEST_USERNAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_USERNAME = "REQUEST_USERNAME"
export const RECEIVE_USERNAME = "RECEIVE_USERNAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_USERNAME = "RECEIVE_USERNAME"
export const REQUEST_ACCOUNT_ACTIVATION_EMAIL = "REQUEST_ACCOUNT_ACTIVATION_EMAIL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_ACCOUNT_ACTIVATION_EMAIL = "REQUEST_ACCOUNT_ACTIVATION_EMAIL"
export const RECEIVE_ACCOUNT_ACTIVATION_EMAIL = "RECEIVE_ACCOUNT_ACTIVATION_EMAIL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_ACCOUNT_ACTIVATION_EMAIL = "RECEIVE_ACCOUNT_ACTIVATION_EMAIL"
export const REQUEST_NEW_DISPLAY_NAME = "REQUEST_NEW_DISPLAY_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_NEW_DISPLAY_NAME = "REQUEST_NEW_DISPLAY_NAME"
export const RECEIVE_NEW_DISPLAY_NAME = "RECEIVE_NEW_DISPLAY_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_NEW_DISPLAY_NAME = "RECEIVE_NEW_DISPLAY_NAME"
export const REQUEST_NEW_PASSWORD = "REQUEST_NEW_PASSWORD"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_NEW_PASSWORD = "REQUEST_NEW_PASSWORD"
export const RECEIVE_NEW_PASSWORD = "RECEIVE_NEW_PASSWORD"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_NEW_PASSWORD = "RECEIVE_NEW_PASSWORD"
export const REQUEST_HERO_SAVE = "REQUEST_HERO_SAVE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_HERO_SAVE = "REQUEST_HERO_SAVE"
export const RECEIVE_HERO_SAVE = "RECEIVE_HERO_SAVE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_HERO_SAVE = "RECEIVE_HERO_SAVE"
export const RECEIVE_DELETE_HERO = "RECEIVE_DELETE_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_DELETE_HERO = "RECEIVE_DELETE_HERO"
export const RECEIVE_ALL_HEROES_SAVE = "RECEIVE_ALL_HEROES_SAVE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_ALL_HEROES_SAVE = "RECEIVE_ALL_HEROES_SAVE"
export const REQUEST_FAILED = "REQUEST_FAILED"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_FAILED = "REQUEST_FAILED"
export const SET_HEROLIST_VISIBILITY_FILTER = "SET_HEROLIST_VISIBILITY_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HEROLIST_VISIBILITY_FILTER = "SET_HEROLIST_VISIBILITY_FILTER"
export const SET_HEROLIST_SORT_ORDER = "SET_HEROLIST_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HEROLIST_SORT_ORDER = "SET_HEROLIST_SORT_ORDER"
export const SET_HEROLIST_FILTER_TEXT = "SET_HEROLIST_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HEROLIST_FILTER_TEXT = "SET_HEROLIST_FILTER_TEXT"
export const REQUEST_HEROLIST = "REQUEST_HEROLIST"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_HEROLIST = "REQUEST_HEROLIST"
export const RECEIVE_HEROLIST = "RECEIVE_HEROLIST"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_HEROLIST = "RECEIVE_HEROLIST"
export const CREATE_HERO = "CREATE_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CREATE_HERO = "CREATE_HERO"
export const SAVE_HERO = "SAVE_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SAVE_HERO = "SAVE_HERO"
export const DELETE_HERO = "DELETE_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DELETE_HERO = "DELETE_HERO"
export const IMPORT_HERO = "IMPORT_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type IMPORT_HERO = "IMPORT_HERO"
export const LOAD_HERO = "LOAD_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type LOAD_HERO = "LOAD_HERO"
export const DUPLICATE_HERO = "DUPLICATE_HERO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DUPLICATE_HERO = "DUPLICATE_HERO"
export const UPDATE_DATE_MODIFIED = "UPDATE_DATE_MODIFIED"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type UPDATE_DATE_MODIFIED = "UPDATE_DATE_MODIFIED"
export const SET_WIKI_FILTER = "SET_WIKI_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_FILTER = "SET_WIKI_FILTER"
export const SET_WIKI_FILTER_ALL = "SET_WIKI_FILTER_ALL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_FILTER_ALL = "SET_WIKI_FILTER_ALL"
export const SET_WIKI_CATEGORY_1 = "SET_WIKI_CATEGORY_1"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_CATEGORY_1 = "SET_WIKI_CATEGORY_1"
export const SET_WIKI_CATEGORY_2 = "SET_WIKI_CATEGORY_2"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_CATEGORY_2 = "SET_WIKI_CATEGORY_2"
export const SET_WIKI_PROFESSIONS_GROUP = "SET_WIKI_PROFESSIONS_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_PROFESSIONS_GROUP = "SET_WIKI_PROFESSIONS_GROUP"
export const SET_WIKI_SKILLS_GROUP = "SET_WIKI_SKILLS_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_SKILLS_GROUP = "SET_WIKI_SKILLS_GROUP"
export const SET_WIKI_COMBAT_TECHNIQUES_GROUP = "SET_WIKI_COMBAT_TECHNIQUES_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_COMBAT_TECHNIQUES_GROUP = "SET_WIKI_COMBAT_TECHNIQUES_GROUP"
export const SET_WIKI_SPECIAL_ABILITIES_GROUP = "SET_WIKI_SPECIAL_ABILITIES_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_SPECIAL_ABILITIES_GROUP = "SET_WIKI_SPECIAL_ABILITIES_GROUP"
export const SET_WIKI_SPELLS_GROUP = "SET_WIKI_SPELLS_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_SPELLS_GROUP = "SET_WIKI_SPELLS_GROUP"
export const SET_WIKI_LITURGICAL_CHANTS_GROUP = "SET_WIKI_LITURGICAL_CHANTS_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_LITURGICAL_CHANTS_GROUP = "SET_WIKI_LITURGICAL_CHANTS_GROUP"
export const SET_WIKI_ITEM_TEMPLATES_GROUP = "SET_WIKI_ITEM_TEMPLATES_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WIKI_ITEM_TEMPLATES_GROUP = "SET_WIKI_ITEM_TEMPLATES_GROUP"
export const UNDO = "UNDO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type UNDO = "UNDO"
export const REDO = "REDO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REDO = "REDO"
export const REQUEST_HERO_DATA = "REQUEST_HERO_DATA"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_HERO_DATA = "REQUEST_HERO_DATA"
export const RECEIVE_HERO_DATA = "RECEIVE_HERO_DATA"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_HERO_DATA = "RECEIVE_HERO_DATA"
export const REQUEST_HERO_AVATAR = "REQUEST_HERO_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REQUEST_HERO_AVATAR = "REQUEST_HERO_AVATAR"
export const RECEIVE_HERO_AVATAR = "RECEIVE_HERO_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type RECEIVE_HERO_AVATAR = "RECEIVE_HERO_AVATAR"
export const SET_HERO_AVATAR = "SET_HERO_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HERO_AVATAR = "SET_HERO_AVATAR"
export const DELETE_HERO_AVATAR = "DELETE_HERO_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DELETE_HERO_AVATAR = "DELETE_HERO_AVATAR"
export const OPEN_EDIT_PERMANENT_ENERGY = "OPEN_EDIT_PERMANENT_ENERGY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_EDIT_PERMANENT_ENERGY = "OPEN_EDIT_PERMANENT_ENERGY"
export const CLOSE_EDIT_PERMANENT_ENERGY = "CLOSE_EDIT_PERMANENT_ENERGY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_EDIT_PERMANENT_ENERGY = "CLOSE_EDIT_PERMANENT_ENERGY"
export const OPEN_ADD_PERMANENT_ENERGY_LOSS = "OPEN_ADD_PERMANENT_ENERGY_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_ADD_PERMANENT_ENERGY_LOSS = "OPEN_ADD_PERMANENT_ENERGY_LOSS"
export const CLOSE_ADD_PERMANENT_ENERGY_LOSS = "CLOSE_ADD_PERMANENT_ENERGY_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_ADD_PERMANENT_ENERGY_LOSS = "CLOSE_ADD_PERMANENT_ENERGY_LOSS"
export const OPEN_CHARACTER_CREATOR = "OPEN_CHARACTER_CREATOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_CHARACTER_CREATOR = "OPEN_CHARACTER_CREATOR"
export const CLOSE_CHARACTER_CREATOR = "CLOSE_CHARACTER_CREATOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_CHARACTER_CREATOR = "CLOSE_CHARACTER_CREATOR"
export const OPEN_SETTINGS = "OPEN_SETTINGS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_SETTINGS = "OPEN_SETTINGS"
export const CLOSE_SETTINGS = "CLOSE_SETTINGS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_SETTINGS = "CLOSE_SETTINGS"
export const OPEN_ADD_ADVENTURE_POINTS = "OPEN_ADD_ADVENTURE_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_ADD_ADVENTURE_POINTS = "OPEN_ADD_ADVENTURE_POINTS"
export const CLOSE_ADD_ADVENTURE_POINTS = "CLOSE_ADD_ADVENTURE_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_ADD_ADVENTURE_POINTS = "CLOSE_ADD_ADVENTURE_POINTS"
export const OPEN_EDIT_CHARACTER_AVATAR = "OPEN_EDIT_CHARACTER_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_EDIT_CHARACTER_AVATAR = "OPEN_EDIT_CHARACTER_AVATAR"
export const CLOSE_EDIT_CHARACTER_AVATAR = "CLOSE_EDIT_CHARACTER_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_EDIT_CHARACTER_AVATAR = "CLOSE_EDIT_CHARACTER_AVATAR"
export const OPEN_EDIT_PET_AVATAR = "OPEN_EDIT_PET_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_EDIT_PET_AVATAR = "OPEN_EDIT_PET_AVATAR"
export const CLOSE_EDIT_PET_AVATAR = "CLOSE_EDIT_PET_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_EDIT_PET_AVATAR = "CLOSE_EDIT_PET_AVATAR"
export const OPEN_ADD_REMOVE_MONEY = "OPEN_ADD_REMOVE_MONEY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type OPEN_ADD_REMOVE_MONEY = "OPEN_ADD_REMOVE_MONEY"
export const CLOSE_ADD_REMOVE_MONEY = "CLOSE_ADD_REMOVE_MONEY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_ADD_REMOVE_MONEY = "CLOSE_ADD_REMOVE_MONEY"
export const SET_HIGHER_PARADE_VALUES = "SET_HIGHER_PARADE_VALUES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HIGHER_PARADE_VALUES = "SET_HIGHER_PARADE_VALUES"
export const SWITCH_ATTRIBUTE_VALUE_LIMIT = "SWITCH_ATTRIBUTE_VALUE_LIMIT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ATTRIBUTE_VALUE_LIMIT = "SWITCH_ATTRIBUTE_VALUE_LIMIT"
export const SWITCH_ENABLE_ALL_RULE_BOOKS = "SWITCH_ENABLE_ALL_RULE_BOOKS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ENABLE_ALL_RULE_BOOKS = "SWITCH_ENABLE_ALL_RULE_BOOKS"
export const SWITCH_ENABLE_RULE_BOOK = "SWITCH_ENABLE_RULE_BOOK"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ENABLE_RULE_BOOK = "SWITCH_ENABLE_RULE_BOOK"
export const SWITCH_ENABLE_LANG_SPEC = "SWITCH_ENABLE_LANG_SPEC"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ENABLE_LANG_SPEC = "SWITCH_ENABLE_LANG_SPEC"
export const SELECT_RACE = "SELECT_RACE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SELECT_RACE = "SELECT_RACE"
export const SET_RACES_SORT_ORDER = "SET_RACES_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_RACES_SORT_ORDER = "SET_RACES_SORT_ORDER"
export const SWITCH_RACE_VALUE_VISIBILITY = "SWITCH_RACE_VALUE_VISIBILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_RACE_VALUE_VISIBILITY = "SWITCH_RACE_VALUE_VISIBILITY"
export const SET_RACE_VARIANT = "SET_RACE_VARIANT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_RACE_VARIANT = "SET_RACE_VARIANT"
export const SELECT_CULTURE = "SELECT_CULTURE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SELECT_CULTURE = "SELECT_CULTURE"
export const SET_CULTURES_SORT_ORDER = "SET_CULTURES_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_CULTURES_SORT_ORDER = "SET_CULTURES_SORT_ORDER"
export const SET_CULTURES_VISIBILITY_FILTER = "SET_CULTURES_VISIBILITY_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_CULTURES_VISIBILITY_FILTER = "SET_CULTURES_VISIBILITY_FILTER"
export const SWITCH_CULTURE_VALUE_VISIBILITY = "SWITCH_CULTURE_VALUE_VISIBILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_CULTURE_VALUE_VISIBILITY = "SWITCH_CULTURE_VALUE_VISIBILITY"
export const SELECT_PROFESSION = "SELECT_PROFESSION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SELECT_PROFESSION = "SELECT_PROFESSION"
export const SET_PROFESSIONS_SORT_ORDER = "SET_PROFESSIONS_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PROFESSIONS_SORT_ORDER = "SET_PROFESSIONS_SORT_ORDER"
export const SET_PROFESSIONS_VISIBILITY_FILTER = "SET_PROFESSIONS_VISIBILITY_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PROFESSIONS_VISIBILITY_FILTER = "SET_PROFESSIONS_VISIBILITY_FILTER"
export const SET_PROFESSIONS_GR_VISIBILITY_FILTER = "SET_PROFESSIONS_GR_VISIBILITY_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PROFESSIONS_GR_VISIBILITY_FILTER = "SET_PROFESSIONS_GR_VISIBILITY_FILTER"
export const ASSIGN_RCP_OPTIONS = "ASSIGN_RCP_OPTIONS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ASSIGN_RCP_OPTIONS = "ASSIGN_RCP_OPTIONS"
export const SELECT_PROFESSION_VARIANT = "SELECT_PROFESSION_VARIANT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SELECT_PROFESSION_VARIANT = "SELECT_PROFESSION_VARIANT"
export const SET_HERO_LOCALE = "SET_HERO_LOCALE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HERO_LOCALE = "SET_HERO_LOCALE"
export const SET_HERO_NAME = "SET_HERO_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HERO_NAME = "SET_HERO_NAME"
export const SET_CUSTOM_PROFESSION_NAME = "SET_CUSTOM_PROFESSION_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_CUSTOM_PROFESSION_NAME = "SET_CUSTOM_PROFESSION_NAME"
export const SET_FAMILY = "SET_FAMILY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_FAMILY = "SET_FAMILY"
export const SET_PLACEOFBIRTH = "SET_PLACEOFBIRTH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PLACEOFBIRTH = "SET_PLACEOFBIRTH"
export const SET_DATEOFBIRTH = "SET_DATEOFBIRTH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_DATEOFBIRTH = "SET_DATEOFBIRTH"
export const SET_AGE = "SET_AGE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_AGE = "SET_AGE"
export const SET_HAIRCOLOR = "SET_HAIRCOLOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HAIRCOLOR = "SET_HAIRCOLOR"
export const SET_EYECOLOR = "SET_EYECOLOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_EYECOLOR = "SET_EYECOLOR"
export const SET_SIZE = "SET_SIZE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SIZE = "SET_SIZE"
export const SET_WEIGHT = "SET_WEIGHT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_WEIGHT = "SET_WEIGHT"
export const SET_TITLE = "SET_TITLE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TITLE = "SET_TITLE"
export const SET_SOCIALSTATUS = "SET_SOCIALSTATUS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SOCIALSTATUS = "SET_SOCIALSTATUS"
export const SET_CHARACTERISTICS = "SET_CHARACTERISTICS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_CHARACTERISTICS = "SET_CHARACTERISTICS"
export const SET_OTHERINFO = "SET_OTHERINFO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_OTHERINFO = "SET_OTHERINFO"
export const SET_CULTURE_AREA_KNOWLEDGE = "SET_CULTURE_AREA_KNOWLEDGE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_CULTURE_AREA_KNOWLEDGE = "SET_CULTURE_AREA_KNOWLEDGE"
export const ADD_ADVENTURE_POINTS = "ADD_ADVENTURE_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ADVENTURE_POINTS = "ADD_ADVENTURE_POINTS"
export const END_HERO_CREATION = "END_HERO_CREATION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type END_HERO_CREATION = "END_HERO_CREATION"
export const SET_PACT_CATEGORY = "SET_PACT_CATEGORY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PACT_CATEGORY = "SET_PACT_CATEGORY"
export const SET_PACT_LEVEL = "SET_PACT_LEVEL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PACT_LEVEL = "SET_PACT_LEVEL"
export const SET_TARGET_TYPE = "SET_TARGET_TYPE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TARGET_TYPE = "SET_TARGET_TYPE"
export const SET_TARGET_DOMAIN = "SET_TARGET_DOMAIN"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TARGET_DOMAIN = "SET_TARGET_DOMAIN"
export const SET_TARGET_NAME = "SET_TARGET_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TARGET_NAME = "SET_TARGET_NAME"
export const ADD_ATTRIBUTE_POINT = "ADD_ATTRIBUTE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ATTRIBUTE_POINT = "ADD_ATTRIBUTE_POINT"
export const REMOVE_ATTRIBUTE_POINT = "REMOVE_ATTRIBUTE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_ATTRIBUTE_POINT = "REMOVE_ATTRIBUTE_POINT"
export const ADD_LIFE_POINT = "ADD_LIFE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LIFE_POINT = "ADD_LIFE_POINT"
export const ADD_ARCANE_ENERGY_POINT = "ADD_ARCANE_ENERGY_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ARCANE_ENERGY_POINT = "ADD_ARCANE_ENERGY_POINT"
export const ADD_KARMA_POINT = "ADD_KARMA_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_KARMA_POINT = "ADD_KARMA_POINT"
export const REMOVE_LIFE_POINT = "REMOVE_LIFE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_LIFE_POINT = "REMOVE_LIFE_POINT"
export const REMOVE_ARCANE_ENERGY_POINT = "REMOVE_ARCANE_ENERGY_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_ARCANE_ENERGY_POINT = "REMOVE_ARCANE_ENERGY_POINT"
export const REMOVE_KARMA_POINT = "REMOVE_KARMA_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_KARMA_POINT = "REMOVE_KARMA_POINT"
export const ADD_LOST_LP_POINT = "ADD_LOST_LP_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LOST_LP_POINT = "ADD_LOST_LP_POINT"
export const REMOVE_LOST_LP_POINT = "REMOVE_LOST_LP_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_LOST_LP_POINT = "REMOVE_LOST_LP_POINT"
export const ADD_LOST_LP_POINTS = "ADD_LOST_LP_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LOST_LP_POINTS = "ADD_LOST_LP_POINTS"
export const ADD_BOUGHT_BACK_AE_POINT = "ADD_BOUGHT_BACK_AE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_BOUGHT_BACK_AE_POINT = "ADD_BOUGHT_BACK_AE_POINT"
export const REMOVE_BOUGHT_BACK_AE_POINT = "REMOVE_BOUGHT_BACK_AE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_BOUGHT_BACK_AE_POINT = "REMOVE_BOUGHT_BACK_AE_POINT"
export const ADD_LOST_AE_POINT = "ADD_LOST_AE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LOST_AE_POINT = "ADD_LOST_AE_POINT"
export const REMOVE_LOST_AE_POINT = "REMOVE_LOST_AE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_LOST_AE_POINT = "REMOVE_LOST_AE_POINT"
export const ADD_LOST_AE_POINTS = "ADD_LOST_AE_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LOST_AE_POINTS = "ADD_LOST_AE_POINTS"
export const ADD_BOUGHT_BACK_KP_POINT = "ADD_BOUGHT_BACK_KP_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_BOUGHT_BACK_KP_POINT = "ADD_BOUGHT_BACK_KP_POINT"
export const REMOVE_BOUGHT_BACK_KP_POINT = "REMOVE_BOUGHT_BACK_KP_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_BOUGHT_BACK_KP_POINT = "REMOVE_BOUGHT_BACK_KP_POINT"
export const ADD_LOST_KP_POINT = "ADD_LOST_KP_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LOST_KP_POINT = "ADD_LOST_KP_POINT"
export const REMOVE_LOST_KP_POINT = "REMOVE_LOST_KP_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_LOST_KP_POINT = "REMOVE_LOST_KP_POINT"
export const ADD_LOST_KP_POINTS = "ADD_LOST_KP_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LOST_KP_POINTS = "ADD_LOST_KP_POINTS"
export const SET_ATTR_ADJUSTMENT_SID = "SET_ATTR_ADJUSTMENT_SID"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ATTR_ADJUSTMENT_SID = "SET_ATTR_ADJUSTMENT_SID"
export const ACTIVATE_DISADV = "ACTIVATE_DISADV"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ACTIVATE_DISADV = "ACTIVATE_DISADV"
export const DEACTIVATE_DISADV = "DEACTIVATE_DISADV"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DEACTIVATE_DISADV = "DEACTIVATE_DISADV"
export const SET_DISADV_TIER = "SET_DISADV_TIER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_DISADV_TIER = "SET_DISADV_TIER"
export const SWITCH_DISADV_RATING_VISIBILITY = "SWITCH_DISADV_RATING_VISIBILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_DISADV_RATING_VISIBILITY = "SWITCH_DISADV_RATING_VISIBILITY"
export const ADD_TALENT_POINT = "ADD_TALENT_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_TALENT_POINT = "ADD_TALENT_POINT"
export const REMOVE_TALENT_POINT = "REMOVE_TALENT_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_TALENT_POINT = "REMOVE_TALENT_POINT"
export const SET_TALENTS_SORT_ORDER = "SET_TALENTS_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TALENTS_SORT_ORDER = "SET_TALENTS_SORT_ORDER"
export const SWITCH_TALENT_RATING_VISIBILITY = "SWITCH_TALENT_RATING_VISIBILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_TALENT_RATING_VISIBILITY = "SWITCH_TALENT_RATING_VISIBILITY"
export const ADD_COMBATTECHNIQUE_POINT = "ADD_COMBATTECHNIQUE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_COMBATTECHNIQUE_POINT = "ADD_COMBATTECHNIQUE_POINT"
export const REMOVE_COMBATTECHNIQUE_POINT = "REMOVE_COMBATTECHNIQUE_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_COMBATTECHNIQUE_POINT = "REMOVE_COMBATTECHNIQUE_POINT"
export const SET_COMBATTECHNIQUES_SORT_ORDER = "SET_COMBATTECHNIQUES_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_COMBATTECHNIQUES_SORT_ORDER = "SET_COMBATTECHNIQUES_SORT_ORDER"
export const ACTIVATE_SPELL = "ACTIVATE_SPELL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ACTIVATE_SPELL = "ACTIVATE_SPELL"
export const DEACTIVATE_SPELL = "DEACTIVATE_SPELL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DEACTIVATE_SPELL = "DEACTIVATE_SPELL"
export const ACTIVATE_CANTRIP = "ACTIVATE_CANTRIP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ACTIVATE_CANTRIP = "ACTIVATE_CANTRIP"
export const DEACTIVATE_CANTRIP = "DEACTIVATE_CANTRIP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DEACTIVATE_CANTRIP = "DEACTIVATE_CANTRIP"
export const ADD_SPELL_POINT = "ADD_SPELL_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_SPELL_POINT = "ADD_SPELL_POINT"
export const REMOVE_SPELL_POINT = "REMOVE_SPELL_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_SPELL_POINT = "REMOVE_SPELL_POINT"
export const SET_SPELLS_SORT_ORDER = "SET_SPELLS_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SPELLS_SORT_ORDER = "SET_SPELLS_SORT_ORDER"
export const ACTIVATE_LITURGY = "ACTIVATE_LITURGY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ACTIVATE_LITURGY = "ACTIVATE_LITURGY"
export const DEACTIVATE_LITURGY = "DEACTIVATE_LITURGY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DEACTIVATE_LITURGY = "DEACTIVATE_LITURGY"
export const ACTIVATE_BLESSING = "ACTIVATE_BLESSING"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ACTIVATE_BLESSING = "ACTIVATE_BLESSING"
export const DEACTIVATE_BLESSING = "DEACTIVATE_BLESSING"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DEACTIVATE_BLESSING = "DEACTIVATE_BLESSING"
export const ADD_LITURGY_POINT = "ADD_LITURGY_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_LITURGY_POINT = "ADD_LITURGY_POINT"
export const REMOVE_LITURGY_POINT = "REMOVE_LITURGY_POINT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_LITURGY_POINT = "REMOVE_LITURGY_POINT"
export const SET_LITURGIES_SORT_ORDER = "SET_LITURGIES_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_LITURGIES_SORT_ORDER = "SET_LITURGIES_SORT_ORDER"
export const ACTIVATE_SPECIALABILITY = "ACTIVATE_SPECIALABILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ACTIVATE_SPECIALABILITY = "ACTIVATE_SPECIALABILITY"
export const DEACTIVATE_SPECIALABILITY = "DEACTIVATE_SPECIALABILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DEACTIVATE_SPECIALABILITY = "DEACTIVATE_SPECIALABILITY"
export const SET_SPECIALABILITY_TIER = "SET_SPECIALABILITY_TIER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SPECIALABILITY_TIER = "SET_SPECIALABILITY_TIER"
export const SET_SPECIALABILITIES_SORT_ORDER = "SET_SPECIALABILITIES_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SPECIALABILITIES_SORT_ORDER = "SET_SPECIALABILITIES_SORT_ORDER"
export const SET_TRAD_GUILD_MAGE_UNFAM_SPELL_ID = "SET_TRAD_GUILD_MAGE_UNFAM_SPELL_ID"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_TRAD_GUILD_MAGE_UNFAM_SPELL_ID = "SET_TRAD_GUILD_MAGE_UNFAM_SPELL_ID"
export const ADD_ITEM = "ADD_ITEM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ITEM = "ADD_ITEM"
export const ADD_ITEM_TEMPLATE = "ADD_ITEM_TEMPLATE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ITEM_TEMPLATE = "ADD_ITEM_TEMPLATE"
export const CREATE_ITEM = "CREATE_ITEM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CREATE_ITEM = "CREATE_ITEM"
export const CLOSE_ITEM_EDITOR = "CLOSE_ITEM_EDITOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_ITEM_EDITOR = "CLOSE_ITEM_EDITOR"
export const SAVE_ITEM = "SAVE_ITEM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SAVE_ITEM = "SAVE_ITEM"
export const EDIT_ITEM = "EDIT_ITEM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type EDIT_ITEM = "EDIT_ITEM"
export const REMOVE_ITEM = "REMOVE_ITEM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_ITEM = "REMOVE_ITEM"
export const SET_ITEM = "SET_ITEM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM = "SET_ITEM"
export const SET_ITEMS_SORT_ORDER = "SET_ITEMS_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEMS_SORT_ORDER = "SET_ITEMS_SORT_ORDER"
export const SET_DUCATES = "SET_DUCATES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_DUCATES = "SET_DUCATES"
export const SET_SILVERTHALERS = "SET_SILVERTHALERS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SILVERTHALERS = "SET_SILVERTHALERS"
export const SET_HELLERS = "SET_HELLERS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_HELLERS = "SET_HELLERS"
export const SET_KREUTZERS = "SET_KREUTZERS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_KREUTZERS = "SET_KREUTZERS"
export const SET_MONEY = "SET_MONEY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_MONEY = "SET_MONEY"
export const SET_ITEM_NAME = "SET_ITEM_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_NAME = "SET_ITEM_NAME"
export const SET_ITEM_PRICE = "SET_ITEM_PRICE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_PRICE = "SET_ITEM_PRICE"
export const SET_ITEM_WEIGHT = "SET_ITEM_WEIGHT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_WEIGHT = "SET_ITEM_WEIGHT"
export const SET_ITEM_AMOUNT = "SET_ITEM_AMOUNT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_AMOUNT = "SET_ITEM_AMOUNT"
export const SET_ITEM_WHERE = "SET_ITEM_WHERE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_WHERE = "SET_ITEM_WHERE"
export const SET_ITEM_GROUP = "SET_ITEM_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_GROUP = "SET_ITEM_GROUP"
export const SET_ITEM_TEMPLATE = "SET_ITEM_TEMPLATE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_TEMPLATE = "SET_ITEM_TEMPLATE"
export const SET_ITEM_COMBAT_TECHNIQUE = "SET_ITEM_COMBAT_TECHNIQUE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_COMBAT_TECHNIQUE = "SET_ITEM_COMBAT_TECHNIQUE"
export const SET_ITEM_DAMAGE_DICE_NUMBER = "SET_ITEM_DAMAGE_DICE_NUMBER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_DAMAGE_DICE_NUMBER = "SET_ITEM_DAMAGE_DICE_NUMBER"
export const SET_ITEM_DAMAGE_DICE_SIDES = "SET_ITEM_DAMAGE_DICE_SIDES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_DAMAGE_DICE_SIDES = "SET_ITEM_DAMAGE_DICE_SIDES"
export const SET_ITEM_DAMAGE_FLAT = "SET_ITEM_DAMAGE_FLAT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_DAMAGE_FLAT = "SET_ITEM_DAMAGE_FLAT"
export const SET_ITEM_PRIMARY_ATTRIBUTE = "SET_ITEM_PRIMARY_ATTRIBUTE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_PRIMARY_ATTRIBUTE = "SET_ITEM_PRIMARY_ATTRIBUTE"
export const SET_ITEM_DAMAGE_THRESHOLD = "SET_ITEM_DAMAGE_THRESHOLD"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_DAMAGE_THRESHOLD = "SET_ITEM_DAMAGE_THRESHOLD"
export const SET_ITEM_FIRST_DAMAGE_THRESHOLD = "SET_ITEM_FIRST_DAMAGE_THRESHOLD"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_FIRST_DAMAGE_THRESHOLD = "SET_ITEM_FIRST_DAMAGE_THRESHOLD"
export const SET_ITEM_SECOND_DAMAGE_THRESHOLD = "SET_ITEM_SECOND_DAMAGE_THRESHOLD"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_SECOND_DAMAGE_THRESHOLD = "SET_ITEM_SECOND_DAMAGE_THRESHOLD"
export const SWITCH_IS_ITEM_DT_SEPARATED = "SWITCH_IS_ITEM_DT_SEPARATED"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_IS_ITEM_DT_SEPARATED = "SWITCH_IS_ITEM_DT_SEPARATED"
export const SET_ITEM_ATTACK = "SET_ITEM_ATTACK"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_ATTACK = "SET_ITEM_ATTACK"
export const SET_ITEM_PARRY = "SET_ITEM_PARRY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_PARRY = "SET_ITEM_PARRY"
export const SET_ITEM_REACH = "SET_ITEM_REACH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_REACH = "SET_ITEM_REACH"
export const SET_ITEM_LENGTH = "SET_ITEM_LENGTH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_LENGTH = "SET_ITEM_LENGTH"
export const SET_ITEM_STRUCTURE_POINTS = "SET_ITEM_STRUCTURE_POINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_STRUCTURE_POINTS = "SET_ITEM_STRUCTURE_POINTS"
export const SET_ITEM_RANGE = "SET_ITEM_RANGE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_RANGE = "SET_ITEM_RANGE"
export const SET_ITEM_RELOAD_TIME = "SET_ITEM_RELOAD_TIME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_RELOAD_TIME = "SET_ITEM_RELOAD_TIME"
export const SET_ITEM_AMMUNITION = "SET_ITEM_AMMUNITION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_AMMUNITION = "SET_ITEM_AMMUNITION"
export const SET_ITEM_PROTECTION = "SET_ITEM_PROTECTION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_PROTECTION = "SET_ITEM_PROTECTION"
export const SET_ITEM_ENCUMBRANCE = "SET_ITEM_ENCUMBRANCE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_ENCUMBRANCE = "SET_ITEM_ENCUMBRANCE"
export const SET_ITEM_MOVEMENT_MODIFIER = "SET_ITEM_MOVEMENT_MODIFIER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_MOVEMENT_MODIFIER = "SET_ITEM_MOVEMENT_MODIFIER"
export const SET_ITEM_INITIATIVE_MODIFIER = "SET_ITEM_INITIATIVE_MODIFIER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_INITIATIVE_MODIFIER = "SET_ITEM_INITIATIVE_MODIFIER"
export const SET_ITEM_STABILITY_MODIFIER = "SET_ITEM_STABILITY_MODIFIER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_STABILITY_MODIFIER = "SET_ITEM_STABILITY_MODIFIER"
export const SWITCH_IS_ITEM_PARRYING_WEAPON = "SWITCH_IS_ITEM_PARRYING_WEAPON"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_IS_ITEM_PARRYING_WEAPON = "SWITCH_IS_ITEM_PARRYING_WEAPON"
export const SWITCH_IS_ITEM_TWO_HANDED_WEAPON = "SWITCH_IS_ITEM_TWO_HANDED_WEAPON"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_IS_ITEM_TWO_HANDED_WEAPON = "SWITCH_IS_ITEM_TWO_HANDED_WEAPON"
export const SWITCH_IS_ITEM_IMPROVISED_WEAPON = "SWITCH_IS_ITEM_IMPROVISED_WEAPON"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_IS_ITEM_IMPROVISED_WEAPON = "SWITCH_IS_ITEM_IMPROVISED_WEAPON"
export const SET_ITEM_IMPROVISED_WEAPON_GROUP = "SET_ITEM_IMPROVISED_WEAPON_GROUP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_IMPROVISED_WEAPON_GROUP = "SET_ITEM_IMPROVISED_WEAPON_GROUP"
export const SET_ITEM_LOSS = "SET_ITEM_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_LOSS = "SET_ITEM_LOSS"
export const SWITCH_IS_ITEM_FOR_ARMOR_ZONES_ONLY = "SWITCH_IS_ITEM_FOR_ARMOR_ZONES_ONLY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_IS_ITEM_FOR_ARMOR_ZONES_ONLY = "SWITCH_IS_ITEM_FOR_ARMOR_ZONES_ONLY"
export const SWITCH_ITEM_HAS_ADDITIONAL_PENALTIES = "SWITCH_ITEM_HAS_ADDITIONAL_PENALTIES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ITEM_HAS_ADDITIONAL_PENALTIES = "SWITCH_ITEM_HAS_ADDITIONAL_PENALTIES"
export const SET_ITEM_ARMOR_TYPE = "SET_ITEM_ARMOR_TYPE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_ARMOR_TYPE = "SET_ITEM_ARMOR_TYPE"
export const APPLY_ITEM_TEMPLATE = "APPLY_ITEM_TEMPLATE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type APPLY_ITEM_TEMPLATE = "APPLY_ITEM_TEMPLATE"
export const LOCK_ITEM_TEMPLATE = "LOCK_ITEM_TEMPLATE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type LOCK_ITEM_TEMPLATE = "LOCK_ITEM_TEMPLATE"
export const UNLOCK_ITEM_TEMPLATE = "UNLOCK_ITEM_TEMPLATE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type UNLOCK_ITEM_TEMPLATE = "UNLOCK_ITEM_TEMPLATE"
export const SET_MELEE_ITEM_TEMPLATES_CT_FILTER = "SET_MELEE_ITEM_TEMPLATES_CT_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_MELEE_ITEM_TEMPLATES_CT_FILTER = "SET_MELEE_ITEM_TEMPLATES_CT_FILTER"
export const SET_RANGED_ITEM_TEMPLATES_CT_FILTER = "SET_RANGED_ITEM_TEMPLATES_CT_FILTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_RANGED_ITEM_TEMPLATES_CT_FILTER = "SET_RANGED_ITEM_TEMPLATES_CT_FILTER"
export const SWITCH_ENABLE_ANIMATIONS = "SWITCH_ENABLE_ANIMATIONS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ENABLE_ANIMATIONS = "SWITCH_ENABLE_ANIMATIONS"
export const ADD_ARMOR_ZONES = "ADD_ARMOR_ZONES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ARMOR_ZONES = "ADD_ARMOR_ZONES"
export const REMOVE_ARMOR_ZONES = "REMOVE_ARMOR_ZONES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_ARMOR_ZONES = "REMOVE_ARMOR_ZONES"
export const CREATE_ARMOR_ZONES = "CREATE_ARMOR_ZONES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CREATE_ARMOR_ZONES = "CREATE_ARMOR_ZONES"
export const CLOSE_ARMOR_ZONES_EDITOR = "CLOSE_ARMOR_ZONES_EDITOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_ARMOR_ZONES_EDITOR = "CLOSE_ARMOR_ZONES_EDITOR"
export const SAVE_ARMOR_ZONES = "SAVE_ARMOR_ZONES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SAVE_ARMOR_ZONES = "SAVE_ARMOR_ZONES"
export const EDIT_ARMOR_ZONES = "EDIT_ARMOR_ZONES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type EDIT_ARMOR_ZONES = "EDIT_ARMOR_ZONES"
export const SET_ARMOR_ZONES_NAME = "SET_ARMOR_ZONES_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_NAME = "SET_ARMOR_ZONES_NAME"
export const SET_ARMOR_ZONES_HEAD = "SET_ARMOR_ZONES_HEAD"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_HEAD = "SET_ARMOR_ZONES_HEAD"
export const SET_ARMOR_ZONES_HEAD_LOSS = "SET_ARMOR_ZONES_HEAD_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_HEAD_LOSS = "SET_ARMOR_ZONES_HEAD_LOSS"
export const SET_ARMOR_ZONES_LEFT_ARM = "SET_ARMOR_ZONES_LEFT_ARM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_LEFT_ARM = "SET_ARMOR_ZONES_LEFT_ARM"
export const SET_ARMOR_ZONES_LEFT_ARM_LOSS = "SET_ARMOR_ZONES_LEFT_ARM_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_LEFT_ARM_LOSS = "SET_ARMOR_ZONES_LEFT_ARM_LOSS"
export const SET_ARMOR_ZONES_LEFT_LEG = "SET_ARMOR_ZONES_LEFT_LEG"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_LEFT_LEG = "SET_ARMOR_ZONES_LEFT_LEG"
export const SET_ARMOR_ZONES_LEFT_LEG_LOSS = "SET_ARMOR_ZONES_LEFT_LEG_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_LEFT_LEG_LOSS = "SET_ARMOR_ZONES_LEFT_LEG_LOSS"
export const SET_ARMOR_ZONES_TORSO = "SET_ARMOR_ZONES_TORSO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_TORSO = "SET_ARMOR_ZONES_TORSO"
export const SET_ARMOR_ZONES_TORSO_LOSS = "SET_ARMOR_ZONES_TORSO_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_TORSO_LOSS = "SET_ARMOR_ZONES_TORSO_LOSS"
export const SET_ARMOR_ZONES_RIGHT_ARM = "SET_ARMOR_ZONES_RIGHT_ARM"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_RIGHT_ARM = "SET_ARMOR_ZONES_RIGHT_ARM"
export const SET_ARMOR_ZONES_RIGHT_ARM_LOSS = "SET_ARMOR_ZONES_RIGHT_ARM_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_RIGHT_ARM_LOSS = "SET_ARMOR_ZONES_RIGHT_ARM_LOSS"
export const SET_ARMOR_ZONES_RIGHT_LEG = "SET_ARMOR_ZONES_RIGHT_LEG"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_RIGHT_LEG = "SET_ARMOR_ZONES_RIGHT_LEG"
export const SET_ARMOR_ZONES_RIGHT_LEG_LOSS = "SET_ARMOR_ZONES_RIGHT_LEG_LOSS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ARMOR_ZONES_RIGHT_LEG_LOSS = "SET_ARMOR_ZONES_RIGHT_LEG_LOSS"
export const ADD_PET = "ADD_PET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_PET = "ADD_PET"
export const CREATE_PET = "CREATE_PET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CREATE_PET = "CREATE_PET"
export const EDIT_PET = "EDIT_PET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type EDIT_PET = "EDIT_PET"
export const SAVE_PET = "SAVE_PET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SAVE_PET = "SAVE_PET"
export const CLOSE_PET_EDITOR = "CLOSE_PET_EDITOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CLOSE_PET_EDITOR = "CLOSE_PET_EDITOR"
export const REMOVE_PET = "REMOVE_PET"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_PET = "REMOVE_PET"
export const SET_PETS_SORT_ORDER = "SET_PETS_SORT_ORDER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PETS_SORT_ORDER = "SET_PETS_SORT_ORDER"
export const SET_PET_AVATAR = "SET_PET_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_AVATAR = "SET_PET_AVATAR"
export const DELETE_PET_AVATAR = "DELETE_PET_AVATAR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type DELETE_PET_AVATAR = "DELETE_PET_AVATAR"
export const SET_PET_NAME = "SET_PET_NAME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_NAME = "SET_PET_NAME"
export const SET_PET_SIZE = "SET_PET_SIZE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_SIZE = "SET_PET_SIZE"
export const SET_PET_TYPE = "SET_PET_TYPE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_TYPE = "SET_PET_TYPE"
export const SET_PET_SPENT_AP = "SET_PET_SPENT_AP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_SPENT_AP = "SET_PET_SPENT_AP"
export const SET_PET_TOTAL_AP = "SET_PET_TOTAL_AP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_TOTAL_AP = "SET_PET_TOTAL_AP"
export const SET_PET_COURAGE = "SET_PET_COURAGE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_COURAGE = "SET_PET_COURAGE"
export const SET_PET_SAGACITY = "SET_PET_SAGACITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_SAGACITY = "SET_PET_SAGACITY"
export const SET_PET_INTUITION = "SET_PET_INTUITION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_INTUITION = "SET_PET_INTUITION"
export const SET_PET_CHARISMA = "SET_PET_CHARISMA"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_CHARISMA = "SET_PET_CHARISMA"
export const SET_PET_DEXTERITY = "SET_PET_DEXTERITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_DEXTERITY = "SET_PET_DEXTERITY"
export const SET_PET_AGILITY = "SET_PET_AGILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_AGILITY = "SET_PET_AGILITY"
export const SET_PET_CONSTITUTION = "SET_PET_CONSTITUTION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_CONSTITUTION = "SET_PET_CONSTITUTION"
export const SET_PET_STRENGTH = "SET_PET_STRENGTH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_STRENGTH = "SET_PET_STRENGTH"
export const SET_PET_LP = "SET_PET_LP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_LP = "SET_PET_LP"
export const SET_PET_AE = "SET_PET_AE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_AE = "SET_PET_AE"
export const SET_PET_SPI = "SET_PET_SPI"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_SPI = "SET_PET_SPI"
export const SET_PET_TOU = "SET_PET_TOU"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_TOU = "SET_PET_TOU"
export const SET_PET_PRO = "SET_PET_PRO"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_PRO = "SET_PET_PRO"
export const SET_PET_INI = "SET_PET_INI"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_INI = "SET_PET_INI"
export const SET_PET_MOV = "SET_PET_MOV"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_MOV = "SET_PET_MOV"
export const SET_PET_ATTACK = "SET_PET_ATTACK"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_ATTACK = "SET_PET_ATTACK"
export const SET_PET_AT = "SET_PET_AT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_AT = "SET_PET_AT"
export const SET_PET_PA = "SET_PET_PA"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_PA = "SET_PET_PA"
export const SET_PET_DP = "SET_PET_DP"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_DP = "SET_PET_DP"
export const SET_PET_REACH = "SET_PET_REACH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_REACH = "SET_PET_REACH"
export const SET_PET_ACTIONS = "SET_PET_ACTIONS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_ACTIONS = "SET_PET_ACTIONS"
export const SET_PET_SKILLS = "SET_PET_SKILLS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_SKILLS = "SET_PET_SKILLS"
export const SET_PET_ABILITIES = "SET_PET_ABILITIES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_ABILITIES = "SET_PET_ABILITIES"
export const SET_PET_NOTES = "SET_PET_NOTES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PET_NOTES = "SET_PET_NOTES"
export const SWITCH_SHEET_ATTR_VALUE_VISIBILITY = "SWITCH_SHEET_ATTR_VALUE_VISIBILITY"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_SHEET_ATTR_VALUE_VISIBILITY = "SWITCH_SHEET_ATTR_VALUE_VISIBILITY"
export const SWITCH_SHEET_USE_PARCHMENT = "SWITCH_SHEET_USE_PARCHMENT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_SHEET_USE_PARCHMENT = "SWITCH_SHEET_USE_PARCHMENT"
export const SET_SHEET_ZOOM_FACTOR = "SET_SHEET_ZOOM_FACTOR"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SHEET_ZOOM_FACTOR = "SET_SHEET_ZOOM_FACTOR"
export const SWITCH_ENABLE_ACTIVE_ITEM_HINTS = "SWITCH_ENABLE_ACTIVE_ITEM_HINTS"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ENABLE_ACTIVE_ITEM_HINTS = "SWITCH_ENABLE_ACTIVE_ITEM_HINTS"
export const SET_THEME = "SET_THEME"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_THEME = "SET_THEME"
export const SWITCH_ENABLE_EDIT_AFTER_CREATION = "SWITCH_ENABLE_EDIT_AFTER_CREATION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SWITCH_ENABLE_EDIT_AFTER_CREATION = "SWITCH_ENABLE_EDIT_AFTER_CREATION"
export const SET_RACES_FILTER_TEXT = "SET_RACES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_RACES_FILTER_TEXT = "SET_RACES_FILTER_TEXT"
export const SET_CULTURES_FILTER_TEXT = "SET_CULTURES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_CULTURES_FILTER_TEXT = "SET_CULTURES_FILTER_TEXT"
export const SET_PROFESSIONS_FILTER_TEXT = "SET_PROFESSIONS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_PROFESSIONS_FILTER_TEXT = "SET_PROFESSIONS_FILTER_TEXT"
export const SET_ADVANTAGES_FILTER_TEXT = "SET_ADVANTAGES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ADVANTAGES_FILTER_TEXT = "SET_ADVANTAGES_FILTER_TEXT"
export const SET_INAC_ADVANTAGES_FILTER_TEXT = "SET_INAC_ADVANTAGES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_INAC_ADVANTAGES_FILTER_TEXT = "SET_INAC_ADVANTAGES_FILTER_TEXT"
export const SET_DISADVANTAGES_FILTER_TEXT = "SET_DISADVANTAGES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_DISADVANTAGES_FILTER_TEXT = "SET_DISADVANTAGES_FILTER_TEXT"
export const SET_INAC_DISADVANTAGES_FILTER_TEXT = "SET_INAC_DISADVANTAGES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_INAC_DISADVANTAGES_FILTER_TEXT = "SET_INAC_DISADVANTAGES_FILTER_TEXT"
export const SET_SKILLS_FILTER_TEXT = "SET_SKILLS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SKILLS_FILTER_TEXT = "SET_SKILLS_FILTER_TEXT"
export const SET_COMBAT_TECHNIQUES_FILTER_TEXT = "SET_COMBAT_TECHNIQUES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_COMBAT_TECHNIQUES_FILTER_TEXT = "SET_COMBAT_TECHNIQUES_FILTER_TEXT"
export const SET_SPECIAL_ABILITIES_FILTER_TEXT = "SET_SPECIAL_ABILITIES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SPECIAL_ABILITIES_FILTER_TEXT = "SET_SPECIAL_ABILITIES_FILTER_TEXT"
export const SET_INAC_SAS_FILTER_TEXT = "SET_INAC_SAS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_INAC_SAS_FILTER_TEXT = "SET_INAC_SAS_FILTER_TEXT"
export const SET_SPELLS_FILTER_TEXT = "SET_SPELLS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_SPELLS_FILTER_TEXT = "SET_SPELLS_FILTER_TEXT"
export const SET_INACTIVE_SPELLS_FILTER_TEXT = "SET_INACTIVE_SPELLS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_INACTIVE_SPELLS_FILTER_TEXT = "SET_INACTIVE_SPELLS_FILTER_TEXT"
export const SET_LITURGICAL_CHANTS_FILTER_TEXT = "SET_LITURGICAL_CHANTS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_LITURGICAL_CHANTS_FILTER_TEXT = "SET_LITURGICAL_CHANTS_FILTER_TEXT"
export const SET_INAC_LCS_FILTER_TEXT = "SET_INAC_LCS_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_INAC_LCS_FILTER_TEXT = "SET_INAC_LCS_FILTER_TEXT"
export const SET_EQUIPMENT_FILTER_TEXT = "SET_EQUIPMENT_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_EQUIPMENT_FILTER_TEXT = "SET_EQUIPMENT_FILTER_TEXT"
export const SET_ITEM_TEMPLATES_FILTER_TEXT = "SET_ITEM_TEMPLATES_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ITEM_TEMPLATES_FILTER_TEXT = "SET_ITEM_TEMPLATES_FILTER_TEXT"
export const SET_ZONE_ARMOR_FILTER_TEXT = "SET_ZONE_ARMOR_FILTER_TEXT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type SET_ZONE_ARMOR_FILTER_TEXT = "SET_ZONE_ARMOR_FILTER_TEXT"
export const LOAD_RAW_INGAME_DATA = "LOAD_RAW_INGAME_DATA"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type LOAD_RAW_INGAME_DATA = "LOAD_RAW_INGAME_DATA"
export const INGAME_PREVIOUS_PHASE = "INGAME_PREVIOUS_PHASE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_PREVIOUS_PHASE = "INGAME_PREVIOUS_PHASE"
export const INGAME_NEXT_PHASE = "INGAME_NEXT_PHASE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_NEXT_PHASE = "INGAME_NEXT_PHASE"
export const UPDATE_INGAME_CAST = "UPDATE_INGAME_CAST"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type UPDATE_INGAME_CAST = "UPDATE_INGAME_CAST"
export const CANCEL_INGAME_CAST = "CANCEL_INGAME_CAST"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type CANCEL_INGAME_CAST = "CANCEL_INGAME_CAST"
export const INGAME_USE_ENDURANCE = "INGAME_USE_ENDURANCE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_USE_ENDURANCE = "INGAME_USE_ENDURANCE"
export const INGAME_USE_ACTION = "INGAME_USE_ACTION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_USE_ACTION = "INGAME_USE_ACTION"
export const INGAME_USE_FREE_ACTION = "INGAME_USE_FREE_ACTION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_USE_FREE_ACTION = "INGAME_USE_FREE_ACTION"
export const INGAME_ACTIVATE_FIGHTER = "INGAME_ACTIVATE_FIGHTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_ACTIVATE_FIGHTER = "INGAME_ACTIVATE_FIGHTER"
export const INGAME_DEACTIVATE_FIGHTER = "INGAME_DEACTIVATE_FIGHTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_DEACTIVATE_FIGHTER = "INGAME_DEACTIVATE_FIGHTER"
export const INGAME_EDIT_START = "INGAME_EDIT_START"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_EDIT_START = "INGAME_EDIT_START"
export const INGAME_EDIT_UPDATE_VALUE = "INGAME_EDIT_UPDATE_VALUE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_EDIT_UPDATE_VALUE = "INGAME_EDIT_UPDATE_VALUE"
export const INGAME_EDIT_UPDATE_CAST_VALUE = "INGAME_EDIT_UPDATE_CAST_VALUE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_EDIT_UPDATE_CAST_VALUE = "INGAME_EDIT_UPDATE_CAST_VALUE"
export const INGAME_EDIT_UPDATE_DUPLICATE_VALUE = "INGAME_EDIT_UPDATE_DUPLICATE_VALUE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_EDIT_UPDATE_DUPLICATE_VALUE = "INGAME_EDIT_UPDATE_DUPLICATE_VALUE"
export const INGAME_EDIT_END = "INGAME_EDIT_END"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_EDIT_END = "INGAME_EDIT_END"
export const INGAME_ADD_FIGHTER = "INGAME_ADD_FIGHTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_ADD_FIGHTER = "INGAME_ADD_FIGHTER"
export const INGAME_DUPLICATE_FIGHTER = "INGAME_DUPLICATE_FIGHTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_DUPLICATE_FIGHTER = "INGAME_DUPLICATE_FIGHTER"
export const INGAME_REMOVE_FIGHTER = "INGAME_REMOVE_FIGHTER"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_REMOVE_FIGHTER = "INGAME_REMOVE_FIGHTER"
export const INGAME_RESET_PHASES = "INGAME_RESET_PHASES"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_RESET_PHASES = "INGAME_RESET_PHASES"
export const INGAME_RESET_HEALTH = "INGAME_RESET_HEALTH"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_RESET_HEALTH = "INGAME_RESET_HEALTH"
export const INGAME_RESET_ALL = "INGAME_RESET_ALL"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_RESET_ALL = "INGAME_RESET_ALL"
export const INGAME_UPDATE_ONLINE_LINK = "INGAME_UPDATE_ONLINE_LINK"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_UPDATE_ONLINE_LINK = "INGAME_UPDATE_ONLINE_LINK"
export const INGAME_SAVE = "INGAME_SAVE"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_SAVE = "INGAME_SAVE"
export const INGAME_SWITCH_OPTION = "INGAME_SWITCH_OPTION"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type INGAME_SWITCH_OPTION = "INGAME_SWITCH_OPTION"
export const ADD_ALERT = "ADD_ALERT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ADD_ALERT = "ADD_ALERT"
export const REMOVE_ALERT = "REMOVE_ALERT"
// eslint-disable-next-line @typescript-eslint/no-redeclare
export type REMOVE_ALERT = "REMOVE_ALERT" | the_stack |
import {
HttpClientTestingModule,
HttpTestingController,
} from '@angular/common/http/testing';
import { TestBed, async, inject } from '@angular/core/testing';
import { skip, take } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { PaginationBaseService } from './pagination-base.service';
import { PaginationResult } from './pagination-result';
describe('PaginationBaseService', () => {
let getHttpMock: () => HttpTestingController = () =>
TestBed.get(HttpTestingController);
let getService: () => UserService = () => TestBed.get(UserService);
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [UserService],
});
});
it('can provide HttpClient', inject(
[HttpClient],
(httpClient: HttpClient) => {
expect(httpClient).toBeTruthy();
expect(httpClient instanceof HttpClient).toBeTruthy();
}
));
it('can be provided', () => {
let service = getService();
expect(service).toBeTruthy();
expect(service instanceof UserService).toBeTruthy();
});
it('returns the correct result', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const request = httpMock.expectOne('/users?page=1&pageSize=20');
const paginationResponse: PaginationResult<User> = {
data: [{ id: 1, userName: 'George' }],
page: 1,
pageSize: 20,
totalCount: 1,
};
request.flush(paginationResponse);
const serviceResult = await service.paginationResult
.pipe(take(1))
.toPromise();
expect(serviceResult.totalCount).toBe(1);
httpMock.verify();
}));
it('requeries again on page change', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=1&pageSize=20');
expect(req.request.method).toBe('GET');
httpMock.verify();
service.page++;
await delay(1);
httpMock.expectOne('/users?page=2&pageSize=20');
httpMock.verify();
}));
it('requeries again on pageSize change', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=1&pageSize=20');
expect(req.request.method).toBe('GET');
httpMock.verify();
service.pageSize++;
await delay(1);
httpMock.expectOne('/users?page=1&pageSize=21');
httpMock.verify();
}));
it('requeries again on parameter addition', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=1&pageSize=20');
expect(req.request.method).toBe('GET');
httpMock.verify();
service.setQueryParameter('filter', 'byName');
await delay(1);
httpMock.expectOne('/users?page=1&pageSize=20&filter=byName');
httpMock.verify();
}));
it('requeries again on parameter change', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=1&pageSize=20');
expect(req.request.method).toBe('GET');
httpMock.verify();
service.setQueryParameter('filter', 'byName');
await delay(1);
httpMock.expectOne('/users?page=1&pageSize=20&filter=byName');
httpMock.verify();
service.setQueryParameter('filter', 'byAge');
await delay(1);
httpMock.expectOne('/users?page=1&pageSize=20&filter=byAge');
httpMock.verify();
}));
it('requeries again on force refresh', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=1&pageSize=20');
expect(req.request.method).toBe('GET');
httpMock.verify();
service.forceRefresh();
await delay(1);
httpMock.expectOne('/users?page=1&pageSize=20');
httpMock.verify();
}));
it('calls the correct url', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
service.pageSize = 13;
service.page = 2;
service.setQueryParameter('filter', 'byName');
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=2&pageSize=13&filter=byName');
expect(req.request.method).toBe('GET');
}));
it('calls url to get All items', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
service.getAll().toPromise();
await delay(1);
let httpMock = getHttpMock();
const req = httpMock.expectOne('/users?page=1&pageSize=500');
expect(req.request.method).toBe('GET');
}));
it('makes multiple requests when calling getAll', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
const getAllPromise = service.getAll().toPromise();
await delay(1);
let httpMock = getHttpMock();
let req = httpMock.expectOne('/users?page=1&pageSize=500');
expect(req.request.method).toBe('GET');
const response: PaginationResult<User> = {
page: 1,
pageSize: 1,
totalCount: 2,
data: [{ id: 1, userName: 'Alice' }],
};
req.flush(response);
await delay(1);
req = httpMock.expectOne('/users?page=2&pageSize=500');
expect(req.request.method).toBe('GET');
response.page = 2;
response.data = [{ id: 2, userName: 'Bob' }];
req.flush(response);
await delay(1);
req = httpMock.expectOne('/users?page=3&pageSize=500');
expect(req.request.method).toBe('GET');
req.flush(response);
const returnedResult = await getAllPromise;
expect(returnedResult.length).toBe(2);
expect(returnedResult[0].id).toBe(1);
expect(returnedResult[1].id).toBe(2);
}));
it('does not emit result on error response', async(async () => {
let hasReceivedResponse = false;
let service = getService();
service.baseUrl = '/users';
await delay(1);
service.paginationResult.subscribe((r) => (hasReceivedResponse = true));
let httpMock = getHttpMock();
const request = httpMock.expectOne('/users?page=1&pageSize=20');
request.error(new ErrorEvent('error'));
expect(hasReceivedResponse).toBeFalsy();
}));
it('cancels first request when second request sent', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const firstRequest = httpMock.expectOne('/users?page=1&pageSize=20');
service.forceRefresh();
await delay(1);
const secondRequest = httpMock.expectOne('/users?page=1&pageSize=20');
expect(firstRequest.cancelled).toBeTruthy();
expect(secondRequest.cancelled).toBeFalsy();
}));
it('does not send two requests when calling forceRefresh twice subsequently', async(async () => {
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const firstRequest = httpMock.expectOne('/users?page=1&pageSize=20');
service.forceRefresh();
service.forceRefresh();
await delay(1);
const secondRequest = httpMock.expectOne('/users?page=1&pageSize=20');
expect(firstRequest.cancelled).toBeTruthy();
expect(secondRequest.cancelled).toBeFalsy();
}));
it('does not break observable chain when receiving an error', async(async () => {
let hasReceivedResponse = false;
let service = getService();
service.baseUrl = '/users';
await delay(1);
service.paginationResult.subscribe((r) => (hasReceivedResponse = true));
let httpMock = getHttpMock();
const request = httpMock.expectOne('/users?page=1&pageSize=20');
request.error(new ErrorEvent('error'));
expect(hasReceivedResponse).toBeFalsy();
httpMock.verify();
service.forceRefresh();
await delay(1);
const secondRequest = httpMock.expectOne('/users?page=1&pageSize=20');
secondRequest.flush({});
expect(hasReceivedResponse).toBeTruthy();
}));
it('updates cached last pagination result before anouncing new result with forceRefresh', async(async () => {
await asyncStyleCacheCheck((s) => s.forceRefresh());
}));
it('updates cached last pagination result before anouncing new result with requery', async(async () => {
await asyncStyleCacheCheck((s) => s.publicRequery());
}));
let asyncStyleCacheCheck = async (requeryAction: (UserService) => void) => {
// This is a regression for the following bug:
// A derived service did implement a getItemById() function which did, before making a
// network call to retrieve the resource from the server, check if the item with the given
// id is present in the 'lastPaginationResult' local cache.
// Now after a force refresh and a subsequent retrieval, the following sequence of events happened:
// 1. Component subscribes to the pagination result to be notified when an update was finished.
// 2. The same component did react to the subscribe event by getting an item by its id
// 3. The service refreshed the items and raised the events
// 4. The component reacted by getting the item by id, which retrived it from the (stale) local cache of the service
// 5. The service finished it's refresh action and updated the local cache
// This was happening because after emitting 'next()' on an observable, subscribed actions were executed before
// continuing with the current code path
// Something learned today!
let service = getService();
service.baseUrl = '/users';
await delay(1);
let httpMock = getHttpMock();
const initialUsers = [
{ userName: 'George', id: 1 },
{ userName: 'Dave', id: 2 },
];
const updatedUsers = [
{ userName: 'Giorgio', id: 1 },
{ userName: 'Dave', id: 2 },
];
const initialRequest = httpMock.expectOne('/users?page=1&pageSize=20');
const initialPaginationResponse: PaginationResult<User> = {
data: initialUsers,
page: 1,
pageSize: 20,
totalCount: 1,
};
initialRequest.flush(initialPaginationResponse);
service.paginationResult
.pipe(skip(1)) // To not get the initial value from the first request
.subscribe((usersPaginated) => {
var hasNewUser = usersPaginated.data.find(
(u) => u.id === 1 && u.userName === 'Giorgio'
);
expect(hasNewUser).toBeTruthy();
var newUserById = service.getUserById(1).then((user) => {
expect(user.userName).toBe('Giorgio'); // Initially, this returned the user 'George' from the stale cache
});
});
requeryAction(service); // This is currently either calling 'forceRefresh()' or 'requery()'
await delay(1);
const secondRequest = httpMock.expectOne('/users?page=1&pageSize=20');
const secondPaginationResponse: PaginationResult<User> = {
data: updatedUsers,
page: 1,
pageSize: 20,
totalCount: 1,
};
secondRequest.flush(secondPaginationResponse);
};
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
});
@Injectable()
class UserService extends PaginationBaseService<User> {
constructor(protected http: HttpClient) {
super(http);
}
public publicRequery = () => this.requery();
public getUserById(userId: number): Promise<User> {
if (this.lastPaginationResult && this.lastPaginationResult.data) {
const cachedUser = this.lastPaginationResult.data.find(
(u) => u.id === userId
);
if (cachedUser) {
return Promise.resolve(cachedUser);
}
}
throw Error('Not implemented');
}
}
interface User {
id: number;
userName: string;
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_liveworkstream_Information {
interface Header extends DevKit.Controls.IHeader {
/** The channel to which this workstream is attached */
msdyn_streamsource: DevKit.Controls.OptionSet;
/** Specifies the mode i.e Push/Pick for the workstream */
msdyn_workdistributionmode: DevKit.Controls.OptionSet;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface tab_BotAssistedAgentGuidance_Sections {
tab_4_section_1: DevKit.Controls.Section;
}
interface tab_quickReplies_Sections {
tab_6_section_1: DevKit.Controls.Section;
}
interface tab_RoutingRuleItems_Sections {
}
interface tab_SkillAttachmentRulesTab_Sections {
SkillAttachmentSection: DevKit.Controls.Section;
}
interface tab_smsNumbers_Sections {
tab_4_section_1: DevKit.Controls.Section;
}
interface tab_smsSettings_Sections {
MSFlowOutboundNotifications: DevKit.Controls.Section;
RESTAPIDetails: DevKit.Controls.Section;
SMSConnectionParameters: DevKit.Controls.Section;
SMSProviderDetails: DevKit.Controls.Section;
}
interface tab_tab_3_Sections {
tab_3_section_2: DevKit.Controls.Section;
}
interface tab_tab_templates_Sections {
tab_templates_section_1: DevKit.Controls.Section;
tab_templates_section_2: DevKit.Controls.Section;
}
interface tab_tab1_summary_Sections {
tab_3_section_1: DevKit.Controls.Section;
tab1_summary_section_6: DevKit.Controls.Section;
}
interface tab_BotAssistedAgentGuidance extends DevKit.Controls.ITab {
Section: tab_BotAssistedAgentGuidance_Sections;
}
interface tab_quickReplies extends DevKit.Controls.ITab {
Section: tab_quickReplies_Sections;
}
interface tab_RoutingRuleItems extends DevKit.Controls.ITab {
Section: tab_RoutingRuleItems_Sections;
}
interface tab_SkillAttachmentRulesTab extends DevKit.Controls.ITab {
Section: tab_SkillAttachmentRulesTab_Sections;
}
interface tab_smsNumbers extends DevKit.Controls.ITab {
Section: tab_smsNumbers_Sections;
}
interface tab_smsSettings extends DevKit.Controls.ITab {
Section: tab_smsSettings_Sections;
}
interface tab_tab_3 extends DevKit.Controls.ITab {
Section: tab_tab_3_Sections;
}
interface tab_tab_templates extends DevKit.Controls.ITab {
Section: tab_tab_templates_Sections;
}
interface tab_tab1_summary extends DevKit.Controls.ITab {
Section: tab_tab1_summary_Sections;
}
interface Tabs {
BotAssistedAgentGuidance: tab_BotAssistedAgentGuidance;
quickReplies: tab_quickReplies;
RoutingRuleItems: tab_RoutingRuleItems;
SkillAttachmentRulesTab: tab_SkillAttachmentRulesTab;
smsNumbers: tab_smsNumbers;
smsSettings: tab_smsSettings;
tab_3: tab_tab_3;
tab_templates: tab_tab_templates;
tab1_summary: tab_tab1_summary;
}
interface Body {
Tab: Tabs;
msdyn_allowedpresencehelptext: DevKit.Controls.ActionCards;
/** Allowed base presences for the work stream */
msdyn_AllowedPresences: DevKit.Controls.MultiOptionSet;
/** The API Key equivalent to password of account set up with TeleSign */
msdyn_APIKey: DevKit.Controls.String;
/** Set the time after which a work item can be assigned to the agent again after he/she has declined the work item or the request has timed out */
msdyn_AssignWorkItemAfterDecline: DevKit.Controls.Integer;
/** Set the time after which the work item will be closed if there is no activity on the work item. */
msdyn_AutoCloseAfterInactivity: DevKit.Controls.Integer;
/** Defines how the work stream will measure capacity consumption */
msdyn_capacityformat: DevKit.Controls.OptionSet;
/** The units of capacity that should be available for an item of this work stream to be processed. */
msdyn_CapacityRequired: DevKit.Controls.Integer;
/** Flow URL for Dynamics 365 connector */
msdyn_ConnectorsURL: DevKit.Controls.String;
/** The Customer Id equivalent to username of account set up with TeleSign */
msdyn_CustomerID: DevKit.Controls.String;
/** Keep same agent for entire conversation */
msdyn_enableagentaffinity: DevKit.Controls.Boolean;
msdyn_enableagentAffinityhelptext: DevKit.Controls.ActionCards;
/** Agents can choose to work on items from push-based work streams. */
msdyn_enableselectingfrompushbasedworkstreams: DevKit.Controls.Boolean;
/** Unique identifier for Workstream Entity Configuration associated with Work Stream. */
msdyn_EntityRoutingConfigurationId: DevKit.Controls.Lookup;
/** The time when Validation api was last run */
msdyn_LastValidationOn: DevKit.Controls.DateTime;
/** The status of the last Validation results */
msdyn_LastValidationStatus: DevKit.Controls.String;
/** Matching logic used for Skill Based Routing like Exact Match or Closest match */
msdyn_matchinglogic: DevKit.Controls.OptionSet;
/** Maximum number of concurrent sessions that an agent can work for a work item of a particular stream. */
msdyn_MaxConcurrentConnection: DevKit.Controls.Integer;
/** Name of Work stream */
msdyn_name: DevKit.Controls.String;
/** Notification type */
msdyn_Notification: DevKit.Controls.OptionSet;
/** Consult notification template scenario */
msdyn_notificationtemplate_consult: DevKit.Controls.String;
/** Incoming authenticated notification template scenario */
msdyn_notificationtemplate_incoming_auth: DevKit.Controls.String;
/** Incoming unauthenticated notification template scenario */
msdyn_notificationtemplate_incoming_unauth: DevKit.Controls.String;
/** supervisorAssign notification template scenario */
msdyn_notificationtemplate_supervisorassign: DevKit.Controls.String;
/** Transfer notification template scenario */
msdyn_notificationtemplate_transfer: DevKit.Controls.String;
/** Time duration options for notification. */
msdyn_Screenpoptimeout_optionSet: DevKit.Controls.OptionSet;
/** Default session template scenario */
msdyn_sessiontemplate_default: DevKit.Controls.String;
/** SMS Provider */
msdyn_smsprovider: DevKit.Controls.OptionSet;
/** The channel to which this workstream is attached */
msdyn_streamsource: DevKit.Controls.OptionSet;
/** URL for TeleSign Inbound link */
msdyn_TelesignInboundURL: DevKit.Controls.String;
/** URL for Twilio Inbound link */
msdyn_TwilioInboundURL: DevKit.Controls.String;
/** Specifies the mode i.e Push/Pick for the workstream */
msdyn_workdistributionmode: DevKit.Controls.OptionSet;
WebResource_HelpDialog: DevKit.Controls.WebResource;
}
interface Grid {
contextvariables: DevKit.Controls.Grid;
SMSNumbers: DevKit.Controls.Grid;
AttachmentRulesSubGrid: DevKit.Controls.Grid;
RuleItems: DevKit.Controls.Grid;
BotAssistedAgentGuidanceSubGrid: DevKit.Controls.Grid;
quickreplies: DevKit.Controls.Grid;
}
}
class Formmsdyn_liveworkstream_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_liveworkstream_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_liveworkstream_Information */
Body: DevKit.Formmsdyn_liveworkstream_Information.Body;
/** The Header section of form msdyn_liveworkstream_Information */
Header: DevKit.Formmsdyn_liveworkstream_Information.Header;
/** The Grid of form msdyn_liveworkstream_Information */
Grid: DevKit.Formmsdyn_liveworkstream_Information.Grid;
}
namespace FormInformation_New {
interface tab_tab1_summary_Sections {
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_tab1_summary extends DevKit.Controls.ITab {
Section: tab_tab1_summary_Sections;
}
interface Tabs {
tab1_summary: tab_tab1_summary;
}
interface Body {
Tab: Tabs;
/** The channel to which this workstream is attached */
msdyn_streamsource: DevKit.Controls.OptionSet;
}
}
class FormInformation_New extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Information_New
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Information_New */
Body: DevKit.FormInformation_New.Body;
}
class msdyn_liveworkstreamApi {
/**
* DynamicsCrm.DevKit msdyn_liveworkstreamApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Allowed base presences for the work stream */
msdyn_AllowedPresences: DevKit.WebApi.MultiOptionSetValue;
/** The API Key equivalent to password of account set up with TeleSign */
msdyn_APIKey: DevKit.WebApi.StringValue;
/** Version number of the API key */
msdyn_apikeyversionnumber: DevKit.WebApi.IntegerValue;
/** Set the time after which a work item can be assigned to the agent again after he/she has declined the work item or the request has timed out */
msdyn_AssignWorkItemAfterDecline: DevKit.WebApi.IntegerValue;
/** Set the time after which the work item will be closed if there is no activity on the work item. */
msdyn_AutoCloseAfterInactivity: DevKit.WebApi.IntegerValue;
/** The queue created for the bot in the workstream. */
msdyn_bot_queue: DevKit.WebApi.LookupValue;
/** The rule added to workstream for bot routing. */
msdyn_bot_rule: DevKit.WebApi.StringValue;
/** The user of the bot. */
msdyn_bot_user: DevKit.WebApi.LookupValue;
/** Defines how the work stream will measure capacity consumption */
msdyn_capacityformat: DevKit.WebApi.OptionSetValue;
/** The units of capacity that should be available for an item of this work stream to be processed. */
msdyn_CapacityRequired: DevKit.WebApi.IntegerValue;
/** Flow URL for Dynamics 365 connector */
msdyn_ConnectorsURL: DevKit.WebApi.StringValue;
/** Conversation mode of chat channels */
msdyn_conversationmode: DevKit.WebApi.OptionSetValue;
/** The Customer Id equivalent to username of account set up with TeleSign */
msdyn_CustomerID: DevKit.WebApi.StringValue;
/** Keep same agent for entire conversation */
msdyn_enableagentaffinity: DevKit.WebApi.BooleanValue;
/** Option for allowing automated messages or not */
msdyn_enableautomatedmessages: DevKit.WebApi.BooleanValue;
/** Agents can choose to work on items from push-based work streams. */
msdyn_enableselectingfrompushbasedworkstreams: DevKit.WebApi.BooleanValue;
/** Unique identifier for Workstream Entity Configuration associated with Work Stream. */
msdyn_EntityRoutingConfigurationId: DevKit.WebApi.LookupValue;
/** Fall back language to be used for Live chat */
msdyn_FallBackLanguage: DevKit.WebApi.StringValue;
/** Set the time after which the work item should be offered to an agent if the work item has been waiting for input. */
msdyn_FollowUpAfterWaiting: DevKit.WebApi.IntegerValue;
/** Declare the expected handling time under which work items for this work stream should get resolved */
msdyn_handlingtimethreshold: DevKit.WebApi.IntegerValue;
/** The time when Validation api was last run */
msdyn_LastValidationOn_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue;
/** The status of the last Validation results */
msdyn_LastValidationStatus: DevKit.WebApi.StringValue;
/** Unique identifier for entity instances */
msdyn_liveworkstreamId: DevKit.WebApi.GuidValue;
/** Unique identifier for master entity routing configuration associated with work stream. */
msdyn_masterentityroutingconfigurationid: DevKit.WebApi.LookupValue;
/** Matching logic used for Skill Based Routing like Exact Match or Closest match */
msdyn_matchinglogic: DevKit.WebApi.OptionSetValue;
/** Maximum number of concurrent sessions that an agent can work for a work item of a particular stream. */
msdyn_MaxConcurrentConnection: DevKit.WebApi.IntegerValue;
/** Mode of experience */
msdyn_mode: DevKit.WebApi.OptionSetValue;
/** Name of Work stream */
msdyn_name: DevKit.WebApi.StringValue;
/** Notification type */
msdyn_Notification: DevKit.WebApi.OptionSetValue;
/** Notification association with scenarios */
msdyn_notificationscenarioplaceholder: DevKit.WebApi.StringValue;
/** Consult notification template scenario */
msdyn_notificationtemplate_consult: DevKit.WebApi.StringValue;
/** Incoming authenticated notification template scenario */
msdyn_notificationtemplate_incoming_auth: DevKit.WebApi.StringValue;
/** Incoming unauthenticated notification template scenario */
msdyn_notificationtemplate_incoming_unauth: DevKit.WebApi.StringValue;
/** supervisorAssign notification template scenario */
msdyn_notificationtemplate_supervisorassign: DevKit.WebApi.StringValue;
/** Transfer notification template scenario */
msdyn_notificationtemplate_transfer: DevKit.WebApi.StringValue;
/** Record identification rule associated to a workstream */
msdyn_recordidentificationrule: DevKit.WebApi.StringValue;
/** Record Identification Validation Rule */
msdyn_RecordIdentificationValidationRule: DevKit.WebApi.StringValue;
/** Link contracts with live work streams. */
msdyn_routingcontractid: DevKit.WebApi.LookupValue;
/** Time duration for which notification will be shown to agent. */
msdyn_Screenpoptimeout: DevKit.WebApi.IntegerValue;
/** Time duration options for notification. */
msdyn_Screenpoptimeout_optionSet: DevKit.WebApi.OptionSetValue;
/** Session association with scenarios */
msdyn_sessionscenarioplaceholder: DevKit.WebApi.StringValue;
/** Default session template scenario */
msdyn_sessiontemplate_default: DevKit.WebApi.StringValue;
/** Skill Attachment Rules Count */
msdyn_skillattachmentrulescount: DevKit.WebApi.IntegerValueReadonly;
/** Last Updated time of rollup field Skill Attachment Rules Count. */
msdyn_skillattachmentrulescount_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Skill Attachment Rules Count. */
msdyn_skillattachmentrulescount_State: DevKit.WebApi.IntegerValueReadonly;
/** SMS Provider */
msdyn_smsprovider: DevKit.WebApi.OptionSetValue;
/** The channel to which this workstream is attached */
msdyn_streamsource: DevKit.WebApi.OptionSetValue;
/** URL for TeleSign Inbound link */
msdyn_TelesignInboundURL: DevKit.WebApi.StringValue;
/** URL for Twilio Inbound link */
msdyn_TwilioInboundURL: DevKit.WebApi.StringValue;
/** Declare the expected waiting time under which work items for this work stream should be assigned to agents */
msdyn_waitingtimethreshold: DevKit.WebApi.IntegerValue;
/** Specifies the mode i.e Push/Pick for the workstream */
msdyn_workdistributionmode: DevKit.WebApi.OptionSetValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Work stream */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Work stream */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_liveworkstream {
enum msdyn_AllowedPresences {
/** 192360000 */
Available,
/** 192360003 */
Away,
/** 192360001 */
Busy,
/** 192360002 */
Busy_DND,
/** 192360004 */
Offline
}
enum msdyn_capacityformat {
/** 192360000 */
Profile_based,
/** 192350000 */
Unit_based
}
enum msdyn_conversationmode {
/** 192350000 */
Live_Chat,
/** 192350001 */
Persistent_Chat
}
enum msdyn_matchinglogic {
/** 192350001 */
Closest_Match,
/** 192350000 */
Exact_Match
}
enum msdyn_mode {
/** 717210000 */
Legacy,
/** 717210001 */
Simplified
}
enum msdyn_Notification {
/** 100000000 */
Directly_open_session,
/** 100000002 */
Screen_pop_with_decline,
/** 100000001 */
Screen_pop_with_timeout
}
enum msdyn_Screenpoptimeout_optionSet {
/** 120 */
_120,
/** 150 */
_150,
/** 180 */
_180,
/** 210 */
_210,
/** 240 */
_240,
/** 270 */
_270,
/** 30 */
_30,
/** 300 */
_300,
/** 60 */
_60,
/** 90 */
_90
}
enum msdyn_smsprovider {
/** 192350000 */
TeleSign,
/** 192350001 */
Twilio
}
enum msdyn_streamsource {
/** 192390000 */
Co_browse,
/** 192350002 */
Custom,
/** 192350000 */
Entity_Records,
/** 192330000 */
Facebook,
/** 192310000 */
LINE,
/** 192360000 */
Live_chat,
/** 19241000 */
Microsoft_Teams,
/** 192400000 */
Screen_sharing,
/** 192340000 */
SMS,
/** 192350001 */
Twitter,
/** 192380000 */
Video,
/** 192370000 */
Voice,
/** 192320000 */
WeChat,
/** 192300000 */
WhatsApp
}
enum msdyn_workdistributionmode {
/** 192350001 */
Pick,
/** 192350000 */
Push
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information','Information (New)'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { TypedRule, Replacement, typescriptOnly, excludeDeclarationFiles } from '@fimbul/ymir';
import * as ts from 'typescript';
import {
expressionNeedsParensWhenReplacingNode,
isAmbientPropertyDeclaration,
isAmbientVariableDeclaration,
typesAreEqual,
tryGetBaseConstraintType,
} from '../utils';
import {
isVariableDeclaration,
hasModifier,
isFunctionScopeBoundary,
unionTypeParts,
isFunctionExpression,
isArrowFunction,
getIIFE,
removeOptionalityFromType,
isStrictCompilerOptionEnabled,
isConstAssertion,
isInConstContext,
isTypeReference,
isTupleType,
isOptionalChainingUndefinedMarkerType,
} from 'tsutils';
import * as debug from 'debug';
const log = debug('wotan:rule:no-useless-assertion');
const FAIL_MESSAGE = "This assertion is unnecesary as it doesn't change the type of the expression.";
const FAIL_DEFINITE_ASSIGNMENT = 'This assertion is unnecessary as it has no effect on this declaration.';
@excludeDeclarationFiles
@typescriptOnly
export class Rule extends TypedRule {
private strictNullChecks = isStrictCompilerOptionEnabled(this.context.compilerOptions, 'strictNullChecks');
public apply(): void {
for (const node of this.context.getFlatAst()) {
switch (node.kind) {
case ts.SyntaxKind.NonNullExpression:
this.checkNonNullAssertion(<ts.NonNullExpression>node);
break;
case ts.SyntaxKind.AsExpression:
case ts.SyntaxKind.TypeAssertionExpression:
this.checkTypeAssertion(<ts.AssertionExpression>node);
break;
case ts.SyntaxKind.VariableDeclaration:
this.checkDefiniteAssignmentAssertion(<ts.VariableDeclaration>node);
break;
case ts.SyntaxKind.PropertyDeclaration:
this.checkDefiniteAssignmentAssertionProperty(<ts.PropertyDeclaration>node);
}
}
}
private checkDefiniteAssignmentAssertion(node: ts.VariableDeclaration) {
// compiler already emits an error for definite assignment assertions on ambient or initialized variables
if (node.exclamationToken !== undefined &&
node.initializer === undefined &&
node.type !== undefined &&
!isAmbientVariableDeclaration(node) && (
!isStrictCompilerOptionEnabled(this.context.compilerOptions, 'strictNullChecks') ||
// type does not allow undefined
getNullableFlagsOfReceiver(this.checker.getTypeAtLocation(node.name)) & ts.TypeFlags.Undefined
))
this.addFinding(
node.exclamationToken.end - 1,
node.exclamationToken.end,
FAIL_DEFINITE_ASSIGNMENT,
Replacement.delete(node.exclamationToken.pos, node.exclamationToken.end),
);
}
private checkDefiniteAssignmentAssertionProperty(node: ts.PropertyDeclaration) {
// compiler emits an error for definite assignment assertions on ambient, initialized or abstract properties
if (node.exclamationToken !== undefined &&
node.initializer === undefined &&
node.type !== undefined &&
!isAmbientPropertyDeclaration(node) &&
!hasModifier(node.modifiers, ts.SyntaxKind.AbstractKeyword, ts.SyntaxKind.StaticKeyword) && (
// properties with string or computed name are not checked
node.name.kind !== ts.SyntaxKind.Identifier && node.name.kind !== ts.SyntaxKind.PrivateIdentifier ||
!isStrictCompilerOptionEnabled(this.context.compilerOptions, 'strictPropertyInitialization') ||
getNullableFlagsOfReceiver(this.checker.getTypeAtLocation(node)) & ts.TypeFlags.Undefined // type allows undefined
))
this.addFinding(
node.exclamationToken.end - 1,
node.exclamationToken.end,
FAIL_DEFINITE_ASSIGNMENT,
Replacement.delete(node.exclamationToken.pos, node.exclamationToken.end),
);
}
private checkNonNullAssertion(node: ts.NonNullExpression) {
let message = FAIL_MESSAGE;
if (this.strictNullChecks) {
const originalType = this.checker.getTypeAtLocation(node.expression);
const flags = getNullableFlags(
tryGetBaseConstraintType(originalType, this.checker),
ts.isOptionalChain(node)
? (t) => isOptionalChainingUndefinedMarkerType(this.checker, t) ? 0 : t.flags
: undefined,
);
if (flags) { // type is nullable
const contextualType = this.getSafeContextualType(node);
if (contextualType === undefined || (flags & ~getNullableFlagsOfReceiver(contextualType)))
return;
message = `This assertion is unnecessary as the receiver accepts ${formatNullableFlags(flags)} values.`;
}
if (maybeUsedBeforeBeingAssigned(node.expression, originalType, this.checker)) {
log('Identifier %s could be used before being assigned', node.expression.text);
return;
}
}
this.addFinding(node.end - 1, node.end, message, Replacement.delete(node.expression.end, node.end));
}
private checkTypeAssertion(node: ts.AssertionExpression) {
if (isConstAssertion(node)) {
if (isInConstContext(node))
this.reportUselessTypeAssertion(node, 'This assertion is unnecessary as it is already in a const context.');
return;
}
let targetType = this.checker.getTypeFromTypeNode(node.type);
if ((targetType.flags & ts.TypeFlags.Literal) !== 0 && !isInConstContext(node) || // allow "foo" as "foo" to avoid widening
isTupleType(isTypeReference(targetType) ? targetType.target : targetType))
return;
let sourceType = this.checker.getTypeAtLocation(node.expression);
if ((targetType.flags & (ts.TypeFlags.TypeVariable | ts.TypeFlags.Instantiable)) === 0) {
targetType = tryGetBaseConstraintType(targetType, this.checker);
sourceType = tryGetBaseConstraintType(sourceType, this.checker);
}
let message = FAIL_MESSAGE;
if (!typesAreEqual(sourceType, targetType, this.checker)) {
const contextualType = this.getSafeContextualType(node);
// TODO use assignability check once it's exposed from TypeChecker
if (
contextualType === undefined ||
contextualType.flags & (ts.TypeFlags.TypeVariable | ts.TypeFlags.Instantiable) ||
(contextualType.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) === 0 &&
// contextual type is exactly the same
!typesAreEqual(sourceType, contextualType, this.checker) &&
// contextual type is an optional parameter or similar
!typesAreEqual(sourceType, removeOptionalityFromType(this.checker, contextualType), this.checker)
)
return;
message = 'This assertion is unnecessary as the receiver accepts the original type of the expression.';
}
this.reportUselessTypeAssertion(node, message);
}
private reportUselessTypeAssertion(node: ts.AssertionExpression, message: string) {
if (node.kind === ts.SyntaxKind.AsExpression) {
this.addFinding(
node.type.pos - 'as'.length,
node.end,
message,
Replacement.delete(node.expression.end, node.end),
);
} else {
const start = node.getStart(this.sourceFile);
const fix = [Replacement.delete(start, node.expression.getStart(this.sourceFile))];
if (expressionNeedsParensWhenReplacingNode(node.expression, node))
fix.push(
Replacement.append(start, '('),
Replacement.append(node.end, ')'),
);
this.addFinding(start, node.expression.pos, message, fix);
}
}
/** Returns the contextual type if it is a position that does not contribute to control flow analysis. */
private getSafeContextualType(node: ts.Expression): ts.Type | undefined {
const parent = node.parent!;
// If assertion is used as argument, check if the function accepts this expression without an assertion
// TODO expand this to VariableLike initializers and return expressions where a type declaration exists
switch (parent.kind) {
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.NewExpression:
if (node === (<ts.CallExpression | ts.NewExpression>parent).expression)
return;
break;
case ts.SyntaxKind.TemplateSpan: // TODO return 'any' for non-tagged template expressions
case ts.SyntaxKind.JsxExpression:
break;
default:
return;
}
return this.checker.getContextualType(node);
}
}
function getNullableFlags(type: ts.Type, selector?: (t: ts.Type) => ts.TypeFlags): ts.TypeFlags {
let flags = 0;
for (const t of unionTypeParts(type))
flags |= selector !== undefined ? selector(t) : t.flags;
return flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined);
}
function getNullableFlagsOfReceiver(type: ts.Type) {
return getNullableFlags(type, (t) => t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown) ? -1 : t.flags);
}
function formatNullableFlags(flags: ts.TypeFlags) {
switch (flags) {
case ts.TypeFlags.Null: return "'null'";
case ts.TypeFlags.Undefined: return "'undefined'";
default: return "'null' and 'undefined'";
}
}
/**
* Determine if the assertion may be necessary to avoid a compile error for use before being assigned.
* This function may yield some false negatives, but is needed until https://github.com/Microsoft/TypeScript/issues/20221 is implemented.
*
* The rules are as follows:
* * strictNullChecks are enabled
* * assertion is on an identifier
* * identifier is a mutable variable
* * no destructuring, parameters, catch binding, ambient declarations
* * variable is not initialized
* * variable has no definite assignment assertion (exclamation mark)
* * variable has a type annotation
* * declared type is equal to the type at the assertion
* * declaration and assertion are in the same function scope
*
* We don't need to worry about strictPropertyInitialization errors, because they cannot be suppressed with a non-null assertion
*/
function maybeUsedBeforeBeingAssigned(node: ts.Expression, type: ts.Type, checker: ts.TypeChecker): node is ts.Identifier {
if (node.kind !== ts.SyntaxKind.Identifier || getNullableFlagsOfReceiver(type) & ts.TypeFlags.Undefined)
return false;
const symbol = checker.getSymbolAtLocation(node)!;
const declaration = symbol.declarations![0];
if (!isVariableDeclaration(declaration) ||
declaration.parent!.kind !== ts.SyntaxKind.VariableDeclarationList ||
declaration.initializer !== undefined ||
declaration.exclamationToken !== undefined ||
declaration.type === undefined ||
declaration.parent!.parent!.kind === ts.SyntaxKind.VariableStatement &&
hasModifier(declaration.parent!.parent!.modifiers, ts.SyntaxKind.DeclareKeyword))
return false;
if (!typesAreEqual(type, checker.getTypeFromTypeNode(declaration.type), checker))
return false;
const declaringFunctionScope = findupFunction(declaration.parent!.parent!.parent!);
let useFunctionScope = findupFunction(node.parent!.parent!);
while (useFunctionScope !== declaringFunctionScope && isInlinedIife(useFunctionScope))
// TypeScript inlines IIFEs, so we need to do as well
useFunctionScope = findupFunction(useFunctionScope.parent!.parent!);
return useFunctionScope === declaringFunctionScope;
}
/** Finds the nearest parent that has a function scope. */
function findupFunction(node: ts.Node) {
while (!isFunctionScopeBoundary(node) && node.kind !== ts.SyntaxKind.SourceFile)
node = node.parent!;
return node;
}
function isInlinedIife(node: ts.Node): boolean {
return (isFunctionExpression(node) || isArrowFunction(node)) &&
node.asteriskToken === undefined && // exclude generators
!hasModifier(node.modifiers, ts.SyntaxKind.AsyncKeyword) && // exclude async functions
getIIFE(node) !== undefined;
} | the_stack |
import ADB from 'appium-adb';
import { KeyEventCode, PackageInfo } from 'electron/platform/android/adb-wrapper';
import { AppiumAdbWrapper } from 'electron/platform/android/appium-adb-wrapper';
import { ExpectedCallType, IMock, It, Mock, MockBehavior, Times } from 'typemoq';
describe('AppiumAdbWrapper tests', () => {
let adbMock: IMock<ADB>;
let testSubject: AppiumAdbWrapper;
const emulatorId: string = 'id1';
const emulatorModel: string = 'model1';
const deviceId: string = 'id2';
const deviceModel: string = 'model2';
const testPackageName: string = 'my_service';
const testDumpsysService = 'super_widget';
const expectedPathToApk: string = './some/path/package.apk';
const testConfig = {
deviceName: 'my device',
packageName: 'app.company.com',
irrelevantOtherProperty: 'should not appear in output',
};
const testContentUri: string = `content://${testPackageName}`;
beforeEach(() => {
adbMock = Mock.ofType<ADB>(undefined, MockBehavior.Strict);
testSubject = new AppiumAdbWrapper(adbMock.object);
});
it('getConnectedDevices, propagates error', async () => {
const expectedMessage = 'Thrown during getConnectedDevices';
adbMock
.setup(m => m.getConnectedEmulators())
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(testSubject.getConnectedDevices()).rejects.toThrowError(expectedMessage);
adbMock.verifyAll();
});
it('getConnectedDevices, No devices detected', async () => {
adbMock
.setup(m => m.getConnectedEmulators())
.returns(() => [])
.verifiable(Times.once());
adbMock
.setup(m => m.getConnectedDevices())
.returns(() => [])
.verifiable(Times.once());
const devices = await testSubject.getConnectedDevices();
expect(devices.length).toBe(0);
adbMock.verifyAll();
});
it('getConnectedDevices, 1 emulator detected', async () => {
const expectedDevices = [{ udid: emulatorId }];
adbMock
.setup(m => m.getConnectedEmulators())
.returns(() => expectedDevices)
.verifiable(Times.once());
adbMock
.setup(m => m.getConnectedDevices())
.returns(() => expectedDevices)
.verifiable(Times.once());
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.getModel())
.returns(() => emulatorModel)
.verifiable(Times.once());
const devices = await testSubject.getConnectedDevices();
expect(devices.length).toBe(1);
expect(devices[0].id).toBe(emulatorId);
expect(devices[0].isEmulator).toBe(true);
expect(devices[0].friendlyName).toBe(emulatorModel);
adbMock.verifyAll();
});
it('getConnectedDevices, 1 physical device detected', async () => {
const expectedDevices = [{ udid: deviceId }];
adbMock
.setup(m => m.getConnectedEmulators())
.returns(() => [])
.verifiable(Times.once());
adbMock
.setup(m => m.getConnectedDevices())
.returns(() => expectedDevices)
.verifiable(Times.once());
adbMock.setup(m => m.setDeviceId(deviceId)).verifiable(Times.once());
adbMock
.setup(m => m.getModel())
.returns(() => deviceModel)
.verifiable(Times.once());
const devices = await testSubject.getConnectedDevices();
expect(devices.length).toBe(1);
expect(devices[0].id).toBe(deviceId);
expect(devices[0].isEmulator).toBe(false);
expect(devices[0].friendlyName).toBe(deviceModel);
adbMock.verifyAll();
});
it('getConnectedDevices, 1 emulator and 1 physical device detected', async () => {
const expectedEmulators = [{ udid: emulatorId }];
const expectedDevices = [{ udid: deviceId }, { udid: emulatorId }];
const expectedModels: Array<string> = [emulatorModel, deviceModel];
let modelIndex = 0;
adbMock
.setup(m => m.getConnectedEmulators())
.returns(() => expectedEmulators)
.verifiable(Times.once());
adbMock
.setup(m => m.getConnectedDevices())
.returns(() => expectedDevices)
.verifiable(Times.once());
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock.setup(m => m.setDeviceId(deviceId)).verifiable(Times.once());
adbMock
.setup(m => m.getModel())
.returns(() => expectedModels[modelIndex++])
.verifiable(Times.exactly(2));
const devices = await testSubject.getConnectedDevices();
expect(devices.length).toBe(2);
expect(devices[0].id).toBe(emulatorId);
expect(devices[0].isEmulator).toBe(true);
expect(devices[0].friendlyName).toBe(emulatorModel);
expect(devices[1].id).toBe(deviceId);
expect(devices[1].isEmulator).toBe(false);
expect(devices[1].friendlyName).toBe(deviceModel);
adbMock.verifyAll();
});
it('getPackageInfo, propagates error', async () => {
const expectedMessage = 'Thrown during getPackageInfo';
adbMock
.setup(m => m.setDeviceId(emulatorId))
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(testSubject.getPackageInfo(emulatorId, testPackageName)).rejects.toThrowError(
expectedMessage,
);
adbMock.verifyAll();
});
it('getPackageInfo, contains neither versionName nor versionCode', async () => {
const expectedPackageInfo: PackageInfo = {};
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.getPackageInfo(testPackageName))
.returns(() => expectedPackageInfo)
.verifiable(Times.once());
const info = await testSubject.getPackageInfo(emulatorId, testPackageName);
expect(info.versionCode).toBeUndefined();
expect(info.versionName).toBeUndefined();
adbMock.verifyAll();
});
it('getPackageInfo, contains only versionName', async () => {
const versionName: string = 'my version';
const expectedPackageInfo: PackageInfo = { versionName };
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.getPackageInfo(testPackageName))
.returns(() => expectedPackageInfo)
.verifiable(Times.once());
const info = await testSubject.getPackageInfo(emulatorId, testPackageName);
expect(info.versionCode).toBeUndefined();
expect(info.versionName).toBe(versionName);
adbMock.verifyAll();
});
it('getPackageInfo, contains only versionCode', async () => {
const versionCode: number = 12345;
const expectedPackageInfo: PackageInfo = { versionCode };
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.getPackageInfo(testPackageName))
.returns(() => expectedPackageInfo)
.verifiable(Times.once());
const info = await testSubject.getPackageInfo(emulatorId, testPackageName);
expect(info.versionCode).toBe(versionCode);
expect(info.versionName).toBeUndefined();
adbMock.verifyAll();
});
it('getDumpsysOutput, propagates error', async () => {
const expectedMessage = 'Thrown during getDumpsysOutput';
adbMock
.setup(m => m.setDeviceId(emulatorId))
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(
testSubject.getDumpsysOutput(emulatorId, testDumpsysService),
).rejects.toThrowError(expectedMessage);
adbMock.verifyAll();
});
it('getDumpsysOutput, returns output', async () => {
const expectedDumpsysOutput: String = 'Mary had a little lamb';
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.shell(['dumpsys', testDumpsysService]))
.returns(() => expectedDumpsysOutput)
.verifiable(Times.once());
const output = await testSubject.getDumpsysOutput(emulatorId, testDumpsysService);
expect(output).toBe(expectedDumpsysOutput);
adbMock.verifyAll();
});
it('installService, propagates error', async () => {
const expectedMessage: string = 'Thrown during installService';
adbMock
.setup(m => m.setDeviceId(emulatorId))
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(testSubject.installService(emulatorId, testPackageName)).rejects.toThrowError(
expectedMessage,
);
adbMock.verifyAll();
});
it('installService, succeeds', async () => {
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.install(expectedPathToApk))
.returns(() => '')
.verifiable(Times.once());
await testSubject.installService(emulatorId, expectedPathToApk);
adbMock.verifyAll();
});
it('uninstallService, propagates error', async () => {
const expectedMessage: string = 'Thrown during uninstallService';
adbMock
.setup(m => m.setDeviceId(emulatorId))
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(
testSubject.uninstallService(emulatorId, testPackageName),
).rejects.toThrowError(expectedMessage);
adbMock.verifyAll();
});
it('uninstallService, succeeds', async () => {
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.uninstallApk(testPackageName))
.returns(() => '')
.verifiable(Times.once());
await testSubject.uninstallService(emulatorId, testPackageName);
adbMock.verifyAll();
});
it('readContent, succeeds', async () => {
const testContentType = 'config';
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m =>
m.shell(['content', 'read', '--uri', `${testContentUri}/${testContentType}`]),
)
.returns(() => testConfig.toString())
.verifiable(Times.once());
const config = await testSubject.readContent(
emulatorId,
`${testContentUri}/${testContentType}`,
);
expect(config).toBe(testConfig.toString());
adbMock.verifyAll();
});
it('readContent, propagates error', async () => {
const testContentType = 'config';
const expectedErrorMsg: string = 'Thrown during readContent';
adbMock
.setup(m => m.setDeviceId(emulatorId))
.throws(new Error(expectedErrorMsg))
.verifiable(Times.once());
await expect(
testSubject.readContent(emulatorId, `${testPackageName}/${testContentType}`),
).rejects.toThrowError(expectedErrorMsg);
adbMock.verifyAll();
});
it('callContent, succeeds', async () => {
const testCommand = 'DO_SOMETHING';
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m =>
m.shell(['content', 'call', '--uri', `${testContentUri}`, '--method', testCommand]),
)
.returns(() => Promise.resolve())
.verifiable(Times.once());
await testSubject.callContent(emulatorId, `${testContentUri}`, testCommand);
adbMock.verifyAll();
});
it('callContent, propagates error', async () => {
const testCommand = 'DO_SOMETHING';
const expectedErrorMsg: string = 'Thrown during callContent';
adbMock
.setup(m => m.setDeviceId(emulatorId))
.throws(new Error(expectedErrorMsg))
.verifiable(Times.once());
await expect(
testSubject.callContent(emulatorId, testContentUri, testCommand),
).rejects.toThrowError(expectedErrorMsg);
adbMock.verifyAll();
});
it('sendKeyEvent, propagates error', async () => {
const expectedMessage: string = 'Thrown during sendKeyEvent';
const keyEventCode: KeyEventCode = KeyEventCode.Tab;
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.shell(['input', 'keyevent', keyEventCode]))
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(testSubject.sendKeyEvent(emulatorId, keyEventCode)).rejects.toThrowError(
expectedMessage,
);
adbMock.verifyAll();
});
describe('sendKeyEvent, succeeds', () => {
test.each([
KeyEventCode.Up,
KeyEventCode.Down,
KeyEventCode.Left,
KeyEventCode.Right,
KeyEventCode.Enter,
KeyEventCode.Tab,
])('sendKeyEvent sending %p', async (keyEventCode: KeyEventCode) => {
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.shell(['input', 'keyevent', keyEventCode]))
.verifiable(Times.once());
await testSubject.sendKeyEvent(emulatorId, keyEventCode);
adbMock.verifyAll();
});
});
it('hasPermission, returns true if matchString is in dumpsys output', async () => {
const checkPermissionCommand = `dumpsys my_permission`;
const permissionIndicator = 'MY_PERMISSION="granted"';
const permissionSuccessOutput = `hooray yes ${permissionIndicator}`;
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.exactly(1));
adbMock
.setup(m => m.shell(checkPermissionCommand.split(/\s+/)))
.returns(() => Promise.resolve(permissionSuccessOutput))
.verifiable(Times.once());
const hasPermission = await testSubject.hasPermission(
emulatorId,
'my_permission',
permissionIndicator,
);
expect(hasPermission).toEqual(true);
adbMock.verifyAll();
});
it('hasPermission, returns false if matchString is not in dumpsys output', async () => {
const checkPermissionCommand = `dumpsys my_permission`;
const permissionIndicator = 'MY_PERMISSION="granted"';
const permissionFailOutput = `indicator NOT present!`;
adbMock
.setup(m => m.setDeviceId(emulatorId))
.verifiable(Times.exactly(1), ExpectedCallType.InSequence);
adbMock
.setup(m => m.shell(checkPermissionCommand.split(/\s+/)))
.returns(() => Promise.resolve(permissionFailOutput))
.verifiable(Times.once());
const hasPermission = await testSubject.hasPermission(
emulatorId,
'my_permission',
permissionIndicator,
);
expect(hasPermission).toEqual(false);
adbMock.verifyAll();
});
it('hasPermission, propagates errors from dumpsys output', async () => {
const permissionIndicator = 'MY_PERMISSION="granted"';
const errorMessage = `error thrown in dumpsys!`;
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.exactly(1));
adbMock
.setup(m => m.shell(['dumpsys', 'my_permission']))
.throws(new Error(errorMessage))
.verifiable(Times.once());
await expect(
testSubject.hasPermission(emulatorId, 'my_permission', permissionIndicator),
).rejects.toThrowError(errorMessage);
adbMock.verifyAll();
});
it('grantPermission, calls expected adb commands', async () => {
const resetCommand = `cmd appops reset ${testPackageName}`;
const testPermission = 'android.permission.SYSTEM_ALERT_WINDOW';
const grantCommand = `pm grant ${testPackageName} ${testPermission}`;
adbMock
.setup(m => m.setDeviceId(emulatorId))
.verifiable(Times.once(), ExpectedCallType.InSequence);
adbMock
.setup(m => m.shell(resetCommand.split(/\s+/)))
.verifiable(Times.once(), ExpectedCallType.InSequence);
adbMock
.setup(m => m.shell(grantCommand.split(/\s+/)))
.verifiable(Times.once(), ExpectedCallType.InSequence);
await testSubject.grantPermission(emulatorId, testPackageName, testPermission);
adbMock.verifyAll();
});
it('grantPermission, propagates error', async () => {
const expectedMessage: string = 'Thrown during grantPermission';
adbMock.setup(m => m.setDeviceId(emulatorId)).verifiable(Times.once());
adbMock
.setup(m => m.shell(It.isAny()))
.throws(new Error(expectedMessage))
.verifiable(Times.once());
await expect(
testSubject.grantPermission(emulatorId, testPackageName, 'testPermission'),
).rejects.toThrowError(expectedMessage);
adbMock.verifyAll();
});
/*
// For live testing, set ANDROID_HOME or ANDROID_SDK_ROOT to point
// to your local installation, then add this line just before
// calling the testSubject:
//
// await setLiveTestSubject();
//
// You'll also need to change the device ID to match your actual device
async function setLiveTestSubject(): Promise<void> {
const adb: ADB = await ADB.createADB();
testSubject = new AppiumServiceConfigurator(adb);
adbMock = Mock.ofType<ADB>(undefined, MockBehavior.Strict);
}
*/
}); | the_stack |
import ethers, {
constants,
Wallet,
utils,
BigNumber,
Transaction,
} from 'ethers';
import { latency, bigNumberWithDecimalToStr } from '../../services/base';
import {
HttpException,
OUT_OF_GAS_ERROR_CODE,
OUT_OF_GAS_ERROR_MESSAGE,
LOAD_WALLET_ERROR_CODE,
LOAD_WALLET_ERROR_MESSAGE,
TOKEN_NOT_SUPPORTED_ERROR_CODE,
TOKEN_NOT_SUPPORTED_ERROR_MESSAGE,
} from '../../services/error-handler';
import { tokenValueToString } from '../../services/base';
import { TokenInfo } from '../../services/ethereum-base';
import {
PollRequest,
PollResponse,
CustomTransactionReceipt,
CustomTransaction,
CustomTransactionResponse,
} from './ethereum.requests';
import { Ethereumish } from '../../services/common-interfaces';
import {
NonceRequest,
NonceResponse,
AllowancesRequest,
AllowancesResponse,
ApproveRequest,
ApproveResponse,
CancelRequest,
CancelResponse,
} from '../../evm/evm.requests';
import {
BalanceRequest,
BalanceResponse,
} from '../../network/network.requests';
import { logger } from '../../services/logger';
export async function nonce(
ethereum: Ethereumish,
req: NonceRequest
): Promise<NonceResponse> {
// get the address via the public key since we generally use the public
// key to interact with gateway and the address is not part of the user config
const wallet = await ethereum.getWallet(req.address);
const nonce = await ethereum.nonceManager.getNonce(wallet.address);
return { nonce };
}
export const getTokenSymbolsToTokens = (
ethereum: Ethereumish,
tokenSymbols: Array<string>
): Record<string, TokenInfo> => {
const tokens: Record<string, TokenInfo> = {};
for (let i = 0; i < tokenSymbols.length; i++) {
const symbol = tokenSymbols[i];
const token = ethereum.getTokenBySymbol(symbol);
if (token) tokens[symbol] = token;
}
return tokens;
};
export async function allowances(
ethereumish: Ethereumish,
req: AllowancesRequest
): Promise<AllowancesResponse | string> {
const initTime = Date.now();
const wallet = await ethereumish.getWallet(req.address);
const tokens = getTokenSymbolsToTokens(ethereumish, req.tokenSymbols);
const spender = ethereumish.getSpender(req.spender);
const approvals: Record<string, string> = {};
await Promise.all(
Object.keys(tokens).map(async (symbol) => {
// instantiate a contract and pass in provider for read-only access
const contract = ethereumish.getContract(
tokens[symbol].address,
ethereumish.provider
);
approvals[symbol] = tokenValueToString(
await ethereumish.getERC20Allowance(
contract,
wallet,
spender,
tokens[symbol].decimals
)
);
})
);
return {
network: ethereumish.chain,
timestamp: initTime,
latency: latency(initTime, Date.now()),
spender: spender,
approvals: approvals,
};
}
export async function balances(
ethereumish: Ethereumish,
req: BalanceRequest
): Promise<BalanceResponse | string> {
const initTime = Date.now();
let wallet: Wallet;
try {
wallet = await ethereumish.getWallet(req.address);
} catch (err) {
throw new HttpException(
500,
LOAD_WALLET_ERROR_MESSAGE + err,
LOAD_WALLET_ERROR_CODE
);
}
const tokens = getTokenSymbolsToTokens(ethereumish, req.tokenSymbols);
const balances: Record<string, string> = {};
if (req.tokenSymbols.includes(ethereumish.nativeTokenSymbol)) {
balances[ethereumish.nativeTokenSymbol] = tokenValueToString(
await ethereumish.getNativeBalance(wallet)
);
}
await Promise.all(
Object.keys(tokens).map(async (symbol) => {
if (tokens[symbol] !== undefined) {
const address = tokens[symbol].address;
const decimals = tokens[symbol].decimals;
// instantiate a contract and pass in provider for read-only access
const contract = ethereumish.getContract(address, ethereumish.provider);
const balance = await ethereumish.getERC20Balance(
contract,
wallet,
decimals
);
balances[symbol] = tokenValueToString(balance);
}
})
);
if (!Object.keys(balances).length) {
throw new HttpException(
500,
TOKEN_NOT_SUPPORTED_ERROR_MESSAGE,
TOKEN_NOT_SUPPORTED_ERROR_CODE
);
}
return {
network: ethereumish.chain,
timestamp: initTime,
latency: latency(initTime, Date.now()),
balances: balances,
};
}
const toEthereumTransaction = (transaction: Transaction): CustomTransaction => {
let maxFeePerGas = null;
if (transaction.maxFeePerGas) {
maxFeePerGas = transaction.maxFeePerGas.toString();
}
let maxPriorityFeePerGas = null;
if (transaction.maxPriorityFeePerGas) {
maxPriorityFeePerGas = transaction.maxPriorityFeePerGas.toString();
}
let gasLimit = null;
if (transaction.gasLimit) {
gasLimit = transaction.gasLimit.toString();
}
return {
...transaction,
maxPriorityFeePerGas,
maxFeePerGas,
gasLimit,
value: transaction.value.toString(),
};
};
export async function approve(
ethereumish: Ethereumish,
req: ApproveRequest
): Promise<ApproveResponse | string> {
const { amount, nonce, address, token, maxFeePerGas, maxPriorityFeePerGas } =
req;
const spender = ethereumish.getSpender(req.spender);
const initTime = Date.now();
let wallet: Wallet;
try {
wallet = await ethereumish.getWallet(address);
} catch (err) {
throw new HttpException(
500,
LOAD_WALLET_ERROR_MESSAGE + err,
LOAD_WALLET_ERROR_CODE
);
}
const fullToken = ethereumish.getTokenBySymbol(token);
if (!fullToken) {
throw new HttpException(
500,
TOKEN_NOT_SUPPORTED_ERROR_MESSAGE + token,
TOKEN_NOT_SUPPORTED_ERROR_CODE
);
}
const amountBigNumber = amount
? utils.parseUnits(amount, fullToken.decimals)
: constants.MaxUint256;
let maxFeePerGasBigNumber;
if (maxFeePerGas) {
maxFeePerGasBigNumber = BigNumber.from(maxFeePerGas);
}
let maxPriorityFeePerGasBigNumber;
if (maxPriorityFeePerGas) {
maxPriorityFeePerGasBigNumber = BigNumber.from(maxPriorityFeePerGas);
}
// instantiate a contract and pass in wallet, which act on behalf of that signer
const contract = ethereumish.getContract(fullToken.address, wallet);
// convert strings to BigNumber
// call approve function
const approval = await ethereumish.approveERC20(
contract,
wallet,
spender,
amountBigNumber,
nonce,
maxFeePerGasBigNumber,
maxPriorityFeePerGasBigNumber,
ethereumish.gasPrice
);
if (approval.hash) {
await ethereumish.txStorage.saveTx(
ethereumish.chain,
ethereumish.chainId,
approval.hash,
new Date(),
ethereumish.gasPrice
);
}
return {
network: ethereumish.chain,
timestamp: initTime,
latency: latency(initTime, Date.now()),
tokenAddress: fullToken.address,
spender: spender,
amount: bigNumberWithDecimalToStr(amountBigNumber, fullToken.decimals),
nonce: approval.nonce,
approval: toEthereumTransaction(approval),
};
}
// TransactionReceipt from ethers uses BigNumber which is not easy to interpret directly from JSON.
// Transform those BigNumbers to string and pass the rest of the data without changes.
const toEthereumTransactionReceipt = (
receipt: ethers.providers.TransactionReceipt | null
): CustomTransactionReceipt | null => {
if (receipt) {
let effectiveGasPrice = null;
if (receipt.effectiveGasPrice) {
effectiveGasPrice = receipt.effectiveGasPrice.toString();
}
return {
...receipt,
gasUsed: receipt.gasUsed.toString(),
cumulativeGasUsed: receipt.cumulativeGasUsed.toString(),
effectiveGasPrice,
};
}
return null;
};
const toEthereumTransactionResponse = (
response: ethers.providers.TransactionResponse | null
): CustomTransactionResponse | null => {
if (response) {
let gasPrice = null;
if (response.gasPrice) {
gasPrice = response.gasPrice.toString();
}
return {
...response,
gasPrice,
gasLimit: response.gasLimit.toString(),
value: response.value.toString(),
};
}
return null;
};
export function willTxSucceed(
txDuration: number,
txDurationLimit: number,
txGasPrice: number,
currentGasPrice: number
): boolean {
if (txDuration > txDurationLimit && currentGasPrice > txGasPrice) {
return false;
}
return true;
}
// txStatus
// -1: not in the mempool or failed
// 1: succeeded
// 2: in the mempool and likely to succeed
// 3: in the mempool and likely to fail
// 0: in the mempool but we dont have data to guess its status
export async function poll(
ethereumish: Ethereumish,
req: PollRequest
): Promise<PollResponse> {
const initTime = Date.now();
const currentBlock = await ethereumish.getCurrentBlockNumber();
const txData = await ethereumish.getTransaction(req.txHash);
let txBlock, txReceipt, txStatus;
if (!txData) {
// tx not found, didn't reach the mempool or it never existed
txBlock = -1;
txReceipt = null;
txStatus = -1;
} else {
txReceipt = await ethereumish.getTransactionReceipt(req.txHash);
if (txReceipt === null) {
// tx is in the mempool
txBlock = -1;
txReceipt = null;
txStatus = 0;
const transactions = await ethereumish.txStorage.getTxs(
ethereumish.chain,
ethereumish.chainId
);
if (transactions[txData.hash]) {
const data: [Date, number] = transactions[txData.hash];
const now = new Date();
const txDuration = Math.abs(now.getTime() - data[0].getTime());
if (
willTxSucceed(txDuration, 60000 * 3, data[1], ethereumish.gasPrice)
) {
txStatus = 2;
} else {
txStatus = 3;
}
}
} else {
// tx has been processed
txBlock = txReceipt.blockNumber;
txStatus = typeof txReceipt.status === 'number' ? 1 : -1;
if (txReceipt.status === 0) {
const gasUsed = BigNumber.from(txReceipt.gasUsed).toNumber();
const gasLimit = BigNumber.from(txData.gasLimit).toNumber();
if (gasUsed / gasLimit > 0.9) {
throw new HttpException(
503,
OUT_OF_GAS_ERROR_MESSAGE,
OUT_OF_GAS_ERROR_CODE
);
}
}
}
}
logger.info(
`Poll ${ethereumish.chain}, txHash ${req.txHash}, status ${txStatus}.`
);
return {
network: ethereumish.chain,
currentBlock,
timestamp: initTime,
txHash: req.txHash,
txBlock,
txStatus,
txData: toEthereumTransactionResponse(txData),
txReceipt: toEthereumTransactionReceipt(txReceipt),
};
}
export async function cancel(
ethereumish: Ethereumish,
req: CancelRequest
): Promise<CancelResponse> {
const initTime = Date.now();
let wallet: Wallet;
try {
wallet = await ethereumish.getWallet(req.address);
} catch (err) {
throw new HttpException(
500,
LOAD_WALLET_ERROR_MESSAGE + err,
LOAD_WALLET_ERROR_CODE
);
}
// call cancelTx function
const cancelTx = await ethereumish.cancelTx(wallet, req.nonce);
logger.info(
`Cancelled transaction at nonce ${req.nonce}, cancel txHash ${cancelTx.hash}.`
);
return {
network: ethereumish.chain,
timestamp: initTime,
latency: latency(initTime, Date.now()),
txHash: cancelTx.hash,
};
} | the_stack |
import {
initState,
reducer,
distribute,
getActionPlan,
predictOptimisticState,
updateAllProgress,
getNextAppOp,
} from "./logic";
import { runAll, runOneAppOp } from "./runner";
import {
deviceInfo155,
mockListAppsResult,
mockExecWithInstalledContext,
} from "./mock";
import { prettyActionPlan, prettyInstalled } from "./formatting";
import { setEnv } from "../env";
import { Action } from "./types";
setEnv("MANAGER_INSTALL_DELAY", 0);
const scenarios = [
{
name: "wipe installed apps",
apps: "Bitcoin, Ethereum, Litecoin, Dogecoin, Ethereum Classic, XRP",
installed: "Bitcoin, Litecoin, XRP, Ethereum Classic, Ethereum",
actions: [
{
dispatch: {
type: "wipe",
},
expectPlan: "-Litecoin, -Bitcoin, -XRP, -Ethereum Classic, -Ethereum",
expectInstalled: "",
},
],
},
{
name: "install an app install its dep",
apps: "Bitcoin, Litecoin, Dogecoin",
installed: "",
actions: [
{
dispatch: {
type: "install",
name: "Dogecoin",
},
expectPlan: "+Bitcoin, +Dogecoin",
expectInstalled: "Bitcoin, Dogecoin",
},
{
dispatch: {
type: "install",
name: "Litecoin",
},
expectPlan: "+Litecoin",
expectInstalled: "Bitcoin, Dogecoin, Litecoin",
},
],
},
{
name: "install and uninstall an app",
apps: "XRP",
installed: "",
actions: [
{
dispatch: {
type: "install",
name: "XRP",
},
expectPlan: "+XRP",
expectInstalled: "XRP",
},
{
dispatch: {
type: "uninstall",
name: "XRP",
},
expectPlan: "-XRP",
expectInstalled: "",
},
],
},
{
name: "install an app install its dep",
apps: "Bitcoin, Litecoin, Dogecoin",
installed: "",
actions: [
{
dispatch: {
type: "install",
name: "Dogecoin",
},
expectPlan: "+Bitcoin, +Dogecoin",
expectInstalled: "Bitcoin, Dogecoin",
},
{
dispatch: {
type: "install",
name: "Litecoin",
},
expectPlan: "+Litecoin",
expectInstalled: "Bitcoin, Dogecoin, Litecoin",
},
],
},
{
name: "uninstall an app that have deps",
apps: "Bitcoin, Litecoin, Dogecoin",
installed: "Bitcoin, Litecoin, Dogecoin",
actions: [
{
dispatch: {
type: "uninstall",
name: "Bitcoin",
},
expectPlan: "-Litecoin, -Dogecoin, -Bitcoin",
expectInstalled: "",
},
],
},
{
name: "install existing is noop",
apps: "Bitcoin",
installed: "Bitcoin",
actions: [
{
dispatch: {
type: "install",
name: "Bitcoin",
},
expectPlan: "",
expectInstalled: "Bitcoin",
},
],
},
{
name: "uninstall non-existing is noop",
apps: "Bitcoin",
installed: "",
actions: [
{
dispatch: {
type: "uninstall",
name: "Bitcoin",
},
expectPlan: "",
expectInstalled: "",
},
],
},
{
name: "install an outdated app",
apps: "Bitcoin",
installed: "Bitcoin (outdated)",
actions: [
{
dispatch: {
type: "install",
name: "Bitcoin",
},
expectPlan: "-Bitcoin, +Bitcoin",
expectInstalled: "Bitcoin",
},
],
},
{
name: "install an outdated app dep",
apps: "Bitcoin, Dogecoin",
installed: "Bitcoin (outdated), Dogecoin (outdated)",
actions: [
{
dispatch: {
type: "install",
name: "Dogecoin",
},
expectPlan: "-Dogecoin, -Bitcoin, +Bitcoin, +Dogecoin",
expectInstalled: "Bitcoin, Dogecoin",
},
],
},
{
name: "install an app with outdated dep",
apps: "Bitcoin, Litecoin, Dogecoin",
installed: "Bitcoin (outdated), Litecoin (outdated)",
actions: [
{
dispatch: {
type: "install",
name: "Dogecoin",
},
expectPlan: "-Litecoin, -Bitcoin, +Bitcoin, +Litecoin, +Dogecoin",
expectInstalled: "Bitcoin, Litecoin, Dogecoin",
},
],
},
{
name: "install an outdated app with dependents",
apps: "Bitcoin, Dogecoin",
installed: "Bitcoin (outdated), Dogecoin (outdated)",
actions: [
{
dispatch: {
type: "install",
name: "Bitcoin",
},
expectPlan: "-Dogecoin, -Bitcoin, +Bitcoin, +Dogecoin",
expectInstalled: "Bitcoin, Dogecoin",
},
],
},
{
name: "update all will reinstall the outdated",
apps: "Bitcoin, Litecoin, Ethereum",
installed: "Bitcoin (outdated), Litecoin (outdated), Ethereum",
actions: [
{
dispatch: {
type: "updateAll",
},
expectPlan: "-Litecoin, -Bitcoin, +Bitcoin, +Litecoin",
expectInstalled: "Ethereum, Bitcoin, Litecoin",
},
],
},
{
name: "update all still works with unknown apps",
apps: "Bitcoin, Litecoin, Ethereum",
installed: "Bitcoin (outdated), Litecoin (outdated), Ethereum, Unknown",
actions: [
{
dispatch: {
type: "updateAll",
},
expectPlan: "-Litecoin, -Bitcoin, +Bitcoin, +Litecoin",
expectInstalled: "Ethereum, Unknown, Bitcoin, Litecoin",
},
],
},
{
name: "install and uninstall will undo (if top level dep)",
apps: "Bitcoin",
installed: "",
actions: [
{
dispatch: [
{
type: "install",
name: "Bitcoin",
},
{
type: "uninstall",
name: "Bitcoin",
},
],
expectPlan: "",
expectInstalled: "",
},
],
},
{
name: "order is preserved in install action plan",
apps: "Bitcoin, XRP, Ethereum, Ethereum Classic, Dogecoin, Zcash",
installed: "",
actions: [
{
dispatch: [
{
type: "install",
name: "XRP",
},
{
type: "install",
name: "Ethereum Classic",
},
{
type: "install",
name: "Dogecoin",
},
{
type: "install",
name: "Zcash",
},
],
expectPlan:
"+XRP, +Ethereum, +Ethereum Classic, +Bitcoin, +Dogecoin, +Zcash",
expectInstalled:
"XRP, Ethereum, Ethereum Classic, Bitcoin, Dogecoin, Zcash",
},
],
},
{
name: "order is preserved in uninstall action plan",
apps: "Bitcoin, XRP, Ethereum, Ethereum Classic, Dogecoin, Zcash",
installed: "XRP, Ethereum, Ethereum Classic, Bitcoin, Dogecoin, Zcash",
actions: [
{
dispatch: [
{
type: "uninstall",
name: "XRP",
},
{
type: "uninstall",
name: "Ethereum",
},
{
type: "uninstall",
name: "Dogecoin",
},
{
type: "uninstall",
name: "Bitcoin",
},
],
expectPlan:
"-XRP, -Ethereum Classic, -Ethereum, -Dogecoin, -Zcash, -Bitcoin",
expectInstalled: "",
},
],
},
];
scenarios.forEach((scenario) => {
test("Scenario: " + scenario.name, async () => {
let state = initState(
mockListAppsResult(scenario.apps, scenario.installed, deviceInfo155)
);
expect(prettyActionPlan(getActionPlan(state))).toBe("");
for (const action of scenario.actions) {
state = (<any[]>[]).concat(action.dispatch).reduce(reducer, state);
expect(prettyActionPlan(getActionPlan(state))).toBe(action.expectPlan);
const optimisticState = predictOptimisticState(state);
state = await runAll(
state,
mockExecWithInstalledContext(state.installed)
).toPromise();
if (action.expectInstalled) {
expect(prettyInstalled(state.installed)).toBe(action.expectInstalled);
}
state.currentProgressSubject = null;
expect(state).toEqual(optimisticState);
expect(prettyActionPlan(getActionPlan(state))).toBe("");
const d: any = distribute(state);
d.apps = d.apps.map(({ currency, ...rest }) => ({
...rest,
currencyId: currency && currency.id,
}));
expect(d).toMatchSnapshot();
}
});
});
test("appsToRestore", async () => {
const state = initState(
mockListAppsResult(
"Bitcoin, XRP, Ethereum, Ethereum Classic, Dogecoin, Zcash",
"Bitcoin, Zcash",
deviceInfo155
),
["Bitcoin", "XRP", "Dogecoin", "Zcash", "Ethereum Classic"]
);
expect(prettyActionPlan(getActionPlan(state))).toBe(
"+XRP, +Dogecoin, +Ethereum, +Ethereum Classic"
);
});
/*
test("a lock error that occurs will not cancel the queue, another error will", () => {
let state = initState(
mockListAppsResult(
"Bitcoin, XRP, Ethereum, Ethereum Classic, Dogecoin, Zcash",
"",
deviceInfo155
)
);
state = [
{ type: "install", name: "Dogecoin" },
{ type: "install", name: "Ethereum Classic" }
].reduce(reducer, state);
const plan = getActionPlan(state);
state = reducer(state, {
type: "onRunnerEvent",
event: {
type: "runError",
appOp: plan[0],
error: new ManagerDeviceLockedError()
}
});
expect(getActionPlan(state)).toEqual(plan);
expect(state.currentError).toEqual({
appOp: plan[0],
error: new ManagerDeviceLockedError()
});
state = reducer(state, { type: "recover" });
expect(state.currentError).toBe(null);
state = reducer(state, {
type: "onRunnerEvent",
event: {
type: "runError",
appOp: plan[0],
error: new Error()
}
});
expect(getActionPlan(state)).toEqual([]);
});
*/
test("global progress", async () => {
let state = initState(
mockListAppsResult(
"Bitcoin, XRP, Ethereum, Ethereum Classic, Dogecoin, Zcash",
"Bitcoin (outdated), Ethereum (outdated)",
deviceInfo155
)
);
expect(updateAllProgress(state)).toBe(1);
state = [
<Action>{
type: "updateAll",
},
].reduce(reducer, state);
expect(updateAllProgress(state)).toBe(0);
let next;
let i = 0;
const total = 4;
while ((next = getNextAppOp(state))) {
state = await runOneAppOp(
state,
next,
mockExecWithInstalledContext(state.installed)
).toPromise();
expect(updateAllProgress(state)).toBe(++i / total);
}
expect(i).toBe(total);
expect(updateAllProgress(state)).toBe(1);
}); | the_stack |
"use strict"
import * as maptalks from 'maptalks';
import * as THREE from 'three';
import { BaseObjectOptionType } from './type/BaseOption';
import Line2 from './util/fatline/Line2';
const OPTIONS = {
interactive: true,
altitude: 0,
minZoom: 0,
maxZoom: 30,
asynchronous: false
};
/**
* a Class for Eventable
*/
function Base() {
}
// class Base {
// constructor() {
// }
// }
/**
* EVENTS=[
* 'add',
* 'remove',
'mousemove',
'click',
'mousedown',
'mouseup',
'dblclick',
'contextmenu',
'touchstart',
'touchmove',
'touchend',
'mouseover',
'mouseout',
'idchange',
'propertieschange',
'show',
'hide',
'symbolchange'
empty
];
* This is the base class for all 3D objects
*
*
* Its function and maptalks.geometry are as similar as possible
*
* maptalks.Eventable(Base) return a Class https://github.com/maptalks/maptalks.js/blob/master/src/core/Eventable.js
*
*/
class BaseObject extends maptalks.Eventable(Base) {
isAdd: boolean = false;
object3d: THREE.Object3D;
options: BaseObjectOptionType;
toolTip: maptalks.ui.ToolTip;
infoWindow: maptalks.ui.InfoWindow;
_mouseover: boolean = false;
_showPlayer: any;
_visible: boolean = true;
_zoomVisible: boolean = true;
_vt: any;
picked: boolean = false;
pickObject3d: THREE.Object3D;
id: string | number;
type: string;
_baseObjects: BaseObject[];
readonly isBaseObject: boolean = true;
constructor(id?: string | number) {
super();
if (id === undefined) {
id = maptalks.Util.GUID();
}
this.id = id;
}
addTo(layer: any) {
if (layer && layer.type === 'ThreeLayer') {
layer.addMesh([this]);
} else {
console.error('layer only support maptalks.ThreeLayer');
}
return this;
}
remove() {
const layer = this.getLayer();
if (layer) {
layer.removeMesh([this]);
}
return this;
}
getObject3d(): THREE.Object3D {
return this.object3d;
}
getId(): string | number {
return this.id;
}
setId(id: string | number) {
const oldId = this.getId();
this.id = id;
this._fire('idchange', {
'old': oldId,
'new': id,
'target': this
});
return this;
}
getType(): string {
return this.type;
}
getOptions(): BaseObjectOptionType {
return this.options;
}
getProperties(): object {
return (this.options || {}).properties;
}
setProperties(property: object) {
const old = Object.assign({}, this.getProperties());
this.options.properties = property;
this._fire('propertieschange', {
'old': old,
'new': property,
'target': this
});
return this;
}
getLayer() {
return this.options.layer;
}
// eslint-disable-next-line consistent-return
getMap(): maptalks.Map {
const layer = this.getLayer();
if (layer) {
return layer.getMap();
}
}
// eslint-disable-next-line consistent-return
getCenter(): maptalks.Coordinate {
const options = this.getOptions();
const { coordinate, lineString, polygon } = options;
if (coordinate) {
return coordinate instanceof maptalks.Coordinate ? coordinate : new maptalks.Coordinate(coordinate);
} else {
const geometry = polygon || lineString;
if (geometry && geometry.getCenter) {
return geometry.getCenter();
}
}
}
getAltitude(): number {
return this.getOptions().altitude;
}
/**
* Different objects need to implement their own methods
* @param {*} altitude
*/
setAltitude(altitude: number) {
if (maptalks.Util.isNumber(altitude)) {
const z = this.getLayer().distanceToVector3(altitude, altitude).x;
this.getObject3d().position.z = z;
this.options.altitude = altitude;
if (this.pickObject3d) {
this.pickObject3d.position.z = z;
}
//fix merged mesh
if (this._baseObjects && Array.isArray(this._baseObjects)) {
for (let i = 0, len = this._baseObjects.length; i < len; i++) {
if (this._baseObjects[i]) {
this._baseObjects[i].getObject3d().position.z = z;
}
}
}
}
return this;
}
show() {
// in zoom range
if (this._zoomVisible) {
this.getObject3d().visible = true;
this._fire('show');
}
this._visible = true;
return this;
}
hide() {
this.getObject3d().visible = false;
this._fire('hide');
this._visible = false;
return this;
}
isVisible(): boolean {
return (!!this.getObject3d().visible);
}
/**
* Different objects need to implement their own methods
*/
getSymbol(): THREE.Material {
return (this.getObject3d() as any).material;
}
/**
* Different objects need to implement their own methods
* @param {*} material
*/
setSymbol(material: THREE.Material) {
if (material && material instanceof THREE.Material) {
material.needsUpdate = true;
material.vertexColors = (this.getObject3d() as any).material.vertexColors;
const old = (this.getObject3d() as any).material.clone();
(this.getObject3d() as any).material = material;
this._fire('symbolchange', {
'old': old,
'new': material,
'target': this
});
}
return this;
}
setInfoWindow(options: object) {
this.removeInfoWindow();
this.infoWindow = new maptalks.ui.InfoWindow(options);
this.infoWindow.addTo(this);
return this;
}
getInfoWindow(): maptalks.ui.InfoWindow {
return this.infoWindow;
}
openInfoWindow(coordinate: maptalks.Coordinate) {
coordinate = coordinate || this.getCenter();
if (!(coordinate instanceof maptalks.Coordinate)) {
coordinate = new maptalks.Coordinate(coordinate);
}
// eslint-disable-next-line no-unused-expressions
(coordinate && this.infoWindow && this.infoWindow.show(coordinate));
return this;
}
closeInfoWindow() {
// eslint-disable-next-line no-unused-expressions
(this.infoWindow && this.infoWindow.hide());
return this;
}
removeInfoWindow() {
// eslint-disable-next-line no-unused-expressions
if (this.infoWindow) {
this.infoWindow.remove();
delete this.infoWindow;
}
return this;
}
setToolTip(content: string, options: object) {
this.removeToolTip();
this.toolTip = new maptalks.ui.ToolTip(content, options);
this.toolTip.addTo(this);
return this;
}
getToolTip(): maptalks.ui.ToolTip {
return this.toolTip;
}
openToolTip(coordinate: maptalks.Coordinate) {
coordinate = coordinate || this.getCenter();
if (!(coordinate instanceof maptalks.Coordinate)) {
coordinate = new maptalks.Coordinate(coordinate);
}
// eslint-disable-next-line no-unused-expressions
(coordinate && this.toolTip && this.toolTip.show(coordinate));
return this;
}
closeToolTip() {
// eslint-disable-next-line no-unused-expressions
(this.toolTip && this.toolTip.hide());
return this;
}
removeToolTip() {
// eslint-disable-next-line no-unused-expressions
if (this.toolTip) {
this.toolTip.remove();
delete this.toolTip;
}
return this;
}
/**
* different components should implement their own animation methods
* @param {*} options
* @param {*} cb
*/
// eslint-disable-next-line no-unused-vars
animateShow(options: object = {}, cb: Function) {
if (this._showPlayer) {
this._showPlayer.cancel();
}
if (maptalks.Util.isFunction(options)) {
options = {};
cb = options as Function;
}
const duration = options['duration'] || 1000,
easing = options['easing'] || 'out';
const player = this._showPlayer = maptalks.animation.Animation.animate({
'scale': 1
}, {
'duration': duration,
'easing': easing
}, frame => {
const scale = frame.styles.scale;
if (scale > 0) {
this.getObject3d().scale.set(1, 1, scale);
}
if (cb) {
cb(frame, scale);
}
});
player.play();
return player;
}
getMinZoom(): number {
return this.getOptions().minZoom;
}
getMaxZoom(): number {
return this.getOptions().maxZoom;
}
isAsynchronous(): boolean {
return this.getOptions().asynchronous;
}
fire(eventType: string, param: any) {
this._fire(eventType, param);
if (this._vt && this._vt.onSelectMesh) {
this._vt.onSelectMesh(eventType, param);
}
return this;
}
config() {
return this;
}
setPickObject3d(object3d: THREE.Object3D) {
this.pickObject3d = object3d;
this.pickObject3d['__parent'] = this;
return this;
}
/**
* more method support
* @param {*} options
*/
/**
*
* @param {*} options
*/
_initOptions(options: BaseObjectOptionType) {
this.options = maptalks.Util.extend({} as BaseObjectOptionType, OPTIONS, options);
return this;
}
_createMesh(geometry: THREE.BufferGeometry, material: THREE.Material) {
this.object3d = new THREE.Mesh(geometry, material);
this.object3d['__parent'] = this;
return this;
}
_createGroup() {
this.object3d = new THREE.Group();
this.object3d['__parent'] = this;
return this;
}
_createLine(geometry: THREE.BufferGeometry, material: THREE.LineBasicMaterial | THREE.LineDashedMaterial) {
this.object3d = new THREE.Line(geometry, material);
(this.object3d as THREE.Line).computeLineDistances();
this.object3d['__parent'] = this;
return this;
}
_createLine2(geometry, material) {
this.object3d = new Line2(geometry, material);
(this.object3d as any).computeLineDistances();
this.object3d['__parent'] = this;
return this;
}
// eslint-disable-next-line no-unused-vars
_createPoints(geometry: THREE.BufferGeometry, material: THREE.PointsMaterial) {
//Serving for particles
this.object3d = new THREE.Points(geometry, material);
this.object3d['__parent'] = this;
return this;
}
_createLineSegments(geometry: THREE.BufferGeometry, material: THREE.LineBasicMaterial | THREE.LineDashedMaterial) {
this.object3d = new THREE.LineSegments(geometry, material);
(this.object3d as THREE.LineSegments).computeLineDistances();
this.object3d['__parent'] = this;
return this;
}
}
export default BaseObject; | the_stack |
import * as moment from 'moment';
import * as unhandled from 'electron-unhandled';
import * as uuid from 'uuid';
import {
BundleType,
Relationship,
SDO,
SRO,
StixObject,
Indicator,
ObservedData,
Report,
StixNode,
} from './stix';
import * as stix from './stix';
import * as fileSaver from 'file-saver';
// import { ViewUtilitiesOptions } from './cytoscape-view-utilities';
import { StigDB } from './db/db';
import {
edge_style,
node_style,
select_node_style,
view_utils_options,
modified_unselect_style,
modified_select_style,
} from './graph/graphOptions';
import * as cola from 'cytoscape-cola';
import * as cosebilkent from 'cytoscape-cose-bilkent';
import * as dagre from 'cytoscape-dagre';
import * as euler from 'cytoscape-euler';
import * as ngraph from 'cytoscape-ngraph.forcelayout';
import * as spread from 'cytoscape-spread';
import { QueryHistoryDialog } from './ui/queryHistoryWidget';
import { setup_edge_handles, edgehandles_style } from './graph/edge-handles';
import { setup_ctx_menu } from './graph/context-menu';
import { GraphUtils } from './graph/graphFunctions';
import { StixEditor } from './ui/stix-editor';
import * as Split from 'split.js';
import * as cytoscape from 'cytoscape';
import { ViewUtilitiesOptions } from './graph/graphOptions';
import { ipcRenderer } from 'electron';
import { GraphQueryResult } from './db/db_types';
import * as edgehandles from 'cytoscape-edgehandles';
import { QueryStorageService, DatabaseConfigurationStorage, StigSettings } from './storage';
import { setHandlers } from './ui/ipc-render-handlers';
declare global {
interface Window {
cycore: cytoscape.Core;
layout: string;
}
}
// tslint:disable-next-line:class-name
export class main {
// tslint:disable-next-line:no-empty
constructor() { }
public run() {
const storage: QueryStorageService = QueryStorageService.Instance;
let loading: boolean = false;
document.addEventListener('DOMContentLoaded', async () => {
unhandled();
const cyto_options: cytoscape.CytoscapeOptions = {
container: $('#cy')[0],
style: [node_style, edge_style, select_node_style, modified_select_style, modified_unselect_style, ...edgehandles_style],
// wheelSensitivity: 0.25,
} as cytoscape.CytoscapeOptions;
// set up cytoscape
const cy = cytoscape(cyto_options);
window.cycore = cy;
// used by some events to make cytoscape respond
window.addEventListener("resize", () => cy.resize(), false);
const call_forceRender = () => {
cy.resize();
};
Split(['#cy', '#editpane'], {
direction: 'horizontal',
sizes: [75, 25],
gutterSize: 8,
cursor: 'col-resize',
onDragEnd: call_forceRender,
});
const current_db_config = DatabaseConfigurationStorage.Instance.current;
const db = new StigDB(current_db_config);
// Graph handling functions
const graph_utils = new GraphUtils(cy, db);
// configures edge behaviors
edgehandles(cytoscape);
setup_edge_handles(cy);
// set up view utilities
const jquery = require('jquery');
// var jquery;
const viewUtilities = require('cytoscape-view-utilities');
viewUtilities(cytoscape, jquery);
const view_util = cy.viewUtilities(view_utils_options as ViewUtilitiesOptions);
// context menus inside the graph
const cxtmenu = require('cytoscape-cxtmenu');
cxtmenu(cytoscape);
setup_ctx_menu(cy, db, view_util);
const klay = require('cytoscape-klay');
klay(cytoscape);
cola(cytoscape);
cosebilkent(cytoscape);
dagre(cytoscape);
euler(cytoscape);
ngraph(cytoscape);
spread(cytoscape);
setHandlers();
// the editor form that is filled when a node is clicked
const editor = new StixEditor(cy, db);
//#endregion
// function to search elements inside the displayed graph
function search(prop: string, searchterm: string | number): cytoscape.CollectionReturnValue {
let prop2: string = null;
let prop3: string = null;
searchterm = searchterm.toString().trim();
if (prop.indexOf('.') !== -1) {
const s = prop.split('.');
prop2 = s[0];
prop3 = s[1];
}
return cy.elements().filter((ele) => {
let ret: boolean = false;
if (ele.data('raw_data')) {
if (prop3 !== null) {
try {
if (ele.data('raw_data')[prop2].length) {
ele.data('raw_data')[prop2].forEach((eleArr: { [x: string]: string; }) => {
ret = eleArr[prop3].trim() === searchterm;
});
} else {
ret = ele.data('raw_data')[prop2][0][prop3].trim() === searchterm;
}
} catch (error) {
// console.log('error here, value: ', prop, searchterm, error);
}
} else {
ret = ele.data('raw_data')[prop] === searchterm;
}
}
if (ele.data(prop) !== undefined) {
ret = ele.data(prop).toString() === searchterm;
}
return ret;
});
}
$("#btn-graph-search").on("click", (e: JQuery.Event) => {
e.preventDefault();
e.stopPropagation();
$('.search-status').html('');
const text: string = $("#toSearch").val() as string;
let prop = 'name';
let searchparam = '';
if (text.indexOf(':')) {
const s = text.split(':');
prop = s[0];
searchparam = s[1];
}
let selected = cy.$(':selected');
// view_util.removeHighlights(selected);
selected.unselect();
const eles = search(prop, searchparam);
selected = eles;
if (eles.length) {
eles.forEach((ele) => {
if (ele.isEdge()) {
selected = selected.add(ele.sources());
selected = selected.add(ele.targets());
}
});
selected.select();
// view_util.highlight(selected);
// cy.center(selected);
// cy.fit(selected);
$('.search-status').html(`Found ${selected.length} elements`);
cy.animate({
fit: {
eles: cy.elements(),
padding: 50,
},
step: () => undefined,
duration: 1000,
});
cy.animate({
fit: {
eles: selected,
padding: 50,
},
step: () => undefined,
duration: 1000,
});
} else {
$('.search-status').html('Found 0 elements');
}
});
// make the graph display search do the search when enter key is pressed
$("#toSearch").on("keyup", (e: JQuery.Event) => {
e.preventDefault();
e.stopPropagation();
const key = e.which;
if (key === 13) {
// e.preventDefault();
// e.stopPropagation();
$("#btn-graph-search").trigger("click");
}
});
// Query history dialog holds a history of DB queries
const hist_dialog = new QueryHistoryDialog($('#query-anchor'));
$("#btn-db-history").on('click', () => {
hist_dialog.open();
});
// handler for DB search button click
$("#btn-db-search").on("click", async (e: JQuery.Event) => {
e.preventDefault();
e.stopPropagation();
const text = $("#dbSearch").val() as string;
if (text.length === 0) {
return;
}
storage.add(text);
hist_dialog.addToHistoryDialog();
const result = await db.doGraphQuery({
command: text,
mode: 'graph',
parameters: [],
});
if (result.graph === undefined || result.graph.vertices === undefined) {
$('#query-status').html('No results');
return;
}
// console.log(result);
$('#query-status').html(`Returned ${result.graph.vertices.length} nodes and ${result.graph.edges.length} edges.`);
const add_graph: GraphQueryResult = {
graph: {
vertices: [],
edges: [],
},
};
let results: StixObject[] = [];
results = results.concat(result.graph.edges, result.graph.vertices);
// results.concat(result.graph.vertices);
loading = true;
results.forEach((item: StixObject) => {
if (cy.getElementById(item.id_).length === 0) {
/((r|R)elationship)|((s|S)ighting)/.exec(item.type) ? add_graph.graph.edges.push(item as SRO) : add_graph.graph.vertices.push(item as SDO);
}
});
try {
const bundle = await db.handleResponse(add_graph);
const new_nodes = await graph_utils.buildNodes(bundle, true);
// const selected = cy.$(':selected');
// view_util.removeHighlights(selected);
cy.elements().unselect();
graph_utils.myLayout(StigSettings.Instance.layout.toLowerCase());
new_nodes.select();
$('.message-status').html(`Added ${new_nodes.length} elements to graph`);
loading = false;
} catch (err) {
loading = false;
throw err;
}
});
// Handler to make DB search happen upon ctrl-enter
$("#dbSearch").on("keyup", async (e: JQuery.Event) => {
$('#query-status').html('');
const key = e.which;
if (key === 17) {
e.preventDefault();
e.stopPropagation();
$("#btn-db-search").trigger("click");
}
});
// clears all items from displayed graph
$("#button-clear-graph").on("click", (e: JQuery.Event) => {
e.preventDefault();
e.stopPropagation();
cy.elements().remove();
$('#metawidget').empty();
db.diff_dialog.reset();
cy.reset();
$("#query-status").html("No Results");
});
// Show stix form on click
cy.on("click", 'node, edge', (evt: cytoscape.EventObject) => {
const ele: cytoscape.CollectionReturnValue = evt.target;
cy.$(':selected').unselect();
if (ele.empty() || ele.length > 1 || loading === true) {
return true;
}
const input_data = ele.data('raw_data');
if (input_data === undefined) { return true; }
if (ele.isNode()) {
// load the form for this node
try {
editor.buildWidget(ele, ele.data('type'), input_data);
}
catch(err) {
if(err.message === "Cannot read property '$ref' of undefined"){
// added to handle sub directory 'observables'
editor.buildWidget(ele, 'observables/' + ele.data('type'), input_data);
}
else{
console.error(err);
}
}
} else {
// edge
// input_data.type
let relationship_file = "";
// objects that shouldn't be related to other objects or only require the fundamental relationship types
let common = ["artifact", "autonomous-system", "directory", "domain-name", "email-addr",
"email-message", "file", "grouping", "ipv4-addr", "ipv6-addr", "language-content",
"location", "mac-addr", "mutex", "network-traffic", "note", "observed-data",
"opinion", "process", "report", "software", "url", "user-account", "vulnerability",
"windows-registry-key", "x509-certificate"];
let target_obj_type = (input_data.source_ref).slice(0,-38);
// get the file name for the corresponding source object
if (common.includes(target_obj_type)) {
relationship_file = "common-relationship";
} else {
relationship_file = target_obj_type + "-relationship";
}
editor.buildWidget(ele, relationship_file , input_data);
}
$('button#btn-export-single').button('option', 'disabled', false);
if (ele.data('saved') === false) {
$('button.btn-commit').button('option', 'disabled', false);
} else {
$('button.btn-commit').button('option', 'disabled', true);
}
return true;
});
$('#btn-export-single').on('click', (e: JQuery.Event) => {
// console.log(editor.root.getValue())
e.preventDefault();
e.stopPropagation();
const form_data = editor.editor.getEditor('root').getValue();
const jsonToSave = JSON.stringify(form_data, null, 2);
const jsonSingleSave = new Blob([jsonToSave], { type: "application/json" });
fileSaver.saveAs(jsonSingleSave, `${form_data.id}.json`);
$('.message-status').html(`Exported ${form_data.id} objects`);
});
// Clear Stix form editor when node/edge is unselected
cy.on("unselect", 'node, edge', (_evt: cytoscape.EventObject) => {
// editor.editor.destroy();
$('#metawidget').empty();
$('#current_node').empty();
$('button.btn-commit').button('option', 'disabled', true);
$('button#btn-export-single').button('option', 'disabled', true);
});
// Handler for when an edge is created via the graph editor
cy.on('add', 'edge', (evt: cytoscape.EventObject) => {
let my_map = new Map();
my_map.set('attack-pattern', 'uses');
my_map.set('campaign', 'uses');
my_map.set('course-of-action', 'mitigates');
my_map.set('identity', 'located-at');
my_map.set('indicator', 'indicates');
my_map.set('infrastructure', 'consists-of');
my_map.set('intrusion-set', 'uses');
my_map.set('malware', 'targets');
my_map.set('malware-analysis', 'analysis-of');
my_map.set('threat-actor', 'uses');
my_map.set('tool', 'targets');
const ele = evt.target;
// first check to see if the edge has been completed
// if either end of the edge doesn't have raw_data it hasn't been completed
if (ele.source().data('raw_data') === undefined || ele.target().data('raw_data') === undefined) {
return;
}
const input_data = ele.data('raw_data');
if (input_data === undefined) {
let src_obj_type = ele.source().data('raw_data').type;
let default_relationship = "";
if (my_map.has(src_obj_type)) {
default_relationship = my_map.get(src_obj_type);
} else {
default_relationship = "related-to";
}
const raw_data: Relationship = {
// get source node
source_ref: ele.source().data('raw_data').id,
// get target node
target_ref: ele.target().data('raw_data').id,
type: 'relationship',
created: moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'),
modified: moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'),
id: 'relationship--' + ele.id(),
relationship_type: (default_relationship),
};
ele.data('raw_data', raw_data);
ele.data('saved', false);
ele.style('label', default_relationship);
}
});
ipcRenderer.on("layout", (_event: Electron.Event, layout_type: string) => {
// layout = layout_type;
// window.layout = layout_type;
graph_utils.myLayout(layout_type);
});
ipcRenderer.on('database_reconfigured', () => {
cy.elements().remove();
$('#metawidget').empty();
db.diff_dialog.reset();
cy.reset();
$("#query-status").html("No Results");
});
// Handlers for drag and drop of files containing stix bundles
const uploader: HTMLElement = document.getElementById('cy')!;
/**
* Event handler for when a file is dropped into the UI
*
* @param {DragEvent} evt
*/
function handleFileDrop(evt: DragEvent) {
// evt.stopPropagation();
evt.preventDefault();
handleFiles(evt.dataTransfer.files);
}
/**
* @description Event handler for drag in progress
* @param {DragEvent} evt
*/
function handleDragOver(evt: DragEvent) {
// evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
/**
* Handles files added to UI via drag and drop
*
* @param {FileList} files
*/
function handleFiles(files: FileList) {
// files is a FileList of File objects (in our case, just one)
let f;
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < files.length; i++) {
if (files[i] && files[i] instanceof File) {
f = files[i];
document.getElementById('chosen-files')!.innerText += f.name + " ";
// hideMessages();
const r = new FileReader();
r.onload = (_e: Event) => {
// this.result
// addToGraph(JSON.parse(e.target.result))
addToGraph(JSON.parse(r.result as string));
};
r.readAsText(f);
}
}
}
/**
* Adds a stix bundle to the current graph.
*
* @param {BundleType} pkg
*/
function addToGraph(pkg: BundleType) {
graph_utils.buildNodes(pkg, false).then((added) => {
$('.message-status').html(`Added ${added.length} elements to graph.`);
});
graph_utils.myLayout(StigSettings.Instance.layout.toLowerCase());
}
uploader.addEventListener('dragover', handleDragOver, false);
uploader.addEventListener('drop', handleFileDrop, false);
/**
* Handler for Export Bundle button
*
*/
$(document).on('click', '#btn-export-bundle', () => {
// Get raw data from all cy elements
// Create bundle object
const bundle_id = 'bundle--' + uuid.v4();
const bundle = { type: 'bundle', id: bundle_id, objects: [] } as BundleType;
let nodes = cy.$(':visible');
nodes = nodes.union(nodes.connectedEdges());
nodes.each((ele) => {
if (ele.length === 0) {
return;
}
//logic to remove null on json export
if(ele.data('raw_data')!==undefined){
bundle.objects.push(ele.data('raw_data'));
}
});
// cy.edges().each((ele) => {
// // TODO FIXME: Do not save created_by edges, and other implicit edges
// bundle.objects.push(ele.data('raw_data'));
// });
// Convert to JSON and save
const jsonToSave = JSON.stringify(bundle, null, 2);
const jsonBundleSave = new Blob([jsonToSave], { type: "application/json" });
fileSaver.saveAs(jsonBundleSave, "bundle.json");
$('.message-status').html(`Exported ${bundle.objects.length} objects`);
});
$(document).on('click', '#btn-diff', () => {
db.diff_dialog.open();
});
/***************************************** *
* Save stix form to DB on click
*************************************** */
$('button').button();
$('button.btn-commit').on("click", (e: JQuery.Event) => {
e.preventDefault();
e.stopPropagation();
let result: StixObject[];
let ourres = '';
try {
const formdata: StixObject = editor.editor.getValue();
db.updateDB(formdata).then((r) => {
result = r;
// ourres = result[0]['type'];
});
} catch (e) {
console.error('Error saving to database:');
console.error(e);
throw e;
}
$('button.btn-commit').button('option', 'disabled', true);
$('.message-status').html(`Committed 1 object to the database.`);
});
/***********************************************************************************
*
* Widget Bar Code
*
***********************************************************************************/
/**
* @description Helper function to build a stixnode to insert into the graph
* @param {string} node_type
* @returns {Promise<StixNode>}
*/
async function event_add_node(node_type: string): Promise<StixNode> {
const opts: stix.StixNodeData = {
type: node_type,
id: node_type + '--' + uuid.v4(),
created: moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]'),
};
if (node_type === 'indicator') {
(opts as Indicator).valid_from = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
} else if (node_type === 'observed-data') {
(opts as ObservedData).first_observed = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
(opts as ObservedData).last_observed = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
} else if (node_type === 'report') {
(opts as Report).published = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
}
if (node_type !== "marking-definition") {
opts.name = node_type;
opts.modified = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
}
return new StixNode(opts, node_type, 'GUI');
}
/**
* Event handler for when an icon in the top widget bar is clicked.
* It adds a node of that type to the canvas.
*
*
* @template HTMLElement
* @param {JQuery.ClickEvent<HTMLElement, { name: string; }>} evt
* @returns {Promise<boolean>}
*/
async function widget_bar_onclick<HTMLElement>(evt: JQuery.ClickEvent<HTMLElement, { name: string; }>): Promise<boolean> {
// alert(evt.data['name'] + " clicked");
const my_node = await event_add_node(evt.data.name);
cy.add(my_node);
return true;
}
/**
* Load Widget Bar
*/
const node_img = stix.node_img;
$('.loadlater').each((_index: number, element: HTMLElement) => {
const ele = $(element);
if (ele === undefined) {
return;
}
// click handler for icons in the widget bar
$(element).on("click",
null,
{ name: $(element).attr('name') },
(e: JQuery.ClickEvent<HTMLElement, { name: string; }>) => widget_bar_onclick(e));
// associate the name of stix object represented by the icon to the icon. This association is used later to
// look up the correct stix schema
const name = ele.attr('name');
const src = ele.attr('src');
if (name === undefined || src === undefined) {
return;
} else {
node_img[name] = src;
}
// make icons draggable
$(element).draggable({
opacity: 0.7,
helper: 'clone',
zIndex: 999,
start() {
// console.log('icon position:' + $(element).attr('position').x + $(element).attr('position').y)
// console.log('drag start:' + ui.position.left.toString() + ' ' + ui.position.top.toString())
},
// handle widgets being dragged in from the widget bar
stop: async (evt: DragEvent) => {
const my_node = await event_add_node($(element).attr('name')!);
const view_pos = cy._private.renderer.projectIntoViewport(evt.clientX, evt.clientY);
my_node.position = {
x: view_pos[0],
y: view_pos[1],
};
cy.add(my_node);
},
});
return;
});
},
);
//
/*document.addEventListener("DOMContentLoaded", function() {
var cy = (window.cy = cytoscape({
container: document.getElementsByClassName("icon-box"),
style: [{
selector: "node",
style: {
content: "data(id)"
}
}
],
}));
function makePopper(ele) {
let ref = ele.popperRef(); // used only for positioning
ele.tippy = tippy(ref, { // tippy options:
content: () => {
let content = document.createElement('div');
content.innerHTML = ele.id();
return content;
},
trigger: 'manual' // probably want manual mode
});
}
cy.ready(function() {
cy.elements().forEach(function(ele) {
makePopper(ele);
});
});
cy.elements().unbind('mouseover');
cy.elements().bind('mouseover', (event) => event.target.tippy.show());
cy.elements().unbind('mouseout');
cy.elements().bind('mouseout', (event) => event.target.tippy.hide());
});
//*/
}
} | the_stack |
import { Observer } from "../Misc/observable";
import { Nullable } from "../types";
import { WebVRFreeCamera } from "../Cameras/VR/webVRCamera";
import { Scene, IDisposable } from "../scene";
import { Quaternion, Vector3, Matrix } from "../Maths/math.vector";
import { AbstractMesh } from "../Meshes/abstractMesh";
import { Mesh } from "../Meshes/mesh";
import { Camera } from "../Cameras/camera";
import { TargetCamera } from "../Cameras/targetCamera";
import { Node } from "../node";
import { Bone } from "../Bones/bone";
import { UtilityLayerRenderer } from "../Rendering/utilityLayerRenderer";
import { TransformNode } from '../Meshes/transformNode';
import { StandardMaterial } from '../Materials/standardMaterial';
import { PointerEventTypes, PointerInfo } from '../Events/pointerEvents';
import { LinesMesh } from '../Meshes/linesMesh';
import { PointerDragBehavior } from "../Behaviors/Meshes/pointerDragBehavior";
import { ShadowLight } from "../Lights/shadowLight";
import { Light } from "../Lights/light";
/**
* Cache built by each axis. Used for managing state between all elements of gizmo for enhanced UI
*/
export interface GizmoAxisCache {
/** Mesh used to render the Gizmo */
gizmoMeshes: Mesh[];
/** Mesh used to detect user interaction with Gizmo */
colliderMeshes: Mesh[];
/** Material used to indicate color of gizmo mesh */
material: StandardMaterial;
/** Material used to indicate hover state of the Gizmo */
hoverMaterial: StandardMaterial;
/** Material used to indicate disabled state of the Gizmo */
disableMaterial: StandardMaterial;
/** Used to indicate Active state of the Gizmo */
active: boolean;
/** DragBehavior */
dragBehavior: PointerDragBehavior;
}
/**
* Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
*/
export class Gizmo implements IDisposable {
/**
* The root mesh of the gizmo
*/
public _rootMesh: Mesh;
private _attachedMesh: Nullable<AbstractMesh> = null;
private _attachedNode: Nullable<Node> = null;
private _customRotationQuaternion: Nullable<Quaternion> = null;
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
protected _scaleRatio = 1;
/**
* boolean updated by pointermove when a gizmo mesh is hovered
*/
protected _isHovered = false;
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
public set scaleRatio(value: number) {
this._scaleRatio = value;
}
public get scaleRatio() {
return this._scaleRatio;
}
/**
* True when the mouse pointer is hovered a gizmo mesh
*/
public get isHovered() {
return this._isHovered;
}
/**
* If a custom mesh has been set (Default: false)
*/
protected _customMeshSet = false;
/**
* Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
* * When set, interactions will be enabled
*/
public get attachedMesh() {
return this._attachedMesh;
}
public set attachedMesh(value) {
this._attachedMesh = value;
if (value) {
this._attachedNode = value;
}
this._rootMesh.setEnabled(value ? true : false);
this._attachedNodeChanged(value);
}
/**
* Node that the gizmo will be attached to. (eg. on a drag gizmo the mesh, bone or NodeTransform that will be dragged)
* * When set, interactions will be enabled
*/
public get attachedNode() {
return this._attachedNode;
}
public set attachedNode(value) {
this._attachedNode = value;
this._attachedMesh = null;
this._rootMesh.setEnabled(value ? true : false);
this._attachedNodeChanged(value);
}
/**
* Disposes and replaces the current meshes in the gizmo with the specified mesh
* @param mesh The mesh to replace the default mesh of the gizmo
*/
public setCustomMesh(mesh: Mesh) {
if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
}
this._rootMesh.getChildMeshes().forEach((c) => {
c.dispose();
});
mesh.parent = this._rootMesh;
this._customMeshSet = true;
}
protected _updateGizmoRotationToMatchAttachedMesh = true;
/**
* If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
*/
public set updateGizmoRotationToMatchAttachedMesh(value: boolean) {
this._updateGizmoRotationToMatchAttachedMesh = value;
}
public get updateGizmoRotationToMatchAttachedMesh() {
return this._updateGizmoRotationToMatchAttachedMesh;
}
/**
* If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
*/
public updateGizmoPositionToMatchAttachedMesh = true;
/**
* When set, the gizmo will always appear the same size no matter where the camera is (default: true)
*/
public updateScale = true;
protected _interactionsEnabled = true;
protected _attachedNodeChanged(value: Nullable<Node>) {
}
private _beforeRenderObserver: Nullable<Observer<Scene>>;
private _tempQuaternion = new Quaternion(0, 0, 0, 1);
private _tempVector = new Vector3();
private _tempVector2 = new Vector3();
private _tempMatrix1 = new Matrix();
private _tempMatrix2 = new Matrix();
private _rightHandtoLeftHandMatrix = Matrix.RotationY(Math.PI);
/**
* Creates a gizmo
* @param gizmoLayer The utility layer the gizmo will be added to
*/
constructor(
/** The utility layer the gizmo will be added to */
public gizmoLayer: UtilityLayerRenderer = UtilityLayerRenderer.DefaultUtilityLayer) {
this._rootMesh = new Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
this._rootMesh.rotationQuaternion = Quaternion.Identity();
this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(() => {
this._update();
});
}
/**
* posture that the gizmo will be display
* When set null, default value will be used (Quaternion(0, 0, 0, 1))
*/
public get customRotationQuaternion(): Nullable<Quaternion> {
return this._customRotationQuaternion;
}
public set customRotationQuaternion(customRotationQuaternion: Nullable<Quaternion>) {
this._customRotationQuaternion = customRotationQuaternion;
}
/**
* Updates the gizmo to match the attached mesh's position/rotation
*/
protected _update() {
if (this.attachedNode) {
var effectiveNode = this.attachedNode;
if (this.attachedMesh) {
effectiveNode = this.attachedMesh._effectiveMesh || this.attachedNode;
}
// Position
if (this.updateGizmoPositionToMatchAttachedMesh) {
const row = effectiveNode.getWorldMatrix().getRow(3);
const position = row ? row.toVector3() : new Vector3(0, 0, 0);
this._rootMesh.position.copyFrom(position);
}
// Rotation
if (this.updateGizmoRotationToMatchAttachedMesh) {
effectiveNode.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion!);
}
else {
if (this._customRotationQuaternion) {
this._rootMesh.rotationQuaternion!.copyFrom(this._customRotationQuaternion);
} else {
this._rootMesh.rotationQuaternion!.set(0, 0, 0, 1);
}
}
// Scale
if (this.updateScale) {
const activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera!;
var cameraPosition = activeCamera.globalPosition;
if ((<WebVRFreeCamera>activeCamera).devicePosition) {
cameraPosition = (<WebVRFreeCamera>activeCamera).devicePosition;
}
this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
var dist = this._tempVector.length() * this.scaleRatio;
this._rootMesh.scaling.set(dist, dist, dist);
// Account for handedness, similar to Matrix.decompose
if (effectiveNode._getWorldMatrixDeterminant() < 0) {
this._rootMesh.scaling.y *= -1;
}
} else {
this._rootMesh.scaling.setAll(this.scaleRatio);
}
}
}
/**
* Handle position/translation when using an attached node using pivot
*/
protected _handlePivot() {
const attachedNodeTransform = this._attachedNode as any;
// check there is an active pivot for the TransformNode attached
if (attachedNodeTransform.isUsingPivotMatrix && attachedNodeTransform.isUsingPivotMatrix() && attachedNodeTransform.position) {
// When a TransformNode has an active pivot, even without parenting,
// translation from the world matrix is different from TransformNode.position.
// Pivot works like a virtual parent that's using the node orientation.
// As the world matrix is transformed by the gizmo and then decomposed to TRS
// its translation part must be set to the Node's position.
attachedNodeTransform.getWorldMatrix().setTranslation(attachedNodeTransform.position);
}
}
/**
* computes the rotation/scaling/position of the transform once the Node world matrix has changed.
* @param value Node, TransformNode or mesh
*/
protected _matrixChanged() {
if (!this._attachedNode) {
return;
}
if ((<Camera>this._attachedNode)._isCamera) {
var camera = this._attachedNode as Camera;
var worldMatrix;
var worldMatrixUC;
if (camera.parent) {
var parentInv = this._tempMatrix2;
camera.parent._worldMatrix.invertToRef(parentInv);
this._attachedNode._worldMatrix.multiplyToRef(parentInv, this._tempMatrix1);
worldMatrix = this._tempMatrix1;
} else {
worldMatrix = this._attachedNode._worldMatrix;
}
if (camera.getScene().useRightHandedSystem) {
// avoid desync with RH matrix computation. Otherwise, rotation of PI around Y axis happens each frame resulting in axis flipped because worldMatrix is computed as inverse of viewMatrix.
this._rightHandtoLeftHandMatrix.multiplyToRef(worldMatrix, this._tempMatrix2);
worldMatrixUC = this._tempMatrix2;
} else {
worldMatrixUC = worldMatrix;
}
worldMatrixUC.decompose(this._tempVector2, this._tempQuaternion, this._tempVector);
var inheritsTargetCamera = this._attachedNode.getClassName() === "FreeCamera"
|| this._attachedNode.getClassName() === "FlyCamera"
|| this._attachedNode.getClassName() === "ArcFollowCamera"
|| this._attachedNode.getClassName() === "TargetCamera"
|| this._attachedNode.getClassName() === "TouchCamera"
|| this._attachedNode.getClassName() === "UniversalCamera";
if (inheritsTargetCamera) {
var targetCamera = this._attachedNode as TargetCamera;
targetCamera.rotation = this._tempQuaternion.toEulerAngles();
if (targetCamera.rotationQuaternion) {
targetCamera.rotationQuaternion.copyFrom(this._tempQuaternion);
targetCamera.rotationQuaternion.normalize();
}
}
camera.position.copyFrom(this._tempVector);
} else if ((<Mesh>this._attachedNode)._isMesh || this._attachedNode.getClassName() === "AbstractMesh" || this._attachedNode.getClassName() === "TransformNode" || this._attachedNode.getClassName() === "InstancedMesh") {
var transform = this._attachedNode as TransformNode;
if (transform.parent) {
var parentInv = this._tempMatrix1;
var localMat = this._tempMatrix2;
transform.parent.getWorldMatrix().invertToRef(parentInv);
this._attachedNode.getWorldMatrix().multiplyToRef(parentInv, localMat);
localMat.decompose(transform.scaling, this._tempQuaternion, transform.position);
} else {
this._attachedNode._worldMatrix.decompose(transform.scaling, this._tempQuaternion, transform.position);
}
if (!transform.billboardMode) {
if (transform.rotationQuaternion) {
transform.rotationQuaternion.copyFrom(this._tempQuaternion);
transform.rotationQuaternion.normalize();
} else {
transform.rotation = this._tempQuaternion.toEulerAngles();
}
}
} else if (this._attachedNode.getClassName() === "Bone") {
var bone = this._attachedNode as Bone;
const parent = bone.getParent();
if (parent) {
var invParent = this._tempMatrix1;
var boneLocalMatrix = this._tempMatrix2;
parent.getWorldMatrix().invertToRef(invParent);
bone.getWorldMatrix().multiplyToRef(invParent, boneLocalMatrix);
var lmat = bone.getLocalMatrix();
lmat.copyFrom(boneLocalMatrix);
} else {
var lmat = bone.getLocalMatrix();
lmat.copyFrom(bone.getWorldMatrix());
}
bone.markAsDirty();
} else {
const light = this._attachedNode as ShadowLight;
if (light.getTypeID)
{
const type = light.getTypeID();
if (type === Light.LIGHTTYPEID_DIRECTIONALLIGHT || type === Light.LIGHTTYPEID_SPOTLIGHT || type === Light.LIGHTTYPEID_POINTLIGHT) {
const parent = light.parent;
if (parent) {
var invParent = this._tempMatrix1;
var nodeLocalMatrix = this._tempMatrix2;
parent.getWorldMatrix().invertToRef(invParent);
light.getWorldMatrix().multiplyToRef(invParent, nodeLocalMatrix);
nodeLocalMatrix.decompose(undefined, this._tempQuaternion, this._tempVector);
} else {
this._attachedNode._worldMatrix.decompose(undefined, this._tempQuaternion, this._tempVector);
}
// setter doesn't copy values. Need a new Vector3
light.position = new Vector3(this._tempVector.x, this._tempVector.y, this._tempVector.z);
Vector3.Backward(false).rotateByQuaternionToRef(this._tempQuaternion, this._tempVector);
light.direction = new Vector3(this._tempVector.x, this._tempVector.y, this._tempVector.z);
}
}
}
}
/**
* refresh gizmo mesh material
* @param material material to apply
*/
protected _setGizmoMeshMaterial(gizmoMeshes: Mesh[], material: StandardMaterial) {
if (gizmoMeshes) {
gizmoMeshes.forEach((m: Mesh) => {
m.material = material;
if ((<LinesMesh>m).color) {
(<LinesMesh>m).color = material.diffuseColor;
}
});
}
}
/**
* Subscribes to pointer up, down, and hover events. Used for responsive gizmos.
* @param gizmoLayer The utility layer the gizmo will be added to
* @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI
* @returns {Observer<PointerInfo>} pointerObserver
*/
public static GizmoAxisPointerObserver(gizmoLayer: UtilityLayerRenderer, gizmoAxisCache: Map<Mesh, GizmoAxisCache>): Observer<PointerInfo> {
let dragging = false;
const pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {
if (pointerInfo.pickInfo) {
// On Hover Logic
if (pointerInfo.type === PointerEventTypes.POINTERMOVE) {
if (dragging) { return; }
gizmoAxisCache.forEach((cache) => {
if (cache.colliderMeshes && cache.gizmoMeshes) {
const isHovered = (cache.colliderMeshes?.indexOf((pointerInfo?.pickInfo?.pickedMesh as Mesh)) != -1);
const material = cache.dragBehavior.enabled ? (isHovered || cache.active ? cache.hoverMaterial : cache.material) : cache.disableMaterial;
cache.gizmoMeshes.forEach((m: Mesh) => {
m.material = material;
if ((m as LinesMesh).color) {
(m as LinesMesh).color = material.diffuseColor;
}
});
}
});
}
// On Mouse Down
if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {
// If user Clicked Gizmo
if (gizmoAxisCache.has(pointerInfo.pickInfo.pickedMesh?.parent as Mesh)) {
dragging = true;
const statusMap = gizmoAxisCache.get(pointerInfo.pickInfo.pickedMesh?.parent as Mesh);
statusMap!.active = true;
gizmoAxisCache.forEach((cache) => {
const isHovered = (cache.colliderMeshes?.indexOf((pointerInfo?.pickInfo?.pickedMesh as Mesh)) != -1);
const material = ((isHovered || cache.active) && cache.dragBehavior.enabled) ? cache.hoverMaterial : cache.disableMaterial;
cache.gizmoMeshes.forEach((m: Mesh) => {
m.material = material;
if ((m as LinesMesh).color) {
(m as LinesMesh).color = material.diffuseColor;
}
});
});
}
}
// On Mouse Up
if (pointerInfo.type === PointerEventTypes.POINTERUP) {
gizmoAxisCache.forEach((cache) => {
cache.active = false;
dragging = false;
cache.gizmoMeshes.forEach((m: Mesh) => {
m.material = cache.dragBehavior.enabled ? cache.material : cache.disableMaterial;
if ((m as LinesMesh).color) {
(m as LinesMesh).color = cache.material.diffuseColor;
}
});
});
}
}
});
return pointerObserver!;
}
/**
* Disposes of the gizmo
*/
public dispose() {
this._rootMesh.dispose();
if (this._beforeRenderObserver) {
this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
}
}
} | the_stack |
import { DomElement, HTMLInstance, IDom, IKeyValue } from "../types";
import { DomDiff } from "./DomDiff";
/**
* Dom 유틸리티
*
*/
export class Dom implements IDom {
el: HTMLInstance;
_initContext: any;
constructor(tag: DomElement, className: string = '', attr: IKeyValue = {}) {
if (typeof tag !== 'string') {
this.el = tag;
} else {
var el = document.createElement(tag);
if (className) {
el.className = className;
}
for (var k in attr) {
el.setAttribute(k, attr[k]);
}
this.el = el;
}
}
static create (tag: DomElement, className: string = '', attr: IKeyValue = {}) {
return new Dom(tag, className, attr);
}
/**
* @param {any} htmlString
*/
static createByHTML (htmlString: any) {
var div = Dom.create('div')
var list = (div.html(htmlString) as Dom).children();
if (list.length) {
return Dom.create(list[0].el);
}
return null;
}
static getScrollTop() {
return Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
);
}
static getScrollLeft() {
return Math.max(
window.pageXOffset,
document.documentElement.scrollLeft,
document.body.scrollLeft
);
}
static parse(html: string) {
var parser = new DOMParser();
return parser.parseFromString(html, "text/html");
}
static body () {
return Dom.create(document.body)
}
get htmlEl (): HTMLElement {
return this.el as HTMLElement;
}
get inputEl (): HTMLInputElement {
return this.el as HTMLInputElement
}
get svgEl (): SVGElement {
return this.el as SVGElement;
}
setAttr (obj: IKeyValue) {
Object.keys(obj).forEach(key => {
this.attr(key, obj[key])
})
return this;
}
setAttrNS (obj: IKeyValue, namespace = 'http://www.w3.org/2000/svg') {
Object.keys(obj).forEach(key => {
this.attrNS(key, obj[key], namespace)
})
return this;
}
setProp (obj: IKeyValue) {
Object.keys(obj).forEach(key => {
// 동일한 값을 갱신하지 않는다.
if (this.htmlEl[key] != obj[key]) {
this.htmlEl[key] = obj[key];
}
})
return this;
}
/**
* data-xxx 속성을 관리한다.
*
* @param {string} key
* @param {any} value
*/
data (key: string, value: any) {
if (arguments.length === 1) {
return this.attr('data-' + key);
} else if (arguments.length === 2) {
return this.attr('data-' + key, value);
}
//TODO: data 속성을 모두 {[key]: value} 형태로 리턴하기
return this;
}
/**
* Dom attribute 얻기 또는 설정
*
* get -> Dom.create(targetElement).attr('key');
* set -> Dom.create(targetElement).attr('key', value);
*
* @param {string} key
* @param {[string]} value
*/
attr(key: string, value?: undefined) {
if (arguments.length == 1) {
return this.htmlEl.getAttribute(key);
}
// 동일한 속성 값이 있다면 변경하지 않는다.
if (this.htmlEl.getAttribute(key) != value) {
this.htmlEl.setAttribute(key, `${value}`);
}
return this;
}
/**
* @param {any} key
* @param {any} value
*/
attrNS(key: string, value: any, namespace = 'http://www.w3.org/2000/svg') {
if (arguments.length == 1) {
return this.svgEl.getAttributeNS(namespace, key);
}
// 동일한 속성 값이 있다면 변경하지 않는다.
if (this.svgEl.getAttributeNS(namespace, key) != value) {
this.svgEl.setAttributeNS(namespace, key, value);
}
return this;
}
/**
* @param {any} keyField
*/
attrKeyValue(keyField: any): IKeyValue {
return {
[`${this.htmlEl.getAttribute(keyField)}`]: this.val()
}
}
attrs(...args: string[]) {
return args.map(key => {
return this.htmlEl.getAttribute(key);
});
}
/**
* @param {any[]} args
*/
styles(...args: any[]) {
return args.map(key => {
return this.htmlEl.style[key];
});
}
/**
* @param {string} key
*/
removeAttr(key: string) {
this.htmlEl.removeAttribute(key);
return this;
}
/**
* @param {any} key
*/
removeStyle(key: any) {
this.htmlEl.style.removeProperty(key);
return this;
}
/**
* @param {{ el: any; }} checkElement
*/
is(checkElement: { el: any; }) {
return this.htmlEl === (checkElement.el || checkElement);
}
/**
* @param {string} tag
*/
isTag(tag: string) {
return this.htmlEl.tagName.toLowerCase() === tag.toLowerCase()
}
/**
* @param {any} cls
*/
closest(cls: any) {
var temp: Dom = this;
var checkCls = false;
while (!(checkCls = temp.hasClass(cls))) {
if (temp.el.parentNode) {
temp = Dom.create(temp.el.parentNode as HTMLElement);
} else {
return null;
}
}
if (checkCls) {
return temp;
}
return null;
}
path(): Dom[] {
if (!this.htmlEl) return [];
const $parentNode = this.parent();
if ($parentNode) {
return [...$parentNode.path(), this]
} else {
return [this]
}
}
parent() {
return Dom.create(this.htmlEl.parentNode as HTMLElement);
}
hasParent () {
return !!this.htmlEl.parentNode
}
/**
* @param {any[]} args
*/
removeClass(...args: any[]) {
this.htmlEl.classList.remove(...args);
return this;
}
/**
* @param {any} cls
*/
hasClass(cls: any) {
if (!this.htmlEl.classList) return false;
return this.htmlEl.classList.contains(cls);
}
/**
* @param {any[]} args
*/
addClass(...args: any[]) {
this.htmlEl.classList.add(...args);
return this;
}
/**
* @param {any} cls
*/
onlyOneClass(cls: any) {
var parent = this.parent();
parent.children().forEach(it => {
it.removeClass(cls);
})
this.addClass(cls);
}
/**
* @param {string} cls
* @param {any} isForce
*/
toggleClass(cls: string, isForce: any) {
this.htmlEl.classList.toggle(cls, isForce);
return this;
}
/**
* @param {string} html
*/
html(html: string) {
if (typeof html === 'undefined') {
return this.htmlEl.innerHTML;
}
if (typeof html === 'string') {
this.htmlEl.innerHTML = html;
} else {
this.empty().append(html);
}
return this;
}
/**
* @param {any} fragment
*/
htmlDiff(fragment: HTMLInstance) {
DomDiff(this, fragment);
}
/**
* @param {any} html
*/
updateDiff (html: string, rootElement:string = 'div') {
DomDiff(this, Dom.create(rootElement).html(html) as Dom)
}
/**
* @param {any} html
*/
updateSVGDiff (html: any, rootElement = 'div') {
DomDiff(this, (Dom.create(rootElement).html(`<svg>${html}</svg>`) as Dom).firstChild.firstChild)
}
/**
* @param {any} selector
*/
find(selector: any) {
return this.htmlEl.querySelector(selector);
}
/**
* @param {any} selector
*/
$(selector: any) {
var node = this.find(selector);
return node ? Dom.create(node) : null;
}
/**
* @param {any} selector
*/
findAll(selector: string) {
return Array.from(this.htmlEl.querySelectorAll(selector));
}
$$(selector: string) {
var arr = this.findAll(selector);
return arr.map(node => Dom.create(node as HTMLElement));
}
empty() {
while (this.htmlEl.firstChild) this.htmlEl.removeChild(this.htmlEl.firstChild);
return this;
}
append(el: string | HTMLInstance | Dom) {
if (typeof el === 'string') {
this.htmlEl.appendChild(document.createTextNode(el));
} else {
this.htmlEl.appendChild((el as Dom).el || el);
}
return this;
}
prepend(el: string| HTMLInstance | Dom) {
if (typeof el === 'string') {
this.htmlEl.prepend(document.createTextNode(el));
} else {
this.htmlEl.prepend((el as Dom).el || el);
}
return this;
}
prependHTML(html: string) {
var $dom = Dom.create("div").html(html);
this.prepend(($dom as Dom).createChildrenFragment());
return $dom;
}
appendHTML(html: string) {
var $dom = Dom.create("div").html(html);
this.append(($dom as Dom).createChildrenFragment());
return $dom;
}
/**
* create document fragment with children dom
*/
createChildrenFragment() {
const list = this.children();
var fragment = document.createDocumentFragment();
list.forEach($el => fragment.appendChild($el.el));
return fragment;
}
/**
* @param {{ el: any; }} target
*/
appendTo(target: { el: any; }) {
var t = target.el ? target.el : target;
t.appendChild(this.htmlEl);
return this;
}
remove() {
if (this.htmlEl.parentNode) {
this.htmlEl.parentNode.removeChild(this.htmlEl);
}
return this;
}
/**
* @param {{ el: any; }} el
*/
removeChild(el: { el: any; }) {
this.htmlEl.removeChild(el.el || el);
return this;
}
/**
*
* @param {string} value
* @returns {string} 파라미터가 없을 때 textContent 를 리턴한다.
*/
text(value?: string | Dom | undefined) {
if (typeof value === 'undefined') {
return this.htmlEl.textContent;
} else {
var tempText: string = value as string;
if (value instanceof Dom) {
tempText = value.text() as string;
}
// 값의 변경 사항이 없으면 업데이트 하지 않는다.
if (this.htmlEl.textContent !== tempText) {
this.htmlEl.textContent = tempText;
}
return this;
}
}
/**
*
* $el.css`
* border-color: yellow;
* `
*
* @param {*} key
* @param {*} value
*/
css(key: string | ArrayLike<unknown> | IKeyValue, value?: string | undefined) {
const el = this.htmlEl as HTMLElement;
if (typeof key === 'string' && typeof value !== 'undefined') {
if (key.indexOf('--') === 0 && typeof value !== 'undefined' ) {
el.style.setProperty(key, value);
} else {
el.style[key] = value;
}
} else if (typeof key !== 'undefined') {
if (typeof key === 'string') {
return getComputedStyle(el)[key];
} else {
Object.entries(key).forEach(([localKey, value]) => {
if (localKey.indexOf('--') === 0 && typeof value !== 'undefined' ) {
el.style.setProperty(localKey, value);
} else {
el.style[localKey] = value;
}
})
}
}
return this;
}
getComputedStyle (...list: string[]) {
var css = getComputedStyle(this.htmlEl);
var obj = {}
list.forEach(it => {
obj[it] = css[it]
})
return obj;
}
/**
* @param {any[]} list
*/
getStyleList(...list: string[]) {
const el = this.htmlEl;
var style = {};
var len = el.style.length;
for (var i = 0; i < len; i++) {
var key = el.style[i];
style[key] = el.style[key];
}
list.forEach(key => {
style[key] = this.css(key);
});
return style;
}
/**
* @param {any} value
*/
cssText(value: any): string|Dom {
const el = this.htmlEl;
if (typeof value === 'undefined') {
return el.style.cssText;
}
return this;
}
cssFloat(key: string) {
return parseFloat(this.css(key));
}
cssInt(key: any) {
return parseInt(this.css(key));
}
/**
* @param {string} key
* @param {number} value
*/
px(key: string, value: number) {
return this.css(key, `${value}px`);
}
rect() {
return this.htmlEl.getBoundingClientRect();
}
bbox () {
return (this.el as SVGSVGElement).getBBox();
}
isSVG () {
return this.htmlEl.tagName.toUpperCase() === 'SVG';
}
offsetRect() {
const el = this.htmlEl;
if (this.isSVG()) {
const parentBox = this.parent().rect();
const box = this.rect();
return {
x: box.x - parentBox.x,
y: box.y - parentBox.y,
top: box.x - parentBox.x,
left: box.y - parentBox.y,
width: box.width,
height: box.height
}
}
return {
x: el.offsetLeft,
y: el.offsetTop,
top: el.offsetTop,
left: el.offsetLeft,
width: el.offsetWidth,
height: el.offsetHeight
};
}
offset() {
var rect = this.rect();
var scrollTop = Dom.getScrollTop();
var scrollLeft = Dom.getScrollLeft();
return {
top: rect.top + scrollTop,
left: rect.left + scrollLeft
};
}
offsetLeft() {
return this.offset().left;
}
offsetTop() {
return this.offset().top;
}
position() {
if (this.htmlEl.style.top) {
return {
top: parseFloat(this.css("top")),
left: parseFloat(this.css("left"))
};
} else {
return this.rect();
}
}
size() {
return [this.width(), this.height()];
}
width() {
return this.htmlEl.offsetWidth || this.rect().width;
}
contentWidth() {
return (
this.width() -
this.cssFloat("padding-left") -
this.cssFloat("padding-right")
);
}
height() {
return this.htmlEl.offsetHeight || this.rect().height;
}
contentHeight() {
return (
this.height() -
this.cssFloat("padding-top") -
this.cssFloat("padding-bottom")
);
}
/**
* @param {{ val: () => any; } | undefined} [value]
*/
val(value?: Dom | string) {
if (typeof value === 'undefined') {
return this.inputEl.value;
} else if (typeof value !== 'undefined') {
var tempValue = value;
if (value instanceof Dom) {
tempValue = value.val() as string;
} else {
this.inputEl.value = tempValue as string;
}
}
return this;
}
matches (selector: string): Dom | null {
if (this.htmlEl) {
if (!this.htmlEl.matches) return null;
if (this.htmlEl.matches(selector)) {
return this;
}
return this.parent().matches(selector);
}
return null;
}
get value() {
return this.inputEl.value;
}
get files() {
return this.inputEl.files ? Array.from(this.inputEl.files) : [];
}
show(displayType = "block") {
this.htmlEl.style.display = displayType != "none" ? displayType : "block"
return this;
}
hide() {
this.htmlEl.style.display = 'none';
return this;
}
isHide () {
return this.htmlEl.style.display === "none"
}
isShow () {
return !this.isHide();
}
/**
* @param {any} isForce
*/
toggle(isForce: any) {
var currentHide = this.isHide();
if (arguments.length == 1) {
if (isForce) {
return this.show();
} else {
return this.hide();
}
} else {
if (currentHide) {
return this.show();
} else {
return this.hide();
}
}
}
scrollIntoView () {
this.htmlEl.scrollIntoView()
}
/**
* @param {any} dt
*/
addScrollLeft (dt: any) {
this.htmlEl.scrollLeft += dt;
return this;
}
/**
* @param {any} dt
*/
addScrollTop (dt: any) {
this.htmlEl.scrollTop += dt;
return this;
}
/**
* @param {any} scrollTop
*/
setScrollTop(scrollTop: any) {
this.htmlEl.scrollTop = scrollTop;
return this;
}
/**
* @param {any} scrollLeft
*/
setScrollLeft(scrollLeft: any) {
this.htmlEl.scrollLeft = scrollLeft;
return this;
}
scrollTop() {
if (this.htmlEl === document.body) {
return Dom.getScrollTop();
}
return this.htmlEl.scrollTop;
}
scrollLeft() {
if (this.htmlEl === document.body) {
return Dom.getScrollLeft();
}
return this.htmlEl.scrollLeft;
}
scrollHeight() {
return this.htmlEl.scrollHeight;
}
scrollWidth() {
return this.htmlEl.scrollWidth;
}
/**
* @param {any} eventName
* @param {any} callback
* @param {any} opt1
* @param {any} opt2
*/
on(eventName: keyof HTMLElementEventMap, callback: (...arg: any[]) => any, opt1: any) {
this.htmlEl.addEventListener(eventName, callback, opt1);
return this;
}
off(eventName: keyof HTMLElementEventMap, callback: (...arg: any[]) => any) {
this.htmlEl.removeEventListener(eventName, callback);
return this;
}
getElement() {
return this.htmlEl;
}
/**
* @param {any} tag
*/
createChild(tag: any, className = '', attrs = {}, css = {}) {
let $element = Dom.create(tag, className, attrs);
$element.css(css);
this.append($element);
return $element;
}
get firstChild() {
return Dom.create(this.htmlEl.firstElementChild as HTMLElement);
}
children() {
var element = this.htmlEl.firstElementChild;
if (!element) {
return [];
}
var results = [];
do {
results.push(Dom.create(element as HTMLElement));
element = element.nextElementSibling;
} while (element);
return results;
}
childLength() {
return this.htmlEl.children.length;
}
/**
* @param {{ el: any; }} newElement
*/
replace(newElement: { el: any; }) {
if (this.htmlEl.parentNode) {
this.htmlEl.parentNode.replaceChild(newElement.el || newElement, this.htmlEl);
}
return this;
}
/**
* @param {{ el: any; }} oldElement
* @param {{ el: any; }} newElement
*/
replaceChild(oldElement: { el: any; }, newElement: { el: any; }) {
this.htmlEl.replaceChild(newElement.el || newElement, oldElement.el || oldElement);
return this;
}
checked(isChecked = false) {
if (arguments.length == 0) {
return !!this.inputEl.checked;
}
this.inputEl.checked = !!isChecked;
return this;
}
click () {
this.htmlEl.click();
return this;
}
focus() {
this.htmlEl.focus();
return this;
}
select() {
// contenteditable 의 경우 selection api 를 사용해서 select() 를 수행한다.
if (this.attr('contenteditable') === 'true') {
var range = document.createRange();
range.selectNodeContents(this.htmlEl);
var sel = window.getSelection();
sel?.removeAllRanges();
sel?.addRange(range);
} else {
this.inputEl.select();
}
return this;
}
blur() {
this.htmlEl.blur();
return this;
}
} | the_stack |
import { IGrid, ResponsiveDialogArgs } from '../base/interface';
import { Column } from '../models/column';
import { Dialog, DialogModel } from '@syncfusion/ej2-popups';
import { remove, extend, updateBlazorTemplate } from '@syncfusion/ej2-base';
import { L10n } from '@syncfusion/ej2-base';
import { ServiceLocator } from '../services/service-locator';
import * as events from '../base/constant';
import { appendChildren, applyBiggerTheme, addBiggerDialog } from '../base/util';
import { ResponsiveDialogRenderer } from './responsive-dialog-renderer';
import { ResponsiveDialogAction } from '../base/enum';
import * as literals from '../base/string-literals';
/**
* Edit render module is used to render grid edit row.
*
* @hidden
*/
export class DialogEditRender {
//Internal variables
//Module declarations
private parent: IGrid;
private l10n: L10n;
private isEdit: boolean;
private serviceLocator: ServiceLocator;
private dialog: HTMLElement;
private dialogObj: Dialog;
/**
* Constructor for render module
*
* @param {IGrid} parent - specifies the IGrid
* @param {ServiceLocator} serviceLocator - specifies the serviceLocator
*/
constructor(parent?: IGrid, serviceLocator?: ServiceLocator) {
this.parent = parent;
this.serviceLocator = serviceLocator;
if (this.parent.isDestroyed) { return; }
this.parent.on(events.dialogDestroy, this.destroy, this);
this.parent.on(events.destroy, this.destroy, this);
}
private setLocaleObj(): void {
this.l10n = this.serviceLocator.getService<L10n>('localization');
}
public addNew(elements: Element[], args: { primaryKeyValue?: string[] }): void {
this.isEdit = false;
this.createDialog(elements, args);
}
public update(elements: Element[], args: { primaryKeyValue?: string[] }): void {
this.isEdit = true;
this.createDialog(elements, args);
}
private createDialogHeader(args: ResponsiveDialogArgs): Element | string {
const gObj: IGrid = this.parent;
let header: Element | string;
if (this.parent.enableAdaptiveUI) {
const responsiveDlgRenderer: ResponsiveDialogRenderer = new ResponsiveDialogRenderer(this.parent, this.serviceLocator);
responsiveDlgRenderer.action = this.isEdit ? ResponsiveDialogAction.isEdit : ResponsiveDialogAction.isAdd;
return responsiveDlgRenderer.renderResponsiveHeader(undefined, args);
} else {
if (gObj.editSettings.headerTemplate) {
header = this.getDialogEditTemplateElement('HeaderTemplate', args);
} else if (this.isEdit) {
header = this.l10n.getConstant('EditFormTitle') + args.primaryKeyValue[0];
} else {
header = this.l10n.getConstant('AddFormTitle');
}
}
return header;
}
private createDialog(elements: Element[], args: {
primaryKeyValue?: string[], rowData?: Object,
dialog?: DialogModel, target?: HTMLElement
}): void {
const gObj: IGrid = this.parent;
this.dialog = this.parent.createElement('div', { id: gObj.element.id + '_dialogEdit_wrapper', styles: 'width: auto' });
if (gObj.enableAdaptiveUI) {
this.dialog.classList.add('e-responsive-dialog');
}
this.dialog.setAttribute('aria-label', 'Dialog edit');
gObj.element.appendChild(this.dialog);
this.setLocaleObj();
// let position: PositionDataModel = this.parent.element.getBoundingClientRect().height < 400 ?
// { X: 'center', Y: 'top' } : { X: 'center', Y: 'center' };
this.dialogObj = new Dialog(extend(
{
header: this.createDialogHeader(args), isModal: true, visible: true, cssClass: 'e-edit-dialog',
content: this.getEditElement(elements, args) as HTMLElement,
showCloseIcon: true,
allowDragging: true,
// position: position,
close: this.dialogClose.bind(this),
created: this.dialogCreated.bind(this),
closeOnEscape: true, width: gObj.editSettings.template ? 'auto' : '330px',
target: args.target ? args.target : document.body, animationSettings: { effect: 'None' },
footerTemplate: gObj.editSettings.footerTemplate ? this.getDialogEditTemplateElement('FooterTemplate', args) : null,
buttons: [{
click: this.btnClick.bind(this),
buttonModel: { content: this.l10n.getConstant('SaveButton'), cssClass: 'e-primary', isPrimary: true }
},
{ click: this.btnClick.bind(this), buttonModel: { cssClass: 'e-flat', content: this.l10n.getConstant('CancelButton') } }]
},
gObj.editSettings.dialog ? (gObj.editSettings.dialog.params || {}) : {}
));
args.dialog = this.dialogObj;
const isStringTemplate: string = 'isStringTemplate';
this.dialogObj[isStringTemplate] = true;
this.renderResponsiveDialog();
this.dialogObj.appendTo(this.dialog);
applyBiggerTheme(this.parent.element, this.dialogObj.element.parentElement);
if (gObj.enableAdaptiveUI) {
this.dialogObj.show(true);
}
}
private dialogCreated(): void {
addBiggerDialog(this.parent);
}
private renderResponsiveDialog(): void {
if (this.parent.enableAdaptiveUI) {
if (this.parent.adaptiveDlgTarget) {
this.dialogObj.target = this.parent.adaptiveDlgTarget;
}
this.dialogObj.buttons = [{}];
this.dialogObj.showCloseIcon = true;
this.dialogObj.visible = false;
this.dialogObj.width = '100%';
this.dialogObj.open = () => {
this.dialogObj.element.style.maxHeight = '100%';
};
}
}
private btnClick(e: MouseEvent): void {
if (this.l10n.getConstant('CancelButton').toLowerCase() === (e.target as HTMLInputElement).innerText.trim().toLowerCase()) {
this.dialogClose();
} else {
this.parent.endEdit();
}
}
private dialogClose(): void {
this.parent.closeEdit();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private destroy(args?: { requestType: string }): void {
const dialogEditTemplates: string[] = ['template', 'headerTemplate', 'footerTemplate'];
for (let i: number = 0; i < dialogEditTemplates.length; i++) {
if (this.parent.editSettings[dialogEditTemplates[i]]) {
const templateName: string = dialogEditTemplates[i].charAt(0).toUpperCase() + dialogEditTemplates[i].slice(1);
const editTemplateID: string = this.parent.element.id + 'editSettings' + templateName;
updateBlazorTemplate(editTemplateID, templateName, this.parent.editSettings);
}
}
this.parent.notify(events.destroyForm, {});
this.parent.isEdit = false;
this.parent.notify(events.toolbarRefresh, {});
if (this.dialog && !this.dialogObj.isDestroyed) {
this.dialogObj.destroy();
remove(this.dialog);
}
}
private getDialogEditTemplateElement(dialogTemp: string, args: { rowData?: Object, form?: Element }): Element {
const tempDiv: Element = this.parent.createElement('div', { className: 'e-dialog' + dialogTemp });
const dummyData: Object = extend({}, args.rowData, { isAdd: !this.isEdit }, true);
const templateID: string = this.parent.element.id + 'editSettings' + dialogTemp;
appendChildren(tempDiv, (dialogTemp === 'HeaderTemplate' ? this.parent.getEditHeaderTemplate() :
this.parent.getEditFooterTemplate())(dummyData, this.parent, 'editSettings' + dialogTemp, templateID));
updateBlazorTemplate(templateID, dialogTemp, this.parent.editSettings);
return tempDiv;
}
private getEditElement(elements: Object, args: { rowData?: Object, form?: Element }): Element {
const gObj: IGrid = this.parent;
const div: Element = this.parent.createElement('div', { className: this.isEdit ? literals.editedRow : 'e-insertedrow' });
const form: HTMLFormElement = args.form =
this.parent.createElement('form', { id: gObj.element.id + 'EditForm', className: 'e-gridform' }) as HTMLFormElement;
if (this.parent.editSettings.template) {
const editTemplateID: string = this.parent.element.id + 'editSettingsTemplate';
const dummyData: Object = extend({}, args.rowData, { isAdd: !this.isEdit }, true);
const isReactCompiler: boolean = this.parent.isReact && typeof (this.parent.editSettings.template) !== 'string';
if (isReactCompiler) {
this.parent.getEditTemplate()(dummyData, this.parent, 'editSettingsTemplate', editTemplateID, null, null, form);
this.parent.renderTemplates();
} else {
appendChildren(form, this.parent.getEditTemplate()(dummyData, this.parent, 'editSettingsTemplate', editTemplateID));
}
const setRules: Function = () => {
const columns: Column[] = this.parent.getColumns();
for (let i: number = 0; i < columns.length; i++) {
if ((columns[i] as Column).validationRules) {
this.parent.editModule.formObj.rules[(columns[i] as Column).field] =
(columns[i] as Column).validationRules as {[rule: string]: Object};
}
}
};
updateBlazorTemplate(editTemplateID, 'Template', this.parent.editSettings, true, setRules);
div.appendChild(form);
return div;
}
const table: Element = this.parent.createElement('table', { className: literals.table, attrs: { cellspacing: '6px', role: 'grid' } });
const tbody: Element = this.parent.createElement( literals.tbody, { attrs: { role: 'rowgroup' } });
const cols: Column[] = gObj.getColumns() as Column[];
for (let i: number = 0; i < cols.length; i++) {
if (this.parent.editModule.checkColumnIsGrouped(cols[i]) || cols[i].commands || cols[i].commandsTemplate ||
cols[i].type === 'checkbox') {
continue;
}
const tr: Element = this.parent.createElement('tr', { attrs: { role: 'row' } });
const dataCell: HTMLElement = this.parent.createElement('td', {
className: literals.rowCell, attrs: {
style: 'text-align:' + (this.parent.enableRtl ? 'right' : 'left') + ';width:190px'
}
});
elements[cols[i].uid].classList.remove('e-input');
dataCell.appendChild(elements[cols[i].uid]);
tr.appendChild(dataCell);
tbody.appendChild(tr);
}
table.appendChild(tbody);
form.appendChild(table);
div.appendChild(form);
return div;
}
public removeEventListener(): void {
if (this.parent.isDestroyed) { return; }
this.parent.off(events.dialogDestroy, this.destroy);
this.parent.off(events.destroy, this.destroy);
}
} | the_stack |
import type { SendEventForFacet } from '../../lib/utils';
import {
checkRendering,
warning,
createDocumentationMessageGenerator,
createSendEventForFacet,
isEqual,
noop,
} from '../../lib/utils';
import type { SearchResults } from 'algoliasearch-helper';
import type {
Connector,
CreateURL,
TransformItems,
RenderOptions,
Widget,
SortBy,
WidgetRenderState,
} from '../../types';
const withUsage = createDocumentationMessageGenerator({
name: 'hierarchical-menu',
connector: true,
});
const DEFAULT_SORT = ['name:asc'];
export type HierarchicalMenuItem = {
/**
* Value of the menu item.
*/
value: string;
/**
* Human-readable value of the menu item.
*/
label: string;
/**
* Number of matched results after refinement is applied.
*/
count: number;
/**
* Indicates if the refinement is applied.
*/
isRefined: boolean;
/**
* n+1 level of items, same structure HierarchicalMenuItem
*/
data: HierarchicalMenuItem[] | null;
};
export type HierarchicalMenuConnectorParams = {
/**
* Attributes to use to generate the hierarchy of the menu.
*/
attributes: string[];
/**
* Separator used in the attributes to separate level values.
*/
separator?: string;
/**
* Prefix path to use if the first level is not the root level.
*/
rootPath?: string | null;
/**
* Show the siblings of the selected parent levels of the current refined value. This
* does not impact the root level.
*/
showParentLevel?: boolean;
/**
* Max number of values to display.
*/
limit?: number;
/**
* Whether to display the "show more" button.
*/
showMore?: boolean;
/**
* Max number of values to display when showing more.
*/
showMoreLimit?: number;
/**
* How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`.
* You can also use a sort function that behaves like the standard Javascript [compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).
*
* If a facetOrdering is set in the index settings, it is used when sortBy isn't passed
*/
sortBy?: SortBy<HierarchicalMenuItem>;
/**
* Function to transform the items passed to the templates.
*/
transformItems?: TransformItems<HierarchicalMenuItem>;
};
export type HierarchicalMenuRenderState = {
/**
* Creates an url for the next state for a clicked item.
*/
createURL: CreateURL<string>;
/**
* Values to be rendered.
*/
items: HierarchicalMenuItem[];
/**
* Sets the path of the hierarchical filter and triggers a new search.
*/
refine: (value: string) => void;
/**
* Indicates if search state can be refined.
*/
canRefine: boolean;
/**
* True if the menu is displaying all the menu items.
*/
isShowingMore: boolean;
/**
* Toggles the number of values displayed between `limit` and `showMoreLimit`.
*/
toggleShowMore: () => void;
/**
* `true` if the toggleShowMore button can be activated (enough items to display more or
* already displaying more than `limit` items)
*/
canToggleShowMore: boolean;
/**
* Send event to insights middleware
*/
sendEvent: SendEventForFacet;
};
export type HierarchicalMenuWidgetDescription = {
$$type: 'ais.hierarchicalMenu';
renderState: HierarchicalMenuRenderState;
indexRenderState: {
hierarchicalMenu: {
[rootAttribute: string]: WidgetRenderState<
HierarchicalMenuRenderState,
HierarchicalMenuConnectorParams
>;
};
};
indexUiState: {
hierarchicalMenu: {
[rootAttribute: string]: string[];
};
};
};
export type HierarchicalMenuConnector = Connector<
HierarchicalMenuWidgetDescription,
HierarchicalMenuConnectorParams
>;
/**
* **HierarchicalMenu** connector provides the logic to build a custom widget
* that will give the user the ability to explore facets in a tree-like structure.
*
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two
* levels deep.
*
* @type {Connector}
* @param {function(HierarchicalMenuRenderingOptions, boolean)} renderFn Rendering function for the custom **HierarchicalMenu** widget.
* @param {function} unmountFn Unmount function called when the widget is disposed.
* @return {function(CustomHierarchicalMenuWidgetParams)} Re-usable widget factory for a custom **HierarchicalMenu** widget.
*/
const connectHierarchicalMenu: HierarchicalMenuConnector =
function connectHierarchicalMenu(renderFn, unmountFn = noop) {
checkRendering(renderFn, withUsage());
return (widgetParams) => {
const {
attributes,
separator = ' > ',
rootPath = null,
showParentLevel = true,
limit = 10,
showMore = false,
showMoreLimit = 20,
sortBy = DEFAULT_SORT,
transformItems = ((items) =>
items) as TransformItems<HierarchicalMenuItem>,
} = widgetParams || {};
if (
!attributes ||
!Array.isArray(attributes) ||
attributes.length === 0
) {
throw new Error(
withUsage('The `attributes` option expects an array of strings.')
);
}
if (showMore === true && showMoreLimit <= limit) {
throw new Error(
withUsage('The `showMoreLimit` option must be greater than `limit`.')
);
}
type ThisWidget = Widget<
HierarchicalMenuWidgetDescription & {
widgetParams: typeof widgetParams;
}
>;
// we need to provide a hierarchicalFacet name for the search state
// so that we can always map $hierarchicalFacetName => real attributes
// we use the first attribute name
const [hierarchicalFacetName] = attributes;
let sendEvent: HierarchicalMenuRenderState['sendEvent'];
// Provide the same function to the `renderFn` so that way the user
// has to only bind it once when `isFirstRendering` for instance
let toggleShowMore = () => {};
function cachedToggleShowMore() {
toggleShowMore();
}
let _refine: HierarchicalMenuRenderState['refine'] | undefined;
let isShowingMore = false;
function createToggleShowMore(
renderOptions: RenderOptions,
widget: ThisWidget
) {
return () => {
isShowingMore = !isShowingMore;
widget.render!(renderOptions);
};
}
function getLimit() {
return isShowingMore ? showMoreLimit : limit;
}
function _prepareFacetValues(
facetValues: SearchResults.HierarchicalFacet[]
): HierarchicalMenuItem[] {
return facetValues
.slice(0, getLimit())
.map(({ name: label, path: value, data, ...subValue }) => {
const item: HierarchicalMenuItem = {
...subValue,
label,
value,
data: null,
};
if (Array.isArray(data)) {
item.data = _prepareFacetValues(data);
}
return item;
});
}
return {
$$type: 'ais.hierarchicalMenu',
init(initOptions) {
const { instantSearchInstance } = initOptions;
renderFn(
{
...this.getWidgetRenderState(initOptions),
instantSearchInstance,
},
true
);
},
render(renderOptions) {
const { instantSearchInstance } = renderOptions;
toggleShowMore = createToggleShowMore(renderOptions, this);
renderFn(
{
...this.getWidgetRenderState(renderOptions),
instantSearchInstance,
},
false
);
},
dispose({ state }) {
unmountFn();
return state
.removeHierarchicalFacet(hierarchicalFacetName)
.setQueryParameter('maxValuesPerFacet', undefined);
},
getRenderState(renderState, renderOptions) {
return {
...renderState,
hierarchicalMenu: {
...renderState.hierarchicalMenu,
[hierarchicalFacetName]: this.getWidgetRenderState(renderOptions),
},
};
},
getWidgetRenderState({
results,
state,
createURL,
instantSearchInstance,
helper,
}) {
let items: HierarchicalMenuRenderState['items'] = [];
let canToggleShowMore = false;
// Bind createURL to this specific attribute
function _createURL(facetValue: string) {
return createURL(
state
.resetPage()
.toggleFacetRefinement(hierarchicalFacetName, facetValue)
);
}
if (!sendEvent) {
sendEvent = createSendEventForFacet({
instantSearchInstance,
helper,
attribute: hierarchicalFacetName,
widgetType: this.$$type,
});
}
if (!_refine) {
_refine = function (facetValue) {
sendEvent('click', facetValue);
helper
.toggleFacetRefinement(hierarchicalFacetName, facetValue)
.search();
};
}
if (results) {
const facetValues = results.getFacetValues(hierarchicalFacetName, {
sortBy,
facetOrdering: sortBy === DEFAULT_SORT,
});
const facetItems =
facetValues && !Array.isArray(facetValues) && facetValues.data
? facetValues.data
: [];
// If the limit is the max number of facet retrieved it is impossible to know
// if the facets are exhaustive. The only moment we are sure it is exhaustive
// is when it is strictly under the number requested unless we know that another
// widget has requested more values (maxValuesPerFacet > getLimit()).
// Because this is used for making the search of facets unable or not, it is important
// to be conservative here.
const hasExhaustiveItems =
(state.maxValuesPerFacet || 0) > getLimit()
? facetItems.length <= getLimit()
: facetItems.length < getLimit();
canToggleShowMore =
showMore && (isShowingMore || !hasExhaustiveItems);
items = transformItems(_prepareFacetValues(facetItems));
}
return {
items,
refine: _refine,
canRefine: items.length > 0,
createURL: _createURL,
sendEvent,
widgetParams,
isShowingMore,
toggleShowMore: cachedToggleShowMore,
canToggleShowMore,
};
},
getWidgetUiState(uiState, { searchParameters }) {
const path = searchParameters.getHierarchicalFacetBreadcrumb(
hierarchicalFacetName
);
if (!path.length) {
return uiState;
}
return {
...uiState,
hierarchicalMenu: {
...uiState.hierarchicalMenu,
[hierarchicalFacetName]: path,
},
};
},
getWidgetSearchParameters(searchParameters, { uiState }) {
const values =
uiState.hierarchicalMenu &&
uiState.hierarchicalMenu[hierarchicalFacetName];
if (searchParameters.isHierarchicalFacet(hierarchicalFacetName)) {
const facet = searchParameters.getHierarchicalFacetByName(
hierarchicalFacetName
);
warning(
isEqual(facet.attributes, attributes) &&
facet.separator === separator &&
facet.rootPath === rootPath,
'Using Breadcrumb and HierarchicalMenu on the same facet with different options overrides the configuration of the HierarchicalMenu.'
);
}
const withFacetConfiguration = searchParameters
.removeHierarchicalFacet(hierarchicalFacetName)
.addHierarchicalFacet({
name: hierarchicalFacetName,
attributes,
separator,
rootPath,
showParentLevel,
});
const currentMaxValuesPerFacet =
withFacetConfiguration.maxValuesPerFacet || 0;
const nextMaxValuesPerFacet = Math.max(
currentMaxValuesPerFacet,
showMore ? showMoreLimit : limit
);
const withMaxValuesPerFacet =
withFacetConfiguration.setQueryParameter(
'maxValuesPerFacet',
nextMaxValuesPerFacet
);
if (!values) {
return withMaxValuesPerFacet.setQueryParameters({
hierarchicalFacetsRefinements: {
...withMaxValuesPerFacet.hierarchicalFacetsRefinements,
[hierarchicalFacetName]: [],
},
});
}
return withMaxValuesPerFacet.addHierarchicalFacetRefinement(
hierarchicalFacetName,
values.join(separator)
);
},
};
};
};
export default connectHierarchicalMenu; | the_stack |
import type { IIndexable, IServiceLocator } from '@aurelia/kernel';
import type { Scope } from './observation/binding-context';
import type { CollectionLengthObserver, CollectionSizeObserver } from './observation/collection-length-observer';
export interface IBinding {
interceptor: this;
readonly locator: IServiceLocator;
readonly $scope?: Scope;
readonly isBound: boolean;
$bind(flags: LifecycleFlags, scope: Scope): void;
$unbind(flags: LifecycleFlags): void;
}
export type InterceptorFunc<TInput = unknown, TOutput = unknown> = (value: TInput) => TOutput;
/*
* Note: the oneTime binding now has a non-zero value for 2 reasons:
* - plays nicer with bitwise operations (more consistent code, more explicit settings)
* - allows for potentially having something like BindingMode.oneTime | BindingMode.fromView, where an initial value is set once to the view but updates from the view also propagate back to the view model
*
* Furthermore, the "default" mode would be for simple ".bind" expressions to make it explicit for our logic that the default is being used.
* This essentially adds extra information which binding could use to do smarter things and allows bindingBehaviors that add a mode instead of simply overwriting it
*/
export enum BindingMode {
oneTime = 0b0001,
toView = 0b0010,
fromView = 0b0100,
twoWay = 0b0110,
default = 0b1000
}
export const enum LifecycleFlags {
none = 0b0000_000_00_0,
// Bitmask for flags that need to be stored on a binding during $bind for mutation
// callbacks outside of $bind
persistentBindingFlags = 0b1111_000_00_1,
allowParentScopeTraversal = 0b0001_000_00_0,
observeLeafPropertiesOnly = 0b0010_000_00_0,
targetObserverFlags = 0b1100_000_00_1,
noFlush = 0b0100_000_00_0,
persistentTargetObserverQueue = 0b1000_000_00_0,
bindingStrategy = 0b0000_000_00_1,
isStrictBindingStrategy = 0b0000_000_00_1,
fromBind = 0b0000_000_01_0,
fromUnbind = 0b0000_000_10_0,
mustEvaluate = 0b0000_001_00_0,
isTraversingParentScope = 0b0000_010_00_0,
dispose = 0b0000_100_00_0,
}
export interface IConnectable {
observe(obj: object, key: PropertyKey): void;
observeCollection(obj: Collection): void;
subscribeTo(subscribable: ISubscribable | ICollectionSubscribable): void;
}
/** @internal */
export const enum SubscriberFlags {
None = 0,
Subscriber0 = 0b0001,
Subscriber1 = 0b0010,
Subscriber2 = 0b0100,
SubscribersRest = 0b1000,
Any = 0b1111,
}
export enum DelegationStrategy {
none = 0,
capturing = 1,
bubbling = 2,
}
export interface IBatchable {
flushBatch(flags: LifecycleFlags): void;
}
export interface ISubscriber<TValue = unknown> {
handleChange(newValue: TValue, previousValue: TValue, flags: LifecycleFlags): void;
}
export interface ICollectionSubscriber {
handleCollectionChange(indexMap: IndexMap, flags: LifecycleFlags): void;
}
export interface ISubscribable {
subscribe(subscriber: ISubscriber): void;
unsubscribe(subscriber: ISubscriber): void;
}
export interface ICollectionSubscribable {
subscribe(subscriber: ICollectionSubscriber): void;
unsubscribe(subscriber: ICollectionSubscriber): void;
}
/**
* An interface describing the contract of a subscriber list,
* with the ability to propagate values to those subscribers
*/
export interface ISubscriberRecord<T extends ISubscriber | ICollectionSubscriber> {
readonly count: number;
add(subscriber: T): boolean;
has(subscriber: T): boolean;
remove(subscriber: T): boolean;
any(): boolean;
notify(value: unknown, oldValue: unknown, flags: LifecycleFlags): void;
notifyCollection(indexMap: IndexMap, flags: LifecycleFlags): void;
}
/**
* An internal interface describing the implementation of a ISubscribable of Aurelia that supports batching
*
* This is usually mixed into a class via the import `subscriberCollection` import from Aurelia.
* The `subscriberCollection` import can be used as either a decorator, or a function call.
*/
export interface ISubscriberCollection extends ISubscribable {
[key: number]: LifecycleFlags;
/**
* The backing subscriber record for all subscriber methods of this collection
*/
readonly subs: ISubscriberRecord<ISubscriber>;
}
/**
* An internal interface describing the implementation of a ICollectionSubscribable of Aurelia that supports batching
*
* This is usually mixed into a class via the import `subscriberCollection` import from Aurelia.
* The `subscriberCollection` import can be used as either a decorator, or a function call.
*/
export interface ICollectionSubscriberCollection extends ICollectionSubscribable {
[key: number]: LifecycleFlags;
/**
* The backing subscriber record for all subscriber methods of this collection
*/
readonly subs: ISubscriberRecord<ICollectionSubscriber>;
}
/**
* A collection (array, set or map)
*/
export type Collection = unknown[] | Set<unknown> | Map<unknown, unknown>;
export const enum CollectionKind {
indexed = 0b1000,
keyed = 0b0100,
array = 0b1001,
map = 0b0110,
set = 0b0111,
}
export type LengthPropertyName<T> =
T extends unknown[] ? 'length' :
T extends Set<unknown> ? 'size' :
T extends Map<unknown, unknown> ? 'size' :
never;
export type CollectionTypeToKind<T> =
T extends unknown[] ? CollectionKind.array | CollectionKind.indexed :
T extends Set<unknown> ? CollectionKind.set | CollectionKind.keyed :
T extends Map<unknown, unknown> ? CollectionKind.map | CollectionKind.keyed :
never;
export type CollectionKindToType<T> =
T extends CollectionKind.array ? unknown[] :
T extends CollectionKind.indexed ? unknown[] :
T extends CollectionKind.map ? Map<unknown, unknown> :
T extends CollectionKind.set ? Set<unknown> :
T extends CollectionKind.keyed ? Set<unknown> | Map<unknown, unknown> :
never;
export type ObservedCollectionKindToType<T> =
T extends CollectionKind.array ? unknown[] :
T extends CollectionKind.indexed ? unknown[] :
T extends CollectionKind.map ? Map<unknown, unknown> :
T extends CollectionKind.set ? Set<unknown> :
T extends CollectionKind.keyed ? Map<unknown, unknown> | Set<unknown> :
never;
export const enum AccessorType {
None = 0b0_0000_0000,
Observer = 0b0_0000_0001,
Node = 0b0_0000_0010,
// misc characteristic of accessors/observers when update
//
// by default, everything is synchronous
// except changes that are supposed to cause reflow/heavy computation
// an observer can use this flag to signal binding that don't carelessly tell it to update
// queue it instead
// todo: https://gist.github.com/paulirish/5d52fb081b3570c81e3a
// todo: https://csstriggers.com/
Layout = 0b0_0000_0100,
// by default, everything is an object
// eg: a property is accessed on an object
// unless explicitly not so
Primtive = 0b0_0000_1000,
Array = 0b0_0001_0010,
Set = 0b0_0010_0010,
Map = 0b0_0100_0010,
}
/**
* Basic interface to normalize getting/setting a value of any property on any object
*/
export interface IAccessor<TValue = unknown> {
type: AccessorType;
getValue(obj?: object, key?: PropertyKey): TValue;
setValue(newValue: TValue, flags: LifecycleFlags, obj?: object, key?: PropertyKey): void;
}
/**
* An interface describing a standard contract of an observer in Aurelia binding & observation system
*/
export interface IObserver extends IAccessor, ISubscribable {}
export type AccessorOrObserver = (IAccessor | IObserver) & {
doNotCache?: boolean;
};
/**
* An array of indices, where the index of an element represents the index to map FROM, and the numeric value of the element itself represents the index to map TO
*
* The deletedItems property contains the items (in case of an array) or keys (in case of map or set) that have been deleted.
*/
export type IndexMap = number[] & {
deletedItems: number[];
isIndexMap: true;
};
export function copyIndexMap(
existing: number[] & { deletedItems?: number[] },
deletedItems?: number[],
): IndexMap {
const { length } = existing;
const arr = Array(length) as IndexMap;
let i = 0;
while (i < length) {
arr[i] = existing[i];
++i;
}
if (deletedItems !== void 0) {
arr.deletedItems = deletedItems.slice(0);
} else if (existing.deletedItems !== void 0) {
arr.deletedItems = existing.deletedItems.slice(0);
} else {
arr.deletedItems = [];
}
arr.isIndexMap = true;
return arr;
}
export function createIndexMap(length: number = 0): IndexMap {
const arr = Array(length) as IndexMap;
let i = 0;
while (i < length) {
arr[i] = i++;
}
arr.deletedItems = [];
arr.isIndexMap = true;
return arr;
}
export function cloneIndexMap(indexMap: IndexMap): IndexMap {
const clone = indexMap.slice() as IndexMap;
clone.deletedItems = indexMap.deletedItems.slice();
clone.isIndexMap = true;
return clone;
}
export function isIndexMap(value: unknown): value is IndexMap {
return value instanceof Array && (value as IndexMap).isIndexMap === true;
}
export interface IArrayIndexObserver extends IObserver {
owner: ICollectionObserver<CollectionKind.array>;
}
/**
* Describes a type that specifically tracks changes in a collection (map, set or array)
*/
export interface ICollectionChangeTracker<T extends Collection> {
collection: T;
indexMap: IndexMap;
}
/**
* An observer that tracks collection mutations and notifies subscribers (either directly or in batches)
*/
export interface ICollectionObserver<T extends CollectionKind> extends
ICollectionChangeTracker<CollectionKindToType<T>>,
ICollectionSubscribable {
type: AccessorType;
collection: ObservedCollectionKindToType<T>;
getLengthObserver(): T extends CollectionKind.array ? CollectionLengthObserver : CollectionSizeObserver;
notify(): void;
}
export type CollectionObserver = ICollectionObserver<CollectionKind>;
export interface IBindingContext {
[key: string]: any;
}
export interface IOverrideContext {
[key: string]: unknown;
readonly bindingContext: IBindingContext;
}
export type IObservable<T = IIndexable> = T & {
$observers?: IIndexable<{}, AccessorOrObserver>;
}; | the_stack |
import { Parser } from 'interweave';
import { createExpectedToken, parentConfig, TOKEN_LOCATIONS } from 'interweave/test';
import { URL_PATTERN } from '../src/constants';
import UrlMatcher from '../src/UrlMatcher';
interface URLParams {
url: string;
scheme?: string | null;
auth?: string;
host?: string;
path?: string;
port?: string;
query?: string;
fragment?: string;
}
// Borrowed from: https://github.com/Sporkmonger/Addressable/blob/master/spec/addressable/uri_spec.rb
const VALID_URLS: URLParams[] = [
{ url: 'example.com', scheme: null, host: 'example.com' },
{ url: 'www.example.com', scheme: null, host: 'www.example.com' },
{ url: 'http://under_score.example.com/', host: 'under_score.example.com', path: '/' },
{ url: 'http://example.com/', path: '/' },
{ url: 'http://example.uk/', path: '/', host: 'example.uk' },
{ url: 'http://example.co.uk/', path: '/', host: 'example.co.uk' },
{ url: 'http://example.com/path', path: '/path' },
{ url: 'http://example.com/path/to/resource/', path: '/path/to/resource/' },
{ url: 'http://example.com/?q=string', path: '/', query: '?q=string' },
{ url: 'http://example.com/?x=1&y=2', path: '/', query: '?x=1&y=2' },
{ url: 'http://example.com:80/', path: '/', port: '80' },
{ url: 'http://example.com:8080/', path: '/', port: '8080' },
{
url: 'http://example.com:8080/path?query=value#fragment',
port: '8080',
path: '/path',
query: '?query=value',
fragment: '#fragment',
},
{
url: 'http://example.com/path/to/resource?query=x#fragment',
path: '/path/to/resource',
query: '?query=x',
fragment: '#fragment',
},
{ url: 'http://example.com/file.txt', path: '/file.txt' },
{
url: 'https://ftp.is.co.za/rfc/rfc1808.txt',
scheme: 'https://',
host: 'ftp.is.co.za',
path: '/rfc/rfc1808.txt',
},
{ url: 'http://www.ietf.org/rfc/rfc2396.txt', host: 'www.ietf.org', path: '/rfc/rfc2396.txt' },
{
url: 'http://www.w3.org/pub/WWW/TheProject.html',
host: 'www.w3.org',
path: '/pub/WWW/TheProject.html',
},
{ url: 'http://example.com?#', query: '?', fragment: '#' },
{ url: 'http://example.com/~smith/', path: '/~smith/' },
{ url: 'http://example.com/%E8', path: '/%E8' },
{ url: 'http://example.com/path%2Fsegment/', path: '/path%2Fsegment/' },
{ url: 'http://example.com/?%F6', path: '/', query: '?%F6' },
{ url: 'HTTP://example.com/#%F6', scheme: 'HTTP://', path: '/', fragment: '#%F6' },
{ url: 'http://example.com/%C3%87', path: '/%C3%87' },
{ url: 'http://example.com/%2E/', path: '/%2E/' },
{ url: 'http://www.example.com//', host: 'www.example.com', path: '//' },
{ url: 'http://example.com/x;y/', path: '/x;y/' },
{ url: 'http://example.com/search?q=Q%26A', path: '/search', query: '?q=Q%26A' },
{ url: 'http://example.com/?&x=b', path: '/', query: '?&x=b' },
{ url: "http://example.com/?q='one;two'&x=1", path: '/', query: "?q='one;two'&x=1" },
{ url: 'http://example.com/?&&x=b', path: '/', query: '?&&x=b' },
{ url: 'http://example.com/?q=a&&x=b', path: '/', query: '?q=a&&x=b' },
{ url: 'http://example.com/?q&&x=b', path: '/', query: '?q&&x=b' },
{ url: 'http://example.com/?q=a+b', path: '/', query: '?q=a+b' },
{ url: 'http://example.com/?q=a%2bb', path: '/', query: '?q=a%2bb' },
{
url: 'http://example.com/?v=%7E&w=%&x=%25&y=%2B&z=C%CC%A7',
path: '/',
query: '?v=%7E&w=%&x=%25&y=%2B&z=C%CC%A7',
},
{ url: 'http://example.com/sound%2bvision', path: '/sound%2bvision' },
{ url: 'http://example.com/?q=', path: '/', query: '?q=' },
{ url: 'http://example.com/?date=2017/01/01', path: '/', query: '?date=2017/01/01' },
{ url: 'http://example.com/?route=foo\\bar\\baz', path: '/', query: '?route=foo\\bar\\baz' },
{ url: 'http://example.com/?one=1&two=2&three=3', path: '/', query: '?one=1&two=2&three=3' },
{ url: 'http://example.com/?one=1=uno&two=2=dos', path: '/', query: '?one=1=uno&two=2=dos' },
{ url: 'http://example.com/?one[two][three]=four', path: '/', query: '?one[two][three]=four' },
{
url: 'http://example.com/?one[two][three]=four&one[two][five]=six',
path: '/',
query: '?one[two][three]=four&one[two][five]=six',
},
{
url: 'http://example.com/?one[two][three][]=four&one[two][three][]=five',
path: '/',
query: '?one[two][three][]=four&one[two][three][]=five',
},
{
url: 'http://example.com/?one[two][three][0]=four&one[two][three][1]=five',
path: '/',
query: '?one[two][three][0]=four&one[two][three][1]=five',
},
{
url: 'http://example.com/?one[two][three][1]=four&one[two][three][0]=five',
path: '/',
query: '?one[two][three][1]=four&one[two][three][0]=five',
},
{
url: 'http://example.com/?one[two][three][2]=four&one[two][three][1]=five',
path: '/',
query: '?one[two][three][2]=four&one[two][three][1]=five',
},
{ url: 'http://example.com/?one.two.three=four', path: '/', query: '?one.two.three=four' },
{
url: 'http://example.com/?one.two.three=four&one.two.five=six',
path: '/',
query: '?one.two.three=four&one.two.five=six',
},
{ url: 'http://www.xn--8ws00zhy3a.com/', path: '/', host: 'www.xn--8ws00zhy3a.com' },
{ url: 'http://user:@example.com', auth: 'user:@' },
{ url: 'http://:pass@example.com', auth: ':pass@' },
{ url: 'http://:@example.com', auth: ':@' },
{
url: 'http://user:pass@example.com/path/to/resource?query=x#fragment',
auth: 'user:pass@',
path: '/path/to/resource',
query: '?query=x',
fragment: '#fragment',
},
// I feel like these should be invalid
{ url: 'http://:@example.com/', auth: ':@', path: '/' },
{
url: 'http://example.com/indirect/path/./to/../resource/',
path: '/indirect/path/./to/../resource/',
},
];
const INVALID_URLS = [
{ url: 'someword' },
{ url: 'http://' },
{ url: 'http://foo' },
{ url: 'http://example.com./' },
{ url: 'http://example.com:%38%30/' },
{ url: 'http://www.詹姆斯.com/' },
{ url: 'http://www.詹姆斯.com/atomtests/iri/詹.html' },
{ url: 'http:example.com' },
{ url: 'https:example.com/' },
{ url: 'http://@example.com/' },
{ url: 'HTTP://example.com.:%38%30/%70a%74%68?a=%31#1%323' },
{ url: 'http://example.com/(path)/' },
// Sorry, no periods
{ url: 'http://example.com/..', path: '/..' },
{ url: 'http://example.com/../..', path: '/../..' },
// This matcher doesn't support IPs
{ url: '192.0.2.16' },
{ url: 'https://192.0.2.16?query' },
{ url: '192.0.2.16:8000/path' },
{ url: 'http://[3ffe:1900:4545:3:200:f8ff:fe21:67cf]/' },
// Or localhosts
{ url: 'localhost/' },
{ url: 'http://localhost/' },
// Or other protocols
{ url: 'ftp://domain.com' },
{ url: 'file://domain.com' },
{ url: 'sftp://domain.com' },
];
describe('matchers/UrlMatcher', () => {
let matcher = new UrlMatcher('url');
const pattern = new RegExp(`^${URL_PATTERN.source}$`, 'i');
beforeEach(() => {
matcher = new UrlMatcher('url');
});
describe('does match valid url:', () => {
VALID_URLS.forEach((urlParams) => {
const { url, ...params } = urlParams;
it(`${url}`, () => {
// @ts-expect-error
const expected: Partial<RegExpMatchArray> = [
url,
// eslint-disable-next-line jest/no-if
params.scheme === null ? undefined : params.scheme || 'http://',
params.auth,
// eslint-disable-next-line jest/no-if
typeof params.host === 'undefined' ? 'example.com' : params.host,
params.port,
params.path,
params.query,
params.fragment,
];
expected.index = 0;
expected.input = url;
expect(url.match(pattern)).toEqual(expected);
});
});
});
describe('doesnt match invalid url:', () => {
INVALID_URLS.forEach((urlParams) => {
const { url } = urlParams;
it(`${url}`, () => {
expect(url.match(pattern)).toBeNull();
});
});
});
describe('matches all urls in a string', () => {
const parser = new Parser('', {}, [matcher]);
const createUrl = (urlParams: URLParams, key: number) => {
const { url, ...params } = urlParams;
return matcher.replaceWith(url, {
children: url,
url,
urlParts: {
host: 'example.com',
path: '',
query: '',
fragment: '',
...params,
scheme: params.scheme ? params.scheme.replace('://', '') : 'http',
auth: params.auth ? params.auth.slice(0, -1) : '',
port: params.port || '',
},
key,
});
};
VALID_URLS.forEach((urlParams) => {
TOKEN_LOCATIONS.forEach((location, i) => {
it(`for: ${urlParams.url} - ${location}`, () => {
parser.keyIndex = -1; // Reset for easier testing
const tokenString = location.replace(/{token}/g, urlParams.url);
const actual = parser.applyMatchers(tokenString, parentConfig);
if (i === 0) {
expect(actual).toBe(createExpectedToken(urlParams, createUrl, 0));
} else {
expect(actual).toEqual(createExpectedToken(urlParams, createUrl, i));
}
});
});
});
});
describe('replaceWith()', () => {
const props = {
children: '',
url: 'http://domain.foo',
urlParts: {
auth: '',
scheme: 'http',
fragment: '',
host: 'domain.foo',
path: '',
port: '',
query: '',
},
};
it('can disable validation for an unsupported TLD', () => {
matcher.options.validateTLD = false;
expect(matcher.replaceWith('http://domain.foo', props)).not.toBe('http://domain.foo');
});
it('supports a custom list of TLDs', () => {
matcher.options.customTLDs = ['foo'];
expect(matcher.replaceWith('http://domain.foo', props)).not.toBe('http://domain.foo');
});
it('supports prefixed TLDs', () => {
expect(
matcher.replaceWith('http://domain.co.uk', {
children: 'http://domain.co.uk',
url: 'http://domain.co.uk',
urlParts: {
...props.urlParts,
scheme: 'http',
host: 'domain.co.uk',
},
}),
).not.toBe('http://domain.co.uk');
});
});
describe('match()', () => {
it('returns null for invalid match', () => {
expect(matcher.match('notaurl')).toBeNull();
});
it('returns null for unsupported TLD', () => {
expect(matcher.match('http://domain.foo')).toBeNull();
expect(matcher.match('customer.first_name')).toBeNull();
expect(matcher.match('user.alias')).toBeNull();
});
it('returns invalid match for emails that look like URLs', () => {
expect(matcher.match('user.1@google.com')).toEqual(expect.objectContaining({ valid: false }));
});
it('returns object for valid match', () => {
expect(
matcher.match('http://user:pass@domain.com:8080/some/path?with=query#fragment'),
).toEqual({
index: 0,
length: 62,
match: 'http://user:pass@domain.com:8080/some/path?with=query#fragment',
url: 'http://user:pass@domain.com:8080/some/path?with=query#fragment',
urlParts: {
scheme: 'http',
auth: 'user:pass',
host: 'domain.com',
port: '8080',
path: '/some/path',
query: '?with=query',
fragment: '#fragment',
},
valid: true,
void: false,
});
});
});
}); | the_stack |
import { OptgroupProps } from './block-kit/composition/Optgroup'
import { OptionProps } from './block-kit/composition/Option'
import { ButtonProps } from './block-kit/elements/Button'
import { SelectProps } from './block-kit/elements/Select'
import { AutoFocusibleIntrinsicProps } from './block-kit/elements/utils'
import { TextareaProps } from './block-kit/input/Textarea'
import { DividerProps } from './block-kit/layout/Divider'
import { HeaderProps } from './block-kit/layout/Header'
import { ImageProps } from './block-kit/layout/Image'
import { InputProps } from './block-kit/layout/Input'
import { SectionProps } from './block-kit/layout/Section'
export interface BuiltInComponent<P extends {}> extends JSXSlack.FC<P> {
readonly $$jsxslackComponent: { name: string } & Record<any, any>
}
/**
* The helper function to cast the output type from JSX element to `any`. Just
* returns the passed value with no operations.
*
* This function is provided for TypeScript user and migrated user from
* jsx-slack v1.
*
* @param element - JSX element
* @return The passed JSX element with no-ops
*/
export function JSXSlack(element: JSXSlack.JSX.Element): any {
return element
}
/** @internal */
export const createElementInternal = (
type: JSXSlack.FC | keyof JSXSlack.JSX.IntrinsicElements,
props: JSXSlack.Props | null = null,
...children: JSXSlack.ChildElement[]
): JSXSlack.JSX.Element | null => {
let rendered: JSXSlack.Node | null = Object.create(null)
if (typeof type === 'function') {
const p = { ...(props || {}) }
if (children.length === 1) [p.children] = children
else if (children.length > 1) p.children = children
rendered = type(p)
}
if (rendered && typeof rendered === 'object') {
// Apply JSON normalization
for (const key of Object.keys(rendered)) {
if (rendered[key] === undefined) delete rendered[key]
}
if (!rendered.$$jsxslack) {
// Children in metadata must be an array
let metaChildren = children
if (children.length === 0) {
// Fallback to children props
const { children: propsChildren } = props || {}
if (propsChildren !== undefined) metaChildren = [].concat(propsChildren)
}
Object.defineProperty(rendered, '$$jsxslack', {
value: { type, props, children: metaChildren },
})
}
}
return rendered
}
/**
* Create the component for JSON payload building with jsx-slack.
*
* The passed functional component has to return JSON object or `null`, to build
* JSON payload for Slack. Unlike a simple functional component defined by
* JavaScript function, the output would be always preserved in JSON even if it
* was an array.
*
* @remarks
* `createComponent()` is an internal helper to create built-in components for
* jsx-slack. Typically user must use a simple function definition of JavaScript
* to create the functional component.
*
* @internal
* @param name - Component name for showing in debug log
* @param component - The functional component to turn into jsx-slack component
* @param meta - An optional metadata for jsx-slack component
* @return A created jsx-slack component
*/
export const createComponent = <P extends {}, O extends object>(
name: string,
component: (props: JSXSlack.Props<P>) => O | null,
meta: Record<any, any> = {}
): BuiltInComponent<P> =>
Object.defineProperty(component as any, '$$jsxslackComponent', {
value: Object.freeze(
Object.defineProperty({ ...meta }, 'name', {
value: name || '[Anonymous component]',
enumerable: true,
})
),
})
/** @internal */
export const FragmentInternal = createComponent<
{ children: JSXSlack.ChildElements },
JSXSlack.ChildElement[]
>('Fragment', ({ children }) =>
// Should return array's shallow copy to remove metadata from array
([] as JSXSlack.ChildElement[]).concat(children)
)
/**
* Verify the passed function is a jsx-slack component.
*
* @internal
* @param fn - A function to verify
* @return `true` if the passed object was a jsx-slack component., otherwise
* `false`
*/
export const isValidComponent = <T = any>(
fn: unknown
): fn is BuiltInComponent<T> =>
typeof fn === 'function' &&
!!Object.prototype.hasOwnProperty.call(fn, '$$jsxslackComponent')
/**
* Verify the passed object is a jsx-slack element created from built-in
* component.
*
* @internal
* @param element - An object to verify
* @param component - The optional component to match while verifying
* @return `true` if the passed object was a jsx-slack element created from
* built-in component, otherwise `false`
*/
export const isValidElementFromComponent = (
obj: unknown,
component?: JSXSlack.FunctionalComponent<any>
): obj is JSXSlack.JSX.Element =>
JSXSlack.isValidElement(obj) &&
isValidComponent(obj.$$jsxslack.type) &&
(!component || obj.$$jsxslack.type === component)
/**
* Clean up hidden meta value for jsx-slack from object.
*
* If the built-in component has nested JSX output such as alias, a hidden
* metadata can reference an internal JSX from the public partial object. An
* internal would not matter for jsx-slack user, so the error message displaying
* private JSX info may confuse.
*
* It just re-assigns public objects into new object, but this helper makes
* clear its purpose.
*
* @internal
* @param element - The object with meta value for jsx-slack
* @return The object without meta value
*/
export const cleanMeta = <T extends object>(
element: T
): T extends Array<infer R> ? Array<R> : Omit<T, keyof JSXSlack.Node> =>
(Array.isArray(element) ? [...element] : { ...element }) as any
export namespace JSXSlack {
interface StringLike {
toString: () => string
}
/** A element allowed as a child. */
export type ChildElement =
| Node
| string
| StringLike
| ChildElement[] // as fragment elements (WARN: Recrusive type has required TypeScript >= 3.7)
| boolean // will remove while normalization
| null // will remove while normalization
| undefined // will remove while normalization
/** Elements allowed as children. */
export type ChildElements = ChildElement | ChildElement[]
/** Similar to `ChildElement`, but excluded string and string-like object. */
export type ChildNode = Node | ChildNode[] | boolean | null | undefined
/** Similar to `ChildElements`, but excluded string and string-like object. */
export type ChildNodes = ChildNode | ChildNode[]
type FilteredChild = Node | string | StringLike
type MapCallbackFn<T> = (
this: FilteredChild | null,
child: FilteredChild | null,
index: number
) => T
export type Props<P = any> = { children?: ChildElements } & P
export type FunctionalComponent<P extends {} = {}> = (
props: Props<P>
) => Node | null
export type FunctionComponent<P extends {} = {}> = FunctionalComponent<P>
export type FC<P extends {} = {}> = FunctionalComponent<P>
export type VoidFunctionalComponent<P extends {} = Record<any, never>> = (
props: P
) => Node | null
export type VoidFunctionComponent<P extends {} = Record<any, never>> =
VoidFunctionalComponent<P>
export type VFC<P extends {} = Record<any, never>> =
VoidFunctionalComponent<P>
export interface Node<P extends {} = any> {
/**
* @internal
* **⚠️ This is an internal member of jsx-slack. ⚠️** Not recommend to use.
*/
readonly $$jsxslack: {
type: FC<P> | string
props: Props<P>
children: ChildElement[]
}
}
/**
* Verify the passed object is a jsx-slack element.
*
* @param element - An object to verify
* @return `true` if the passed object was a jsx-slack element, otherwise
* `false`
*/
export const isValidElement = (obj: unknown): obj is JSXSlack.JSX.Element =>
typeof obj === 'object' &&
!!obj &&
!!Object.prototype.hasOwnProperty.call(obj, '$$jsxslack')
/**
* Create and return a new jsx-slack element of the given type.
*
* The `type` argument can be either a component function, a tag name string
* such as `'strong'` or `'em'`, and a fragment (`JSXSlack.Fragment`).
*
* **NOTE**: _You won't typically invoke this directly if you are using JSX._
*
* @param type - A component function, fragment, or intrinsic HTML tag name
* @param props - Property values to pass into the element for creation
* @param children - Children elements of a new jsx-slack element
* @return A new jsx-slack element
*/
export const createElement = createElementInternal
/** An alias into `JSXSlack.createElement`. */
export const h = createElementInternal
/**
* Group a list of JSX elements.
*
* Typically the component for jsx-slack should return a single JSX element.
* Wrapping multiple elements in `JSXSlack.Fragment` lets you return a list of
* children.
*/
export const Fragment = FragmentInternal
const flatChildren = (children: ChildElement[]) =>
children.reduce((reduced: Array<FilteredChild | null>, child) => {
if (Array.isArray(child) && !isValidElementFromComponent(child)) {
reduced.push(...flatChildren(child))
} else if (child == null || child === true || child === false) {
reduced.push(null)
} else {
reduced.push(child)
}
return reduced
}, [])
/**
* Make flatten JSX elements into an array consited by allowed children and
* `null`.
*
* @remarks
* This function does not traverse children of the built-in component,
* included `JSXSlack.Fragment`.
*
* @internal
* @param children - The target child or children
*/
const flat = (children: ChildElements) => flatChildren([children])
/**
* Provide utilities for dealing with the `props.children` opaque data
* structure.
*/
export const Children = Object.freeze({
/**
* Return the total number of elements in `children`.
*
* It would be same as the number of times `JSXSlack.Children.map()` would
* invoke the callback.
*
* @param children - The target element(s) to count
* @return The total number of elements in the passed children
*/
count: (children: ChildElements): number =>
children == null ? 0 : flat(children).length,
/**
* Like `JSXSlack.Children.map()`, but no return value.
*
* @param children - The target element(s) to traverse
* @param callbackFn - Callback function
*/
forEach: (children: ChildElements, callbackFn: MapCallbackFn<void>) => {
Children.map(children, callbackFn)
},
/**
* Invoke callback function on every immediate child in `children`.
*
* The callback function allows up to 2 arguments compatible with
* `Array.prototype.map()`, and `this` will be a traversed child. The
* callback can return any value for transforming, or the nullish value for
* to skip mapping.
*
* @remarks
* When the passed `children` is `null` or `undefined`, this function
* returns the passed value instead of an array as it is.
*
* If `JSXSlack.Fragment` was passed as `children`, it will be treated as _a
* single child_. The callback won't invoke with every child of the
* fragment.
*
* @param children - The target element(s) to traverse
* @param callbackFn - Callback function
* @return An array of the value returned by callback function, or nullish
* value when passed `null` or `undefined`.
*/
map: <T>(children: ChildElements, callbackFn: MapCallbackFn<T>) => {
if (children == null) return children
return flat(children).reduce(
(reduced: Exclude<T, null | undefined>[], child, idx) => {
const ret: any = callbackFn.call(child, child, idx)
if (ret != null) reduced.push(ret)
return reduced
},
[]
)
},
/**
* Verify whether `children` has an only one child of jsx-slack element and
* return it. Otherwise, throw an error.
*
* @remarks
* Even if passed a single jsx-slack element, this method may throw an error
* when the component returned `null` or any primitive value such as string,
* number, etc.
*
* @param children - The target element(s)
* @return A single jsx-slack element if verified
* @throws Will throw an error if `children` is not a single JSX element
*/
only: (children: ChildElements): JSX.Element => {
if (isValidElement(children)) return children
throw new Error(
'JSXSlack.Children.only expected to receive a single JSXSlack element child.'
)
},
/**
* Return an array made flatten the `children` opaque data structure.
*
* Useful for manipulating or re-ordering collection of children passed to
* the component.
*
* @remarks
* If an array in the children could be a subset of JSON payload, such as a
* returned array from the built-in component, it would not be flatten.
*
* @param children - The target element(s)
* @return A flatten array consisted of JSX elements
*/
toArray: (children: ChildElements): FilteredChild[] =>
flat(children).reduce((reduced: FilteredChild[], child) => {
if (child == null) return reduced
// Make flatten fragment's children
if (isValidElementFromComponent(child, Fragment))
return reduced.concat(Children.toArray([...(child as any)]))
return [...reduced, child]
}, []),
})
let currentExactMode = false
/**
* Set the state of the exact mode, to enable or disable forcible styling in
* rendered Slack mrkdwn.
*
* Some special characters to style text will work only in the break of words.
* By turning the exact mode on, jsx-slack will insert zero-width space around
* special chars generated by HTML-like elements (`<b>`, `<i>`, `<s>`, etc),
* to enable styling forcibly.
*
* @remarks
* __Exact mode is the last resort__, because zero-width space included text
* may confuse a reader when editing the copied message. _You should consider
* to deal with inserting whitespaces around the styled text manually instead
* of turning on exact mode._
*
* @param mode - A boolean value to indicate whether turning on exact mode
* @return The current state of exact mode
*/
export const exactMode = (mode?: boolean) => {
if (mode !== undefined) currentExactMode = mode
return currentExactMode
}
export namespace JSX {
export interface Element extends Node {}
export interface IntrinsicElements {
/** An HTML-compatible alias into `<Header>` layout block. */
header: HeaderProps
/** An HTML-compatible alias into `<Divider>` layout block. */
hr: DividerProps
/**
* A HTML-compatible alias into `<Image>` layout block and block element.
*/
img: ImageProps
/** A HTML-compatible alias into `<Section>` layout block. */
section: SectionProps
/** A HTML-compatible alias into `<Button>` block element. */
button: ButtonProps
/** A HTML-compatible alias into `<Textarea>` input component. */
textarea: TextareaProps & AutoFocusibleIntrinsicProps
/**
* A HTML-compatible alias into `<Input>` layout block, input component,
* and helpers for some surfaces.
*/
input: InputProps & AutoFocusibleIntrinsicProps
/**
* A HTML-compatible alias into `<Optgroup>` component for composition
* object.
*/
optgroup: OptgroupProps
/**
* A HTML-compatible alias into `<Option>` component for composition
* object.
*/
option: OptionProps
/**
* A HTML-compatible alias into `<Select>` block element and input
* component.
*/
select: SelectProps & AutoFocusibleIntrinsicProps
// ----------- HTML-like elements -----------
/**
* Creates a hyperlink to the external web pages, email addresses, public
* Slack channels, and Slack users with mention.
*
* ### Slack-specifics
*
* Keep in mind that the custom contents in children of `<a>` tag cannot
* render when using Slack-specific features. Slack will fill the content
* by own.
*
* In following cases, `<a>` tag would accept the void element `<a />`
* unlike HTML specification.
*
* #### Link to public Slack channel
*
* jsx-slack can create [a link to the Slack channel](https://api.slack.com/reference/surfaces/formatting#linking-channels)
* by specifying hash-prefixed ID for the public channel:
* `<a href="#C0123456789" />` _(Notice that it is not the channel name)_
*
* Slack's link syntax _only accepts the public channel_. Channels in
* private won't make a link.
*
* #### Mention to user and user group
*
* You can send a mention the specified user by ID through similar syntax
* `<a href="@U0123456789" />`.
*
* jsx-slack can detect atmark-prefixed user ID `@U`, the user ID for
* Enterprise Grid `@W`, and the user-group ID `@S`.
*
* #### Special mentions
*
* You can also use these [special mentions](https://api.slack.com/reference/surfaces/formatting#special-mentions)
* to send widely (but typically they should be used carefully):
*
* - `<a href="@here" />`
* - `<a href="@channel" />`
* - `<a href="@everyone" />`
*/
a: {
children?: ChildElements
/**
* Either one of the URL for the created hyperlink, hash-prefixed public
* channel ID, or atmark-prefixed ID of the target to mention.
*/
href: string
}
/**
* Style the content with bold through generating the text surrounded by
* `*`.
*
* @remarks
* Depending on contents around the element, styling may not apply
* correctly due to the restriction of mrkdwn that _special character will
* only work in a word boundary_. Make sure that the element is surrounded
* by word boundaries (e.g. Whitespaces).
*
* Not recommended but you can also deal it with turning on exact mode via
* `JSXSlack.exactMode(true)`.
*/
b: {}
/**
* Create the block for the quotation. Slack renders the content with the
* gray line on the left.
*/
blockquote: {}
/**
* Add a line-break.
*
* Any break characters in JSX are ignored and collapsed to single
* whitespace so you should always use `<br />` for line-break.
*/
br: { children?: never }
/**
* Make the inline code element through generating the text surrounded by
* `` ` ``, to indicate that is a short fragment of computer code.
*
* In the content of `<code>`, all basic text stylings by both raw mrkdwn
* and JSX are ignored.
*
* @remarks
* Depending on contents around the element, styling may not apply
* correctly due to the restriction of mrkdwn that _special character will
* only work in a word boundary_. Make sure that the element is surrounded
* by word boundaries (e.g. Whitespaces).
*
* Not recommended but you can also deal it with turning on exact mode via
* `JSXSlack.exactMode(true)`.
*/
code: {}
/** An alias into `<s>`. */
del: {}
/** An alias into `<i>`. */
em: {}
/**
* Style the content with italic through generating the text surrounded by
* `_`.
*
* @remarks
* Depending on contents around the element, styling may not apply
* correctly due to the restriction of mrkdwn that _special character will
* only work in a word boundary_. Make sure that the element is surrounded
* by word boundaries (e.g. Whitespaces).
*
* Not recommended but you can also deal it with turning on exact mode via
* `JSXSlack.exactMode(true)`.
*/
i: {}
/**
* Define an item of the list.
*
* This element has to be contained in children of `<ul>` and `<ol>`.
*/
li: {
children: ChildElements
/**
* Set the ordinal value of the current list item for the ordered list.
*/
value?: number
}
/**
* Create the ordered list.
*
* Slack mrkdwn does not support list but jsx-slack can imitate HTML-style
* list by generating list-like plain text. It should contain list items
* provided by `<li>` element.
*/
ol: {
children: ChildElements
/** A number of the beginning count for the first list item. */
start?: number
/**
* Set the type of the number for list item markers.
*
* - `1`: Arabic numerals (default: 1, 2, 3...)
* - `a`: Alphabetical numerals with lowercase letters (a, b, c...)
* - `A`: Alphabetical numerals with uppercase letters (A, B, C...)
* - `i`: Roman numerals with lowercase letters (i, ii, iii...)
* - `I`: Roman numerals with uppercase letters (I, II, III...)
*/
type?: '1' | 'a' | 'A' | 'i' | 'I'
}
/** Make a paragraph. */
p: {}
/**
* Create the block for multiline pre-formatted text.
*
* Whitespaces and line-breaks in the content of `<pre>` element will
* render as are written.
*
* @example
* ```jsx
* const preformatted = '1\n2\n3'
*
* console.log(
* <Mrkdwn>
* <pre>{preformatted}</pre>
* </Mrkdwn>
* )
* ```
*
* `<pre>` in JSX has well-known pitfall: Whitespaces in the contents
* written as same as other elements will be collapsed by JSX transpiler.
* You should pass string value through JSX interpolation by expression to
* keep pre-formatted text.
*/
pre: {}
/**
* Style the content with strikethrough through generating the text
* surrounded by `~`.
*
* @remarks
* Depending on contents around the element, styling may not apply
* correctly due to the restriction of mrkdwn that _special character will
* only work in a word boundary_. Make sure that the element is surrounded
* by word boundaries (e.g. Whitespaces).
*
* Not recommended but you can also deal it with turning on exact mode via
* `JSXSlack.exactMode(true)`.
*/
s: {}
/**
* Redirect contents in its children to the description of `<Checkbox>`
* and `<RadioButton>`.
*
* It provides ergonomic templating instead of using JSX interpolation to
* `description` prop.
*
* ```jsx
* <Checkbox value="check">
* <b>Checkbox</b>
* <small>
* It's a <i>description</i>
* </small>
* </Checkbox>
* ```
*
* _This element is only available in `<Checkbox>` and `<RadioButton>`._
* It would be ignored in other components because Slack cannot change
* font size in a part of the text.
*/
small: {}
/**
* Divide mrkdwn text explicitly in `<Context>`.
*
* Usually text contents in `<Context>` will merge in pertinent mrkdwn
* elements automatically, but you can also apply manual dividation via
* `<span>` (or `<Mrkdwn>`) to get effective rendering in Slack client.
*
* _This element is only available in `<Context>`._ It has no effect even
* if used in other components.
*/
span: {}
/** An alias into `<s>`. */
strike: {}
/** An alias into `<b>`. */
strong: {}
/**
* Render a specific date and time, with defined format for Slack.
*
* It makes easy to render the formatted date and time with localized
* timezone for each Slack user.
* [Learn about date formatting in Slack documentation.](https://api.slack.com/reference/surfaces/formatting#date-formatting)
*
* ```jsx
* <time dateTime="1392734382">{'Posted {date_num} {time_secs}'}</time>
* // <!date^1392734382^Posted {date_num} {time_secs}|Posted 2014-02-18 14:39:42 PM>
*
* <time dateTime={1392734382}>{'{date} at {time}'}</time>
* // <!date^1392734382^{date} at {time}|February 18th, 2014 at 14:39 PM>
*
* <a href="https://example.com/">
* <time dateTime={new Date(Date.UTC(2014, 1, 18, 14, 39, 42))} fallback="Feb 18, 2014 PST">
* {'{date_short}'}
* </time>
* </a>
* // <!date^1392734382^{date_short}^https://example.com/|Feb 18, 2014 PST>
* ```
*
* We have very similar definition to HTML5 `<time>` tag, but _there is
* not-compatible attribute with HTML_: `fallback` to define the fallback
* text for not-supported Slack client.
*/
time:
| (TimeIntrinsicElementProps &
Required<Pick<TimeIntrinsicElementProps, 'dateTime'>>)
| (TimeIntrinsicElementProps &
Required<Pick<TimeIntrinsicElementProps, 'datetime'>>)
/**
* Create the unordered list.
*
* Slack mrkdwn does not support list but jsx-slack can imitate HTML-style
* list by generating list-like plain text. It should contain list items
* provided by `<li>` element.
*/
ul: {}
}
export interface ElementChildrenAttribute {
children: {}
}
type TimeIntrinsicElementProps = {
children?: ChildElements
/**
* Set the value of date and time to render.
*
* jsx-slack accepts either of a parsable string as date, UNIX timestamp
* _in second_, or JavaScript `Date` instance.
*/
dateTime?: string | number | Date
/**
* An alias into `dateTime` attribute.
*/
datetime?: string | number | Date
/**
* Define the fallback text, may render when the client cannot parse
* specified date and format.
*
* If not defined, jsx-slack tries to generate the fallback text
* automatically from the specified date and format. _Please note that a
* timezone for the generated text is always UTC._
*
* __NOTE__: This prop is not-compatible with HTML.
*/
fallback?: string
}
}
}
Object.freeze(JSXSlack) | the_stack |
import { IPickAndOpenOptions, ISaveDialogOptions, IOpenDialogOptions, IFileDialogService, FileFilter } from 'vs/platform/dialogs/common/dialogs';
import { URI } from 'vs/base/common/uri';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { AbstractFileDialogService } from 'vs/workbench/services/dialogs/browser/abstractFileDialogService';
import { Schemas } from 'vs/base/common/network';
import { memoize } from 'vs/base/common/decorators';
import { HTMLFileSystemProvider } from 'vs/platform/files/browser/htmlFileSystemProvider';
import { localize } from 'vs/nls';
import { getMediaOrTextMime } from 'vs/base/common/mime';
import { basename } from 'vs/base/common/resources';
import { triggerDownload, triggerUpload } from 'vs/base/browser/dom';
import Severity from 'vs/base/common/severity';
import { VSBuffer } from 'vs/base/common/buffer';
import { extractFileListData } from 'vs/platform/dnd/browser/dnd';
import { Iterable } from 'vs/base/common/iterator';
import { WebFileSystemAccess } from 'vs/platform/files/browser/webFileSystemAccess';
export class FileDialogService extends AbstractFileDialogService implements IFileDialogService {
@memoize
private get fileSystemProvider(): HTMLFileSystemProvider {
return this.fileService.getProvider(Schemas.file) as HTMLFileSystemProvider;
}
async pickFileFolderAndOpen(options: IPickAndOpenOptions): Promise<void> {
const schema = this.getFileSystemSchema(options);
if (!options.defaultUri) {
options.defaultUri = await this.defaultFilePath(schema);
}
if (this.shouldUseSimplified(schema)) {
return super.pickFileFolderAndOpenSimplified(schema, options, false);
}
throw new Error(localize('pickFolderAndOpen', "Can't open folders, try adding a folder to the workspace instead."));
}
protected override addFileSchemaIfNeeded(schema: string, isFolder: boolean): string[] {
return (schema === Schemas.untitled) ? [Schemas.file]
: (((schema !== Schemas.file) && (!isFolder || (schema !== Schemas.vscodeRemote))) ? [schema, Schemas.file] : [schema]);
}
async pickFileAndOpen(options: IPickAndOpenOptions): Promise<void> {
const schema = this.getFileSystemSchema(options);
if (!options.defaultUri) {
options.defaultUri = await this.defaultFilePath(schema);
}
if (this.shouldUseSimplified(schema)) {
return super.pickFileAndOpenSimplified(schema, options, false);
}
if (!WebFileSystemAccess.supported(window)) {
return this.showUnsupportedBrowserWarning('open');
}
let fileHandle: FileSystemHandle | undefined = undefined;
try {
([fileHandle] = await window.showOpenFilePicker({ multiple: false }));
} catch (error) {
return; // `showOpenFilePicker` will throw an error when the user cancels
}
if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) {
return;
}
const uri = await this.fileSystemProvider.registerFileHandle(fileHandle);
this.addFileToRecentlyOpened(uri);
await this.openerService.open(uri, { fromUserGesture: true, editorOptions: { pinned: true } });
}
async pickFolderAndOpen(options: IPickAndOpenOptions): Promise<void> {
const schema = this.getFileSystemSchema(options);
if (!options.defaultUri) {
options.defaultUri = await this.defaultFolderPath(schema);
}
if (this.shouldUseSimplified(schema)) {
return super.pickFolderAndOpenSimplified(schema, options);
}
throw new Error(localize('pickFolderAndOpen', "Can't open folders, try adding a folder to the workspace instead."));
}
async pickWorkspaceAndOpen(options: IPickAndOpenOptions): Promise<void> {
options.availableFileSystems = this.getWorkspaceAvailableFileSystems(options);
const schema = this.getFileSystemSchema(options);
if (!options.defaultUri) {
options.defaultUri = await this.defaultWorkspacePath(schema);
}
if (this.shouldUseSimplified(schema)) {
return super.pickWorkspaceAndOpenSimplified(schema, options);
}
throw new Error(localize('pickWorkspaceAndOpen', "Can't open workspaces, try adding a folder to the workspace instead."));
}
async pickFileToSave(defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined> {
const schema = this.getFileSystemSchema({ defaultUri, availableFileSystems });
const options = this.getPickFileToSaveDialogOptions(defaultUri, availableFileSystems);
if (this.shouldUseSimplified(schema)) {
return super.pickFileToSaveSimplified(schema, options);
}
if (!WebFileSystemAccess.supported(window)) {
return this.showUnsupportedBrowserWarning('save');
}
let fileHandle: FileSystemHandle | undefined = undefined;
const startIn = Iterable.first(this.fileSystemProvider.directories);
try {
fileHandle = await window.showSaveFilePicker({ types: this.getFilePickerTypes(options.filters), ...{ suggestedName: basename(defaultUri), startIn } });
} catch (error) {
return; // `showSaveFilePicker` will throw an error when the user cancels
}
if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) {
return undefined;
}
return this.fileSystemProvider.registerFileHandle(fileHandle);
}
private getFilePickerTypes(filters?: FileFilter[]): FilePickerAcceptType[] | undefined {
return filters?.filter(filter => {
return !((filter.extensions.length === 1) && ((filter.extensions[0] === '*') || filter.extensions[0] === ''));
}).map(filter => {
const accept: Record<string, string[]> = {};
const extensions = filter.extensions.filter(ext => (ext.indexOf('-') < 0) && (ext.indexOf('*') < 0) && (ext.indexOf('_') < 0));
accept[getMediaOrTextMime(`fileName.${filter.extensions[0]}`) ?? 'text/plain'] = extensions.map(ext => ext.startsWith('.') ? ext : `.${ext}`);
return {
description: filter.name,
accept
};
});
}
async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> {
const schema = this.getFileSystemSchema(options);
if (this.shouldUseSimplified(schema)) {
return super.showSaveDialogSimplified(schema, options);
}
if (!WebFileSystemAccess.supported(window)) {
return this.showUnsupportedBrowserWarning('save');
}
let fileHandle: FileSystemHandle | undefined = undefined;
const startIn = Iterable.first(this.fileSystemProvider.directories);
try {
fileHandle = await window.showSaveFilePicker({ types: this.getFilePickerTypes(options.filters), ...options.defaultUri ? { suggestedName: basename(options.defaultUri) } : undefined, ...{ startIn } });
} catch (error) {
return undefined; // `showSaveFilePicker` will throw an error when the user cancels
}
if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) {
return undefined;
}
return this.fileSystemProvider.registerFileHandle(fileHandle);
}
async showOpenDialog(options: IOpenDialogOptions): Promise<URI[] | undefined> {
const schema = this.getFileSystemSchema(options);
if (this.shouldUseSimplified(schema)) {
return super.showOpenDialogSimplified(schema, options);
}
if (!WebFileSystemAccess.supported(window)) {
return this.showUnsupportedBrowserWarning('open');
}
let uri: URI | undefined;
const startIn = Iterable.first(this.fileSystemProvider.directories) ?? 'documents';
try {
if (options.canSelectFiles) {
const handle = await window.showOpenFilePicker({ multiple: false, types: this.getFilePickerTypes(options.filters), ...{ startIn } });
if (handle.length === 1 && WebFileSystemAccess.isFileSystemFileHandle(handle[0])) {
uri = await this.fileSystemProvider.registerFileHandle(handle[0]);
}
} else {
const handle = await window.showDirectoryPicker({ ...{ startIn } });
uri = await this.fileSystemProvider.registerDirectoryHandle(handle);
}
} catch (error) {
// ignore - `showOpenFilePicker` / `showDirectoryPicker` will throw an error when the user cancels
}
return uri ? [uri] : undefined;
}
private async showUnsupportedBrowserWarning(context: 'save' | 'open'): Promise<undefined> {
// When saving, try to just download the contents
// of the active text editor if any as a workaround
if (context === 'save') {
const activeTextModel = this.codeEditorService.getActiveCodeEditor()?.getModel();
if (activeTextModel) {
triggerDownload(VSBuffer.fromString(activeTextModel.getValue()).buffer, basename(activeTextModel.uri));
return;
}
}
// Otherwise inform the user about options
const buttons = context === 'open' ?
[localize('openRemote', "Open Remote..."), localize('learnMore', "Learn More"), localize('openFiles', "Open Files...")] :
[localize('openRemote', "Open Remote..."), localize('learnMore', "Learn More")];
const res = await this.dialogService.show(
Severity.Warning,
localize('unsupportedBrowserMessage', "Opening Local Folders is Unsupported"),
buttons,
{
detail: localize('unsupportedBrowserDetail', "Your browser doesn't support opening local folders.\nYou can either open single files or open a remote repository."),
cancelId: -1 // no "Cancel" button offered
}
);
switch (res.choice) {
case 0:
this.commandService.executeCommand('workbench.action.remote.showMenu');
break;
case 1:
this.openerService.open('https://aka.ms/VSCodeWebLocalFileSystemAccess');
break;
case 2:
{
const files = await triggerUpload();
if (files) {
const filesData = (await this.instantiationService.invokeFunction(accessor => extractFileListData(accessor, files))).filter(fileData => !fileData.isDirectory);
if (filesData.length > 0) {
this.editorService.openEditors(filesData.map(fileData => {
return {
resource: fileData.resource,
contents: fileData.contents?.toString(),
options: { pinned: true }
};
}));
}
}
}
break;
}
return undefined;
}
private shouldUseSimplified(scheme: string): boolean {
return ![Schemas.file, Schemas.vscodeUserData, Schemas.tmp].includes(scheme);
}
}
registerSingleton(IFileDialogService, FileDialogService, true); | the_stack |
import { CPU } from './cpu';
import { u16 } from '../types';
function isTwoWordInstruction(opcode: u16) {
return (
/* LDS */
(opcode & 0xfe0f) === 0x9000 ||
/* STS */
(opcode & 0xfe0f) === 0x9200 ||
/* CALL */
(opcode & 0xfe0e) === 0x940e ||
/* JMP */
(opcode & 0xfe0e) === 0x940c
);
}
export function avrInstruction(cpu: CPU) {
const opcode = cpu.progMem[cpu.pc];
if ((opcode & 0xfc00) === 0x1c00) {
/* ADC, 0001 11rd dddd rrrr */
const d = cpu.data[(opcode & 0x1f0) >> 4];
const r = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
const sum = d + r + (cpu.data[95] & 1);
const R = sum & 255;
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= (R ^ r) & (d ^ R) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= sum & 256 ? 1 : 0;
sreg |= 1 & ((d & r) | (r & ~R) | (~R & d)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfc00) === 0xc00) {
/* ADD, 0000 11rd dddd rrrr */
const d = cpu.data[(opcode & 0x1f0) >> 4];
const r = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
const R = (d + r) & 255;
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= (R ^ r) & (R ^ d) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= (d + r) & 256 ? 1 : 0;
sreg |= 1 & ((d & r) | (r & ~R) | (~R & d)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xff00) === 0x9600) {
/* ADIW, 1001 0110 KKdd KKKK */
const addr = 2 * ((opcode & 0x30) >> 4) + 24;
const value = cpu.dataView.getUint16(addr, true);
const R = (value + ((opcode & 0xf) | ((opcode & 0xc0) >> 2))) & 0xffff;
cpu.dataView.setUint16(addr, R, true);
let sreg = cpu.data[95] & 0xe0;
sreg |= R ? 0 : 2;
sreg |= 0x8000 & R ? 4 : 0;
sreg |= ~value & R & 0x8000 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= ~R & value & 0x8000 ? 1 : 0;
cpu.data[95] = sreg;
cpu.cycles++;
} else if ((opcode & 0xfc00) === 0x2000) {
/* AND, 0010 00rd dddd rrrr */
const R = cpu.data[(opcode & 0x1f0) >> 4] & cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xe1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xf000) === 0x7000) {
/* ANDI, 0111 KKKK dddd KKKK */
const R = cpu.data[((opcode & 0xf0) >> 4) + 16] & ((opcode & 0xf) | ((opcode & 0xf00) >> 4));
cpu.data[((opcode & 0xf0) >> 4) + 16] = R;
let sreg = cpu.data[95] & 0xe1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfe0f) === 0x9405) {
/* ASR, 1001 010d dddd 0101 */
const value = cpu.data[(opcode & 0x1f0) >> 4];
const R = (value >>> 1) | (128 & value);
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xe0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= value & 1;
sreg |= ((sreg >> 2) & 1) ^ (sreg & 1) ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xff8f) === 0x9488) {
/* BCLR, 1001 0100 1sss 1000 */
cpu.data[95] &= ~(1 << ((opcode & 0x70) >> 4));
} else if ((opcode & 0xfe08) === 0xf800) {
/* BLD, 1111 100d dddd 0bbb */
const b = opcode & 7;
const d = (opcode & 0x1f0) >> 4;
cpu.data[d] = (~(1 << b) & cpu.data[d]) | (((cpu.data[95] >> 6) & 1) << b);
} else if ((opcode & 0xfc00) === 0xf400) {
/* BRBC, 1111 01kk kkkk ksss */
if (!(cpu.data[95] & (1 << (opcode & 7)))) {
cpu.pc = cpu.pc + (((opcode & 0x1f8) >> 3) - (opcode & 0x200 ? 0x40 : 0));
cpu.cycles++;
}
} else if ((opcode & 0xfc00) === 0xf000) {
/* BRBS, 1111 00kk kkkk ksss */
if (cpu.data[95] & (1 << (opcode & 7))) {
cpu.pc = cpu.pc + (((opcode & 0x1f8) >> 3) - (opcode & 0x200 ? 0x40 : 0));
cpu.cycles++;
}
} else if ((opcode & 0xff8f) === 0x9408) {
/* BSET, 1001 0100 0sss 1000 */
cpu.data[95] |= 1 << ((opcode & 0x70) >> 4);
} else if ((opcode & 0xfe08) === 0xfa00) {
/* BST, 1111 101d dddd 0bbb */
const d = cpu.data[(opcode & 0x1f0) >> 4];
const b = opcode & 7;
cpu.data[95] = (cpu.data[95] & 0xbf) | ((d >> b) & 1 ? 0x40 : 0);
} else if ((opcode & 0xfe0e) === 0x940e) {
/* CALL, 1001 010k kkkk 111k kkkk kkkk kkkk kkkk */
const k = cpu.progMem[cpu.pc + 1] | ((opcode & 1) << 16) | ((opcode & 0x1f0) << 13);
const ret = cpu.pc + 2;
const sp = cpu.dataView.getUint16(93, true);
const { pc22Bits } = cpu;
cpu.data[sp] = 255 & ret;
cpu.data[sp - 1] = (ret >> 8) & 255;
if (pc22Bits) {
cpu.data[sp - 2] = (ret >> 16) & 255;
}
cpu.dataView.setUint16(93, sp - (pc22Bits ? 3 : 2), true);
cpu.pc = k - 1;
cpu.cycles += pc22Bits ? 4 : 3;
} else if ((opcode & 0xff00) === 0x9800) {
/* CBI, 1001 1000 AAAA Abbb */
const A = opcode & 0xf8;
const b = opcode & 7;
const R = cpu.readData((A >> 3) + 32);
const mask = 1 << b;
cpu.writeData((A >> 3) + 32, R & ~mask, mask);
} else if ((opcode & 0xfe0f) === 0x9400) {
/* COM, 1001 010d dddd 0000 */
const d = (opcode & 0x1f0) >> 4;
const R = 255 - cpu.data[d];
cpu.data[d] = R;
let sreg = (cpu.data[95] & 0xe1) | 1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfc00) === 0x1400) {
/* CP, 0001 01rd dddd rrrr */
const val1 = cpu.data[(opcode & 0x1f0) >> 4];
const val2 = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
const R = val1 - val2;
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= 0 !== ((val1 ^ val2) & (val1 ^ R) & 128) ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= val2 > val1 ? 1 : 0;
sreg |= 1 & ((~val1 & val2) | (val2 & R) | (R & ~val1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfc00) === 0x400) {
/* CPC, 0000 01rd dddd rrrr */
const arg1 = cpu.data[(opcode & 0x1f0) >> 4];
const arg2 = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
let sreg = cpu.data[95];
const r = arg1 - arg2 - (sreg & 1);
sreg = (sreg & 0xc0) | (!r && (sreg >> 1) & 1 ? 2 : 0) | (arg2 + (sreg & 1) > arg1 ? 1 : 0);
sreg |= 128 & r ? 4 : 0;
sreg |= (arg1 ^ arg2) & (arg1 ^ r) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= 1 & ((~arg1 & arg2) | (arg2 & r) | (r & ~arg1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xf000) === 0x3000) {
/* CPI, 0011 KKKK dddd KKKK */
const arg1 = cpu.data[((opcode & 0xf0) >> 4) + 16];
const arg2 = (opcode & 0xf) | ((opcode & 0xf00) >> 4);
const r = arg1 - arg2;
let sreg = cpu.data[95] & 0xc0;
sreg |= r ? 0 : 2;
sreg |= 128 & r ? 4 : 0;
sreg |= (arg1 ^ arg2) & (arg1 ^ r) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= arg2 > arg1 ? 1 : 0;
sreg |= 1 & ((~arg1 & arg2) | (arg2 & r) | (r & ~arg1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfc00) === 0x1000) {
/* CPSE, 0001 00rd dddd rrrr */
if (cpu.data[(opcode & 0x1f0) >> 4] === cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)]) {
const nextOpcode = cpu.progMem[cpu.pc + 1];
const skipSize = isTwoWordInstruction(nextOpcode) ? 2 : 1;
cpu.pc += skipSize;
cpu.cycles += skipSize;
}
} else if ((opcode & 0xfe0f) === 0x940a) {
/* DEC, 1001 010d dddd 1010 */
const value = cpu.data[(opcode & 0x1f0) >> 4];
const R = value - 1;
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xe1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= 128 === value ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if (opcode === 0x9519) {
/* EICALL, 1001 0101 0001 1001 */
const retAddr = cpu.pc + 1;
const sp = cpu.dataView.getUint16(93, true);
const eind = cpu.data[0x5c];
cpu.data[sp] = retAddr & 255;
cpu.data[sp - 1] = (retAddr >> 8) & 255;
cpu.data[sp - 2] = (retAddr >> 16) & 255;
cpu.dataView.setUint16(93, sp - 3, true);
cpu.pc = ((eind << 16) | cpu.dataView.getUint16(30, true)) - 1;
cpu.cycles += 3;
} else if (opcode === 0x9419) {
/* EIJMP, 1001 0100 0001 1001 */
const eind = cpu.data[0x5c];
cpu.pc = ((eind << 16) | cpu.dataView.getUint16(30, true)) - 1;
cpu.cycles++;
} else if (opcode === 0x95d8) {
/* ELPM, 1001 0101 1101 1000 */
const rampz = cpu.data[0x5b];
cpu.data[0] = cpu.progBytes[(rampz << 16) | cpu.dataView.getUint16(30, true)];
cpu.cycles += 2;
} else if ((opcode & 0xfe0f) === 0x9006) {
/* ELPM(REG), 1001 000d dddd 0110 */
const rampz = cpu.data[0x5b];
cpu.data[(opcode & 0x1f0) >> 4] =
cpu.progBytes[(rampz << 16) | cpu.dataView.getUint16(30, true)];
cpu.cycles += 2;
} else if ((opcode & 0xfe0f) === 0x9007) {
/* ELPM(INC), 1001 000d dddd 0111 */
const rampz = cpu.data[0x5b];
const i = cpu.dataView.getUint16(30, true);
cpu.data[(opcode & 0x1f0) >> 4] = cpu.progBytes[(rampz << 16) | i];
cpu.dataView.setUint16(30, i + 1, true);
if (i === 0xffff) {
cpu.data[0x5b] = (rampz + 1) % (cpu.progBytes.length >> 16);
}
cpu.cycles += 2;
} else if ((opcode & 0xfc00) === 0x2400) {
/* EOR, 0010 01rd dddd rrrr */
const R = cpu.data[(opcode & 0x1f0) >> 4] ^ cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xe1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xff88) === 0x308) {
/* FMUL, 0000 0011 0ddd 1rrr */
const v1 = cpu.data[((opcode & 0x70) >> 4) + 16];
const v2 = cpu.data[(opcode & 7) + 16];
const R = (v1 * v2) << 1;
cpu.dataView.setUint16(0, R, true);
cpu.data[95] = (cpu.data[95] & 0xfc) | (0xffff & R ? 0 : 2) | ((v1 * v2) & 0x8000 ? 1 : 0);
cpu.cycles++;
} else if ((opcode & 0xff88) === 0x380) {
/* FMULS, 0000 0011 1ddd 0rrr */
const v1 = cpu.dataView.getInt8(((opcode & 0x70) >> 4) + 16);
const v2 = cpu.dataView.getInt8((opcode & 7) + 16);
const R = (v1 * v2) << 1;
cpu.dataView.setInt16(0, R, true);
cpu.data[95] = (cpu.data[95] & 0xfc) | (0xffff & R ? 0 : 2) | ((v1 * v2) & 0x8000 ? 1 : 0);
cpu.cycles++;
} else if ((opcode & 0xff88) === 0x388) {
/* FMULSU, 0000 0011 1ddd 1rrr */
const v1 = cpu.dataView.getInt8(((opcode & 0x70) >> 4) + 16);
const v2 = cpu.data[(opcode & 7) + 16];
const R = (v1 * v2) << 1;
cpu.dataView.setInt16(0, R, true);
cpu.data[95] = (cpu.data[95] & 0xfc) | (0xffff & R ? 2 : 0) | ((v1 * v2) & 0x8000 ? 1 : 0);
cpu.cycles++;
} else if (opcode === 0x9509) {
/* ICALL, 1001 0101 0000 1001 */
const retAddr = cpu.pc + 1;
const sp = cpu.dataView.getUint16(93, true);
const { pc22Bits } = cpu;
cpu.data[sp] = retAddr & 255;
cpu.data[sp - 1] = (retAddr >> 8) & 255;
if (pc22Bits) {
cpu.data[sp - 2] = (retAddr >> 16) & 255;
}
cpu.dataView.setUint16(93, sp - (pc22Bits ? 3 : 2), true);
cpu.pc = cpu.dataView.getUint16(30, true) - 1;
cpu.cycles += pc22Bits ? 3 : 2;
} else if (opcode === 0x9409) {
/* IJMP, 1001 0100 0000 1001 */
cpu.pc = cpu.dataView.getUint16(30, true) - 1;
cpu.cycles++;
} else if ((opcode & 0xf800) === 0xb000) {
/* IN, 1011 0AAd dddd AAAA */
const i = cpu.readData(((opcode & 0xf) | ((opcode & 0x600) >> 5)) + 32);
cpu.data[(opcode & 0x1f0) >> 4] = i;
} else if ((opcode & 0xfe0f) === 0x9403) {
/* INC, 1001 010d dddd 0011 */
const d = cpu.data[(opcode & 0x1f0) >> 4];
const r = (d + 1) & 255;
cpu.data[(opcode & 0x1f0) >> 4] = r;
let sreg = cpu.data[95] & 0xe1;
sreg |= r ? 0 : 2;
sreg |= 128 & r ? 4 : 0;
sreg |= 127 === d ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfe0e) === 0x940c) {
/* JMP, 1001 010k kkkk 110k kkkk kkkk kkkk kkkk */
cpu.pc = (cpu.progMem[cpu.pc + 1] | ((opcode & 1) << 16) | ((opcode & 0x1f0) << 13)) - 1;
cpu.cycles += 2;
} else if ((opcode & 0xfe0f) === 0x9206) {
/* LAC, 1001 001r rrrr 0110 */
const r = (opcode & 0x1f0) >> 4;
const clear = cpu.data[r];
const value = cpu.readData(cpu.dataView.getUint16(30, true));
cpu.writeData(cpu.dataView.getUint16(30, true), value & (255 - clear));
cpu.data[r] = value;
} else if ((opcode & 0xfe0f) === 0x9205) {
/* LAS, 1001 001r rrrr 0101 */
const r = (opcode & 0x1f0) >> 4;
const set = cpu.data[r];
const value = cpu.readData(cpu.dataView.getUint16(30, true));
cpu.writeData(cpu.dataView.getUint16(30, true), value | set);
cpu.data[r] = value;
} else if ((opcode & 0xfe0f) === 0x9207) {
/* LAT, 1001 001r rrrr 0111 */
const r = cpu.data[(opcode & 0x1f0) >> 4];
const R = cpu.readData(cpu.dataView.getUint16(30, true));
cpu.writeData(cpu.dataView.getUint16(30, true), r ^ R);
cpu.data[(opcode & 0x1f0) >> 4] = R;
} else if ((opcode & 0xf000) === 0xe000) {
/* LDI, 1110 KKKK dddd KKKK */
cpu.data[((opcode & 0xf0) >> 4) + 16] = (opcode & 0xf) | ((opcode & 0xf00) >> 4);
} else if ((opcode & 0xfe0f) === 0x9000) {
/* LDS, 1001 000d dddd 0000 kkkk kkkk kkkk kkkk */
cpu.cycles++;
const value = cpu.readData(cpu.progMem[cpu.pc + 1]);
cpu.data[(opcode & 0x1f0) >> 4] = value;
cpu.pc++;
} else if ((opcode & 0xfe0f) === 0x900c) {
/* LDX, 1001 000d dddd 1100 */
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(cpu.dataView.getUint16(26, true));
} else if ((opcode & 0xfe0f) === 0x900d) {
/* LDX(INC), 1001 000d dddd 1101 */
const x = cpu.dataView.getUint16(26, true);
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(x);
cpu.dataView.setUint16(26, x + 1, true);
} else if ((opcode & 0xfe0f) === 0x900e) {
/* LDX(DEC), 1001 000d dddd 1110 */
const x = cpu.dataView.getUint16(26, true) - 1;
cpu.dataView.setUint16(26, x, true);
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(x);
} else if ((opcode & 0xfe0f) === 0x8008) {
/* LDY, 1000 000d dddd 1000 */
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(cpu.dataView.getUint16(28, true));
} else if ((opcode & 0xfe0f) === 0x9009) {
/* LDY(INC), 1001 000d dddd 1001 */
const y = cpu.dataView.getUint16(28, true);
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(y);
cpu.dataView.setUint16(28, y + 1, true);
} else if ((opcode & 0xfe0f) === 0x900a) {
/* LDY(DEC), 1001 000d dddd 1010 */
const y = cpu.dataView.getUint16(28, true) - 1;
cpu.dataView.setUint16(28, y, true);
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(y);
} else if (
(opcode & 0xd208) === 0x8008 &&
(opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8)
) {
/* LDDY, 10q0 qq0d dddd 1qqq */
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(
cpu.dataView.getUint16(28, true) +
((opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8))
);
} else if ((opcode & 0xfe0f) === 0x8000) {
/* LDZ, 1000 000d dddd 0000 */
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(cpu.dataView.getUint16(30, true));
} else if ((opcode & 0xfe0f) === 0x9001) {
/* LDZ(INC), 1001 000d dddd 0001 */
const z = cpu.dataView.getUint16(30, true);
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(z);
cpu.dataView.setUint16(30, z + 1, true);
} else if ((opcode & 0xfe0f) === 0x9002) {
/* LDZ(DEC), 1001 000d dddd 0010 */
const z = cpu.dataView.getUint16(30, true) - 1;
cpu.dataView.setUint16(30, z, true);
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(z);
} else if (
(opcode & 0xd208) === 0x8000 &&
(opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8)
) {
/* LDDZ, 10q0 qq0d dddd 0qqq */
cpu.cycles++;
cpu.data[(opcode & 0x1f0) >> 4] = cpu.readData(
cpu.dataView.getUint16(30, true) +
((opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8))
);
} else if (opcode === 0x95c8) {
/* LPM, 1001 0101 1100 1000 */
cpu.data[0] = cpu.progBytes[cpu.dataView.getUint16(30, true)];
cpu.cycles += 2;
} else if ((opcode & 0xfe0f) === 0x9004) {
/* LPM(REG), 1001 000d dddd 0100 */
cpu.data[(opcode & 0x1f0) >> 4] = cpu.progBytes[cpu.dataView.getUint16(30, true)];
cpu.cycles += 2;
} else if ((opcode & 0xfe0f) === 0x9005) {
/* LPM(INC), 1001 000d dddd 0101 */
const i = cpu.dataView.getUint16(30, true);
cpu.data[(opcode & 0x1f0) >> 4] = cpu.progBytes[i];
cpu.dataView.setUint16(30, i + 1, true);
cpu.cycles += 2;
} else if ((opcode & 0xfe0f) === 0x9406) {
/* LSR, 1001 010d dddd 0110 */
const value = cpu.data[(opcode & 0x1f0) >> 4];
const R = value >>> 1;
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xe0;
sreg |= R ? 0 : 2;
sreg |= value & 1;
sreg |= ((sreg >> 2) & 1) ^ (sreg & 1) ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfc00) === 0x2c00) {
/* MOV, 0010 11rd dddd rrrr */
cpu.data[(opcode & 0x1f0) >> 4] = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
} else if ((opcode & 0xff00) === 0x100) {
/* MOVW, 0000 0001 dddd rrrr */
const r2 = 2 * (opcode & 0xf);
const d2 = 2 * ((opcode & 0xf0) >> 4);
cpu.data[d2] = cpu.data[r2];
cpu.data[d2 + 1] = cpu.data[r2 + 1];
} else if ((opcode & 0xfc00) === 0x9c00) {
/* MUL, 1001 11rd dddd rrrr */
const R = cpu.data[(opcode & 0x1f0) >> 4] * cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
cpu.dataView.setUint16(0, R, true);
cpu.data[95] = (cpu.data[95] & 0xfc) | (0xffff & R ? 0 : 2) | (0x8000 & R ? 1 : 0);
cpu.cycles++;
} else if ((opcode & 0xff00) === 0x200) {
/* MULS, 0000 0010 dddd rrrr */
const R =
cpu.dataView.getInt8(((opcode & 0xf0) >> 4) + 16) * cpu.dataView.getInt8((opcode & 0xf) + 16);
cpu.dataView.setInt16(0, R, true);
cpu.data[95] = (cpu.data[95] & 0xfc) | (0xffff & R ? 0 : 2) | (0x8000 & R ? 1 : 0);
cpu.cycles++;
} else if ((opcode & 0xff88) === 0x300) {
/* MULSU, 0000 0011 0ddd 0rrr */
const R = cpu.dataView.getInt8(((opcode & 0x70) >> 4) + 16) * cpu.data[(opcode & 7) + 16];
cpu.dataView.setInt16(0, R, true);
cpu.data[95] = (cpu.data[95] & 0xfc) | (0xffff & R ? 0 : 2) | (0x8000 & R ? 1 : 0);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x9401) {
/* NEG, 1001 010d dddd 0001 */
const d = (opcode & 0x1f0) >> 4;
const value = cpu.data[d];
const R = 0 - value;
cpu.data[d] = R;
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= 128 === R ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= R ? 1 : 0;
sreg |= 1 & (R | value) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if (opcode === 0) {
/* NOP, 0000 0000 0000 0000 */
/* NOP */
} else if ((opcode & 0xfc00) === 0x2800) {
/* OR, 0010 10rd dddd rrrr */
const R = cpu.data[(opcode & 0x1f0) >> 4] | cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xe1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xf000) === 0x6000) {
/* SBR, 0110 KKKK dddd KKKK */
const R = cpu.data[((opcode & 0xf0) >> 4) + 16] | ((opcode & 0xf) | ((opcode & 0xf00) >> 4));
cpu.data[((opcode & 0xf0) >> 4) + 16] = R;
let sreg = cpu.data[95] & 0xe1;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xf800) === 0xb800) {
/* OUT, 1011 1AAr rrrr AAAA */
cpu.writeData(((opcode & 0xf) | ((opcode & 0x600) >> 5)) + 32, cpu.data[(opcode & 0x1f0) >> 4]);
} else if ((opcode & 0xfe0f) === 0x900f) {
/* POP, 1001 000d dddd 1111 */
const value = cpu.dataView.getUint16(93, true) + 1;
cpu.dataView.setUint16(93, value, true);
cpu.data[(opcode & 0x1f0) >> 4] = cpu.data[value];
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x920f) {
/* PUSH, 1001 001d dddd 1111 */
const value = cpu.dataView.getUint16(93, true);
cpu.data[value] = cpu.data[(opcode & 0x1f0) >> 4];
cpu.dataView.setUint16(93, value - 1, true);
cpu.cycles++;
} else if ((opcode & 0xf000) === 0xd000) {
/* RCALL, 1101 kkkk kkkk kkkk */
const k = (opcode & 0x7ff) - (opcode & 0x800 ? 0x800 : 0);
const retAddr = cpu.pc + 1;
const sp = cpu.dataView.getUint16(93, true);
const { pc22Bits } = cpu;
cpu.data[sp] = 255 & retAddr;
cpu.data[sp - 1] = (retAddr >> 8) & 255;
if (pc22Bits) {
cpu.data[sp - 2] = (retAddr >> 16) & 255;
}
cpu.dataView.setUint16(93, sp - (pc22Bits ? 3 : 2), true);
cpu.pc += k;
cpu.cycles += pc22Bits ? 3 : 2;
} else if (opcode === 0x9508) {
/* RET, 1001 0101 0000 1000 */
const { pc22Bits } = cpu;
const i = cpu.dataView.getUint16(93, true) + (pc22Bits ? 3 : 2);
cpu.dataView.setUint16(93, i, true);
cpu.pc = (cpu.data[i - 1] << 8) + cpu.data[i] - 1;
if (pc22Bits) {
cpu.pc |= cpu.data[i - 2] << 16;
}
cpu.cycles += pc22Bits ? 4 : 3;
} else if (opcode === 0x9518) {
/* RETI, 1001 0101 0001 1000 */
const { pc22Bits } = cpu;
const i = cpu.dataView.getUint16(93, true) + (pc22Bits ? 3 : 2);
cpu.dataView.setUint16(93, i, true);
cpu.pc = (cpu.data[i - 1] << 8) + cpu.data[i] - 1;
if (pc22Bits) {
cpu.pc |= cpu.data[i - 2] << 16;
}
cpu.cycles += pc22Bits ? 4 : 3;
cpu.data[95] |= 0x80; // Enable interrupts
} else if ((opcode & 0xf000) === 0xc000) {
/* RJMP, 1100 kkkk kkkk kkkk */
cpu.pc = cpu.pc + ((opcode & 0x7ff) - (opcode & 0x800 ? 0x800 : 0));
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x9407) {
/* ROR, 1001 010d dddd 0111 */
const d = cpu.data[(opcode & 0x1f0) >> 4];
const r = (d >>> 1) | ((cpu.data[95] & 1) << 7);
cpu.data[(opcode & 0x1f0) >> 4] = r;
let sreg = cpu.data[95] & 0xe0;
sreg |= r ? 0 : 2;
sreg |= 128 & r ? 4 : 0;
sreg |= 1 & d ? 1 : 0;
sreg |= ((sreg >> 2) & 1) ^ (sreg & 1) ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfc00) === 0x800) {
/* SBC, 0000 10rd dddd rrrr */
const val1 = cpu.data[(opcode & 0x1f0) >> 4];
const val2 = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
let sreg = cpu.data[95];
const R = val1 - val2 - (sreg & 1);
cpu.data[(opcode & 0x1f0) >> 4] = R;
sreg = (sreg & 0xc0) | (!R && (sreg >> 1) & 1 ? 2 : 0) | (val2 + (sreg & 1) > val1 ? 1 : 0);
sreg |= 128 & R ? 4 : 0;
sreg |= (val1 ^ val2) & (val1 ^ R) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= 1 & ((~val1 & val2) | (val2 & R) | (R & ~val1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xf000) === 0x4000) {
/* SBCI, 0100 KKKK dddd KKKK */
const val1 = cpu.data[((opcode & 0xf0) >> 4) + 16];
const val2 = (opcode & 0xf) | ((opcode & 0xf00) >> 4);
let sreg = cpu.data[95];
const R = val1 - val2 - (sreg & 1);
cpu.data[((opcode & 0xf0) >> 4) + 16] = R;
sreg = (sreg & 0xc0) | (!R && (sreg >> 1) & 1 ? 2 : 0) | (val2 + (sreg & 1) > val1 ? 1 : 0);
sreg |= 128 & R ? 4 : 0;
sreg |= (val1 ^ val2) & (val1 ^ R) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= 1 & ((~val1 & val2) | (val2 & R) | (R & ~val1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xff00) === 0x9a00) {
/* SBI, 1001 1010 AAAA Abbb */
const target = ((opcode & 0xf8) >> 3) + 32;
const mask = 1 << (opcode & 7);
cpu.writeData(target, cpu.readData(target) | mask, mask);
cpu.cycles++;
} else if ((opcode & 0xff00) === 0x9900) {
/* SBIC, 1001 1001 AAAA Abbb */
const value = cpu.readData(((opcode & 0xf8) >> 3) + 32);
if (!(value & (1 << (opcode & 7)))) {
const nextOpcode = cpu.progMem[cpu.pc + 1];
const skipSize = isTwoWordInstruction(nextOpcode) ? 2 : 1;
cpu.cycles += skipSize;
cpu.pc += skipSize;
}
} else if ((opcode & 0xff00) === 0x9b00) {
/* SBIS, 1001 1011 AAAA Abbb */
const value = cpu.readData(((opcode & 0xf8) >> 3) + 32);
if (value & (1 << (opcode & 7))) {
const nextOpcode = cpu.progMem[cpu.pc + 1];
const skipSize = isTwoWordInstruction(nextOpcode) ? 2 : 1;
cpu.cycles += skipSize;
cpu.pc += skipSize;
}
} else if ((opcode & 0xff00) === 0x9700) {
/* SBIW, 1001 0111 KKdd KKKK */
const i = 2 * ((opcode & 0x30) >> 4) + 24;
const a = cpu.dataView.getUint16(i, true);
const l = (opcode & 0xf) | ((opcode & 0xc0) >> 2);
const R = a - l;
cpu.dataView.setUint16(i, R, true);
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 0x8000 & R ? 4 : 0;
sreg |= a & ~R & 0x8000 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= l > a ? 1 : 0;
sreg |= 1 & ((~a & l) | (l & R) | (R & ~a)) ? 0x20 : 0;
cpu.data[95] = sreg;
cpu.cycles++;
} else if ((opcode & 0xfe08) === 0xfc00) {
/* SBRC, 1111 110r rrrr 0bbb */
if (!(cpu.data[(opcode & 0x1f0) >> 4] & (1 << (opcode & 7)))) {
const nextOpcode = cpu.progMem[cpu.pc + 1];
const skipSize = isTwoWordInstruction(nextOpcode) ? 2 : 1;
cpu.cycles += skipSize;
cpu.pc += skipSize;
}
} else if ((opcode & 0xfe08) === 0xfe00) {
/* SBRS, 1111 111r rrrr 0bbb */
if (cpu.data[(opcode & 0x1f0) >> 4] & (1 << (opcode & 7))) {
const nextOpcode = cpu.progMem[cpu.pc + 1];
const skipSize = isTwoWordInstruction(nextOpcode) ? 2 : 1;
cpu.cycles += skipSize;
cpu.pc += skipSize;
}
} else if (opcode === 0x9588) {
/* SLEEP, 1001 0101 1000 1000 */
/* not implemented */
} else if (opcode === 0x95e8) {
/* SPM, 1001 0101 1110 1000 */
/* not implemented */
} else if (opcode === 0x95f8) {
/* SPM(INC), 1001 0101 1111 1000 */
/* not implemented */
} else if ((opcode & 0xfe0f) === 0x9200) {
/* STS, 1001 001d dddd 0000 kkkk kkkk kkkk kkkk */
const value = cpu.data[(opcode & 0x1f0) >> 4];
const addr = cpu.progMem[cpu.pc + 1];
cpu.writeData(addr, value);
cpu.pc++;
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x920c) {
/* STX, 1001 001r rrrr 1100 */
cpu.writeData(cpu.dataView.getUint16(26, true), cpu.data[(opcode & 0x1f0) >> 4]);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x920d) {
/* STX(INC), 1001 001r rrrr 1101 */
const x = cpu.dataView.getUint16(26, true);
cpu.writeData(x, cpu.data[(opcode & 0x1f0) >> 4]);
cpu.dataView.setUint16(26, x + 1, true);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x920e) {
/* STX(DEC), 1001 001r rrrr 1110 */
const i = cpu.data[(opcode & 0x1f0) >> 4];
const x = cpu.dataView.getUint16(26, true) - 1;
cpu.dataView.setUint16(26, x, true);
cpu.writeData(x, i);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x8208) {
/* STY, 1000 001r rrrr 1000 */
cpu.writeData(cpu.dataView.getUint16(28, true), cpu.data[(opcode & 0x1f0) >> 4]);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x9209) {
/* STY(INC), 1001 001r rrrr 1001 */
const i = cpu.data[(opcode & 0x1f0) >> 4];
const y = cpu.dataView.getUint16(28, true);
cpu.writeData(y, i);
cpu.dataView.setUint16(28, y + 1, true);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x920a) {
/* STY(DEC), 1001 001r rrrr 1010 */
const i = cpu.data[(opcode & 0x1f0) >> 4];
const y = cpu.dataView.getUint16(28, true) - 1;
cpu.dataView.setUint16(28, y, true);
cpu.writeData(y, i);
cpu.cycles++;
} else if (
(opcode & 0xd208) === 0x8208 &&
(opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8)
) {
/* STDY, 10q0 qq1r rrrr 1qqq */
cpu.writeData(
cpu.dataView.getUint16(28, true) +
((opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8)),
cpu.data[(opcode & 0x1f0) >> 4]
);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x8200) {
/* STZ, 1000 001r rrrr 0000 */
cpu.writeData(cpu.dataView.getUint16(30, true), cpu.data[(opcode & 0x1f0) >> 4]);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x9201) {
/* STZ(INC), 1001 001r rrrr 0001 */
const z = cpu.dataView.getUint16(30, true);
cpu.writeData(z, cpu.data[(opcode & 0x1f0) >> 4]);
cpu.dataView.setUint16(30, z + 1, true);
cpu.cycles++;
} else if ((opcode & 0xfe0f) === 0x9202) {
/* STZ(DEC), 1001 001r rrrr 0010 */
const i = cpu.data[(opcode & 0x1f0) >> 4];
const z = cpu.dataView.getUint16(30, true) - 1;
cpu.dataView.setUint16(30, z, true);
cpu.writeData(z, i);
cpu.cycles++;
} else if (
(opcode & 0xd208) === 0x8200 &&
(opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8)
) {
/* STDZ, 10q0 qq1r rrrr 0qqq */
cpu.writeData(
cpu.dataView.getUint16(30, true) +
((opcode & 7) | ((opcode & 0xc00) >> 7) | ((opcode & 0x2000) >> 8)),
cpu.data[(opcode & 0x1f0) >> 4]
);
cpu.cycles++;
} else if ((opcode & 0xfc00) === 0x1800) {
/* SUB, 0001 10rd dddd rrrr */
const val1 = cpu.data[(opcode & 0x1f0) >> 4];
const val2 = cpu.data[(opcode & 0xf) | ((opcode & 0x200) >> 5)];
const R = val1 - val2;
cpu.data[(opcode & 0x1f0) >> 4] = R;
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= (val1 ^ val2) & (val1 ^ R) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= val2 > val1 ? 1 : 0;
sreg |= 1 & ((~val1 & val2) | (val2 & R) | (R & ~val1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xf000) === 0x5000) {
/* SUBI, 0101 KKKK dddd KKKK */
const val1 = cpu.data[((opcode & 0xf0) >> 4) + 16];
const val2 = (opcode & 0xf) | ((opcode & 0xf00) >> 4);
const R = val1 - val2;
cpu.data[((opcode & 0xf0) >> 4) + 16] = R;
let sreg = cpu.data[95] & 0xc0;
sreg |= R ? 0 : 2;
sreg |= 128 & R ? 4 : 0;
sreg |= (val1 ^ val2) & (val1 ^ R) & 128 ? 8 : 0;
sreg |= ((sreg >> 2) & 1) ^ ((sreg >> 3) & 1) ? 0x10 : 0;
sreg |= val2 > val1 ? 1 : 0;
sreg |= 1 & ((~val1 & val2) | (val2 & R) | (R & ~val1)) ? 0x20 : 0;
cpu.data[95] = sreg;
} else if ((opcode & 0xfe0f) === 0x9402) {
/* SWAP, 1001 010d dddd 0010 */
const d = (opcode & 0x1f0) >> 4;
const i = cpu.data[d];
cpu.data[d] = ((15 & i) << 4) | ((240 & i) >>> 4);
} else if (opcode === 0x95a8) {
/* WDR, 1001 0101 1010 1000 */
cpu.onWatchdogReset();
} else if ((opcode & 0xfe0f) === 0x9204) {
/* XCH, 1001 001r rrrr 0100 */
const r = (opcode & 0x1f0) >> 4;
const val1 = cpu.data[r];
const val2 = cpu.data[cpu.dataView.getUint16(30, true)];
cpu.data[cpu.dataView.getUint16(30, true)] = val1;
cpu.data[r] = val2;
}
cpu.pc = (cpu.pc + 1) % cpu.progMem.length;
cpu.cycles++;
} | the_stack |
import { Resource } from 'i18next';
import { Strings as $ } from '../constants/Strings';
import { SharedSlotType } from '../interactionModelGeneration/ModelTypes';
//todo: move this somewhere more appropriate. consider splitting prompts/intents
/**
* Localized data for built-ins.
*
* Contains prompts, reprompts, APL strings, and interaction model data.
*/
export const defaultI18nResources: Resource = {
en: {
translation: {
// DateControl Runtime
DATE_CONTROL_DEFAULT_PROMPT_VALUE_SET: 'OK.',
DATE_CONTROL_DEFAULT_PROMPT_VALUE_CHANGED: 'Changed from {{old}} to {{new}}.',
DATE_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON:
"Sorry but that's not a valid date because {{reason}}.",
DATE_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE: 'Sorry, invalid Date.',
DATE_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE: 'What date?',
DATE_CONTROL_DEFAULT_PROMPT_REQUEST_CHANGED_VALUE: 'What should I change it to?',
DATE_CONTROL_DEFAULT_PROMPT_VALIDATION_FAIL_PAST_DATE_ONLY:
'the date cannot be greater than today',
DATE_CONTROL_DEFAULT_PROMPT_VALIDATION_FAIL_FUTURE_DATE_ONLY:
'the date cannot be less than today',
DATE_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
DATE_CONTROL_DEFAULT_PROMPT_VALUE_AFFIRMED: 'Great.',
DATE_CONTROL_DEFAULT_PROMPT_VALUE_DISAFFIRMED: 'My mistake.',
DATE_CONTROL_DEFAULT_REPROMPT_VALUE_SET: 'OK.',
DATE_CONTROL_DEFAULT_REPROMPT_VALUE_CHANGED: 'Changed from {{old}} to {{new}}.',
DATE_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON:
"Sorry but that's not a valid date because {{reason}}.",
DATE_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE: 'Sorry, invalid Date.',
DATE_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE: 'What date?',
DATE_CONTROL_DEFAULT_REPROMPT_REQUEST_CHANGED_VALUE: 'What should I change it to?',
DATE_CONTROL_DEFAULT_REPROMPT_VALIDATION_FAIL_PAST_DATE_ONLY:
'the date cannot be greater than today',
DATE_CONTROL_DEFAULT_REPROMPT_VALIDATION_FAIL_FUTURE_DATE_ONLY:
'the date cannot be less than today',
DATE_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
DATE_CONTROL_DEFAULT_REPROMPT_VALUE_AFFIRMED: 'Great.',
DATE_CONTROL_DEFAULT_REPROMPT_VALUE_DISAFFIRMED: 'My mistake.',
// NumberControl Runtime
NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_SET: 'Ok. Value set to {{value}}.',
NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_CHANGED: 'Ok. Value changed to {{value}}.',
NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_CLEARED: 'Ok, cleared.',
NUMBER_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON:
"Sorry but that's not a valid choice because {{reason}}.",
NUMBER_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE: "Sorry but that's not a valid choice.",
NUMBER_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE: 'What number?',
NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_CONFIRMED: 'Great.',
NUMBER_CONTROL_DEFAULT_PROMPT_VALUE_DISAFFIRMED: 'My mistake.',
NUMBER_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
NUMBER_CONTROL_DEFAULT_PROMPT_SUGGEST_VALUE: 'Did you perhaps mean {{value}}?',
// RePrompts
NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_SET: 'Ok. Value set to {{value}}.',
NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_CHANGED: 'Ok. Value changed to {{value}}.',
NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_CLEARED: 'Ok, cleared.',
NUMBER_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON:
"Sorry but that's not a valid choice because {{reason}}.",
NUMBER_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE: "Sorry but that's not a valid choice.",
NUMBER_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE: 'What number?',
NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_CONFIRMED: 'Great.',
NUMBER_CONTROL_DEFAULT_REPROMPT_VALUE_DISAFFIRMED: 'My mistake.',
NUMBER_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
NUMBER_CONTROL_DEFAULT_REPROMPT_SUGGEST_VALUE: 'Did you perhaps mean {{value}}?',
NUMBER_CONTROL_DEFAULT_APL_HEADER_TITLE: 'Enter a number...',
NUMBER_CONTROL_DEFAULT_APL_INVALID_VALUE: "Sorry but '{{value}}' is not a valid choice.",
// ValueControl Runtime
VALUE_CONTROL_DEFAULT_PROMPT_VALUE_SET: 'OK, {{value}}.',
VALUE_CONTROL_DEFAULT_PROMPT_VALUE_CHANGED: 'OK, I changed it to {{value}}.',
VALUE_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON:
'Sorry, {{value}} is not a valid choice because {{reason}}.',
VALUE_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE: 'Sorry, {{value}} is not a valid choice.',
VALUE_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE: 'What should i set it to?',
VALUE_CONTROL_DEFAULT_PROMPT_REQUEST_CHANGED_VALUE: 'What should I change it to?',
VALUE_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
VALUE_CONTROL_DEFAULT_PROMPT_VALUE_AFFIRMED: 'Great.',
VALUE_CONTROL_DEFAULT_PROMPT_VALUE_DISAFFIRMED: 'My mistake.',
// RePrompts
VALUE_CONTROL_DEFAULT_REPROMPT_VALUE_SET: 'OK, {{value}}.',
VALUE_CONTROL_DEFAULT_REPROMPT_VALUE_CHANGED: 'OK, I changed it to {{value}}.',
VALUE_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON:
'Sorry, {{value}} is not a valid choice because {{reason}}.',
VALUE_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE: 'Sorry, {{value}} is not a valid choice.',
VALUE_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE: 'What should i set it to?',
VALUE_CONTROL_DEFAULT_REPROMPT_REQUEST_CHANGED_VALUE: 'What should I change it to?',
VALUE_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
VALUE_CONTROL_DEFAULT_REPROMPT_VALUE_AFFIRMED: 'Great.',
VALUE_CONTROL_DEFAULT_REPROMPT_VALUE_DISAFFIRMED: 'My mistake.',
// ListControl Runtime
LIST_CONTROL_DEFAULT_PROMPT_VALUE_SET: 'OK, {{value}}.',
LIST_CONTROL_DEFAULT_PROMPT_VALUE_CHANGED: 'OK, I changed it to {{value}}.',
LIST_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE: 'Sorry, {{value}} is not a valid choice.',
LIST_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON:
'Sorry, {{value}} is not a valid choice because {{reason}}.',
LIST_CONTROL_DEFAULT_PROMPT_UNUSABLE_INPUT_VALUE: "Sorry, I'm not sure how to do that.",
LIST_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE:
'What is your selection? Some suggestions are {{suggestions}}.',
LIST_CONTROL_DEFAULT_PROMPT_REQUEST_CHANGED_VALUE:
'What should I change it to? Some suggestions are {{suggestions}}.',
LIST_CONTROL_DEFAULT_PROMPT_REQUEST_REMOVED_VALUE:
'What value do you want to remove? Some suggestions are {{suggestions}}.',
LIST_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
LIST_CONTROL_DEFAULT_PROMPT_VALUE_AFFIRMED: 'Great.',
LIST_CONTROL_DEFAULT_PROMPT_VALUE_DISAFFIRMED: 'My mistake.',
// RePrompts
LIST_CONTROL_DEFAULT_REPROMPT_VALUE_SET: 'OK, {{value}}.',
LIST_CONTROL_DEFAULT_REPROMPT_VALUE_CHANGED: 'OK, I changed it to {{value}}.',
LIST_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE: 'Sorry, {{value}} is not a valid choice.',
LIST_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON:
'Sorry, {{value}} is not a valid choice because {{reason}}.',
LIST_CONTROL_DEFAULT_REPROMPT_UNUSABLE_INPUT_VALUE: "Sorry, I'm not sure how to do that.",
LIST_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE:
'What is your selection? Some suggestions are {{suggestions}}.',
LIST_CONTROL_DEFAULT_REPROMPT_REQUEST_CHANGED_VALUE:
'What should I change it to? Some suggestions are {{suggestions}}.',
LIST_CONTROL_DEFAULT_REPROMPT_REQUEST_REMOVED_VALUE:
'What value do you want to remove? Some suggestions are {{suggestions}}.',
LIST_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
LIST_CONTROL_DEFAULT_REPROMPT_VALUE_AFFIRMED: 'Great.',
LIST_CONTROL_DEFAULT_REPROMPT_VALUE_DISAFFIRMED: 'My mistake.',
LIST_CONTROL_DEFAULT_APL_HEADER_TITLE: 'Please select',
// MultiValueListControl Runtime
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_VALUE_ADD: 'OK, added {{value}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_VALUE_REMOVE: 'OK, removed {{value}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_VALUE_CLEARED: 'OK, cleared {{value}} from the list.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_ACTION_SUGGEST:
'You can add new values or update existing values',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE:
"Sorry, {{value}} can't be added it doesn't exist.",
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON:
"Sorry, {{value}} can't be added as {{reason}}.",
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_REMOVE_VALUE:
'Sorry, {{value}} is not in the list.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE:
'What is your selection? Some suggestions are {{suggestions}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_REQUEST_REMOVED_VALUE:
'What value do you want to remove? Some suggestions are {{suggestions}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_GENERAL_REQUEST_REMOVED_VALUE:
'What value do you want to remove?',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE: 'OK, I have {{value}}. Is that all?',
MULTI_VALUE_LIST_CONTROL_DEFAULT_PROMPT_VALUE_AFFIRMED: 'Great.',
// RePrompts
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_VALUE_ADD: 'OK, added {{value}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_VALUE_REMOVE: 'OK, removed {{value}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_VALUE_CLEARED: 'OK, cleared {{value}} from the list.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_ACTION_SUGGEST:
'You can add new values or update existing values',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE:
"Sorry, {{value}} can't be added it doesn't exist.",
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_REMOVE_VALUE:
'Sorry, {{value}} is not in the list.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON:
"Sorry, {{value}} can't be added as {{reason}}.",
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE:
'What is your selection? Some suggestions are {{suggestions}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_REQUEST_REMOVED_VALUE:
'What value do you want to remove? Some suggestions are {{suggestions}}.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_GENERAL_REQUEST_REMOVED_VALUE:
'What value do you want to remove?',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE: 'Ok I have {{value}}. Is that all?',
MULTI_VALUE_LIST_CONTROL_DEFAULT_REPROMPT_VALUE_AFFIRMED: 'Great.',
MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_HEADER_TITLE: 'Create your list',
MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_HEADER_SUBTITLE:
'Say an item or touch it to add it your list',
MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_SELECTION_TITLE: 'YOUR SELECTIONS',
MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_SELECTION_SUBTITLE: 'Swipe left to remove items',
// DateRangeControl Runtime
DATE_RANGE_CONTROL_DEFAULT_PROMPT_START_DATE_SET: 'Got it. The start date is {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_START_DATE_CHANGED:
'Got it. The start date is changed to {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_REQUEST_START_DATE: 'What is the start date you want?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_REQUEST_CHANGED_START_DATE:
'What should I change the start date to?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_CONFIRM_START_DATE: 'Was that {{value}}?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_START_DATE_AFFIRMED: 'Great.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_START_DATE_DISAFFIRMED: 'My mistake.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_END_DATE_SET: 'Got it. The end date is {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_END_DATE_CHANGED:
'Got it. The end date is changed to {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_REQUEST_END_DATE: 'What is the end date you want?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_REQUEST_CHANGED_END_DATE:
'What should I change the end date to?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_CONFIRM_END_DATE: 'Was that {{value}}?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_END_DATE_AFFIRMED: 'Great.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_END_DATE_DISAFFIRMED: 'My mistake.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_REQUEST_VALUE: 'What is the start date and end date you want?',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_VALUE_SET: 'Got it. The date range is {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_VALUE_CHANGED:
'Got it. The date range is changed to {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_INVALID_START_WITH_REASON:
"Sorry but that's not a valid start date because {{reason}}.",
DATE_RANGE_CONTROL_DEFAULT_PROMPT_INVALID_END_WITH_REASON:
"Sorry but that's not a valid end date because {{reason}}.",
DATE_RANGE_CONTROL_DEFAULT_PROMPT_INVALID_VALUE_WITH_REASON:
'Sorry, invalid range because {{reason}}.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_DATE: 'Sorry, invalid date.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_GENERAL_INVALID_VALUE: 'Sorry, invalid range.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_VALIDATION_FAIL_START_AFTER_END:
'start date can not be greater than end date',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_VALUE_AFFIRMED: 'Great.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_VALUE_DISAFFIRMED: 'My mistake.',
DATE_RANGE_CONTROL_DEFAULT_PROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_START_DATE_SET: 'Got it. The start date is {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_START_DATE_CHANGED:
'Got it. The start date is changed to {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_REQUEST_START_DATE: 'What is the start date you want?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_REQUEST_CHANGED_START_DATE:
'What should I change the start date to?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_CONFIRM_START_DATE: 'Was that {{value}}?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_START_DATE_AFFIRMED: 'Great.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_START_DATE_DISAFFIRMED: 'My mistake.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_END_DATE_SET: 'Got it. The end date is {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_END_DATE_CHANGED:
'Got it. The end date is changed to {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_REQUEST_END_DATE: 'What is the end date you want?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_REQUEST_CHANGED_END_DATE:
'What should I change the end date to?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_CONFIRM_END_DATE: 'Was that {{value}}?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_END_DATE_AFFIRMED: 'Great.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_END_DATE_DISAFFIRMED: 'My mistake.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_REQUEST_VALUE:
'What is the start date and end date you want?',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_VALUE_SET: 'Got it. The date range is {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_VALUE_CHANGED:
'Got it. The date range is changed to {{value}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_INVALID_START_WITH_REASON:
"Sorry but that's not a valid start date because {{reason}}.",
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_INVALID_END_WITH_REASON:
"Sorry but that's not a valid end date because {{reason}}.",
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_INVALID_VALUE_WITH_REASON:
'Sorry, invalid range because {{reason}}.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_DATE: 'Sorry, invalid date.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_GENERAL_INVALID_VALUE: 'Sorry, invalid range.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_VALIDATION_FAIL_START_AFTER_END:
'start date can not be greater than end date',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_VALUE_AFFIRMED: 'Great.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_VALUE_DISAFFIRMED: 'My mistake.',
DATE_RANGE_CONTROL_DEFAULT_REPROMPT_CONFIRM_VALUE: 'Was that {{value}}?',
// QuestionnaireControl
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_QUESTION_ANSWERED_LOW_RISK_OF_MISUNDERSTANDING: '',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_QUESTION_ANSWERED_RISK_OF_MISUNDERSTANDING_CHOICE:
'OK, {{choice}}.',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_QUESTION_ANSWERED_RISK_OF_MISUNDERSTANDING_QUESTION_AND_CHOICE:
'OK, {{choice}} for {{question}}.',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_COMPLETED: 'Great, thank you.',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_COMPLETION_REJECTED:
'Sorry, {{renderedReason}} is not a valid choice.',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_ACKNOWLEDGE_NOT_COMPLETE:
'No problem. Just let me know when you are done.',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_ASK_IF_COMPLETE: 'Are you happy with all answers?',
QUESTIONNAIRE_CONTROL_DEFAULT_PROMPT_ASK_IF_COMPLETE_TERSE: '',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_QUESTION_ANSWERED_LOW_RISK_OF_MISUNDERSTANDING: '',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_QUESTION_ANSWERED_RISK_OF_MISUNDERSTANDING_CHOICE:
'OK, {{choice}}.',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_QUESTION_ANSWERED_RISK_OF_MISUNDERSTANDING_QUESTION_AND_CHOICE:
'OK, {{choice}} for {{question}}.',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_COMPLETED: 'Great, thank you.',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_COMPLETION_REJECTED:
'Sorry, {{renderedReason}} is not a valid choice.',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_ACKNOWLEDGE_NOT_COMPLETE:
'No problem. Just let me know when you are done.',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_ASK_IF_COMPLETE: 'Are you happy with all answers?',
QUESTIONNAIRE_CONTROL_DEFAULT_REPROMPT_ASK_IF_COMPLETE_TERSE: '',
QUESTIONNAIRE_CONTROL_DEFAULT_APL_HEADER_TITLE: 'Please select...',
QUESTIONNAIRE_CONTROL_DEFAULT_APL_SUBMIT_TEXT: 'Submit >',
// Content Act default prompts
UNUSABLE_INPUT_VALUE_ACT_DEFAULT_PROMPT: `Sorry, {{value}}.`,
ACKNOWLEDGE_INPUT_ACT_DEFAULT_PROMPT: 'OK.',
VALUE_SET_ACT_DEFAULT_PROMPT: `OK, {{value}}.`,
VALUE_CHANGED_ACT_DEFAULT_PROMPT: `Ok, updated to {{value}}.`,
INVALID_VALUE_ACT_DEFAULT_PROMPT: `Sorry, {{value}}.`,
VALUE_CONFIRMED_ACT_DEFAULT_PROMPT: 'Great.',
VALUE_DISCONFIRMED_ACT_DEFAULT_PROMPT: 'My mistake.',
NON_UNDERSTANDING_ACT_DEFAULT_PROMPT: "Sorry I didn't understand that.",
LAUNCH_ACT_DEFAULT_PROMPT: 'Welcome.',
VALUE_ADDED_ACT_DEFAULT_PROMPT: `OK, added {{value}}.`,
VALUE_REMOVED_ACT_DEFAULT_PROMPT: `OK, removed {{value}}.`,
VALUE_CLEARED_ACT_DEFAULT_PROMPT: `OK, cleared {{value}}.`,
INVALID_REMOVE_VALUE_ACT_DEFAULT_PROMPT: `Sorry, invalid {{value}}.`,
// Initiative Act default prompts
REQUEST_VALUE_ACT_DEFAULT_PROMPT: `What value for {{value}}.`,
REQUEST_CHANGED_VALUE_ACT_DEFAULT_PROMPT: `What is the new value for {{value}}.`,
REQUEST_VALUE_BY_LIST_ACT_DEFAULT_PROMPT: `What value for {{value}}? Choices include {{choices}}`,
REQUEST_CHANGED_VALUE_BY_LIST_ACT_DEFAULT_PROMPT: `What is the new value for {{value}}? Choices include {{choices}}.`,
REQUEST_REMOVED_VALUE_BY_LIST_ACT_DEFAULT_PROMPT: `What value to remove for {{value}}? Choices include {{choices}}.`,
CONFIRM_VALUE_ACT_DEFAULT_PROMPT: `Was that {{value}}.`,
SUGGEST_VALUE_ACT_DEFAULT_PROMPT: `Did you perhaps mean {{value}}?`,
SUGGEST_ACTION_ACT_DEFAULT_PROMPT: 'You can add or update values.',
// ControlIntent Samples
/*
* ConjunctionControlIntent is for controls that accept multiple values
* It will likely be replaced when support for multi-value slots is added.
*/
CONJUNCTION_CONTROL_INTENT_SAMPLES: [
'{action} {target.a} {conjunction} {target.b}', // {change} {start} {and} {end}
'{feedback} {action} {target.a} {conjunction} {target.b}', // {yes} {change} {start} {and} {end}
'{head} {action} {target.a} {conjunction} {target.b}', // {just} {change} {start} {and} {end}
'{action} {target.a} {conjunction} {target.b} {tail}', // {change} {start} {and} {end} {please}
'{feedback} {action} {target.a} {conjunction} {target.b} {tail}', // {yes} {change} {start} {and} {end} {please}
'{head} {action} {target.a} {conjunction} {target.b} {tail}', // {just} {change} {start} {and} {end} {please}
],
/*
* Example values for AMAZON.DATE (see https://developer.amazon.com/en-US/docs/alexa/custom-skills/slot-type-reference.html#date)
* "tomorrow"
* "monday" | "next monday"
* "last monday"
* "may first"
* "next week"
* "next month"
* "next weekend"
* "last weekend"
* "christmas day"
*/
DATE_CONTROL_INTENT_SAMPLES: [
'{AMAZON.DATE}', // {monday}
'{action} {preposition} {AMAZON.DATE}', // {set} {to} {monday}
'{action} {target} {preposition} {AMAZON.DATE}', // {set} {delivery} {to} {monday}
'{target} {preposition} {AMAZON.DATE}', // {delivery} {should be} {monday}
'{feedback} {AMAZON.DATE}', // {yes} {monday}
'{feedback} {preposition} {AMAZON.DATE}', // {yes} {to} {monday}
'{feedback} {action} {preposition} {AMAZON.DATE}', // {yes} {set} {to} {monday}
'{feedback} {action} {target} {preposition} {AMAZON.DATE}', // {yes} {set} {delivery} {to} {monday}
'{feedback} {target} {preposition} {AMAZON.DATE}', // {yes} {delivery} {should be} {monday}
'{head} {AMAZON.DATE}', // {I want} {monday}
'{head} {action} {preposition} {AMAZON.DATE}', // {just} {set} {to} {monday}
'{head} {action} {target} {preposition} {AMAZON.DATE}', // {You can} {change} {delivery} {to be} {monday}
'{head} {target} {preposition} {AMAZON.DATE}', // {I want} {delivery} {to be} {monday}
'{AMAZON.DATE} {tail}', // {monday} {please}
'{preposition} {AMAZON.DATE} {tail}', // {to} {monday} {please}
'{action} {preposition} {AMAZON.DATE} {tail}', // {set} {to} {monday} {please}
'{action} {target} {preposition} {AMAZON.DATE} {tail}', // {set} {delivery} {to} {monday} {thanks}
'{target} {preposition} {AMAZON.DATE} {tail}', // {delivery} {should be} {monday} {thanks}
'{feedback} {AMAZON.DATE} {tail}', // {yes} {monday} {will be great}
'{feedback} {preposition} {AMAZON.DATE} {tail}', // {yes} {to} {monday} {please}
'{feedback} {action} {preposition} {AMAZON.DATE} {tail}', // {yes} {set} {to} {monday} {please}
'{feedback} {action} {target} {preposition} {AMAZON.DATE} {tail}', // {yes} {set} {delivery} {to} {monday} {thanks}
'{feedback} {target} {preposition} {AMAZON.DATE} {tail}', // {yes} {delivery} {is} {monday} {thanks}
'{head} {AMAZON.DATE} {tail}', // {Just} {monday} {please}
'{head} {preposition} {AMAZON.DATE} {tail}', // {Just} {to} {monday} {thanks}
'{head} {action} {preposition} {AMAZON.DATE} {tail}', // {I want to} {change} {to} {monday} {thanks}
'{head} {target} {preposition} {AMAZON.DATE} {tail}', // {I need} {delivery} {to be} {monday} {thanks}
'{head} {action} {target} {preposition} {AMAZON.DATE} {tail}', // {You can} {change} {delivery} {to be} {monday} {thanks}
],
// Note: every sample should have two dates. For utterances with zero or one date use SimpleControlIntent or DateControlIntent.
DATE_RANGE_CONTROL_INTENT_SAMPLES: [
'{AMAZON.DATE.a} {conjunction} {AMAZON.DATE.b}', // {monday} {and} {friday}
'{AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {monday} {to} {friday}
'{preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {from} {monday} {to} {friday}
'between {AMAZON.DATE.a} and {AMAZON.DATE.b}', // between {monday} and {friday}
'{action} {preposition.a} {AMAZON.DATE.a} {conjunction} {AMAZON.DATE.b}', // {set} {to} {monday} {and} {friday}
'{action} {preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {change} {to} {monday} {to} {friday}
'{action} between {AMAZON.DATE.a} and {AMAZON.DATE.b}', // {set} between {monday} and {friday}
'{action} {target} {preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {change} {blackout} {to} {monday} {to} {friday}
'{action} {target} between {AMAZON.DATE.a} and {AMAZON.DATE.b}', // {set} {blackout} between {monday} and {friday}
'{action} {target.a} {preposition.a} {AMAZON.DATE.a} {conjunction} {target.b} {preposition.b} {AMAZON.DATE.b}', // {change} {start} {to} {monday} and {end} {to} {friday}
'{feedback} {AMAZON.DATE.a} {conjunction} {AMAZON.DATE.b}', // {yes} {monday} {and} {friday}
'{feedback} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {yes} {monday} {to} {friday}
'{feedback} {preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {yes} {from} {monday} {to} {friday}
'{feedback} between {AMAZON.DATE.a} and {AMAZON.DATE.b}', // {yes} between {monday} and {friday}
'{head} {AMAZON.DATE.a} {conjunction} {AMAZON.DATE.b}', // {I think} {monday} {and} {friday}
'{head} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {I think} {monday} {to} {friday}
'{head} {preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b}', // {I think} {from} {monday} {to} {friday}
'{head} between {AMAZON.DATE.a} and {AMAZON.DATE.b}', // {I think} between {monday} and {friday}
'{AMAZON.DATE.a} {conjunction} {AMAZON.DATE.b} {tail}', // {monday} {and} {friday} {please}
'{AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b} {tail}', // {monday} {to} {friday} {please}
'{preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b} {tail}', // {from} {monday} {to} {friday} {please}
'between {AMAZON.DATE.a} and {AMAZON.DATE.b} {tail}', // between {monday} and {friday} {please}
'{head} {AMAZON.DATE.a} {conjunction} {AMAZON.DATE.b} {tail}', // {I think} {monday} {and} {friday} {thanks}
'{head} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b} {tail}', // {I think} {monday} {to} {friday} {thanks}
'{head} {preposition.a} {AMAZON.DATE.a} {preposition.b} {AMAZON.DATE.b} {tail}', // {I think} {from} {monday} {to} {friday} {thanks}
'{head} between {AMAZON.DATE.a} and {AMAZON.DATE.b} {tail}', // {I think} between {monday} and {friday} {thanks}
],
/*
* For consideration:
* * trailing feedback, e.g. "{action} {is correct}" | "{it} {is correct}"
* Currently this type of trailing feedback is captured using {tail} and it is not used by control logic.
* A complication is that users might say "yes it is correct"
* - simple slot capture can't handle non-adjacent words
* - We don't really want to deal with two separate feedback slots and have to reconcile them.
* - So for now only the leading feedback is 'active' and we typically ignore the tail slot.
*/
GENERAL_CONTROL_INTENT_SAMPLES: [
// "{feedback}", // {Yes} // For bare feedback utterances, use specific simple intents, eg AMAZON.YesIntent.
'{feedback} {action}', // {No}, {delete}
'{feedback} {action} {target}', // {Yes}, {change} {the delivery date}
'{filteredFeedback} {tail}', // {Yes}, {thanks}
'{feedback} {action} {tail}', // {Yes} {review} {would be great}
'{feedback} {action} {target} {tail}', // {Yes} {review} {the delivery date} {please}
// "{action}", // For bare action utterances, use specific simple intents to be compatible with existing ecosystem.
'{target}', // {delivery date}
'{feedback} {target}', // {Yes}, {delivery date}'
'{head} {target}', // {just} {delivery date}'
'{target} {tail}', // {delivery date} {please}'
'{action} {target}', // {change} {start date}
'{head} {action}', // {just} {delete}
'{head} {action} {target}', // {just} {delete} {it}
'{action} {tail}', // {delete} {is correct}
'{action} {target} {tail}', // {update} {my address} {please}
'{head} {action} {tail}', // {go ahead and} {delete} {thanks}
'{head} {action} {target} {tail}', // {go ahead and} {delete} {the item} {thanks}
],
NUMBER_CONTROL_INTENT_SAMPLES: [
'{AMAZON.NUMBER}', // {three}
'{action} {AMAZON.NUMBER}', // {add} {three}
'{action} {preposition} {AMAZON.NUMBER}', // {set} {to} {three}
'{action} {target} {preposition} {AMAZON.NUMBER}', // {set} {quantity} {to} {three}
'{target} {preposition} {AMAZON.NUMBER}', // {quantity} {is} {three}
'{feedback} {AMAZON.NUMBER}', // {yes} {three}
'{feedback} {action} {AMAZON.NUMBER}', // {yes} {add} {three}
'{feedback} {preposition} {AMAZON.NUMBER}', // {yes} {to} {three}
'{feedback} {action} {preposition} {AMAZON.NUMBER}', // {yes} {set} {to} {three}
'{feedback} {action} {target} {preposition} {AMAZON.NUMBER}', // {yes} {set} {quantity} {to} {three}
'{feedback} {target} {preposition} {AMAZON.NUMBER}', // {yes} {quantity} {should be} {three}
'{head} {AMAZON.NUMBER}', // {I want} {three}
'{head} {action} {AMAZON.NUMBER}', // {just} {add} {three}
'{head} {action} {preposition} {AMAZON.NUMBER}', // {just} {set} {to} {three}
'{head} {action} {target} {preposition} {AMAZON.NUMBER}', // {You can} {change} {quantity} {to be} {three}
'{head} {target} {preposition} {AMAZON.NUMBER}', // {I want} {quantity} {to be} {three}
'{AMAZON.NUMBER} {tail}', // {three} {please}
'{preposition} {AMAZON.NUMBER} {tail}', // {to} {three} {please}
'{action} {preposition} {AMAZON.NUMBER} {tail}', // {set} {to} {three} {please}
'{action} {target} {preposition} {AMAZON.NUMBER} {tail}', // {set} {quantity} {to} {three} {thanks}
'{target} {preposition} {AMAZON.NUMBER} {tail}', // {quantity} {should be} {three} {thanks}
'{feedback} {AMAZON.NUMBER} {tail}', // {yes} {three} {will be great}
'{feedback} {preposition} {AMAZON.NUMBER} {tail}', // {yes} {to} {three} {please}
'{feedback} {action} {AMAZON.NUMBER} {tail}', // {yes} {add} {three} {please}
'{feedback} {action} {preposition} {AMAZON.NUMBER} {tail}', // {yes} {set} {to} {three} {please}
'{feedback} {action} {target} {preposition} {AMAZON.NUMBER} {tail}', // {yes} {set} {quantity} {to} {three} {thanks}
'{feedback} {target} {preposition} {AMAZON.NUMBER} {tail}', // {yes} {quantity} {is} {three} {thanks}
'{head} {AMAZON.NUMBER} {tail}', // {Just} {three} {please}
'{head} {preposition} {AMAZON.NUMBER} {tail}', // {Just} {to} {three} {thanks}
'{head} {action} {AMAZON.NUMBER} {tail}', // {I want to} {add} {three} {thanks}
'{head} {action} {preposition} {AMAZON.NUMBER} {tail}', // {I want to} {change} {to} {three} {thanks}
'{head} {target} {preposition} {AMAZON.NUMBER} {tail}', // {I need} {quantity} {to be} {three} {thanks}
'{head} {action} {target} {preposition} {AMAZON.NUMBER} {tail}', // {You can} {change} {quantity} {to be} {three} {thanks}
],
ORDINAL_CONTROL_INTENT_SAMPLES: [
'{AMAZON.Ordinal}', // {first}
'{preposition} {AMAZON.Ordinal}', // {the} {first}
'{AMAZON.Ordinal} one', // {first} one
'{preposition} {AMAZON.Ordinal} one', // {the} {first} one
'{action} {AMAZON.Ordinal}', // {select} {first}
'{action} {preposition} {AMAZON.Ordinal}', // {select} {the} {first}
'{action} {preposition} {AMAZON.Ordinal} one', // {select} {the} {first} one
'{action} {target} {preposition} {AMAZON.Ordinal}', // {Move} {Bob} {to} {second}
'{target} {preposition} {AMAZON.Ordinal}', // {Bob} {is} {first}
'{feedback} {AMAZON.Ordinal}', // {yes} {first}
'{feedback} {preposition} {AMAZON.Ordinal}', // {yes} {the} {first}
'{feedback} {AMAZON.Ordinal} one', // {yes} {first} one
'{feedback} {preposition} {AMAZON.Ordinal} one', // {yes} {the} {first} one
'{feedback} {action} {AMAZON.Ordinal}', // {yes} {select} {first}
'{feedback} {action} {preposition} {AMAZON.Ordinal}', // {yes} {select} {the} {first}
'{feedback} {action} {preposition} {AMAZON.Ordinal} one', // {yes} {select} {the} {first} one
'{feedback} {action} {target} {preposition} {AMAZON.Ordinal}', // {yes} {Move} {Bob} {to} {second}
'{feedback} {target} {preposition} {AMAZON.Ordinal}', // {yes} {Bob} {is} {first}
'{head} {preposition} {AMAZON.Ordinal}', // {I want} {the} {first}
'{head} {preposition} {AMAZON.Ordinal} one', // {I want} {the} {first} one
'{head} {action} {preposition} {AMAZON.Ordinal}', // {just} {select} {the} {first}
'{head} {action} {target} {preposition} {AMAZON.Ordinal}', // {You can} {change} {Bob} {to be} {first}
'{head} {target} {preposition} {AMAZON.Ordinal}', // {I need} {Bob} {to go} {first}
'{AMAZON.Ordinal} {tail}', // {first} {please}
'{preposition} {AMAZON.Ordinal} {tail}', // {the} {first} {please}
'{AMAZON.Ordinal} one {tail}', // {first} one {please}
'{preposition} {AMAZON.Ordinal} one {tail}', // {the} {first} one {please}
'{action} {AMAZON.Ordinal} {tail}', // {select} {first} {please}
'{action} {target} {preposition} {AMAZON.Ordinal} {tail}', // {Move} {Bob} {to} {second} {thanks}
'{target} {preposition} {AMAZON.Ordinal} {tail}', // {Bob} {is} {first} {thanks}
'{feedback} {AMAZON.Ordinal} {tail}', // {yes} {first} {will be great}
'{feedback} {preposition} {AMAZON.Ordinal} {tail}', // {yes} {the} {first} {please}
'{feedback} {AMAZON.Ordinal} one {tail}', // {yes} {first} one {please}
'{feedback} {preposition} {AMAZON.Ordinal} one {tail}', // {yes} {the} {first} one {please}
'{feedback} {action} {AMAZON.Ordinal} {tail}', // {yes} {select} {first} {please}
'{feedback} {action} {preposition} {AMAZON.Ordinal} {tail}', // {yes} {select} {the} {first} {please}
'{feedback} {action} {preposition} {AMAZON.Ordinal} one {tail}', // {yes} {select} {the} {first} one {please}
'{feedback} {action} {target} {preposition} {AMAZON.Ordinal} {tail}', // {yes} {Move} {Bob} {to} {second} {thanks}
'{feedback} {target} {preposition} {AMAZON.Ordinal} {tail}', // {yes} {Bob} {is} {first} {thanks}
'{head} {AMAZON.Ordinal} {tail}', // {Just} {first} {please}
'{head} {preposition} {AMAZON.Ordinal} {tail}', // {I want} {the} {first} {thanks}
'{head} {preposition} {AMAZON.Ordinal} one {tail}', // {I want} {the} {first} {one} {thanks}
'{head} {action} {preposition} {AMAZON.Ordinal} {tail}', // {I want to} {change} {the} {first} {thanks}
'{head} {action} {preposition} {AMAZON.Ordinal} one {tail}', // {I want to} {change} {the} {first} one {thanks}
'{head} {target} {preposition} {AMAZON.Ordinal} {tail}', // {I need} {Bob} {to go} {first} {thanks}
'{head} {action} {target} {preposition} {AMAZON.Ordinal} {tail}', // {You can} {change} {Bob} {to be} {first} {thanks}
],
VALUE_CONTROL_INTENT_SAMPLES: [
'[[filteredValueSlotType]]', // {Apples}, assuming 'apples' matches a value of the slotType.
'{action} [[valueSlotType]]', // {select} {apples}
'{action} {preposition} [[valueSlotType]]', // {change} {to} {apples}
'{action} {target} {preposition} [[valueSlotType]]', // {change} {my choice} {to} {apples}
'{target} {preposition} [[valueSlotType]]', // {my favorite fruit} {is} {apples}
'{target} [[valueSlotType]]', // {have headache} {frequently}
'{feedback} [[filteredValueSlotType]]', // {yes} {apples}
'{feedback} {action} [[valueSlotType]]', // {yes} {add} {apples}
'{feedback} {preposition} [[filteredValueSlotType]]', // {yes} {to} {apples}
'{feedback} {action} {preposition} [[valueSlotType]]', // {yes} {change} {to} {apples}
'{feedback} {action} {target} {preposition} [[valueSlotType]]', // {yes} {set} {my choice} {to} {apples}
'{feedback} {target} {preposition} [[valueSlotType]]', // {yes} {my choice} {is} {three}
'{feedback} {target} [[valueSlotType]]', // {yes} {I have headache} {frequently}
'{head} [[filteredValueSlotType]]', // {I want} {apples}
'{head} {action} [[valueSlotType]]', // {just} {add} {apples}
'{head} {action} {preposition} [[valueSlotType]]', // {just} {set} {to} {apples}
'{head} {action} {target} {preposition} [[valueSlotType]]', // {You can} {change} {my choice} {to be} {apples}
'{head} {target} {preposition} [[valueSlotType]]', // {I want} {it} {to be} {apples}
'{head} {target} [[valueSlotType]]', // {well} {I have headache} {frequently}
'[[filteredValueSlotType]] {tail}', // {apples} {please}
'{preposition} [[filteredValueSlotType]] {tail}', // {to} {apples} {please}
'{action} {preposition} [[valueSlotType]] {tail}', // {set} {to} {apples} {please}
'{action} {target} {preposition} [[valueSlotType]] {tail}', // {set} {it} {to} {apples} {thanks}
'{target} {preposition} [[valueSlotType]] {tail}', // {it} {should be} {apples} {thanks}
'{feedback} [[filteredValueSlotType]] {tail}', // {yes} {apples} {will be great}
'{feedback} {preposition} [[filteredValueSlotType]] {tail}', // {yes} {to} {apples} {please}
'{feedback} {action} [[valueSlotType]] {tail}', // {yes} {add} {apples} {please}
'{feedback} {action} {preposition} [[valueSlotType]] {tail}', // {yes} {set} {to} {apples} {please}
'{feedback} {action} {target} {preposition} [[valueSlotType]] {tail}', // {yes} {change} {my choice} {to} {apples} {thanks}
'{feedback} {target} {preposition} [[valueSlotType]] {tail}', // {yes} {my choice} {is} {apples} {thanks}
'{feedback} {target} [[valueSlotType]] {tail}', // {yes} {I get headaches} {frequently} {for some reason}
'{head} [[filteredValueSlotType]] {tail}', // {Just} {apples} {please}
'{head} {preposition} [[filteredValueSlotType]] {tail}', // {Just} {to} {apples} {thanks}
'{head} {action} [[valueSlotType]] {tail}', // {I want to} {add} {apples} {thanks}
'{head} {action} {preposition} [[valueSlotType]] {tail}', // {I want to} {change} {to} {apples} {thanks}
'{head} {target} {preposition} [[valueSlotType]] {tail}', // {I need} {it} {to be} {apples} {thanks}
'{head} {target} [[valueSlotType]] {tail}', // {I just} {get headaches} {frequently} {for some reason}
'{head} {action} {target} {preposition} [[valueSlotType]] {tail}', // {You can} {change} {it} {to be} {apples} {thanks}
// new things for questionnaire control. // TODO: integrate into main list.
'[[valueSlotType]] {target}', // {I rarely have} {headache}
'{feedback} [[valueSlotType]] {target}', // {correct} {I rarely have} {headache}
'{head} [[valueSlotType]] {target}', // {I only} {rarely get} {headache}
'[[valueSlotType]] {target} {tail}', // {I frequently have} {headache} {for some reason}
'{head} [[valueSlotType]] {target} {tail}', // {I just} {I frequently have} {headache} {for some reason}
],
// Shared Slot Type values
SHARED_SLOT_TYPES_FEEDBACK: {
name: SharedSlotType.FEEDBACK,
values: [
{
id: $.Feedback.Affirm,
name: {
value: 'affirm',
synonyms: [
'yes I do',
'okay',
'kay',
'k',
'yes',
'yup',
'yep',
'yes',
'ya',
'yes I want', // TODO: consider splitting out as action=desire.
'yes I need',
'yes I said',
"yes that's right",
"that's correct",
'ah yes',
'affirmative',
'makes sense',
'right',
'sounds good',
'sure',
"that's right",
'totally',
'works for me',
'yeah',
'yeah ok',
'yes ok',
"yes that's good",
'yes sure',
'yes good',
'yes exactly',
'exactly',
'yes I do',
'absolutely',
'yes absolutely',
'fine',
'yes fine',
'I have',
'yes I have',
],
},
},
{
id: $.Feedback.Disaffirm,
name: {
value: 'disaffirm',
synonyms: [
'no',
'no no',
'no no no',
'no no no no',
'no I want',
'no I said',
'no not that',
'not even close',
'nope',
'incorrect',
'you misunderstood',
'you have it wrong',
"that's wrong",
'thats wrong',
'wrong',
'absolutely not',
"I don't think so",
'naw',
'naw',
'negative',
'never',
'no alexa',
'no amazon',
'no incorrect',
"no that's wrong",
"no it's not",
'definitely not',
'no definitely not',
'not ever',
'oh no',
'ohh no',
'o no no',
'please no',
"that's not what I want",
'that was totally wrong',
'that is totally wrong',
'that is wrong',
'I do not have',
"I don't have",
'I do not',
"I don't",
'no I do not',
"no I don't",
'no I do not have',
'no I do not have',
"no I don't have",
"no I don't have",
],
},
},
],
},
SHARED_SLOT_TYPES_FILTERED_FEEDBACK: {
name: SharedSlotType.FILTERED_FEEDBACK,
values: [
{
id: 'placeholder',
name: {
value: 'placeholder_awaiting_real_values',
synonyms: ['placeholder_awaiting_real_values_synonym'],
},
},
],
},
SHARED_SLOT_TYPES_HEAD: {
name: SharedSlotType.HEAD,
values: [
{
id: $.Head,
name: {
value: 'head',
synonyms: [
'I',
"I'll",
'please',
'thanks',
'thank you',
'I will',
'I want you to',
'I want you to just',
'I need you to',
'I need you to just',
'I think',
'I think just',
'I think I want',
'I think I need',
'I think you can',
'I think you can just',
'I think that',
"I'm pretty sure",
"I'm pretty sure that",
'I am pretty sure',
'I am pretty sure that',
'I believe',
'I believe that',
'You can',
'You can just',
'You can just go ahead and',
'You should',
'You should just',
'Just',
'Go ahead and',
'Just go ahead',
'Just go ahead and',
'I only',
],
},
},
],
},
SHARED_SLOT_TYPES_TAIL: {
name: SharedSlotType.TAIL,
values: [
{
id: $.Tail,
name: {
value: 'tail',
synonyms: [
'please',
'thanks',
'now please',
'now thanks',
'please thanks',
'will be fine',
'will be fine thanks',
'is good',
'is good thanks',
'will be good',
'will be good thanks',
'is plenty',
'is plenty thanks',
'will be plenty',
'will be plenty thanks',
'is great',
'is great thanks',
'will be great',
'will be great thanks',
'will work',
'will work thanks',
'is correct',
'is correct thanks',
'is right',
'is right thanks',
'at a time',
'for some reason',
],
},
},
],
},
SHARED_SLOT_TYPES_CONJUNCTION: {
name: SharedSlotType.CONJUNCTION,
values: [
{
id: $.Conjunction,
name: {
value: 'conjunction',
synonyms: ['and', 'and then', 'then', 'and also'],
},
},
],
},
SHARED_SLOT_TYPES_PREPOSITION: {
name: SharedSlotType.PREPOSITION,
values: [
{
id: $.Preposition,
name: {
value: 'preposition',
synonyms: [
'the',
'to',
'to the',
'to be',
'to go',
'in',
'in to',
'into',
'is',
'equal to',
'to be equal to',
'also',
'to also be',
'to be also',
'from',
'until',
],
},
},
],
},
SHARED_SLOT_TYPES_ACTION: {
name: SharedSlotType.ACTION,
values: [
{
id: $.Action.Set,
name: {
value: 'set',
synonyms: [
'set',
'assign',
'make',
'will be',
'must be',
'must be set to',
'must be equal to',
'should be',
'should be',
'should be set to',
'should be equal to',
'needs to be',
'needs to be set to',
],
},
},
{
id: $.Action.Change,
name: {
value: 'change',
synonyms: [
'update',
'move',
'alter',
'change',
'switch',
'should be',
'should be changed to',
'should be changed',
'should be updated to',
'should be updated',
'should be altered to',
'should be altered',
'needs to be changed to',
'needs to be changed',
'needs to be updated to',
'needs to be updated',
'needs to be altered to',
'needs to be altered',
],
},
},
{
id: $.Action.Select,
name: {
value: 'select',
synonyms: [
'select',
'choose',
'take',
'pick',
'want',
'need',
'go with',
'be fine with',
'going to go with',
'gonna pick',
'gonna go with',
'be taking',
],
},
},
{
id: $.Action.Complete,
name: {
value: 'complete',
synonyms: [
'complete',
'am done',
'can be done',
'am complete',
`don't have anything else`,
'nothing further',
"that's it",
'all done',
'no more',
'submit',
'nothing else',
'got nothing else',
'got nothing more',
'not nothing further',
],
},
},
{
id: $.Action.GoBack,
name: {
value: 'goBack',
synonyms: [
'back',
'go back',
'go back to previous',
'go back to the last',
'go back to last',
'return',
'go backward',
'back to previous',
'back to last',
],
},
},
{
id: $.Action.Start,
name: {
value: 'start',
synonyms: ['start', 'commence', 'begin'],
},
},
{
id: $.Action.Restart,
name: {
value: 'restart',
synonyms: ['recommence', 'start over'],
},
},
{
id: $.Action.Resume,
name: {
value: 'resume',
synonyms: ['continue'],
},
},
{
id: $.Action.Add,
name: {
value: 'add',
synonyms: ['add'],
},
},
{
id: $.Action.Remove,
name: {
value: 'remove',
synonyms: ['remove', 'delete'],
},
},
{
id: $.Action.Clear,
name: {
value: 'clear',
synonyms: ['remove all', 'clear'],
},
},
{
id: $.Action.Ignore,
name: {
value: 'ignore',
synonyms: ['ignore'],
},
},
],
},
SHARED_SLOT_TYPES_TARGET: {
name: SharedSlotType.TARGET,
values: [
{
id: $.Target.It,
name: {
value: 'it',
synonyms: [
'it',
'this',
'that',
'them',
'them all',
'those',
'all those',
'most',
'most all',
'most all of them',
'most of them',
'almost all',
'almost all of them',
],
},
},
{
id: $.Target.Date,
name: {
value: 'date',
synonyms: ['date', 'the date', 'day', 'the day'],
},
},
{
id: $.Target.Number,
name: {
value: 'number',
synonyms: ['the number'],
},
},
{
id: $.Target.Choice,
name: {
value: 'choice',
synonyms: ['my choice', 'selection', 'my selection'],
},
},
{
id: $.Target.Start,
name: {
value: 'start',
synonyms: ['the start'],
},
},
{
id: $.Target.End,
name: {
value: 'end',
synonyms: ['the end'],
},
},
{
id: $.Target.StartDate,
name: {
value: 'startDate',
synonyms: ['start date', 'the start date', 'starting date', 'the starting date'],
},
},
{
id: $.Target.EndDate,
name: {
value: 'endDate',
synonyms: ['end date', 'the end date', 'ending date', 'the ending date'],
},
},
{
id: $.Target.DateRange,
name: {
value: 'dateRange',
synonyms: ['date range', 'the date range', 'dates', 'the dates'],
},
},
{
id: $.Target.Questionnaire,
name: {
value: 'questionnaire',
synonyms: [
'questionnaire',
'the questionnaire',
'the questions',
'survey',
'the survey',
],
},
},
],
},
},
},
}; | the_stack |
import type { MLASTElement } from '@markuplint/ml-ast';
import { nodeListToDebugMaps } from '@markuplint/parser-utils';
import { parse } from './';
describe('parser', () => {
it('empty code', () => {
const doc = parse('<template></template>');
expect(doc.nodeList).toStrictEqual([]);
expect(doc.nodeList.length).toBe(0);
});
it('<div />', () => {
const doc = parse('<template><div /></template>');
expect(doc.nodeList[0].nodeName).toBe('div');
expect(doc.nodeList.length).toBe(1);
});
it('<div></div>', () => {
const doc = parse('<template><div></div></template>');
expect(doc.nodeList[0].nodeName).toBe('div');
expect(doc.nodeList[1].nodeName).toBe('div');
expect(doc.nodeList.length).toBe(2);
});
it('text only', () => {
const doc = parse('<template>text</template>');
expect(doc.nodeList[0].nodeName).toBe('#text');
expect(doc.nodeList[0].raw).toBe('text');
expect(doc.nodeList.length).toBe(1);
});
it('fragments', () => {
const doc = parse('<template><header></header><main></main><footer></footer></template>');
expect(doc.nodeList[0].nodeName).toBe('header');
expect(doc.nodeList[1].nodeName).toBe('header');
expect(doc.nodeList[2].nodeName).toBe('main');
expect(doc.nodeList[3].nodeName).toBe('main');
expect(doc.nodeList[4].nodeName).toBe('footer');
expect(doc.nodeList[5].nodeName).toBe('footer');
expect(doc.nodeList.length).toBe(6);
});
it('standard code', () => {
const doc = parse(`
<template>
<script>
const i = 0;
</script>
<!comment-node>
{{ CodeExpression }}
<div>
text&div
</div>
<table>
<tr>
<th>header</th>
<td>cell</td>
</tr>
</table>
<table>
<tbody>
<tr>
<th>header</th>
<td>cell</td>
</tr>
</tbody>
</table>
<img src="path/to" />
invalid-indent
<?template engine;
$var = '<html attr="value">text</html>'
?>
<%template engine;
$var = '<html attr="value">text</html>'
%>
</expected>
<div>
text-node
</template>
`);
const map = nodeListToDebugMaps(doc.nodeList);
expect(map).toStrictEqual([
'[2:12]>[3:3](12,15)#text: ⏎→→',
'[3:3]>[3:11](15,23)script: <script>',
'[3:11]>[5:3](23,42)#text: ⏎→→→const␣i␣=␣0;⏎→→',
'[5:3]>[5:12](42,51)script: </script>',
'[5:12]>[7:3](51,72)#text: ⏎→→⏎→→',
'[7:3]>[7:23](72,92)#comment: {{␣CodeExpression␣}}',
'[7:23]>[8:3](92,95)#text: ⏎→→',
'[8:3]>[8:8](95,100)div: <div>',
'[8:8]>[10:3](100,119)#text: ⏎→→→text&div⏎→→',
'[10:3]>[10:9](119,125)div: </div>',
'[10:9]>[11:3](125,128)#text: ⏎→→',
'[11:3]>[11:10](128,135)table: <table>',
'[11:10]>[12:4](135,139)#text: ⏎→→→',
'[12:4]>[12:8](139,143)tr: <tr>',
'[12:8]>[13:5](143,148)#text: ⏎→→→→',
'[13:5]>[13:9](148,152)th: <th>',
'[13:9]>[13:15](152,158)#text: header',
'[13:15]>[13:20](158,163)th: </th>',
'[13:20]>[14:5](163,168)#text: ⏎→→→→',
'[14:5]>[14:9](168,172)td: <td>',
'[14:9]>[14:13](172,176)#text: cell',
'[14:13]>[14:18](176,181)td: </td>',
'[14:18]>[15:4](181,185)#text: ⏎→→→',
'[15:4]>[15:9](185,190)tr: </tr>',
'[15:9]>[16:3](190,193)#text: ⏎→→',
'[16:3]>[16:11](193,201)table: </table>',
'[16:11]>[17:3](201,204)#text: ⏎→→',
'[17:3]>[17:10](204,211)table: <table>',
'[17:10]>[18:4](211,215)#text: ⏎→→→',
'[18:4]>[18:11](215,222)tbody: <tbody>',
'[18:11]>[19:5](222,227)#text: ⏎→→→→',
'[19:5]>[19:9](227,231)tr: <tr>',
'[19:9]>[20:6](231,237)#text: ⏎→→→→→',
'[20:6]>[20:10](237,241)th: <th>',
'[20:10]>[20:16](241,247)#text: header',
'[20:16]>[20:21](247,252)th: </th>',
'[20:21]>[21:6](252,258)#text: ⏎→→→→→',
'[21:6]>[21:10](258,262)td: <td>',
'[21:10]>[21:14](262,266)#text: cell',
'[21:14]>[21:19](266,271)td: </td>',
'[21:19]>[22:5](271,276)#text: ⏎→→→→',
'[22:5]>[22:10](276,281)tr: </tr>',
'[22:10]>[23:4](281,285)#text: ⏎→→→',
'[23:4]>[23:12](285,293)tbody: </tbody>',
'[23:12]>[24:3](293,296)#text: ⏎→→',
'[24:3]>[24:11](296,304)table: </table>',
'[24:11]>[25:3](304,307)#text: ⏎→→',
'[25:3]>[25:24](307,328)img: <img␣src="path/to"␣/>',
"[25:24]>[33:12](328,451)#text: ⏎→→→→invalid-indent⏎⏎→→text'⏎→→?>⏎⏎→→<%template␣engine;⏎→→→$var␣=␣'",
'[33:12]>[33:31](451,470)html: <html␣attr="value">',
'[33:31]>[33:35](470,474)#text: text',
'[33:35]>[33:42](474,481)html: </html>',
"[33:42]>[37:3](481,505)#text: '⏎→→%>⏎⏎→→⏎→→",
'[37:3]>[37:8](505,510)div: <div>',
'[37:8]>[39:2](510,523)#text: ⏎→text-node⏎→',
]);
});
it('<template>', () => {
const doc = parse(`
<template>
<script>
const i = 0;
</script>
<!comment-node>
<!-- html-comment -->
<div>
text&div
</div>
<table>
<tr>
<th>header</th>
<td>cell</td>
</tr>
</table>
<table>
<tbody>
<tr>
<th>header</th>
<td>cell</td>
</tr>
</tbody>
</table>
<img src="path/to" />
invalid-indent
<?template engine;
$var = '<html attr="value">text</html>'
?>
<%template engine;
$var = '<html attr="value">text</html>'
%>
</expected>
<div>
text-node
</template>
`);
const map = nodeListToDebugMaps(doc.nodeList);
expect(map).toStrictEqual([
'[2:12]>[3:3](12,15)#text: ⏎→→',
'[3:3]>[3:11](15,23)script: <script>',
'[3:11]>[5:3](23,42)#text: ⏎→→→const␣i␣=␣0;⏎→→',
'[5:3]>[5:12](42,51)script: </script>',
'[5:12]>[8:3](51,96)#text: ⏎→→⏎→→⏎→→',
'[8:3]>[8:8](96,101)div: <div>',
'[8:8]>[10:3](101,120)#text: ⏎→→→text&div⏎→→',
'[10:3]>[10:9](120,126)div: </div>',
'[10:9]>[11:3](126,129)#text: ⏎→→',
'[11:3]>[11:10](129,136)table: <table>',
'[11:10]>[12:4](136,140)#text: ⏎→→→',
'[12:4]>[12:8](140,144)tr: <tr>',
'[12:8]>[13:5](144,149)#text: ⏎→→→→',
'[13:5]>[13:9](149,153)th: <th>',
'[13:9]>[13:15](153,159)#text: header',
'[13:15]>[13:20](159,164)th: </th>',
'[13:20]>[14:5](164,169)#text: ⏎→→→→',
'[14:5]>[14:9](169,173)td: <td>',
'[14:9]>[14:13](173,177)#text: cell',
'[14:13]>[14:18](177,182)td: </td>',
'[14:18]>[15:4](182,186)#text: ⏎→→→',
'[15:4]>[15:9](186,191)tr: </tr>',
'[15:9]>[16:3](191,194)#text: ⏎→→',
'[16:3]>[16:11](194,202)table: </table>',
'[16:11]>[17:3](202,205)#text: ⏎→→',
'[17:3]>[17:10](205,212)table: <table>',
'[17:10]>[18:4](212,216)#text: ⏎→→→',
'[18:4]>[18:11](216,223)tbody: <tbody>',
'[18:11]>[19:5](223,228)#text: ⏎→→→→',
'[19:5]>[19:9](228,232)tr: <tr>',
'[19:9]>[20:6](232,238)#text: ⏎→→→→→',
'[20:6]>[20:10](238,242)th: <th>',
'[20:10]>[20:16](242,248)#text: header',
'[20:16]>[20:21](248,253)th: </th>',
'[20:21]>[21:6](253,259)#text: ⏎→→→→→',
'[21:6]>[21:10](259,263)td: <td>',
'[21:10]>[21:14](263,267)#text: cell',
'[21:14]>[21:19](267,272)td: </td>',
'[21:19]>[22:5](272,277)#text: ⏎→→→→',
'[22:5]>[22:10](277,282)tr: </tr>',
'[22:10]>[23:4](282,286)#text: ⏎→→→',
'[23:4]>[23:12](286,294)tbody: </tbody>',
'[23:12]>[24:3](294,297)#text: ⏎→→',
'[24:3]>[24:11](297,305)table: </table>',
'[24:11]>[25:3](305,308)#text: ⏎→→',
'[25:3]>[25:24](308,329)img: <img␣src="path/to"␣/>',
"[25:24]>[33:12](329,452)#text: ⏎→→→→invalid-indent⏎⏎→→text'⏎→→?>⏎⏎→→<%template␣engine;⏎→→→$var␣=␣'",
'[33:12]>[33:31](452,471)html: <html␣attr="value">',
'[33:31]>[33:35](471,475)#text: text',
'[33:35]>[33:42](475,482)html: </html>',
"[33:42]>[37:3](482,506)#text: '⏎→→%>⏎⏎→→⏎→→",
'[37:3]>[37:8](506,511)div: <div>',
'[37:8]>[39:2](511,524)#text: ⏎→text-node⏎→',
]);
});
it('<noscript>', () => {
const doc = parse(`
<template>
<noscript>
<div>test</div>
<expected>
</expected2>
</noscript>
</template>
`);
const map = nodeListToDebugMaps(doc.nodeList);
expect(map).toStrictEqual([
'[2:12]>[3:2](12,14)#text: ⏎→',
'[3:2]>[3:12](14,24)noscript: <noscript>',
'[3:12]>[7:2](24,72)#text: ⏎→→<div>test</div>⏎→→<expected>⏎→→</expected2>⏎→',
'[7:2]>[7:13](72,83)noscript: </noscript>',
'[7:13]>[8:2](83,85)#text: ⏎→',
]);
});
it('UUID', () => {
const doc = parse(
'<template><x-wrap><x-before><span>title</span></x-before><x-after><div>test</div></x-after></x-wrap></template>',
);
// const map = nodeListToDebugMaps(doc.nodeList);
// console.log(map);
// console.log(doc.nodeList.map((n, i) => `${i}: ${n.uuid} ${n.raw.trim()}`));
// <x-wrap>
expect(doc.nodeList[0].parentNode).toEqual(null);
expect(doc.nodeList[0].prevNode).toEqual(null);
expect(doc.nodeList[0].nextNode).toEqual(null);
// @ts-ignore
expect(doc.nodeList[0].pearNode.uuid).toEqual(doc.nodeList[11].uuid);
// </x-wrap>
expect(doc.nodeList[11].parentNode).toEqual(null);
// @ts-ignore
expect(doc.nodeList[11].pearNode.uuid).toEqual(doc.nodeList[0].uuid);
// <x-before>
// @ts-ignore
expect(doc.nodeList[1].parentNode.uuid).toEqual(doc.nodeList[0].uuid);
// @ts-ignore
expect(doc.nodeList[1].prevNode).toEqual(null);
// @ts-ignore
expect(doc.nodeList[1].nextNode.uuid).toEqual(doc.nodeList[6].uuid);
// @ts-ignore
expect(doc.nodeList[1].pearNode.uuid).toEqual(doc.nodeList[5].uuid);
// </x-before>
// @ts-ignore
expect(doc.nodeList[5].parentNode.uuid).toEqual(doc.nodeList[0].uuid);
// @ts-ignore
expect(doc.nodeList[5].pearNode.uuid).toEqual(doc.nodeList[1].uuid);
// <x-after>
// @ts-ignore
expect(doc.nodeList[6].parentNode.uuid).toEqual(doc.nodeList[0].uuid);
// @ts-ignore
expect(doc.nodeList[6].prevNode.uuid).toEqual(doc.nodeList[1].uuid);
// @ts-ignore
expect(doc.nodeList[6].nextNode).toEqual(null);
// @ts-ignore
expect(doc.nodeList[6].pearNode.uuid).toEqual(doc.nodeList[10].uuid);
// </x-after>
// @ts-ignore
expect(doc.nodeList[10].parentNode.uuid).toEqual(doc.nodeList[0].uuid);
// @ts-ignore
expect(doc.nodeList[10].pearNode.uuid).toEqual(doc.nodeList[6].uuid);
});
it('attributes', () => {
const doc = parse(
'<template><div v-if="bool" data-attr v-bind:data-attr2="variable" @click.once="event" v-on:click.foobar="event"></div></template>',
);
// @ts-ignore
expect(doc.nodeList[0].attributes[0].raw).toBe(' v-if="bool"');
// @ts-ignore
expect(doc.nodeList[0].attributes[0].isDirective).toBeTruthy();
// @ts-ignore
expect(doc.nodeList[0].attributes[1].raw).toBe(' data-attr');
// @ts-ignore
expect(doc.nodeList[0].attributes[1].isDirective).toBeUndefined();
// @ts-ignore
expect(doc.nodeList[0].attributes[2].raw).toBe(' v-bind:data-attr2="variable"');
// @ts-ignore
expect(doc.nodeList[0].attributes[2].potentialName).toBe('data-attr2');
// @ts-ignore
expect(doc.nodeList[0].attributes[3].isDirective).toBeTruthy();
// @ts-ignore
expect(doc.nodeList[0].attributes[4].isDirective).toBeTruthy();
});
it('namespace', () => {
const doc = parse('<template><div><svg><text /></svg></div></template>');
expect(doc.nodeList[0].nodeName).toBe('div');
expect((doc.nodeList[0] as MLASTElement).namespace).toBe('http://www.w3.org/1999/xhtml');
expect(doc.nodeList[1].nodeName).toBe('svg');
expect((doc.nodeList[1] as MLASTElement).namespace).toBe('http://www.w3.org/2000/svg');
expect(doc.nodeList[2].nodeName).toBe('text');
expect((doc.nodeList[2] as MLASTElement).namespace).toBe('http://www.w3.org/2000/svg');
});
}); | the_stack |
import Dictionary from '../../util/Dictionary';
import Point from '../geometry/Point';
import GraphLayout from './GraphLayout';
import CellPath from '../cell/CellPath';
import Rectangle from '../geometry/Rectangle';
import { sortCells } from '../../util/styleUtils';
import WeightedCellSorter from './util/WeightedCellSorter';
import Cell from '../cell/Cell';
import { Graph } from '../Graph';
import { findTreeRoots } from '../../util/treeTraversal';
import CellArray from '../cell/CellArray';
export interface _mxCompactTreeLayoutNode {
cell?: Cell;
x?: number;
y?: number;
width?: number;
height?: number;
offsetX?: number;
offsetY?: number;
contour?: {
upperTail?: _mxCompactTreeLayoutLine,
upperHead?: _mxCompactTreeLayoutLine,
lowerTail?: _mxCompactTreeLayoutLine,
lowerHead?: _mxCompactTreeLayoutLine,
[key: string]: any,
};
next?: _mxCompactTreeLayoutNode;
child?: _mxCompactTreeLayoutNode;
theta?: number;
}
export interface _mxCompactTreeLayoutLine {
dx: number;
dy: number;
next: _mxCompactTreeLayoutLine;
child?: _mxCompactTreeLayoutLine;
}
/**
* @class CompactTreeLayout
* @extends {GraphLayout}
*
* Extends {@link GraphLayout} to implement a compact tree (Moen) algorithm. This
* layout is suitable for graphs that have no cycles (trees). Vertices that are
* not connected to the tree will be ignored by this layout.
*
* ### Example
*
* ```javascript
* var layout = new mxCompactTreeLayout(graph);
* layout.execute(graph.getDefaultParent());
* ```
*/
export class CompactTreeLayout extends GraphLayout {
constructor(graph: Graph, horizontal: boolean = true, invert: boolean = false) {
super(graph);
this.horizontal = horizontal;
this.invert = invert;
}
parentX: number | null = null;
parentY: number | null = null;
visited: { [key: string]: Cell } = {};
/**
* Specifies the orientation of the layout.
* @default true
*/
horizontal: boolean = true;
/**
* Specifies if edge directions should be inverted.
* @default false.
*/
invert: boolean = false;
/**
* If the parents should be resized to match the width/height of the
* children. Default is true.
* @default true
*/
resizeParent: boolean = true;
/**
* Specifies if the parent location should be maintained, so that the
* top, left corner stays the same before and after execution of
* the layout. Default is false for backwards compatibility.
* @default false
*/
maintainParentLocation: boolean = false;
/**
* Padding added to resized parents.
* @default 10
*/
groupPadding: number = 10;
/**
* Top padding added to resized parents.
* @default 0
*/
groupPaddingTop: number = 0;
/**
* Right padding added to resized parents.
* @default 0
*/
groupPaddingRight: number = 0;
/**
* Bottom padding added to resized parents.
* @default 0
*/
groupPaddingBottom: number = 0;
/**
* Left padding added to resized parents.
* @default 0
*/
groupPaddingLeft: number = 0;
/**
* A set of the parents that need updating based on children
* process as part of the layout.
*/
parentsChanged: { [id: string]: Cell } | null = null;
/**
* Specifies if the tree should be moved to the top, left corner
* if it is inside a top-level layer.
* @default false
*/
moveTree: boolean = false;
/**
* Holds the levelDistance.
* @default 10
*/
levelDistance: number = 10;
/**
* Holds the nodeDistance.
* @default 20
*/
nodeDistance: number = 20;
/**
* Specifies if all edge points of traversed edges should be removed.
*
* @default true
*/
resetEdges: boolean = true;
/**
* The preferred horizontal distance between edges exiting a vertex.
*/
prefHozEdgeSep: number = 5;
/**
* The preferred vertical offset between edges exiting a vertex.
*/
prefVertEdgeOff: number = 4;
/**
* The minimum distance for an edge jetty from a vertex.
*/
minEdgeJetty: number = 8;
/**
* The size of the vertical buffer in the center of inter-rank channels
* where edge control points should not be placed.
*/
channelBuffer: number = 4;
/**
* Whether or not to apply the internal tree edge routing.
*/
edgeRouting: boolean = true;
/**
* Specifies if edges should be sorted according to the order of their
* opposite terminal cell in the model.
*/
sortEdges: boolean = false;
/**
* Whether or not the tops of cells in each rank should be aligned
* across the rank
*/
alignRanks: boolean = false;
/**
* An array of the maximum height of cells (relative to the layout direction)
* per rank
*/
maxRankHeight: CellArray | null = null;
/**
* The cell to use as the root of the tree
*/
root: Cell | null = null;
/**
* The internal node representation of the root cell. Do not set directly
* , this value is only exposed to assist with post-processing functionality
*/
node: _mxCompactTreeLayoutNode | null = null;
/**
* Returns a boolean indicating if the given {@link mxCell} should be ignored as a
* vertex. This returns true if the cell has no connections.
*
* @param vertex {@link mxCell} whose ignored state should be returned.
*/
isVertexIgnored(vertex: Cell): boolean {
return (
super.isVertexIgnored(vertex) || vertex.getConnections().length === 0
);
}
/**
* Returns {@link horizontal}.
*/
isHorizontal(): boolean {
return this.horizontal;
}
/**
* Implements {@link GraphLayout.execute}.
*
* If the parent has any connected edges, then it is used as the root of
* the tree. Else, {@link mxGraph.findTreeRoots} will be used to find a suitable
* root node within the set of children of the given parent.
*
* @param parent {@link mxCell} whose children should be laid out.
* @param root Optional {@link mxCell} that will be used as the root of the tree. Overrides {@link root} if specified.
*/
execute(parent: Cell, root?: Cell): void {
this.parent = parent;
const model = this.graph.getDataModel();
if (root == null) {
// Takes the parent as the root if it has outgoing edges
if (
this.graph.getEdges(parent, parent.getParent(), this.invert, !this.invert, false)
.length > 0
) {
this.root = parent;
}
// Tries to find a suitable root in the parent's
// children
else {
const roots = findTreeRoots(this.graph, parent, true, this.invert);
if (roots.length > 0) {
for (let i = 0; i < roots.length; i += 1) {
if (
!this.isVertexIgnored(roots[i]) &&
this.graph.getEdges(roots[i], null, this.invert, !this.invert, false)
.length > 0
) {
this.root = roots[i];
break;
}
}
}
}
} else {
this.root = root;
}
if (this.root != null) {
if (this.resizeParent) {
this.parentsChanged = {};
} else {
this.parentsChanged = null;
}
// Maintaining parent location
this.parentX = null;
this.parentY = null;
if (
parent !== this.root &&
parent.isVertex() != null &&
this.maintainParentLocation
) {
const geo = parent.getGeometry();
if (geo != null) {
this.parentX = geo.x;
this.parentY = geo.y;
}
}
model.beginUpdate();
try {
this.visited = {};
this.node = this.dfs(this.root, parent);
if (this.alignRanks) {
this.maxRankHeight = new CellArray();
this.findRankHeights(this.node, 0);
this.setCellHeights(this.node, 0);
}
if (this.node != null) {
this.layout(this.node);
let x0 = this.graph.gridSize;
let y0 = x0;
if (!this.moveTree) {
const g = this.getVertexBounds(this.root);
if (g != null) {
x0 = g.x;
y0 = g.y;
}
}
let bounds = null;
if (this.isHorizontal()) {
bounds = this.horizontalLayout(this.node, x0, y0);
} else {
bounds = this.verticalLayout(this.node, null, x0, y0);
}
if (bounds != null) {
let dx = 0;
let dy = 0;
if (bounds.x < 0) {
dx = Math.abs(x0 - bounds.x);
}
if (bounds.y < 0) {
dy = Math.abs(y0 - bounds.y);
}
if (dx !== 0 || dy !== 0) {
this.moveNode(this.node, dx, dy);
}
if (this.resizeParent) {
this.adjustParents();
}
if (this.edgeRouting) {
// Iterate through all edges setting their positions
this.localEdgeProcessing(this.node);
}
}
// Maintaining parent location
if (this.parentX != null && this.parentY != null) {
let geo = parent.getGeometry();
if (geo != null) {
geo = geo.clone();
geo.x = this.parentX;
geo.y = this.parentY;
model.setGeometry(parent, geo);
}
}
}
} finally {
model.endUpdate();
}
}
}
/**
* Moves the specified node and all of its children by the given amount.
*/
moveNode(node: any, dx: number, dy: number): void {
node.x += dx;
node.y += dy;
this.apply(node);
let { child } = node;
while (child != null) {
this.moveNode(child, dx, dy);
child = child.next;
}
}
/**
* Called if {@link sortEdges} is true to sort the array of outgoing edges in place.
*/
sortOutgoingEdges(source: Cell, edges: CellArray): void {
const lookup = new Dictionary();
edges.sort((e1, e2) => {
const end1 = <Cell>e1.getTerminal(e1.getTerminal(false) == source);
let p1 = lookup.get(end1);
if (p1 == null) {
p1 = CellPath.create(end1).split(CellPath.PATH_SEPARATOR);
lookup.put(end1, p1);
}
const end2 = <Cell>e2.getTerminal(e2.getTerminal(false) === source);
let p2 = lookup.get(end2);
if (p2 == null) {
p2 = CellPath.create(end2).split(CellPath.PATH_SEPARATOR);
lookup.put(end2, p2);
}
return CellPath.compare(<string[]>p1, <string[]>p2);
});
}
/**
* Stores the maximum height (relative to the layout
* direction) of cells in each rank
*/
findRankHeights(node: any, rank: number): void {
const maxRankHeight = <CellArray>this.maxRankHeight;
if (maxRankHeight[rank] == null || maxRankHeight[rank] < node.height) {
maxRankHeight[rank] = node.height;
}
let { child } = node;
while (child != null) {
this.findRankHeights(child, rank + 1);
child = child.next;
}
}
/**
* Set the cells heights (relative to the layout
* direction) when the tops of each rank are to be aligned
*/
setCellHeights(node: any, rank: number): void {
const maxRankHeight = <CellArray>this.maxRankHeight;
if (maxRankHeight[rank] != null && maxRankHeight[rank] > node.height) {
node.height = maxRankHeight[rank];
}
let { child } = node;
while (child != null) {
this.setCellHeights(child, rank + 1);
child = child.next;
}
}
/**
* Does a depth first search starting at the specified cell.
* Makes sure the specified parent is never left by the
* algorithm.
*/
dfs(cell: Cell, parent: Cell) {
const id = CellPath.create(cell);
let node = null;
if (cell != null && this.visited[id] == null && !this.isVertexIgnored(cell)) {
this.visited[id] = cell;
node = this.createNode(cell);
const model = this.graph.getDataModel();
let prev = null;
const out = this.graph.getEdges(
cell,
parent,
this.invert,
!this.invert,
false,
true
);
const view = this.graph.getView();
if (this.sortEdges) {
this.sortOutgoingEdges(cell, out);
}
for (let i = 0; i < out.length; i += 1) {
const edge = out[i];
if (!this.isEdgeIgnored(edge)) {
// Resets the points on the traversed edge
if (this.resetEdges) {
this.setEdgePoints(edge, null);
}
if (this.edgeRouting) {
this.setEdgeStyleEnabled(edge, false);
this.setEdgePoints(edge, null);
}
// Checks if terminal in same swimlane
const state = view.getState(edge);
const target =
state != null
? <Cell>state.getVisibleTerminal(this.invert)
: <Cell>view.getVisibleTerminal(edge, this.invert);
const tmp = this.dfs(target, parent);
if (tmp != null && target.getGeometry() != null) {
if (prev == null) {
node.child = tmp;
} else {
prev.next = tmp;
}
prev = tmp;
}
}
}
}
return node;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
layout(node: any): void {
let { child } = node;
while (child != null) {
this.layout(child);
child = child.next;
}
if (node.child != null) {
this.attachParent(node, this.join(node));
} else {
this.layoutLeaf(node);
}
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
horizontalLayout(node: any, x0: number, y0: number, bounds: Rectangle | null=null): Rectangle | null {
node.x += x0 + node.offsetX;
node.y += y0 + node.offsetY;
bounds = this.apply(node, bounds);
const { child } = node;
if (child != null) {
bounds = this.horizontalLayout(child, node.x, node.y, bounds);
let siblingOffset = node.y + child.offsetY;
let s = child.next;
while (s != null) {
bounds = this.horizontalLayout(s, node.x + child.offsetX, siblingOffset, bounds);
siblingOffset += s.offsetY;
s = s.next;
}
}
return bounds;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
verticalLayout(
node: _mxCompactTreeLayoutNode,
parent: _mxCompactTreeLayoutNode | null,
x0: number,
y0: number,
bounds: Rectangle | null=null
): Rectangle | null {
node.x = <number>node.x + x0 + <number>node.offsetY;
node.y = <number>node.y + y0 + <number>node.offsetX;
bounds = this.apply(node, bounds);
const { child } = node;
if (child != null) {
bounds = this.verticalLayout(child, node, <number>node.x, <number>node.y, bounds);
let siblingOffset = <number>node.x + <number>child.offsetY;
let s = child.next;
while (s != null) {
bounds = this.verticalLayout(
s,
node,
siblingOffset,
<number>node.y + <number>child.offsetX,
bounds
);
siblingOffset += <number>s.offsetY;
s = s.next;
}
}
return bounds;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
attachParent(node: any, height: number): void {
const x = this.nodeDistance + this.levelDistance;
const y2 = (height - node.width) / 2 - this.nodeDistance;
const y1 = y2 + node.width + 2 * this.nodeDistance - height;
node.child.offsetX = x + node.height;
node.child.offsetY = y1;
node.contour.upperHead = this.createLine(
node.height,
0,
this.createLine(x, y1, node.contour.upperHead)
);
node.contour.lowerHead = this.createLine(
node.height,
0,
this.createLine(x, y2, node.contour.lowerHead)
);
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
// layoutLeaf(node: any): void;
layoutLeaf(node: any): void {
const dist = 2 * this.nodeDistance;
node.contour.upperTail = this.createLine(node.height + dist, 0);
node.contour.upperHead = node.contour.upperTail;
node.contour.lowerTail = this.createLine(0, -node.width - dist);
node.contour.lowerHead = this.createLine(
node.height + dist,
0,
node.contour.lowerTail
);
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
join(node: any): number {
const dist = 2 * this.nodeDistance;
let { child } = node;
node.contour = child.contour;
let h = child.width + dist;
let sum = h;
child = child.next;
while (child != null) {
const d = this.merge(node.contour, child.contour);
child.offsetY = d + h;
child.offsetX = 0;
h = child.width + dist;
sum += d + h;
child = child.next;
}
return sum;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
merge(p1: any, p2: any): number {
let x = 0;
let y = 0;
let total = 0;
let upper = p1.lowerHead;
let lower = p2.upperHead;
while (lower != null && upper != null) {
const d = this.offset(x, y, lower.dx, lower.dy, upper.dx, upper.dy);
y += d;
total += d;
if (x + lower.dx <= upper.dx) {
x += lower.dx;
y += lower.dy;
lower = lower.next;
} else {
x -= upper.dx;
y -= upper.dy;
upper = upper.next;
}
}
if (lower != null) {
const b = this.bridge(p1.upperTail, 0, 0, lower, x, y);
p1.upperTail = b.next != null ? p2.upperTail : b;
p1.lowerTail = p2.lowerTail;
} else {
const b = this.bridge(p2.lowerTail, x, y, upper, 0, 0);
if (b.next == null) {
p1.lowerTail = b;
}
}
p1.lowerHead = p2.lowerHead;
return total;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
// offset(p1: number, p2: number, a1: number, a2: number, b1: number, b2: number): number;
offset(p1: number, p2: number, a1: number, a2: number, b1: number, b2: number): number {
let d = 0;
if (b1 <= p1 || p1 + a1 <= 0) {
return 0;
}
const t = b1 * a2 - a1 * b2;
if (t > 0) {
if (p1 < 0) {
const s = p1 * a2;
d = s / a1 - p2;
} else if (p1 > 0) {
const s = p1 * b2;
d = s / b1 - p2;
} else {
d = -p2;
}
} else if (b1 < p1 + a1) {
const s = (b1 - p1) * a2;
d = b2 - (p2 + s / a1);
} else if (b1 > p1 + a1) {
const s = (a1 + p1) * b2;
d = s / b1 - (p2 + a2);
} else {
d = b2 - (p2 + a2);
}
if (d > 0) {
return d;
}
return 0;
}
bridge(
line1: _mxCompactTreeLayoutLine,
x1: number,
y1: number,
line2: _mxCompactTreeLayoutLine,
x2: number,
y2: number
) {
const dx = x2 + line2.dx - x1;
let dy = 0;
let s = 0;
if (line2.dx === 0) {
dy = line2.dy;
} else {
s = dx * line2.dy;
dy = s / line2.dx;
}
const r = this.createLine(dx, dy, line2.next);
line1.next = this.createLine(0, y2 + line2.dy - dy - y1, r);
return r;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
createNode(cell: Cell): _mxCompactTreeLayoutNode {
const node: _mxCompactTreeLayoutNode = {};
node.cell = cell;
node.x = 0;
node.y = 0;
node.width = 0;
node.height = 0;
const geo = this.getVertexBounds(cell);
if (geo != null) {
if (this.isHorizontal()) {
node.width = geo.height;
node.height = geo.width;
} else {
node.width = geo.width;
node.height = geo.height;
}
}
node.offsetX = 0;
node.offsetY = 0;
node.contour = {};
return node;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
apply(node: _mxCompactTreeLayoutNode, bounds: Rectangle | null=null): Rectangle | null {
const model = this.graph.getDataModel();
const cell = <Cell>node.cell;
let g: Rectangle = <Rectangle>cell.getGeometry();
if (cell != null && g != null) {
if (this.isVertexMovable(cell)) {
g = <Rectangle>this.setVertexLocation(cell, <number>node.x, <number>node.y);
if (this.resizeParent) {
const parent = <Cell>cell.getParent();
const id = <string>CellPath.create(parent);
// Implements set semantic
const parentsChanged = <{ [id: string]: Cell }>this.parentsChanged;
if (parentsChanged[id] == null) {
parentsChanged[id] = parent;
}
}
}
if (bounds == null) {
bounds = new Rectangle(g.x, g.y, g.width, g.height);
} else {
bounds = new Rectangle(
Math.min(bounds.x, g.x),
Math.min(bounds.y, g.y),
Math.max(bounds.x + bounds.width, g.x + g.width),
Math.max(bounds.y + bounds.height, g.y + g.height)
);
}
}
return bounds;
}
/**
* Starts the actual compact tree layout algorithm
* at the given node.
*/
createLine(dx: number, dy: number, next: any=null): _mxCompactTreeLayoutLine {
let line: _mxCompactTreeLayoutLine = {
dx,
dy,
next
};
return line;
}
/**
* Adjust parent cells whose child geometries have changed. The default
* implementation adjusts the group to just fit around the children with
* a padding.
*/
adjustParents(): void {
const tmp = new CellArray();
for (const id in this.parentsChanged) {
tmp.push(this.parentsChanged[id]);
}
this.arrangeGroups(
sortCells(tmp, true),
this.groupPadding,
this.groupPaddingTop,
this.groupPaddingRight,
this.groupPaddingBottom,
this.groupPaddingLeft
);
}
/**
* Moves the specified node and all of its children by the given amount.
*/
localEdgeProcessing(node: _mxCompactTreeLayoutNode): void {
this.processNodeOutgoing(node);
let { child } = node;
while (child != null) {
this.localEdgeProcessing(child);
child = child.next;
}
}
/**
* Separates the x position of edges as they connect to vertices
*/
processNodeOutgoing(node: _mxCompactTreeLayoutNode): void {
let { child } = node;
const parentCell = <Cell>node.cell;
let childCount = 0;
const sortedCells: WeightedCellSorter[] = [];
while (child != null) {
childCount++;
let sortingCriterion;
if (this.horizontal) {
sortingCriterion = <number>child.y;
} else {
sortingCriterion = <number>child.x;
}
sortedCells.push(new WeightedCellSorter(child, sortingCriterion));
child = child.next;
}
sortedCells.sort(WeightedCellSorter.compare);
let availableWidth = <number>node.width;
const requiredWidth = (childCount + 1) * this.prefHozEdgeSep;
// Add a buffer on the edges of the vertex if the edge count allows
if (availableWidth > requiredWidth + 2 * this.prefHozEdgeSep) {
availableWidth -= 2 * this.prefHozEdgeSep;
}
const edgeSpacing = availableWidth / childCount;
let currentXOffset = edgeSpacing / 2.0;
if (availableWidth > requiredWidth + 2 * this.prefHozEdgeSep) {
currentXOffset += this.prefHozEdgeSep;
}
let currentYOffset = this.minEdgeJetty - this.prefVertEdgeOff;
let maxYOffset = 0;
const parentBounds = this.getVertexBounds(parentCell);
child = node.child;
for (let j = 0; j < sortedCells.length; j++) {
const childCell = <Cell>(<_mxCompactTreeLayoutNode>sortedCells[j].cell).cell;
const childBounds = this.getVertexBounds(childCell);
const edges = this.graph.getEdgesBetween(parentCell, childCell, false);
const newPoints: Point[] = [];
let x = 0;
let y = 0;
for (let i = 0; i < edges.length; i += 1) {
if (this.horizontal) {
// Use opposite co-ords, calculation was done for
//
x = parentBounds.x + parentBounds.width;
y = parentBounds.y + currentXOffset;
newPoints.push(new Point(x, y));
x = parentBounds.x + parentBounds.width + currentYOffset;
newPoints.push(new Point(x, y));
y = childBounds.y + childBounds.height / 2.0;
newPoints.push(new Point(x, y));
this.setEdgePoints(edges[i], newPoints);
} else {
x = parentBounds.x + currentXOffset;
y = parentBounds.y + parentBounds.height;
newPoints.push(new Point(x, y));
y = parentBounds.y + parentBounds.height + currentYOffset;
newPoints.push(new Point(x, y));
x = childBounds.x + childBounds.width / 2.0;
newPoints.push(new Point(x, y));
this.setEdgePoints(edges[i], newPoints);
}
}
if (j < childCount / 2) {
currentYOffset += this.prefVertEdgeOff;
} else if (j > childCount / 2) {
currentYOffset -= this.prefVertEdgeOff;
}
// Ignore the case if equals, this means the second of 2
// jettys with the same y (even number of edges)
// pos[k * 2] = currentX;
currentXOffset += edgeSpacing;
// pos[k * 2 + 1] = currentYOffset;
maxYOffset = Math.max(maxYOffset, currentYOffset);
}
}
}
export default CompactTreeLayout; | the_stack |
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
DeviceEventEmitter,
ScrollView,
TouchableOpacity,
} from 'react-native';
import Kontakt from 'react-native-kontaktio';
import type { ColorValue } from 'react-native';
import type {
ConfigType,
RegionType,
IBeaconAndroid,
} from 'react-native-kontaktio';
const {
connect,
configure,
disconnect,
isConnected,
startScanning,
stopScanning,
restartScanning,
isScanning,
// setBeaconRegion,
setBeaconRegions,
getBeaconRegions,
setEddystoneNamespace,
IBEACON,
EDDYSTONE,
// Configurations
scanMode,
scanPeriod,
activityCheckConfiguration,
forceScanConfiguration,
monitoringEnabled,
monitoringSyncInterval,
} = Kontakt;
const region1: RegionType = {
identifier: 'Test beacons 1',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 1,
// no minor provided: will detect all minors
};
const region2: RegionType = {
identifier: 'Test beacons 2',
uuid: 'B0702880-A295-A8AB-F734-031A98A512D3',
major: 2,
// no minor provided: will detect all minors
};
type State = {
scanning: boolean;
beacons: Array<IBeaconAndroid>;
eddystones: Array<IBeaconAndroid>;
statusText: string | null;
};
/**
* Monitors beacons in two regions and sorts them by proximity,
* color-coded by minors with values 1 through 5.
*
* Just change the values in the regions to work with your beacons.
* Then press `Start scanning` and you should very soon see your beacons
* in a ScrollView sorted by their 'accuracy' which reflects a measure of
* distance from the beacons to your mobile phone in meters.
*
* This example makes use of regions to limit scanning to beacons
* belonging to one of these two regions.
* Of course regions can also be used to separately process the data later.
* Such logic may be built inside the listeners.
*
* Press `Start scanning` and you should very soon see your beacons in a ScrollView
* sorted by their RSSI which reflects a measure of distance from the beacons
* to your mobile phone.
*/
export default class IBeaconExample extends Component<{}, State> {
state: State = {
scanning: false,
beacons: [],
eddystones: [],
statusText: null,
};
componentDidMount() {
// Initialization, configuration and adding of beacon regions
const config: ConfigType = {
scanMode: scanMode.BALANCED,
scanPeriod: scanPeriod.create({
activePeriod: 6000,
passivePeriod: 20000,
}),
activityCheckConfiguration: activityCheckConfiguration.DEFAULT,
forceScanConfiguration: forceScanConfiguration.MINIMAL,
monitoringEnabled: monitoringEnabled.TRUE,
monitoringSyncInterval: monitoringSyncInterval.DEFAULT,
};
connect('MY_KONTAKTIO_API_KEY', [IBEACON, EDDYSTONE])
.then(() => configure(config))
.then(() => setBeaconRegions([region1, region2]))
.then(() => setEddystoneNamespace(null))
.catch((error) => console.log('error', error));
// Beacon listeners
DeviceEventEmitter.addListener(
'beaconDidAppear',
({ beacon: newBeacon, region }) => {
console.log('beaconDidAppear', newBeacon, region);
this.setState({
beacons: this.state.beacons.concat(newBeacon),
});
}
);
DeviceEventEmitter.addListener(
'beaconDidDisappear',
({ beacon: lostBeacon, region }) => {
console.log('beaconDidDisappear', lostBeacon, region);
const { beacons } = this.state;
const index = beacons.findIndex((beacon) =>
this._isIdenticalBeacon(lostBeacon, beacon)
);
this.setState({
beacons: beacons.reduce<Array<IBeaconAndroid>>((result, val, ind) => {
// don't add disappeared beacon to array
if (ind === index) return result;
// add all other beacons to array
else {
result.push(val);
return result;
}
}, []),
});
}
);
DeviceEventEmitter.addListener(
'beaconsDidUpdate',
({
beacons: updatedBeacons,
region,
}: {
beacons: Array<IBeaconAndroid>;
region: RegionType;
}) => {
console.log('beaconsDidUpdate', updatedBeacons, region);
const { beacons } = this.state;
updatedBeacons.forEach((updatedBeacon) => {
const index = beacons.findIndex((beacon) =>
this._isIdenticalBeacon(updatedBeacon, beacon)
);
this.setState({
beacons: beacons.reduce<Array<IBeaconAndroid>>(
(result, val, ind) => {
// replace current beacon values for updatedBeacon, keep current value for others
ind === index ? result.push(updatedBeacon) : result.push(val);
return result;
},
[]
),
});
});
}
);
// Region listeners
DeviceEventEmitter.addListener('regionDidEnter', ({ region }) => {
console.log('regionDidEnter', region);
});
DeviceEventEmitter.addListener('regionDidExit', ({ region }) => {
console.log('regionDidExit', region);
});
// Beacon monitoring listener
DeviceEventEmitter.addListener('monitoringCycle', ({ status }) => {
console.log('monitoringCycle', status);
});
/*
* Eddystone
*/
DeviceEventEmitter.addListener(
'eddystoneDidAppear',
({ eddystone, namespace }) => {
console.log('eddystoneDidAppear', eddystone, namespace);
this.setState({
eddystones: this.state.eddystones.concat(eddystone),
});
}
);
DeviceEventEmitter.addListener('namespaceDidEnter', ({ status }) => {
console.log('namespaceDidEnter', status);
});
DeviceEventEmitter.addListener('namespaceDidExit', ({ status }) => {
console.log('namespaceDidExit', status);
});
}
componentWillUnmount() {
// Disconnect beaconManager and set to it to null
disconnect();
DeviceEventEmitter.removeAllListeners();
}
_startScanning = () => {
startScanning()
.then(() => this.setState({ scanning: true, statusText: null }))
.then(() => console.log('started scanning'))
.catch((error) => console.log('[startScanning]', error));
};
_stopScanning = () => {
stopScanning()
.then(() =>
this.setState({ scanning: false, beacons: [], statusText: null })
)
.then(() => console.log('stopped scanning'))
.catch((error) => console.log('[stopScanning]', error));
};
_restartScanning = () => {
restartScanning()
.then(() =>
this.setState({ scanning: true, beacons: [], statusText: null })
)
.then(() => console.log('restarted scanning'))
.catch((error) => console.log('[restartScanning]', error));
};
_isScanning = () => {
isScanning()
.then((result) => {
this.setState({
statusText: `Device is currently ${result ? '' : 'NOT '}scanning.`,
});
console.log('Is device scanning?', result);
})
.catch((error) => console.log('[isScanning]', error));
};
_isConnected = () => {
isConnected()
.then((result) => {
this.setState({
statusText: `Device is ${result ? '' : 'NOT '}ready to scan beacons.`,
});
console.log('Is device connected?', result);
})
.catch((error) => console.log('[isConnected]', error));
};
_getBeaconRegions = () => {
getBeaconRegions()
.then((regions) => console.log('regions', regions))
.catch((error) => console.log('[getBeaconRegions]', error));
};
/**
* Helper function used to identify equal beacons
*/
_isIdenticalBeacon = (b1: IBeaconAndroid, b2: IBeaconAndroid) =>
b1.uniqueId === b2.uniqueId &&
b1.uuid === b2.uuid &&
b1.major === b2.major &&
b1.minor === b2.minor;
_renderBeacons = () => {
const colors = ['#F7C376', '#EFF7B7', '#F4CDED', '#A2C8F9', '#AAF7AF'];
return this.state.beacons
.sort(
(a: IBeaconAndroid, b: IBeaconAndroid) =>
parseInt(a.accuracy) - parseInt(b.accuracy)
)
.map(
(beacon, ind) => (
<View
style={[
styles.beacon,
{ backgroundColor: colors[beacon.minor - 1] },
]}
>
<Text style={{ fontWeight: 'bold' }}>{beacon.uniqueId}</Text>
<Text>
Major: {beacon.major}, Minor: {beacon.minor}
</Text>
<Text>
Distance: {beacon.accuracy}, Proximity: {beacon.proximity}
</Text>
<Text>
Battery Power: {beacon.batteryPower}, TxPower: {beacon.txPower}
</Text>
<Text>
FirmwareVersion: {beacon.firmwareVersion}, Address:{' '}
{beacon.uniqueId}
</Text>
</View>
),
this
);
};
_renderEmpty = () => {
const { scanning, beacons } = this.state;
let text;
if (!scanning) text = 'Start scanning to listen for beacon signals!';
if (scanning && !beacons.length) text = 'No beacons detected yet...';
return (
<View style={styles.textContainer}>
<Text style={styles.text}>{text}</Text>
</View>
);
};
_renderStatusText = () => {
const { statusText } = this.state;
return statusText ? (
<View style={styles.textContainer}>
<Text style={[styles.text, { color: 'red' }]}>{statusText}</Text>
</View>
) : null;
};
_renderButton = (
text: string,
onPress: () => void,
backgroundColor: ColorValue
) => (
<TouchableOpacity
style={[styles.button, { backgroundColor }]}
onPress={onPress}
>
<Text>{text}</Text>
</TouchableOpacity>
);
render() {
const { scanning, beacons } = this.state;
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
{this._renderButton('Start scan', this._startScanning, '#84e2f9')}
{this._renderButton('Stop scan', this._stopScanning, '#84e2f9')}
{this._renderButton('Restart scan', this._restartScanning, '#84e2f9')}
</View>
<View style={styles.buttonContainer}>
{this._renderButton('Is scanning?', this._isScanning, '#f2a2a2')}
{this._renderButton('Is connected?', this._isConnected, '#f2a2a2')}
</View>
<View style={styles.buttonContainer}>
{this._renderButton(
'Beacon regions (log)',
this._getBeaconRegions,
'#F4ED5A'
)}
</View>
{this._renderStatusText()}
<ScrollView>
{scanning && beacons.length
? this._renderBeacons()
: this._renderEmpty()}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
beacon: {
justifyContent: 'space-around',
alignItems: 'center',
padding: 10,
},
textContainer: {
alignItems: 'center',
},
text: {
fontSize: 18,
fontWeight: 'bold',
},
buttonContainer: {
marginVertical: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
button: {
padding: 10,
borderRadius: 10,
},
}); | the_stack |
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
// Types
ContextType,
ElementType,
MouseEvent as ReactMouseEvent,
MutableRefObject,
Ref,
} from 'react'
import { Props } from '../../types'
import { match } from '../../utils/match'
import { forwardRefWithAs, render, Features, PropsForFeatures } from '../../utils/render'
import { useSyncRefs } from '../../hooks/use-sync-refs'
import { Keys } from '../keyboard'
import { isDisabledReactIssue7711 } from '../../utils/bugs'
import { useId } from '../../hooks/use-id'
import { useFocusTrap, Features as FocusTrapFeatures } from '../../hooks/use-focus-trap'
import { useInertOthers } from '../../hooks/use-inert-others'
import { Portal } from '../../components/portal/portal'
import { ForcePortalRoot } from '../../internal/portal-force-root'
import { Description, useDescriptions } from '../description/description'
import { useWindowEvent } from '../../hooks/use-window-event'
import { useOpenClosed, State } from '../../internal/open-closed'
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
import { StackProvider, StackMessage } from '../../internal/stack-context'
enum DialogStates {
Open,
Closed,
}
interface StateDefinition {
titleId: string | null
}
enum ActionTypes {
SetTitleId,
}
type Actions = { type: ActionTypes.SetTitleId; id: string | null }
let reducers: {
[P in ActionTypes]: (
state: StateDefinition,
action: Extract<Actions, { type: P }>
) => StateDefinition
} = {
[ActionTypes.SetTitleId](state, action) {
if (state.titleId === action.id) return state
return { ...state, titleId: action.id }
},
}
let DialogContext = createContext<
| [
{
dialogState: DialogStates
close(): void
setTitleId(id: string | null): void
},
StateDefinition
]
| null
>(null)
DialogContext.displayName = 'DialogContext'
function useDialogContext(component: string) {
let context = useContext(DialogContext)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <${Dialog.displayName} /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useDialogContext)
throw err
}
return context
}
function stateReducer(state: StateDefinition, action: Actions) {
return match(action.type, reducers, state, action)
}
// ---
let DEFAULT_DIALOG_TAG = 'div' as const
interface DialogRenderPropArg {
open: boolean
}
type DialogPropsWeControl =
| 'id'
| 'role'
| 'aria-modal'
| 'aria-describedby'
| 'aria-labelledby'
| 'onClick'
let DialogRenderFeatures = Features.RenderStrategy | Features.Static
let DialogRoot = forwardRefWithAs(function Dialog<
TTag extends ElementType = typeof DEFAULT_DIALOG_TAG
>(
props: Props<TTag, DialogRenderPropArg, DialogPropsWeControl> &
PropsForFeatures<typeof DialogRenderFeatures> & {
open?: boolean
onClose(value: boolean): void
initialFocus?: MutableRefObject<HTMLElement | null>
},
ref: Ref<HTMLDivElement>
) {
let { open, onClose, initialFocus, ...rest } = props
let [nestedDialogCount, setNestedDialogCount] = useState(0)
let usesOpenClosedState = useOpenClosed()
if (open === undefined && usesOpenClosedState !== null) {
// Update the `open` prop based on the open closed state
open = match(usesOpenClosedState, {
[State.Open]: true,
[State.Closed]: false,
})
}
let containers = useRef<Set<MutableRefObject<HTMLElement | null>>>(new Set())
let internalDialogRef = useRef<HTMLDivElement | null>(null)
let dialogRef = useSyncRefs(internalDialogRef, ref)
// Validations
let hasOpen = props.hasOwnProperty('open') || usesOpenClosedState !== null
let hasOnClose = props.hasOwnProperty('onClose')
if (!hasOpen && !hasOnClose) {
throw new Error(
`You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.`
)
}
if (!hasOpen) {
throw new Error(
`You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.`
)
}
if (!hasOnClose) {
throw new Error(
`You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.`
)
}
if (typeof open !== 'boolean') {
throw new Error(
`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${open}`
)
}
if (typeof onClose !== 'function') {
throw new Error(
`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${onClose}`
)
}
let dialogState = open ? DialogStates.Open : DialogStates.Closed
let visible = (() => {
if (usesOpenClosedState !== null) {
return usesOpenClosedState === State.Open
}
return dialogState === DialogStates.Open
})()
let [state, dispatch] = useReducer(stateReducer, {
titleId: null,
descriptionId: null,
} as StateDefinition)
let close = useCallback(() => onClose(false), [onClose])
let setTitleId = useCallback(
(id: string | null) => dispatch({ type: ActionTypes.SetTitleId, id }),
[dispatch]
)
let ready = useServerHandoffComplete()
let enabled = ready && dialogState === DialogStates.Open
let hasNestedDialogs = nestedDialogCount > 1 // 1 is the current dialog
let hasParentDialog = useContext(DialogContext) !== null
// If there are multiple dialogs, then you can be the root, the leaf or one
// in between. We only care abou whether you are the top most one or not.
let position = !hasNestedDialogs ? 'leaf' : 'parent'
useFocusTrap(
internalDialogRef,
enabled
? match(position, {
parent: FocusTrapFeatures.RestoreFocus,
leaf: FocusTrapFeatures.All,
})
: FocusTrapFeatures.None,
{ initialFocus, containers }
)
useInertOthers(internalDialogRef, hasNestedDialogs ? enabled : false)
// Handle outside click
useWindowEvent('mousedown', event => {
let target = event.target as HTMLElement
if (dialogState !== DialogStates.Open) return
if (hasNestedDialogs) return
if (internalDialogRef.current?.contains(target)) return
close()
})
// Handle `Escape` to close
useWindowEvent('keydown', event => {
if (event.key !== Keys.Escape) return
if (dialogState !== DialogStates.Open) return
if (hasNestedDialogs) return
event.preventDefault()
event.stopPropagation()
close()
})
// Scroll lock
useEffect(() => {
if (dialogState !== DialogStates.Open) return
if (hasParentDialog) return
let overflow = document.documentElement.style.overflow
let paddingRight = document.documentElement.style.paddingRight
let scrollbarWidth = window.innerWidth - document.documentElement.clientWidth
document.documentElement.style.overflow = 'hidden'
document.documentElement.style.paddingRight = `${scrollbarWidth}px`
return () => {
document.documentElement.style.overflow = overflow
document.documentElement.style.paddingRight = paddingRight
}
}, [dialogState, hasParentDialog])
// Trigger close when the FocusTrap gets hidden
useEffect(() => {
if (dialogState !== DialogStates.Open) return
if (!internalDialogRef.current) return
let observer = new IntersectionObserver(entries => {
for (let entry of entries) {
if (
entry.boundingClientRect.x === 0 &&
entry.boundingClientRect.y === 0 &&
entry.boundingClientRect.width === 0 &&
entry.boundingClientRect.height === 0
) {
close()
}
}
})
observer.observe(internalDialogRef.current)
return () => observer.disconnect()
}, [dialogState, internalDialogRef, close])
let [describedby, DescriptionProvider] = useDescriptions()
let id = `headlessui-dialog-${useId()}`
let contextBag = useMemo<ContextType<typeof DialogContext>>(
() => [{ dialogState, close, setTitleId }, state],
[dialogState, state, close, setTitleId]
)
let slot = useMemo<DialogRenderPropArg>(() => ({ open: dialogState === DialogStates.Open }), [
dialogState,
])
let propsWeControl = {
ref: dialogRef,
id,
role: 'dialog',
'aria-modal': dialogState === DialogStates.Open ? true : undefined,
'aria-labelledby': state.titleId,
'aria-describedby': describedby,
onClick(event: ReactMouseEvent) {
event.stopPropagation()
},
}
let passthroughProps = rest
return (
<StackProvider
type="Dialog"
element={internalDialogRef}
onUpdate={useCallback((message, type, element) => {
if (type !== 'Dialog') return
match(message, {
[StackMessage.Add]() {
containers.current.add(element)
setNestedDialogCount(count => count + 1)
},
[StackMessage.Remove]() {
containers.current.add(element)
setNestedDialogCount(count => count - 1)
},
})
}, [])}
>
<ForcePortalRoot force={true}>
<Portal>
<DialogContext.Provider value={contextBag}>
<Portal.Group target={internalDialogRef}>
<ForcePortalRoot force={false}>
<DescriptionProvider slot={slot} name="Dialog.Description">
{render({
props: { ...passthroughProps, ...propsWeControl },
slot,
defaultTag: DEFAULT_DIALOG_TAG,
features: DialogRenderFeatures,
visible,
name: 'Dialog',
})}
</DescriptionProvider>
</ForcePortalRoot>
</Portal.Group>
</DialogContext.Provider>
</Portal>
</ForcePortalRoot>
</StackProvider>
)
})
// ---
let DEFAULT_OVERLAY_TAG = 'div' as const
interface OverlayRenderPropArg {
open: boolean
}
type OverlayPropsWeControl = 'id' | 'aria-hidden' | 'onClick'
let Overlay = forwardRefWithAs(function Overlay<
TTag extends ElementType = typeof DEFAULT_OVERLAY_TAG
>(props: Props<TTag, OverlayRenderPropArg, OverlayPropsWeControl>, ref: Ref<HTMLDivElement>) {
let [{ dialogState, close }] = useDialogContext([Dialog.displayName, Overlay.name].join('.'))
let overlayRef = useSyncRefs(ref)
let id = `headlessui-dialog-overlay-${useId()}`
let handleClick = useCallback(
(event: ReactMouseEvent) => {
if (event.target !== event.currentTarget) return
if (isDisabledReactIssue7711(event.currentTarget)) return event.preventDefault()
event.preventDefault()
event.stopPropagation()
close()
},
[close]
)
let slot = useMemo<OverlayRenderPropArg>(() => ({ open: dialogState === DialogStates.Open }), [
dialogState,
])
let propsWeControl = {
ref: overlayRef,
id,
'aria-hidden': true,
onClick: handleClick,
}
let passthroughProps = props
return render({
props: { ...passthroughProps, ...propsWeControl },
slot,
defaultTag: DEFAULT_OVERLAY_TAG,
name: 'Dialog.Overlay',
})
})
// ---
let DEFAULT_TITLE_TAG = 'h2' as const
interface TitleRenderPropArg {
open: boolean
}
type TitlePropsWeControl = 'id'
function Title<TTag extends ElementType = typeof DEFAULT_TITLE_TAG>(
props: Props<TTag, TitleRenderPropArg, TitlePropsWeControl>
) {
let [{ dialogState, setTitleId }] = useDialogContext([Dialog.displayName, Title.name].join('.'))
let id = `headlessui-dialog-title-${useId()}`
useEffect(() => {
setTitleId(id)
return () => setTitleId(null)
}, [id, setTitleId])
let slot = useMemo<TitleRenderPropArg>(() => ({ open: dialogState === DialogStates.Open }), [
dialogState,
])
let propsWeControl = { id }
let passthroughProps = props
return render({
props: { ...passthroughProps, ...propsWeControl },
slot,
defaultTag: DEFAULT_TITLE_TAG,
name: 'Dialog.Title',
})
}
// ---
export let Dialog = Object.assign(DialogRoot, { Overlay, Title, Description }) | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import {
Chart, LineSeries, ILoadedEventArgs, getElement, DataLabel, AreaSeries, ColumnSeries, BarSeries,
StackingAreaSeries, ScatterSeries, BubbleSeries, StepLineSeries, SplineSeries, removeElement,
StepAreaSeries, RangeColumnSeries, Category
} from '../../../src/chart/index';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { unbindResizeEvents, DataValue } from '../base/data.spec';
import { EmitType } from '@syncfusion/ej2-base';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
Chart.Inject(
LineSeries, DataLabel, AreaSeries, ColumnSeries, BarSeries, SplineSeries,
StackingAreaSeries, ScatterSeries, BubbleSeries, StepLineSeries, StepAreaSeries,
RangeColumnSeries, Category);
export let emptyPointsData1: DataValue[] = [
{ x: 1000, y: 70 }, { x: 2000, y: 40 },
{ x: 3000, y: null }, { x: 4000, y: 60 },
{ x: 5000, y: 50 }, { x: 6000, y: null },
{ x: 7000, y: 40 }];
export let emptyPointsData2: DataValue[] = [
{ x: 1000, y: null }, { x: 2000, y: 40 },
{ x: 3000, y: 50 }, { x: 4000, y: null },
{ x: 5000, y: null }, { x: 6000, y: 90 },
{ x: 7000, y: 40 }];
describe('Empty Points checking with', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
let element: HTMLElement;
describe('Numeric value Type', () => {
let chartObj: Chart;
let loaded: EmitType<ILoadedEventArgs>;
let pathElement: Element = null;
let markerElement: Element = null;
let pointElement: Element = null;
let path: string = null;
let id: string = 'empty-container';
let temp: number;
element = createElement('div', { id: id });
beforeAll(() => {
document.body.appendChild(element);
chartObj = new Chart(
{
series: [{
animation: { enable: false }, name: 'Holiday Expense', dataSource: emptyPointsData1, xName: 'x', yName: 'y',
type: 'Line', fill: 'rgba(135,206,235,1)',
marker: { visible: true, dataLabel: { visible: true}}
},
{
animation: { enable: false }, name: 'Holiday Income', dataSource: emptyPointsData2, xName: 'x', yName: 'y',
type: 'Line', fill: 'green',
marker: { visible: true, dataLabel: { visible: true}}
}],
width: '800', title: 'Chart Empty Point Sample',
loaded: loaded,
legendSettings: { visible: false }
});
chartObj.appendTo('#' + id);
});
afterAll((): void => {
chartObj.loaded = null;
chartObj.destroy();
removeElement('empty-container');
});
it('Empty Point with Line Series Gap mode', (done: Function) => {
loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(3);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Empty Point with Line Series Zero mode', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(12);
markerElement = getElement('empty-container_Series_0_Point_2_Symbol');
expect(parseInt(markerElement.getAttribute('cx'), 10)).toBe(250);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect( temp === 372 || temp === 368 ).toBe(true);
expect(markerElement.getAttribute('fill')).toBe('blue');
expect(markerElement.getAttribute('stroke')).toBe('purple');
expect(markerElement.getAttribute('stroke-width')).toBe('2');
expect(pathLength).toBe(12);
markerElement = getElement('empty-container_Series_1_Point_3_Symbol');
expect(parseInt(markerElement.getAttribute('cx'), 10)).toBe(375);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 372 || temp === 368).toBe(true);
expect(markerElement.getAttribute('fill')).toBe('blue');
expect(markerElement.getAttribute('stroke')).toBe('purple');
expect(markerElement.getAttribute('stroke-width')).toBe('2');
done();
};
chartObj.series[0].emptyPointSettings = { mode: 'Zero', fill: 'blue', border: { width: 2, color: 'purple'}};
chartObj.series[1].emptyPointSettings = { mode: 'Zero', fill: 'blue', border: { width: 2, color: 'purple'}};
chartObj.refresh();
});
it('Empty Point with Line Series Average Mode', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(12);
markerElement = getElement('empty-container_Series_0_Point_5_Symbol');
temp = parseInt(markerElement.getAttribute('cx'), 10);
expect(temp === 626 || temp === 625).toBe(true);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 204 ||temp === 202).toBe(true);
markerElement = getElement('empty-container_Series_1_Point_4_Symbol');
temp = parseInt(markerElement.getAttribute('cx'), 10);
expect(temp === 500 || temp === 501).toBe(true);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 204 ||temp === 202).toBe(true);
done();
};
chartObj.series[0].emptyPointSettings = { mode: 'Average'};
chartObj.series[1].emptyPointSettings = { mode: 'Average'};
chartObj.refresh();
});
it('Empty Point with Line Series Drop Mode', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(8);
markerElement = getElement('empty-container_Series_0_Point_5_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_0_Point_2_Symbol');
expect(markerElement).toBe(null);
done();
};
chartObj.series[0].emptyPointSettings = { mode: 'Drop'};
chartObj.series[1].emptyPointSettings = { mode: 'Drop'};
chartObj.refresh();
});
it('Empty Point with Column Series Average and Zero Mode', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_1_Point_4');
path = pathElement.getAttribute('d');
let pathXY: string[] = path.split(' ');
expect(pathXY[2] === '372.25' || pathXY[2] === '368.25' ).toBe(true);
expect(pathXY[2] === '372.25' || pathXY[5] === '368.25' ).toBe(true);
pathElement = getElement(id + '_Series_0_Point_5');
path = pathElement.getAttribute('d');
pathXY = path.split(' ');
temp = parseInt(pathXY[18], 10);
expect(temp === 372 || temp === 368).toBe(true);
temp = parseInt(pathXY[5], 10);
expect(temp === 204 || temp === 202).toBe(true);
done();
};
chartObj.series[0].type = 'Column';
chartObj.series[1].type = 'Column';
chartObj.series[0].emptyPointSettings = { mode: 'Average'};
chartObj.series[1].emptyPointSettings = { mode: 'Zero'};
chartObj.refresh();
});
it('Empty Point with Area Series Drop', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(7);
markerElement = getElement('empty-container_Series_0_Point_5_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_0_Point_2_Symbol');
expect(markerElement).toBe(null);
pathElement = getElement(id + '_Series_1');
path = pathElement.getAttribute('d');
pathLength = path.split('L').length;
expect(pathLength).toBe(6);
markerElement = getElement('empty-container_Series_1_Point_4_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_1_Point_0_Symbol');
expect(markerElement).toBe(null);
done();
};
chartObj.series[0].type = 'Area';
chartObj.series[1].type = 'Area';
chartObj.series[0].emptyPointSettings = { mode: 'Drop'};
chartObj.series[1].emptyPointSettings = { mode: 'Drop'};
chartObj.refresh();
});
it('Empty Point with Stepline Series Drop', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(14);
markerElement = getElement('empty-container_Series_0_Point_5_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_0_Point_2_Symbol');
expect(markerElement).toBe(null);
pathElement = getElement(id + '_Series_1');
path = pathElement.getAttribute('d');
pathLength = path.split('L').length;
expect(pathLength).toBe(11);
markerElement = getElement('empty-container_Series_1_Point_4_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_1_Point_0_Symbol');
expect(markerElement).toBe(null);
done();
};
chartObj.series[0].type = 'StepLine';
chartObj.series[1].type = 'StepLine';
chartObj.refresh();
});
it('Empty Point with Stacking Area Series Drop', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(11);
markerElement = getElement('empty-container_Series_0_Point_5_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_0_Point_2_Symbol');
expect(markerElement).toBe(null);
pathElement = getElement(id + '_Series_1');
path = pathElement.getAttribute('d');
pathLength = path.split('L').length;
expect(pathLength).toBe(10);
markerElement = getElement('empty-container_Series_1_Point_4_Symbol');
expect(markerElement).toBe(null);
markerElement = getElement('empty-container_Series_1_Point_0_Symbol');
expect(markerElement).toBe(null);
done();
};
chartObj.series[0].type = 'StackingArea';
chartObj.series[1].type = 'StackingArea';
chartObj.refresh();
});
it('Empty Point with Scatter Series Average', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
markerElement = getElement(id + '_Series_1_Point_0');
expect(parseInt(markerElement.getAttribute('cx'), 10)).toBe(0);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 297 || temp === 294).toBe(true);
markerElement = getElement(id + '_Series_0_Point_5');
temp = parseInt(markerElement.getAttribute('cx'), 10);
expect(temp === 625 || temp === 626).toBe(true);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 204 || temp === 202).toBe(true);
done();
};
chartObj.series[0].type = 'Scatter';
chartObj.series[1].type = 'Scatter';
chartObj.series[0].emptyPointSettings = { mode: 'Average'};
chartObj.series[1].emptyPointSettings = { mode: 'Average'};
chartObj.refresh();
});
it('Empty Point with Bubble Series Average', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
markerElement = getElement(id + '_Series_1_Point_3');
expect(parseInt(markerElement.getAttribute('cx'), 10)).toBe(375);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 279 || temp === 276).toBe(true);
markerElement = getElement(id + '_Series_0_Point_1');
expect(parseInt(markerElement.getAttribute('cx'), 10)).toBe(125);
temp = parseInt(markerElement.getAttribute('cy'), 10);
expect(temp === 223 || temp === 220).toBe(true);
done();
};
chartObj.series[0].type = 'Bubble';
chartObj.series[1].type = 'Bubble';
chartObj.series[0].emptyPointSettings = { mode: 'Average'};
chartObj.series[1].emptyPointSettings = { mode: 'Average'};
chartObj.refresh();
});
it('Empty Point with Spline Series Drop', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(4);
pathElement = getElement(id + '_Series_1');
path = pathElement.getAttribute('d');
pathLength = path.split('L').length;
expect(pathLength).toBe(3);
done();
};
chartObj.series[0].type = 'Spline';
chartObj.series[1].type = 'Spline';
chartObj.series[0].emptyPointSettings = { mode: 'Drop'};
chartObj.series[1].emptyPointSettings = { mode: 'Drop'};
chartObj.refresh();
});
it('Empty Point with StepArea Series Drop', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0');
path = pathElement.getAttribute('d');
let pathLength: number = path.split('L').length;
expect(pathLength).toBe(15);
pathElement = getElement(id + '_Series_1');
path = pathElement.getAttribute('d');
pathLength = path.split('L').length;
expect(pathLength).toBe(10);
done();
};
chartObj.series[0].type = 'StepArea';
chartObj.series[0].dataSource = [
{ x: 1000, y: 70 }, { x: 2000, y: undefined },
{ x: 3000, y: 40 }, { x: 4000, y: 60 },
{ x: 5000, y: 50 }, { x: 6000, y: null },
{ x: 7000, y: 40 }];
chartObj.series[1].type = 'StepArea';
chartObj.series[0].emptyPointSettings = { mode: 'Gap'};
chartObj.series[1].emptyPointSettings = { mode: 'Drop'};
chartObj.refresh();
});
it('Empty Point with Range Column Series Average and Zero', (done: Function) => {
chartObj.loaded = (args: ILoadedEventArgs): void => {
pathElement = getElement(id + '_Series_0_Point_5');
path = pathElement.getAttribute('d');
let pathXY: string[] = path.split(' ');
temp = parseInt(pathXY[18], 10);
expect(temp === 230 || temp === 227).toBe(true);
temp = parseInt(pathXY[5], 10);
expect(temp === 87).toBe(true);
expect(pathElement.getAttribute('fill')).toBe('blue');
pathElement = getElement(id + '_Series_1_Point_9');
path = pathElement.getAttribute('d');
pathXY = path.split(' ');
temp = parseInt(pathXY[2], 10);
expect(temp === 372 || temp === 368).toBe(true);
temp = parseInt(pathXY[5], 10);
expect(temp === 372 || temp === 368).toBe(true);
done();
};
chartObj.series[0].dataSource = [
{ x: 'Jan', low: 0.7, high: 6.1 }, { x: 'Feb', low: 1.3, high: 6.3 },
{ x: 'Mar', low: 1.9, high: 8.5 }, { x: 'Apr', low: null, high: 10.8 },
{ x: 'May', low: 5.7, high: 14.4 }, { x: 'June', low: 8.4, high: null },
{ x: 'July', low: 10.6, high: 19.2 }, { x: 'Aug', low: 10.5, high: 18.9 },
{ x: 'Sep', low: 8.5, high: 16.1 }, { x: 'Oct', low: null, high: null },
{ x: 'Nov', low: 1.5, high: 6.9 }, { x: 'Dec', low: 5.1, high: 12.1 }
];
chartObj.series[0].xName = 'x';
chartObj.series[0].high = 'high';
chartObj.series[0].low = 'low';
chartObj.series[0].type = 'RangeColumn';
chartObj.series[1].dataSource = [
{ x: 'Jan', low: 1.7, high: 7.1 }, { x: 'Feb', low: 1.9, high: 7.7 },
{ x: 'Mar', low: 1.2, high: 7.5 }, { x: 'Apr', low: null, high: 9.8 },
{ x: 'May', low: 4.7, high: 11.4 }, { x: 'June', low: 6.4, high: null },
{ x: 'July', low: 9.6, high: 17.2 }, { x: 'Aug', low: 10.7, high: 17.9 },
{ x: 'Sep', low: 7.5, high: 15.1 }, { x: 'Oct', low: null, high: null },
{ x: 'Nov', low: 1.2, high: 7.9 }, { x: 'Dec', low: 4.1, high: 9.1 }
];
chartObj.series[1].xName = 'x';
chartObj.series[1].high = 'high';
chartObj.series[1].low = 'low';
chartObj.series[1].type = 'RangeColumn';
chartObj.primaryXAxis.valueType = 'Category';
chartObj.series[0].emptyPointSettings = { mode: 'Average'};
chartObj.series[1].emptyPointSettings = { mode: 'Zero'};
chartObj.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
import * as path from 'path';
import {google} from '../../protos/protos';
import {grpc} from 'google-gax';
import * as protoLoader from '@grpc/proto-loader';
import {createUnimplementedError, now} from './mockspanner';
import v1 = google.spanner.admin.instance.v1;
import iam = google.iam.v1;
import longrunning = google.longrunning;
import Any = google.protobuf.Any;
import Empty = google.protobuf.Empty;
const PROTO_PATH = 'spanner_instance_admin.proto';
const IMPORT_PATH = __dirname + '/../../../protos';
const PROTO_DIR =
__dirname + '/../../../protos/google/spanner/admin/instance/v1';
const GAX_PROTO_DIR = path.join(
path.dirname(require.resolve('google-gax')),
'..',
'protos'
);
/**
* Load the Spanner Instance Admin service proto.
*/
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: false,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs: [IMPORT_PATH, PROTO_DIR, GAX_PROTO_DIR],
});
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const instanceAdminProtoDescriptor =
protoDescriptor['google']['spanner']['admin']['instance']['v1'];
export const TEST_INSTANCE_CONFIG_NAME =
'projects/mock-project/instanceConfigs/test-instance-config';
export const TEST_INSTANCE_NAME = 'projects/mock-project/instances/test';
export const PROD_INSTANCE_NAME = 'projects/mock-project/instances/prod';
export class MockInstanceAdmin {
private static TEST_INSTANCE_CONFIG = v1.InstanceConfig.create({
name: TEST_INSTANCE_CONFIG_NAME,
displayName: 'Test Instance Config',
replicas: [
v1.ReplicaInfo.create({
type: v1.ReplicaInfo.ReplicaType.READ_WRITE,
location: 'local',
defaultLeaderLocation: true,
}),
],
});
private static TEST_INSTANCE = v1.Instance.create({
config: TEST_INSTANCE_CONFIG_NAME,
name: TEST_INSTANCE_NAME,
displayName: 'Test Instance',
nodeCount: 1,
state: v1.Instance.State.READY,
labels: {purpose: 'Test'},
});
private static PROD_INSTANCE = v1.Instance.create({
config: TEST_INSTANCE_CONFIG_NAME,
name: PROD_INSTANCE_NAME,
displayName: 'Production Instance',
nodeCount: 6,
state: v1.Instance.State.READY,
labels: {purpose: 'Production'},
});
private constructor() {}
/**
* Creates a MockInstanceAdmin.
*/
static create(): MockInstanceAdmin {
return new MockInstanceAdmin();
}
private static createNotFoundError(msg: string): grpc.ServiceError {
const error = new Error(msg);
return Object.assign(error, {
code: grpc.status.NOT_FOUND,
}) as grpc.ServiceError;
}
private static createServiceError(msg: string, code: grpc.status) {
const error = new Error(msg);
return Object.assign(error, {
code,
});
}
listInstanceConfigs(
call: grpc.ServerUnaryCall<
v1.ListInstanceConfigsRequest,
v1.ListInstanceConfigsResponse
>,
callback: v1.InstanceAdmin.ListInstanceConfigsCallback
) {
callback(
null,
v1.ListInstanceConfigsResponse.create({
instanceConfigs: [MockInstanceAdmin.TEST_INSTANCE_CONFIG],
})
);
}
getInstanceConfig(
call: grpc.ServerUnaryCall<v1.GetInstanceConfigRequest, v1.Instance>,
callback: v1.InstanceAdmin.GetInstanceConfigCallback
) {
if (call.request!.name === TEST_INSTANCE_CONFIG_NAME) {
callback(null, MockInstanceAdmin.TEST_INSTANCE_CONFIG);
} else {
callback(
MockInstanceAdmin.createNotFoundError(
`InstanceConfig not found: ${call.request!.name}`
)
);
}
}
listInstances(
call: grpc.ServerUnaryCall<
v1.ListInstancesRequest,
v1.ListInstancesResponse
>,
callback: v1.InstanceAdmin.ListInstancesCallback
) {
let instances: google.spanner.admin.instance.v1.IInstance[] = [];
if (
!call.request!.filter ||
call.request!.filter.includes(
`name:${MockInstanceAdmin.TEST_INSTANCE.name}`
)
) {
instances.push(MockInstanceAdmin.TEST_INSTANCE);
}
if (
!call.request!.filter ||
call.request!.filter.includes(
`name:${MockInstanceAdmin.PROD_INSTANCE.name}`
)
) {
instances.push(MockInstanceAdmin.PROD_INSTANCE);
}
if (call.request!.pageToken) {
const beginIndex = Number.parseInt(call.request!.pageToken, 10);
instances = instances.slice(beginIndex);
}
if (call.request!.pageSize && call.request!.pageSize < instances.length) {
instances = instances.slice(0, call.request!.pageSize);
}
callback(
null,
v1.ListInstancesResponse.create({
instances,
})
);
}
getInstance(
call: grpc.ServerUnaryCall<v1.GetInstanceRequest, v1.Instance>,
callback: v1.InstanceAdmin.GetInstanceCallback
) {
if (call.request!.name === TEST_INSTANCE_NAME) {
callback(null, MockInstanceAdmin.TEST_INSTANCE);
} else if (call.request!.name === PROD_INSTANCE_NAME) {
callback(null, MockInstanceAdmin.PROD_INSTANCE);
} else {
callback(
MockInstanceAdmin.createNotFoundError(
`Instance not found: ${call.request!.name}`
)
);
}
}
createInstance(
call: grpc.ServerUnaryCall<v1.CreateInstanceRequest, longrunning.Operation>,
callback: v1.InstanceAdmin.CreateInstanceCallback
) {
const instance = v1.Instance.create({
name: `${call.request!.parent}/instances/${call.request!.instanceId}`,
displayName: call.request!.instance
? call.request!.instance.displayName
: undefined,
config: call.request!.instance
? call.request!.instance.config
: undefined,
nodeCount: call.request!.instance
? call.request!.instance.nodeCount
: undefined,
processingUnits: call.request!.instance
? call.request!.instance.processingUnits
: undefined,
labels: call.request!.instance
? call.request!.instance.labels
: undefined,
state: v1.Instance.State.READY,
});
const metadataBuffer = v1.CreateInstanceMetadata.encode(
v1.CreateInstanceMetadata.create({
instance,
startTime: now(),
endTime: now(),
})
).finish();
const instanceBuffer = v1.Instance.encode(instance).finish();
callback(
null,
longrunning.Operation.create({
name: 'projects/mock-project/operations/mock-operation',
done: true,
metadata: Any.create({
value: metadataBuffer,
}),
response: Any.create({
value: instanceBuffer,
}),
})
);
}
updateInstance(
call: grpc.ServerUnaryCall<v1.UpdateInstanceRequest, longrunning.Operation>,
callback: v1.InstanceAdmin.UpdateInstanceCallback
) {
if (call.request!.instance) {
if (
call.request!.instance.name === PROD_INSTANCE_NAME ||
call.request!.instance.name === TEST_INSTANCE_NAME
) {
const metadataBuffer = v1.CreateInstanceMetadata.encode(
v1.CreateInstanceMetadata.create({
instance: call.request!.instance,
startTime: now(),
endTime: now(),
})
).finish();
callback(
null,
longrunning.Operation.create({
name: 'projects/mock-project/operations/mock-operation',
done: true,
metadata: Any.create({
value: metadataBuffer,
}),
response: Any.create({
value: v1.Instance.encode(call.request!.instance).finish(),
}),
})
);
} else {
callback(
MockInstanceAdmin.createNotFoundError(
`Instance not found: ${call.request!.instance.name}`
)
);
}
} else {
callback(
MockInstanceAdmin.createServiceError(
'Missing instance in UpdateInstance request',
grpc.status.INVALID_ARGUMENT
)
);
}
}
deleteInstance(
call: grpc.ServerUnaryCall<v1.DeleteInstanceRequest, Empty>,
callback: v1.InstanceAdmin.DeleteInstanceCallback
) {
if (
call.request!.name === PROD_INSTANCE_NAME ||
call.request!.name === TEST_INSTANCE_NAME
) {
callback(null, Empty.create({}));
} else {
callback(
MockInstanceAdmin.createNotFoundError(
`Instance not found: ${call.request!.name}`
)
);
}
}
setIamPolicy(
call: grpc.ServerUnaryCall<iam.SetIamPolicyRequest, {}>,
callback: iam.IAMPolicy.SetIamPolicyCallback
) {
callback(createUnimplementedError('SetIamPolicy is not yet implemented'));
}
getIamPolicy(
call: grpc.ServerUnaryCall<iam.GetIamPolicyRequest, {}>,
callback: iam.IAMPolicy.GetIamPolicyCallback
) {
callback(createUnimplementedError('GetIamPolicy is not yet implemented'));
}
testIamPermissions(
call: grpc.ServerUnaryCall<iam.TestIamPermissionsRequest, {}>,
callback: iam.IAMPolicy.TestIamPermissionsCallback
) {
callback(
createUnimplementedError('TestIamPermissions is not yet implemented')
);
}
}
/**
* Creates and adds a MockInstanceAdmin instance to the given server. The mock contains the following data by default:
* 1. One InstanceConfig with the name 'projects/mock-project/instanceConfigs/test-instance-config'.
* 2. Two Instances: 'projects/mock-project/instances/test' and 'projects/mock-project/instances/prod'.
*/
export function createMockInstanceAdmin(
server: grpc.Server
): MockInstanceAdmin {
const mock = MockInstanceAdmin.create();
server.addService(instanceAdminProtoDescriptor.InstanceAdmin.service, {
listInstanceConfigs: mock.listInstanceConfigs,
getInstanceConfig: mock.getInstanceConfig,
listInstances: mock.listInstances,
getInstance: mock.getInstance,
createInstance: mock.createInstance,
updateInstance: mock.updateInstance,
deleteInstance: mock.deleteInstance,
setIamPolicy: mock.setIamPolicy,
getIamPolicy: mock.getIamPolicy,
testIamPermissions: mock.testIamPermissions,
});
return mock;
} | the_stack |
import type {
LineAndColumnData,
ReportDescriptor,
RuleContext,
SourceLocation,
ReportDescriptorSourceLocation,
} from "../../../types"
import type { StyleContext } from "../style"
import type { VCSSCommentNode } from "../../ast"
const COMMENT_DIRECTIVE_B =
/^\s*(eslint-(?:en|dis)able)(?:\s+(\S|\S[\s\S]*\S))?\s*$/u
const COMMENT_DIRECTIVE_L =
/^\s*(eslint-disable(?:-next)?-line)(?:\s+(\S|\S[\s\S]*\S))?\s*$/u
type ParsingResult = { type: string; rules: string[] }
type BlockData = { loc: LineAndColumnData; disable: boolean }
/**
* Parse a given comment.
* @param {RegExp} pattern The RegExp pattern to parse.
* @param {string} comment The comment value to parse.
* @returns {({type:string,rules:string[]})|null} The parsing result.
*/
function parse(pattern: RegExp, comment: string): ParsingResult | null {
const match = pattern.exec(comment)
if (match == null) {
return null
}
const type = match[1]
const rules = (match[2] || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean)
return { type, rules }
}
/**
* Enable rules.
* @param {CommentDirectives} commentDirectives The comment directives context.
* @param {{line:number,column:number}} loc The location information to enable.
* @param {string[]} rules The rule IDs to enable.
* @returns {void}
*/
function enable(
commentDirectives: CommentDirectives,
loc: LineAndColumnData,
rules: string[],
) {
if (rules.length === 0) {
commentDirectives.enableAll(loc)
} else {
commentDirectives.enableRules(loc, rules)
}
}
/**
* Disable rules.
* @param {CommentDirectives} commentDirectives The comment directives context.
* @param {{line:number,column:number}} loc The location information to disable.
* @param {string[]} rules The rule IDs to disable.
* @returns {void}
*/
function disable(
commentDirectives: CommentDirectives,
loc: LineAndColumnData,
rules: string[],
) {
if (rules.length === 0) {
commentDirectives.disableAll(loc)
} else {
commentDirectives.disableRules(loc, rules)
}
}
/**
* Process a given comment token.
* If the comment is `eslint-disable` or `eslint-enable` then it reports the comment.
* @param {CommentDirectives} commentDirectives The comment directives context.
* @param {Token} comment The comment token to process.
* @returns {void}
*/
function processBlock(
commentDirectives: CommentDirectives,
comment: VCSSCommentNode,
) {
const parsed = parse(COMMENT_DIRECTIVE_B, comment.text)
if (parsed != null) {
if (parsed.type === "eslint-disable") {
disable(commentDirectives, comment.loc.start, parsed.rules)
} else {
enable(commentDirectives, comment.loc.start, parsed.rules)
}
}
}
/**
* Process a given comment token.
* If the comment is `eslint-disable-line` or `eslint-disable-next-line` then it reports the comment.
* @param {CommentDirectives} commentDirectives The comment directives context.
* @param {Token} comment The comment token to process.
* @returns {void}
*/
function processLine(
commentDirectives: CommentDirectives,
comment: VCSSCommentNode,
) {
const parsed = parse(COMMENT_DIRECTIVE_L, comment.text)
if (parsed != null && comment.loc.start.line === comment.loc.end.line) {
const line =
comment.loc.start.line +
(parsed.type === "eslint-disable-line" ? 0 : 1)
const column = -1
if (!parsed.rules.length) {
commentDirectives.disableLineAll({ line, column })
} else {
commentDirectives.disableLineRules({ line, column }, parsed.rules)
}
}
}
export class CommentDirectives {
private _disableLines: {
[key: number]: {
all: boolean
[key: string]: boolean
}
}
private _disableBlocks: { [key: string]: BlockData[] }
/**
* constructor
* @param {StyleContext[]} styles The styles
* @returns {void}
*/
public constructor(styles: StyleContext[]) {
this._disableLines = {}
this._disableBlocks = {}
for (const style of styles) {
const cssNode = style.cssNode
if (cssNode != null) {
for (const comment of cssNode.comments) {
processBlock(this, comment)
processLine(this, comment)
}
this.clear(cssNode.loc.end)
}
}
for (const rule of Object.keys(this._disableBlocks)) {
this._disableBlocks[rule].sort((a, b) => compareLoc(a.loc, b.loc))
}
}
public disableLineAll(loc: LineAndColumnData): void {
const disableLine =
this._disableLines[loc.line] ||
(this._disableLines[loc.line] = { all: true })
disableLine.all = true
}
public disableLineRules(loc: LineAndColumnData, rules: string[]): void {
const disableLine =
this._disableLines[loc.line] ||
(this._disableLines[loc.line] = { all: false })
for (const rule of rules) {
disableLine[rule] = true
}
}
public disableAll(loc: LineAndColumnData): void {
const disableBlock =
this._disableBlocks.all || (this._disableBlocks.all = [])
disableBlock.push({ loc, disable: true })
}
public disableRules(loc: LineAndColumnData, rules: string[]): void {
for (const rule of rules) {
const disableBlock =
this._disableBlocks[rule] || (this._disableBlocks[rule] = [])
disableBlock.push({ loc, disable: true })
}
}
public enableAll(loc: LineAndColumnData): void {
const disableBlock =
this._disableBlocks.all || (this._disableBlocks.all = [])
disableBlock.push({ loc, disable: false })
}
public enableRules(loc: LineAndColumnData, rules: string[]): void {
for (const rule of rules) {
const disableBlock =
this._disableBlocks[rule] || (this._disableBlocks[rule] = [])
disableBlock.push({ loc, disable: false })
}
}
public clear(loc: LineAndColumnData): void {
for (const rule of Object.keys(this._disableBlocks)) {
this._disableBlocks[rule].push({ loc, disable: false })
}
}
/**
* Checks if rule is enabled or not
* @param {string} rule
* @param {ReportDescriptor} descriptor ESLint report descriptor
* @returns {boolean} `true` if rule is enabled
*/
public isEnabled(rule: string, descriptor: ReportDescriptor): boolean {
const loc = hasSourceLocation(descriptor)
? descriptor.loc
: descriptor.node?.loc
if (!loc) {
return false
}
const locStart = (loc as SourceLocation).start || loc
const disableLine = this._disableLines[locStart.line]
if (disableLine) {
if (disableLine.all || disableLine[rule]) {
return false
}
}
for (const ruleId of [rule, "all"]) {
const disableBlock = this._disableBlocks[ruleId]
if (disableBlock) {
let disableState = false
for (const block of disableBlock) {
if (compareLoc(locStart, block.loc) < 0) {
break
}
disableState = block.disable
}
if (disableState) {
return false
}
}
}
return true
}
}
export class CommentDirectivesReporter {
private readonly context: RuleContext
private readonly commentDirectives: CommentDirectives
/**
* constructor
* @param {RuleContext} context ESLint rule context
* @param {CommentDirectives} commentDirectives The comment directives context.
* @returns {void}
*/
public constructor(
context: RuleContext,
commentDirectives: CommentDirectives,
) {
this.context = context
this.commentDirectives = commentDirectives
}
/**
* Reports a problem in the code.
* @param {ReportDescriptor} descriptor ESLint report descriptor
* @returns {void}
*/
public report(descriptor: ReportDescriptor): void {
if (this.commentDirectives.isEnabled(this.context.id, descriptor)) {
this.context.report(descriptor)
}
}
}
/**
* Create the comment directives context
* @param {RuleContext} context ESLint rule context
* @param {StyleContext[]} styleContexts The styles
* @returns {CommentDirectives} the comment directives context
*/
export function createCommentDirectives(
styleContexts: StyleContext[],
): CommentDirectives {
return new CommentDirectives(styleContexts)
}
/**
* Create the comment directive reporter
* @param {RuleContext} context ESLint rule context
* @param {CommentDirectives} commentDirectives the comment directives context
* @returns {CommentDirectivesReporter} the comment directives
*/
export function createCommentDirectivesReporter(
context: RuleContext,
commentDirectives: CommentDirectives,
): CommentDirectivesReporter {
return new CommentDirectivesReporter(context, commentDirectives)
}
/**
* Compare values
* @param {*} a The first value
* @param {*} b The second value
*/
function compare(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- check compare
a: any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- check compare
b: any,
) {
return a === b ? 0 : a > b ? 1 : -1
}
/**
* Compare locations
* @param {*} a The first value
* @param {*} b The second value
*/
function compareLoc(a: LineAndColumnData, b: LineAndColumnData) {
const lc = compare(a.line, b.line)
if (lc !== 0) {
return lc
}
return compare(a.column, b.column)
}
/**
* Checks whether the given descriptor has loc property
*/
function hasSourceLocation(
descriptor: ReportDescriptor,
): descriptor is ReportDescriptor & ReportDescriptorSourceLocation {
return (descriptor as ReportDescriptorSourceLocation).loc != null
} | the_stack |
// eslint-disable-next-line import/no-extraneous-dependencies
import { DynamoDB } from 'aws-sdk';
export class CompositeStringIndexTable {
public static readonly API_VERSION = '2012-08-10';
public static async fromExisting(client: DynamoDB, tableName: string): Promise<CompositeStringIndexTable> {
// Determine the key schema of the table
// We let this throw if the table does not exist.
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#describeTable-property
const describeResponse = await client.describeTable({ TableName: tableName }).promise();
if (!describeResponse.Table) {
throw Error(`Could not describeTable for Table '${tableName}'`);
}
const keySchema = describeResponse.Table.KeySchema;
if (!keySchema) {
throw Error(`Could not get KeySchema for Table '${tableName}'`);
}
const attributes = describeResponse.Table.AttributeDefinitions;
if (!attributes) {
throw Error(`Could not get Attributes for Table '${tableName}'`);
}
// Find the names of the Primary & Sort keys.
const hashIndex: number = keySchema.findIndex(item => item.KeyType === 'HASH');
const sortIndex: number = keySchema.findIndex(item => item.KeyType === 'RANGE');
if (hashIndex < 0 || sortIndex < 0) {
console.debug(`Error initializing DynamoDatabase. KeySchema: ${JSON.stringify(keySchema)}`);
if (hashIndex < 0) {
throw Error(`Could not find PrimaryKey of Table '${tableName}'`);
} else {
throw Error(`Could not find SortKey of Table '${tableName}'`);
}
}
const primaryKey = keySchema[hashIndex].AttributeName;
const sortKey = keySchema[sortIndex].AttributeName;
// Make sure that the primary & sort key types are both string types
// (( We didn't make this flexible enough for other attribute types for the key ))
if ('S' !== attributes.find(item => item.AttributeName === primaryKey)?.AttributeType) {
throw Error(`Primary key '${primaryKey}' must be string type`);
}
if ('S' !== attributes.find(item => item.AttributeName === sortKey)?.AttributeType) {
throw Error(`Sort key '${sortKey}' must be string type`);
}
return new CompositeStringIndexTable(
client,
tableName,
primaryKey,
sortKey,
);
}
/**
* A simplified interface to create a new DynamoDB Table with a composite index
* consisting of a pair of string attributes.
* @param args
*/
public static async createNew(args: {
client: DynamoDB,
name: string,
primaryKeyName: string,
sortKeyName: string,
region?: string,
tags?: Array<{ Key: string, Value: string }>
}): Promise<CompositeStringIndexTable> {
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property
const request: DynamoDB.CreateTableInput = {
TableName: args.name,
AttributeDefinitions: [
{
AttributeName: args.primaryKeyName,
AttributeType: 'S',
},
{
AttributeName: args.sortKeyName,
AttributeType: 'S',
},
],
KeySchema: [
{
AttributeName: args.primaryKeyName,
KeyType: 'HASH',
},
{
AttributeName: args.sortKeyName,
KeyType: 'RANGE',
},
],
BillingMode: 'PAY_PER_REQUEST',
Tags: args.tags,
};
try {
await args.client.createTable(request).promise();
const table: CompositeStringIndexTable = new CompositeStringIndexTable(
args.client,
args.name,
args.primaryKeyName,
args.sortKeyName,
);
return table;
} catch (e) {
throw new Error(`CreateTable '${args.name}': ${e.code} -- ${e.message}`);
}
}
public readonly primaryKey: string;
public readonly sortKey: string;
protected readonly client: DynamoDB;
// tableName will only be undefined if the Table has been deleted.
protected tableName: string | undefined;
protected constructor(
client: DynamoDB,
name: string,
primaryKey: string,
sortKey: string,
) {
this.client = client;
this.tableName = name;
this.primaryKey = primaryKey;
this.sortKey = sortKey;
}
/**
* Delete this table from DynamoDB.
*/
public async deleteTable(): Promise<void> {
if (!this.tableName) {
return; // Already gone.
}
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#deleteTable-property
const request: DynamoDB.DeleteTableInput = {
TableName: this.tableName,
};
try {
await this.client.deleteTable(request).promise();
this.tableName = undefined;
} catch (e) {
if (e.code === 'ResourceNotFoundException') {
// Already gone. We're good.
this.tableName = undefined;
} else {
throw new Error(`DeleteTable '${this.tableName}': ${e.code} -- ${e.message}`);
}
}
}
/**
* Puts an item into the Table. The item it put into the table index with the given
* primary and sort key attribute values. If any attributes are given, then they are
* stored in the item.
*
* @param props
* @throws Error if the request fails.
* @returns True if the item was stored in the table; false otherwise
*/
public async putItem(props: {
primaryKeyValue: string,
sortKeyValue: string,
/**
* Additional attribute values to store in the table. This must
* not contain values for the primary & sort key attributes.
* Property key is the attribute name.
*/
attributes?: object,
/**
* If true, then allow dynamo to overwrite an existing value at the index
* if one exists.
* @default false
*/
allow_overwrite?: boolean,
}): Promise<boolean> {
if (!this.tableName) {
throw Error('Attempt to PutItem in deleted table');
}
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#putItem-property
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html
const item = DynamoDB.Converter.marshall(props.attributes ?? {});
item[this.primaryKey] = DynamoDB.Converter.input(props.primaryKeyValue);
item[this.sortKey] = DynamoDB.Converter.input(props.sortKeyValue);
const request: DynamoDB.PutItemInput = {
TableName: this.tableName,
Item: item,
ReturnConsumedCapacity: 'NONE',
ReturnItemCollectionMetrics: 'NONE',
ReturnValues: 'NONE',
};
if (!props.allow_overwrite) {
request.ConditionExpression = `attribute_not_exists(${this.primaryKey}) AND attribute_not_exists(${this.sortKey})`;
}
try {
console.debug(`Dynamo.PutItem request: ${JSON.stringify(request)}`);
const response = await this.client.putItem(request).promise();
console.debug(`PutItem response: ${JSON.stringify(response)}`);
} catch (e) {
if (e.code === 'ConditionalCheckFailedException' && !props.allow_overwrite) {
return false;
}
throw new Error(`PutItem '${props.primaryKeyValue}' '${props.sortKeyValue}:" ` +
`${e.code} -- ${e.message}`);
}
return true;
}
/**
* Does a consistent read to get the item from the Table with the given primary and sort key, if one exists.
*
* @param props
* @throws Error if the request fails.
* @returns The attributes of the item **excluding** the primary and sort key, or undefined if there was no item
* found.
*/
public async getItem(props: {
primaryKeyValue: string,
sortKeyValue: string,
}): Promise<{ [key: string]: any } | undefined> {
if (!this.tableName) {
throw Error('Attempt to GetItem from deleted table');
}
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#getItem-property
const key: { [key: string]: any } = {};
key[this.primaryKey] = props.primaryKeyValue;
key[this.sortKey] = props.sortKeyValue;
const request: DynamoDB.GetItemInput = {
TableName: this.tableName,
Key: DynamoDB.Converter.marshall(key),
ConsistentRead: true,
ReturnConsumedCapacity: 'NONE',
};
try {
console.debug(`Dynamo.GetItem request: ${JSON.stringify(request)}`);
const response: DynamoDB.GetItemOutput = await this.client.getItem(request).promise();
console.debug(`GetItem response: ${JSON.stringify(response)}`);
if (!response.Item) {
// The item was not present in the DB
return undefined;
}
const item = DynamoDB.Converter.unmarshall(response.Item);
delete item[this.primaryKey];
delete item[this.sortKey];
return item;
} catch (e) {
throw new Error(`GetItem '${props.primaryKeyValue}' '${props.sortKeyValue}:" ` +
`${e.code} -- ${e.message}`);
}
}
/**
* Deletes the item from the table that is indexed by the given primary and sort key value
* @param props
* @throws Error if the request fails
* @returns True if the item was deleted; false if there was no matching item to delete.
*/
public async deleteItem(props: {
primaryKeyValue: string,
sortKeyValue: string,
}): Promise<boolean> {
if (!this.tableName) {
throw Error('Attempt to DeleteItem from deleted table');
}
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#deleteItem-property
const key: { [key: string]: any } = {};
key[this.primaryKey] = props.primaryKeyValue;
key[this.sortKey] = props.sortKeyValue;
const request: DynamoDB.DeleteItemInput = {
TableName: this.tableName,
Key: DynamoDB.Converter.marshall(key),
ReturnValues: 'ALL_OLD',
ReturnConsumedCapacity: 'NONE',
ReturnItemCollectionMetrics: 'NONE',
};
try {
console.debug(`Dynamo.DeleteItem request: ${JSON.stringify(request)}`);
const response: DynamoDB.DeleteItemOutput = await this.client.deleteItem(request).promise();
console.debug(`DeleteItem response: ${JSON.stringify(response)}`);
if (response.Attributes) {
// There was a match in the DB, and we deleted it
return true;
}
return false;
} catch (e) {
throw new Error(`DeleteItem '${props.primaryKeyValue}' '${props.sortKeyValue}:" ` +
`${e.code} -- ${e.message}`);
}
}
/**
* Query the table for all items with the given primary key value.
* @param primaryKeyValue
* @param pageLimit Maximum number of table items to evaluate per request.
* @throws Error if the request fails.
* @returns All of the found items, keyed by their unique sort key values. i.e.
* {
* 'sort key value 1': {
* # attributes other than sort & primary key for this item
* },
* 'sort key value 2': {
* # attributes other than sort & primary key for this item
* },
* ... etc
* }
*/
public async query(
primaryKeyValue: string,
pageLimit?: number,
): Promise<{ [key: string]: { [key: string]: any }}> {
if (!this.tableName) {
throw Error('Attempt to Query a deleted table');
}
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property
const request: DynamoDB.QueryInput = {
TableName: this.tableName,
Select: 'ALL_ATTRIBUTES',
ConsistentRead: true,
ReturnConsumedCapacity: 'NONE',
ExpressionAttributeNames: {
'#PK': this.primaryKey,
},
ExpressionAttributeValues: {
':PKV': DynamoDB.Converter.input(primaryKeyValue),
},
KeyConditionExpression: '#PK = :PKV',
Limit: pageLimit,
};
console.debug(`DynamoDB.Query: ${JSON.stringify(request)}`);
const items: { [key: string]: { [key: string]: any }} = {};
try {
do {
const response: DynamoDB.QueryOutput = await this.client.query(request).promise();
request.ExclusiveStartKey = response.LastEvaluatedKey;
if (response.Items) {
for (const item of response.Items) {
const unmarshalled = DynamoDB.Converter.unmarshall(item);
const sortValue: string = unmarshalled[this.sortKey];
delete unmarshalled[this.primaryKey];
delete unmarshalled[this.sortKey];
items[sortValue] = unmarshalled;
}
}
} while (request.ExclusiveStartKey);
return items;
} catch (e) {
throw new Error(`Query '${primaryKeyValue}':" ${e.code} -- ${e.message}`);
}
}
} | the_stack |
* @module CartesianGeometry
*/
import { Geometry, PlaneAltitudeEvaluator } from "../Geometry";
import { Matrix4d } from "../geometry4d/Matrix4d";
import { Point4d } from "../geometry4d/Point4d";
import { XYParitySearchContext } from "../topology/XYParitySearchContext";
import { GrowableXYZArray } from "./GrowableXYZArray";
import { IndexedReadWriteXYZCollection, IndexedXYZCollection } from "./IndexedXYZCollection";
import { Point2d, Vector2d } from "./Point2dVector2d";
import { Point3dArrayCarrier } from "./Point3dArrayCarrier";
import { Point3d, Vector3d } from "./Point3dVector3d";
import { Range1d, Range3d } from "./Range";
import { Ray3d } from "./Ray3d";
import { SortablePolygon } from "./SortablePolygon";
import { XAndY } from "./XYZProps";
/**
* Carrier for a loop extracted from clip operation, annotated for sorting
* @internal
*/
export class CutLoop {
/* All points of the loop */
public xyz: GrowableXYZArray;
/* ray within point of "on" edge */
public edge?: Ray3d;
public sortCoordinate0: number;
public sortCoordinate1: number;
public sortDelta: number;
public isNotch: boolean;
public constructor(xyz: GrowableXYZArray) {
this.xyz = xyz;
this.edge = undefined;
this.sortCoordinate0 = this.sortCoordinate1 = 0;
this.sortDelta = 0;
this.isNotch = false;
}
/**
* Create a `CutLoop` structure annotated with the vector from last point to first.
* @param xyz coordinates to capture
*/
public static createCaptureWithReturnEdge(xyz: GrowableXYZArray): CutLoop {
const result = new CutLoop(xyz);
if (xyz.length >= 2)
result.edge = Ray3d.createStartEnd(xyz.front()!, xyz.back()!);
return result;
}
/**
* Set up coordinates for sort steps:
* * Make `sortCoordinate0` and `sortCoordinate` the (algebraically sorted) start and end fractions along the ray
* * Make `sortDelta` the oriented difference of those two
* * Hence sorting on the coordinates puts loops in left-to-right order by the their edge vector leftmost point.
*/
public setSortCoordinates(ray: Ray3d) {
this.sortDelta = this.edge!.direction.dotProduct(ray.direction);
const a = ray.dotProductToPoint(this.edge!.origin);
if (this.sortDelta >= 0) {
this.sortCoordinate0 = a;
this.sortCoordinate1 = a + this.sortDelta;
} else {
this.sortCoordinate0 = a + this.sortDelta; // and sortDelta is negative !!!
this.sortCoordinate1 = a;
}
}
/** Return
* * 0 if other sort limits are not strictly contained in this.
* * 1 if other sort limits are strictly contained with same direction
* * -1 if other sort limits are strictly contained in opposite direction.
*/
public containsSortLimits(other: CutLoop): number {
if (other.sortCoordinate0 >= this.sortCoordinate1
|| other.sortCoordinate0 <= this.sortCoordinate0
|| other.sortCoordinate1 <= this.sortCoordinate0
|| other.sortCoordinate1 >= this.sortCoordinate1)
return 0;
return this.sortDelta * other.sortDelta > 0 ? 1 : -1;
}
/**
* * push coordinates from other onto this
* * reset this.sortCoordinate0 to other.sortCoordinate1
* @param other new coordinates
*/
public absorb(other: CutLoop) {
this.xyz.pushFromGrowableXYZArray(other.xyz);
this.sortCoordinate0 = other.sortCoordinate1;
}
/** Comparison function for system sort function applied to an array of CutLoop .... */
public static sortFunction(loopA: CutLoop, loopB: CutLoop): number {
const q = loopA.sortCoordinate0 - loopB.sortCoordinate0;
return q > 0 ? 1 : -1;
}
/** Return first point coordinates.
* * For type checking, assume array is not empty.
*/
public front(result?: Point3d): Point3d { return this.xyz.front(result)!; }
/** Return last point coordinates.
* * For type checking, assume array is not empty.
*/
public back(result?: Point3d): Point3d { return this.xyz.back(result)!; }
}
/**
* Context to hold an array of input loops and apply sort logic.
* * This is used when a non-convex face is clipped by a plane
* * Simple convex clip logic in this case generates double-back edges that need to be eliminated.
* * This class manages the elimination.
* * Usage pattern is:
* @internal
*/
export class CutLoopMergeContext {
/** Array (filled by user code) of loops being sorted. Contents are subject to being changed during sort. */
public inputLoops: CutLoop[];
/** Array (filled by sortAndMergeLoops) of reorganized loops. */
public outputLoops: CutLoop[];
// Initialize with empty loop arrays.
public constructor() {
this.inputLoops = [];
this.outputLoops = [];
}
/**
* * Search all start and end points for the one most distant from point0.
*/
private mostDistantPoint(point0: Point3d, workPoint: Point3d, resultPoint: Point3d) {
let dMax = -1.0;
resultPoint.setZero();
let d;
for (const loop of this.inputLoops) {
loop.front(workPoint);
d = workPoint.distanceSquared(point0);
if (d > dMax) {
dMax = d;
resultPoint.setFromPoint3d(workPoint);
}
loop.back(workPoint);
d = workPoint.distanceSquared(point0);
if (d > dMax) {
dMax = d;
resultPoint.setFromPoint3d(workPoint);
}
}
}
/**
* * Find a long (probably longest) edge through start and end points of inputs.
* * Setup sortCoordinate0 and sortCoordinate1 along that edge for each loop
* * sort all inputLoop members by sortCoordinate0.
*/
private sortInputs() {
if (this.inputLoops.length > 0 && this.inputLoops[0].xyz.length > 0) {
const point0 = this.inputLoops[0].xyz.front()!;
const workPoint = Point3d.create();
const point1 = Point3d.create();
// point0 could be in the middle. Find the most distant point ...
this.mostDistantPoint(point0, workPoint, point1);
// And again from point1 to get to the other extreme . .
this.mostDistantPoint(point1, workPoint, point0);
const sortRay = Ray3d.createStartEnd(point0, point1);
sortRay.direction.normalizeInPlace();
for (const loop of this.inputLoops)
loop.setSortCoordinates(sortRay);
this.inputLoops.sort(CutLoop.sortFunction);
}
}
/**
* * sort all input loops by coordinate along the cut edge
* * sweep left to right, using start and end coordinates to decide if loops are outer or hole, and combine holes into their containing outer loops.
*/
public sortAndMergeLoops() {
this.sortInputs();
const inputs = this.inputLoops;
const outputs = this.outputLoops;
const stack = [];
outputs.length = 0;
for (const candidate of inputs) {
candidate.isNotch = false;
// candidate must be either (a) absorbed in to of stack or (b) pushed onto stack.
// If pushed, must have indication of natch state.
for (; stack.length > 0;) {
const topOfStack = stack[stack.length - 1];
const containment = topOfStack.containsSortLimits(candidate);
if (containment === 0) {
if (!topOfStack.isNotch)
outputs.push(topOfStack);
stack.pop();
continue; // a larger topOfStack may have appeared !
candidate.isNotch = false;
} else if (containment === 1) {
candidate.isNotch = false;
break;
} else {
topOfStack.absorb(candidate);
candidate.isNotch = true;
break;
}
}
stack.push(candidate);
}
// Anything on stack must be complete ...
for (const p of stack) {
if (!p.isNotch)
outputs.push(p);
}
}
}
/** Static class for operations that treat an array of points as a polygon (with area!) */
/**
* Various (static method) computations for arrays of points interpreted as a polygon.
* @public
*/
export class PolygonOps {
/** Sum areas of triangles from points[0] to each far edge.
* * Consider triangles from points[0] to each edge.
* * Sum the areas(absolute, without regard to orientation) all these triangles.
* @returns sum of absolute triangle areas.
*/
public static sumTriangleAreas(points: Point3d[] | GrowableXYZArray): number {
let s = 0;
const n = points.length;
if (Array.isArray(points)) {
if (n >= 3) {
const origin = points[0];
const vector0 = origin.vectorTo(points[1]);
let vector1 = Vector3d.create();
// This will work with or without closure edge. If closure is given, the last vector is 000.
for (let i = 2; i < n; i++) {
vector1 = origin.vectorTo(points[i], vector1);
s += vector0.crossProductMagnitude(vector1);
vector0.setFrom(vector1);
}
}
return s * 0.5;
}
const crossVector = Vector3d.create();
for (let i = 2; i < n; i++) {
points.crossProductIndexIndexIndex(0, i - 1, i, crossVector);
s += crossVector.magnitude();
}
return s * 0.5;
}
/** Sum areas of triangles from points[0] to each far edge.
* * Consider triangles from points[0] to each edge.
* * Sum the areas(absolute, without regard to orientation) all these triangles.
* @returns sum of absolute triangle areas.
*/
public static sumTriangleAreasXY(points: Point3d[]): number {
let s = 0.0;
const n = points.length;
if (n >= 3) {
const origin = points[0];
const vector0 = origin.vectorTo(points[1]);
let vector1 = Vector3d.create();
// This will work with or without closure edge. If closure is given, the last vector is 000.
for (let i = 2; i < n; i++) {
vector1 = origin.vectorTo(points[i], vector1);
s += vector0.crossProductXY(vector1);
vector0.setFrom(vector1);
}
}
s *= 0.5;
// console.log ("polygon area ", s, points);
return s;
}
/** These values are the integrated area moment products [xx,xy,xz, x]
* for a right triangle in the first quadrant at the origin -- (0,0),(1,0),(0,1)
*/
private static readonly _triangleMomentWeights = Matrix4d.createRowValues(2.0 / 24.0, 1.0 / 24.0, 0, 4.0 / 24.0, 1.0 / 24.0, 2.0 / 24.0, 0, 4.0 / 24.0, 0, 0, 0, 0, 4.0 / 24.0, 4.0 / 24.0, 0, 12.0 / 24.0);
/** These values are the integrated volume moment products [xx,xy,xz, x, yx,yy,yz,y, zx,zy,zz,z,x,y,z,1]
* for a tetrahedron in the first quadrant at the origin -- (0,00),(1,0,0),(0,1,0),(0,0,1)
*/
private static readonly _tetrahedralMomentWeights = Matrix4d.createRowValues(
1.0 / 60.0, 1.0 / 120, 1.0 / 120, 1.0 / 24.0,
1.0 / 120, 1.0 / 60.0, 1.0 / 120, 1.0 / 24.0,
1.0 / 120, 1.0 / 120, 1.0 / 60.0, 1.0 / 24.0,
1.0 / 24.0, 1.0 / 24.0, 1.0 / 24.0, 1.0 / 6.0);
// statics for shared reuse.
// many methods use these.
// only use them in "leaf" methods that are certain not to call other users . . .
private static _vector0 = Vector3d.create();
private static _vector1 = Vector3d.create();
private static _vector2 = Vector3d.create();
private static _vectorOrigin = Vector3d.create();
private static _normal = Vector3d.create();
private static _matrixA = Matrix4d.createIdentity();
private static _matrixB = Matrix4d.createIdentity();
private static _matrixC = Matrix4d.createIdentity();
/** return a vector which is perpendicular to the polygon and has magnitude equal to the polygon area. */
public static areaNormalGo(points: IndexedXYZCollection, result?: Vector3d): Vector3d | undefined {
if (!result)
result = new Vector3d();
const n = points.length;
if (n === 3) {
points.crossProductIndexIndexIndex(0, 1, 2, result);
} else if (n >= 3) {
result.setZero();
// This will work with or without closure edge. If closure is given, the last vector is 000.
for (let i = 2; i < n; i++) {
points.accumulateCrossProductIndexIndexIndex(0, i - 1, i, result);
}
}
// ALL BRANCHES SUM FULL CROSS PRODUCTS AND EXPECT SCALE HERE
result.scaleInPlace(0.5);
return result;
}
/** return a vector which is perpendicular to the polygon and has magnitude equal to the polygon area. */
public static areaNormal(points: Point3d[], result?: Vector3d): Vector3d {
if (!result)
result = Vector3d.create();
PolygonOps.areaNormalGo(new Point3dArrayCarrier(points), result);
return result;
}
/** return the area of the polygon.
* * This assumes the polygon is planar
* * This does NOT assume the polygon is on the xy plane.
*/
public static area(points: Point3d[]): number {
return PolygonOps.areaNormal(points).magnitude();
}
/** return the projected XY area of the polygon. */
public static areaXY(points: Point3d[] | IndexedXYZCollection): number {
let area = 0.0;
if (points instanceof IndexedXYZCollection) {
if (points.length > 2) {
const x0 = points.getXAtUncheckedPointIndex(0);
const y0 = points.getYAtUncheckedPointIndex(0);
let u1 = points.getXAtUncheckedPointIndex(1) - x0;
let v1 = points.getYAtUncheckedPointIndex(1) - y0;
let u2, v2;
for (let i = 1; i + 1 < points.length; i++, u1 = u2, v1 = v2) {
u2 = points.getXAtUncheckedPointIndex(i) - x0;
v2 = points.getYAtUncheckedPointIndex(i) - y0;
area += Geometry.crossProductXYXY(u1, v1, u2, v2);
}
}
} else {
for (let i = 1; i + 1 < points.length; i++)
area += points[0].crossProductToPointsXY(points[i], points[i + 1]);
}
return 0.5 * area;
}
/** Sum the areaXY () values for multiple polygons */
public static sumAreaXY(polygons: Point3d[][]): number{
let s = 0.0;
for (const p of polygons)
s += this.areaXY(p);
return s;
}
/**
* Return a Ray3d with (assuming the polygon is planar and not self-intersecting)
* * origin at the centroid of the (3D) polygon
* * normal is a unit vector perpendicular to the plane
* * 'a' member is the area.
* @param points
*/
public static centroidAreaNormal(points: IndexedXYZCollection | Point3d[]): Ray3d | undefined {
if (Array.isArray(points)) {
const carrier = new Point3dArrayCarrier(points);
return this.centroidAreaNormal(carrier);
}
const n = points.length;
if (n === 3) {
const normal = points.crossProductIndexIndexIndex(0, 1, 2)!;
const a = 0.5 * normal.magnitude();
const centroid = points.getPoint3dAtCheckedPointIndex(0)!;
points.accumulateScaledXYZ(1, 1.0, centroid);
points.accumulateScaledXYZ(2, 1.0, centroid);
centroid.scaleInPlace(1.0 / 3.0);
const result = Ray3d.createCapture(centroid, normal);
if (result.tryNormalizeInPlaceWithAreaWeight(a))
return result;
return undefined;
}
if (n >= 3) {
const areaNormal = Vector3d.createZero();
// This will work with or without closure edge. If closure is given, the last vector is 000.
for (let i = 2; i < n; i++) {
points.accumulateCrossProductIndexIndexIndex(0, i - 1, i, areaNormal);
}
areaNormal.normalizeInPlace();
const origin = points.getPoint3dAtCheckedPointIndex(0)!;
const vector0 = Vector3d.create();
const vector1 = Vector3d.create();
points.vectorXYAndZIndex(origin, 1, vector0);
let cross = Vector3d.create();
const centroidSum = Vector3d.createZero();
const normalSum = Vector3d.createZero();
let signedTriangleArea;
// This will work with or without closure edge. If closure is given, the last vector is 000.
for (let i = 2; i < n; i++) {
points.vectorXYAndZIndex(origin, i, vector1);
cross = vector0.crossProduct(vector1, cross);
signedTriangleArea = areaNormal.dotProduct(cross); // well, actually twice the area.
normalSum.addInPlace(cross); // this grows to twice the area
const b = signedTriangleArea / 6.0;
centroidSum.plus2Scaled(vector0, b, vector1, b, centroidSum);
vector0.setFrom(vector1);
}
const area = 0.5 * normalSum.magnitude();
const inverseArea = Geometry.conditionalDivideFraction(1, area);
if (inverseArea !== undefined) {
const result = Ray3d.createCapture(origin.plusScaled(centroidSum, inverseArea), normalSum);
result.tryNormalizeInPlaceWithAreaWeight(area);
return result;
}
}
return undefined;
}
// Has the potential to be combined with centroidAreaNormal for point3d array and Ray3d return listed above...
// Returns undefined if given point array less than 3 or if not safe to divide at any point
/**
* * Return (in caller-allocated centroid) the centroid of the xy polygon.
* * Return (as function value) the area
*/
public static centroidAndAreaXY(points: Point2d[], centroid: Point2d): number | undefined {
let area = 0.0;
centroid.set(0, 0);
if (points.length < 3)
return undefined;
const origin = points[0];
let vectorSum = Vector2d.create(0, 0); // == sum ((U+V)/3) * (U CROSS V)/2 -- but leave out divisions
let areaSum = 0.0; // == sum (U CROSS V) / 2 -- but leave out divisions
for (let i = 1; i + 1 < points.length; i++) {
const vector0 = origin.vectorTo(points[i]);
const vector1 = origin.vectorTo(points[i + 1]);
const tempArea = vector0.crossProduct(vector1);
vectorSum = vectorSum.plus(vector0.plus(vector1).scale(tempArea));
areaSum += tempArea;
}
area = areaSum * 0.5;
const a = Geometry.conditionalDivideFraction(1.0, 6.0 * area);
if (a === undefined) {
centroid.setFrom(origin);
return undefined;
}
centroid.setFrom(origin.plusScaled(vectorSum, a));
return area;
}
/**
* Return a unit normal to the plane of the polygon.
* @param points array of points around the polygon. This is assumed to NOT have closure edge.
* @param result caller-allocated result vector.
*/
public static unitNormal(points: IndexedXYZCollection, result: Vector3d): boolean {
const n = points.length;
if (n === 3) {
points.crossProductIndexIndexIndex(0, 1, 2, result);
return result.normalizeInPlace();
}
if (n === 4) {
// cross product of diagonals is more stable than from single of the points . . .
points.vectorIndexIndex(0, 2, PolygonOps._vector0);
points.vectorIndexIndex(1, 3, PolygonOps._vector1);
PolygonOps._vector0.crossProduct(PolygonOps._vector1, result);
return result.normalizeInPlace();
}
// more than 4 points ... no shortcuts ...
PolygonOps.areaNormalGo(points, result);
return result.normalizeInPlace();
}
/** Accumulate to the matrix of area products of a polygon with respect to an origin.
* The polygon is assumed to be planar and non-self-intersecting.
*/
/** Accumulate to the matrix of area products of a polygon with respect to an origin.
* * The polygon is assumed to be planar and non-self-intersecting.
* * Accumulated values are integrals over triangles from point 0 of the polygon to other edges of the polygon.
* * Integral over each triangle is transformed to integrals from the given origin.
* @param points array of points around the polygon. Final closure point is not needed.
* @param origin origin for global accumulation.
* @param moments 4x4 matrix where products are accumulated.
*/
public static addSecondMomentAreaProducts(points: IndexedXYZCollection, origin: Point3d, moments: Matrix4d) {
this.addSecondMomentTransformedProducts(PolygonOps._triangleMomentWeights, points, origin, 2, moments);
}
/** Accumulate to the matrix of volume products of a polygon with respect to an origin.
* * The polygon is assumed to be planar and non-self-intersecting.
* * Accumulated values are integrals over tetrahedra from the origin to triangles on the polygon.
* @param points array of points around the polygon. Final closure point is not needed.
* @param origin origin for tetrahedra
* @param moments 4x4 matrix where products are accumulated.
*/
public static addSecondMomentVolumeProducts(points: IndexedXYZCollection, origin: Point3d, moments: Matrix4d) {
this.addSecondMomentTransformedProducts(PolygonOps._tetrahedralMomentWeights, points, origin, 3, moments);
}
/** Return the matrix of area products of a polygon with respect to an origin.
* The polygon is assumed to be planar and non-self-intersecting.
* * `frameType===2` has xy vectors in the plane of the polygon, plus a unit normal z. (Used for area integrals)
* * `frameType===3` has vectors from origin to 3 points in the triangle. (Used for volume integrals)
*/
private static addSecondMomentTransformedProducts(firstQuadrantMoments: Matrix4d, points: IndexedXYZCollection, origin: Point3d,
frameType: 2 | 3,
moments: Matrix4d) {
const unitNormal = PolygonOps._normal;
if (PolygonOps.unitNormal(points, unitNormal)) {
// The direction of the normal makes the various detJ values positive or negative so that non-convex polygons
// sum correctly.
const vector01 = PolygonOps._vector0;
const vector02 = PolygonOps._vector1;
const vector03 = PolygonOps._vector2;
const placement = PolygonOps._matrixA;
const matrixAB = PolygonOps._matrixB;
const matrixABC = PolygonOps._matrixC;
const vectorOrigin = points.vectorXYAndZIndex(origin, 0, PolygonOps._vectorOrigin)!;
const numPoints = points.length;
let detJ = 0;
for (let i2 = 2; i2 < numPoints; i2++) {
if (frameType === 2) {
points.vectorIndexIndex(0, i2 - 1, vector01);
points.vectorIndexIndex(0, i2, vector02);
detJ = unitNormal.tripleProduct(vector01, vector02);
placement.setOriginAndVectors(vectorOrigin, vector01, vector02, unitNormal);
placement.multiplyMatrixMatrix(firstQuadrantMoments, matrixAB);
matrixAB.multiplyMatrixMatrixTranspose(placement, matrixABC);
moments.addScaledInPlace(matrixABC, detJ);
} else if (frameType === 3) {
points.vectorXYAndZIndex(origin, 0, vector01);
points.vectorXYAndZIndex(origin, i2 - 1, vector02);
points.vectorXYAndZIndex(origin, i2, vector03);
detJ = vector01.tripleProduct(vector02, vector03);
placement.setOriginAndVectors(origin, vector01, vector02, vector03);
placement.multiplyMatrixMatrix(firstQuadrantMoments, matrixAB);
matrixAB.multiplyMatrixMatrixTranspose(placement, matrixABC);
moments.addScaledInPlace(matrixABC, detJ);
}
}
}
}
/** Test the direction of turn at the vertices of the polygon, ignoring z-coordinates.
*
* * For a polygon without self intersections, this is a convexity and orientation test: all positive is convex and counterclockwise,
* all negative is convex and clockwise
* * Beware that a polygon which turns through more than a full turn can cross itself and close, but is not convex
* * Returns 1 if all turns are to the left, -1 if all to the right, and 0 if there are any zero or reverse turns
*/
public static testXYPolygonTurningDirections(pPointArray: Point2d[] | Point3d[]): number {
// Reduce count by trailing duplicates; leaves iLast at final index
let numPoint = pPointArray.length;
let iLast = numPoint - 1;
while (iLast > 1 && pPointArray[iLast].x === pPointArray[0].x && pPointArray[iLast].y === pPointArray[0].y) {
numPoint = iLast--;
}
if (numPoint > 2) {
let vector0 = Point2d.create(pPointArray[iLast].x - pPointArray[iLast - 1].x, pPointArray[iLast].y - pPointArray[iLast - 1].y);
const vector1 = Point2d.create(pPointArray[0].x - pPointArray[iLast].x, pPointArray[0].y - pPointArray[iLast].y);
const baseArea = vector0.x * vector1.y - vector0.y * vector1.x;
// In a convex polygon, all successive-vector cross products will
// have the same sign as the base area, hence all products will be
// positive.
for (let i1 = 1; i1 < numPoint; i1++) {
vector0 = vector1.clone();
Point2d.create(pPointArray[i1].x - pPointArray[i1 - 1].x, pPointArray[i1].y - pPointArray[i1 - 1].y, vector1);
const currArea = vector0.x * vector1.y - vector0.y * vector1.x;
if (currArea * baseArea <= 0.0)
return 0;
}
// Fall out with all signs same as base area
return baseArea > 0.0 ? 1 : -1;
}
return 0;
}
/**
* Test if point (x,y) is IN, OUT or ON a polygon.
* @return (1) for in, (-1) for OUT, (0) for ON
* @param x x coordinate
* @param y y coordinate
* @param points array of xy coordinates.
*/
public static classifyPointInPolygon(x: number, y: number, points: XAndY[]): number | undefined {
const context = new XYParitySearchContext(x, y);
let i0 = 0;
const n = points.length;
let i1;
let iLast = -1;
// walk to an acceptable start index ...
for (i0 = 0; i0 < n; i0++) {
i1 = i0 + 1;
if (i1 >= n)
i1 = 0;
if (context.tryStartEdge(points[i0].x, points[i0].y, points[i1].x, points[i1].y)) {
iLast = i1;
break;
}
}
if (iLast < 0)
return undefined;
for (let i = 1; i <= n; i++) {
i1 = iLast + i;
if (i1 >= n)
i1 -= n;
if (!context.advance(points[i1].x, points[i1].y))
return context.classifyCounts();
}
return context.classifyCounts();
}
/**
* Test if point (x,y) is IN, OUT or ON a polygon.
* @return (1) for in, (-1) for OUT, (0) for ON
* @param x x coordinate
* @param y y coordinate
* @param points array of xy coordinates.
*/
public static classifyPointInPolygonXY(x: number, y: number, points: IndexedXYZCollection): number | undefined {
const context = new XYParitySearchContext(x, y);
let i0 = 0;
const n = points.length;
let i1;
let iLast = -1;
// walk to an acceptable start index ...
for (i0 = 0; i0 < n; i0++) {
i1 = i0 + 1;
if (i1 >= n)
i1 = 0;
if (context.tryStartEdge(points.getXAtUncheckedPointIndex(i0), points.getYAtUncheckedPointIndex(i0), points.getXAtUncheckedPointIndex(i1), points.getYAtUncheckedPointIndex(i1))) {
iLast = i1;
break;
}
}
if (iLast < 0)
return undefined;
for (let i = 1; i <= n; i++) {
i1 = iLast + i;
if (i1 >= n)
i1 -= n;
if (!context.advance(points.getXAtUncheckedPointIndex(i1), points.getYAtUncheckedPointIndex(i1)))
return context.classifyCounts();
}
return context.classifyCounts();
}
/**
* Reverse loops as necessary to make them all have CCW orientation for given outward normal.
* @param loops
* @param outwardNormal
* @return the number of loops reversed.
*/
public static orientLoopsCCWForOutwardNormalInPlace(loops: IndexedReadWriteXYZCollection | IndexedReadWriteXYZCollection[], outwardNormal: Vector3d): number {
if (loops instanceof IndexedXYZCollection)
return this.orientLoopsCCWForOutwardNormalInPlace([loops], outwardNormal);
const orientations: number[] = [];
const unitNormal = Vector3d.create();
// orient individually ... (no hole analysis)
let numReverse = 0;
for (const loop of loops) {
if (this.unitNormal(loop, unitNormal)) {
const q = unitNormal.dotProduct(outwardNormal);
orientations.push(q);
if (q <= 0.0)
loop.reverseInPlace();
numReverse++;
} else {
orientations.push(0.0);
}
}
return numReverse;
}
/**
* If reverse loops as necessary to make them all have CCW orientation for given outward normal.
* * Return an array of arrays which capture the input pointers.
* * In each first level array:
* * The first loop is an outer loop.
* * all subsequent loops are holes
* * The outer loop is CCW
* * The holes are CW.
* * Call RegionOps.sortOuterAndHoleLoopsXY to have the result returned as a UnionRegion
* @param loops multiple loops to sort and reverse.
*/
public static sortOuterAndHoleLoopsXY(loops: IndexedReadWriteXYZCollection[]): IndexedReadWriteXYZCollection[][] {
const loopAndArea: SortablePolygon[] = [];
for (const loop of loops) {
SortablePolygon.pushPolygon(loopAndArea, loop);
}
return SortablePolygon.sortAsArrayOfArrayOfPolygons(loopAndArea);
}
}
/**
* `IndexedXYZCollectionPolygonOps` class contains _static_ methods for typical operations on polygons carried as `IndexedXyZCollection`
* @public
*/
export class IndexedXYZCollectionPolygonOps {
private static _xyz0Work: Point3d = Point3d.create();
private static _xyz1Work: Point3d = Point3d.create();
private static _xyz2Work: Point3d = Point3d.create();
/**
* Split a (convex) polygon into 2 parts based on altitude evaluations.
* * POSITIVE ALTITUDE IS IN
* @param plane any `PlaneAltitudeEvaluator` object that can evaluate `plane.altitude(xyz)` for distance from the plane.
* @param xyz original polygon
* @param xyzPositive array to receive inside part (altitude > 0)
* @param xyzNegative array to receive outside part
* @param altitudeRange min and max altitudes encountered.
*/
public static splitConvexPolygonInsideOutsidePlane(plane: PlaneAltitudeEvaluator,
xyz: IndexedReadWriteXYZCollection,
xyzPositive: IndexedReadWriteXYZCollection,
xyzNegative: IndexedReadWriteXYZCollection, altitudeRange: Range1d) {
const xyz0 = IndexedXYZCollectionPolygonOps._xyz0Work;
const xyz1 = IndexedXYZCollectionPolygonOps._xyz1Work;
const xyzInterpolated = IndexedXYZCollectionPolygonOps._xyz2Work;
const n = xyz.length;
xyzPositive.clear();
xyzNegative.clear();
// let numSplit = 0;
const fractionTol = 1.0e-8;
if (n > 2) {
xyz.back(xyz0);
altitudeRange.setNull();
let a0 = plane.altitude(xyz0);
altitudeRange.extendX(a0);
// if (a0 >= 0.0)
// work.push_back (xyz0);
for (let i1 = 0; i1 < n; i1++) {
xyz.getPoint3dAtUncheckedPointIndex(i1, xyz1);
const a1 = plane.altitude(xyz1);
altitudeRange.extendX(a1);
let nearZero = false;
if (a0 * a1 < 0.0) {
// simple crossing. . .
const f = - a0 / (a1 - a0);
if (f > 1.0 - fractionTol && a1 >= 0.0) {
// the endpoint will be saved -- avoid the duplicate
nearZero = true;
} else {
xyz0.interpolate(f, xyz1, xyzInterpolated);
xyzPositive.push(xyzInterpolated);
xyzNegative.push(xyzInterpolated);
}
// numSplit++;
}
if (a1 >= 0.0 || nearZero)
xyzPositive.push(xyz1);
if (a1 <= 0.0 || nearZero)
xyzNegative.push(xyz1);
xyz0.setFromPoint3d(xyz1);
a0 = a1;
}
}
}
/**
* Clip a polygon to one side of a plane.
* * Results with 2 or fewer points are ignored.
* * Other than ensuring capacity in the arrays, there are no object allocations during execution of this function.
* * plane is passed as unrolled Point4d (ax,ay,az,aw) point (x,y,z) acts as homogeneous (x,y,z,1)
* * `keepPositive === true` selects positive altitudes.
* @param plane any type that has `plane.altitude`
* @param xyz input points.
* @param work work buffer
* @param tolerance tolerance for "on plane" decision.
* @return the number of crossings. If this is larger than 2, the result is "correct" in a parity sense but may have overlapping (hence cancelling) parts.
*/
public static clipConvexPolygonInPlace(plane: PlaneAltitudeEvaluator, xyz: GrowableXYZArray, work: GrowableXYZArray, keepPositive: boolean = true, tolerance: number = Geometry.smallMetricDistance): number {
work.clear();
const s = keepPositive ? 1.0 : -1.0;
const n = xyz.length;
let numNegative = 0;
const fractionTol = 1.0e-8;
const b = -tolerance;
let numCrossings = 0;
if (xyz.length > 1) {
let a1;
let index0 = xyz.length - 1;
let a0 = s * xyz.evaluateUncheckedIndexPlaneAltitude(index0, plane);
if (Math.abs(a0) < tolerance)
a0 = 0;
// if (a0 >= 0.0)
// work.push_back (xyz0);
for (let index1 = 0; index1 < n; a0 = a1, index0 = index1++) {
a1 = s * xyz.evaluateUncheckedIndexPlaneAltitude(index1, plane);
if (Math.abs(a1) < tolerance)
a1 = 0;
if (a1 < 0)
numNegative++;
if (a0 * a1 < 0.0) {
// simple crossing . . .
const f = - a0 / (a1 - a0);
if (f > 1.0 - fractionTol && a1 >= 0.0) {
// the endpoint will be saved -- avoid the duplicate
} else {
work.pushInterpolatedFromGrowableXYZArray(xyz, index0, f, index1);
if (a1 > 0)
numCrossings++; // "out to in"
}
}
if (a1 >= b) {
work.pushFromGrowableXYZArray(xyz, index1);
if (a0 < -b) {
numCrossings++; // "in to out"
}
}
index0 = index1;
a0 = a1;
}
}
if (work.length <= 2) {
xyz.clear();
} else if (numNegative > 0) {
xyz.clear();
xyz.pushFromGrowableXYZArray(work);
}
work.clear();
return numCrossings;
}
/**
* * Input a "clipped" polygon (from clipConvexPolygonInPlace) with more than 2 crossings, i.e. is from a non-convex polygon with configurations like:
* * multiple distinct polygons
* * single polygon, but cut lines overlap and cancel by parity rules.
* * return 1 or more polygons, each having first and last points "on" the plane and intermediate points "off"
* * `minChainLength` indicates the shortest chain to be returned.
* @internal
*/
public static gatherCutLoopsFromPlaneClip(plane: PlaneAltitudeEvaluator, xyz: GrowableXYZArray, minChainLength: number = 3, tolerance: number = Geometry.smallMetricDistance): CutLoopMergeContext {
const result: CutLoopMergeContext = new CutLoopMergeContext();
// find the first on-plane point
let firstOnPlaneIndex = 0;
const n = xyz.length;
for (; firstOnPlaneIndex < n; firstOnPlaneIndex++) {
const a = xyz.evaluateUncheckedIndexPlaneAltitude(firstOnPlaneIndex, plane);
if (Math.abs(a) <= tolerance)
break;
}
if (firstOnPlaneIndex === n)
return result;
// find contiguous blocks of "off plane" points with on-plane points at their end.
let candidateA = firstOnPlaneIndex;
while (candidateA < n) {
const currentChain = new GrowableXYZArray();
currentChain.pushFromGrowableXYZArray(xyz, candidateA);
let candidateB = candidateA + 1;
while (candidateB < n) {
currentChain.pushFromGrowableXYZArray(xyz, candidateB);
const a = xyz.evaluateUncheckedIndexPlaneAltitude(candidateB, plane);
if (Math.abs(a) <= tolerance) {
break;
}
candidateB++;
}
if (candidateB === n)
for (let i = 0; i <= firstOnPlaneIndex; i++)
currentChain.pushFromGrowableXYZArray(xyz, i);
if (currentChain.length >= minChainLength)
result.inputLoops.push(CutLoop.createCaptureWithReturnEdge(currentChain));
candidateA = candidateB;
}
return result;
}
/**
* * Input the loops from `gatherCutLoopsFromClipPlane`
* * Consolidate loops for reentrant configurations.
* * WARNING: The output reuses and modifies input loops whenever possible.
* @internal
*/
public static reorderCutLoops(loops: CutLoopMergeContext) {
// Simple case: all loops have common orientation
if (loops.inputLoops.length === 1)
return;
// Simple cases: 2 loops . . .
if (loops.inputLoops.length === 2) {
// if edges are in the same direction, it must be a pair of unrelated loop . . .
if (loops.inputLoops[0].edge!.direction.dotProduct(loops.inputLoops[1].edge!.direction) > 0) {
loops.outputLoops.push(loops.inputLoops[0]);
loops.outputLoops.push(loops.inputLoops[1]);
return;
}
// twist the two loops into 1,
const source = loops.inputLoops[1].xyz;
const dest = loops.inputLoops[0].xyz;
dest.pushFromGrowableXYZArray(source);
loops.outputLoops.push(loops.inputLoops[0]);
return;
}
// 3 or more loops.
loops.sortAndMergeLoops();
//
}
/**
* Return the intersection of the plane with a range cube.
* @param range
* @param xyzOut intersection polygon. This is convex.
* @return reference to xyz if the polygon still has points; undefined if all points are clipped away.
*/
public static intersectRangeConvexPolygonInPlace(range: Range3d, xyz: GrowableXYZArray): GrowableXYZArray | undefined {
if (range.isNull)
return undefined;
const work = new GrowableXYZArray();
const plane = Point4d.create();
plane.set(0, 0, -1, range.high.z);
this.clipConvexPolygonInPlace(plane, xyz, work, true);
if (xyz.length === 0)
return undefined;
plane.set(0, 0, 1, -range.low.z);
this.clipConvexPolygonInPlace(plane, xyz, work, true);
if (xyz.length === 0)
return undefined;
plane.set(0, -1, 0, range.high.y);
this.clipConvexPolygonInPlace(plane, xyz, work, true);
if (xyz.length === 0)
return undefined;
plane.set(0, 1, 0, -range.low.y);
this.clipConvexPolygonInPlace(plane, xyz, work, true);
if (xyz.length === 0)
return undefined;
plane.set(-1, 0, 0, range.high.x);
this.clipConvexPolygonInPlace(plane, xyz, work, true);
if (xyz.length === 0)
return undefined;
plane.set(1, 0, 0, -range.low.x);
this.clipConvexPolygonInPlace(plane, xyz, work, true);
if (xyz.length === 0)
return undefined;
return xyz;
}
}
/**
* `Point3dArrayPolygonOps` class contains _static_ methods for typical operations on polygons carried as `Point3d[]`
* @public
*/
export class Point3dArrayPolygonOps {
private static _xyz0Work: Point3d = Point3d.create();
// private static _xyz1Work: Point3d = Point3d.create();
// private static _xyz2Work: Point3d = Point3d.create();
/**
* Split a (convex) polygon into 2 parts.
* @param xyz original polygon
* @param xyzIn array to receive inside part
* @param xyzOut array to receive outside part
* @param altitudeRange min and max altitudes encountered.
*/
public static convexPolygonSplitInsideOutsidePlane(plane: PlaneAltitudeEvaluator, xyz: Point3d[], xyzIn: Point3d[], xyzOut: Point3d[], altitudeRange: Range1d) {
const xyzCarrier = new Point3dArrayCarrier(xyz);
const xyzInCarrier = new Point3dArrayCarrier(xyzIn);
const xyzOutCarrier = new Point3dArrayCarrier(xyzOut);
IndexedXYZCollectionPolygonOps.splitConvexPolygonInsideOutsidePlane(plane, xyzCarrier, xyzInCarrier, xyzOutCarrier, altitudeRange);
}
/** Return an array containing
* * All points that are exactly on the plane.
* * Crossing points between adjacent points that are (strictly) on opposite sides.
*/
public static polygonPlaneCrossings(plane: PlaneAltitudeEvaluator, xyz: Point3d[], crossings: Point3d[]) {
crossings.length = 0;
if (xyz.length >= 2) {
const xyz0 = this._xyz0Work;
xyz0.setFromPoint3d(xyz[xyz.length - 1]);
let a0 = plane.altitude(xyz0);
for (const xyz1 of xyz) {
const a1 = plane.altitude(xyz1);
if (a0 * a1 < 0.0) {
// simple crossing. . .
const f = - a0 / (a1 - a0);
crossings.push(xyz0.interpolate(f, xyz1));
}
if (a1 === 0.0) { // IMPORTANT -- every point is directly tested here
crossings.push(xyz1.clone());
}
xyz0.setFromPoint3d(xyz1);
a0 = a1;
}
}
}
/**
* Clip a polygon, returning the clip result in the same object.
* @param xyz input/output polygon
* @param work scratch object
* @param tolerance tolerance for on-plane decision.
*/
public static convexPolygonClipInPlace(plane: PlaneAltitudeEvaluator, xyz: Point3d[], work: Point3d[] | undefined, tolerance: number = Geometry.smallMetricDistance) {
if (work === undefined)
work = [];
work.length = 0;
let numNegative = 0;
const fractionTol = 1.0e-8;
const b = -tolerance;
if (xyz.length > 2) {
let xyz0 = xyz[xyz.length - 1];
let a0 = plane.altitude(xyz0);
// if (a0 >= 0.0)
// work.push_back (xyz0);
for (const xyz1 of xyz) {
const a1 = plane.altitude(xyz1);
if (a1 < 0)
numNegative++;
if (a0 * a1 < 0.0) {
// simple crossing . . .
const f = - a0 / (a1 - a0);
if (f > 1.0 - fractionTol && a1 >= 0.0) {
// the endpoint will be saved -- avoid the duplicate
} else {
work.push(xyz0.interpolate(f, xyz1));
}
}
if (a1 >= b)
work.push(xyz1);
xyz0 = Point3d.createFrom(xyz1);
a0 = a1;
}
}
if (work.length <= 2) {
xyz.length = 0;
} else if (numNegative > 0) {
xyz.length = 0;
for (const xyzI of work) {
xyz.push(xyzI);
}
work.length = 0;
}
}
} | the_stack |
import * as vscode from 'vscode'
import * as _ from 'lodash'
import * as mime from 'mime-types'
import * as path from 'path'
import { AWSError, S3 } from 'aws-sdk'
import { inspect } from 'util'
import { ext } from '../extensionGlobals'
import { getLogger } from '../logger'
import { DefaultFileStreams, FileStreams, pipe, promisifyReadStream } from '../utilities/streamUtilities'
import { InterfaceNoSymbol } from '../utilities/tsUtils'
export const DEFAULT_MAX_KEYS = 300
export const DEFAULT_DELIMITER = '/'
export type Bucket = InterfaceNoSymbol<DefaultBucket>
export type Folder = InterfaceNoSymbol<DefaultFolder>
export type File = InterfaceNoSymbol<DefaultFile>
export type S3Client = InterfaceNoSymbol<DefaultS3Client>
interface S3Object {
readonly key: string
readonly versionId?: string
}
export interface ContinuationToken {
readonly keyMarker: string
readonly versionIdMarker?: string
}
export interface CreateBucketRequest {
readonly bucketName: string
}
export interface CreateBucketResponse {
readonly bucket: Bucket
}
export interface ListBucketsResponse {
readonly buckets: Bucket[]
}
export interface ListFilesRequest {
readonly bucketName: string
readonly folderPath?: string
readonly continuationToken?: string
readonly maxResults?: number // Defaults to DEFAULT_MAX_KEYS
}
export interface ListFilesResponse {
readonly files: File[]
readonly folders: Folder[]
readonly continuationToken?: string
}
export interface CreateFolderRequest {
readonly bucketName: string
readonly path: string
}
export interface CreateFolderResponse {
readonly folder: Folder
}
export interface DownloadFileRequest {
readonly bucketName: string
readonly key: string
readonly progressListener?: (loadedBytes: number) => void
readonly saveLocation: vscode.Uri
}
export interface SignedUrlRequest {
readonly bucketName: string
readonly key: string
readonly time: number
readonly operation?: string
readonly body?: string
}
export interface UploadFileRequest {
readonly bucketName: string
readonly key: string
readonly progressListener?: (loadedBytes: number) => void
readonly fileLocation: vscode.Uri
}
export interface ListObjectVersionsRequest {
readonly bucketName: string
readonly continuationToken?: ContinuationToken
readonly maxResults?: number // Defaults to DEFAULT_MAX_KEYS
}
export interface ListObjectVersionsResponse {
readonly objects: S3Object[]
readonly continuationToken?: ContinuationToken
}
export interface DeleteObjectRequest {
readonly bucketName: string
readonly key: string
}
export interface DeleteObjectsRequest {
readonly bucketName: string
readonly objects: { key: string; versionId?: string }[]
}
export interface DeleteObjectsResponse {
readonly errors: S3.Error[]
}
export interface DeleteBucketRequest {
readonly bucketName: string
}
const DEFAULT_CONTENT_TYPE = 'application/octet-stream'
export class DefaultS3Client {
public constructor(
private readonly partitionId: string,
private readonly regionCode: string,
private readonly s3Provider: (regionCode: string) => Promise<S3> = createSdkClient,
private readonly fileStreams: FileStreams = new DefaultFileStreams()
) {}
private async createS3(): Promise<S3> {
return this.s3Provider(this.regionCode)
}
/**
* Creates a bucket in the region of the client.
*
* @throws Error if there is an error calling S3.
*/
public async createBucket(request: CreateBucketRequest): Promise<CreateBucketResponse> {
getLogger().debug('CreateBucket called with request: %O', request)
const s3 = await this.createS3()
try {
await s3
.createBucket({
Bucket: request.bucketName,
// Passing us-east-1 for LocationConstraint breaks creating bucket. To make a bucket in us-east-1, you need to
// not pass a region, so check for this case.
CreateBucketConfiguration:
this.regionCode == 'us-east-1' ? undefined : { LocationConstraint: this.regionCode },
})
.promise()
} catch (e) {
getLogger().error('Failed to create bucket %s: %O', request.bucketName, e)
throw e
}
const response: CreateBucketResponse = {
bucket: new DefaultBucket({
partitionId: this.partitionId,
region: this.regionCode,
name: request.bucketName,
}),
}
getLogger().debug('CreateBucket returned response: %O', response)
return response
}
/**
* Empties and deletes a bucket.
*
* Note that this just repeatedly calls list and delete to empty the bucket before deletion.
* Failures during the emptying or deleting step can leave the bucket in a state where
* some (or all) objects are deleted, but the bucket remains.
*
* @throws Error if there is an error calling S3 to empty or delete the bucket.
*/
public async deleteBucket(request: DeleteBucketRequest): Promise<void> {
getLogger().debug('DeleteBucket called with request: %O', request)
const { bucketName } = request
const s3 = await this.createS3()
try {
await this.emptyBucket(bucketName)
} catch (e) {
getLogger().error('Failed to empty bucket %s before deleting: %O', bucketName, e)
throw e
}
try {
await s3.deleteBucket({ Bucket: bucketName }).promise()
} catch (e) {
getLogger().error('Failed to delete bucket %s: %O', bucketName, e)
throw e
}
getLogger().debug('DeleteBucket succeeded')
}
/**
* Creates a folder.
*
* The folder's bucket should reside in the same region as the one configured for the client.
*
* Note that folders don't actually exist in S3.
* Everything in S3 is an object with a key residing in a bucket.
* However, S3 allows you to emulate folders by providing a key with delimiters (slashes) in its name.
*
* To creating empty "folders", you upload an empty object with a trailing slash.
*
* Creation of folders isn't strictly necessary, as you can just upload keys with delimiters.
* However, empty folders make it easier to work with S3 as if it were a filesystem like in the UI.
*
* @throws Error if there is an error calling S3.
*/
public async createFolder(request: CreateFolderRequest): Promise<CreateFolderResponse> {
getLogger().debug('CreateFolder called with request: %O', request)
const s3 = await this.createS3()
const folder = new DefaultFolder({
path: request.path,
partitionId: this.partitionId,
bucketName: request.bucketName,
})
try {
await s3
.upload({
Bucket: request.bucketName,
Key: request.path,
Body: '',
})
.promise()
} catch (e) {
getLogger().error('Failed to create folder %s: %O', folder.name, e)
throw e
}
const response: CreateFolderResponse = { folder }
getLogger().debug('CreateFolder returned response: %O', response)
return response
}
/**
* Downloads a file to disk.
*
* The file's bucket should reside in the same region as the one configured for the client.
*
* Pipes the response (read) stream into the file (write) stream.
*
* @throws Error if there is an error calling S3 or piping between streams.
*/
public async downloadFile(request: DownloadFileRequest): Promise<void> {
getLogger().debug(
'DownloadFile called for bucketName: %s, key: %s, saveLocation: %s',
request.bucketName,
request.key,
request.saveLocation
)
const s3 = await this.createS3()
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/requests-using-stream-objects.html
const readStream = s3.getObject({ Bucket: request.bucketName, Key: request.key }).createReadStream()
const writeStream = this.fileStreams.createWriteStream(request.saveLocation)
try {
await pipe(readStream, writeStream, request.progressListener)
} catch (e) {
getLogger().error(`Failed to download %s from bucket %s: %O`, request.key, request.bucketName, e)
throw e
}
getLogger().debug('DownloadFile succeeded')
}
/**
* Generates a presigned URL for the given file in S3.
* Takes a valid time option, which must be in seconds. This is the time the URL will be valid for
*
* @returns the string of the link to the presigned URL
*/
public async getSignedUrl(request: SignedUrlRequest): Promise<string> {
const time = request.time
const operation = request.operation ? request.operation : 'getObject'
const s3 = await this.createS3()
const url = s3.getSignedUrl(operation, {
Bucket: request.bucketName,
Key: request.key,
Body: request.body,
Expires: time,
})
return url
}
/**
* Uploads a file from disk.
*
* The destination bucket should reside in the same region as the one configured for the client.
*
* Pipes the file (read) stream into the request (write) stream.
* Assigns the target content type based on the mime type of the file.
* If content type cannot be determined, defaults to {@link DEFAULT_CONTENT_TYPE}.
*
* @throws Error if there is an error calling S3 or piping between streams.
*/
public async uploadFile(request: UploadFileRequest): Promise<void> {
getLogger().debug(
'UploadFile called for bucketName: %s, key: %s, fileLocation: %s',
request.bucketName,
request.key,
request.fileLocation
)
const s3 = await this.createS3()
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-upload-file
const readStream = this.fileStreams.createReadStream(request.fileLocation)
const contentType = mime.lookup(path.basename(request.fileLocation.fsPath)) || DEFAULT_CONTENT_TYPE
const managedUploaded = s3.upload({
Bucket: request.bucketName,
Key: request.key,
Body: readStream,
ContentType: contentType,
})
const progressListener = request.progressListener
if (progressListener) {
managedUploaded.on('httpUploadProgress', progress => {
progressListener(progress.loaded)
})
}
try {
await Promise.all([promisifyReadStream(readStream), managedUploaded.promise()])
} catch (e) {
getLogger().error('Failed to upload %s to bucket %s: %O', request.key, request.bucketName, e)
throw e
}
getLogger().debug('UploadFile succeeded')
}
/**
* Lists all buckets owned by the client.
*
*
* @throws Error if there is an error calling S3.
*/
public async listAllBuckets(): Promise<S3.Bucket[]> {
const s3 = await this.createS3()
let s3Buckets: S3.Bucket[]
try {
const output = await s3.listBuckets().promise()
s3Buckets = output.Buckets ?? []
} catch (e) {
getLogger().error('Failed to list buckets: %O', e)
throw e
}
return s3Buckets
}
/**
* Lists buckets in the region of the client.
*
* Note that S3 returns all buckets in all regions,
* so this incurs the cost of additional S3#getBucketLocation requests for each bucket
* to filter out buckets residing outside of the client's region.
*
* @throws Error if there is an error calling S3.
*/
public async listBuckets(): Promise<ListBucketsResponse> {
getLogger().debug('ListBuckets called')
const s3 = await this.createS3()
const s3Buckets: S3.Bucket[] = await this.listAllBuckets()
// S3#ListBuckets returns buckets across all regions
const allBucketPromises: Promise<Bucket | undefined>[] = s3Buckets.map(async s3Bucket => {
const bucketName = s3Bucket.Name
if (!bucketName) {
return undefined
}
const region = await this.lookupRegion(bucketName, s3)
if (!region) {
return undefined
}
return new DefaultBucket({
partitionId: this.partitionId,
region: region,
name: bucketName,
})
})
const allBuckets = await Promise.all(allBucketPromises)
const bucketsInRegion = _(allBuckets)
.reject(bucket => bucket === undefined)
// we don't have a filerNotNull so we can filter then cast
.map(bucket => bucket as Bucket)
.reject(bucket => bucket.region !== this.regionCode)
.value()
const response: ListBucketsResponse = { buckets: bucketsInRegion }
getLogger().debug('ListBuckets returned response: %O', response)
return { buckets: bucketsInRegion }
}
/**
* Lists files and folders in a folder or inside the bucket root.
*
* The bucket should reside in the same region as the one configured for the client.
*
* Returns the first {@link ListFilesRequest#maxResults} objects (the first "page").
* If there are more results, returns a continuation token that can be passed in a subsequent call
* to get the next "page" of results.
*
* Note that folders don't actually exist in S3.
* Everything in S3 is an object with a key residing in a bucket.
* However, S3 lets you limit results to those residing at a specific "path" specified by delimiters (slashes).
* The list of sub-paths is returned in the result set and can be used in subsequent calls.
*
* A consequence of the fact that folders don't exist is that folders and files are intermingled across all
* of the pages.
* It's not possible to retrieve an exhaustive list of all folders without traversing all of the pages.
*
* @throws Error if there is an error calling S3.
*/
public async listFiles(request: ListFilesRequest): Promise<ListFilesResponse> {
getLogger().debug('ListFiles called with request: %O', request)
const s3 = await this.createS3()
let output: S3.ListObjectsV2Output
try {
output = await s3
.listObjectsV2({
Bucket: request.bucketName,
Delimiter: DEFAULT_DELIMITER,
MaxKeys: request.maxResults ?? DEFAULT_MAX_KEYS,
Prefix: request.folderPath,
ContinuationToken: request.continuationToken,
})
.promise()
} catch (e) {
getLogger().error('Failed to list files for bucket %s: %O', request.bucketName, e)
throw e
}
const files: File[] = _(output.Contents)
.reject(file => file.Key === request.folderPath)
.map(
file =>
new DefaultFile({
key: file.Key!,
partitionId: this.partitionId,
bucketName: request.bucketName,
lastModified: file.LastModified,
sizeBytes: file.Size,
})
)
.value()
const folders: Folder[] = _(output.CommonPrefixes)
.map(prefix => prefix.Prefix)
.compact()
.map(path => new DefaultFolder({ path, partitionId: this.partitionId, bucketName: request.bucketName }))
.value()
const response: ListFilesResponse = {
files,
folders,
continuationToken: output.NextContinuationToken,
}
getLogger().debug('ListFiles returned response: %O', response)
return response
}
/**
* Lists versions of all objects inside a bucket.
*
* The bucket should reside in the same region as the one configured for the client.
*
* Returns the first {@link ListObjectVersionsRequest#maxResults} versions (the first "page").
* If there are more results, returns a continuation token that can be passed in a subsequent call
* to get the next "page" of results.
*
* @throws Error if there is an error calling S3.
*/
public async listObjectVersions(request: ListObjectVersionsRequest): Promise<ListObjectVersionsResponse> {
getLogger().debug('ListObjectVersions called with request: %O', request)
const s3 = await this.createS3()
let output: S3.ListObjectVersionsOutput
try {
output = await s3
.listObjectVersions({
Bucket: request.bucketName,
MaxKeys: request.maxResults ?? DEFAULT_MAX_KEYS,
KeyMarker: request.continuationToken?.keyMarker,
VersionIdMarker: request.continuationToken?.versionIdMarker,
})
.promise()
} catch (e) {
getLogger().error('Failed to list object versions: %O', e)
throw e
}
const response: ListObjectVersionsResponse = {
objects: (output.Versions ?? []).map(version => ({
key: version.Key!,
versionId: version.VersionId,
})),
continuationToken: output.IsTruncated
? { keyMarker: output.NextKeyMarker!, versionIdMarker: output.NextVersionIdMarker }
: undefined,
}
getLogger().debug('ListObjectVersions returned response: %O', response)
return response
}
/**
* Returns an async iterable over all pages of {@link listObjectVersions}.
*
* @throws Error from the iterable if there is an error calling S3.
*/
public async *listObjectVersionsIterable(
request: ListObjectVersionsRequest
): AsyncIterableIterator<ListObjectVersionsResponse> {
let continuationToken: ContinuationToken | undefined = request.continuationToken
do {
const listObjectVersionsResponse: ListObjectVersionsResponse = await this.listObjectVersions({
bucketName: request.bucketName,
maxResults: request.maxResults,
continuationToken,
})
continuationToken = listObjectVersionsResponse.continuationToken
yield listObjectVersionsResponse
} while (continuationToken)
}
/**
* Deletes an object from a bucket.
*
* The bucket should reside in the same region as the one configured for the client.
*
* @throws Error if there is an error calling S3.
*/
public async deleteObject(request: DeleteObjectRequest): Promise<void> {
getLogger().debug('DeleteObject called with request: %O', request)
const s3 = await this.createS3()
try {
await s3
.deleteObject({
Bucket: request.bucketName,
Key: request.key,
})
.promise()
} catch (e) {
getLogger().error('Failed to delete object: %O', e)
throw e
}
getLogger().debug('DeleteObject succeeded')
}
/**
* Deletes objects from a bucket.
*
* The bucket should reside in the same region as the one configured for the client.
*
* Returns a list of Errors that occurred if the delete was only partially completed.
*
* @throws Error if there is an error calling S3, beyond the partial errors mentioned above.
*/
public async deleteObjects(request: DeleteObjectsRequest): Promise<DeleteObjectsResponse> {
getLogger().debug('DeleteObjects called with request: %O', request)
const s3 = await this.createS3()
let errors: S3.Error[]
try {
const output = await s3
.deleteObjects({
Bucket: request.bucketName,
Delete: {
Objects: request.objects.map(({ key: Key, versionId: VersionId }) => ({ Key, VersionId })),
Quiet: true,
},
})
.promise()
errors = output.Errors ?? []
} catch (e) {
getLogger().error('Failed to delete objects: %O', e)
throw e
}
const response: DeleteObjectsResponse = { errors }
getLogger().debug('DeleteObjects returned response: %O', response)
return response
}
/**
* Looks up the region for the given bucket
*
* Use the getBucketLocation API to avoid cross region lookups.
*/
private async lookupRegion(bucketName: string, s3: S3): Promise<string | undefined> {
getLogger().debug('LookupRegion called for bucketName: %s', bucketName)
try {
const response = await s3.getBucketLocation({ Bucket: bucketName }).promise()
// getBucketLocation returns an explicit empty string location contraint for us-east-1
const region = response.LocationConstraint === '' ? 'us-east-1' : response.LocationConstraint
getLogger().debug('LookupRegion returned region: %s', region)
return region
} catch (e) {
// Try to recover region from the error
return (e as AWSError).region
}
}
/**
* Empties a bucket by repeatedly listing and deleting all versions of all objects inside.
*
* Note that this just repeatedly calls list object versions and delete objects to empty the bucket.
* Failures can leave the bucket in a state where only some objects are deleted.
*
* @throws Error if there is an error listing or deleting.
*/
private async emptyBucket(bucketName: string): Promise<void> {
try {
for await (const { objects } of this.listObjectVersionsIterable({ bucketName })) {
if (_(objects).isEmpty()) {
continue
}
const deleteObjectsResponse = await this.deleteObjects({ bucketName, objects })
if (!_(deleteObjectsResponse.errors).isEmpty()) {
const e = new Error(inspect(deleteObjectsResponse.errors[0]))
getLogger().error('Failed to delete %d objects: %O...', deleteObjectsResponse.errors.length, e)
throw e
}
}
} catch (e) {
getLogger().error('Failed to empty bucket %s: %O', bucketName, e)
throw e
}
}
}
export class DefaultBucket {
public readonly name: string
public readonly region: string
public readonly arn: string
public constructor({ partitionId, region, name }: { partitionId: string; region: string; name: string }) {
this.name = name
this.region = region
this.arn = buildArn({ partitionId, bucketName: name })
}
public [inspect.custom](): string {
return `Bucket (name=${this.name}, region=${this.region}, arn=${this.arn})`
}
}
export class DefaultFolder {
public readonly name: string
public readonly path: string
public readonly arn: string
public constructor({ partitionId, bucketName, path }: { partitionId: string; bucketName: string; path: string }) {
this.path = path
this.arn = buildArn({ partitionId, bucketName, key: path })
this.name = _(this.path).split(DEFAULT_DELIMITER).dropRight()!.last()!
}
public [inspect.custom](): string {
return `Folder (name=${this.name}, path=${this.path}, arn=${this.arn})`
}
}
export class DefaultFile {
public readonly name: string
public readonly key: string
public readonly arn: string
public readonly lastModified?: Date
public readonly sizeBytes?: number
public constructor({
partitionId,
bucketName,
key,
lastModified,
sizeBytes,
}: {
partitionId: string
bucketName: string
key: string
lastModified?: Date
sizeBytes?: number
}) {
this.name = _(key).split(DEFAULT_DELIMITER).last()!
this.key = key
this.arn = buildArn({ partitionId, bucketName, key })
this.lastModified = lastModified
this.sizeBytes = sizeBytes
}
public [inspect.custom](): string {
return `File (name=${this.name}, key=${this.key}, arn=${this.arn}, lastModified=${this.lastModified}, sizeBytes=${this.sizeBytes})`
}
}
function buildArn({ partitionId, bucketName, key }: { partitionId: string; bucketName: string; key?: string }) {
if (key === undefined) {
return `arn:${partitionId}:s3:::${bucketName}`
}
return `arn:${partitionId}:s3:::${bucketName}/${key}`
}
async function createSdkClient(regionCode: string): Promise<S3> {
clearInternalBucketCache()
return await ext.sdkClientBuilder.createAwsService(S3, { computeChecksums: true }, regionCode)
}
/**
* Bucket region is cached across invocations without regard to partition
* If partition changes with same bucket name in both partitions, cache is incorrect
* @see https://github.com/aws/aws-sdk-js/blob/16a799c0681c01dcafa7b30be5f16894861b3a32/lib/services/s3.js#L919-L924
*/
function clearInternalBucketCache(): void {
;(S3.prototype as any).bucketRegionCache = {}
} | the_stack |
import { resolve, dirname, relative } from 'path'
import fs from 'fs-extra'
import os from 'os'
import chalk from 'chalk'
import glob from 'fast-glob'
import { debug } from 'debug'
import { Project } from 'ts-morph'
import { normalizePath } from 'vite'
import { readConfigFile } from 'typescript'
import {
normalizeGlob,
transformDynamicImport,
transformAliasImport,
removePureImport
} from './transform'
import { setCompileRoot, compileVueCode } from './compile'
import {
isNativeObj,
isPromise,
mergeObjects,
ensureAbsolute,
ensureArray,
runParallel
} from './utils'
import type { Plugin, Alias, Logger } from 'vite'
import type { ts, Diagnostic, SourceFile } from 'ts-morph'
interface TransformWriteFile {
filePath?: string,
content?: string
}
export interface PluginOptions {
include?: string | string[],
exclude?: string | string[],
root?: string,
outputDir?: string,
compilerOptions?: ts.CompilerOptions | null,
tsConfigFilePath?: string,
cleanVueFileName?: boolean,
staticImport?: boolean,
clearPureImport?: boolean,
insertTypesEntry?: boolean,
copyDtsFiles?: boolean,
noEmitOnError?: boolean,
skipDiagnostics?: boolean,
logDiagnostics?: boolean,
afterDiagnostic?: (diagnostics: Diagnostic[]) => void | Promise<void>,
beforeWriteFile?: (filePath: string, content: string) => void | TransformWriteFile,
afterBuild?: () => void | Promise<void>
}
const noneExport = 'export {};\n'
const virtualPrefix = '\0'
const vueRE = /\.vue$/
const tsRE = /\.tsx?$/
const jsRE = /\.jsx?$/
const dtsRE = /\.d\.tsx?$/
const tjsRE = /\.(t|j)sx?$/
const watchExtensionRE = /\.(vue|(t|j)sx?)$/
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {}
const bundleDebug = debug('vite-plugin-dts:bundle')
export function dtsPlugin(options: PluginOptions = {}): Plugin {
const {
tsConfigFilePath = 'tsconfig.json',
cleanVueFileName = false,
staticImport = false,
clearPureImport = true,
insertTypesEntry = false,
noEmitOnError = false,
skipDiagnostics = true,
logDiagnostics = false,
copyDtsFiles = true,
afterDiagnostic = noop,
beforeWriteFile = noop,
afterBuild = noop
} = options
const compilerOptions = options.compilerOptions ?? {}
let root: string
let aliases: Alias[]
let entries: string[]
let logger: Logger
let project: Project
let tsConfigPath: string
let outputDir: string
let isBundle = false
const sourceDtsFiles = new Set<SourceFile>()
let hasJsVue = false
let allowJs = false
return {
name: 'vite:dts',
apply: 'build',
enforce: 'pre',
config(config) {
if (isBundle) return
const aliasOptions = (config.resolve && config.resolve.alias) ?? []
if (isNativeObj(aliasOptions)) {
aliases = Object.entries(aliasOptions).map(([key, value]) => {
return { find: key, replacement: value }
})
} else {
aliases = ensureArray(aliasOptions)
}
},
configResolved(config) {
if (isBundle) return
logger = config.logger
if (!config.build.lib) {
logger.warn(
chalk.yellow(
`\n${chalk.cyan(
'[vite:dts]'
)} You building not a library that may not need to generate declaration files.\n`
)
)
}
root = ensureAbsolute(options.root ?? '', config.root)
tsConfigPath = ensureAbsolute(tsConfigFilePath, root)
outputDir = options.outputDir
? ensureAbsolute(options.outputDir, root)
: ensureAbsolute(config.build.outDir, root)
if (!outputDir) {
logger.error(
chalk.red(
`\n${chalk.cyan(
'[vite:dts]'
)} Can not resolve declaration directory, please check your vite config and plugin options.\n`
)
)
return
}
setCompileRoot(root)
compilerOptions.rootDir ||= root
project = new Project({
compilerOptions: mergeObjects(compilerOptions, {
noEmitOnError,
outDir: '.',
// #27 declarationDir option will make no declaration file generated
declarationDir: null,
// compile vue setup script will generate expose parameter for setup function
// although user never use it which will get an unexpected unused error
noUnusedParameters: false,
declaration: true,
noEmit: false,
emitDeclarationOnly: true
}),
tsConfigFilePath: tsConfigPath,
skipAddingFilesFromTsConfig: true
})
allowJs = project.getCompilerOptions().allowJs ?? false
},
buildStart(inputOptions) {
if (insertTypesEntry) {
entries = Array.isArray(inputOptions.input)
? inputOptions.input
: Object.values(inputOptions.input)
}
},
transform(code, id) {
if (id.startsWith(virtualPrefix)) {
return null
}
if (vueRE.test(id)) {
const { content, ext } = compileVueCode(code)
if (content) {
if (ext === 'js' || ext === 'jsx') hasJsVue = true
project.createSourceFile(`${id}.${ext || 'js'}`, content, { overwrite: true })
}
} else if (!id.includes('.vue?vue') && (tsRE.test(id) || (allowJs && jsRE.test(id)))) {
project.addSourceFileAtPath(id)
}
return null
},
watchChange(id) {
if (watchExtensionRE.test(id)) {
isBundle = false
if (project) {
const sourceFile = project.getSourceFile(normalizePath(id))
sourceFile && project.removeSourceFile(sourceFile)
}
}
},
async closeBundle() {
if (!outputDir || !project || isBundle) return
logger.info(chalk.green(`\n${chalk.cyan('[vite:dts]')} Start generate declaration files...`))
bundleDebug('start')
isBundle = true
sourceDtsFiles.clear()
const startTime = Date.now()
const tsConfig: {
include?: string[],
exclude?: string[]
} = readConfigFile(tsConfigPath, project.getFileSystem().readFileSync).config ?? {}
const include = options.include ?? tsConfig.include
const exclude = options.exclude ?? tsConfig.exclude
bundleDebug('read config')
const includedFileSet = new Set<string>()
if (include && include.length) {
const files = await glob(ensureArray(include).map(normalizeGlob), {
cwd: root,
absolute: true,
ignore: ensureArray(exclude ?? ['node_modules/**']).map(normalizeGlob)
})
files.forEach(file => {
if (dtsRE.test(file)) {
if (!copyDtsFiles) {
return
}
includedFileSet.add(file)
sourceDtsFiles.add(project.addSourceFileAtPath(file))
return
}
includedFileSet.add(`${tjsRE.test(file) ? file.replace(tjsRE, '') : file}.d.ts`)
})
if (hasJsVue) {
if (!allowJs) {
logger.warn(
chalk.yellow(
`${chalk.cyan(
'[vite:dts]'
)} Some js files are referenced, but you may not enable the 'allowJs' option.`
)
)
}
project.compilerOptions.set({ allowJs: true })
}
bundleDebug('collect files')
}
project.resolveSourceFileDependencies()
bundleDebug('resolve')
if (!skipDiagnostics) {
const diagnostics = project.getPreEmitDiagnostics()
if (diagnostics?.length && logDiagnostics) {
logger.warn(project.formatDiagnosticsWithColorAndContext(diagnostics))
}
if (typeof afterDiagnostic === 'function') {
const result = afterDiagnostic(diagnostics)
isPromise(result) && (await result)
}
bundleDebug('diagnostics')
}
const service = project.getLanguageService()
const outputFiles = project
.getSourceFiles()
.map(sourceFile =>
service
.getEmitOutput(sourceFile, true)
.getOutputFiles()
.map(outputFile => ({
path: outputFile.getFilePath() as string,
content: outputFile.getText()
}))
)
.flat()
.concat(
Array.from(sourceDtsFiles).map(sourceFile => ({
path: sourceFile.getFilePath(),
content: sourceFile.getFullText()
}))
)
bundleDebug('emit')
await runParallel(os.cpus().length, outputFiles, async outputFile => {
let filePath = outputFile.path
let content = outputFile.content
const isMapFile = filePath.endsWith('.map')
if (
!includedFileSet.has(isMapFile ? filePath.slice(0, -4) : filePath) ||
(clearPureImport && content === noneExport)
) {
return
}
if (!isMapFile && content && content !== noneExport) {
content = clearPureImport ? removePureImport(content) : content
content = transformAliasImport(filePath, content, aliases)
content = staticImport ? transformDynamicImport(content) : content
}
filePath = resolve(
outputDir,
relative(root, cleanVueFileName ? filePath.replace('.vue.d.ts', '.d.ts') : filePath)
)
if (typeof beforeWriteFile === 'function') {
const result = beforeWriteFile(filePath, content)
if (result && isNativeObj(result)) {
filePath = result.filePath ?? filePath
content = result.content ?? content
}
}
await fs.mkdir(dirname(filePath), { recursive: true })
await fs.writeFile(
filePath,
cleanVueFileName ? content.replace(/['"](.+)\.vue['"]/g, '"$1"') : content,
'utf8'
)
})
bundleDebug('output')
if (insertTypesEntry) {
const pkgPath = resolve(root, 'package.json')
const pkg = fs.existsSync(pkgPath) ? JSON.parse(await fs.readFile(pkgPath, 'utf-8')) : {}
let typesPath = pkg.types ? resolve(root, pkg.types) : resolve(outputDir, 'index.d.ts')
if (!fs.existsSync(typesPath)) {
let content =
entries
.map(entry => {
let filePath = normalizePath(
relative(dirname(typesPath), resolve(outputDir, relative(root, entry)))
)
filePath = filePath.replace(tsRE, '')
filePath = /^\.\.?\//.test(filePath) ? filePath : `./${filePath}`
return `export * from '${filePath}'`
})
.join('\n') + '\n'
if (typeof beforeWriteFile === 'function') {
const result = beforeWriteFile(typesPath, content)
if (result && isNativeObj(result)) {
typesPath = result.filePath ?? typesPath
content = result.content ?? content
}
}
await fs.writeFile(typesPath, content, 'utf-8')
}
bundleDebug('insert index')
}
if (typeof afterBuild === 'function') {
const result = afterBuild()
isPromise(result) && (await result)
}
bundleDebug('finish')
logger.info(
chalk.green(
`${chalk.cyan('[vite:dts]')} Declaration files built in ${Date.now() - startTime}ms.\n`
)
)
}
}
} | the_stack |
import { Skeleton } from "./Skeleton";
import { MixBlend } from "./Animation";
export interface StringMap<T> {
[key: string]: T;
}
export class IntSet {
array = new Array<number>();
add (value: number): boolean {
let contains = this.contains(value);
this.array[value | 0] = value | 0;
return !contains;
}
contains (value: number) {
return this.array[value | 0] != undefined;
}
remove (value: number) {
this.array[value | 0] = undefined;
}
clear () {
this.array.length = 0;
}
}
export class StringSet {
entries: StringMap<boolean> = {};
size = 0;
add (value: string): boolean {
let contains = this.entries[value];
this.entries[value] = true;
if (!contains) {
this.size++;
return true;
}
return false;
}
addAll (values: string[]): boolean {
let oldSize = this.size;
for (var i = 0, n = values.length; i < n; i++)
this.add(values[i]);
return oldSize != this.size;
}
contains (value: string) {
return this.entries[value];
}
clear () {
this.entries = {};
this.size = 0;
}
}
export interface NumberArrayLike {
readonly length: number;
[n: number]: number;
}
export interface Disposable {
dispose (): void;
}
export interface Restorable {
restore (): void;
}
export class Color {
public static WHITE = new Color(1, 1, 1, 1);
public static RED = new Color(1, 0, 0, 1);
public static GREEN = new Color(0, 1, 0, 1);
public static BLUE = new Color(0, 0, 1, 1);
public static MAGENTA = new Color(1, 0, 1, 1);
constructor (public r: number = 0, public g: number = 0, public b: number = 0, public a: number = 0) {
}
set (r: number, g: number, b: number, a: number) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
return this.clamp();
}
setFromColor (c: Color) {
this.r = c.r;
this.g = c.g;
this.b = c.b;
this.a = c.a;
return this;
}
setFromString (hex: string) {
hex = hex.charAt(0) == '#' ? hex.substr(1) : hex;
this.r = parseInt(hex.substr(0, 2), 16) / 255;
this.g = parseInt(hex.substr(2, 2), 16) / 255;
this.b = parseInt(hex.substr(4, 2), 16) / 255;
this.a = hex.length != 8 ? 1 : parseInt(hex.substr(6, 2), 16) / 255;
return this;
}
add (r: number, g: number, b: number, a: number) {
this.r += r;
this.g += g;
this.b += b;
this.a += a;
return this.clamp();
}
clamp () {
if (this.r < 0) this.r = 0;
else if (this.r > 1) this.r = 1;
if (this.g < 0) this.g = 0;
else if (this.g > 1) this.g = 1;
if (this.b < 0) this.b = 0;
else if (this.b > 1) this.b = 1;
if (this.a < 0) this.a = 0;
else if (this.a > 1) this.a = 1;
return this;
}
static rgba8888ToColor (color: Color, value: number) {
color.r = ((value & 0xff000000) >>> 24) / 255;
color.g = ((value & 0x00ff0000) >>> 16) / 255;
color.b = ((value & 0x0000ff00) >>> 8) / 255;
color.a = ((value & 0x000000ff)) / 255;
}
static rgb888ToColor (color: Color, value: number) {
color.r = ((value & 0x00ff0000) >>> 16) / 255;
color.g = ((value & 0x0000ff00) >>> 8) / 255;
color.b = ((value & 0x000000ff)) / 255;
}
static fromString (hex: string): Color {
return new Color().setFromString(hex);
}
}
export class MathUtils {
static PI = 3.1415927;
static PI2 = MathUtils.PI * 2;
static radiansToDegrees = 180 / MathUtils.PI;
static radDeg = MathUtils.radiansToDegrees;
static degreesToRadians = MathUtils.PI / 180;
static degRad = MathUtils.degreesToRadians;
static clamp (value: number, min: number, max: number) {
if (value < min) return min;
if (value > max) return max;
return value;
}
static cosDeg (degrees: number) {
return Math.cos(degrees * MathUtils.degRad);
}
static sinDeg (degrees: number) {
return Math.sin(degrees * MathUtils.degRad);
}
static signum (value: number): number {
return value > 0 ? 1 : value < 0 ? -1 : 0;
}
static toInt (x: number) {
return x > 0 ? Math.floor(x) : Math.ceil(x);
}
static cbrt (x: number) {
let y = Math.pow(Math.abs(x), 1 / 3);
return x < 0 ? -y : y;
}
static randomTriangular (min: number, max: number): number {
return MathUtils.randomTriangularWith(min, max, (min + max) * 0.5);
}
static randomTriangularWith (min: number, max: number, mode: number): number {
let u = Math.random();
let d = max - min;
if (u <= (mode - min) / d) return min + Math.sqrt(u * d * (mode - min));
return max - Math.sqrt((1 - u) * d * (max - mode));
}
static isPowerOfTwo (value: number) {
return value && (value & (value - 1)) === 0;
}
}
export abstract class Interpolation {
protected abstract applyInternal (a: number): number;
apply (start: number, end: number, a: number): number {
return start + (end - start) * this.applyInternal(a);
}
}
export class Pow extends Interpolation {
protected power = 2;
constructor (power: number) {
super();
this.power = power;
}
applyInternal (a: number): number {
if (a <= 0.5) return Math.pow(a * 2, this.power) / 2;
return Math.pow((a - 1) * 2, this.power) / (this.power % 2 == 0 ? -2 : 2) + 1;
}
}
export class PowOut extends Pow {
constructor (power: number) {
super(power);
}
applyInternal (a: number): number {
return Math.pow(a - 1, this.power) * (this.power % 2 == 0 ? -1 : 1) + 1;
}
}
export class Utils {
static SUPPORTS_TYPED_ARRAYS = typeof (Float32Array) !== "undefined";
static arrayCopy<T> (source: ArrayLike<T>, sourceStart: number, dest: ArrayLike<T>, destStart: number, numElements: number) {
for (let i = sourceStart, j = destStart; i < sourceStart + numElements; i++, j++) {
dest[j] = source[i];
}
}
static arrayFill<T> (array: ArrayLike<T>, fromIndex: number, toIndex: number, value: T) {
for (let i = fromIndex; i < toIndex; i++)
array[i] = value;
}
static setArraySize<T> (array: Array<T>, size: number, value: any = 0): Array<T> {
let oldSize = array.length;
if (oldSize == size) return array;
array.length = size;
if (oldSize < size) {
for (let i = oldSize; i < size; i++) array[i] = value;
}
return array;
}
static ensureArrayCapacity<T> (array: Array<T>, size: number, value: any = 0): Array<T> {
if (array.length >= size) return array;
return Utils.setArraySize(array, size, value);
}
static newArray<T> (size: number, defaultValue: T): Array<T> {
let array = new Array<T>(size);
for (let i = 0; i < size; i++) array[i] = defaultValue;
return array;
}
static newFloatArray (size: number): NumberArrayLike {
if (Utils.SUPPORTS_TYPED_ARRAYS)
return new Float32Array(size)
else {
let array = new Array<number>(size);
for (let i = 0; i < array.length; i++) array[i] = 0;
return array;
}
}
static newShortArray (size: number): NumberArrayLike {
if (Utils.SUPPORTS_TYPED_ARRAYS)
return new Int16Array(size)
else {
let array = new Array<number>(size);
for (let i = 0; i < array.length; i++) array[i] = 0;
return array;
}
}
static toFloatArray (array: Array<number>) {
return Utils.SUPPORTS_TYPED_ARRAYS ? new Float32Array(array) : array;
}
static toSinglePrecision (value: number) {
return Utils.SUPPORTS_TYPED_ARRAYS ? Math.fround(value) : value;
}
// This function is used to fix WebKit 602 specific issue described at http://esotericsoftware.com/forum/iOS-10-disappearing-graphics-10109
static webkit602BugfixHelper (alpha: number, blend: MixBlend) {
}
static contains<T> (array: Array<T>, element: T, identity = true) {
for (var i = 0; i < array.length; i++)
if (array[i] == element) return true;
return false;
}
static enumValue (type: any, name: string) {
return type[name[0].toUpperCase() + name.slice(1)];
}
}
export class DebugUtils {
static logBones (skeleton: Skeleton) {
for (let i = 0; i < skeleton.bones.length; i++) {
let bone = skeleton.bones[i];
console.log(bone.data.name + ", " + bone.a + ", " + bone.b + ", " + bone.c + ", " + bone.d + ", " + bone.worldX + ", " + bone.worldY);
}
}
}
export class Pool<T> {
private items = new Array<T>();
private instantiator: () => T;
constructor (instantiator: () => T) {
this.instantiator = instantiator;
}
obtain () {
return this.items.length > 0 ? this.items.pop() : this.instantiator();
}
free (item: T) {
if ((item as any).reset) (item as any).reset();
this.items.push(item);
}
freeAll (items: ArrayLike<T>) {
for (let i = 0; i < items.length; i++)
this.free(items[i]);
}
clear () {
this.items.length = 0;
}
}
export class Vector2 {
constructor (public x = 0, public y = 0) {
}
set (x: number, y: number): Vector2 {
this.x = x;
this.y = y;
return this;
}
length () {
let x = this.x;
let y = this.y;
return Math.sqrt(x * x + y * y);
}
normalize () {
let len = this.length();
if (len != 0) {
this.x /= len;
this.y /= len;
}
return this;
}
}
export class TimeKeeper {
maxDelta = 0.064;
framesPerSecond = 0;
delta = 0;
totalTime = 0;
private lastTime = Date.now() / 1000;
private frameCount = 0;
private frameTime = 0;
update () {
let now = Date.now() / 1000;
this.delta = now - this.lastTime;
this.frameTime += this.delta;
this.totalTime += this.delta;
if (this.delta > this.maxDelta) this.delta = this.maxDelta;
this.lastTime = now;
this.frameCount++;
if (this.frameTime > 1) {
this.framesPerSecond = this.frameCount / this.frameTime;
this.frameTime = 0;
this.frameCount = 0;
}
}
}
export interface ArrayLike<T> {
length: number;
[n: number]: T;
}
export class WindowedMean {
values: Array<number>;
addedValues = 0;
lastValue = 0;
mean = 0;
dirty = true;
constructor (windowSize: number = 32) {
this.values = new Array<number>(windowSize);
}
hasEnoughData () {
return this.addedValues >= this.values.length;
}
addValue (value: number) {
if (this.addedValues < this.values.length) this.addedValues++;
this.values[this.lastValue++] = value;
if (this.lastValue > this.values.length - 1) this.lastValue = 0;
this.dirty = true;
}
getMean () {
if (this.hasEnoughData()) {
if (this.dirty) {
let mean = 0;
for (let i = 0; i < this.values.length; i++)
mean += this.values[i];
this.mean = mean / this.values.length;
this.dirty = false;
}
return this.mean;
}
return 0;
}
} | the_stack |
//
// Main demos
//
// 01-default.html
function defaultDemo() {
const swiper = new Swiper('.swiper-container');
}
// 02-responsive.html
function responsive() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true
});
}
// 03-vertical.html
function vertical() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
direction: 'vertical'
});
}
// 04-space-between.html
function spaceBetween() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
spaceBetween: 30,
});
}
// 05-slides-per-view.html
function slidesPerView() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 3,
paginationClickable: true,
spaceBetween: 30
});
}
// 06-slides-per-view-auto.html
function slidesPerViewAuto() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 'auto',
paginationClickable: true,
spaceBetween: 30
});
}
// 07-centered.html
function centered() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 4,
centeredSlides: true,
paginationClickable: true,
spaceBetween: 30
});
}
// 08-centered-auto.html
function centeredAuto() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 'auto',
centeredSlides: true,
paginationClickable: true,
spaceBetween: 30
});
}
// 09-freemode.html
function freemode() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 3,
paginationClickable: true,
spaceBetween: 30,
freeMode: true
});
}
// 10-slides-per-column.html
function slidesPerColumn() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 3,
slidesPerColumn: 2,
paginationClickable: true,
spaceBetween: 30
});
}
// 11-nested.html
function nested() {
const swiperH = new Swiper('.swiper-container-h', {
pagination: '.swiper-pagination-h',
paginationClickable: true,
spaceBetween: 50
});
const swiperV = new Swiper('.swiper-container-v', {
pagination: '.swiper-pagination-v',
paginationClickable: true,
direction: 'vertical',
spaceBetween: 50
});
}
// 12-grab-cursor.html
function grabCursor() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 4,
centeredSlides: true,
paginationClickable: true,
spaceBetween: 30,
grabCursor: true
});
}
// 13-scrollbar.html
function scrollbar() {
const swiper = new Swiper('.swiper-container', {
scrollbar: '.swiper-scrollbar',
scrollbarHide: true,
slidesPerView: 'auto',
centeredSlides: true,
spaceBetween: 30,
grabCursor: true
});
}
// 14-nav-arrows.html
function navArrows() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 30
});
}
// 15-infinite-loop.html
function infiniteLoop() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
slidesPerView: 1,
paginationClickable: true,
spaceBetween: 30,
loop: true
});
}
// 16-effect-fade.html
function effectFade() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 30,
effect: 'fade'
});
}
// 17-effect-cube.html
function effectCube() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
effect: 'cube',
grabCursor: true,
cube: {
shadow: true,
slideShadows: true,
shadowOffset: 20,
shadowScale: 0.94
}
});
}
// 18-effect-coverflow.html
function effectCoverflow() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
effect: 'coverflow',
grabCursor: true,
centeredSlides: true,
slidesPerView: 'auto',
coverflow: {
rotate: 50,
stretch: 0,
depth: 100,
modifier: 1,
slideShadows: true
}
});
}
// 19-keyboard-control.html
function keyboardControl() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
slidesPerView: 1,
paginationClickable: true,
spaceBetween: 30,
keyboardControl: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
});
}
// 20-mousewheel-control.html
function mousewheelControl() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
direction: 'vertical',
slidesPerView: 1,
paginationClickable: true,
spaceBetween: 30,
mousewheelControl: true
});
}
// 21-autoplay.html
function autoplay() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
paginationClickable: true,
spaceBetween: 30,
centeredSlides: true,
autoplay: 2500,
autoplayDisableOnInteraction: false
});
}
// 22-dynamic-slides.html
function dynamicSlides() {
let appendNumber = 4;
let prependNumber = 1;
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
slidesPerView: 3,
centeredSlides: true,
paginationClickable: true,
spaceBetween: 30,
});
document.querySelector('.prepend-2-slides').addEventListener('click', e => {
e.preventDefault();
swiper.prependSlide([
`<div class="swiper-slide">Slide ${--prependNumber}</div>`,
`<div class="swiper-slide">Slide ${--prependNumber}</div>`
]);
});
document.querySelector('.prepend-slide').addEventListener('click', e => {
e.preventDefault();
swiper.prependSlide(`<div class="swiper-slide">Slide ${--prependNumber}</div>`);
});
document.querySelector('.append-slide').addEventListener('click', e => {
e.preventDefault();
swiper.appendSlide(`<div class="swiper-slide">Slide ${++appendNumber}</div>`);
});
document.querySelector('.append-2-slides').addEventListener('click', e => {
e.preventDefault();
swiper.appendSlide([
`<div class="swiper-slide">Slide ${++appendNumber}</div>`,
`<div class="swiper-slide">Slide ${++appendNumber}</div>`
]);
});
}
// 23-thumbs-gallery-loop.html
function thumbsGalleryLoop() {
const galleryTop = new Swiper('.gallery-top', {
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 10,
loop: true,
loopedSlides: 5, // looped slides should be the same
});
const galleryThumbs = new Swiper('.gallery-thumbs', {
spaceBetween: 10,
slidesPerView: 4,
touchRatio: 0.2,
loop: true,
loopedSlides: 5, // looped slides should be the same
slideToClickedSlide: true
});
galleryTop.params.control = galleryThumbs;
galleryThumbs.params.control = galleryTop;
}
// 23-thumbs-gallery.html
function thumbsGallery() {
const galleryTop = new Swiper('.gallery-top', {
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 10,
});
const galleryThumbs = new Swiper('.gallery-thumbs', {
spaceBetween: 10,
centeredSlides: true,
slidesPerView: 'auto',
touchRatio: 0.2,
slideToClickedSlide: true
});
galleryTop.params.control = galleryThumbs;
galleryThumbs.params.control = galleryTop;
}
// 24-multiple-swipers.html
function multipleSwipers() {
const swiper1 = new Swiper('.swiper1', {
pagination: '.swiper-pagination1',
paginationClickable: true,
spaceBetween: 30,
});
const swiper2 = new Swiper('.swiper2', {
pagination: '.swiper-pagination2',
paginationClickable: true,
spaceBetween: 30,
});
const swiper3 = new Swiper('.swiper3', {
pagination: '.swiper-pagination3',
paginationClickable: true,
spaceBetween: 30,
});
}
// 25-hash-navigation.html
function hashNavigation() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
spaceBetween: 30,
hashnav: true,
hashnavWatchState: true
});
}
// 26-rtl.html
function rtl() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev'
});
}
// 27-jquery.html
function jquery() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev'
});
}
// 28-parallax.html
function parallax() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
parallax: true,
speed: 600,
});
}
// 29-custom-pagination.html
function customPagination() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
paginationBulletRender(swiper, index, className) {
return `<span class="${className}">${index + 1}</span>`;
}
});
}
// 30-lazy-load-images.html
function lazyLoadImages() {
const swiper = new Swiper('.swiper-container', {
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
pagination: '.swiper-pagination',
paginationClickable: true,
// Disable preloading of all images
preloadImages: false,
// Enable lazy loading
lazyLoading: true
});
}
// 31-custom-plugin.html
function customPlugin() {
/* ========
Debugger plugin, simple demo plugin to console.log some of callbacks
======== */
Swiper.prototype.plugins.debugger = (swiper: any, params: any) => {
if (!params) return;
// Need to return object with properties that names are the same as callbacks
return {
onInit(swiper: any) {
console.log('onInit');
},
onClick(swiper: any, e: any) {
console.log('onClick');
},
onTap(swiper: any, e: any) {
console.log('onTap');
},
onDoubleTap(swiper: any, e: any) {
console.log('onDoubleTap');
},
onSliderMove(swiper: any, e: any) {
console.log('onSliderMove');
},
onSlideChangeStart(swiper: any) {
console.log('onSlideChangeStart');
},
onSlideChangeEnd(swiper: any) {
console.log('onSlideChangeEnd');
},
onTransitionStart(swiper: any) {
console.log('onTransitionStart');
},
onTransitionEnd(swiper: any) {
console.log('onTransitionEnd');
},
onReachBeginning(swiper: any) {
console.log('onReachBeginning');
},
onReachEnd(swiper: any) {
console.log('onReachEnd');
}
};
};
}
// 32-scroll-container.html
function scrollContainer() {
const swiper = new Swiper('.swiper-container', {
scrollbar: '.swiper-scrollbar',
direction: 'vertical',
slidesPerView: 'auto',
mousewheelControl: true,
freeMode: true
});
}
// 32-slideable-menu.html
function slideableMenu() {
const toggleMenu = () => {
if (swiper.previousIndex === 0)
swiper.slidePrev();
};
const menuButton = document.getElementsByClassName('menu-button')[0];
const swiper = new Swiper('.swiper-container', {
slidesPerView: 'auto',
initialSlide: 1,
resistanceRatio: .00000000000001,
onSlideChangeStart: (slider) => {
if (slider.activeIndex === 0) {
menuButton.classList.add('cross');
menuButton.removeEventListener('click', toggleMenu, false);
} else
menuButton.classList.remove('cross');
},
onSlideChangeEnd: (slider) => {
if (slider.activeIndex === 0)
menuButton.removeEventListener('click', toggleMenu, false);
else
menuButton.addEventListener('click', toggleMenu, false);
},
slideToClickedSlide: true
});
}
// 33-responsive-breakpoints.html
function responsiveBreakpoints() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
slidesPerView: 5,
spaceBetween: 50,
breakpoints: {
1024: {
slidesPerView: 4,
spaceBetween: 40
},
768: {
slidesPerView: 3,
spaceBetween: 30
},
640: {
slidesPerView: 2,
spaceBetween: 20
},
320: {
slidesPerView: 1,
spaceBetween: 10
}
}
});
}
// 34-autoheight.html
function autoheight() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
autoHeight: true, // enable auto height
});
}
// 35-effect-flip.html
function effectFlip() {
const swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
effect: 'flip',
grabCursor: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev'
});
}
// 36-pagination-fraction.html
function paginationFraction() {
const swiper = new Swiper('.swiper-container', {
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
pagination: '.swiper-pagination',
paginationType: 'fraction'
});
}
// 37-pagination-progress.html
function paginationProgress() {
const swiper = new Swiper('.swiper-container', {
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
pagination: '.swiper-pagination',
paginationType: 'progress'
});
}
// 38-history.html
function historyDemo() {
const swiper = new Swiper('.swiper-container', {
spaceBetween: 50,
slidesPerView: 2,
centeredSlides: true,
slideToClickedSlide: true,
grabCursor: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
scrollbar: '.swiper-scrollbar',
pagination: '.swiper-pagination',
history: 'slide',
});
}
// 38-jquery-ie9-loop.html
function jqueryIe9Loop() {
const swiper = new Swiper('.swiper-container', {
loop: true,
pagination: '.swiper-pagination',
paginationClickable: true,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev'
});
}
// 39-zoom.html
function zoom() {
const swiper = new Swiper('.swiper-container', {
zoom: true,
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev'
});
} | the_stack |
import { normalizeUrl } from '@worldbrain/memex-url-utils'
import * as DATA from './index.test.data'
import { PageUrlsByDay } from './types'
import { setupBackgroundIntegrationTest } from 'src/tests/background-integration-tests'
import { BackgroundModules } from 'src/background-script/setup'
import { Annotation, AnnotationPrivacyLevels } from 'src/annotations/types'
import { BackgroundIntegrationTestSetup } from 'src/tests/integration-tests'
const countAnnots = (res) => {
return res.docs.reduce(
(count, { annotations }) => count + annotations.length,
0,
)
}
const flattenAnnotUrls = (res) => {
return res.docs.reduce(
(urls, { annotations }) => [...urls, ...annotations.map((a) => a.url)],
[],
)
}
const flattenAnnotUrlsFromDayMap = (res: PageUrlsByDay) => {
const urls: string[] = []
for (const annotsByPageUrl of Object.values(res)) {
const annots = Object.values(annotsByPageUrl) as Annotation[][]
urls.push(...[].concat(...annots).map((a) => a.url))
}
return urls
}
describe('Annotations search', () => {
let coll1Id: number
let coll2Id: number
async function insertTestData({
storageManager,
backgroundModules,
fetchPageDataProcessor,
}: BackgroundIntegrationTestSetup) {
const annotsStorage = backgroundModules.directLinking.annotationStorage
const customListsBg = backgroundModules.customLists
fetchPageDataProcessor.mockPage = {
url: DATA.highlight.object.pageUrl,
hostname: normalizeUrl(DATA.highlight.object.pageUrl),
domain: normalizeUrl(DATA.highlight.object.pageUrl),
fullTitle: DATA.highlight.object.pageTitle,
text: DATA.highlight.object.body,
fullUrl: DATA.highlight.object.url,
tags: [],
terms: [],
titleTerms: [],
urlTerms: [],
}
for (const annot of [
DATA.highlight,
DATA.annotation,
DATA.comment,
DATA.hybrid,
]) {
// Pages also need to be seeded to match domains filters against
await storageManager.collection('pages').createObject({
url: annot.object.pageUrl,
hostname: normalizeUrl(annot.object.pageUrl),
domain: normalizeUrl(annot.object.pageUrl),
title: annot.object.pageTitle,
text: annot.object.body,
canonicalUrl: annot.object.url,
})
// Create a dummy visit 30 secs before annot creation time
await storageManager.collection('visits').createObject({
url: annot.object.pageUrl,
time: new Date(
annot.object.createdWhen.getTime() - 300000,
).getTime(),
})
await annotsStorage.createAnnotation({ ...annot.object })
if (annot.isShared) {
await storageManager
.collection('sharedAnnotationMetadata')
.createObject({
localId: annot.object.url,
remoteId: backgroundModules.contentSharing.options.generateServerId(
'sharedAnnotationMetadata',
),
excludeFromLists: false,
})
}
if (annot.isProtected) {
await storageManager
.collection('annotationPrivacyLevels')
.createObject({
annotation: annot.object.url,
privacyLevel: AnnotationPrivacyLevels.PROTECTED,
createdWhen: new Date(),
})
}
}
// Insert bookmarks
await annotsStorage.toggleAnnotBookmark({ url: DATA.hybrid.object.url })
await annotsStorage.toggleAnnotBookmark({
url: DATA.highlight.object.url,
})
// Insert collections + collection entries
coll1Id = await customListsBg.createCustomList({
name: DATA.coll1,
})
coll2Id = await customListsBg.createCustomList({
name: DATA.coll2,
})
await customListsBg.insertPageToList({
id: coll2Id,
url: DATA.fullPageUrl1,
})
await customListsBg.insertPageToList({
id: coll1Id,
url: DATA.fullPageUrl2,
})
await annotsStorage.insertAnnotToList({
listId: coll1Id,
url: DATA.hybrid.object.url,
})
await annotsStorage.insertAnnotToList({
listId: coll2Id,
url: DATA.highlight.object.url,
})
// Insert tags
await annotsStorage.modifyTags(true)(
DATA.tag1,
DATA.annotation.object.url,
)
await annotsStorage.modifyTags(true)(
DATA.tag2,
DATA.annotation.object.url,
)
}
async function setupTest() {
const setup = await setupBackgroundIntegrationTest({
includePostSyncProcessor: true,
tabManager: {
getActiveTab: () => ({ id: 1, url: 'test' }),
getTabState: () => undefined,
getTabStateByUrl: () => undefined,
} as any,
})
await insertTestData(setup)
return {
storageMan: setup.storageManager,
searchBg: setup.backgroundModules.search,
annotsBg: setup.backgroundModules.directLinking,
}
}
describe('terms-based searches', () => {
test('plain terms search', async () => {
const { searchBg } = await setupTest()
const resA = await searchBg.searchAnnotations({
query: 'comment',
})
expect(countAnnots(resA)).toBe(2)
expect(flattenAnnotUrls(resA)).toEqual(
expect.arrayContaining([
DATA.comment.object.url,
DATA.annotation.object.url,
]),
)
const resB = await searchBg.searchAnnotations({
query: 'bla',
})
expect(countAnnots(resB)).toBe(2)
expect(flattenAnnotUrls(resB)).toEqual(
expect.arrayContaining([
DATA.hybrid.object.url,
DATA.annotation.object.url,
]),
)
})
test('bookmarks filter', async () => {
const { searchBg } = await setupTest()
const resFiltered = await searchBg.searchAnnotations({
query: 'bla',
bookmarksOnly: true,
})
expect(countAnnots(resFiltered)).toBe(1)
expect(flattenAnnotUrls(resFiltered)).toEqual(
expect.arrayContaining([DATA.hybrid.object.url]),
)
const resUnfiltered = await searchBg.searchAnnotations({
query: 'bla',
bookmarksOnly: false,
})
expect(countAnnots(resUnfiltered)).toBe(2)
expect(flattenAnnotUrls(resUnfiltered)).toEqual(
expect.arrayContaining([
DATA.hybrid.object.url,
DATA.annotation.object.url,
]),
)
})
test('collections filter', async () => {
const { searchBg } = await setupTest()
const resA = await searchBg.searchAnnotations({
query: 'highlight',
lists: [coll1Id],
})
expect(countAnnots(resA)).toBe(1)
const resB = await searchBg.searchAnnotations({
query: 'highlight',
lists: [9999999], // Not a real collection ID
})
expect(countAnnots(resB)).toBe(0)
})
test('tags filter', async () => {
const { searchBg } = await setupTest()
const resFiltered = await searchBg.searchAnnotations({
query: 'comment',
tagsInc: [DATA.tag1],
})
expect(countAnnots(resFiltered)).toBe(1)
expect(flattenAnnotUrls(resFiltered)).toEqual(
expect.arrayContaining([DATA.annotation.object.url]),
)
const resUnfiltered = await searchBg.searchAnnotations({
query: 'comment',
})
expect(countAnnots(resUnfiltered)).toBe(2)
expect(flattenAnnotUrls(resUnfiltered)).toEqual(
expect.arrayContaining([
DATA.annotation.object.url,
DATA.comment.object.url,
]),
)
})
test('domains filter', async () => {
const { searchBg } = await setupTest()
const resUnfiltered = await searchBg.searchAnnotations({
query: 'highlight',
})
expect(countAnnots(resUnfiltered)).toBe(2)
expect(flattenAnnotUrls(resUnfiltered)).toEqual(
expect.arrayContaining([
DATA.hybrid.object.url,
DATA.highlight.object.url,
]),
)
const resExc = await searchBg.searchAnnotations({
query: 'highlight',
domainsExclude: ['annotation.url'],
})
expect(countAnnots(resExc)).toBe(1)
expect(flattenAnnotUrls(resExc)).toEqual(
expect.arrayContaining([DATA.hybrid.object.url]),
)
const resInc = await searchBg.searchAnnotations({
query: 'highlight',
domains: ['annotation.url'],
})
expect(countAnnots(resInc)).toBe(1)
expect(flattenAnnotUrls(resInc)).toEqual(
expect.arrayContaining([DATA.highlight.object.url]),
)
})
test('page result limit parameter', async () => {
const { searchBg } = await setupTest()
const single = await searchBg.searchAnnotations({
query: 'term',
limit: 1,
})
const double = await searchBg.searchAnnotations({
query: 'term',
limit: 2,
})
const stillDouble = await searchBg.searchAnnotations({
query: 'term',
limit: 3,
})
expect(single.docs.length).toBe(1)
expect(double.docs.length).toBe(2)
expect(stillDouble.docs.length).toBe(2)
})
test('comment-terms only terms search', async () => {
const { searchBg } = await setupTest()
const resCommentsOnly = await searchBg.searchAnnotations({
query: 'term',
contentTypes: { highlights: false, notes: true, pages: false },
})
expect(countAnnots(resCommentsOnly)).toBe(1)
expect(flattenAnnotUrls(resCommentsOnly)).toEqual(
expect.arrayContaining([DATA.hybrid.object.url]),
)
const resAllFields = await searchBg.searchAnnotations({
query: 'term',
})
expect(countAnnots(resAllFields)).toBe(2)
expect(flattenAnnotUrls(resAllFields)).toEqual(
expect.arrayContaining([
DATA.hybrid.object.url,
DATA.comment.object.url,
]),
)
})
test('highlighted-text-terms only terms search', async () => {
const { searchBg } = await setupTest()
const resBodyOnly = await searchBg.searchAnnotations({
query: 'term',
contentTypes: { highlights: true, notes: false, pages: false },
})
expect(countAnnots(resBodyOnly)).toBe(1)
expect(flattenAnnotUrls(resBodyOnly)).toEqual(
expect.arrayContaining([DATA.comment.object.url]),
)
const resAllFields = await searchBg.searchAnnotations({
query: 'term',
})
expect(countAnnots(resAllFields)).toBe(2)
expect(flattenAnnotUrls(resAllFields)).toEqual(
expect.arrayContaining([
DATA.hybrid.object.url,
DATA.comment.object.url,
]),
)
})
})
describe('URL-based searches', () => {
test('blank', async () => {
const { annotsBg } = await setupTest()
const results = await annotsBg.getAllAnnotationsByUrl(
{ tab: null },
{ url: DATA.normalizedPageUrl1 },
)
expect(results.length).toBe(3)
expect(results.map((a) => a.url)).toEqual(
expect.arrayContaining([
DATA.highlight.object.url,
DATA.annotation.object.url,
DATA.comment.object.url,
]),
)
})
test('bookmarks filter', async () => {
const { annotsBg } = await setupTest()
const results = await annotsBg.getAllAnnotationsByUrl(
{ tab: null },
{ url: DATA.normalizedPageUrl1, bookmarksOnly: true },
)
expect(results.length).toBe(1)
expect(results.map((a) => a.url)).toEqual(
expect.arrayContaining([DATA.highlight.object.url]),
)
})
test('tags included filter', async () => {
const { annotsBg } = await setupTest()
const results = await annotsBg.getAllAnnotationsByUrl(
{ tab: null },
{
url: DATA.normalizedPageUrl1,
tagsInc: [DATA.tag1],
},
)
expect(results.length).toBe(1)
expect(results.map((a) => a.url)).toEqual(
expect.arrayContaining([DATA.annotation.object.url]),
)
})
test('tags excluded filter', async () => {
const { annotsBg } = await setupTest()
const results = await annotsBg.getAllAnnotationsByUrl(
{ tab: null },
{
url: DATA.normalizedPageUrl1,
tagsExc: [DATA.tag1, DATA.tag2, 'dummy'],
},
)
expect(results.length).toBe(0)
})
test('collections filter', async () => {
const { annotsBg } = await setupTest()
const resA = await annotsBg.getAllAnnotationsByUrl(
{ tab: null },
{
url: DATA.normalizedPageUrl1,
collections: [coll2Id],
},
)
expect(resA.length).toBe(3)
expect(resA.map((a) => a.url)).toEqual(
expect.arrayContaining([
DATA.highlight.object.url,
DATA.annotation.object.url,
DATA.comment.object.url,
]),
)
const resB = await annotsBg.getAllAnnotationsByUrl(
{ tab: null },
{
url: DATA.normalizedPageUrl2,
collections: [coll1Id],
},
)
expect(resB.length).toBe(1)
expect(resB.map((a) => a.url)).toEqual(
expect.arrayContaining([DATA.hybrid.object.url]),
)
})
})
describe('blank searches', () => {
test('all content types search', async () => {
const { searchBg } = await setupTest()
const { docs: results } = await searchBg.searchPages({
contentTypes: { highlights: true, notes: true, pages: true },
})
// Ensure order is by latest visit
expect(results).toEqual([
expect.objectContaining({
url: DATA.highlight.object.pageUrl,
annotations: [
expect.objectContaining({
url: DATA.highlight.object.url,
isBulkShareProtected: true,
isShared: true,
}),
expect.objectContaining({
url: DATA.annotation.object.url,
isBulkShareProtected: false,
isShared: true,
}),
expect.objectContaining({
url: DATA.comment.object.url,
isBulkShareProtected: false,
isShared: false,
}),
],
}),
expect.objectContaining({
url: DATA.hybrid.object.pageUrl,
annotations: [
expect.objectContaining({
url: DATA.hybrid.object.url,
isBulkShareProtected: true,
isShared: false,
}),
],
}),
])
})
test('annots-only search', async () => {
const { searchBg } = await setupTest()
const {
annotsByDay: results,
resultsExhausted,
}: any = await searchBg.searchAnnotations({})
const resUrls = flattenAnnotUrlsFromDayMap(results)
expect(resultsExhausted).toBe(true)
// Ensure order of pages is by latest annot
expect(resUrls).toEqual(
expect.arrayContaining([
DATA.hybrid.object.url,
DATA.comment.object.url,
DATA.highlight.object.url,
DATA.annotation.object.url,
]),
)
})
test('time filters', async () => {
const { searchBg } = await setupTest()
// Should result in only the newest annot
const { annotsByDay: resA }: any = await searchBg.searchAnnotations(
{
startDate: new Date('2019-01-30'),
},
)
const resAUrls = flattenAnnotUrlsFromDayMap(resA)
expect(resAUrls.length).toBe(1)
expect(resAUrls).toEqual(
expect.arrayContaining([DATA.hybrid.object.url]),
)
// Should result in only the oldest annot
const { annotsByDay: resB }: any = await searchBg.searchAnnotations(
{
endDate: new Date('2019-01-26'),
},
)
const resBUrls = flattenAnnotUrlsFromDayMap(resB)
expect(resBUrls.length).toBe(1)
expect(resBUrls).toEqual(
expect.arrayContaining([DATA.highlight.object.url]),
)
// Should result in only the oldest annot
const { annotsByDay: resC }: any = await searchBg.searchAnnotations(
{
startDate: new Date('2019-01-25'),
endDate: new Date('2019-01-28T23:00Z'),
},
)
const resCUrls = flattenAnnotUrlsFromDayMap(resC)
expect(resCUrls.length).toBe(2)
expect(resCUrls).toEqual(
expect.arrayContaining([
DATA.comment.object.url,
DATA.highlight.object.url,
]),
)
})
test('tags filter', async () => {
const { searchBg } = await setupTest()
const {
annotsByDay: results,
resultsExhausted,
}: any = await searchBg.searchAnnotations({
tagsInc: [DATA.tag1],
})
const resUrls = flattenAnnotUrlsFromDayMap(results)
expect(resultsExhausted).toBe(true)
expect(resUrls).toEqual([DATA.annotation.object.url])
})
})
test('annotations on page search results should have tags attached', async () => {
const { searchBg } = await setupTest()
const resA = await searchBg.searchAnnotations({ query: 'comment' })
expect(resA.docs[0].annotations[0].tags).toEqual([DATA.tag1, DATA.tag2])
expect(resA.docs[0].annotations[1].tags).toEqual([])
const resB = await searchBg.searchAnnotations({ query: 'comment' })
expect(resB.docs[0].annotations[0].tags).toEqual([DATA.tag1, DATA.tag2])
expect(resB.docs[0].annotations[1].tags).toEqual([])
})
}) | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class ApplicationCostProfiler extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: ApplicationCostProfiler.Types.ClientConfiguration)
config: Config & ApplicationCostProfiler.Types.ClientConfiguration;
/**
* Deletes the specified report definition in AWS Application Cost Profiler. This stops the report from being generated.
*/
deleteReportDefinition(params: ApplicationCostProfiler.Types.DeleteReportDefinitionRequest, callback?: (err: AWSError, data: ApplicationCostProfiler.Types.DeleteReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.DeleteReportDefinitionResult, AWSError>;
/**
* Deletes the specified report definition in AWS Application Cost Profiler. This stops the report from being generated.
*/
deleteReportDefinition(callback?: (err: AWSError, data: ApplicationCostProfiler.Types.DeleteReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.DeleteReportDefinitionResult, AWSError>;
/**
* Retrieves the definition of a report already configured in AWS Application Cost Profiler.
*/
getReportDefinition(params: ApplicationCostProfiler.Types.GetReportDefinitionRequest, callback?: (err: AWSError, data: ApplicationCostProfiler.Types.GetReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.GetReportDefinitionResult, AWSError>;
/**
* Retrieves the definition of a report already configured in AWS Application Cost Profiler.
*/
getReportDefinition(callback?: (err: AWSError, data: ApplicationCostProfiler.Types.GetReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.GetReportDefinitionResult, AWSError>;
/**
* Ingests application usage data from Amazon Simple Storage Service (Amazon S3). The data must already exist in the S3 location. As part of the action, AWS Application Cost Profiler copies the object from your S3 bucket to an S3 bucket owned by Amazon for processing asynchronously.
*/
importApplicationUsage(params: ApplicationCostProfiler.Types.ImportApplicationUsageRequest, callback?: (err: AWSError, data: ApplicationCostProfiler.Types.ImportApplicationUsageResult) => void): Request<ApplicationCostProfiler.Types.ImportApplicationUsageResult, AWSError>;
/**
* Ingests application usage data from Amazon Simple Storage Service (Amazon S3). The data must already exist in the S3 location. As part of the action, AWS Application Cost Profiler copies the object from your S3 bucket to an S3 bucket owned by Amazon for processing asynchronously.
*/
importApplicationUsage(callback?: (err: AWSError, data: ApplicationCostProfiler.Types.ImportApplicationUsageResult) => void): Request<ApplicationCostProfiler.Types.ImportApplicationUsageResult, AWSError>;
/**
* Retrieves a list of all reports and their configurations for your AWS account. The maximum number of reports is one.
*/
listReportDefinitions(params: ApplicationCostProfiler.Types.ListReportDefinitionsRequest, callback?: (err: AWSError, data: ApplicationCostProfiler.Types.ListReportDefinitionsResult) => void): Request<ApplicationCostProfiler.Types.ListReportDefinitionsResult, AWSError>;
/**
* Retrieves a list of all reports and their configurations for your AWS account. The maximum number of reports is one.
*/
listReportDefinitions(callback?: (err: AWSError, data: ApplicationCostProfiler.Types.ListReportDefinitionsResult) => void): Request<ApplicationCostProfiler.Types.ListReportDefinitionsResult, AWSError>;
/**
* Creates the report definition for a report in Application Cost Profiler.
*/
putReportDefinition(params: ApplicationCostProfiler.Types.PutReportDefinitionRequest, callback?: (err: AWSError, data: ApplicationCostProfiler.Types.PutReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.PutReportDefinitionResult, AWSError>;
/**
* Creates the report definition for a report in Application Cost Profiler.
*/
putReportDefinition(callback?: (err: AWSError, data: ApplicationCostProfiler.Types.PutReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.PutReportDefinitionResult, AWSError>;
/**
* Updates existing report in AWS Application Cost Profiler.
*/
updateReportDefinition(params: ApplicationCostProfiler.Types.UpdateReportDefinitionRequest, callback?: (err: AWSError, data: ApplicationCostProfiler.Types.UpdateReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.UpdateReportDefinitionResult, AWSError>;
/**
* Updates existing report in AWS Application Cost Profiler.
*/
updateReportDefinition(callback?: (err: AWSError, data: ApplicationCostProfiler.Types.UpdateReportDefinitionResult) => void): Request<ApplicationCostProfiler.Types.UpdateReportDefinitionResult, AWSError>;
}
declare namespace ApplicationCostProfiler {
export interface DeleteReportDefinitionRequest {
/**
* Required. ID of the report to delete.
*/
reportId: ReportId;
}
export interface DeleteReportDefinitionResult {
/**
* ID of the report that was deleted.
*/
reportId?: ReportId;
}
export type Format = "CSV"|"PARQUET"|string;
export interface GetReportDefinitionRequest {
/**
* ID of the report to retrieve.
*/
reportId: ReportId;
}
export interface GetReportDefinitionResult {
/**
* ID of the report retrieved.
*/
reportId: ReportId;
/**
* Description of the report.
*/
reportDescription: ReportDescription;
/**
* Cadence used to generate the report.
*/
reportFrequency: ReportFrequency;
/**
* Format of the generated report.
*/
format: Format;
/**
* Amazon Simple Storage Service (Amazon S3) location where the report is uploaded.
*/
destinationS3Location: S3Location;
/**
* Timestamp (milliseconds) when this report definition was created.
*/
createdAt: Timestamp;
/**
* Timestamp (milliseconds) when this report definition was last updated.
*/
lastUpdated: Timestamp;
}
export interface ImportApplicationUsageRequest {
/**
* Amazon S3 location to import application usage data from.
*/
sourceS3Location: SourceS3Location;
}
export interface ImportApplicationUsageResult {
/**
* ID of the import request.
*/
importId: ImportId;
}
export type ImportId = string;
export type Integer = number;
export interface ListReportDefinitionsRequest {
/**
* The token value from a previous call to access the next page of results.
*/
nextToken?: Token;
/**
* The maximum number of results to return.
*/
maxResults?: Integer;
}
export interface ListReportDefinitionsResult {
/**
* The retrieved reports.
*/
reportDefinitions?: ReportDefinitionList;
/**
* The value of the next token, if it exists. Null if there are no more results.
*/
nextToken?: Token;
}
export interface PutReportDefinitionRequest {
/**
* Required. ID of the report. You can choose any valid string matching the pattern for the ID.
*/
reportId: ReportId;
/**
* Required. Description of the report.
*/
reportDescription: ReportDescription;
/**
* Required. The cadence to generate the report.
*/
reportFrequency: ReportFrequency;
/**
* Required. The format to use for the generated report.
*/
format: Format;
/**
* Required. Amazon Simple Storage Service (Amazon S3) location where Application Cost Profiler uploads the report.
*/
destinationS3Location: S3Location;
}
export interface PutReportDefinitionResult {
/**
* ID of the report.
*/
reportId?: ReportId;
}
export interface ReportDefinition {
/**
* The ID of the report.
*/
reportId?: ReportId;
/**
* Description of the report
*/
reportDescription?: ReportDescription;
/**
* The cadence at which the report is generated.
*/
reportFrequency?: ReportFrequency;
/**
* The format used for the generated reports.
*/
format?: Format;
/**
* The location in Amazon Simple Storage Service (Amazon S3) the reports should be saved to.
*/
destinationS3Location?: S3Location;
/**
* Timestamp (milliseconds) when this report definition was created.
*/
createdAt?: Timestamp;
/**
* Timestamp (milliseconds) when this report definition was last updated.
*/
lastUpdatedAt?: Timestamp;
}
export type ReportDefinitionList = ReportDefinition[];
export type ReportDescription = string;
export type ReportFrequency = "MONTHLY"|"DAILY"|"ALL"|string;
export type ReportId = string;
export type S3Bucket = string;
export type S3BucketRegion = "ap-east-1"|"me-south-1"|"eu-south-1"|"af-south-1"|string;
export type S3Key = string;
export interface S3Location {
/**
* Name of the S3 bucket.
*/
bucket: S3Bucket;
/**
* Prefix for the location to write to.
*/
prefix: S3Prefix;
}
export type S3Prefix = string;
export interface SourceS3Location {
/**
* Name of the bucket.
*/
bucket: S3Bucket;
/**
* Key of the object.
*/
key: S3Key;
/**
* Region of the bucket. Only required for Regions that are disabled by default. For more infomration about Regions that are disabled by default, see Enabling a Region in the AWS General Reference guide.
*/
region?: S3BucketRegion;
}
export type Timestamp = Date;
export type Token = string;
export interface UpdateReportDefinitionRequest {
/**
* Required. ID of the report to update.
*/
reportId: ReportId;
/**
* Required. Description of the report.
*/
reportDescription: ReportDescription;
/**
* Required. The cadence to generate the report.
*/
reportFrequency: ReportFrequency;
/**
* Required. The format to use for the generated report.
*/
format: Format;
/**
* Required. Amazon Simple Storage Service (Amazon S3) location where Application Cost Profiler uploads the report.
*/
destinationS3Location: S3Location;
}
export interface UpdateReportDefinitionResult {
/**
* ID of the report.
*/
reportId?: ReportId;
}
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2020-09-10"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the ApplicationCostProfiler client.
*/
export import Types = ApplicationCostProfiler;
}
export = ApplicationCostProfiler; | the_stack |
import {
Component,
ContentChildren,
QueryList,
EventEmitter,
Input,
Output,
OnDestroy,
forwardRef,
ElementRef,
AfterContentInit,
AfterViewChecked,
NgZone,
} from '@angular/core';
import { SelectOptionComponent } from '../select-option/select-option.component';
import { Subscription, timer, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { isMobile } from 'is-mobile';
import { ConfigService } from 'services/config.service';
interface BasicSelectOption {
name: string;
value: any;
}
@Component({
selector: 'app-select',
templateUrl: './select.component.html',
styleUrls: ['./select.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectComponent),
multi: true,
},
],
})
export class SelectComponent
implements OnDestroy, ControlValueAccessor, AfterContentInit, AfterViewChecked {
@Input() public placeholder?: string;
@Input() public disabled?: boolean;
public open = false;
public text?: string;
public dropdownMaxHeight?: string;
public dropBottom?: string;
public basicOptions?: BasicSelectOption[];
public readonly useNativeObservable: Observable<boolean>;
@ContentChildren(SelectOptionComponent)
public set options(optionsRaw: QueryList<SelectOptionComponent>) {
// Clear subscriptions to values
this.resetSubscriptions();
const options = Array.from(optionsRaw);
this.clearHighlighted(true);
this.optionsInternal = options;
this.searchStrings = options.map(option => option.text.toLowerCase());
this.clearHighlighted(true);
this.selectedOptions = [];
this.basicOptions = [];
for (let i = 0; i < options.length; i++) {
const option = options[i];
this.basicOptions.push({ name: option.text, value: option.value });
// Set the selected state of each option.
option.setSelected(this.valueInternal.includes(option.value));
if (option.selected) {
this.selectedOptions.push(option);
}
// Subscribe to the change for each.
this.subscriptions.push(
option.selectedChange.subscribe(selected => {
let updated = false;
if (!selected) {
this.selectedOptions = this.selectedOptions.filter(item => option !== item);
updated = true;
} else if (!this.selectedOptions.includes(option)) {
this.selectedOptions = [...this.selectedOptions, option];
updated = true;
}
if (updated) {
this.updateSelected();
if (selected) {
this.selected.emit(option.value);
} else {
this.deselected.emit(option.value);
}
}
}),
);
this.subscriptions.push(
option.highlightedEvent.subscribe(() => {
this.updateHighlighted(i);
}),
);
}
this.sortSelected();
this.subscriptions.push(
this.valueChange.subscribe(value => {
if (this.onChange) {
this.onChange(value);
}
}),
);
this.updateText();
}
@Input()
public get value(): any[] {
return this.valueInternal;
}
public set value(newValue: any[]) {
this.writeValue(newValue);
}
@Output() public valueChange = new EventEmitter<any[]>();
@Output() public selected = new EventEmitter<any>();
@Output() public deselected = new EventEmitter<any>();
// public to be accessed by the template.
public selectedOptions: SelectOptionComponent[] = [];
public optionsInternal?: SelectOptionComponent[];
public inContent = false;
public valueInternal: any[] = [];
private subscriptions: Subscription[] = [];
private onChange?: (values: any[]) => void;
private onTouched?: () => void;
private touched = false;
private selfRef: ElementRef;
private zone: NgZone;
private lastTop?: number;
private timeout?: any;
private writeValueTimeout?: any;
private highlightIndex?: number;
private searchStrings?: string[];
private searchSubscription?: Subscription;
private searchString?: string;
public constructor(selfRef: ElementRef, zone: NgZone, configService: ConfigService) {
this.selfRef = selfRef;
this.zone = zone;
this.useNativeObservable = configService.getConfiguration().pipe(
map(config => {
return (config.user.useNativeSelectOnMobile && isMobile()) || false;
}),
);
}
public ngAfterContentInit(): void {
this.onResize();
}
public ngAfterViewChecked(): void {
const { top } = this.selfRef.nativeElement.getBoundingClientRect();
const topAdjusted = Math.ceil(top);
if (topAdjusted !== this.lastTop) {
this.lastTop = topAdjusted;
this.zone.run(() => {
this.onResize();
});
}
}
public ngOnDestroy(): void {
this.resetSubscriptions();
this.touched = false;
this.optionsInternal = undefined;
this.selectedOptions = [];
this.text = undefined;
this.valueInternal = [];
this.onChange = undefined;
this.onTouched = undefined;
this.inContent = false;
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
this.timeout = undefined;
}
if (this.writeValueTimeout !== undefined) {
clearTimeout(this.writeValueTimeout);
this.writeValueTimeout = undefined;
}
}
public onKeydown(source: string, event: any): void {
if (source === 'select' && !this.open && event.key === ' ') {
this.open = true;
event.preventDefault();
}
if (this.open && event.key === 'Escape') {
this.open = false;
this.clearHighlighted(true);
event.preventDefault();
}
if (!this.optionsInternal) {
return;
}
if (event.key === 'ArrowDown') {
let index = (this.highlightIndex === undefined ? -1 : this.highlightIndex) + 1;
if (index >= this.optionsInternal.length) {
index = 0;
}
this.updateHighlighted(index);
} else if (event.key === 'ArrowUp') {
let index =
(this.highlightIndex === undefined ? this.optionsInternal.length : this.highlightIndex) - 1;
if (index < 0) {
index = this.optionsInternal.length - 1;
}
this.updateHighlighted(index);
} else if (event.key === 'Enter') {
if (this.highlightIndex !== undefined) {
const option = this.optionsInternal[this.highlightIndex];
option.onValueChange(!option.selected);
}
} else if (this.searchStrings) {
const searchString = (this.searchString || '') + event.key.toLowerCase();
const startIndex = this.searchStrings.findIndex(str => str.startsWith(searchString));
const includeIndex = this.searchStrings.findIndex(str => str.includes(searchString));
const foundIndex = startIndex >= 0 ? startIndex : includeIndex;
if (foundIndex >= 0) {
this.updateHighlighted(foundIndex);
} else {
this.clearHighlighted();
}
this.searchString = searchString;
this.searchSubscription?.unsubscribe();
this.searchSubscription = timer(1000).subscribe(() => {
this.searchString = undefined;
});
}
}
private resetSubscriptions(): void {
for (const subscription of this.subscriptions) {
subscription.unsubscribe();
}
this.subscriptions = [];
this.searchSubscription?.unsubscribe();
this.searchSubscription = undefined;
}
public onFocusOut(): void {
if (!this.inContent) {
this.open = false;
this.clearHighlighted(true);
}
}
public onResize(): void {
const { top, height, bottom } = this.selfRef.nativeElement.getBoundingClientRect();
const padding = height * 2;
const dropdownStart = bottom;
const dropupStart = top;
const body = document.body;
const html = document.documentElement;
const windowHeight =
Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, window.innerHeight) -
padding;
const spaceDropdown = windowHeight - dropdownStart;
const spaceDropup = dropupStart - padding;
const dropdown = spaceDropdown > spaceDropup;
const maxHeight = Math.floor(dropdown ? spaceDropdown : spaceDropup);
const dropdownMaxHeight = `${maxHeight}px`;
const dropBottom = dropdown ? undefined : `${Math.floor(height)}px`;
if (dropdownMaxHeight !== this.dropdownMaxHeight || dropBottom !== this.dropBottom) {
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
this.timeout = undefined;
}
this.timeout = setTimeout(() => {
this.zone.run(() => {
this.dropdownMaxHeight = dropdownMaxHeight;
this.dropBottom = dropBottom;
});
}, 0);
}
}
public writeValue(newValue: any[] | null | undefined): void {
if (this.writeValueTimeout !== undefined) {
clearTimeout(this.writeValueTimeout);
}
this.writeValueTimeout = setTimeout(() => {
this.zone.run(() => {
if (newValue === null || newValue === undefined || !Array.isArray(newValue)) {
newValue = [];
}
if (newValue !== this.valueInternal) {
this.valueInternal = newValue;
this.selectedOptions = [];
if (this.optionsInternal) {
for (const option of Array.from(this.optionsInternal)) {
option.setSelected(this.valueInternal.includes(option.value));
if (option.selected) {
this.selectedOptions.push(option);
}
}
this.sortSelected();
}
this.touched = false;
this.updateText();
}
});
}, 0);
}
public registerOnChange(fn: any): void {
this.onChange = fn;
}
public registerOnTouched(fn: any): void {
this.onTouched = fn;
}
public setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
public onNativeSelectChange(values: any[]): void {
if (!this.optionsInternal) {
return;
}
const added = values.filter(val => !this.valueInternal.includes(val));
const removed = this.valueInternal.filter(val => !values.includes(val));
for (const option of this.optionsInternal) {
option.setSelected(values.includes(option.value));
}
this.selectedOptions = this.optionsInternal.filter(opt => opt.selected);
this.updateSelected();
for (const val of added) {
this.selected.emit(val);
}
for (const val of removed) {
this.deselected.emit(val);
}
}
public clearHighlighted(force?: boolean): void {
if (this.highlightIndex !== undefined || force) {
this.updateHighlighted(undefined);
}
}
private updateHighlighted(index?: number): void {
if (!this.optionsInternal) {
return;
}
if (index === this.highlightIndex && index !== undefined) {
return;
}
if (index === undefined) {
this.highlightIndex = index;
for (const item of this.optionsInternal) {
item.setHighlighted(false);
}
return;
}
if (this.highlightIndex === undefined) {
for (let i = 0; i < this.optionsInternal.length; i++) {
this.optionsInternal[i].setHighlighted(index === i);
if (index === i) {
this.optionsInternal[i].scroll();
}
}
this.highlightIndex = index;
return;
}
this.optionsInternal[this.highlightIndex].setHighlighted(false);
this.optionsInternal[index].setHighlighted(true);
this.highlightIndex = index;
this.optionsInternal[this.highlightIndex].scroll();
}
private updateSelected(): void {
this.sortSelected();
if (!this.touched && this.onTouched) {
this.touched = true;
this.onTouched();
}
this.valueInternal = this.selectedOptions.map(selected => selected.value);
this.valueChange.next(this.valueInternal);
this.updateText();
}
private sortSelected(): void {
const options = this.optionsInternal;
if (!options) {
return;
}
this.selectedOptions.sort((a, b) => {
return options.indexOf(a) - options.indexOf(b);
});
}
private updateText(): void {
if (this.selectedOptions.length === 0) {
this.text = undefined;
} else {
this.text = this.selectedOptions.map(sel => sel.text).join(', ');
}
}
} | the_stack |
declare module "vscode-tasks" {
export interface TaskConfiguration extends BaseTaskConfiguration {
/**
* The configuration's version number
*/
version: string;
/**
* Windows specific task configuration
*/
windows?: BaseTaskConfiguration;
/**
* Mac specific task configuration
*/
osx?: BaseTaskConfiguration;
/**
* Linux specific task configuration
*/
linux?: BaseTaskConfiguration;
}
export interface BaseTaskConfiguration {
/**
* The type of a custom task. Tasks of type "shell" are executed
* inside a shell (e.g. bash, cmd, powershell, ...)
*/
type?: "shell" | "process";
/**
* The command to be executed. Can be an external program or a shell
* command.
*/
command?: string;
/**
* Specifies whether a global command is a background task.
*/
isBackground?: boolean;
/**
* The command options used when the command is executed. Can be omitted.
*/
options?: CommandOptions;
/**
* The arguments passed to the command. Can be omitted.
*/
args?: string[];
/**
* The presentation options.
*/
presentation?: PresentationOptions;
/**
* The problem matcher to be used if a global command is executed (e.g. no tasks
* are defined). A tasks.json file can either contain a global problemMatcher
* property or a tasks property but not both.
*/
problemMatcher?: string | ProblemMatcher | (string | ProblemMatcher)[];
/**
* The configuration of the available tasks. A tasks.json file can either
* contain a global problemMatcher property or a tasks property but not both.
*/
tasks?: TaskDescription[];
}
/**
* Options to be passed to the external program or shell
*/
export interface CommandOptions {
/**
* The current working directory of the executed program or shell.
* If omitted Ticino's current workspace root is used.
*/
cwd?: string;
/**
* The environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: { [key: string]: string; };
/**
* Configuration of the shell when task type is `shell`
*/
shell: {
/**
* The shell to use.
*/
executable: string;
/**
* The arguments to be passed to the shell executable to run in command mode
* (e.g ['-c'] for bash or ['/S', '/C'] for cmd.exe).
*/
args?: string[];
}
}
/**
* The description of a task.
*/
export interface TaskDescription {
/**
* The task's name
*/
label: string;
/**
* The type of a custom task. Tasks of type "shell" are executed
* inside a shell (e.g. bash, cmd, powershell, ...)
*/
type: "shell" | "process";
/**
* The command to execute. If the type is "shell" it should be the full
* command line including any additional arguments passed to the command.
*/
command: string;
/**
* Whether the executed command is kept alive and runs in the background.
*/
isBackground?: boolean;
/**
* Additional arguments passed to the command. Should be used if type
* is "process".
*/
args?: string[];
/**
* Tasks V1 isBuildCommand is used to detect if the tasks is in a build group.
*/
isBuildCommand?: boolean;
/**
* Defines the group to which this tasks belongs
*/
group?: "build" | "string";
/**
* The presentation options.
*/
presentation?: PresentationOptions;
/**
* The problem matcher(s) to use to capture problems in the tasks
* output.
*/
problemMatcher?: string | ProblemMatcher | (string | ProblemMatcher)[];
}
export interface PresentationOptions {
/**
* Controls whether the task output is reveal in the user interface.
* Defaults to `always`.
*/
reveal?: "never" | "silent" | "always";
/**
* Controls whether the command associated with the task is echoed
* in the user interface.
*/
echo?: boolean;
/**
* Controls whether the panel showing the task output is taking focus.
*/
focus?: boolean;
/**
* Controls if the task panel is used for this task only (dedicated),
* shared between tasks (shared) or if a new panel is created on
* every task execution (new). Defaults to `shared`
*/
panel?: "shared" | "dedicated" | "new";
}
/**
* A description of a problem matcher that detects problems
* in build output.
*/
export interface ProblemMatcher {
/**
* The name of a base problem matcher to use. If specified the
* base problem matcher will be used as a template and properties
* specified here will replace properties of the base problem
* matcher
*/
base?: string;
/**
* The owner of the produced VS Code problem. This is typically
* the identifier of a VS Code language service if the problems are
* to be merged with the one produced by the language service
* or 'external'. Defaults to 'external' if omitted.
*/
owner?: string;
/**
* The severity of the VS Code problem produced by this problem matcher.
*
* Valid values are:
* "error": to produce errors.
* "warning": to produce warnings.
* "info": to produce infos.
*
* The value is used if a pattern doesn't specify a severity match group.
* Defaults to "error" if omitted.
*/
severity?: string;
/**
* Defines how filename reported in a problem pattern
* should be read. Valid values are:
* - "absolute": the filename is always treated absolute.
* - "relative": the filename is always treated relative to
* the current working directory. This is the default.
* - ["relative", "path value"]: the filename is always
* treated relative to the given path value.
*/
fileLocation?: string | string[];
/**
* The name of a predefined problem pattern, the inline definition
* of a problem pattern or an array of problem patterns to match
* problems spread over multiple lines.
*/
pattern?: string | ProblemPattern | ProblemPattern[];
/**
* Additional information used to detect when a background task (like a watching task in Gulp)
* is active.
*/
background?: BackgroundMatcher;
}
/**
* A description to track the start and end of a background task.
*/
export interface BackgroundMatcher {
/**
* If set to true the watcher is in active mode when the task
* starts. This is equals of issuing a line that matches the
* beginPattern.
*/
activeOnStart?: boolean;
/**
* If matched in the output the start of a background task is signaled.
*/
beginsPattern?: string;
/**
* If matched in the output the end of a background task is signaled.
*/
endsPattern?: string;
}
export interface ProblemPattern {
/**
* The regular expression to find a problem in the console output of an
* executed task.
*/
regexp: string;
/**
* The match group index of the filename.
*/
file: number;
/**
* The match group index of the problems's location. Valid location
* patterns are: (line), (line,column) and (startLine,startColumn,endLine,endColumn).
* If omitted the line and column properties are used.
*/
location?: number;
/**
* The match group index of the problem's line in the source file.
* Can only be omitted if location is specified.
*/
line?: number;
/**
* The match group index of the problem's column in the source file.
*/
column?: number;
/**
* The match group index of the problem's end line in the source file.
*
* Defaults to undefined. No end line is captured.
*/
endLine?: number;
/**
* The match group index of the problem's end column in the source file.
*
* Defaults to undefined. No end column is captured.
*/
endColumn?: number;
/**
* The match group index of the problem's severity.
*
* Defaults to undefined. In this case the problem matcher's severity
* is used.
*/
severity?: number;
/**
* The match group index of the problem's code.
*
* Defaults to undefined. No code is captured.
*/
code?: number;
/**
* The match group index of the message. Defaults to 0.
*/
message: number;
/**
* Specifies if the last pattern in a multi line problem matcher should
* loop as long as it does match a line consequently. Only valid on the
* last problem pattern in a multi line problem matcher.
*/
loop?: boolean;
}
} | the_stack |
import { render, Component, h } from 'preact';
import ZoomableTwoUp from './ZoomableTwoUp';
import f1WebpMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-match.webp';
import f1WebpMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-match.webp';
import f1WebpGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-good.webp';
import f1WebpGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-good.webp';
import f1JpgMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-match.jpg';
import f1JpgMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-match.jpg';
import f1JpgGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-good.jpg';
import f1JpgGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-good.jpg';
import f1JpgKornel from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-kornel.jpg';
import f1JpgKornelSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-kornel.jpg';
import f1AvifGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-good.avif';
import f1AvifGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-good.avif';
import f1AvifNearLossless from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/f1-near-lossless.avif';
import f1AvifNearLosslessSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/f1-near-lossless.avif';
import teamAvifGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-good.avif';
import teamAvifGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-good.avif';
import teamWebpGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-good.webp';
import teamWebpGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-good.webp';
import teamPngGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-good.png';
import teamPngGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-good.png';
import teamPngMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-match.png';
import teamPngMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-match.png';
import teamSvgGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-traced.svg';
import teamSvgGoodSize from 'asset-pretty-size-br:static-build/posts/2020/09/avif-has-landed/demos/team-traced.svg';
import teamAvifLossless from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-lossless.avif';
import teamAvifLosslessSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-lossless.avif';
import teamWebpMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-match.webp';
import teamWebpMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-match.webp';
import teamJpgMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-match.jpg';
import teamJpgMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-match.jpg';
import teamWebpLossless from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/team-lossless.webp';
import teamWebpLosslessSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/team-lossless.webp';
import carWebpGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-good.webp';
import carWebpGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/car-good.webp';
import carAvifGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-good.avif';
import carAvifGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/car-good.avif';
import carSvgGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-good.svg';
import carSvgGoodSize from 'asset-pretty-size-br:static-build/posts/2020/09/avif-has-landed/demos/car-good.svg';
import carPngGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-good.png';
import carPngGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/car-good.png';
import carSvgOriginal from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-original.svg';
import carSvgOriginalSize from 'asset-pretty-size-br:static-build/posts/2020/09/avif-has-landed/demos/car-original.svg';
import carWebpMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-match.webp';
import carWebpMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/car-match.webp';
import carPngMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/car-match.png';
import carPngMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/car-match.png';
import machineWebpGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-good.webp';
import machineWebpGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-good.webp';
import machineWebpDithered from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-dithered.webp';
import machineWebpDitheredSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-dithered.webp';
import machineWebpLossless from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-lossless.webp';
import machineWebpLosslessSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-lossless.webp';
import machineJpgGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-good.jpg';
import machineJpgGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-good.jpg';
import machineAvifGood from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-good.avif';
import machineAvifGoodSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-good.avif';
import machineWebpMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-match.webp';
import machineWebpMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-match.webp';
import machineJpgMatch from 'asset-url:static-build/posts/2020/09/avif-has-landed/demos/machine-match.jpg';
import machineJpgMatchSize from 'asset-pretty-size:static-build/posts/2020/09/avif-has-landed/demos/machine-match.jpg';
import redBullWebpOriginal from 'asset-url:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay.webp';
import redBullWebpOriginalSize from 'asset-pretty-size:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay.webp';
import redBullWebpGood from 'asset-url:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay-optim.webp';
import redBullWebpGoodSize from 'asset-pretty-size:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay-optim.webp';
import redBullAvif from 'asset-url:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay.avif';
import redBullAvifSize from 'asset-pretty-size:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay.avif';
import redBullAvifMobile from 'asset-url:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay-mobile.avif';
import redBullAvifMobileSize from 'asset-pretty-size:static-build/posts/2021/03/f1-perf-part-3/img-optim/red-bull-overlay-mobile.avif';
import DecodedImg from 'shared/DecodedImg';
const categories: {
[category: string]:
| {
width: number;
options: { [name: string]: string };
backgroundStyle?: { [name: string]: string };
}
| undefined;
} = {
f1: {
width: 960,
options: {
[`AVIF - acceptable - ${f1AvifGoodSize}`]: f1AvifGood,
[`WebP - acceptable - ${f1WebpGoodSize}`]: f1WebpGood,
[`JPEG - acceptable - ${f1JpgGoodSize}`]: f1JpgGood,
[`JPEG - Kornel powers - ${f1JpgKornelSize}`]: f1JpgKornel,
[`WebP - ${f1WebpMatchSize}`]: f1WebpMatch,
[`JPEG - ${f1JpgMatchSize}`]: f1JpgMatch,
[`AVIF - near lossless - ${f1AvifNearLosslessSize}`]: f1AvifNearLossless,
},
},
team: {
width: 400,
options: {
[`AVIF - acceptable - ${teamAvifGoodSize}`]: teamAvifGood,
[`WebP - 68 color lossless - ${teamWebpGoodSize}`]: teamWebpGood,
[`PNG - 68 color lossless - ${teamPngGoodSize}`]: teamPngGood,
[`AVIF - 68 color lossless - ${teamAvifLosslessSize}`]: teamAvifLossless,
[`SVG - traced - ${teamSvgGoodSize}`]: teamSvgGood,
[`WebP - lossy - ${teamWebpMatchSize}`]: teamWebpMatch,
[`JPEG - ${teamJpgMatchSize}`]: teamJpgMatch,
[`PNG - 9 color lossless - ${teamPngMatchSize}`]: teamPngMatch,
[`WebP - full color lossless - ${teamWebpLosslessSize}`]: teamWebpLossless,
},
},
car: {
width: 500,
options: {
[`AVIF - acceptable - ${carAvifGoodSize}`]: carAvifGood,
[`WebP - acceptable - ${carWebpGoodSize}`]: carWebpGood,
[`PNG - 256 colour - ${carPngGoodSize}`]: carPngGood,
[`WebP - ${carWebpMatchSize}`]: carWebpMatch,
[`PNG - 12 colour - ${carPngMatchSize}`]: carPngMatch,
[`SVG - SVGO'd - ${carSvgGoodSize}`]: carSvgGood,
[`SVG - original - ${carSvgOriginalSize}`]: carSvgOriginal,
},
},
machine: {
width: 960,
options: {
[`AVIF - acceptable - ${machineAvifGoodSize}`]: machineAvifGood,
[`WebP - acceptable - ${machineWebpGoodSize}`]: machineWebpGood,
[`JPEG - acceptable - ${machineJpgGoodSize}`]: machineJpgGood,
[`WebP - ${machineWebpMatchSize}`]: machineWebpMatch,
[`JPEG - ${machineJpgMatchSize}`]: machineJpgMatch,
[`WebP - 256 color lossless - ${machineWebpDitheredSize}`]: machineWebpDithered,
[`WebP - full color lossless - ${machineWebpLosslessSize}`]: machineWebpLossless,
},
},
redBull: {
width: 1920,
backgroundStyle: { backgroundColor: 'rgba(0, 0, 0, 0.7)' },
options: {
[`WebP - original - ${redBullWebpOriginalSize}`]: redBullWebpOriginal,
[`WebP - acceptable - ${redBullWebpGoodSize}`]: redBullWebpGood,
[`AVIF - acceptable - ${redBullAvifSize}`]: redBullAvif,
[`AVIF - mobile - ${redBullAvifMobileSize}`]: redBullAvifMobile,
},
},
};
const loadingTimeout = 600;
const urlParams = new URLSearchParams(location.search);
const category = categories[urlParams.get('show') || 'f1'] || categories.f1!;
const images = Object.entries(category.options);
const backgroundStyle = category.backgroundStyle || {};
const initalLeftImg = images[0][1];
const imgParam = urlParams.get('img');
const initialRightImg =
imgParam && imgParam !== initalLeftImg ? imgParam : images[1][1];
interface State {
leftImgSrc: string;
rightImgSrc: string;
leftLoading: boolean;
rightLoading: boolean;
}
class App extends Component<{}, State> {
state: State = {
leftImgSrc: initalLeftImg,
rightImgSrc: initialRightImg,
leftLoading: false,
rightLoading: false,
};
private _leftLoadingTimeout?: number;
private _rightLoadingTimeout?: number;
private _onChoiceLeftChange = (event: Event) => {
this.setState({
leftImgSrc: (event.target as HTMLSelectElement).value,
});
};
private _onChoiceRightChange = (event: Event) => {
this.setState({
rightImgSrc: (event.target as HTMLSelectElement).value,
});
};
private _onLeftLoadStart = () => {
if (this._leftLoadingTimeout) clearInterval(this._leftLoadingTimeout);
this._leftLoadingTimeout = setTimeout(
() => this.setState({ leftLoading: true }),
loadingTimeout,
);
};
private _onLeftLoadEnd = () => {
if (this._leftLoadingTimeout) clearInterval(this._leftLoadingTimeout);
this.setState({ leftLoading: false });
};
private _onRightLoadStart = () => {
if (this._rightLoadingTimeout) clearInterval(this._rightLoadingTimeout);
this._rightLoadingTimeout = setTimeout(
() => this.setState({ rightLoading: true }),
loadingTimeout,
);
};
private _onRightLoadEnd = () => {
if (this._rightLoadingTimeout) clearInterval(this._rightLoadingTimeout);
this.setState({ rightLoading: false });
};
render({}, { leftImgSrc, rightImgSrc, leftLoading, rightLoading }: State) {
return (
<div class="compare-root" style={backgroundStyle}>
<ZoomableTwoUp
left={
<div class={`img-container${leftLoading ? ' loading' : ''}`}>
<DecodedImg
renderWidth={category.width}
src={leftImgSrc}
onLoadStart={this._onLeftLoadStart}
onLoadEnd={this._onLeftLoadEnd}
/>
</div>
}
right={
<div class={`img-container${rightLoading ? ' loading' : ''}`}>
<DecodedImg
renderWidth={category.width}
src={rightImgSrc}
onLoadStart={this._onRightLoadStart}
onLoadEnd={this._onRightLoadEnd}
/>
</div>
}
/>
<select
class="choice-left"
value={leftImgSrc}
onChange={this._onChoiceLeftChange}
>
{images.map(([name, url]) => (
<option value={url}>{name}</option>
))}
</select>
<select
class="choice-right"
value={rightImgSrc}
onChange={this._onChoiceRightChange}
>
{images.map(([name, url]) => (
<option value={url}>{name}</option>
))}
</select>
</div>
);
}
}
render(<App />, document.body); | the_stack |
import * as WebSocketProtocol from "../../../../main/js/generated/joynr/system/RoutingTypes/WebSocketProtocol";
import ProvisioningRoot from "../../../resources/joynr/provisioning/provisioning_root"; // logger and mqtt
// @ts-ignore
const onFatalRuntimeError = (error: JoynrRuntimeException) => {
return;
};
const mocks: Record<string, any> = {};
const constructors: Record<string, any> = {};
const spies: Record<string, any> = {};
[
["DiscoveryQos"],
["CapabilitiesRegistrar", ["shutdown"]],
["MessageRouter", ["setRoutingProxy", "addNextHop", "shutdown", "configureReplyToAddressFromRoutingProxy"]],
["MessageQueue"],
[
"Dispatcher",
[
"registerRequestReplyManager",
"registerSubscriptionManager",
"registerPublicationManager",
"registerMessageRouter",
"shutdown"
]
],
["ParticipantIdStorage"],
["PublicationManager", ["shutdown"]],
["LocalStorageNode", ["shutdown", "getItem"]],
["MessagingQos"],
["WebSocketMessagingSkeleton", ["registerListener", "shutdown"]],
["SharedWebSocket", ["enableShutdownMode"]],
["WebSocketMessagingStubFactory"],
["JoynrMessage"],
["LoggingManager", ["configure", "getLogger"]],
["SubscriptionManager", ["shutdown", "terminateSubscriptions"]],
["ProxyBuilder", ["build"]]
].forEach(([name, keys = []]: any) => {
mocks[name] = {};
keys.forEach((key: string) => {
mocks[name][key] = jest.fn();
});
spies[name] = jest.fn();
constructors[name] = function(...args: any[]) {
spies[name](...args);
return mocks[name];
};
});
mocks.MessageRouter.setRoutingProxy = jest.fn().mockReturnValue(Promise.resolve());
mocks.MessageRouter.configureReplyToAddressFromRoutingProxy = jest.fn().mockReturnValue(Promise.resolve());
mocks.ProxyBuilder.build.mockReturnValue(Promise.resolve(jest.fn()));
mocks.SubscriptionManager.terminateSubscriptions.mockReturnValue(Promise.resolve());
constructors.CapabilitiesRegistrar.setDefaultExpiryIntervalMs = jest.fn();
constructors.DiscoveryQos.setDefaultSettings = jest.fn();
constructors.JoynrMessage.setSigningCallback = jest.fn();
mocks.LocalStorageNode.init = jest.fn().mockReturnValue(Promise.resolve());
mocks.LoggingManager.getLogger.mockReturnValue({
debug: jest.fn(),
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
verbose: jest.fn()
});
const config = {
"../../../../main/js/joynr/proxy/DiscoveryQos": constructors.DiscoveryQos,
"../../../../main/js/joynr/capabilities/CapabilitiesRegistrar": constructors.CapabilitiesRegistrar,
"../../../../main/js/joynr/messaging/routing/MessageRouter": constructors.MessageRouter,
"../../../../main/js/joynr/messaging/routing/MessageQueue": constructors.MessageQueue,
"../../../../main/js/joynr/dispatching/Dispatcher": constructors.Dispatcher,
"../../../../main/js/joynr/capabilities/ParticipantIdStorage": constructors.ParticipantIdStorage,
"../../../../main/js/joynr/dispatching/subscription/PublicationManager": constructors.PublicationManager,
"../../../../main/js/global/LocalStorageNode": constructors.LocalStorageNode,
"../../../../main/js/joynr/messaging/MessagingQos": constructors.MessagingQos,
"../../../../main/js/joynr/messaging/websocket/WebSocketMessagingSkeleton": constructors.WebSocketMessagingSkeleton,
"../../../../main/js/joynr/messaging/websocket/SharedWebSocket": constructors.SharedWebSocket,
"../../../../main/js/joynr/messaging/websocket/WebSocketMessagingStubFactory":
constructors.WebSocketMessagingStubFactory,
"../../../../main/js/joynr/messaging/JoynrMessage": constructors.JoynrMessage,
"../../../../main/js/joynr/dispatching/subscription/SubscriptionManager": constructors.SubscriptionManager,
"../../../../main/js/joynr/system/LoggingManager": mocks.LoggingManager,
"../../../../main/js/joynr/proxy/ProxyBuilder": constructors.ProxyBuilder
};
for (const [key, value] of Object.entries(config)) {
jest.doMock(key, () => value);
}
import WebSocketLibjoynrRuntime from "../../../../main/js/joynr/start/WebSocketLibjoynrRuntime";
import JoynrRuntimeException from "../../../../main/js/joynr/exceptions/JoynrRuntimeException";
import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos";
describe("libjoynr-js.joynr.start.WebSocketLibjoynrRuntime", () => {
let runtime: any;
let provisioning: any;
beforeEach(() => {
provisioning = Object.assign({}, ProvisioningRoot, {
ccAddress: {
protocol: "ws",
host: "localhost",
port: 4242,
path: ""
}
});
// unfortunately jasmine doesn't reset spies between specs per default ...
Object.keys(spies).forEach((spy: any) => {
spies[spy].mockClear();
});
mocks.SubscriptionManager.terminateSubscriptions.mockClear();
});
it("won't override settings unnecessarily", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.shutdown();
expect(constructors.DiscoveryQos.setDefaultSettings).not.toHaveBeenCalled();
expect(constructors.CapabilitiesRegistrar.setDefaultExpiryIntervalMs).not.toHaveBeenCalled();
});
it("will set the default discoveryQos settings correctly", async () => {
const discoveryRetryDelayMs = 100;
const discoveryTimeoutMs = 200;
const discoveryExpiryIntervalMs = 100;
provisioning.discoveryQos = {
discoveryRetryDelayMs,
discoveryTimeoutMs,
discoveryExpiryIntervalMs
};
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.shutdown();
expect(constructors.DiscoveryQos.setDefaultSettings).toHaveBeenCalledWith({
discoveryRetryDelayMs,
discoveryTimeoutMs
});
expect(constructors.CapabilitiesRegistrar.setDefaultExpiryIntervalMs).toHaveBeenCalledWith(
discoveryExpiryIntervalMs
);
});
it("will initialize SharedWebSocket correctly", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
expect(spies.SharedWebSocket).toHaveBeenCalledWith({
remoteAddress: expect.objectContaining({
_typeName: "joynr.system.RoutingTypes.WebSocketAddress",
protocol: WebSocketProtocol.WS,
host: provisioning.ccAddress.host,
port: provisioning.ccAddress.port,
path: provisioning.ccAddress.path
}),
localAddress: expect.objectContaining({
_typeName: "joynr.system.RoutingTypes.WebSocketClientAddress"
}),
provisioning: expect.any(Object),
keychain: undefined
});
await runtime.shutdown();
});
it("will use the default persistency settings", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
expect(spies.MessageRouter.mock.calls.length).toEqual(1);
expect(spies.ParticipantIdStorage.mock.calls.length).toEqual(1);
expect(spies.ParticipantIdStorage.mock.calls[0][0]).toEqual(mocks.LocalStorageNode);
expect(spies.PublicationManager.mock.calls.length).toEqual(1);
await runtime.shutdown();
});
it("enables ParticipantIdStorage persistency if configured", async () => {
provisioning.persistency = { capabilities: true };
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
expect(spies.ParticipantIdStorage.mock.calls.length).toEqual(1);
expect(spies.ParticipantIdStorage.mock.calls[0][0]).toEqual(mocks.LocalStorageNode);
await runtime.shutdown();
});
it("will call MessageQueue with the settings from the provisioning", async () => {
const maxQueueSizeInKBytes = 100;
provisioning.messaging = { maxQueueSizeInKBytes };
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
expect(spies.MessageQueue.mock.calls.length).toEqual(1);
expect(spies.MessageQueue).toHaveBeenCalledWith({
maxQueueSizeInKBytes
});
await runtime.shutdown();
});
it("will call Dispatcher with the settings from the provisioning", async () => {
const ttlUpLiftMs = 1000;
provisioning.messaging = { TTL_UPLIFT: ttlUpLiftMs };
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
expect(spies.Dispatcher.mock.calls.length).toEqual(1);
expect(spies.Dispatcher.mock.calls[0][2]).toEqual(ttlUpLiftMs);
await runtime.shutdown();
});
it("will call MessagingQos with the default ttl", async () => {
const ttl = MessagingQos.DEFAULT_TTL + 10000;
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
expect(spies.MessagingQos).toHaveBeenCalledWith({ ttl });
await runtime.shutdown();
});
it("will set the signingCallback to the joynrMessage.prototype", async () => {
provisioning.keychain = {
tlsCert: "tlsCert",
tlsKey: "tlsKey",
tlsCa: "tlsCa",
ownerId: "ownerID"
};
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.shutdown();
expect(constructors.JoynrMessage.setSigningCallback).toHaveBeenCalled();
});
it("calls SharedWebSocket.enableShutdownMode in terminateAllSubscriptions", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.terminateAllSubscriptions();
expect(mocks.SharedWebSocket.enableShutdownMode).toHaveBeenCalled();
await runtime.shutdown();
});
it("calls SubscriptionManager.terminateSubscriptions in terminateAllSubscriptions", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.terminateAllSubscriptions();
expect(mocks.SubscriptionManager.terminateSubscriptions).toHaveBeenCalledWith(0);
await runtime.shutdown();
});
it("terminates Subscriptions upon shutdown with default timeout", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.shutdown();
expect(mocks.SubscriptionManager.terminateSubscriptions).toHaveBeenCalledWith(1000);
});
it("won't terminate Subscriptions upon shutdown when specified by provisioning", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
provisioning.shutdownSettings = { clearSubscriptionsEnabled: false };
await runtime.start(provisioning);
await runtime.shutdown();
expect(mocks.SubscriptionManager.terminateSubscriptions).not.toHaveBeenCalled();
});
it("won't terminate Subscriptions when explicitly called with shutdown", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
runtime.shutdown({ clearSubscriptionsEnabled: false });
expect(mocks.SubscriptionManager.terminateSubscriptions).not.toHaveBeenCalled();
});
it("calls enableShutdownMode of SharedWebsocket before when shut down", async () => {
runtime = new WebSocketLibjoynrRuntime(onFatalRuntimeError);
await runtime.start(provisioning);
await runtime.shutdown();
expect(mocks.SharedWebSocket.enableShutdownMode).toHaveBeenCalled();
});
}); | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class Inspector2 extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Inspector2.Types.ClientConfiguration)
config: Config & Inspector2.Types.ClientConfiguration;
/**
* Associates an Amazon Web Services account with an Amazon Inspector delegated administrator.
*/
associateMember(params: Inspector2.Types.AssociateMemberRequest, callback?: (err: AWSError, data: Inspector2.Types.AssociateMemberResponse) => void): Request<Inspector2.Types.AssociateMemberResponse, AWSError>;
/**
* Associates an Amazon Web Services account with an Amazon Inspector delegated administrator.
*/
associateMember(callback?: (err: AWSError, data: Inspector2.Types.AssociateMemberResponse) => void): Request<Inspector2.Types.AssociateMemberResponse, AWSError>;
/**
* Retrieves the Amazon Inspector status of multiple Amazon Web Services accounts within your environment.
*/
batchGetAccountStatus(params: Inspector2.Types.BatchGetAccountStatusRequest, callback?: (err: AWSError, data: Inspector2.Types.BatchGetAccountStatusResponse) => void): Request<Inspector2.Types.BatchGetAccountStatusResponse, AWSError>;
/**
* Retrieves the Amazon Inspector status of multiple Amazon Web Services accounts within your environment.
*/
batchGetAccountStatus(callback?: (err: AWSError, data: Inspector2.Types.BatchGetAccountStatusResponse) => void): Request<Inspector2.Types.BatchGetAccountStatusResponse, AWSError>;
/**
* Gets free trial status for multiple Amazon Web Services accounts.
*/
batchGetFreeTrialInfo(params: Inspector2.Types.BatchGetFreeTrialInfoRequest, callback?: (err: AWSError, data: Inspector2.Types.BatchGetFreeTrialInfoResponse) => void): Request<Inspector2.Types.BatchGetFreeTrialInfoResponse, AWSError>;
/**
* Gets free trial status for multiple Amazon Web Services accounts.
*/
batchGetFreeTrialInfo(callback?: (err: AWSError, data: Inspector2.Types.BatchGetFreeTrialInfoResponse) => void): Request<Inspector2.Types.BatchGetFreeTrialInfoResponse, AWSError>;
/**
* Cancels the given findings report.
*/
cancelFindingsReport(params: Inspector2.Types.CancelFindingsReportRequest, callback?: (err: AWSError, data: Inspector2.Types.CancelFindingsReportResponse) => void): Request<Inspector2.Types.CancelFindingsReportResponse, AWSError>;
/**
* Cancels the given findings report.
*/
cancelFindingsReport(callback?: (err: AWSError, data: Inspector2.Types.CancelFindingsReportResponse) => void): Request<Inspector2.Types.CancelFindingsReportResponse, AWSError>;
/**
* Creates a filter resource using specified filter criteria.
*/
createFilter(params: Inspector2.Types.CreateFilterRequest, callback?: (err: AWSError, data: Inspector2.Types.CreateFilterResponse) => void): Request<Inspector2.Types.CreateFilterResponse, AWSError>;
/**
* Creates a filter resource using specified filter criteria.
*/
createFilter(callback?: (err: AWSError, data: Inspector2.Types.CreateFilterResponse) => void): Request<Inspector2.Types.CreateFilterResponse, AWSError>;
/**
* Creates a finding report.
*/
createFindingsReport(params: Inspector2.Types.CreateFindingsReportRequest, callback?: (err: AWSError, data: Inspector2.Types.CreateFindingsReportResponse) => void): Request<Inspector2.Types.CreateFindingsReportResponse, AWSError>;
/**
* Creates a finding report.
*/
createFindingsReport(callback?: (err: AWSError, data: Inspector2.Types.CreateFindingsReportResponse) => void): Request<Inspector2.Types.CreateFindingsReportResponse, AWSError>;
/**
* Deletes a filter resource.
*/
deleteFilter(params: Inspector2.Types.DeleteFilterRequest, callback?: (err: AWSError, data: Inspector2.Types.DeleteFilterResponse) => void): Request<Inspector2.Types.DeleteFilterResponse, AWSError>;
/**
* Deletes a filter resource.
*/
deleteFilter(callback?: (err: AWSError, data: Inspector2.Types.DeleteFilterResponse) => void): Request<Inspector2.Types.DeleteFilterResponse, AWSError>;
/**
* Describe Amazon Inspector configuration settings for an Amazon Web Services organization
*/
describeOrganizationConfiguration(params: Inspector2.Types.DescribeOrganizationConfigurationRequest, callback?: (err: AWSError, data: Inspector2.Types.DescribeOrganizationConfigurationResponse) => void): Request<Inspector2.Types.DescribeOrganizationConfigurationResponse, AWSError>;
/**
* Describe Amazon Inspector configuration settings for an Amazon Web Services organization
*/
describeOrganizationConfiguration(callback?: (err: AWSError, data: Inspector2.Types.DescribeOrganizationConfigurationResponse) => void): Request<Inspector2.Types.DescribeOrganizationConfigurationResponse, AWSError>;
/**
* Disables Amazon Inspector scans for one or more Amazon Web Services accounts. Disabling all scan types in an account disables the Amazon Inspector service.
*/
disable(params: Inspector2.Types.DisableRequest, callback?: (err: AWSError, data: Inspector2.Types.DisableResponse) => void): Request<Inspector2.Types.DisableResponse, AWSError>;
/**
* Disables Amazon Inspector scans for one or more Amazon Web Services accounts. Disabling all scan types in an account disables the Amazon Inspector service.
*/
disable(callback?: (err: AWSError, data: Inspector2.Types.DisableResponse) => void): Request<Inspector2.Types.DisableResponse, AWSError>;
/**
* Disables the Amazon Inspector delegated administrator for your organization.
*/
disableDelegatedAdminAccount(params: Inspector2.Types.DisableDelegatedAdminAccountRequest, callback?: (err: AWSError, data: Inspector2.Types.DisableDelegatedAdminAccountResponse) => void): Request<Inspector2.Types.DisableDelegatedAdminAccountResponse, AWSError>;
/**
* Disables the Amazon Inspector delegated administrator for your organization.
*/
disableDelegatedAdminAccount(callback?: (err: AWSError, data: Inspector2.Types.DisableDelegatedAdminAccountResponse) => void): Request<Inspector2.Types.DisableDelegatedAdminAccountResponse, AWSError>;
/**
* Disassociates a member account from an Amazon Inspector delegated administrator.
*/
disassociateMember(params: Inspector2.Types.DisassociateMemberRequest, callback?: (err: AWSError, data: Inspector2.Types.DisassociateMemberResponse) => void): Request<Inspector2.Types.DisassociateMemberResponse, AWSError>;
/**
* Disassociates a member account from an Amazon Inspector delegated administrator.
*/
disassociateMember(callback?: (err: AWSError, data: Inspector2.Types.DisassociateMemberResponse) => void): Request<Inspector2.Types.DisassociateMemberResponse, AWSError>;
/**
* Enables Amazon Inspector scans for one or more Amazon Web Services accounts.
*/
enable(params: Inspector2.Types.EnableRequest, callback?: (err: AWSError, data: Inspector2.Types.EnableResponse) => void): Request<Inspector2.Types.EnableResponse, AWSError>;
/**
* Enables Amazon Inspector scans for one or more Amazon Web Services accounts.
*/
enable(callback?: (err: AWSError, data: Inspector2.Types.EnableResponse) => void): Request<Inspector2.Types.EnableResponse, AWSError>;
/**
* Enables the Amazon Inspector delegated administrator for your Organizations organization.
*/
enableDelegatedAdminAccount(params: Inspector2.Types.EnableDelegatedAdminAccountRequest, callback?: (err: AWSError, data: Inspector2.Types.EnableDelegatedAdminAccountResponse) => void): Request<Inspector2.Types.EnableDelegatedAdminAccountResponse, AWSError>;
/**
* Enables the Amazon Inspector delegated administrator for your Organizations organization.
*/
enableDelegatedAdminAccount(callback?: (err: AWSError, data: Inspector2.Types.EnableDelegatedAdminAccountResponse) => void): Request<Inspector2.Types.EnableDelegatedAdminAccountResponse, AWSError>;
/**
* Retrieves information about the Amazon Inspector delegated administrator for your organization.
*/
getDelegatedAdminAccount(params: Inspector2.Types.GetDelegatedAdminAccountRequest, callback?: (err: AWSError, data: Inspector2.Types.GetDelegatedAdminAccountResponse) => void): Request<Inspector2.Types.GetDelegatedAdminAccountResponse, AWSError>;
/**
* Retrieves information about the Amazon Inspector delegated administrator for your organization.
*/
getDelegatedAdminAccount(callback?: (err: AWSError, data: Inspector2.Types.GetDelegatedAdminAccountResponse) => void): Request<Inspector2.Types.GetDelegatedAdminAccountResponse, AWSError>;
/**
* Gets the status of a findings report.
*/
getFindingsReportStatus(params: Inspector2.Types.GetFindingsReportStatusRequest, callback?: (err: AWSError, data: Inspector2.Types.GetFindingsReportStatusResponse) => void): Request<Inspector2.Types.GetFindingsReportStatusResponse, AWSError>;
/**
* Gets the status of a findings report.
*/
getFindingsReportStatus(callback?: (err: AWSError, data: Inspector2.Types.GetFindingsReportStatusResponse) => void): Request<Inspector2.Types.GetFindingsReportStatusResponse, AWSError>;
/**
* Gets member information for your organization.
*/
getMember(params: Inspector2.Types.GetMemberRequest, callback?: (err: AWSError, data: Inspector2.Types.GetMemberResponse) => void): Request<Inspector2.Types.GetMemberResponse, AWSError>;
/**
* Gets member information for your organization.
*/
getMember(callback?: (err: AWSError, data: Inspector2.Types.GetMemberResponse) => void): Request<Inspector2.Types.GetMemberResponse, AWSError>;
/**
* Lists the permissions an account has to configure Amazon Inspector.
*/
listAccountPermissions(params: Inspector2.Types.ListAccountPermissionsRequest, callback?: (err: AWSError, data: Inspector2.Types.ListAccountPermissionsResponse) => void): Request<Inspector2.Types.ListAccountPermissionsResponse, AWSError>;
/**
* Lists the permissions an account has to configure Amazon Inspector.
*/
listAccountPermissions(callback?: (err: AWSError, data: Inspector2.Types.ListAccountPermissionsResponse) => void): Request<Inspector2.Types.ListAccountPermissionsResponse, AWSError>;
/**
* Lists coverage details for you environment.
*/
listCoverage(params: Inspector2.Types.ListCoverageRequest, callback?: (err: AWSError, data: Inspector2.Types.ListCoverageResponse) => void): Request<Inspector2.Types.ListCoverageResponse, AWSError>;
/**
* Lists coverage details for you environment.
*/
listCoverage(callback?: (err: AWSError, data: Inspector2.Types.ListCoverageResponse) => void): Request<Inspector2.Types.ListCoverageResponse, AWSError>;
/**
* Lists Amazon Inspector coverage statistics for your environment.
*/
listCoverageStatistics(params: Inspector2.Types.ListCoverageStatisticsRequest, callback?: (err: AWSError, data: Inspector2.Types.ListCoverageStatisticsResponse) => void): Request<Inspector2.Types.ListCoverageStatisticsResponse, AWSError>;
/**
* Lists Amazon Inspector coverage statistics for your environment.
*/
listCoverageStatistics(callback?: (err: AWSError, data: Inspector2.Types.ListCoverageStatisticsResponse) => void): Request<Inspector2.Types.ListCoverageStatisticsResponse, AWSError>;
/**
* Lists information about the Amazon Inspector delegated administrator of your organization.
*/
listDelegatedAdminAccounts(params: Inspector2.Types.ListDelegatedAdminAccountsRequest, callback?: (err: AWSError, data: Inspector2.Types.ListDelegatedAdminAccountsResponse) => void): Request<Inspector2.Types.ListDelegatedAdminAccountsResponse, AWSError>;
/**
* Lists information about the Amazon Inspector delegated administrator of your organization.
*/
listDelegatedAdminAccounts(callback?: (err: AWSError, data: Inspector2.Types.ListDelegatedAdminAccountsResponse) => void): Request<Inspector2.Types.ListDelegatedAdminAccountsResponse, AWSError>;
/**
* Lists the filters associated with your account.
*/
listFilters(params: Inspector2.Types.ListFiltersRequest, callback?: (err: AWSError, data: Inspector2.Types.ListFiltersResponse) => void): Request<Inspector2.Types.ListFiltersResponse, AWSError>;
/**
* Lists the filters associated with your account.
*/
listFilters(callback?: (err: AWSError, data: Inspector2.Types.ListFiltersResponse) => void): Request<Inspector2.Types.ListFiltersResponse, AWSError>;
/**
* Lists aggregated finding data for your environment based on specific criteria.
*/
listFindingAggregations(params: Inspector2.Types.ListFindingAggregationsRequest, callback?: (err: AWSError, data: Inspector2.Types.ListFindingAggregationsResponse) => void): Request<Inspector2.Types.ListFindingAggregationsResponse, AWSError>;
/**
* Lists aggregated finding data for your environment based on specific criteria.
*/
listFindingAggregations(callback?: (err: AWSError, data: Inspector2.Types.ListFindingAggregationsResponse) => void): Request<Inspector2.Types.ListFindingAggregationsResponse, AWSError>;
/**
* Lists findings for your environment.
*/
listFindings(params: Inspector2.Types.ListFindingsRequest, callback?: (err: AWSError, data: Inspector2.Types.ListFindingsResponse) => void): Request<Inspector2.Types.ListFindingsResponse, AWSError>;
/**
* Lists findings for your environment.
*/
listFindings(callback?: (err: AWSError, data: Inspector2.Types.ListFindingsResponse) => void): Request<Inspector2.Types.ListFindingsResponse, AWSError>;
/**
* List members associated with the Amazon Inspector delegated administrator for your organization.
*/
listMembers(params: Inspector2.Types.ListMembersRequest, callback?: (err: AWSError, data: Inspector2.Types.ListMembersResponse) => void): Request<Inspector2.Types.ListMembersResponse, AWSError>;
/**
* List members associated with the Amazon Inspector delegated administrator for your organization.
*/
listMembers(callback?: (err: AWSError, data: Inspector2.Types.ListMembersResponse) => void): Request<Inspector2.Types.ListMembersResponse, AWSError>;
/**
* Lists all tags attached to a given resource.
*/
listTagsForResource(params: Inspector2.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Inspector2.Types.ListTagsForResourceResponse) => void): Request<Inspector2.Types.ListTagsForResourceResponse, AWSError>;
/**
* Lists all tags attached to a given resource.
*/
listTagsForResource(callback?: (err: AWSError, data: Inspector2.Types.ListTagsForResourceResponse) => void): Request<Inspector2.Types.ListTagsForResourceResponse, AWSError>;
/**
* Lists the Amazon Inspector usage totals over the last 30 days.
*/
listUsageTotals(params: Inspector2.Types.ListUsageTotalsRequest, callback?: (err: AWSError, data: Inspector2.Types.ListUsageTotalsResponse) => void): Request<Inspector2.Types.ListUsageTotalsResponse, AWSError>;
/**
* Lists the Amazon Inspector usage totals over the last 30 days.
*/
listUsageTotals(callback?: (err: AWSError, data: Inspector2.Types.ListUsageTotalsResponse) => void): Request<Inspector2.Types.ListUsageTotalsResponse, AWSError>;
/**
* Adds tags to a resource.
*/
tagResource(params: Inspector2.Types.TagResourceRequest, callback?: (err: AWSError, data: Inspector2.Types.TagResourceResponse) => void): Request<Inspector2.Types.TagResourceResponse, AWSError>;
/**
* Adds tags to a resource.
*/
tagResource(callback?: (err: AWSError, data: Inspector2.Types.TagResourceResponse) => void): Request<Inspector2.Types.TagResourceResponse, AWSError>;
/**
* Removes tags from a resource.
*/
untagResource(params: Inspector2.Types.UntagResourceRequest, callback?: (err: AWSError, data: Inspector2.Types.UntagResourceResponse) => void): Request<Inspector2.Types.UntagResourceResponse, AWSError>;
/**
* Removes tags from a resource.
*/
untagResource(callback?: (err: AWSError, data: Inspector2.Types.UntagResourceResponse) => void): Request<Inspector2.Types.UntagResourceResponse, AWSError>;
/**
* Specifies the action that is to be applied to the findings that match the filter.
*/
updateFilter(params: Inspector2.Types.UpdateFilterRequest, callback?: (err: AWSError, data: Inspector2.Types.UpdateFilterResponse) => void): Request<Inspector2.Types.UpdateFilterResponse, AWSError>;
/**
* Specifies the action that is to be applied to the findings that match the filter.
*/
updateFilter(callback?: (err: AWSError, data: Inspector2.Types.UpdateFilterResponse) => void): Request<Inspector2.Types.UpdateFilterResponse, AWSError>;
/**
* Updates the configurations for your Amazon Inspector organization.
*/
updateOrganizationConfiguration(params: Inspector2.Types.UpdateOrganizationConfigurationRequest, callback?: (err: AWSError, data: Inspector2.Types.UpdateOrganizationConfigurationResponse) => void): Request<Inspector2.Types.UpdateOrganizationConfigurationResponse, AWSError>;
/**
* Updates the configurations for your Amazon Inspector organization.
*/
updateOrganizationConfiguration(callback?: (err: AWSError, data: Inspector2.Types.UpdateOrganizationConfigurationResponse) => void): Request<Inspector2.Types.UpdateOrganizationConfigurationResponse, AWSError>;
}
declare namespace Inspector2 {
export interface Account {
/**
* The ID of the Amazon Web Services account.
*/
accountId: AccountId;
/**
* Details of the status of Amazon Inspector scans by resource type.
*/
resourceStatus: ResourceStatus;
/**
* The status of Amazon Inspector for the account.
*/
status: Status;
}
export interface AccountAggregation {
/**
* The type of finding.
*/
findingType?: AggregationFindingType;
/**
* The type of resource.
*/
resourceType?: AggregationResourceType;
/**
* The value to sort by.
*/
sortBy?: AccountSortBy;
/**
* The sort order (ascending or descending).
*/
sortOrder?: SortOrder;
}
export interface AccountAggregationResponse {
/**
* The Amazon Web Services account ID.
*/
accountId?: AccountId;
/**
* The number of findings by severity.
*/
severityCounts?: SeverityCounts;
}
export type AccountId = string;
export type AccountIdSet = AccountId[];
export type AccountList = Account[];
export type AccountSortBy = "CRITICAL"|"HIGH"|"ALL"|string;
export interface AccountState {
/**
* The Amazon Web Services account ID.
*/
accountId: AccountId;
/**
* An object detailing which resources Amazon Inspector is enabled to scan for the account.
*/
resourceState: ResourceState;
/**
* An object detailing the status of Amazon Inspector for the account.
*/
state: State;
}
export type AccountStateList = AccountState[];
export type AggCounts = number;
export type AggregationFindingType = "NETWORK_REACHABILITY"|"PACKAGE_VULNERABILITY"|string;
export interface AggregationRequest {
/**
* An object that contains details about an aggregation request based on Amazon Web Services account IDs.
*/
accountAggregation?: AccountAggregation;
/**
* An object that contains details about an aggregation request based on Amazon Machine Images (AMIs).
*/
amiAggregation?: AmiAggregation;
/**
* An object that contains details about an aggregation request based on Amazon ECR container images.
*/
awsEcrContainerAggregation?: AwsEcrContainerAggregation;
/**
* An object that contains details about an aggregation request based on Amazon EC2 instances.
*/
ec2InstanceAggregation?: Ec2InstanceAggregation;
/**
* An object that contains details about an aggregation request based on finding types.
*/
findingTypeAggregation?: FindingTypeAggregation;
/**
* An object that contains details about an aggregation request based on container image layers.
*/
imageLayerAggregation?: ImageLayerAggregation;
/**
* An object that contains details about an aggregation request based on operating system package type.
*/
packageAggregation?: PackageAggregation;
/**
* An object that contains details about an aggregation request based on Amazon ECR repositories.
*/
repositoryAggregation?: RepositoryAggregation;
/**
* An object that contains details about an aggregation request based on finding title.
*/
titleAggregation?: TitleAggregation;
}
export type AggregationResourceType = "AWS_EC2_INSTANCE"|"AWS_ECR_CONTAINER_IMAGE"|string;
export interface AggregationResponse {
/**
* An object that contains details about an aggregation response based on Amazon Web Services account IDs.
*/
accountAggregation?: AccountAggregationResponse;
/**
* An object that contains details about an aggregation response based on Amazon Machine Images (AMIs).
*/
amiAggregation?: AmiAggregationResponse;
/**
* An object that contains details about an aggregation response based on Amazon ECR container images.
*/
awsEcrContainerAggregation?: AwsEcrContainerAggregationResponse;
/**
* An object that contains details about an aggregation response based on Amazon EC2 instances.
*/
ec2InstanceAggregation?: Ec2InstanceAggregationResponse;
/**
* An object that contains details about an aggregation response based on finding types.
*/
findingTypeAggregation?: FindingTypeAggregationResponse;
/**
* An object that contains details about an aggregation response based on container image layers.
*/
imageLayerAggregation?: ImageLayerAggregationResponse;
/**
* An object that contains details about an aggregation response based on operating system package type.
*/
packageAggregation?: PackageAggregationResponse;
/**
* An object that contains details about an aggregation response based on Amazon ECR repositories.
*/
repositoryAggregation?: RepositoryAggregationResponse;
/**
* An object that contains details about an aggregation response based on finding title.
*/
titleAggregation?: TitleAggregationResponse;
}
export type AggregationResponseList = AggregationResponse[];
export type AggregationType = "FINDING_TYPE"|"PACKAGE"|"TITLE"|"REPOSITORY"|"AMI"|"AWS_EC2_INSTANCE"|"AWS_ECR_CONTAINER"|"IMAGE_LAYER"|"ACCOUNT"|string;
export interface AmiAggregation {
/**
* The IDs of AMIs to aggregate findings for.
*/
amis?: StringFilterList;
/**
* The value to sort results by.
*/
sortBy?: AmiSortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
}
export interface AmiAggregationResponse {
/**
* The Amazon Web Services account ID that the AMI belongs.
*/
accountId?: AccountId;
/**
* The IDs of Amazon EC2 instances using this AMI.
*/
affectedInstances?: Long;
/**
* The ID of the AMI that findings were aggregated for.
*/
ami: AmiId;
/**
* An object that contains the count of matched findings per severity.
*/
severityCounts?: SeverityCounts;
}
export type AmiId = string;
export type AmiSortBy = "CRITICAL"|"HIGH"|"ALL"|"AFFECTED_INSTANCES"|string;
export type Arn = string;
export interface AssociateMemberRequest {
/**
* The Amazon Web Services account ID of the member account to be associated.
*/
accountId: AccountId;
}
export interface AssociateMemberResponse {
/**
* The Amazon Web Services account ID of the successfully associated member account.
*/
accountId: AccountId;
}
export interface AutoEnable {
/**
* Represents whether Amazon EC2 scans are automatically enabled for new members of your Amazon Inspector organization.
*/
ec2: Boolean;
/**
* Represents whether Amazon ECR scans are automatically enabled for new members of your Amazon Inspector organization.
*/
ecr: Boolean;
}
export interface AwsEc2InstanceDetails {
/**
* The IAM instance profile ARN of the Amazon EC2 instance.
*/
iamInstanceProfileArn?: NonEmptyString;
/**
* The image ID of the Amazon EC2 instance.
*/
imageId?: NonEmptyString;
/**
* The IPv4 addresses of the Amazon EC2 instance.
*/
ipV4Addresses?: IpV4AddressList;
/**
* The IPv6 addresses of the Amazon EC2 instance.
*/
ipV6Addresses?: IpV6AddressList;
/**
* The name of the key pair used to launch the Amazon EC2 instance.
*/
keyName?: NonEmptyString;
/**
* The date and time the Amazon EC2 instance was launched at.
*/
launchedAt?: DateTimeTimestamp;
/**
* The platform of the Amazon EC2 instance.
*/
platform?: Platform;
/**
* The subnet ID of the Amazon EC2 instance.
*/
subnetId?: NonEmptyString;
/**
* The type of the Amazon EC2 instance.
*/
type?: NonEmptyString;
/**
* The VPC ID of the Amazon EC2 instance.
*/
vpcId?: NonEmptyString;
}
export interface AwsEcrContainerAggregation {
/**
* The architecture of the containers.
*/
architectures?: StringFilterList;
/**
* The image SHA values.
*/
imageShas?: StringFilterList;
/**
* The image tags.
*/
imageTags?: StringFilterList;
/**
* The container repositories.
*/
repositories?: StringFilterList;
/**
* The container resource IDs.
*/
resourceIds?: StringFilterList;
/**
* The value to sort by.
*/
sortBy?: AwsEcrContainerSortBy;
/**
* The sort order (ascending or descending).
*/
sortOrder?: SortOrder;
}
export interface AwsEcrContainerAggregationResponse {
/**
* The Amazon Web Services account ID of the account that owns the container.
*/
accountId?: AccountId;
/**
* The architecture of the container.
*/
architecture?: String;
/**
* The SHA value of the container image.
*/
imageSha?: String;
/**
* The container image stags.
*/
imageTags?: StringList;
/**
* The container repository.
*/
repository?: String;
/**
* The resource ID of the container.
*/
resourceId: NonEmptyString;
/**
* The number of finding by severity.
*/
severityCounts?: SeverityCounts;
}
export interface AwsEcrContainerImageDetails {
/**
* The architecture of the Amazon ECR container image.
*/
architecture?: NonEmptyString;
/**
* The image author of the Amazon ECR container image.
*/
author?: String;
/**
* The image hash of the Amazon ECR container image.
*/
imageHash: ImageHash;
/**
* The image tags attached to the Amazon ECR container image.
*/
imageTags?: ImageTagList;
/**
* The platform of the Amazon ECR container image.
*/
platform?: Platform;
/**
* The date and time the Amazon ECR container image was pushed.
*/
pushedAt?: DateTimeTimestamp;
/**
* The registry the Amazon ECR container image belongs to.
*/
registry: NonEmptyString;
/**
* The name of the repository the Amazon ECR container image resides in.
*/
repositoryName: NonEmptyString;
}
export type AwsEcrContainerSortBy = "CRITICAL"|"HIGH"|"ALL"|string;
export interface BatchGetAccountStatusRequest {
/**
* The 12-digit Amazon Web Services account IDs of the accounts to retrieve Amazon Inspector status for.
*/
accountIds?: AccountIdSet;
}
export interface BatchGetAccountStatusResponse {
/**
* An array of objects that provide details on the status of Amazon Inspector for each of the requested accounts.
*/
accounts: AccountStateList;
/**
* An array of objects detailing any accounts that failed to enable Amazon Inspector and why.
*/
failedAccounts?: FailedAccountList;
}
export interface BatchGetFreeTrialInfoRequest {
/**
* The account IDs to get free trial status for.
*/
accountIds: BatchGetFreeTrialInfoRequestAccountIdsList;
}
export type BatchGetFreeTrialInfoRequestAccountIdsList = MeteringAccountId[];
export interface BatchGetFreeTrialInfoResponse {
/**
* An array of objects that provide Amazon Inspector free trial details for each of the requested accounts.
*/
accounts: FreeTrialAccountInfoList;
/**
* An array of objects detailing any accounts that free trial data could not be returned for.
*/
failedAccounts: FreeTrialInfoErrorList;
}
export type Boolean = boolean;
export interface CancelFindingsReportRequest {
/**
* The ID of the report to be canceled.
*/
reportId: ReportId;
}
export interface CancelFindingsReportResponse {
/**
* The ID of the canceled report.
*/
reportId: ReportId;
}
export type ClientToken = string;
export type Component = string;
export type ComponentType = string;
export interface Counts {
/**
* The number of resources.
*/
count?: AggCounts;
/**
* The key associated with this group
*/
groupKey?: GroupKey;
}
export type CountsList = Counts[];
export interface CoverageFilterCriteria {
/**
* An array of Amazon Web Services account IDs to return coverage statistics for.
*/
accountId?: CoverageStringFilterList;
/**
* The Amazon EC2 instance tags to filter on.
*/
ec2InstanceTags?: CoverageMapFilterList;
/**
* The Amazon ECR image tags to filter on.
*/
ecrImageTags?: CoverageStringFilterList;
/**
* The Amazon ECR repository name to filter on.
*/
ecrRepositoryName?: CoverageStringFilterList;
/**
* An array of Amazon Web Services resource IDs to return coverage statistics for.
*/
resourceId?: CoverageStringFilterList;
/**
* An array of Amazon Web Services resource types to return coverage statistics for.
*/
resourceType?: CoverageStringFilterList;
/**
* The scan status code to filter on.
*/
scanStatusCode?: CoverageStringFilterList;
/**
* The scan status reason to filter on.
*/
scanStatusReason?: CoverageStringFilterList;
/**
* An array of Amazon Inspector scan types to return coverage statistics for.
*/
scanType?: CoverageStringFilterList;
}
export type CoverageMapComparison = "EQUALS"|string;
export interface CoverageMapFilter {
/**
* The operator to compare coverage on.
*/
comparison: CoverageMapComparison;
/**
* The tag key associated with the coverage map filter.
*/
key: NonEmptyString;
/**
* The tag value associated with the coverage map filter.
*/
value?: NonEmptyString;
}
export type CoverageMapFilterList = CoverageMapFilter[];
export type CoverageResourceType = "AWS_EC2_INSTANCE"|"AWS_ECR_CONTAINER_IMAGE"|"AWS_ECR_REPOSITORY"|string;
export type CoverageStringComparison = "EQUALS"|"NOT_EQUALS"|string;
export interface CoverageStringFilter {
/**
* The operator to compare strings on.
*/
comparison: CoverageStringComparison;
/**
* The value to compare strings on.
*/
value: CoverageStringInput;
}
export type CoverageStringFilterList = CoverageStringFilter[];
export type CoverageStringInput = string;
export interface CoveredResource {
/**
* The Amazon Web Services account ID of the covered resource.
*/
accountId: AccountId;
/**
* The ID of the covered resource.
*/
resourceId: ResourceId;
/**
* An object that contains details about the metadata.
*/
resourceMetadata?: ResourceScanMetadata;
/**
* The type of the covered resource.
*/
resourceType: CoverageResourceType;
/**
* The status of the scan covering the resource.
*/
scanStatus?: ScanStatus;
/**
* The Amazon Inspector scan type covering the resource.
*/
scanType: ScanType;
}
export type CoveredResources = CoveredResource[];
export interface CreateFilterRequest {
/**
* Defines the action that is to be applied to the findings that match the filter.
*/
action: FilterAction;
/**
* A description of the filter.
*/
description?: FilterDescription;
/**
* Defines the criteria to be used in the filter for querying findings.
*/
filterCriteria: FilterCriteria;
/**
* The name of the filter. Minimum length of 3. Maximum length of 64. Valid characters include alphanumeric characters, dot (.), underscore (_), and dash (-). Spaces are not allowed.
*/
name: FilterName;
/**
* A list of tags for the filter.
*/
tags?: TagMap;
}
export interface CreateFilterResponse {
/**
* The Amazon Resource Number (ARN) of the successfully created filter.
*/
arn: FilterArn;
}
export interface CreateFindingsReportRequest {
/**
* The filter criteria to apply to the results of the finding report.
*/
filterCriteria?: FilterCriteria;
/**
* The format to generate the report in.
*/
reportFormat: ReportFormat;
/**
* The Amazon S3 export destination for the report.
*/
s3Destination: Destination;
}
export interface CreateFindingsReportResponse {
/**
* The ID of the report.
*/
reportId?: ReportId;
}
export type Currency = "USD"|string;
export interface CvssScore {
/**
* The base CVSS score used for the finding.
*/
baseScore: Double;
/**
* The vector string of the CVSS score.
*/
scoringVector: NonEmptyString;
/**
* The source of the CVSS score.
*/
source: NonEmptyString;
/**
* The version of CVSS used for the score.
*/
version: NonEmptyString;
}
export interface CvssScoreAdjustment {
/**
* The metric used to adjust the CVSS score.
*/
metric: NonEmptyString;
/**
* The reason the CVSS score has been adjustment.
*/
reason: NonEmptyString;
}
export type CvssScoreAdjustmentList = CvssScoreAdjustment[];
export interface CvssScoreDetails {
/**
* An object that contains details about adjustment Amazon Inspector made to the CVSS score.
*/
adjustments?: CvssScoreAdjustmentList;
/**
* The source of the CVSS data.
*/
cvssSource?: NonEmptyString;
/**
* The CVSS score.
*/
score: Double;
/**
* The source for the CVSS score.
*/
scoreSource: NonEmptyString;
/**
* The vector for the CVSS score.
*/
scoringVector: NonEmptyString;
/**
* The CVSS version used in scoring.
*/
version: NonEmptyString;
}
export type CvssScoreList = CvssScore[];
export interface DateFilter {
/**
* A timestamp representing the end of the time period filtered on.
*/
endInclusive?: Timestamp;
/**
* A timestamp representing the start of the time period filtered on.
*/
startInclusive?: Timestamp;
}
export type DateFilterList = DateFilter[];
export type DateTimeTimestamp = Date;
export interface DelegatedAdmin {
/**
* The Amazon Web Services account ID of the Amazon Inspector delegated administrator for your organization.
*/
accountId?: AccountId;
/**
* The status of the Amazon Inspector delegated administrator.
*/
relationshipStatus?: RelationshipStatus;
}
export interface DelegatedAdminAccount {
/**
* The Amazon Web Services account ID of the Amazon Inspector delegated administrator for your organization.
*/
accountId?: AccountId;
/**
* The status of the Amazon Inspector delegated administrator.
*/
status?: DelegatedAdminStatus;
}
export type DelegatedAdminAccountList = DelegatedAdminAccount[];
export type DelegatedAdminStatus = "ENABLED"|"DISABLE_IN_PROGRESS"|string;
export interface DeleteFilterRequest {
/**
* The Amazon Resource Number (ARN) of the filter to be deleted.
*/
arn: FilterArn;
}
export interface DeleteFilterResponse {
/**
* The Amazon Resource Number (ARN) of the filter that has been deleted.
*/
arn: FilterArn;
}
export interface DescribeOrganizationConfigurationRequest {
}
export interface DescribeOrganizationConfigurationResponse {
/**
* The scan types are automatically enabled for new members of your organization.
*/
autoEnable?: AutoEnable;
/**
* Represents whether your organization has reached the maximum Amazon Web Services account limit for Amazon Inspector.
*/
maxAccountLimitReached?: Boolean;
}
export interface Destination {
/**
* The name of the Amazon S3 bucket to export findings to.
*/
bucketName: String;
/**
* The prefix of the KMS key used to export findings.
*/
keyPrefix?: String;
/**
* The ARN of the KMS key used to encrypt data when exporting findings.
*/
kmsKeyArn: String;
}
export interface DisableDelegatedAdminAccountRequest {
/**
* The Amazon Web Services account ID of the current Amazon Inspector delegated administrator.
*/
delegatedAdminAccountId: AccountId;
}
export interface DisableDelegatedAdminAccountResponse {
/**
* The Amazon Web Services account ID of the successfully disabled delegated administrator.
*/
delegatedAdminAccountId: AccountId;
}
export interface DisableRequest {
/**
* An array of account IDs you want to disable Amazon Inspector scans for.
*/
accountIds?: AccountIdSet;
/**
* The resource scan types you want to disable.
*/
resourceTypes?: DisableResourceTypeList;
}
export type DisableResourceTypeList = ResourceScanType[];
export interface DisableResponse {
/**
* Information on the accounts that have had Amazon Inspector scans successfully disabled. Details are provided for each account.
*/
accounts: AccountList;
/**
* Information on any accounts for which Amazon Inspector scans could not be disabled. Details are provided for each account.
*/
failedAccounts?: FailedAccountList;
}
export interface DisassociateMemberRequest {
/**
* The Amazon Web Services account ID of the member account to disassociate.
*/
accountId: AccountId;
}
export interface DisassociateMemberResponse {
/**
* The Amazon Web Services account ID of the successfully disassociated member.
*/
accountId: AccountId;
}
export type Double = number;
export interface Ec2InstanceAggregation {
/**
* The AMI IDs associated with the Amazon EC2 instances to aggregate findings for.
*/
amis?: StringFilterList;
/**
* The Amazon EC2 instance IDs to aggregate findings for.
*/
instanceIds?: StringFilterList;
/**
* The Amazon EC2 instance tags to aggregate findings for.
*/
instanceTags?: MapFilterList;
/**
* The operating system types to aggregate findings for. Valid values must be uppercase and underscore separated, examples are ORACLE_LINUX_7 and ALPINE_LINUX_3_8.
*/
operatingSystems?: StringFilterList;
/**
* The value to sort results by.
*/
sortBy?: Ec2InstanceSortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
}
export interface Ec2InstanceAggregationResponse {
/**
* The Amazon Web Services account the Amazon EC2 instance belongs to.
*/
accountId?: String;
/**
* The Amazon Machine Image (AMI) of the Amazon EC2 instance.
*/
ami?: AmiId;
/**
* The Amazon EC2 instance ID.
*/
instanceId: NonEmptyString;
/**
* The tags attached to the instance.
*/
instanceTags?: TagMap;
/**
* The number of network findings for the Amazon EC2 instance.
*/
networkFindings?: Long;
/**
* The operating system of the Amazon EC2 instance.
*/
operatingSystem?: String;
/**
* An object that contains the count of matched findings per severity.
*/
severityCounts?: SeverityCounts;
}
export type Ec2InstanceSortBy = "NETWORK_FINDINGS"|"CRITICAL"|"HIGH"|"ALL"|string;
export interface Ec2Metadata {
/**
* The ID of the Amazon Machine Image (AMI) used to launch the instance.
*/
amiId?: AmiId;
/**
* The platform of the instance.
*/
platform?: Ec2Platform;
/**
* The tags attached to the instance.
*/
tags?: TagMap;
}
export type Ec2Platform = "WINDOWS"|"LINUX"|"UNKNOWN"|string;
export interface EcrContainerImageMetadata {
/**
* Tags associated with the Amazon ECR image metadata.
*/
tags?: TagList;
}
export interface EcrRepositoryMetadata {
/**
* The name of the Amazon ECR repository.
*/
name?: String;
/**
* The frequency of scans.
*/
scanFrequency?: EcrScanFrequency;
}
export type EcrScanFrequency = "MANUAL"|"SCAN_ON_PUSH"|"CONTINUOUS_SCAN"|string;
export interface EnableDelegatedAdminAccountRequest {
/**
* The idempotency token for the request.
*/
clientToken?: ClientToken;
/**
* The Amazon Web Services account ID of the Amazon Inspector delegated administrator.
*/
delegatedAdminAccountId: AccountId;
}
export interface EnableDelegatedAdminAccountResponse {
/**
* The Amazon Web Services account ID of the successfully Amazon Inspector delegated administrator.
*/
delegatedAdminAccountId: AccountId;
}
export interface EnableRequest {
/**
* A list of account IDs you want to enable Amazon Inspector scans for.
*/
accountIds?: AccountIdSet;
/**
* The idempotency token for the request.
*/
clientToken?: ClientToken;
/**
* The resource scan types you want to enable.
*/
resourceTypes: EnableResourceTypeList;
}
export type EnableResourceTypeList = ResourceScanType[];
export interface EnableResponse {
/**
* Information on the accounts that have had Amazon Inspector scans successfully enabled. Details are provided for each account.
*/
accounts: AccountList;
/**
* Information on any accounts for which Amazon Inspector scans could not be enabled. Details are provided for each account.
*/
failedAccounts?: FailedAccountList;
}
export type ErrorCode = "ALREADY_ENABLED"|"ENABLE_IN_PROGRESS"|"DISABLE_IN_PROGRESS"|"SUSPEND_IN_PROGRESS"|"RESOURCE_NOT_FOUND"|"ACCESS_DENIED"|"INTERNAL_ERROR"|"SSM_UNAVAILABLE"|"SSM_THROTTLED"|"EVENTBRIDGE_UNAVAILABLE"|"EVENTBRIDGE_THROTTLED"|"RESOURCE_SCAN_NOT_DISABLED"|"DISASSOCIATE_ALL_MEMBERS"|string;
export type ErrorMessage = string;
export type ExternalReportStatus = "SUCCEEDED"|"IN_PROGRESS"|"CANCELLED"|"FAILED"|string;
export interface FailedAccount {
/**
* The Amazon Web Services account ID.
*/
accountId: AccountId;
/**
* The error code explaining why the account failed to enable Amazon Inspector.
*/
errorCode: ErrorCode;
/**
* The error message received when the account failed to enable Amazon Inspector.
*/
errorMessage: NonEmptyString;
/**
* An object detailing which resources Amazon Inspector is enabled to scan for the account.
*/
resourceStatus?: ResourceStatus;
/**
* The status of Amazon Inspector for the account.
*/
status?: Status;
}
export type FailedAccountList = FailedAccount[];
export type FilePath = string;
export interface Filter {
/**
* The action that is to be applied to the findings that match the filter.
*/
action: FilterAction;
/**
* The Amazon Resource Number (ARN) associated with this filter.
*/
arn: FilterArn;
/**
* The date and time this filter was created at.
*/
createdAt: DateTimeTimestamp;
/**
* Details on the filter criteria associated with this filter.
*/
criteria: FilterCriteria;
/**
* A description of the filter.
*/
description?: FilterDescription;
/**
* The name of the filter.
*/
name: FilterName;
/**
* The Amazon Web Services account ID of the account that created the filter.
*/
ownerId: OwnerId;
/**
* The reason for the filter.
*/
reason?: FilterReason;
/**
* The tags attached to the filter.
*/
tags?: TagMap;
/**
* The date and time the filter was last updated at.
*/
updatedAt: DateTimeTimestamp;
}
export type FilterAction = "NONE"|"SUPPRESS"|string;
export type FilterArn = string;
export type FilterArnList = FilterArn[];
export interface FilterCriteria {
/**
* Details of the Amazon Web Services account IDs used to filter findings.
*/
awsAccountId?: StringFilterList;
/**
* Details of the component IDs used to filter findings.
*/
componentId?: StringFilterList;
/**
* Details of the component types used to filter findings.
*/
componentType?: StringFilterList;
/**
* Details of the Amazon EC2 instance image IDs used to filter findings.
*/
ec2InstanceImageId?: StringFilterList;
/**
* Details of the Amazon EC2 instance subnet IDs used to filter findings.
*/
ec2InstanceSubnetId?: StringFilterList;
/**
* Details of the Amazon EC2 instance VPC IDs used to filter findings.
*/
ec2InstanceVpcId?: StringFilterList;
/**
* Details of the Amazon ECR image architecture types used to filter findings.
*/
ecrImageArchitecture?: StringFilterList;
/**
* Details of the Amazon ECR image hashes used to filter findings.
*/
ecrImageHash?: StringFilterList;
/**
* Details on the Amazon ECR image push date and time used to filter findings.
*/
ecrImagePushedAt?: DateFilterList;
/**
* Details on the Amazon ECR registry used to filter findings.
*/
ecrImageRegistry?: StringFilterList;
/**
* Details on the name of the Amazon ECR repository used to filter findings.
*/
ecrImageRepositoryName?: StringFilterList;
/**
* The tags attached to the Amazon ECR container image.
*/
ecrImageTags?: StringFilterList;
/**
* Details on the finding ARNs used to filter findings.
*/
findingArn?: StringFilterList;
/**
* Details on the finding status types used to filter findings.
*/
findingStatus?: StringFilterList;
/**
* Details on the finding types used to filter findings.
*/
findingType?: StringFilterList;
/**
* Details on the date and time a finding was first seen used to filter findings.
*/
firstObservedAt?: DateFilterList;
/**
* The Amazon Inspector score to filter on.
*/
inspectorScore?: NumberFilterList;
/**
* Details on the date and time a finding was last seen used to filter findings.
*/
lastObservedAt?: DateFilterList;
/**
* Details on the ingress source addresses used to filter findings.
*/
networkProtocol?: StringFilterList;
/**
* Details on the port ranges used to filter findings.
*/
portRange?: PortRangeFilterList;
/**
* Details on the related vulnerabilities used to filter findings.
*/
relatedVulnerabilities?: StringFilterList;
/**
* Details on the resource IDs used to filter findings.
*/
resourceId?: StringFilterList;
/**
* Details on the resource tags used to filter findings.
*/
resourceTags?: MapFilterList;
/**
* Details on the resource types used to filter findings.
*/
resourceType?: StringFilterList;
/**
* Details on the severity used to filter findings.
*/
severity?: StringFilterList;
/**
* Details on the finding title used to filter findings.
*/
title?: StringFilterList;
/**
* Details on the date and time a finding was last updated at used to filter findings.
*/
updatedAt?: DateFilterList;
/**
* Details on the vendor severity used to filter findings.
*/
vendorSeverity?: StringFilterList;
/**
* Details on the vulnerability ID used to filter findings.
*/
vulnerabilityId?: StringFilterList;
/**
* Details on the vulnerability type used to filter findings.
*/
vulnerabilitySource?: StringFilterList;
/**
* Details on the vulnerable packages used to filter findings.
*/
vulnerablePackages?: PackageFilterList;
}
export type FilterDescription = string;
export type FilterList = Filter[];
export type FilterName = string;
export type FilterReason = string;
export interface Finding {
/**
* The Amazon Web Services account ID associated with the finding.
*/
awsAccountId: AccountId;
/**
* The description of the finding.
*/
description: FindingDescription;
/**
* The Amazon Resource Number (ARN) of the finding.
*/
findingArn: FindingArn;
/**
* The date and time that the finding was first observed.
*/
firstObservedAt: DateTimeTimestamp;
/**
* The Amazon Inspector score given to the finding.
*/
inspectorScore?: Double;
/**
* An object that contains details of the Amazon Inspector score.
*/
inspectorScoreDetails?: InspectorScoreDetails;
/**
* The date and time that the finding was last observed.
*/
lastObservedAt: DateTimeTimestamp;
/**
* An object that contains the details of a network reachability finding.
*/
networkReachabilityDetails?: NetworkReachabilityDetails;
/**
* An object that contains the details of a package vulnerability finding.
*/
packageVulnerabilityDetails?: PackageVulnerabilityDetails;
/**
* An object that contains the details about how to remediate a finding.
*/
remediation: Remediation;
/**
* Contains information on the resources involved in a finding.
*/
resources: ResourceList;
/**
* The severity of the finding.
*/
severity: Severity;
/**
* The status of the finding.
*/
status: FindingStatus;
/**
* The title of the finding.
*/
title?: FindingTitle;
/**
* The type of the finding.
*/
type: FindingType;
/**
* The date and time the finding was last updated at.
*/
updatedAt?: DateTimeTimestamp;
}
export type FindingArn = string;
export type FindingDescription = string;
export type FindingList = Finding[];
export type FindingStatus = "ACTIVE"|"SUPPRESSED"|"CLOSED"|string;
export type FindingTitle = string;
export type FindingType = "NETWORK_REACHABILITY"|"PACKAGE_VULNERABILITY"|string;
export interface FindingTypeAggregation {
/**
* The finding type to aggregate.
*/
findingType?: AggregationFindingType;
/**
* The resource type to aggregate.
*/
resourceType?: AggregationResourceType;
/**
* The value to sort results by.
*/
sortBy?: FindingTypeSortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
}
export interface FindingTypeAggregationResponse {
/**
* The ID of the Amazon Web Services account associated with the findings.
*/
accountId?: AccountId;
/**
* The value to sort results by.
*/
severityCounts?: SeverityCounts;
}
export type FindingTypeSortBy = "CRITICAL"|"HIGH"|"ALL"|string;
export interface FreeTrialAccountInfo {
/**
* The account associated with the Amazon Inspector free trial information.
*/
accountId: MeteringAccountId;
/**
* Contains information about the Amazon Inspector free trial for an account.
*/
freeTrialInfo: FreeTrialInfoList;
}
export type FreeTrialAccountInfoList = FreeTrialAccountInfo[];
export interface FreeTrialInfo {
/**
* The date and time that the Amazon Inspector free trail ends for a given account.
*/
end: Timestamp;
/**
* The date and time that the Amazon Inspector free trail started for a given account.
*/
start: Timestamp;
/**
* The order to sort results by.
*/
status: FreeTrialStatus;
/**
* The type of scan covered by the Amazon Inspector free trail.
*/
type: FreeTrialType;
}
export interface FreeTrialInfoError {
/**
* The account associated with the Amazon Inspector free trial information.
*/
accountId: MeteringAccountId;
/**
* The error code.
*/
code: FreeTrialInfoErrorCode;
/**
* The error message returned.
*/
message: String;
}
export type FreeTrialInfoErrorCode = "ACCESS_DENIED"|"INTERNAL_ERROR"|string;
export type FreeTrialInfoErrorList = FreeTrialInfoError[];
export type FreeTrialInfoList = FreeTrialInfo[];
export type FreeTrialStatus = "ACTIVE"|"INACTIVE"|string;
export type FreeTrialType = "EC2"|"ECR"|string;
export interface GetDelegatedAdminAccountRequest {
}
export interface GetDelegatedAdminAccountResponse {
/**
* The Amazon Web Services account ID of the Amazon Inspector delegated administrator.
*/
delegatedAdmin?: DelegatedAdmin;
}
export interface GetFindingsReportStatusRequest {
/**
* The ID of the report to retrieve the status of.
*/
reportId?: ReportId;
}
export interface GetFindingsReportStatusResponse {
/**
* The destination of the report.
*/
destination?: Destination;
/**
* The error code of the report.
*/
errorCode?: ReportingErrorCode;
/**
* The error message of the report.
*/
errorMessage?: ErrorMessage;
/**
* The filter criteria associated with the report.
*/
filterCriteria?: FilterCriteria;
/**
* The ID of the report.
*/
reportId?: ReportId;
/**
* The status of the report.
*/
status?: ExternalReportStatus;
}
export interface GetMemberRequest {
/**
* The Amazon Web Services account ID of the member account to retrieve information on.
*/
accountId: AccountId;
}
export interface GetMemberResponse {
/**
* Details of the retrieved member account.
*/
member?: Member;
}
export type GroupKey = "SCAN_STATUS_CODE"|"SCAN_STATUS_REASON"|"ACCOUNT_ID"|"RESOURCE_TYPE"|"ECR_REPOSITORY_NAME"|string;
export type ImageHash = string;
export interface ImageLayerAggregation {
/**
* The hashes associated with the layers.
*/
layerHashes?: StringFilterList;
/**
* The repository associated with the container image hosting the layers.
*/
repositories?: StringFilterList;
/**
* The ID of the container image layer.
*/
resourceIds?: StringFilterList;
/**
* The value to sort results by.
*/
sortBy?: ImageLayerSortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
}
export interface ImageLayerAggregationResponse {
/**
* The ID of the Amazon Web Services account that owns the container image hosting the layer image.
*/
accountId: AccountId;
/**
* The layer hash.
*/
layerHash: NonEmptyString;
/**
* The repository the layer resides in.
*/
repository: NonEmptyString;
/**
* The resource ID of the container image layer.
*/
resourceId: NonEmptyString;
/**
* An object that represents the count of matched findings per severity.
*/
severityCounts?: SeverityCounts;
}
export type ImageLayerSortBy = "CRITICAL"|"HIGH"|"ALL"|string;
export type ImageTagList = NonEmptyString[];
export interface InspectorScoreDetails {
/**
* An object that contains details about the CVSS score given to a finding.
*/
adjustedCvss?: CvssScoreDetails;
}
export type IpV4Address = string;
export type IpV4AddressList = IpV4Address[];
export type IpV6Address = string;
export type IpV6AddressList = IpV6Address[];
export type ListAccountPermissionsMaxResults = number;
export interface ListAccountPermissionsRequest {
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListAccountPermissionsMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
/**
* The service scan type to check permissions for.
*/
service?: Service;
}
export interface ListAccountPermissionsResponse {
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
/**
* Contains details on the permissions an account has to configure Amazon Inspector.
*/
permissions: Permissions;
}
export type ListCoverageMaxResults = number;
export interface ListCoverageRequest {
/**
* An object that contains details on the filters to apply to the coverage data for your environment.
*/
filterCriteria?: CoverageFilterCriteria;
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListCoverageMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export interface ListCoverageResponse {
/**
* An object that contains details on the covered resources in your environment.
*/
coveredResources?: CoveredResources;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export interface ListCoverageStatisticsRequest {
/**
* An object that contains details on the filters to apply to the coverage data for your environment.
*/
filterCriteria?: CoverageFilterCriteria;
/**
* The value to group the results by.
*/
groupBy?: GroupKey;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export interface ListCoverageStatisticsResponse {
/**
* An array with the number for each group.
*/
countsByGroup?: CountsList;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
/**
* The total number for all groups.
*/
totalCounts: Long;
}
export interface ListDelegatedAdminAccountsRequest {
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListDelegatedAdminMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export interface ListDelegatedAdminAccountsResponse {
/**
* Details of the Amazon Inspector delegated administrator of your organization.
*/
delegatedAdminAccounts?: DelegatedAdminAccountList;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export type ListDelegatedAdminMaxResults = number;
export type ListFilterMaxResults = number;
export interface ListFiltersRequest {
/**
* The action the filter applies to matched findings.
*/
action?: FilterAction;
/**
* The Amazon resource number (ARN) of the filter.
*/
arns?: FilterArnList;
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListFilterMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export interface ListFiltersResponse {
/**
* Contains details on the filters associated with your account.
*/
filters: FilterList;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export type ListFindingAggregationsMaxResults = number;
export interface ListFindingAggregationsRequest {
/**
* The Amazon Web Services account IDs to retrieve finding aggregation data for.
*/
accountIds?: StringFilterList;
/**
* Details of the aggregation request that is used to filter your aggregation results.
*/
aggregationRequest?: AggregationRequest;
/**
* The type of the aggregation request.
*/
aggregationType: AggregationType;
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListFindingAggregationsMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export interface ListFindingAggregationsResponse {
/**
* The type of aggregation to perform.
*/
aggregationType: AggregationType;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
/**
* Objects that contain the results of an aggregation operation.
*/
responses?: AggregationResponseList;
}
export type ListFindingsMaxResults = number;
export interface ListFindingsRequest {
/**
* Details on the filters to apply to your finding results.
*/
filterCriteria?: FilterCriteria;
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListFindingsMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
/**
* Details on the sort criteria to apply to your finding results.
*/
sortCriteria?: SortCriteria;
}
export interface ListFindingsResponse {
/**
* Contains details on the findings in your environment.
*/
findings?: FindingList;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
}
export type ListMembersMaxResults = number;
export interface ListMembersRequest {
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListMembersMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: NextToken;
/**
* Specifies whether to list only currently associated members if True or to list all members within the organization if False.
*/
onlyAssociated?: Boolean;
}
export interface ListMembersResponse {
/**
* An object that contains details for each member account.
*/
members?: MemberList;
/**
* The pagination parameter to be used on the next list operation to retrieve more items.
*/
nextToken?: NextToken;
}
export interface ListTagsForResourceRequest {
/**
* The Amazon resource number (ARN) of the resource to list tags of.
*/
resourceArn: Arn;
}
export interface ListTagsForResourceResponse {
/**
* The tags associated with the resource.
*/
tags?: TagMap;
}
export type ListUsageTotalsMaxResults = number;
export type ListUsageTotalsNextToken = string;
export interface ListUsageTotalsRequest {
/**
* The Amazon Web Services account IDs to retrieve usage totals for.
*/
accountIds?: UsageAccountIdList;
/**
* The maximum number of results to return in the response.
*/
maxResults?: ListUsageTotalsMaxResults;
/**
* A token to use for paginating results that are returned in the response. Set the value of this parameter to null for the first request to a list action. For subsequent calls, use the NextToken value returned from the previous request to continue listing results after the first page.
*/
nextToken?: ListUsageTotalsNextToken;
}
export interface ListUsageTotalsResponse {
/**
* The pagination parameter to be used on the next list operation to retrieve more items.
*/
nextToken?: ListUsageTotalsNextToken;
/**
* An object with details on the total usage for the requested account.
*/
totals?: UsageTotalList;
}
export type Long = number;
export type MapComparison = "EQUALS"|string;
export interface MapFilter {
/**
* The operator to use when comparing values in the filter.
*/
comparison: MapComparison;
/**
* The tag key used in the filter.
*/
key: MapKey;
/**
* The tag value used in the filter.
*/
value?: MapValue;
}
export type MapFilterList = MapFilter[];
export type MapKey = string;
export type MapValue = string;
export interface Member {
/**
* The Amazon Web Services account ID of the member account.
*/
accountId?: AccountId;
/**
* The Amazon Web Services account ID of the Amazon Inspector delegated administrator for this member account.
*/
delegatedAdminAccountId?: AccountId;
/**
* The status of the member account.
*/
relationshipStatus?: RelationshipStatus;
/**
* A timestamp showing when the status of this member was last updated.
*/
updatedAt?: DateTimeTimestamp;
}
export type MemberList = Member[];
export type MeteringAccountId = string;
export type MonthlyCostEstimate = number;
export interface NetworkPath {
/**
* The details on the steps in the network path.
*/
steps?: StepList;
}
export type NetworkProtocol = "TCP"|"UDP"|string;
export interface NetworkReachabilityDetails {
/**
* An object that contains details about a network path associated with a finding.
*/
networkPath: NetworkPath;
/**
* An object that contains details about the open port range associated with a finding.
*/
openPortRange: PortRange;
/**
* The protocol associated with a finding.
*/
protocol: NetworkProtocol;
}
export type NextToken = string;
export type NonEmptyString = string;
export type NonEmptyStringList = NonEmptyString[];
export interface NumberFilter {
/**
* The lowest number to be included in the filter.
*/
lowerInclusive?: Double;
/**
* The highest number to be included in the filter.
*/
upperInclusive?: Double;
}
export type NumberFilterList = NumberFilter[];
export type Operation = "ENABLE_SCANNING"|"DISABLE_SCANNING"|"ENABLE_REPOSITORY"|"DISABLE_REPOSITORY"|string;
export type OwnerId = string;
export interface PackageAggregation {
/**
* The names of packages to aggregate findings on.
*/
packageNames?: StringFilterList;
/**
* The value to sort results by.
*/
sortBy?: PackageSortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
}
export interface PackageAggregationResponse {
/**
* The ID of the Amazon Web Services account associated with the findings.
*/
accountId?: AccountId;
/**
* The name of the operating system package.
*/
packageName: NonEmptyString;
/**
* An object that contains the count of matched findings per severity.
*/
severityCounts?: SeverityCounts;
}
export type PackageArchitecture = string;
export type PackageEpoch = number;
export interface PackageFilter {
/**
* An object that contains details on the package architecture type to filter on.
*/
architecture?: StringFilter;
/**
* An object that contains details on the package epoch to filter on.
*/
epoch?: NumberFilter;
/**
* An object that contains details on the name of the package to filter on.
*/
name?: StringFilter;
/**
* An object that contains details on the package release to filter on.
*/
release?: StringFilter;
/**
* An object that contains details on the source layer hash to filter on.
*/
sourceLayerHash?: StringFilter;
/**
* The package version to filter on.
*/
version?: StringFilter;
}
export type PackageFilterList = PackageFilter[];
export type PackageManager = "BUNDLER"|"CARGO"|"COMPOSER"|"NPM"|"NUGET"|"PIPENV"|"POETRY"|"YARN"|"GOBINARY"|"GOMOD"|"JAR"|"OS"|string;
export type PackageName = string;
export type PackageRelease = string;
export type PackageSortBy = "CRITICAL"|"HIGH"|"ALL"|string;
export type PackageVersion = string;
export interface PackageVulnerabilityDetails {
/**
* An object that contains details about the CVSS score of a finding.
*/
cvss?: CvssScoreList;
/**
* One or more URLs that contain details about this vulnerability type.
*/
referenceUrls?: NonEmptyStringList;
/**
* One or more vulnerabilities related to the one identified in this finding.
*/
relatedVulnerabilities?: VulnerabilityIdList;
/**
* The source of the vulnerability information.
*/
source: NonEmptyString;
/**
* A URL to the source of the vulnerability information.
*/
sourceUrl?: NonEmptyString;
/**
* The date and time that this vulnerability was first added to the vendor's database.
*/
vendorCreatedAt?: DateTimeTimestamp;
/**
* The severity the vendor has given to this vulnerability type.
*/
vendorSeverity?: NonEmptyString;
/**
* The date and time the vendor last updated this vulnerability in their database.
*/
vendorUpdatedAt?: DateTimeTimestamp;
/**
* The ID given to this vulnerability.
*/
vulnerabilityId: VulnerabilityId;
/**
* The packages impacted by this vulnerability.
*/
vulnerablePackages: VulnerablePackageList;
}
export interface Permission {
/**
* The operations that can be performed with the given permissions.
*/
operation: Operation;
/**
* The services that the permissions allow an account to perform the given operations for.
*/
service: Service;
}
export type Permissions = Permission[];
export type Platform = string;
export type Port = number;
export interface PortRange {
/**
* The beginning port in a port range.
*/
begin: Port;
/**
* The ending port in a port range.
*/
end: Port;
}
export interface PortRangeFilter {
/**
* The port number the port range begins at.
*/
beginInclusive?: Port;
/**
* The port number the port range ends at.
*/
endInclusive?: Port;
}
export type PortRangeFilterList = PortRangeFilter[];
export interface Recommendation {
/**
* The URL address to the CVE remediation recommendations.
*/
Url?: NonEmptyString;
/**
* The recommended course of action to remediate the finding.
*/
text?: NonEmptyString;
}
export type RelationshipStatus = "CREATED"|"INVITED"|"DISABLED"|"ENABLED"|"REMOVED"|"RESIGNED"|"DELETED"|"EMAIL_VERIFICATION_IN_PROGRESS"|"EMAIL_VERIFICATION_FAILED"|"REGION_DISABLED"|"ACCOUNT_SUSPENDED"|"CANNOT_CREATE_DETECTOR_IN_ORG_MASTER"|string;
export interface Remediation {
/**
* An object that contains information about the recommended course of action to remediate the finding.
*/
recommendation?: Recommendation;
}
export type ReportFormat = "CSV"|"JSON"|string;
export type ReportId = string;
export type ReportingErrorCode = "INTERNAL_ERROR"|"INVALID_PERMISSIONS"|string;
export interface RepositoryAggregation {
/**
* The names of repositories to aggregate findings on.
*/
repositories?: StringFilterList;
/**
* The value to sort results by.
*/
sortBy?: RepositorySortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
}
export interface RepositoryAggregationResponse {
/**
* The ID of the Amazon Web Services account associated with the findings.
*/
accountId?: AccountId;
/**
* The number of container images impacted by the findings.
*/
affectedImages?: Long;
/**
* The name of the repository associated with the findings.
*/
repository: NonEmptyString;
/**
* An object that represent the count of matched findings per severity.
*/
severityCounts?: SeverityCounts;
}
export type RepositorySortBy = "CRITICAL"|"HIGH"|"ALL"|"AFFECTED_IMAGES"|string;
export interface Resource {
/**
* An object that contains details about the resource involved in a finding.
*/
details?: ResourceDetails;
/**
* The ID of the resource.
*/
id: NonEmptyString;
/**
* The partition of the resource.
*/
partition?: NonEmptyString;
/**
* The Amazon Web Services Region the impacted resource is located in.
*/
region?: NonEmptyString;
/**
* The tags attached to the resource.
*/
tags?: TagMap;
/**
* The type of resource.
*/
type: ResourceType;
}
export interface ResourceDetails {
/**
* An object that contains details about the Amazon EC2 instance involved in the finding.
*/
awsEc2Instance?: AwsEc2InstanceDetails;
/**
* An object that contains details about the Amazon ECR container image involved in the finding.
*/
awsEcrContainerImage?: AwsEcrContainerImageDetails;
}
export type ResourceId = string;
export type ResourceList = Resource[];
export interface ResourceScanMetadata {
/**
* An object that contains metadata details for an Amazon EC2 instance.
*/
ec2?: Ec2Metadata;
/**
* An object that contains details about the container metadata for an Amazon ECR image.
*/
ecrImage?: EcrContainerImageMetadata;
/**
* An object that contains details about the repository an Amazon ECR image resides in.
*/
ecrRepository?: EcrRepositoryMetadata;
}
export type ResourceScanType = "EC2"|"ECR"|string;
export interface ResourceState {
/**
* An object detailing the state of Amazon Inspector scanning for Amazon EC2 resources.
*/
ec2: State;
/**
* An object detailing the state of Amazon Inspector scanning for Amazon ECR resources.
*/
ecr: State;
}
export interface ResourceStatus {
/**
* The status of Amazon Inspector scanning for Amazon EC2 resources.
*/
ec2: Status;
/**
* The status of Amazon Inspector scanning for Amazon ECR resources.
*/
ecr: Status;
}
export type ResourceType = "AWS_EC2_INSTANCE"|"AWS_ECR_CONTAINER_IMAGE"|"AWS_ECR_REPOSITORY"|string;
export interface ScanStatus {
/**
* The reason for the scan.
*/
reason: ScanStatusReason;
/**
* The status code of the scan.
*/
statusCode: ScanStatusCode;
}
export type ScanStatusCode = "ACTIVE"|"INACTIVE"|string;
export type ScanStatusReason = "PENDING_INITIAL_SCAN"|"ACCESS_DENIED"|"INTERNAL_ERROR"|"UNMANAGED_EC2_INSTANCE"|"UNSUPPORTED_OS"|"SCAN_ELIGIBILITY_EXPIRED"|"RESOURCE_TERMINATED"|"SUCCESSFUL"|"NO_RESOURCES_FOUND"|"IMAGE_SIZE_EXCEEDED"|"SCAN_FREQUENCY_MANUAL"|"SCAN_FREQUENCY_SCAN_ON_PUSH"|"EC2_INSTANCE_STOPPED"|string;
export type ScanType = "NETWORK"|"PACKAGE"|string;
export type Service = "EC2"|"ECR"|string;
export type Severity = "INFORMATIONAL"|"LOW"|"MEDIUM"|"HIGH"|"CRITICAL"|"UNTRIAGED"|string;
export interface SeverityCounts {
/**
* The total count of findings from all severities.
*/
all?: Long;
/**
* The total count of critical severity findings.
*/
critical?: Long;
/**
* The total count of high severity findings.
*/
high?: Long;
/**
* The total count of medium severity findings.
*/
medium?: Long;
}
export interface SortCriteria {
/**
* The finding detail field by which results are sorted.
*/
field: SortField;
/**
* The order by which findings are sorted.
*/
sortOrder: SortOrder;
}
export type SortField = "AWS_ACCOUNT_ID"|"FINDING_TYPE"|"SEVERITY"|"FIRST_OBSERVED_AT"|"LAST_OBSERVED_AT"|"FINDING_STATUS"|"RESOURCE_TYPE"|"ECR_IMAGE_PUSHED_AT"|"ECR_IMAGE_REPOSITORY_NAME"|"ECR_IMAGE_REGISTRY"|"NETWORK_PROTOCOL"|"COMPONENT_TYPE"|"VULNERABILITY_ID"|"VULNERABILITY_SOURCE"|"INSPECTOR_SCORE"|"VENDOR_SEVERITY"|string;
export type SortOrder = "ASC"|"DESC"|string;
export type SourceLayerHash = string;
export interface State {
/**
* The error code explaining why the account failed to enable Amazon Inspector.
*/
errorCode: ErrorCode;
/**
* The error message received when the account failed to enable Amazon Inspector.
*/
errorMessage: NonEmptyString;
/**
* The status of Amazon Inspector for the account.
*/
status: Status;
}
export type Status = "ENABLING"|"ENABLED"|"DISABLING"|"DISABLED"|"SUSPENDING"|"SUSPENDED"|string;
export interface Step {
/**
* The component ID.
*/
componentId: Component;
/**
* The component type.
*/
componentType: ComponentType;
}
export type StepList = Step[];
export type String = string;
export type StringComparison = "EQUALS"|"PREFIX"|"NOT_EQUALS"|string;
export interface StringFilter {
/**
* The operator to use when comparing values in the filter
*/
comparison: StringComparison;
/**
* The value to filter on.
*/
value: StringInput;
}
export type StringFilterList = StringFilter[];
export type StringInput = string;
export type StringList = NonEmptyString[];
export type TagKey = string;
export type TagKeyList = TagKey[];
export type TagList = String[];
export type TagMap = {[key: string]: MapValue};
export interface TagResourceRequest {
/**
* The Amazon Resource Name (ARN) of the resource to apply a tag to.
*/
resourceArn: Arn;
/**
* The tags to be added to a resource.
*/
tags: TagMap;
}
export interface TagResourceResponse {
}
export type Timestamp = Date;
export interface TitleAggregation {
/**
* The resource type to aggregate on.
*/
resourceType?: AggregationResourceType;
/**
* The value to sort results by.
*/
sortBy?: TitleSortBy;
/**
* The order to sort results by.
*/
sortOrder?: SortOrder;
/**
* The finding titles to aggregate on.
*/
titles?: StringFilterList;
/**
* The vulnerability IDs of the findings.
*/
vulnerabilityIds?: StringFilterList;
}
export interface TitleAggregationResponse {
/**
* The ID of the Amazon Web Services account associated with the findings.
*/
accountId?: AccountId;
/**
* An object that represent the count of matched findings per severity.
*/
severityCounts?: SeverityCounts;
/**
* The title that the findings were aggregated on.
*/
title: NonEmptyString;
/**
* The vulnerability ID of the finding.
*/
vulnerabilityId?: String;
}
export type TitleSortBy = "CRITICAL"|"HIGH"|"ALL"|string;
export interface UntagResourceRequest {
/**
* The Amazon Resource Name (ARN) for the resource to remove tags from.
*/
resourceArn: Arn;
/**
* The tag keys to remove from the resource.
*/
tagKeys: TagKeyList;
}
export interface UntagResourceResponse {
}
export interface UpdateFilterRequest {
/**
* Specifies the action that is to be applied to the findings that match the filter.
*/
action?: FilterAction;
/**
* A description of the filter.
*/
description?: FilterDescription;
/**
* The Amazon Resource Number (ARN) of the filter to update.
*/
filterArn: FilterArn;
/**
* Defines the criteria to be update in the filter.
*/
filterCriteria?: FilterCriteria;
/**
* The name of the filter.
*/
name?: FilterName;
}
export interface UpdateFilterResponse {
/**
* The Amazon Resource Number (ARN) of the successfully updated filter.
*/
arn: FilterArn;
}
export interface UpdateOrganizationConfigurationRequest {
/**
* Defines which scan types are enabled automatically for new members of your Amazon Inspector organization.
*/
autoEnable: AutoEnable;
}
export interface UpdateOrganizationConfigurationResponse {
/**
* The updated status of scan types automatically enabled for new members of your Amazon Inspector organization.
*/
autoEnable: AutoEnable;
}
export interface Usage {
/**
* The currency type used when calculating usage data.
*/
currency?: Currency;
/**
* The estimated monthly cost of Amazon Inspector.
*/
estimatedMonthlyCost?: MonthlyCostEstimate;
/**
* The total of usage.
*/
total?: UsageValue;
/**
* The type scan.
*/
type?: UsageType;
}
export type UsageAccountId = string;
export type UsageAccountIdList = UsageAccountId[];
export type UsageList = Usage[];
export interface UsageTotal {
/**
* The account ID of the account that usage data was retrieved for.
*/
accountId?: MeteringAccountId;
/**
* An object representing the total usage for an account.
*/
usage?: UsageList;
}
export type UsageTotalList = UsageTotal[];
export type UsageType = "EC2_INSTANCE_HOURS"|"ECR_INITIAL_SCAN"|"ECR_RESCAN"|string;
export type UsageValue = number;
export type VulnerabilityId = string;
export type VulnerabilityIdList = VulnerabilityId[];
export interface VulnerablePackage {
/**
* The architecture of the vulnerable package.
*/
arch?: PackageArchitecture;
/**
* The epoch of the vulnerable package.
*/
epoch?: PackageEpoch;
/**
* The file path of the vulnerable package.
*/
filePath?: FilePath;
/**
* The version of the package that contains the vulnerability fix.
*/
fixedInVersion?: PackageVersion;
/**
* The name of the vulnerable package.
*/
name: PackageName;
/**
* The package manager of the vulnerable package.
*/
packageManager?: PackageManager;
/**
* The release of the vulnerable package.
*/
release?: PackageRelease;
/**
* The source layer hash of the vulnerable package.
*/
sourceLayerHash?: SourceLayerHash;
/**
* The version of the vulnerable package.
*/
version: PackageVersion;
}
export type VulnerablePackageList = VulnerablePackage[];
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2020-06-08"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Inspector2 client.
*/
export import Types = Inspector2;
}
export = Inspector2; | the_stack |
import {TensorContainer, TensorContainerArray, TensorContainerObject} from '@tensorflow/tfjs-core';
import {iteratorFromConcatenated, iteratorFromConcatenatedFunction, iteratorFromFunction, iteratorFromIncrementing, iteratorFromItems, iteratorFromZipped, LazyIterator, ZipMismatchMode} from './lazy_iterator';
export class TestIntegerIterator extends LazyIterator<number> {
currentIndex = 0;
data: number[];
constructor(protected readonly length = 100) {
super();
this.data = Array.from({length}, (v, k) => k);
}
summary() {
return `TestIntegers`;
}
async next(): Promise<IteratorResult<number>> {
if (this.currentIndex >= this.length) {
return {value: null, done: true};
}
const result = this.data[this.currentIndex];
this.currentIndex++;
// Sleep for a millisecond every so often.
// This purposely scrambles the order in which these promises are resolved,
// to demonstrate that the various methods still process the stream
// in the correct order.
if (Math.random() < 0.1) {
await new Promise(res => setTimeout(res, 1));
}
return {value: result, done: false};
}
}
describe('LazyIterator', () => {
it('collects all stream elements into an array', async () => {
const readIterator = new TestIntegerIterator();
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(100);
});
it('reads chunks in order', async () => {
const readIterator = new TestIntegerIterator();
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(100);
for (let i = 0; i < 100; i++) {
expect(result[i]).toEqual(i);
}
});
it('filters elements', async () => {
const readIterator = new TestIntegerIterator().filter(x => x % 2 === 0);
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(50);
for (let i = 0; i < 50; i++) {
expect(result[i]).toEqual(2 * i);
}
});
it('maps elements', async () => {
const readIterator = new TestIntegerIterator().map(x => `item ${x}`);
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(100);
for (let i = 0; i < 100; i++) {
expect(result[i]).toEqual(`item ${i}`);
}
});
it('maps elements through an async function', async () => {
const readIterator = new TestIntegerIterator().mapAsync(async x => {
// Sleep for a millisecond every so often.
// This purposely scrambles the order in which these promises are
// resolved, to demonstrate that we still process the
// stream in the correct order.
if (Math.random() < 0.1) {
await new Promise(res => setTimeout(res, 1));
}
return Promise.resolve(`item ${x}`);
});
// It's important to prefetch in order to test the promise randomization
// above. Note collect() already prefetches by default, but here we do it
// explicitly anyway just to be extra clear.
const result = await readIterator.prefetch(200).toArray();
expect(result.length).toEqual(100);
for (let i = 0; i < 100; i++) {
expect(result[i]).toEqual(`item ${i}`);
}
});
it('flatmaps simple elements', async () => {
const readStream = new TestIntegerIterator().flatmap(
x => [`item ${x} A`, `item ${x} B`, `item ${x} C`]);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(300);
for (let i = 0; i < 100; i++) {
expect(result[3 * i + 0]).toEqual(`item ${i} A`);
expect(result[3 * i + 1]).toEqual(`item ${i} B`);
expect(result[3 * i + 2]).toEqual(`item ${i} C`);
}
});
it('flatmap flattens object elements but not their contents', async () => {
const readStream = new TestIntegerIterator().flatmap(
x =>
[{foo: `foo ${x} A`, bar: `bar ${x} A`},
{foo: `foo ${x} B`, bar: `bar ${x} B`},
{foo: `foo ${x} C`, bar: `bar ${x} C`},
]);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(300);
for (let i = 0; i < 100; i++) {
expect(result[3 * i + 0]).toEqual({foo: `foo ${i} A`, bar: `bar ${i} A`});
expect(result[3 * i + 1]).toEqual({foo: `foo ${i} B`, bar: `bar ${i} B`});
expect(result[3 * i + 2]).toEqual({foo: `foo ${i} C`, bar: `bar ${i} C`});
}
});
it('flatmap flattens array elements but not their contents', async () => {
const readStream = new TestIntegerIterator().flatmap(
x => [
[`foo ${x} A`, `bar ${x} A`],
[`foo ${x} B`, `bar ${x} B`],
[`foo ${x} C`, `bar ${x} C`],
]);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(300);
for (let i = 0; i < 100; i++) {
expect(result[3 * i + 0]).toEqual([`foo ${i} A`, `bar ${i} A`]);
expect(result[3 * i + 1]).toEqual([`foo ${i} B`, `bar ${i} B`]);
expect(result[3 * i + 2]).toEqual([`foo ${i} C`, `bar ${i} C`]);
}
});
it('batches elements to a row-major representation', async () => {
const readIterator = new TestIntegerIterator().rowMajorBatch(8);
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(13);
for (let i = 0; i < 12; i++) {
expect(result[i]).toEqual(Array.from({length: 8}, (v, k) => (i * 8) + k));
}
expect(result[12]).toEqual([96, 97, 98, 99]);
});
it('batches elements to a column-major representation', async () => {
const readIterator = new TestIntegerIterator().columnMajorBatch(8);
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(13);
for (let i = 0; i < 12; i++) {
expect(result[i]).toEqual(Array.from({length: 8}, (v, k) => (i * 8) + k));
}
expect(result[12]).toEqual([96, 97, 98, 99]);
});
it('can be limited to a certain number of elements', async () => {
const readIterator = new TestIntegerIterator().take(8);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
});
it('is unaltered by a negative or undefined take() count.', async () => {
const baseIterator = new TestIntegerIterator();
const readIterator = baseIterator.take(-1);
const result = await readIterator.toArrayForTest();
expect(result).toEqual(baseIterator.data);
const baseIterator2 = new TestIntegerIterator();
const readIterator2 = baseIterator2.take(undefined);
const result2 = await readIterator2.toArrayForTest();
expect(result2).toEqual(baseIterator2.data);
});
it('can skip a certain number of elements', async () => {
const readIterator = new TestIntegerIterator().skip(88).take(8);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([88, 89, 90, 91, 92, 93, 94, 95]);
});
it('is unaltered by a negative or undefined skip() count.', async () => {
const baseIterator = new TestIntegerIterator();
const readIterator = baseIterator.skip(-1);
const result = await readIterator.toArrayForTest();
expect(result).toEqual(baseIterator.data);
const baseIterator2 = new TestIntegerIterator();
const readIterator2 = baseIterator2.skip(undefined);
const result2 = await readIterator2.toArrayForTest();
expect(result2).toEqual(baseIterator2.data);
});
it('can selectively ignore upstream errors', async () => {
const readIterator = new TestIntegerIterator().take(10).map(x => {
if (x % 2 === 0) {
throw new Error('Oh no, an even number!');
}
return x;
});
// The 'true' response means the iterator should continue.
const errorIgnoringIterator = readIterator.handleErrors((e) => true);
const result = await errorIgnoringIterator.toArrayForTest();
expect(result).toEqual([1, 3, 5, 7, 9]);
});
it('can terminate cleanly based on upstream errors', async () => {
const readIterator = new TestIntegerIterator().map(x => {
if (x % 2 === 0) {
throw new Error(`Oh no, an even number: ${x}`);
}
return x;
});
// The 'true' response means the iterator should continue.
// But in the case of 10, return false, terminating the stream.
const errorHandlingIterator = readIterator.handleErrors(
(e) => e.message !== 'Oh no, an even number: 10');
const result = await errorHandlingIterator.toArrayForTest();
expect(result).toEqual([1, 3, 5, 7, 9]);
});
it('can selectively propagate upstream errors', async done => {
const readIterator = new TestIntegerIterator().map(x => {
if (x % 2 === 0) {
throw new Error(`Oh no, an even number: ${x}`);
}
return x;
});
const errorHandlingIterator = readIterator.handleErrors((e) => {
if (e.message === 'Oh no, an even number: 2') {
throw e;
}
return true;
});
try {
// Using toArray() rather than toArrayForTest(). The prefetch in
// the latter, in combination with expecting an exception, causes
// unrelated tests to fail (See
// https://github.com/tensorflow/tfjs/issues/1330.
await errorHandlingIterator.toArray();
done.fail();
} catch (e) {
expect(e.message).toEqual('Oh no, an even number: 2');
done();
}
});
it('can be forced to execute serially', async () => {
// This is like FilterIterator, except that it does not enforce serial
// execution. For testing.
class ParallelFilterIterator<T> extends LazyIterator<T> {
constructor(
protected upstream: LazyIterator<T>,
protected predicate: (value: T) => boolean) {
super();
}
summary() {
return `${this.upstream.summary} -> ParallelFilterIterator`;
}
async next(): Promise<IteratorResult<T>> {
while (true) {
const item = await this.upstream.next();
if (item.done || this.predicate(item.value)) {
return item;
}
}
}
}
const newReadIterator = () =>
new ParallelFilterIterator((new TestIntegerIterator()).take(10), x => {
return x % 2 === 0;
});
// Without enforcing serial execution, order gets scrambled; consequently
// the done signal arrives before any of the accepted elements!
const badResult = await newReadIterator().toArrayForTest();
expect(badResult).toEqual([0]);
// But with serial execution, everything is fine.
const goodResult = await newReadIterator().serial().toArrayForTest();
expect(goodResult).toEqual([0, 2, 4, 6, 8]);
});
it('can be created from an array', async () => {
const readIterator = iteratorFromItems([1, 2, 3, 4, 5, 6]);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([1, 2, 3, 4, 5, 6]);
});
it('can be created from a function', async () => {
let i = -1;
const func = () =>
++i < 7 ? {value: i, done: false} : {value: null, done: true};
const readIterator = iteratorFromFunction(func);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
it('can be created with incrementing integers', async () => {
const readIterator = iteratorFromIncrementing(0).take(7);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
it('can be concatenated', async () => {
const a = iteratorFromItems([1, 2, 3]);
const b = iteratorFromItems([4, 5, 6]);
const readIterator = a.concatenate(b);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([1, 2, 3, 4, 5, 6]);
});
it('can be concatenated after skipping', async () => {
const a = iteratorFromItems([1, 2, 3]);
const b = iteratorFromItems([4, 5, 6]);
const readIterator = a.skip(1).concatenate(b);
const result = await readIterator.toArrayForTest();
expect(result).toEqual([2, 3, 4, 5, 6]);
});
it('can be created by concatenating streams', async () => {
const a = new TestIntegerIterator();
const b = new TestIntegerIterator();
const readIterator = iteratorFromConcatenated(iteratorFromItems([a, b]));
const result = await readIterator.toArrayForTest();
expect(result.length).toEqual(200);
});
it('can be created by concatenating streams from a function', async () => {
const readIterator = iteratorFromConcatenatedFunction(
() => ({value: new TestIntegerIterator(), done: false}), 3);
const expectedResult: number[] = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 100; j++) {
expectedResult[i * 100 + j] = j;
}
}
const result = await readIterator.toArrayForTest();
expect(result).toEqual(expectedResult);
});
it('can be created by zipping an array of streams', async () => {
const a = new TestIntegerIterator();
const b = new TestIntegerIterator().map(x => x * 10);
const c = new TestIntegerIterator().map(x => `string ${x}`);
const readStream = iteratorFromZipped([a, b, c]);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(100);
// each result has the form [x, x * 10, 'string ' + x]
for (const e of result) {
const ee = e as TensorContainerArray;
expect(ee[1]).toEqual(ee[0] as number * 10);
expect(ee[2]).toEqual(`string ${ee[0]}`);
}
});
it('can be created by zipping a dict of streams', async () => {
const a = new TestIntegerIterator();
const b = new TestIntegerIterator().map(x => x * 10);
const c = new TestIntegerIterator().map(x => `string ${x}`);
const readStream = iteratorFromZipped({a, b, c});
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(100);
// each result has the form {a: x, b: x * 10, c: 'string ' + x}
for (const e of result) {
const ee = e as TensorContainerObject;
expect(ee['b']).toEqual(ee['a'] as number * 10);
expect(ee['c']).toEqual(`string ${ee['a']}`);
}
});
it('can be created by zipping a nested structure of streams', async () => {
const a = new TestIntegerIterator().map(x => ({'a': x, 'constant': 12}));
const b = new TestIntegerIterator().map(
x => ({'b': x * 10, 'array': [x * 100, x * 200]}));
const c = new TestIntegerIterator().map(x => ({'c': `string ${x}`}));
const readStream = iteratorFromZipped([a, b, c]);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(100);
// each result has the form
// [
// {a: x, 'constant': 12}
// {b: x * 10, 'array': [x * 100, x * 200]},
// {c: 'string ' + x}
// ]
for (const e of result) {
const ee = e as TensorContainerArray;
const aa = ee[0] as TensorContainerObject;
const bb = ee[1] as TensorContainerObject;
const cc = ee[2] as TensorContainerObject;
expect(aa['constant']).toEqual(12);
expect(bb['b']).toEqual(aa['a'] as number * 10);
expect(bb['array']).toEqual([
aa['a'] as number * 100, aa['a'] as number * 200
]);
expect(cc['c']).toEqual(`string ${aa['a']}`);
}
});
it('zip requires streams of the same length by default', async done => {
try {
const a = new TestIntegerIterator(10);
const b = new TestIntegerIterator(3);
const c = new TestIntegerIterator(2);
const readStream = iteratorFromZipped([a, b, c]);
// Using toArray() rather than toArrayForTest(). The prefetch in
// the latter, in combination with expecting an exception, causes
// unrelated tests to fail (See
// https://github.com/tensorflow/tfjs/issues/1330.
await readStream.toArray();
done.fail();
} catch (error) {
expect(error.message)
.toBe(
'Zipped streams should have the same length. ' +
'Mismatched at element 2.');
done();
}
});
it('zip can be told to terminate when the shortest stream terminates',
async () => {
const a = new TestIntegerIterator(10);
const b = new TestIntegerIterator(3);
const c = new TestIntegerIterator(2);
const readStream =
iteratorFromZipped([a, b, c], ZipMismatchMode.SHORTEST);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(2);
});
it('zip can be told to terminate when the longest stream terminates',
async () => {
const a = new TestIntegerIterator(10);
const b = new TestIntegerIterator(3);
const c = new TestIntegerIterator(2);
const readStream =
iteratorFromZipped([a, b, c], ZipMismatchMode.LONGEST);
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(10);
expect(result[9]).toEqual([9, null, null]);
});
/**
* This test demonstrates behavior that is intrinsic to the tf.data zip()
* API, but that may not be what users ultimately want when zipping dicts.
* This may merit a convenience function (e.g., maybe flatZip()).
*/
it('zipping TensorContainer streams requires manual merge', async () => {
function naiveMerge(xs: TensorContainer[]): TensorContainer {
const result = {};
for (const x of xs) {
// For now, we do nothing to detect name collisions here
Object.assign(result, x);
}
return result;
}
const a = new TestIntegerIterator().map(x => ({'a': x}));
const b = new TestIntegerIterator().map(x => ({'b': x * 10}));
const c = new TestIntegerIterator().map(x => ({'c': `string ${x}`}));
const zippedStream = iteratorFromZipped([a, b, c]);
// At first, each result has the form
// [{a: x}, {b: x * 10}, {c: 'string ' + x}]
const readStream =
zippedStream.map(e => naiveMerge(e as TensorContainerArray));
// Now each result has the form {a: x, b: x * 10, c: 'string ' + x}
const result = await readStream.toArrayForTest();
expect(result.length).toEqual(100);
for (const e of result) {
const ee = e as TensorContainerObject;
expect(ee['b']).toEqual(ee['a'] as number * 10);
expect(ee['c']).toEqual(`string ${ee['a']}`);
}
});
}); | the_stack |
* TreeNavController is the navigation tree component of the documentation page.
* It adds accessiblity attributes to a tree, observes the heading elements
* focus the topmost link for headings visible on the page, and implements the
* WAI-ARIA Treeview Design Pattern with full
* [keyboard support](https://www.w3.org/TR/wai-aria-practices/examples/treeview/treeview-2/treeview-2a.html#kbd_label).
*/
export class TreeNavController {
treeitems: TreeItem[];
/**
* firstChars is the first character of each treeitem in the same order
* as this.treeitems. We use this array to set focus by character when
* navigating the tree with a keyboard.
*/
private firstChars: string[];
private firstTreeitem: TreeItem | null;
private lastTreeitem: TreeItem | null;
private observerCallbacks: ((t: TreeItem) => void)[];
constructor(private el: HTMLElement) {
this.treeitems = [];
this.firstChars = [];
this.firstTreeitem = null;
this.lastTreeitem = null;
this.observerCallbacks = [];
this.init();
}
private init(): void {
this.handleResize();
window.addEventListener('resize', this.handleResize);
this.findTreeItems();
this.updateVisibleTreeitems();
this.observeTargets();
if (this.firstTreeitem) {
this.firstTreeitem.el.tabIndex = 0;
}
}
private handleResize = (): void => {
this.el.style.setProperty('--js-tree-height', '100vh');
this.el.style.setProperty('--js-tree-height', this.el.clientHeight + 'px');
};
private observeTargets() {
this.addObserver(treeitem => {
this.expandTreeitem(treeitem);
this.setSelected(treeitem);
// TODO: Fix scroll issue in https://golang.org/issue/47450.
// treeitem.el.scrollIntoView({ block: 'nearest' });
});
const targets = new Map<string, boolean>();
const observer = new IntersectionObserver(
entries => {
for (const entry of entries) {
targets.set(entry.target.id, entry.isIntersecting || entry.intersectionRatio === 1);
}
for (const [id, isIntersecting] of targets) {
if (isIntersecting) {
const active = this.treeitems.find(t =>
(t.el as HTMLAnchorElement)?.href.endsWith(`#${id}`)
);
if (active) {
for (const fn of this.observerCallbacks) {
fn(active);
}
}
break;
}
}
},
{
threshold: 1.0,
rootMargin: '-60px 0px 0px 0px',
}
);
for (const href of this.treeitems.map(t => t.el.getAttribute('href'))) {
if (href) {
const id = href.replace(window.location.origin, '').replace('/', '').replace('#', '');
const target = document.getElementById(id);
if (target) {
observer.observe(target);
}
}
}
}
addObserver(fn: (t: TreeItem) => void, delay = 200): void {
this.observerCallbacks.push(debounce(fn, delay));
}
setFocusToNextItem(currentItem: TreeItem): void {
let nextItem = null;
for (let i = currentItem.index + 1; i < this.treeitems.length; i++) {
const ti = this.treeitems[i];
if (ti.isVisible) {
nextItem = ti;
break;
}
}
if (nextItem) {
this.setFocusToItem(nextItem);
}
}
setFocusToPreviousItem(currentItem: TreeItem): void {
let prevItem = null;
for (let i = currentItem.index - 1; i > -1; i--) {
const ti = this.treeitems[i];
if (ti.isVisible) {
prevItem = ti;
break;
}
}
if (prevItem) {
this.setFocusToItem(prevItem);
}
}
setFocusToParentItem(currentItem: TreeItem): void {
if (currentItem.groupTreeitem) {
this.setFocusToItem(currentItem.groupTreeitem);
}
}
setFocusToFirstItem(): void {
this.firstTreeitem && this.setFocusToItem(this.firstTreeitem);
}
setFocusToLastItem(): void {
this.lastTreeitem && this.setFocusToItem(this.lastTreeitem);
}
setSelected(currentItem: TreeItem): void {
for (const l1 of this.el.querySelectorAll('[aria-expanded="true"]')) {
if (l1 === currentItem.el) continue;
if (!l1.nextElementSibling?.contains(currentItem.el)) {
l1.setAttribute('aria-expanded', 'false');
}
}
for (const l1 of this.el.querySelectorAll('[aria-selected]')) {
if (l1 !== currentItem.el) {
l1.setAttribute('aria-selected', 'false');
}
}
currentItem.el.setAttribute('aria-selected', 'true');
this.updateVisibleTreeitems();
this.setFocusToItem(currentItem, false);
}
expandTreeitem(treeitem: TreeItem): void {
let currentItem: TreeItem | null = treeitem;
while (currentItem) {
if (currentItem.isExpandable) {
currentItem.el.setAttribute('aria-expanded', 'true');
}
currentItem = currentItem.groupTreeitem;
}
this.updateVisibleTreeitems();
}
expandAllSiblingItems(currentItem: TreeItem): void {
for (const ti of this.treeitems) {
if (ti.groupTreeitem === currentItem.groupTreeitem && ti.isExpandable) {
this.expandTreeitem(ti);
}
}
}
collapseTreeitem(currentItem: TreeItem): void {
let groupTreeitem = null;
if (currentItem.isExpanded()) {
groupTreeitem = currentItem;
} else {
groupTreeitem = currentItem.groupTreeitem;
}
if (groupTreeitem) {
groupTreeitem.el.setAttribute('aria-expanded', 'false');
this.updateVisibleTreeitems();
this.setFocusToItem(groupTreeitem);
}
}
setFocusByFirstCharacter(currentItem: TreeItem, char: string): void {
let start: number, index: number;
char = char.toLowerCase();
// Get start index for search based on position of currentItem
start = currentItem.index + 1;
if (start === this.treeitems.length) {
start = 0;
}
// Check remaining slots in the menu
index = this.getIndexFirstChars(start, char);
// If not found in remaining slots, check from beginning
if (index === -1) {
index = this.getIndexFirstChars(0, char);
}
// If match was found...
if (index > -1) {
this.setFocusToItem(this.treeitems[index]);
}
}
private findTreeItems() {
const findItems = (el: HTMLElement, group: TreeItem | null) => {
let ti = group;
let curr = el.firstElementChild as HTMLElement;
while (curr) {
if (curr.tagName === 'A' || curr.tagName === 'SPAN') {
ti = new TreeItem(curr, this, group);
this.treeitems.push(ti);
this.firstChars.push(ti.label.substring(0, 1).toLowerCase());
}
if (curr.firstElementChild) {
findItems(curr, ti);
}
curr = curr.nextElementSibling as HTMLElement;
}
};
findItems(this.el as HTMLElement, null);
this.treeitems.map((ti, idx) => (ti.index = idx));
}
private updateVisibleTreeitems(): void {
this.firstTreeitem = this.treeitems[0];
for (const ti of this.treeitems) {
let parent = ti.groupTreeitem;
ti.isVisible = true;
while (parent && parent.el !== this.el) {
if (!parent.isExpanded()) {
ti.isVisible = false;
}
parent = parent.groupTreeitem;
}
if (ti.isVisible) {
this.lastTreeitem = ti;
}
}
}
private setFocusToItem(treeitem: TreeItem, focusEl = true) {
treeitem.el.tabIndex = 0;
if (focusEl) {
treeitem.el.focus();
}
for (const ti of this.treeitems) {
if (ti !== treeitem) {
ti.el.tabIndex = -1;
}
}
}
private getIndexFirstChars(startIndex: number, char: string): number {
for (let i = startIndex; i < this.firstChars.length; i++) {
if (this.treeitems[i].isVisible && char === this.firstChars[i]) {
return i;
}
}
return -1;
}
}
class TreeItem {
el: HTMLElement;
groupTreeitem: TreeItem | null;
label: string;
isExpandable: boolean;
isVisible: boolean;
depth: number;
index: number;
private tree: TreeNavController;
private isInGroup: boolean;
constructor(el: HTMLElement, treeObj: TreeNavController, group: TreeItem | null) {
el.tabIndex = -1;
this.el = el;
this.groupTreeitem = group;
this.label = el.textContent?.trim() ?? '';
this.tree = treeObj;
this.depth = (group?.depth || 0) + 1;
this.index = 0;
const parent = el.parentElement;
if (parent?.tagName.toLowerCase() === 'li') {
parent?.setAttribute('role', 'none');
}
el.setAttribute('aria-level', this.depth + '');
if (el.getAttribute('aria-label')) {
this.label = el?.getAttribute('aria-label')?.trim() ?? '';
}
this.isExpandable = false;
this.isVisible = false;
this.isInGroup = !!group;
let curr = el.nextElementSibling;
while (curr) {
if (curr.tagName.toLowerCase() == 'ul') {
const groupId = `${group?.label ?? ''} nav group ${this.label}`.replace(/[\W_]+/g, '_');
el.setAttribute('aria-owns', groupId);
el.setAttribute('aria-expanded', 'false');
curr.setAttribute('role', 'group');
curr.setAttribute('id', groupId);
this.isExpandable = true;
break;
}
curr = curr.nextElementSibling;
}
this.init();
}
private init() {
this.el.tabIndex = -1;
if (!this.el.getAttribute('role')) {
this.el.setAttribute('role', 'treeitem');
}
this.el.addEventListener('keydown', this.handleKeydown.bind(this));
this.el.addEventListener('click', this.handleClick.bind(this));
this.el.addEventListener('focus', this.handleFocus.bind(this));
this.el.addEventListener('blur', this.handleBlur.bind(this));
}
isExpanded() {
if (this.isExpandable) {
return this.el.getAttribute('aria-expanded') === 'true';
}
return false;
}
isSelected() {
return this.el.getAttribute('aria-selected') === 'true';
}
private handleClick(event: MouseEvent) {
// only process click events that directly happened on this treeitem
if (event.target !== this.el && event.target !== this.el.firstElementChild) {
return;
}
if (this.isExpandable) {
if (this.isExpanded() && this.isSelected()) {
this.tree.collapseTreeitem(this);
} else {
this.tree.expandTreeitem(this);
}
event.stopPropagation();
}
this.tree.setSelected(this);
}
private handleFocus() {
let el = this.el;
if (this.isExpandable) {
el = (el.firstElementChild as HTMLElement) ?? el;
}
el.classList.add('focus');
}
private handleBlur() {
let el = this.el;
if (this.isExpandable) {
el = (el.firstElementChild as HTMLElement) ?? el;
}
el.classList.remove('focus');
}
private handleKeydown(event: KeyboardEvent) {
if (event.altKey || event.ctrlKey || event.metaKey) {
return;
}
let captured = false;
switch (event.key) {
case ' ':
case 'Enter':
if (this.isExpandable) {
if (this.isExpanded() && this.isSelected()) {
this.tree.collapseTreeitem(this);
} else {
this.tree.expandTreeitem(this);
}
captured = true;
} else {
event.stopPropagation();
}
this.tree.setSelected(this);
break;
case 'ArrowUp':
this.tree.setFocusToPreviousItem(this);
captured = true;
break;
case 'ArrowDown':
this.tree.setFocusToNextItem(this);
captured = true;
break;
case 'ArrowRight':
if (this.isExpandable) {
if (this.isExpanded()) {
this.tree.setFocusToNextItem(this);
} else {
this.tree.expandTreeitem(this);
}
}
captured = true;
break;
case 'ArrowLeft':
if (this.isExpandable && this.isExpanded()) {
this.tree.collapseTreeitem(this);
captured = true;
} else {
if (this.isInGroup) {
this.tree.setFocusToParentItem(this);
captured = true;
}
}
break;
case 'Home':
this.tree.setFocusToFirstItem();
captured = true;
break;
case 'End':
this.tree.setFocusToLastItem();
captured = true;
break;
default:
if (event.key.length === 1 && event.key.match(/\S/)) {
if (event.key == '*') {
this.tree.expandAllSiblingItems(this);
} else {
this.tree.setFocusByFirstCharacter(this, event.key);
}
captured = true;
}
break;
}
if (captured) {
event.stopPropagation();
event.preventDefault();
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function debounce<T extends (...args: any[]) => any>(func: T, wait: number) {
let timeout: ReturnType<typeof setTimeout> | null;
return (...args: Parameters<T>) => {
const later = () => {
timeout = null;
func(...args);
};
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(later, wait);
};
} | the_stack |
import './_ext';
import errno from './errno';
import {Encoding} from './buffer';
import _util from './_util';
const _fs = __require__('_fs');
export enum FileOpenFlag {
FOPEN_ACCMODE = 0o3,
FOPEN_RDONLY = 0o0,
FOPEN_WRONLY = 0o1,
FOPEN_RDWR = 0o2,
FOPEN_CREAT = 0o100,
FOPEN_EXCL = 0o200,
FOPEN_NOCTTY = 0o400,
FOPEN_TRUNC = 0o1000,
FOPEN_APPEND = 0o2000,
FOPEN_NONBLOCK = 0o4000,
// r 打开只读文件,该文件必须存在。
FOPEN_R = FOPEN_RDONLY,
// w 打开只写文件,若文件存在则文件长度清为零,即该文件内容会消失,若文件不存在则建立该文件。
FOPEN_W = FOPEN_WRONLY | FOPEN_CREAT | FOPEN_TRUNC,
// a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,
// 写入的数据会被加到文件尾,即文件原先的内容会被保留。
FOPEN_A = FOPEN_WRONLY | FOPEN_CREAT | FOPEN_APPEND,
// r+ 打开可读写文件,该文件必须存在。
FOPEN_RP = FOPEN_RDWR,
// w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。
// 若文件不存在则建立该文件。
FOPEN_WP = FOPEN_RDWR | FOPEN_CREAT | FOPEN_TRUNC,
// a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,
// 写入的数据会被加到文件尾后,即文件原先的内容会被保留。
FOPEN_AP = FOPEN_RDWR | FOPEN_CREAT | FOPEN_APPEND,
}
export enum FileType {
FTYPE_UNKNOWN,
FTYPE_FILE,
FTYPE_DIR,
FTYPE_LINK,
FTYPE_FIFO,
FTYPE_SOCKET,
FTYPE_CHAR,
FTYPE_BLOCK,
}
export declare const DEFAULT_MODE: number;
export interface Dirent {
name: string;
pathname: string;
type: FileType;
}
export declare class FileStat {
isValid(): boolean;
isFile(): boolean;
isDir(): boolean;
isDirectory(): boolean;
isLink(): boolean;
isSock(): boolean;
mode(): number;
type(): FileType;
group(): number;
owner(): number;
size(): number;
nlink(): number;
ino(): number;
blksize(): number;
blocks(): number;
flags(): number;
gen(): number;
dev(): number;
rdev(): number;
atime(): number;
mtime(): number;
ctime(): number;
birthtime(): number;
}
export interface ReadStream {
pause(): void;
resume(): void;
};
export interface StreamData {
data: Uint8Array;
complete: boolean;
size: number;
total: number;
}
export class AsyncTask<T> extends Promise<T> {
private _resolve: any;
private _reject: any;
private _complete: boolean;
private _id: number;
private _ok(r: T) {
if (!this._complete) {
this._complete = true;
this._resolve(r);
}
}
private _err(err: Error) {
if (!this._complete) {
this._complete = true;
this._reject(err);
}
}
constructor(exec: (resolve: any, reject: any)=>number) {
var _resolve: any;
var _reject: any;
var self: this;
var id: number = 0;
super(function(resolve, reject) {
_resolve = resolve;
_reject = reject;
id = exec((r: any)=>self._ok(r), (err: any)=>self._err(err));
});
self = this;
this._resolve = _resolve;
this._reject = _reject;
this._complete = false;
this._id = id;
}
get id() { return this._id }
get complete() { return this._complete }
abort(): void {
if (!this._complete) {
_fs.abort(this._id);
this._err(Error.new(errno.ERR_READ_STREAM_ABORT));
}
}
}
// sync
export declare function chmodSync(path: string, mode?: number): void;
export declare function chownSync(path: string, owner: number, group: number): void;
export declare function mkdirSync(path: string, mode?: number): void;
export declare function renameSync(name: string, newName: string): void;
export declare function linkSync(src: string, target: string): void;
export declare function unlinkSync(path: string): void;
export declare function rmdirSync(path: string): void;
export declare function readdirSync(path: string): Dirent[];
export declare function statSync(path: string): FileStat;
export declare function existsSync(path: string): boolean;
export declare function isFileSync(path: string): boolean;
export declare function isDirectorySync(path: string): boolean;
export declare function readableSync(path: string): boolean;
export declare function writableSync(path: string): boolean;
export declare function executableSync(path: string): boolean;
export declare function chmodrSync(path: string, mode?: number): void;
export declare function chownrSync(path: string, owner: number, group: number): void;
export declare function mkdirpSync(path: string, mode?: number): void;
export declare function removerSync(path: string): void;
export declare function copySync(path: string, target: string): void;
export declare function copyrSync(path: string, target: string): void;
// read/write file sync
export declare function writeFileSync(path: string, data: Uint8Array, size?: number): number;
export declare function writeFileSync(path: string, data: string, encoding?: Encoding): number;
export declare function readFileSync(path: string): Uint8Array;
export declare function readFileSync(path: string, encoding?: Encoding): string;
export declare function openSync(path: string, flags?: FileOpenFlag /*= FileOpenFlag.FOPEN_R*/): number;
export declare function closeSync(path: number): void;
export declare function readSync(fd: number, out: Uint8Array, size?: number /*= -1*/, offsetFd?: number /*= -1*/): number;
export declare function writeSync(fd: number, data: Uint8Array, size?: number /*= -1*/, offsetFd?: number /*= -1*/): number;
export declare function writeSync(fd: number, data: string, offsetFd?: number /*= -1*/): number;
export declare function writeSync(fd: number, data: string, encoding?: Encoding, offsetFd?: number /*= -1*/): number;
Object.assign(exports, _fs);
// async
export function chmod(path: string, mode: number = _fs.DEFAULT_MODE) {
return new Promise<void>(function(resolve, reject) {
_fs.chown(path, mode, (err?: Error)=>err?reject(err):resolve());
});
}
export function chown(path: string, owner: number, group: number) {
return new Promise<void>(function(resolve, reject) {
_fs.chown(path, owner, group, (err?: Error)=>err?reject(err):resolve());
});
}
export function mkdir(path: string, mode: number = _fs.DEFAULT_MODE) {
return new Promise<void>(function(resolve, reject) {
_fs.mkdir(path, mode, (err?: Error)=>err?reject(err):resolve());
});
}
export function rename(name: string, newName: string) {
return new Promise<void>(function(resolve, reject) {
_fs.rename(name, newName, (err?: Error)=>err?reject(err):resolve());
});
}
export function link(src: string, target: string) {
return new Promise<void>(function(resolve, reject) {
_fs.link(src, target, (err?: Error)=>err?reject(err):resolve());
});
}
export function unlink(path: string) {
return new Promise<void>(function(resolve, reject) {
_fs.unlink(path, (err?: Error)=>err?reject(err):resolve());
});
}
export function rmdir(path: string) {
return new Promise<void>(function(resolve, reject) {
_fs.rmdir(path, (err?: Error)=>err?reject(err):resolve());
});
}
export function readdir(path: string) {
return new Promise<Dirent[]>(function(resolve, reject) {
_fs.readdir(path, (err?: Error, r?: Dirent[])=>err?reject(err):resolve(r as any));
});
}
export function stat(path: string) {
return new Promise<FileStat>(function(resolve, reject) {
_fs.stat(path, (err?: Error, r?: FileStat)=>err?reject(err):resolve(r as any));
});
}
export function exists(path: string) {
return new Promise<boolean>(function(resolve, reject) {
_fs.exists(path, (err?: Error, r?: boolean)=>err?reject(err):resolve(r as any));
});
}
export function isFile(path: string) {
return new Promise<boolean>(function(resolve, reject) {
_fs.isFile(path, (err?: Error, r?: boolean)=>err?reject(err):resolve(r as any));
});
}
export function isDirectory(path: string) {
return new Promise<boolean>(function(resolve, reject) {
_fs.isDirectory(path, (err?: Error, r?: boolean)=>err?reject(err):resolve(r as any));
});
}
export function readable(path: string) {
return new Promise<boolean>(function(resolve, reject) {
_fs.readable(path, (err?: Error, r?: boolean)=>err?reject(err):resolve(r as any));
});
}
export function writable(path: string) {
return new Promise<boolean>(function(resolve, reject) {
_fs.writable(path, (err?: Error, r?: boolean)=>err?reject(err):resolve(r as any));
});
}
export function executable(path: string) {
return new Promise<boolean>(function(resolve, reject) {
_fs.executable(path, (err?: Error, r?: boolean)=>err?reject(err):resolve(r as any));
});
}
export function chmodr(path: string, mode: number = _fs.DEFAULT_MODE) {
return new AsyncTask<void>(function(resolve, reject) {
return _fs.chmodr(path, mode, (err?: Error)=>err?reject(err):resolve());
});
}
export function chownr(path: string, owner: number, group: number) {
return new AsyncTask<void>(function(resolve, reject) {
return _fs.chownr(path, owner, group, (err?: Error)=>err?reject(err):resolve());
});
}
export function mkdirp(path: string, mode: number = _fs.DEFAULT_MODE) {
return new Promise<void>(function(resolve, reject) {
_fs.mkdirp(path, mode, (err?: Error)=>err?reject(err):resolve());
});
}
export function remover(path: string) {
return new AsyncTask<void>(function(resolve, reject) {
return _fs.remover(path, (err?: Error)=>err?reject(err):resolve());
});
}
export function copy(path: string, target: string) {
return new AsyncTask<void>(function(resolve, reject) {
return _fs.copy(path, target, (err?: Error)=>err?reject(err):resolve());
});
}
export function copyr(path: string, target: string) {
return new AsyncTask<void>(function(resolve, reject) {
return _fs.copyr(path, target, (err?: Error)=>err?reject(err):resolve());
});
}
export function readStream(path: string, cb: (stream: StreamData)=>void): AsyncTask<void> {
return new AsyncTask<void>(function(resolve, reject): number {
return _fs.readStream(function(err?: Error, r?: StreamData) {
if (err) {
reject(err);
} else {
var stream = r as StreamData;
cb(stream);
if (stream.complete) {
resolve();
}
}
}, path);
});
}
export declare function abort(id: number): void;
// async
export declare function writeFile(path: string, data: Uint8Array, size?: number): Promise<number>;
export declare function writeFile(path: string, data: string, encoding?: Encoding): Promise<number>;
export declare function readFile(path: string): Promise<Uint8Array>;
export declare function readFile(path: string, encoding?: Encoding): Promise<string>;
export declare function open(path: string, flags?: FileOpenFlag): Promise<number>;
export declare function close(path: number): Promise<void>;
export declare function read(fd: number, out: Uint8Array, size?: number, offsetFd?: number): Promise<number>;
export declare function write(fd: number, data: Uint8Array, size?: number, offsetFd?: number): Promise<number>;
export declare function write(fd: number, data: string, offsetFd?: number): Promise<number>;
export declare function write(fd: number, data: string, encoding?: Encoding, offsetFd?: number): Promise<number>;
exports.writeFile = function(...args: any[]) {
return new Promise<number>(function(resolve, reject) {
_fs.writeFile((err?: Error, r?: number)=>err ? reject(err) : resolve(r as any), ...args);
});
};
exports.readFile = function(...args: any[]) {
return new Promise<any>(function(resolve, reject) {
_fs.readFile((err?: Error, r?: any)=>err ? reject(err) : resolve(r), ...args);
});
};
exports.open = function(...args: any[]) {
return new Promise<any>(function(resolve, reject) {
_fs.open((err?: Error, r?: any)=>err?reject(err):resolve(r), ...args);
});
};
exports.close = function(...args: any[]) {
return new Promise<void>(function(resolve, reject) {
_fs.close((err?: Error)=>err?reject(err):resolve(), ...args);
});
};
exports.read = function(...args: any[]) {
return new Promise<any>(function(resolve, reject) {
_fs.read((err?: Error, r?: any)=>err?reject(err):resolve(r), ...args);
});
};
exports.write = function(...args: any[]) {
return new Promise<any>(function(resolve, reject) {
_fs.write((err?: Error, r?: any)=>err?reject(err):resolve(r), ...args);
});
}; | the_stack |
import BigNumber from 'bignumber.js';
import _ from 'lodash';
import Web3 from 'web3';
import {
BigNumberable,
MakerOracleMessage,
Price,
address,
} from '../src/lib/types';
import { MirrorOracle } from '../src/modules/MirrorOracle';
import {
expect,
expectAddressesEqual,
expectBaseValueEqual,
expectBN,
expectThrow,
} from './helpers/Expect';
import initializePerpetual from './helpers/initializePerpetual';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { fixRawSignature } from '../src/lib/SignatureHelper';
import { mineAvgBlock } from './helpers/EVM';
import { ADDRESSES } from '../src/lib/Constants';
// Identifier for the Maker oracle, used in the signed messages.
const ORACLE_WAT = 'ETHUSD';
let oracle: MirrorOracle;
// Accounts.
let admin: address;
let reader: address;
let otherAddress: address;
let signers: address[];
async function init(ctx: ITestContext): Promise<void> {
// Accounts.
admin = ctx.accounts[0];
reader = ctx.accounts[2];
otherAddress = ctx.accounts[3];
signers = ctx.accounts.slice(4, 9);
// Module for interacting with the mirror oracle.
oracle = new MirrorOracle(ctx.perpetual.contracts, ctx.perpetual.web3);
// Configure the perpetual to use the mirror oracle, by way of P1MakerOracle.
await Promise.all([
initializePerpetual(
ctx,
{ oracle: ctx.perpetual.contracts.p1MakerOracle.options.address },
),
ctx.perpetual.makerPriceOracle.setRoute(
ctx.perpetual.contracts.perpetualProxy.options.address,
ctx.perpetual.contracts.p1MirrorOracle.options.address,
{ from: admin },
),
oracle.kiss(reader, { from: admin }),
]);
}
perpetualDescribe('P1MirrorOracle', init, (ctx: ITestContext) => {
describe('peek()', () => {
it('reads the oracle price', async () => {
// Set the oracle price.
await oracle.syncBar();
await ctx.perpetual.testing.makerOracle.lift([signers[0]]);
await oracle.lift([signers[0]]);
await poke([signers[0]], [125]);
const [price, isValid] = await oracle.peek({ from: reader });
expect(isValid).to.be.true;
expectBN(price).to.equal(new Price(125).toSolidity());
});
it('succeeds when price has not been set', async () => {
const [price, isValid] = await oracle.peek({ from: reader });
expect(isValid).to.be.false;
expectBN(price).to.equal(0);
});
it('fails if sender is not an authorized reader', async () => {
await expectThrow(
oracle.peek({ from: otherAddress }),
'P1MirrorOracle#peek: Sender not authorized to get price',
);
});
});
describe('read()', () => {
it('reads the oracle price', async () => {
// Set the oracle price.
await oracle.syncBar();
await ctx.perpetual.testing.makerOracle.lift([signers[0]]);
await oracle.lift([signers[0]]);
await poke([signers[0]], [125]);
// Read the mirror oracle, by way of the perpetual contract.
const price = await ctx.perpetual.priceOracle.getPrice();
expectBaseValueEqual(price, new Price(125));
});
it('fails if price has not been set', async () => {
// Read the mirror oracle, by way of the perpetual contract.
await expectThrow(
ctx.perpetual.priceOracle.getPrice(),
'P1MirrorOracle#read: Price is zero',
);
});
it('fails if sender is not an authorized reader', async () => {
await expectThrow(
oracle.getValue({ from: otherAddress }),
'P1MirrorOracle#read: Sender not authorized to get price',
);
});
});
describe('checkSynced()', () => {
beforeEach(async () => {
// Sync bar.
await oracle.syncBar();
});
it('returns all zero when synced, without any signers', async () => {
const { signersToAdd, signersToRemove, barNeedsUpdate } = await oracle.checkSyncedDetailed();
expect(signersToAdd.length).to.equal(0);
expect(signersToRemove.length).to.equal(0);
expect(barNeedsUpdate).to.be.false;
});
it('returns all zero when synced, with signers', async () => {
// Add signers to both oracles.
await ctx.perpetual.testing.makerOracle.lift(signers);
await oracle.lift(signers);
// Call the function.
const { signersToAdd, signersToRemove, barNeedsUpdate } = await oracle.checkSyncedDetailed();
expect(signersToAdd.length).to.equal(0);
expect(signersToRemove.length).to.equal(0);
expect(barNeedsUpdate).to.be.false;
});
it('detects if the value of `bar` is out of sync', async () => {
// Update the value of `bar` on the underlying oracle.
await ctx.perpetual.testing.makerOracle.setBar(11);
// Call the function.
const { signersToAdd, signersToRemove, barNeedsUpdate } = await oracle.checkSyncedDetailed();
expect(signersToAdd.length).to.equal(0);
expect(signersToRemove.length).to.equal(0);
expect(barNeedsUpdate).to.be.true;
});
it('detects if there are signers to be added', async () => {
// Add signers to the underlying oracle.
await ctx.perpetual.testing.makerOracle.lift(signers);
// Call the function.
const { signersToAdd, signersToRemove, barNeedsUpdate } = await oracle.checkSyncedDetailed();
expect(_.sortBy(signersToAdd)).to.deep.equal(_.sortBy(signers));
expect(signersToRemove.length).to.equal(0);
expect(barNeedsUpdate).to.be.false;
});
it('detects if there are signers to be removed', async () => {
// Add signers to the oracle that aren't on the underlying oracle.
await ctx.perpetual.testing.makerOracle.lift(signers);
await oracle.lift(signers);
await ctx.perpetual.testing.makerOracle.drop(signers);
// Call the function.
const { signersToAdd, signersToRemove, barNeedsUpdate } = await oracle.checkSyncedDetailed();
expect(signersToAdd.length).to.equal(0);
expect(_.sortBy(signersToRemove)).to.deep.equal(_.sortBy(signers));
expect(barNeedsUpdate).to.be.false;
});
it('detects if a signer has changed to another signer with the same first byte', async () => {
// Create a new signer address with the same first byte.
const newSigner = (
`${signers[0].slice(0, 4)}00000000000000000000000000000000000000`.toLowerCase()
);
await ctx.perpetual.testing.makerOracle.lift([signers[0]]);
await oracle.lift([signers[0]]);
// Use lowercase to avoid address checksum failure.
await ctx.perpetual.testing.makerOracle.lift([newSigner]);
// Call the function.
const { signersToAdd, signersToRemove, barNeedsUpdate } = await oracle.checkSyncedDetailed();
expect(signersToAdd.length).to.equal(1);
expect(signersToRemove.length).to.equal(1);
expectAddressesEqual(signersToAdd[0], newSigner);
expectAddressesEqual(signersToRemove[0], signers[0]);
expect(barNeedsUpdate).to.be.false;
});
});
describe('poke()', () => {
beforeEach(async () => {
// Require 5 signed messages.
await ctx.perpetual.testing.makerOracle.setBar(5);
await oracle.syncBar();
// Add signers.
await ctx.perpetual.testing.makerOracle.lift(signers);
await oracle.lift(signers);
});
it('updates the oracle price and age', async () => {
const prices = _.range(101.5, 151.5, 10);
await poke(signers, prices);
});
it('allows multiple updates, from different combinations of signers', async () => {
// Require 3 signed messages.
await ctx.perpetual.testing.makerOracle.setBar(3);
await oracle.syncBar();
// Call the function with different groups of signers.
await poke(signers.slice(0, 3), [111, 121, 131]);
await poke(signers.slice(1, 4), [121, 131, 141]);
await poke(signers.slice(2, 5), [101, 111, 121]);
});
it('succeeds when every message contains the same price', async () => {
const prices = _.times(5, _.constant('121.5'));
await poke(signers, prices);
});
it('fails if there are too few messages', async () => {
const prices = _.range(101.5, 141.5, 10);
await expectThrow(
poke(signers.slice(0, 4), prices),
'P1MirrorOracle#poke: Wrong number of messages',
);
});
it('fails if there are too many messages', async () => {
// Require 3 signed messages.
await ctx.perpetual.testing.makerOracle.setBar(3);
await oracle.syncBar();
const prices = _.range(101.5, 141.5, 10);
await expectThrow(
poke(signers.slice(0, 4), prices),
'P1MirrorOracle#poke: Wrong number of messages',
);
});
it('fails if a signature is invalid', async () => {
// Use a timestamp that will be after the current block.
const latestBlock = await ctx.perpetual.web3.eth.getBlock('latest');
const timestamp = Number(latestBlock.timestamp) + 1000;
// Create signed messages.
const prices = _.range(101.5, 151.5, 10);
const messages = await Promise.all(_.zip(prices, signers).map(([price, signer]) => {
return makeMakerOracleMessage(new Price(price), timestamp, signer);
}));
// Make one of the the signatures invalid.
messages[3].signature = `0x${messages[3].signature.slice(3)}0`;
// Call the smart contract function.
await expectThrow(
oracle.poke(messages),
'P1MirrorOracle#poke: Invalid signer',
);
});
it('fails if a signer is not authorized', async () => {
// Unauthorize one of the signers.
await ctx.perpetual.testing.makerOracle.drop([signers[3]]);
await oracle.drop([signers[3]]);
const prices = _.range(101.5, 151.5, 10);
await expectThrow(
poke(signers, prices),
'P1MirrorOracle#poke: Invalid signer',
);
});
it('fails if a message has the same age as the last oracle update', async () => {
const prices = _.range(101.5, 151.5, 10);
await poke(signers, prices);
const age = await oracle.getAge();
await expectThrow(
poke(signers, prices, age.toNumber()),
'P1MirrorOracle#poke: Stale message',
);
});
it('fails if a message is older than the last oracle update', async () => {
const prices = _.range(101.5, 151.5, 10);
await poke(signers, prices);
const age = await oracle.getAge();
await expectThrow(
poke(signers, prices, age.toNumber() - 1000),
'P1MirrorOracle#poke: Stale message',
);
});
it('fails if the messages are not sorted by value', async () => {
const prices = _.range(101.5, 151.5, 10).reverse();
await expectThrow(
poke(signers, prices),
'P1MirrorOracle#poke: Message out of order',
);
});
it('fails if two messages have the same signer', async () => {
const prices = _.range(101.5, 151.5, 10);
await expectThrow(
poke([...signers.slice(0, 4), signers[0]], prices),
'P1MirrorOracle#poke: Duplicate signer',
);
});
});
describe('lift()', () => {
beforeEach(async () => {
await ctx.perpetual.testing.makerOracle.lift(signers);
});
it('adds signers to the list of signers', async () => {
// Call the function and check the contract state.
let txResult = await oracle.lift([signers[0]]);
expect(await oracle.getOrcl(signers[0])).to.be.true;
expect(await oracle.getSlot(Number.parseInt(signers[0].slice(2, 4), 16))).to.equal(
signers[0],
);
// Check logs.
let logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogSetSigner');
expect(logs[0].args.signer).to.equal(signers[0]);
expect(logs[0].args.authorized).to.equal(true);
// Call the function and check the contract state.
txResult = await oracle.lift([signers[1], signers[2]]);
expect(await oracle.getOrcl(signers[1])).to.be.true;
expect(await oracle.getSlot(Number.parseInt(signers[1].slice(2, 4), 16))).to.equal(
signers[1],
);
expect(await oracle.getOrcl(signers[2])).to.be.true;
expect(await oracle.getSlot(Number.parseInt(signers[2].slice(2, 4), 16))).to.equal(
signers[2],
);
// Check logs.
logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(2);
expect(logs[0].name).to.equal('LogSetSigner');
expect(logs[0].args.signer).to.equal(signers[1]);
expect(logs[0].args.authorized).to.equal(true);
expect(logs[1].name).to.equal('LogSetSigner');
expect(logs[1].args.signer).to.equal(signers[2]);
expect(logs[1].args.authorized).to.equal(true);
});
it('fails if the signer is already currently authorized', async () => {
await oracle.lift([signers[2]]);
await expectThrow(
oracle.lift([signers[1], signers[2]]),
'P1MirrorOracle#lift: Signer already authorized',
);
});
it('fails if a different signer with the same first byte is already authorized', async () => {
// Create a new signer address with the same first byte.
const newSigner = (
`${signers[2].slice(0, 4)}00000000000000000000000000000000000000`.toLowerCase()
);
// Authorize it on the underlying oracle.
await ctx.perpetual.testing.makerOracle.drop([signers[2]]);
// Use lowercase to avoid address checksum failure.
await ctx.perpetual.testing.makerOracle.lift([newSigner]);
await oracle.lift([newSigner]);
await expectThrow(
oracle.lift([newSigner]),
'P1MirrorOracle#lift: Signer already authorized',
);
});
it('fails if the signer is not authorized on the underlying', async () => {
await ctx.perpetual.testing.makerOracle.drop([signers[2]]);
await expectThrow(
oracle.lift([signers[2]]),
'P1MirrorOracle#lift: Signer not authorized on underlying oracle',
);
});
});
describe('drop()', () => {
beforeEach(async () => {
await ctx.perpetual.testing.makerOracle.lift(signers);
await oracle.lift(signers.slice(0, 3));
await ctx.perpetual.testing.makerOracle.drop(signers.slice(0, 4));
});
it('removes signers from the list of signers', async () => {
// Call the function.
let txResult = await oracle.drop([signers[0]]);
expect(await oracle.getOrcl(signers[0])).to.be.false;
expect(await oracle.getSlot(Number.parseInt(signers[0].slice(2, 4), 16))).to.equal(
ADDRESSES.ZERO,
);
// Check logs.
let logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogSetSigner');
expect(logs[0].args.signer).to.equal(signers[0]);
expect(logs[0].args.authorized).to.equal(false);
// Call the function.
txResult = await oracle.drop([signers[1], signers[2]]);
expect(await oracle.getOrcl(signers[1])).to.be.false;
expect(await oracle.getSlot(Number.parseInt(signers[1].slice(2, 4), 16))).to.equal(
ADDRESSES.ZERO,
);
expect(await oracle.getOrcl(signers[2])).to.be.false;
expect(await oracle.getSlot(Number.parseInt(signers[2].slice(2, 4), 16))).to.equal(
ADDRESSES.ZERO,
);
// Check logs.
logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(2);
expect(logs[0].name).to.equal('LogSetSigner');
expect(logs[0].args.signer).to.equal(signers[1]);
expect(logs[0].args.authorized).to.equal(false);
expect(logs[1].name).to.equal('LogSetSigner');
expect(logs[1].args.signer).to.equal(signers[2]);
expect(logs[1].args.authorized).to.equal(false);
});
it('fails if the signer is not currently authorized', async () => {
await oracle.drop([signers[2]]);
// Both orcl and slot checks will fail.
await expectThrow(
oracle.drop([signers[1], signers[2]]),
'P1MirrorOracle#drop: Signer is already not authorized',
);
});
it('fails to drop invalid signer even if the first byte matches a valid signer', async () => {
// Create a new signer address with the same first byte.
const newSigner = (
`${signers[2].slice(0, 4)}00000000000000000000000000000000000000`.toLowerCase()
);
// The orcl check will fail, but not the slot check.
await expectThrow(
// Use lowercase to avoid address checksum failure.
oracle.drop([newSigner]),
'P1MirrorOracle#drop: Signer is already not authorized',
);
});
it('fails if the signer is authorized on the underlying', async () => {
await ctx.perpetual.testing.makerOracle.lift([signers[2]]);
await expectThrow(
oracle.drop([signers[2]]),
'P1MirrorOracle#drop: Signer is authorized on underlying oracle',
);
});
});
describe('setBar()', () => {
it('sets the required number of signers to that of the underlying oracle', async () => {
// Check initial value of bar.
expectBN(await oracle.getBar()).to.equal(0);
// Call the function, and also prepare a new bar on the underlying oracle.
let txResult = await oracle.syncBar();
await ctx.perpetual.testing.makerOracle.setBar(11);
// Check the log and the value of bar.
let logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogSetBar');
expectBN(logs[0].args.bar).to.equal(1);
expectBN(await oracle.getBar()).to.equal(1);
// Call the function.
txResult = await oracle.syncBar();
// Check the log and the value of bar.
logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogSetBar');
expectBN(logs[0].args.bar).to.equal(11);
expectBN(await oracle.getBar()).to.equal(11);
});
});
describe('kiss()', () => {
beforeEach(async () => {
// Set the oracle price.
await oracle.syncBar();
await ctx.perpetual.testing.makerOracle.lift([signers[0]]);
await oracle.lift([signers[0]]);
await poke([signers[0]], [125]);
});
it('authorizes an address to read the oracle price', async () => {
// Call the function and check the value of getter.
const txResult = await oracle.kiss(otherAddress, { from: admin });
expect(await oracle.getBud(otherAddress)).to.be.true;
// Check that the address can read the price.
const [peekedPrice] = await oracle.peek({ from: otherAddress });
expectBN(peekedPrice, new Price(125).toSolidity());
const readPrice = await oracle.getValue({ from: otherAddress });
expectBN(readPrice, new Price(125).toSolidity());
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogSetReader');
expect(logs[0].args.reader).to.equal(otherAddress);
expect(logs[0].args.authorized).to.equal(true);
});
it('authorizes multiple addresses to read the oracle price', async () => {
const readers = [admin, reader, otherAddress, signers[0]];
// Call the function.
const txResult = await oracle.kiss(readers, { from: admin });
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(readers.length);
await Promise.all(readers.map(async (someAddress: address, i: number) => {
// Check the value of getter.
expect(await oracle.getBud(someAddress)).to.be.true;
// Check that the address can read the price.
const [peekedPrice] = await oracle.peek({ from: someAddress });
expectBN(peekedPrice, new Price(125).toSolidity());
const readPrice = await oracle.getValue({ from: someAddress });
expectBN(readPrice, new Price(125).toSolidity());
// Check log.
expect(logs[i].name).to.equal('LogSetReader');
expect(logs[i].args.reader).to.equal(someAddress);
expect(logs[i].args.authorized).to.equal(true);
}));
});
it('fails if the caller is not the owner', async () => {
await expectThrow(
oracle.kiss(otherAddress),
'Ownable: caller is not the owner',
);
});
});
describe('diss()', () => {
it('unauthorizes an address, disallowing it to read the price', async () => {
// Call the function and check the value of getter.
const txResult = await oracle.diss(reader, { from: admin });
expect(await oracle.getBud(reader)).to.be.false;
// Check that the address cannot read the price.
await expectThrow(
oracle.peek({ from: reader }),
'P1MirrorOracle#peek: Sender not authorized to get price',
);
await expectThrow(
oracle.getValue({ from: reader }),
'P1MirrorOracle#read: Sender not authorized to get price',
);
// Check logs.
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogSetReader');
expect(logs[0].args.reader).to.equal(reader);
expect(logs[0].args.authorized).to.equal(false);
});
it('unauthorizes multiple addresses, disallowing them to read the oracle price', async () => {
// Start by authorizing all the readers.
const readers = [admin, reader, otherAddress, signers[0]];
await oracle.kiss(readers, { from: admin });
// Call the function.
const txResult = await oracle.diss(readers, { from: admin });
const logs = ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(readers.length);
await Promise.all(readers.map(async (someAddress: address, i: number) => {
// Check the value of getter.
expect(await oracle.getBud(someAddress)).to.be.false;
// Check that the address cannot read the price.
await expectThrow(
oracle.peek({ from: someAddress }),
'P1MirrorOracle#peek: Sender not authorized to get price',
);
await expectThrow(
oracle.getValue({ from: someAddress }),
'P1MirrorOracle#read: Sender not authorized to get price',
);
// Check log.
expect(logs[i].name).to.equal('LogSetReader');
expect(logs[i].args.reader).to.equal(someAddress);
expect(logs[i].args.authorized).to.equal(false);
}));
});
it('fails if the caller is not the owner', async () => {
await expectThrow(
oracle.diss(reader),
'Ownable: caller is not the owner',
);
});
});
/**
* Helper function for making oracle messages and checking that price and age are set as expected.
*/
async function poke(
signers: address[],
prices: BigNumberable[],
timestamp: number | null = null,
): Promise<void> {
const lastBlock = await ctx.perpetual.web3.eth.getBlock('latest');
await mineAvgBlock();
const lastBlockTimestamp = Number(lastBlock.timestamp);
// By default, have the messages use a timestamp that will be after the current block.
const messageTimestamp = timestamp || (lastBlockTimestamp + 1000);
// Create signed messages.
// Assume prices are sorted and the length of the array is odd.
const expectedMedian = new Price(prices[Math.floor(prices.length / 2)]);
const messages = await Promise.all(_.zip(prices, signers).map(([price, signer]) => {
return makeMakerOracleMessage(new Price(price), messageTimestamp, signer);
}));
// Call the smart contract function.
const txResult = await oracle.poke(messages);
// Check value and age.
const price = await oracle.getPrice({ from: reader });
expectBaseValueEqual(price, expectedMedian);
const age = await oracle.getAge();
expectBN(age).to.gt(lastBlockTimestamp);
expectBN(age).to.lt(messageTimestamp);
const { age: privateAge, price: privatePrice } = await oracle.getPrivatePrice();
expectBN(privateAge).to.equal(age);
expectBaseValueEqual(privatePrice, price);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
expect(logs[0].name).to.equal('LogMedianPrice');
expectBN(logs[0].args.val).to.equal(expectedMedian.toSolidity());
expectBN(logs[0].args.age).to.gt(lastBlockTimestamp);
expectBN(logs[0].args.age).to.lt(messageTimestamp);
}
async function makeMakerOracleMessage(
price: Price,
timestampSeconds: BigNumberable,
signer: address,
): Promise<MakerOracleMessage> {
const timestamp = new BigNumber(timestampSeconds);
const message = Web3.utils.soliditySha3(
{ t: 'uint256', v: price.toSolidity() },
{ t: 'uint256', v: timestamp.toFixed(0) },
{ t: 'bytes32', v: `0x${Buffer.from(ORACLE_WAT).toString('hex').padEnd(64, '0')}` },
);
const signature = await ctx.perpetual.web3.eth.sign(message, signer);
return {
price,
timestamp,
signature: fixRawSignature(signature),
};
}
}); | the_stack |
import { EventTarget } from '../utils/EventTarget'
import { Vec3 } from '../math/Vec3'
import { Mat3 } from '../math/Mat3'
import { Quaternion } from '../math/Quaternion'
import { AABB } from '../collision/AABB'
import { Box } from '../shapes/Box'
import type { Shape } from '../shapes/Shape'
import type { Material } from '../material/Material'
import type { World } from '../world/World'
/**
* BODY_TYPES
*/
export const BODY_TYPES = {
/** DYNAMIC */
DYNAMIC: 1,
/** STATIC */
STATIC: 2,
/** KINEMATIC */
KINEMATIC: 4,
} as const
/**
* BodyType
*/
export type BodyType = typeof BODY_TYPES[keyof typeof BODY_TYPES]
/**
* BODY_SLEEP_STATES
*/
export const BODY_SLEEP_STATES = {
/** AWAKE */
AWAKE: 0,
/** SLEEPY */
SLEEPY: 1,
/** SLEEPING */
SLEEPING: 2,
} as const
/**
* BodySleepState
*/
export type BodySleepState = typeof BODY_SLEEP_STATES[keyof typeof BODY_SLEEP_STATES]
export type BodyOptions = ConstructorParameters<typeof Body>[0]
/**
* Base class for all body types.
* @example
* const shape = new CANNON.Sphere(1)
* const body = new CANNON.Body({
* mass: 1,
* shape,
* })
* world.addBody(body)
*/
export class Body extends EventTarget {
static idCounter = 0
/**
* Dispatched after two bodies collide. This event is dispatched on each
* of the two bodies involved in the collision.
* @event collide
* @param body The body that was involved in the collision.
* @param contact The details of the collision.
*/
static COLLIDE_EVENT_NAME = 'collide'
/**
* A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
*/
static DYNAMIC = BODY_TYPES.DYNAMIC
/**
* A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
*/
static STATIC = BODY_TYPES.STATIC
/**
* A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
*/
static KINEMATIC = BODY_TYPES.KINEMATIC
/**
* AWAKE
*/
static AWAKE = BODY_SLEEP_STATES.AWAKE
/**
* SLEEPY
*/
static SLEEPY = BODY_SLEEP_STATES.SLEEPY
/**
* SLEEPING
*/
static SLEEPING = BODY_SLEEP_STATES.SLEEPING
/**
* Dispatched after a sleeping body has woken up.
* @event wakeup
*/
static wakeupEvent = { type: 'wakeup' }
/**
* Dispatched after a body has gone in to the sleepy state.
* @event sleepy
*/
static sleepyEvent = { type: 'sleepy' }
/**
* Dispatched after a body has fallen asleep.
* @event sleep
*/
static sleepEvent = { type: 'sleep' }
/**
* Identifier of the body.
*/
id: number
/**
* Position of body in World.bodies. Updated by World and used in ArrayCollisionMatrix.
*/
index: number
/**
* Reference to the world the body is living in.
*/
world: World | null
vlambda: Vec3
/**
* The collision group the body belongs to.
* @default 1
*/
collisionFilterGroup: number
/**
* The collision group the body can collide with.
* @default -1
*/
collisionFilterMask: number
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled - i.e. "collide" events will be raised, but forces will not be altered.
*/
collisionResponse: boolean
/**
* World space position of the body.
*/
position: Vec3
previousPosition: Vec3
/**
* Interpolated position of the body.
*/
interpolatedPosition: Vec3
/**
* Initial position of the body.
*/
initPosition: Vec3
/**
* World space velocity of the body.
*/
velocity: Vec3
/**
* Initial velocity of the body.
*/
initVelocity: Vec3
/**
* Linear force on the body in world space.
*/
force: Vec3
/**
* The mass of the body.
* @default 0
*/
mass: number
invMass: number
/**
* The physics material of the body. It defines the body interaction with other bodies.
*/
material: Material | null
/**
* How much to damp the body velocity each step. It can go from 0 to 1.
* @default 0.01
*/
linearDamping: number
/**
* One of: `Body.DYNAMIC`, `Body.STATIC` and `Body.KINEMATIC`.
*/
type: BodyType
/**
* If true, the body will automatically fall to sleep.
* @default true
*/
allowSleep: boolean
/**
* Current sleep state.
*/
sleepState: BodySleepState
/**
* If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
* @default 0.1
*/
sleepSpeedLimit: number
/**
* If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
* @default 1
*/
sleepTimeLimit: number
timeLastSleepy: number
wakeUpAfterNarrowphase: boolean
/**
* World space rotational force on the body, around center of mass.
*/
torque: Vec3
/**
* World space orientation of the body.
*/
quaternion: Quaternion
/**
* Initial quaternion of the body.
*/
initQuaternion: Quaternion
previousQuaternion: Quaternion
/**
* Interpolated orientation of the body.
*/
interpolatedQuaternion: Quaternion
/**
* Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
*/
angularVelocity: Vec3
/**
* Initial angular velocity of the body.
*/
initAngularVelocity: Vec3
/**
* List of Shapes that have been added to the body.
*/
shapes: Shape[]
/**
* Position of each Shape in the body, given in local Body space.
*/
shapeOffsets: Vec3[]
/**
* Orientation of each Shape, given in local Body space.
*/
shapeOrientations: Quaternion[]
/**
* The inertia of the body.
*/
inertia: Vec3
invInertia: Vec3
invInertiaWorld: Mat3
invMassSolve: number
invInertiaSolve: Vec3
invInertiaWorldSolve: Mat3
/**
* Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() if you change this after the body creation.
* @default false
*/
fixedRotation: boolean
/**
* How much to damp the body angular velocity each step. It can go from 0 to 1.
* @default 0.01
*/
angularDamping: number
/**
* Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
*/
linearFactor: Vec3
/**
* Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
*/
angularFactor: Vec3
/**
* World space bounding box of the body and its shapes.
*/
aabb: AABB
/**
* Indicates if the AABB needs to be updated before use.
*/
aabbNeedsUpdate: boolean
/**
* Total bounding radius of the Body including its shapes, relative to body.position.
*/
boundingRadius: number
wlambda: Vec3
/**
* When true the body behaves like a trigger. It does not collide
* with other bodies but collision events are still triggered.
* @default false
*/
isTrigger: boolean
constructor(
options: {
/**
* The collision group the body belongs to.
* @default 1
*/
collisionFilterGroup?: number
/**
* The collision group the body can collide with.
* @default -1
*/
collisionFilterMask?: number
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled - i.e. "collide" events will be raised, but forces will not be altered.
*/
collisionResponse?: boolean
/**
* World space position of the body.
*/
position?: Vec3
/**
* World space velocity of the body.
*/
velocity?: Vec3
/**
* The mass of the body.
* @default 0
*/
mass?: number
/**
* The physics material of the body. It defines the body interaction with other bodies.
*/
material?: Material
/**
* How much to damp the body velocity each step. It can go from 0 to 1.
* @default 0.01
*/
linearDamping?: number
/**
* One of: `Body.DYNAMIC`, `Body.STATIC` and `Body.KINEMATIC`.
*/
type?: BodyType
/**
* If true, the body will automatically fall to sleep.
* @default true
*/
allowSleep?: boolean
/**
* If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
* @default 0.1
*/
sleepSpeedLimit?: number
/**
* If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
* @default 1
*/
sleepTimeLimit?: number
/**
* World space orientation of the body.
*/
quaternion?: Quaternion
/**
* Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
*/
angularVelocity?: Vec3
/**
* Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() if you change this after the body creation.
* @default false
*/
fixedRotation?: boolean
/**
* How much to damp the body angular velocity each step. It can go from 0 to 1.
* @default 0.01
*/
angularDamping?: number
/**
* Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
*/
linearFactor?: Vec3
/**
* Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
*/
angularFactor?: Vec3
/**
* Add a Shape to the body.
*/
shape?: Shape
/**
* When true the body behaves like a trigger. It does not collide
* with other bodies but collision events are still triggered.
* @default false
*/
isTrigger?: boolean
} = {}
) {
super()
this.id = Body.idCounter++
this.index = -1
this.world = null
this.vlambda = new Vec3()
this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1
this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1
this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true
this.position = new Vec3()
this.previousPosition = new Vec3()
this.interpolatedPosition = new Vec3()
this.initPosition = new Vec3()
if (options.position) {
this.position.copy(options.position)
this.previousPosition.copy(options.position)
this.interpolatedPosition.copy(options.position)
this.initPosition.copy(options.position)
}
this.velocity = new Vec3()
if (options.velocity) {
this.velocity.copy(options.velocity)
}
this.initVelocity = new Vec3()
this.force = new Vec3()
const mass = typeof options.mass === 'number' ? options.mass : 0
this.mass = mass
this.invMass = mass > 0 ? 1.0 / mass : 0
this.material = options.material || null
this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01
this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC
if (typeof options.type === typeof Body.STATIC) {
this.type = options.type!
}
this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true
this.sleepState = Body.AWAKE
this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1
this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1
this.timeLastSleepy = 0
this.wakeUpAfterNarrowphase = false
this.torque = new Vec3()
this.quaternion = new Quaternion()
this.initQuaternion = new Quaternion()
this.previousQuaternion = new Quaternion()
this.interpolatedQuaternion = new Quaternion()
if (options.quaternion) {
this.quaternion.copy(options.quaternion)
this.initQuaternion.copy(options.quaternion)
this.previousQuaternion.copy(options.quaternion)
this.interpolatedQuaternion.copy(options.quaternion)
}
this.angularVelocity = new Vec3()
if (options.angularVelocity) {
this.angularVelocity.copy(options.angularVelocity)
}
this.initAngularVelocity = new Vec3()
this.shapes = []
this.shapeOffsets = []
this.shapeOrientations = []
this.inertia = new Vec3()
this.invInertia = new Vec3()
this.invInertiaWorld = new Mat3()
this.invMassSolve = 0
this.invInertiaSolve = new Vec3()
this.invInertiaWorldSolve = new Mat3()
this.fixedRotation = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false
this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01
this.linearFactor = new Vec3(1, 1, 1)
if (options.linearFactor) {
this.linearFactor.copy(options.linearFactor)
}
this.angularFactor = new Vec3(1, 1, 1)
if (options.angularFactor) {
this.angularFactor.copy(options.angularFactor)
}
this.aabb = new AABB()
this.aabbNeedsUpdate = true
this.boundingRadius = 0
this.wlambda = new Vec3()
this.isTrigger = Boolean(options.isTrigger)
if (options.shape) {
this.addShape(options.shape)
}
this.updateMassProperties()
}
/**
* Wake the body up.
*/
wakeUp(): void {
const prevState = this.sleepState
this.sleepState = Body.AWAKE
this.wakeUpAfterNarrowphase = false
if (prevState === Body.SLEEPING) {
this.dispatchEvent(Body.wakeupEvent)
}
}
/**
* Force body sleep
*/
sleep(): void {
this.sleepState = Body.SLEEPING
this.velocity.set(0, 0, 0)
this.angularVelocity.set(0, 0, 0)
this.wakeUpAfterNarrowphase = false
}
/**
* Called every timestep to update internal sleep timer and change sleep state if needed.
* @param time The world time in seconds
*/
sleepTick(time: number): void {
if (this.allowSleep) {
const sleepState = this.sleepState
const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared()
const speedLimitSquared = this.sleepSpeedLimit ** 2
if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {
this.sleepState = Body.SLEEPY // Sleepy
this.timeLastSleepy = time
this.dispatchEvent(Body.sleepyEvent)
} else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {
this.wakeUp() // Wake up
} else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {
this.sleep() // Sleeping
this.dispatchEvent(Body.sleepEvent)
}
}
}
/**
* If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
*/
updateSolveMassProperties(): void {
if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {
this.invMassSolve = 0
this.invInertiaSolve.setZero()
this.invInertiaWorldSolve.setZero()
} else {
this.invMassSolve = this.invMass
this.invInertiaSolve.copy(this.invInertia)
this.invInertiaWorldSolve.copy(this.invInertiaWorld)
}
}
/**
* Convert a world point to local body frame.
*/
pointToLocalFrame(worldPoint: Vec3, result = new Vec3()): Vec3 {
worldPoint.vsub(this.position, result)
this.quaternion.conjugate().vmult(result, result)
return result
}
/**
* Convert a world vector to local body frame.
*/
vectorToLocalFrame(worldVector: Vec3, result = new Vec3()): Vec3 {
this.quaternion.conjugate().vmult(worldVector, result)
return result
}
/**
* Convert a local body point to world frame.
*/
pointToWorldFrame(localPoint: Vec3, result = new Vec3()): Vec3 {
this.quaternion.vmult(localPoint, result)
result.vadd(this.position, result)
return result
}
/**
* Convert a local body point to world frame.
*/
vectorToWorldFrame(localVector: Vec3, result = new Vec3()): Vec3 {
this.quaternion.vmult(localVector, result)
return result
}
/**
* Add a shape to the body with a local offset and orientation.
* @return The body object, for chainability.
*/
addShape(shape: Shape, _offset?: Vec3, _orientation?: Quaternion): Body {
const offset = new Vec3()
const orientation = new Quaternion()
if (_offset) {
offset.copy(_offset)
}
if (_orientation) {
orientation.copy(_orientation)
}
this.shapes.push(shape)
this.shapeOffsets.push(offset)
this.shapeOrientations.push(orientation)
this.updateMassProperties()
this.updateBoundingRadius()
this.aabbNeedsUpdate = true
shape.body = this
return this
}
/**
* Remove a shape from the body.
* @return The body object, for chainability.
*/
removeShape(shape: Shape): Body {
const index = this.shapes.indexOf(shape)
if (index === -1) {
console.warn('Shape does not belong to the body')
return this
}
this.shapes.splice(index, 1)
this.shapeOffsets.splice(index, 1)
this.shapeOrientations.splice(index, 1)
this.updateMassProperties()
this.updateBoundingRadius()
this.aabbNeedsUpdate = true
shape.body = null
return this
}
/**
* Update the bounding radius of the body. Should be done if any of the shapes are changed.
*/
updateBoundingRadius(): void {
const shapes = this.shapes
const shapeOffsets = this.shapeOffsets
const N = shapes.length
let radius = 0
for (let i = 0; i !== N; i++) {
const shape = shapes[i]
shape.updateBoundingSphereRadius()
const offset = shapeOffsets[i].length()
const r = shape.boundingSphereRadius
if (offset + r > radius) {
radius = offset + r
}
}
this.boundingRadius = radius
}
/**
* Updates the .aabb
*/
updateAABB(): void {
const shapes = this.shapes
const shapeOffsets = this.shapeOffsets
const shapeOrientations = this.shapeOrientations
const N = shapes.length
const offset = tmpVec
const orientation = tmpQuat
const bodyQuat = this.quaternion
const aabb = this.aabb
const shapeAABB = updateAABB_shapeAABB
for (let i = 0; i !== N; i++) {
const shape = shapes[i]
// Get shape world position
bodyQuat.vmult(shapeOffsets[i], offset)
offset.vadd(this.position, offset)
// Get shape world quaternion
bodyQuat.mult(shapeOrientations[i], orientation)
// Get shape AABB
shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound)
if (i === 0) {
aabb.copy(shapeAABB)
} else {
aabb.extend(shapeAABB)
}
}
this.aabbNeedsUpdate = false
}
/**
* Update `.inertiaWorld` and `.invInertiaWorld`
*/
updateInertiaWorld(force?: boolean): void {
const I = this.invInertia
if (I.x === I.y && I.y === I.z && !force) {
// If inertia M = s*I, where I is identity and s a scalar, then
// R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
// where R is the rotation matrix.
// In other words, we don't have to transform the inertia if all
// inertia diagonal entries are equal.
} else {
const m1 = uiw_m1
const m2 = uiw_m2
const m3 = uiw_m3
m1.setRotationFromQuaternion(this.quaternion)
m1.transpose(m2)
m1.scale(I, m1)
m1.mmult(m2, this.invInertiaWorld)
}
}
/**
* Apply force to a point of the body. This could for example be a point on the Body surface.
* Applying force this way will add to Body.force and Body.torque.
* @param force The amount of force to add.
* @param relativePoint A point relative to the center of mass to apply the force on.
*/
applyForce(force: Vec3, relativePoint: Vec3 = new Vec3()): void {
// Needed?
if (this.type !== Body.DYNAMIC) {
return
}
if (this.sleepState === Body.SLEEPING) {
this.wakeUp()
}
// Compute produced rotational force
const rotForce = Body_applyForce_rotForce
relativePoint.cross(force, rotForce)
// Add linear force
this.force.vadd(force, this.force)
// Add rotational force
this.torque.vadd(rotForce, this.torque)
}
/**
* Apply force to a local point in the body.
* @param force The force vector to apply, defined locally in the body frame.
* @param localPoint A local point in the body to apply the force on.
*/
applyLocalForce(localForce: Vec3, localPoint: Vec3 = new Vec3()): void {
if (this.type !== Body.DYNAMIC) {
return
}
const worldForce = Body_applyLocalForce_worldForce
const relativePointWorld = Body_applyLocalForce_relativePointWorld
// Transform the force vector to world space
this.vectorToWorldFrame(localForce, worldForce)
this.vectorToWorldFrame(localPoint, relativePointWorld)
this.applyForce(worldForce, relativePointWorld)
}
/**
* Apply torque to the body.
* @param torque The amount of torque to add.
*/
applyTorque(torque: Vec3): void {
if (this.type !== Body.DYNAMIC) {
return
}
if (this.sleepState === Body.SLEEPING) {
this.wakeUp()
}
// Add rotational force
this.torque.vadd(torque, this.torque)
}
/**
* Apply impulse to a point of the body. This could for example be a point on the Body surface.
* An impulse is a force added to a body during a short period of time (impulse = force * time).
* Impulses will be added to Body.velocity and Body.angularVelocity.
* @param impulse The amount of impulse to add.
* @param relativePoint A point relative to the center of mass to apply the force on.
*/
applyImpulse(impulse: Vec3, relativePoint: Vec3 = new Vec3()): void {
if (this.type !== Body.DYNAMIC) {
return
}
if (this.sleepState === Body.SLEEPING) {
this.wakeUp()
}
// Compute point position relative to the body center
const r = relativePoint
// Compute produced central impulse velocity
const velo = Body_applyImpulse_velo
velo.copy(impulse)
velo.scale(this.invMass, velo)
// Add linear impulse
this.velocity.vadd(velo, this.velocity)
// Compute produced rotational impulse velocity
const rotVelo = Body_applyImpulse_rotVelo
r.cross(impulse, rotVelo)
/*
rotVelo.x *= this.invInertia.x;
rotVelo.y *= this.invInertia.y;
rotVelo.z *= this.invInertia.z;
*/
this.invInertiaWorld.vmult(rotVelo, rotVelo)
// Add rotational Impulse
this.angularVelocity.vadd(rotVelo, this.angularVelocity)
}
/**
* Apply locally-defined impulse to a local point in the body.
* @param force The force vector to apply, defined locally in the body frame.
* @param localPoint A local point in the body to apply the force on.
*/
applyLocalImpulse(localImpulse: Vec3, localPoint: Vec3 = new Vec3()): void {
if (this.type !== Body.DYNAMIC) {
return
}
const worldImpulse = Body_applyLocalImpulse_worldImpulse
const relativePointWorld = Body_applyLocalImpulse_relativePoint
// Transform the force vector to world space
this.vectorToWorldFrame(localImpulse, worldImpulse)
this.vectorToWorldFrame(localPoint, relativePointWorld)
this.applyImpulse(worldImpulse, relativePointWorld)
}
/**
* Should be called whenever you change the body shape or mass.
*/
updateMassProperties(): void {
const halfExtents = Body_updateMassProperties_halfExtents
this.invMass = this.mass > 0 ? 1.0 / this.mass : 0
const I = this.inertia
const fixed = this.fixedRotation
// Approximate with AABB box
this.updateAABB()
halfExtents.set(
(this.aabb.upperBound.x - this.aabb.lowerBound.x) / 2,
(this.aabb.upperBound.y - this.aabb.lowerBound.y) / 2,
(this.aabb.upperBound.z - this.aabb.lowerBound.z) / 2
)
Box.calculateInertia(halfExtents, this.mass, I)
this.invInertia.set(
I.x > 0 && !fixed ? 1.0 / I.x : 0,
I.y > 0 && !fixed ? 1.0 / I.y : 0,
I.z > 0 && !fixed ? 1.0 / I.z : 0
)
this.updateInertiaWorld(true)
}
/**
* Get world velocity of a point in the body.
* @param worldPoint
* @param result
* @return The result vector.
*/
getVelocityAtWorldPoint(worldPoint: Vec3, result: Vec3): Vec3 {
const r = new Vec3()
worldPoint.vsub(this.position, r)
this.angularVelocity.cross(r, result)
this.velocity.vadd(result, result)
return result
}
/**
* Move the body forward in time.
* @param dt Time step
* @param quatNormalize Set to true to normalize the body quaternion
* @param quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
*/
integrate(dt: number, quatNormalize: boolean, quatNormalizeFast: boolean): void {
// Save previous position
this.previousPosition.copy(this.position)
this.previousQuaternion.copy(this.quaternion)
if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {
// Only for dynamic
return
}
const velo = this.velocity
const angularVelo = this.angularVelocity
const pos = this.position
const force = this.force
const torque = this.torque
const quat = this.quaternion
const invMass = this.invMass
const invInertia = this.invInertiaWorld
const linearFactor = this.linearFactor
const iMdt = invMass * dt
velo.x += force.x * iMdt * linearFactor.x
velo.y += force.y * iMdt * linearFactor.y
velo.z += force.z * iMdt * linearFactor.z
const e = invInertia.elements
const angularFactor = this.angularFactor
const tx = torque.x * angularFactor.x
const ty = torque.y * angularFactor.y
const tz = torque.z * angularFactor.z
angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz)
angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz)
angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz)
// Use new velocity - leap frog
pos.x += velo.x * dt
pos.y += velo.y * dt
pos.z += velo.z * dt
quat.integrate(this.angularVelocity, dt, this.angularFactor, quat)
if (quatNormalize) {
if (quatNormalizeFast) {
quat.normalizeFast()
} else {
quat.normalize()
}
}
this.aabbNeedsUpdate = true
// Update world inertia
this.updateInertiaWorld()
}
}
const tmpVec = new Vec3()
const tmpQuat = new Quaternion()
const updateAABB_shapeAABB = new AABB()
const uiw_m1 = new Mat3()
const uiw_m2 = new Mat3()
const uiw_m3 = new Mat3()
const Body_applyForce_rotForce = new Vec3()
const Body_applyLocalForce_worldForce = new Vec3()
const Body_applyLocalForce_relativePointWorld = new Vec3()
const Body_applyImpulse_velo = new Vec3()
const Body_applyImpulse_rotVelo = new Vec3()
const Body_applyLocalImpulse_worldImpulse = new Vec3()
const Body_applyLocalImpulse_relativePoint = new Vec3()
const Body_updateMassProperties_halfExtents = new Vec3() | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.