text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import type { DataItem } from "../../core/render/Component"; import type * as d3hierarchy from "d3-hierarchy"; import { Hierarchy, IHierarchySettings, IHierarchyDataItem, IHierarchyPrivate, IHierarchyEvents } from "./Hierarchy"; import { Container } from "../../core/render/Container"; import { LinkedHierarchyNode } from "./LinkedHierarchyNode"; import { HierarchyLink } from "./HierarchyLink"; import { Template } from "../../core/util/Template"; import { Circle } from "../../core/render/Circle"; import { ListTemplate } from "../../core/util/List"; import type { IPoint } from "../../core/util/IPoint"; import * as $array from "../../core/util/Array"; import * as $utils from "../../core/util/Utils"; /** * @ignore */ export interface ILinkedHierarchyDataObject { name?: string, value?: number, children?: ILinkedHierarchyDataObject[], dataItem?: DataItem<ILinkedHierarchyDataItem> }; export interface ILinkedHierarchyDataItem extends IHierarchyDataItem { /** * An array of child data items. */ children: Array<DataItem<ILinkedHierarchyDataItem>>; /** * A data item of a parent node. */ parent: DataItem<ILinkedHierarchyDataItem>; /** * A related node. */ node: LinkedHierarchyNode; /** * [[Circle]] element of the related node. */ circle: Circle; /** * [[Circle]] element of the related node, representing outer circle. */ outerCircle: Circle; /** * A [[HierarchyLink]] leading to parent node. */ parentLink: HierarchyLink; /** * An [[HierarchyLink]] leading to parent node. */ links: Array<HierarchyLink>; /** * An array of [[HierarchyLink]] objects leading to child nodes. */ childLinks: Array<HierarchyLink>; /** * An array of IDs of directly linked nodes. */ linkWith: Array<string>; /** * @ignore */ d3HierarchyNode: d3hierarchy.HierarchyPointNode<ILinkedHierarchyDataObject>; } export interface ILinkedHierarchySettings extends IHierarchySettings { /** * A field in data which holds IDs of nodes to link with. */ linkWithField?: string; } export interface ILinkedHierarchyPrivate extends IHierarchyPrivate { } export interface ILinkedHierarchyEvents extends IHierarchyEvents { } /** * A base class for linked hierarchy series. */ export abstract class LinkedHierarchy extends Hierarchy { public static className: string = "LinkedHierarchy"; public static classNames: Array<string> = Hierarchy.classNames.concat([LinkedHierarchy.className]); declare public _settings: ILinkedHierarchySettings; declare public _privateSettings: ILinkedHierarchyPrivate; declare public _dataItemSettings: ILinkedHierarchyDataItem; declare public _events: ILinkedHierarchyEvents; protected _afterNew() { this.fields.push("linkWith", "x", "y"); super._afterNew(); } /** * A list of nodes in a [[LinkedHierarchy]] chart. * * @default new ListTemplate<LinkedHierarchyNode> */ public readonly nodes: ListTemplate<LinkedHierarchyNode> = new ListTemplate( Template.new({}), () => LinkedHierarchyNode._new(this._root, { themeTags: $utils.mergeTags(this.nodes.template.get("themeTags", []), [this._tag, "linkedhierarchy", "hierarchy", "node"]), x: this.width() / 2, y: this.height() / 2 }, [this.nodes.template]) ); /** * A list of node circle elements in a [[LinkedHierarchy]] chart. * * @default new ListTemplate<Circle> */ public readonly circles: ListTemplate<Circle> = new ListTemplate( Template.new({}), () => Circle._new(this._root, { themeTags: $utils.mergeTags(this.circles.template.get("themeTags", []), [this._tag, "shape"]) }, [this.circles.template]) ); /** * A list of node outer circle elements in a [[LinkedHierarchy]] chart. * * @default new ListTemplate<Circle> */ public readonly outerCircles: ListTemplate<Circle> = new ListTemplate( Template.new({}), () => Circle._new(this._root, { themeTags: $utils.mergeTags(this.outerCircles.template.get("themeTags", []), [this._tag, "outer", "shape"]) }, [this.outerCircles.template]) ); /** * A list of link elements in a [[LinkedHierarchy]] chart. * * @default new ListTemplate<HierarchyLink> */ public readonly links: ListTemplate<HierarchyLink> = new ListTemplate( Template.new({}), () => HierarchyLink._new(this._root, { themeTags: $utils.mergeTags(this.links.template.get("themeTags", []), [this._tag, "linkedhierarchy", "hierarchy", "link"]) }, [this.links.template]) ); /** * A [[Container]] that link elements are placed in. * * @default Container.new() */ public readonly linksContainer = this.children.moveValue(Container.new(this._root, {}), 0); /** * @ignore */ public makeNode(dataItem: DataItem<this["_dataItemSettings"]>): LinkedHierarchyNode { const node = super.makeNode(dataItem) as LinkedHierarchyNode; const circle = node.children.moveValue(this.circles.make(), 0); this.circles.push(circle); node.setPrivate("tooltipTarget", circle); dataItem.setRaw("circle", circle); const outerCircle = node.children.moveValue(this.outerCircles.make(), 0); this.outerCircles.push(outerCircle); dataItem.setRaw("outerCircle", outerCircle); const label = dataItem.get("label"); circle.on("radius", () => { const d = circle.get("radius", this.width()) * 2; label.setAll({ maxWidth: d, maxHeight: d }) outerCircle.set("radius", d / 2); this._handleRadiusChange(); }) const d = circle.get("radius", this.width()) * 2; label.setAll({ maxWidth: d, maxHeight: d }); circle._setDataItem(dataItem); outerCircle._setDataItem(dataItem); return node; } public _handleRadiusChange() { } protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { dataItem.setRaw("childLinks", []); dataItem.setRaw("links", []); super.processDataItem(dataItem); } protected _processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { super._processDataItem(dataItem); const parentDataItem = dataItem.get("parent"); if (parentDataItem && parentDataItem.get("depth") >= this.get("topDepth")) { const link = this.linkDataItems(parentDataItem, dataItem); dataItem.setRaw("parentLink", link); } const node = dataItem.get("node"); this.updateLinkWith(this.dataItems); node._updateLinks(0); } /** * @ignore */ public updateLinkWith(dataItems: Array<DataItem<this["_dataItemSettings"]>>) { $array.each(dataItems, (dataItem) => { const linkWith = dataItem.get("linkWith"); if (linkWith) { $array.each(linkWith, (id) => { const linkWithDataItem = this._getDataItemById(this.dataItems, id); if (linkWithDataItem) { this.linkDataItems(dataItem, linkWithDataItem); } }) } const children = dataItem.get("children"); if (children) { this.updateLinkWith(children); } }) } protected _getPoint(hierarchyNode: this["_dataItemSettings"]["d3HierarchyNode"]): IPoint { return { x: hierarchyNode.x, y: hierarchyNode.y }; } protected _updateNode(dataItem: DataItem<this["_dataItemSettings"]>) { super._updateNode(dataItem); const node = dataItem.get("node"); const hierarchyNode = dataItem.get("d3HierarchyNode"); const point = this._getPoint(hierarchyNode); const duration = this.get("animationDuration", 0); const easing = this.get("animationEasing"); node.animate({ key: "x", to: point.x, duration: duration, easing: easing }); node.animate({ key: "y", to: point.y, duration: duration, easing: easing }); const hierarchyChildren = hierarchyNode.children; if (hierarchyChildren) { $array.each(hierarchyChildren, (hierarchyChild) => { this._updateNodes(hierarchyChild) }) } const fill = dataItem.get("fill"); const circle = dataItem.get("circle"); const children = dataItem.get("children"); if (circle) { circle._setDefault("fill", fill); circle._setDefault("stroke", fill); } const outerCircle = dataItem.get("outerCircle"); if (outerCircle) { outerCircle._setDefault("fill", fill); outerCircle._setDefault("stroke", fill); if (!children || children.length == 0) { outerCircle.setPrivate("visible", false); } } } /** * Link two data items with a link element. * * @param source Source node data item * @param target Target node data item * @param strength Link strength * @return Link element */ public linkDataItems(source: DataItem<this["_dataItemSettings"]>, target: DataItem<this["_dataItemSettings"]>, strength?: number): HierarchyLink { let link!: HierarchyLink; const sourceLinks = source.get("links"); if (sourceLinks) { $array.each(sourceLinks, (lnk) => { if (lnk.get("target") == target) { link = lnk; } }) } const targetLinks = target.get("links"); if (targetLinks) { $array.each(targetLinks, (lnk) => { if (lnk.get("target") == source) { link = lnk; } }) } if (!link) { link = this.links.make(); this.links.push(link); this.linksContainer.children.push(link); link.set("source", source); link.set("target", target); link._setDataItem(source); link.set("stroke", source.get("fill")); if (strength != null) { link.set("strength", strength) } source.get("childLinks").push(link); $array.move(source.get("links"), link); $array.move(target.get("links"), link); this._processLink(link, source, target); } return link; } /** * Unlink two linked data items. * * @param source Source node data item * @param target Target node data item */ public unlinkDataItems(source: DataItem<this["_dataItemSettings"]>, target: DataItem<this["_dataItemSettings"]>) { let link!: HierarchyLink; const sourceLinks = source.get("links"); if (sourceLinks) { $array.each(sourceLinks, (lnk) => { if (lnk && lnk.get("target") == target) { link = lnk; $array.remove(sourceLinks, link); } }) } const targetLinks = target.get("links"); if (targetLinks) { $array.each(targetLinks, (lnk) => { if (lnk && lnk.get("target") == source) { link = lnk; $array.remove(targetLinks, link); } }) } if (link) { this._disposeLink(link); } this._handleUnlink(); } protected _handleUnlink() { } protected _disposeLink(link: HierarchyLink) { this.links.removeValue(link); link.dispose(); } /** * Returns `true` if two nodes are linked with each other. */ public areLinked(source: DataItem<this["_dataItemSettings"]>, target: DataItem<this["_dataItemSettings"]>): boolean { const sourceLinks = source.get("links"); let linked = false; if (sourceLinks) { $array.each(sourceLinks, (lnk) => { if (lnk.get("target") == target) { linked = true; } }) } const targetLinks = target.get("links"); if (targetLinks) { $array.each(targetLinks, (lnk) => { if (lnk.get("target") == source) { linked = true; } }) } return linked; } protected _processLink(_link: HierarchyLink, _source: DataItem<this["_dataItemSettings"]>, _target: DataItem<this["_dataItemSettings"]>) { } /** * @ignore */ public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { super.disposeDataItem(dataItem); const links = dataItem.get("links"); if (links) { $array.each(links, (link) => { this._disposeLink(link) }) } } /** * Select a data item. * @param dataItem Data item */ public selectDataItem(dataItem: DataItem<this["_dataItemSettings"]>) { const parent = dataItem.get("parent"); if (!dataItem.get("disabled")) { this.set("selectedDataItem", dataItem); this._selectDataItem(dataItem); } else { if (parent) { this.setRaw("selectedDataItem", parent); const type = "dataitemselected"; this.events.dispatch(type, { type: type, target: this, dataItem: parent }); this.disableDataItem(dataItem); } } } }
the_stack
declare module 'tls' { import { X509Certificate } from 'node:crypto'; import * as net from 'node:net'; const CLIENT_RENEG_LIMIT: number; const CLIENT_RENEG_WINDOW: number; interface Certificate { /** * Country code. */ C: string; /** * Street. */ ST: string; /** * Locality. */ L: string; /** * Organization. */ O: string; /** * Organizational unit. */ OU: string; /** * Common name. */ CN: string; } interface PeerCertificate { subject: Certificate; issuer: Certificate; subjectaltname: string; infoAccess: NodeJS.Dict<string[]>; modulus: string; exponent: string; valid_from: string; valid_to: string; fingerprint: string; fingerprint256: string; ext_key_usage: string[]; serialNumber: string; raw: Buffer; } interface DetailedPeerCertificate extends PeerCertificate { issuerCertificate: DetailedPeerCertificate; } interface CipherNameAndProtocol { /** * The cipher name. */ name: string; /** * SSL/TLS protocol version. */ version: string; /** * IETF name for the cipher suite. */ standardName: string; } interface EphemeralKeyInfo { /** * The supported types are 'DH' and 'ECDH'. */ type: string; /** * The name property is available only when type is 'ECDH'. */ name?: string | undefined; /** * The size of parameter of an ephemeral key exchange. */ size: number; } interface KeyObject { /** * Private keys in PEM format. */ pem: string | Buffer; /** * Optional passphrase. */ passphrase?: string | undefined; } interface PxfObject { /** * PFX or PKCS12 encoded private key and certificate chain. */ buf: string | Buffer; /** * Optional passphrase. */ passphrase?: string | undefined; } interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { /** * If true the TLS socket will be instantiated in server-mode. * Defaults to false. */ isServer?: boolean | undefined; /** * An optional net.Server instance. */ server?: net.Server | undefined; /** * An optional Buffer instance containing a TLS session. */ session?: Buffer | undefined; /** * If true, specifies that the OCSP status request extension will be * added to the client hello and an 'OCSPResponse' event will be * emitted on the socket before establishing a secure communication */ requestOCSP?: boolean | undefined; } /** * Performs transparent encryption of written data and all required TLS * negotiation. * * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. * * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the * connection is open. * @since v0.11.4 */ class TLSSocket extends net.Socket { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ constructor(socket: net.Socket, options?: TLSSocketOptions); /** * Returns `true` if the peer certificate was signed by one of the CAs specified * when creating the `tls.TLSSocket` instance, otherwise `false`. * @since v0.11.4 */ authorized: boolean; /** * Returns the reason why the peer's certificate was not been verified. This * property is set only when `tlsSocket.authorized === false`. * @since v0.11.4 */ authorizationError: Error; /** * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. * @since v0.11.4 */ encrypted: boolean; /** * String containing the selected ALPN protocol. * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. */ alpnProtocol?: string | undefined; /** * Returns an object representing the local certificate. The returned object has * some properties corresponding to the fields of the certificate. * * See {@link TLSSocket.getPeerCertificate} for an example of the certificate * structure. * * If there is no local certificate, an empty object will be returned. If the * socket has been destroyed, `null` will be returned. * @since v11.2.0 */ getCertificate(): PeerCertificate | object | null; /** * Returns an object containing information on the negotiated cipher suite. * * For example: * * ```json * { * "name": "AES128-SHA256", * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", * "version": "TLSv1.2" * } * ``` * * See[SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html)for more information. * @since v0.11.4 */ getCipher(): CipherNameAndProtocol; /** * Returns an object representing the type, name, and size of parameter of * an ephemeral key exchange in `perfect forward secrecy` on a client * connection. It returns an empty object when the key exchange is not * ephemeral. As this is only supported on a client socket; `null` is returned * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. * * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. * @since v5.0.0 */ getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; /** * As the `Finished` messages are message digests of the complete handshake * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can * be used for external authentication procedures when the authentication * provided by SSL/TLS is not desired or is not enough. * * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). * @since v9.9.0 * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. */ getFinished(): Buffer | undefined; /** * Returns an object representing the peer's certificate. If the peer does not * provide a certificate, an empty object will be returned. If the socket has been * destroyed, `null` will be returned. * * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's * certificate. * @since v0.11.4 * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. * @return A certificate object. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * As the `Finished` messages are message digests of the complete handshake * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can * be used for external authentication procedures when the authentication * provided by SSL/TLS is not desired or is not enough. * * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). * @since v9.9.0 * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so * far. */ getPeerFinished(): Buffer | undefined; /** * Returns a string containing the negotiated SSL/TLS protocol version of the * current connection. The value `'unknown'` will be returned for connected * sockets that have not completed the handshaking process. The value `null` will * be returned for server sockets or disconnected client sockets. * * Protocol versions are: * * * `'SSLv3'` * * `'TLSv1'` * * `'TLSv1.1'` * * `'TLSv1.2'` * * `'TLSv1.3'` * * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. * @since v5.7.0 */ getProtocol(): string | null; /** * Returns the TLS session data or `undefined` if no session was * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful * for debugging. * * See `Session Resumption` for more information. * * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications * must use the `'session'` event (it also works for TLSv1.2 and below). * @since v0.11.4 */ getSession(): Buffer | undefined; /** * See[SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html)for more information. * @since v12.11.0 * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. */ getSharedSigalgs(): string[]; /** * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. * * It may be useful for debugging. * * See `Session Resumption` for more information. * @since v0.11.4 */ getTLSTicket(): Buffer | undefined; /** * See `Session Resumption` for more information. * @since v0.5.6 * @return `true` if the session was reused, `false` otherwise. */ isSessionReused(): boolean; /** * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. * Upon completion, the `callback` function will be passed a single argument * that is either an `Error` (if the request failed) or `null`. * * This method can be used to request a peer's certificate after the secure * connection has been established. * * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. * * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the * protocol. * @since v0.11.8 * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. * @return `true` if renegotiation was initiated, `false` otherwise. */ renegotiate( options: { rejectUnauthorized?: boolean | undefined; requestCert?: boolean | undefined; }, callback: (err: Error | null) => void ): undefined | boolean; /** * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. * Returns `true` if setting the limit succeeded; `false` otherwise. * * Smaller fragment sizes decrease the buffering latency on the client: larger * fragments are buffered by the TLS layer until the entire fragment is received * and its integrity is verified; large fragments can span multiple roundtrips * and their processing can be delayed due to packet loss or reordering. However, * smaller fragments add extra TLS framing bytes and CPU overhead, which may * decrease overall server throughput. * @since v0.11.11 * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. */ setMaxSendFragment(size: number): boolean; /** * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts * to renegotiate will trigger an `'error'` event on the `TLSSocket`. * @since v8.4.0 */ disableRenegotiation(): void; /** * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. * * Note: The format of the output is identical to the output of `openssl s_client -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's`SSL_trace()` function, the format is * undocumented, can change without notice, * and should not be relied on. * @since v12.2.0 */ enableTrace(): void; /** * Returns the peer certificate as an `X509Certificate` object. * * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. * @since v15.9.0 */ getPeerX509Certificate(): X509Certificate | undefined; /** * Returns the local certificate as an `X509Certificate` object. * * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. * @since v15.9.0 */ getX509Certificate(): X509Certificate | undefined; /** * Keying material is used for validations to prevent different kind of attacks in * network protocols, for example in the specifications of IEEE 802.1X. * * Example * * ```js * const keyingMaterial = tlsSocket.exportKeyingMaterial( * 128, * 'client finished'); * * * Example return value of keyingMaterial: * <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9 * 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91 * 74 ef 2c ... 78 more bytes> * * ``` * * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more * information. * @since v13.10.0, v12.17.0 * @param length number of bytes to retrieve from keying material * @param label an application specific label, typically this will be a value from the [IANA Exporter Label * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). * @param context Optionally provide a context. * @return requested bytes of the keying material */ exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; addListener(event: 'secureConnect', listener: () => void): this; addListener(event: 'session', listener: (session: Buffer) => void): this; addListener(event: 'keylog', listener: (line: Buffer) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: 'OCSPResponse', response: Buffer): boolean; emit(event: 'secureConnect'): boolean; emit(event: 'session', session: Buffer): boolean; emit(event: 'keylog', line: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; on(event: 'secureConnect', listener: () => void): this; on(event: 'session', listener: (session: Buffer) => void): this; on(event: 'keylog', listener: (line: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; once(event: 'secureConnect', listener: () => void): this; once(event: 'session', listener: (session: Buffer) => void): this; once(event: 'keylog', listener: (line: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; prependListener(event: 'secureConnect', listener: () => void): this; prependListener(event: 'session', listener: (session: Buffer) => void): this; prependListener(event: 'keylog', listener: (line: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; prependOnceListener(event: 'secureConnect', listener: () => void): this; prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; } interface CommonConnectionOptions { /** * An optional TLS context object from tls.createSecureContext() */ secureContext?: SecureContext | undefined; /** * When enabled, TLS packet trace information is written to `stderr`. This can be * used to debug TLS connection problems. * @default false */ enableTrace?: boolean | undefined; /** * If true the server will request a certificate from clients that * connect and attempt to verify that certificate. Defaults to * false. */ requestCert?: boolean | undefined; /** * An array of strings or a Buffer naming possible ALPN protocols. * (Protocols should be ordered by their priority.) */ ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; /** * SNICallback(servername, cb) <Function> A function that will be * called if the client supports SNI TLS extension. Two arguments * will be passed when called: servername and cb. SNICallback should * invoke cb(null, ctx), where ctx is a SecureContext instance. * (tls.createSecureContext(...) can be used to get a proper * SecureContext.) If SNICallback wasn't provided the default callback * with high-level API will be used (see below). */ SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; /** * If true the server will reject any connection which is not * authorized with the list of supplied CAs. This option only has an * effect if requestCert is true. * @default true */ rejectUnauthorized?: boolean | undefined; } interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { /** * Abort the connection if the SSL/TLS handshake does not finish in the * specified number of milliseconds. A 'tlsClientError' is emitted on * the tls.Server object whenever a handshake times out. Default: * 120000 (120 seconds). */ handshakeTimeout?: number | undefined; /** * The number of seconds after which a TLS session created by the * server will no longer be resumable. See Session Resumption for more * information. Default: 300. */ sessionTimeout?: number | undefined; /** * 48-bytes of cryptographically strong pseudo-random data. */ ticketKeys?: Buffer | undefined; /** * * @param socket * @param identity identity parameter sent from the client. * @return pre-shared key that must either be * a buffer or `null` to stop the negotiation process. Returned PSK must be * compatible with the selected cipher's digest. * * When negotiating TLS-PSK (pre-shared keys), this function is called * with the identity provided by the client. * If the return value is `null` the negotiation process will stop and an * "unknown_psk_identity" alert message will be sent to the other party. * If the server wishes to hide the fact that the PSK identity was not known, * the callback must provide some random data as `psk` to make the connection * fail with "decrypt_error" before negotiation is finished. * PSK ciphers are disabled by default, and using TLS-PSK thus * requires explicitly specifying a cipher suite with the `ciphers` option. * More information can be found in the RFC 4279. */ pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; /** * hint to send to a client to help * with selecting the identity during TLS-PSK negotiation. Will be ignored * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. */ pskIdentityHint?: string | undefined; } interface PSKCallbackNegotation { psk: DataView | NodeJS.TypedArray; identity: string; } interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { host?: string | undefined; port?: number | undefined; path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. socket?: net.Socket | undefined; // Establish secure connection on a given socket rather than creating a new socket checkServerIdentity?: typeof checkServerIdentity | undefined; servername?: string | undefined; // SNI TLS Extension session?: Buffer | undefined; minDHSize?: number | undefined; lookup?: net.LookupFunction | undefined; timeout?: number | undefined; /** * When negotiating TLS-PSK (pre-shared keys), this function is called * with optional identity `hint` provided by the server or `null` * in case of TLS 1.3 where `hint` was removed. * It will be necessary to provide a custom `tls.checkServerIdentity()` * for the connection as the default one will try to check hostname/IP * of the server against the certificate but that's not applicable for PSK * because there won't be a certificate present. * More information can be found in the RFC 4279. * * @param hint message sent from the server to help client * decide which identity to use during negotiation. * Always `null` if TLS 1.3 is used. * @returns Return `null` to stop the negotiation process. `psk` must be * compatible with the selected cipher's digest. * `identity` must use UTF-8 encoding. */ pskCallback?(hint: string | null): PSKCallbackNegotation | null; } /** * Accepts encrypted connections using TLS or SSL. * @since v0.3.2 */ class Server extends net.Server { constructor(secureConnectionListener?: (socket: TLSSocket) => void); constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); /** * The `server.addContext()` method adds a secure context that will be used if * the client request's SNI name matches the supplied `hostname` (or wildcard). * * When there are multiple matching contexts, the most recently added one is * used. * @since v0.5.3 * @param hostname A SNI host name or wildcard (e.g. `'*'`) * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). */ addContext(hostname: string, context: SecureContextOptions): void; /** * Returns the session ticket keys. * * See `Session Resumption` for more information. * @since v3.0.0 * @return A 48-byte buffer containing the session ticket keys. */ getTicketKeys(): Buffer; /** * The `server.setSecureContext()` method replaces the secure context of an * existing server. Existing connections to the server are not interrupted. * @since v11.0.0 * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). */ setSecureContext(options: SecureContextOptions): void; /** * Sets the session ticket keys. * * Changes to the ticket keys are effective only for future server connections. * Existing or currently pending server connections will use the previous keys. * * See `Session Resumption` for more information. * @since v3.0.0 * @param keys A 48-byte buffer containing the session ticket keys. */ setTicketKeys(keys: Buffer): void; /** * events.EventEmitter * 1. tlsClientError * 2. newSession * 3. OCSPRequest * 4. resumeSession * 5. secureConnection * 6. keylog */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean; emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean; emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; } /** * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. */ interface SecurePair { encrypted: TLSSocket; cleartext: TLSSocket; } type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; interface SecureContextOptions { /** * Optionally override the trusted CA certificates. Default is to trust * the well-known CAs curated by Mozilla. Mozilla's CAs are completely * replaced when CAs are explicitly specified using this option. */ ca?: string | Buffer | Array<string | Buffer> | undefined; /** * Cert chains in PEM format. One cert chain should be provided per * private key. Each cert chain should consist of the PEM formatted * certificate for a provided private key, followed by the PEM * formatted intermediate certificates (if any), in order, and not * including the root CA (the root CA must be pre-known to the peer, * see ca). When providing multiple cert chains, they do not have to * be in the same order as their private keys in key. If the * intermediate certificates are not provided, the peer will not be * able to validate the certificate, and the handshake will fail. */ cert?: string | Buffer | Array<string | Buffer> | undefined; /** * Colon-separated list of supported signature algorithms. The list * can contain digest algorithms (SHA256, MD5 etc.), public key * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). */ sigalgs?: string | undefined; /** * Cipher suite specification, replacing the default. For more * information, see modifying the default cipher suite. Permitted * ciphers can be obtained via tls.getCiphers(). Cipher names must be * uppercased in order for OpenSSL to accept them. */ ciphers?: string | undefined; /** * Name of an OpenSSL engine which can provide the client certificate. */ clientCertEngine?: string | undefined; /** * PEM formatted CRLs (Certificate Revocation Lists). */ crl?: string | Buffer | Array<string | Buffer> | undefined; /** * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use * openssl dhparam to create the parameters. The key length must be * greater than or equal to 1024 bits or else an error will be thrown. * Although 1024 bits is permissible, use 2048 bits or larger for * stronger security. If omitted or invalid, the parameters are * silently discarded and DHE ciphers will not be available. */ dhparam?: string | Buffer | undefined; /** * A string describing a named curve or a colon separated list of curve * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key * agreement. Set to auto to select the curve automatically. Use * crypto.getCurves() to obtain a list of available curve names. On * recent releases, openssl ecparam -list_curves will also display the * name and description of each available elliptic curve. Default: * tls.DEFAULT_ECDH_CURVE. */ ecdhCurve?: string | undefined; /** * Attempt to use the server's cipher suite preferences instead of the * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be * set in secureOptions */ honorCipherOrder?: boolean | undefined; /** * Private keys in PEM format. PEM allows the option of private keys * being encrypted. Encrypted keys will be decrypted with * options.passphrase. Multiple keys using different algorithms can be * provided either as an array of unencrypted key strings or buffers, * or an array of objects in the form {pem: <string|buffer>[, * passphrase: <string>]}. The object form can only occur in an array. * object.passphrase is optional. Encrypted keys will be decrypted with * object.passphrase if provided, or options.passphrase if it is not. */ key?: string | Buffer | Array<Buffer | KeyObject> | undefined; /** * Name of an OpenSSL engine to get private key from. Should be used * together with privateKeyIdentifier. */ privateKeyEngine?: string | undefined; /** * Identifier of a private key managed by an OpenSSL engine. Should be * used together with privateKeyEngine. Should not be set together with * key, because both options define a private key in different ways. */ privateKeyIdentifier?: string | undefined; /** * Optionally set the maximum TLS version to allow. One * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the * `secureProtocol` option, use one or the other. * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. */ maxVersion?: SecureVersion | undefined; /** * Optionally set the minimum TLS version to allow. One * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the * `secureProtocol` option, use one or the other. It is not recommended to use * less than TLSv1.2, but it may be required for interoperability. * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. */ minVersion?: SecureVersion | undefined; /** * Shared passphrase used for a single private key and/or a PFX. */ passphrase?: string | undefined; /** * PFX or PKCS12 encoded private key and certificate chain. pfx is an * alternative to providing key and cert individually. PFX is usually * encrypted, if it is, passphrase will be used to decrypt it. Multiple * PFX can be provided either as an array of unencrypted PFX buffers, * or an array of objects in the form {buf: <string|buffer>[, * passphrase: <string>]}. The object form can only occur in an array. * object.passphrase is optional. Encrypted PFX will be decrypted with * object.passphrase if provided, or options.passphrase if it is not. */ pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined; /** * Optionally affect the OpenSSL protocol behavior, which is not * usually necessary. This should be used carefully if at all! Value is * a numeric bitmask of the SSL_OP_* options from OpenSSL Options */ secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options /** * Legacy mechanism to select the TLS protocol version to use, it does * not support independent control of the minimum and maximum version, * and does not support limiting the protocol to TLSv1.3. Use * minVersion and maxVersion instead. The possible values are listed as * SSL_METHODS, use the function names as strings. For example, use * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow * any TLS protocol version up to TLSv1.3. It is not recommended to use * TLS versions less than 1.2, but it may be required for * interoperability. Default: none, see minVersion. */ secureProtocol?: string | undefined; /** * Opaque identifier used by servers to ensure session state is not * shared between applications. Unused by clients. */ sessionIdContext?: string | undefined; /** * 48-bytes of cryptographically strong pseudo-random data. * See Session Resumption for more information. */ ticketKeys?: Buffer | undefined; /** * The number of seconds after which a TLS session created by the * server will no longer be resumable. See Session Resumption for more * information. Default: 300. */ sessionTimeout?: number | undefined; } interface SecureContext { context: any; } /** * Verifies the certificate `cert` is issued to `hostname`. * * Returns [&lt;Error&gt;](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on * failure. On success, returns [&lt;undefined&gt;](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). * * This function can be overwritten by providing alternative function as part of * the `options.checkServerIdentity` option passed to `tls.connect()`. The * overwriting function can call `tls.checkServerIdentity()` of course, to augment * the checks done with additional verification. * * This function is only called if the certificate passed all other checks, such as * being issued by trusted CA (`options.ca`). * @since v0.8.4 * @param hostname The host name or IP address to verify the certificate against. * @param cert A `certificate object` representing the peer's certificate. */ function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; /** * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is * automatically set as a listener for the `'secureConnection'` event. * * The `ticketKeys` options is automatically shared between `cluster` module * workers. * * The following illustrates a simple echo server: * * ```js * const tls = require('tls'); * const fs = require('fs'); * * const options = { * key: fs.readFileSync('server-key.pem'), * cert: fs.readFileSync('server-cert.pem'), * * // This is necessary only if using client certificate authentication. * requestCert: true, * * // This is necessary only if the client uses a self-signed certificate. * ca: [ fs.readFileSync('client-cert.pem') ] * }; * * const server = tls.createServer(options, (socket) => { * console.log('server connected', * socket.authorized ? 'authorized' : 'unauthorized'); * socket.write('welcome!\n'); * socket.setEncoding('utf8'); * socket.pipe(socket); * }); * server.listen(8000, () => { * console.log('server bound'); * }); * ``` * * The server can be tested by connecting to it using the example client from {@link connect}. * @since v0.3.2 */ function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; /** * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. * * `tls.connect()` returns a {@link TLSSocket} object. * * Unlike the `https` API, `tls.connect()` does not enable the * SNI (Server Name Indication) extension by default, which may cause some * servers to return an incorrect certificate or reject the connection * altogether. To enable SNI, set the `servername` option in addition * to `host`. * * The following illustrates a client for the echo server example from {@link createServer}: * * ```js * // Assumes an echo server that is listening on port 8000. * const tls = require('tls'); * const fs = require('fs'); * * const options = { * // Necessary only if the server requires client certificate authentication. * key: fs.readFileSync('client-key.pem'), * cert: fs.readFileSync('client-cert.pem'), * * // Necessary only if the server uses a self-signed certificate. * ca: [ fs.readFileSync('server-cert.pem') ], * * // Necessary only if the server's cert isn't for "localhost". * checkServerIdentity: () => { return null; }, * }; * * const socket = tls.connect(8000, options, () => { * console.log('client connected', * socket.authorized ? 'authorized' : 'unauthorized'); * process.stdin.pipe(socket); * process.stdin.resume(); * }); * socket.setEncoding('utf8'); * socket.on('data', (data) => { * console.log(data); * }); * socket.on('end', () => { * console.log('server ends connection'); * }); * ``` * @since v0.11.3 */ function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; /** * Creates a new secure pair object with two streams, one of which reads and writes * the encrypted data and the other of which reads and writes the cleartext data. * Generally, the encrypted stream is piped to/from an incoming encrypted data * stream and the cleartext one is used as a replacement for the initial encrypted * stream. * * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. * * Using `cleartext` has the same API as {@link TLSSocket}. * * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: * * ```js * pair = tls.createSecurePair(// ... ); * pair.encrypted.pipe(socket); * socket.pipe(pair.encrypted); * ``` * * can be replaced by: * * ```js * secureSocket = tls.TLSSocket(socket, options); * ``` * * where `secureSocket` has the same API as `pair.cleartext`. * @since v0.3.2 * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. * @param context A secure context object as returned by `tls.createSecureContext()` * @param isServer `true` to specify that this TLS connection should be opened as a server. * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. */ function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; /** * {@link createServer} sets the default value of the `honorCipherOrder` option * to `true`, other APIs that create secure contexts leave it unset. * * {@link createServer} uses a 128 bit truncated SHA1 hash value generated * from `process.argv` as the default value of the `sessionIdContext` option, other * APIs that create secure contexts have no default value. * * The `tls.createSecureContext()` method creates a `SecureContext` object. It is * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. * * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. * * If the `ca` option is not given, then Node.js will default to using[Mozilla's publicly trusted list of * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). * @since v0.11.13 */ function createSecureContext(options?: SecureContextOptions): SecureContext; /** * Returns an array with the names of the supported TLS ciphers. The names are * lower-case for historical reasons, but must be uppercased to be used in * the `ciphers` option of {@link createSecureContext}. * * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for * TLSv1.2 and below. * * ```js * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] * ``` * @since v0.10.2 */ function getCiphers(): string[]; /** * The default curve name to use for ECDH key agreement in a tls server. * The default value is 'auto'. See tls.createSecureContext() for further * information. */ let DEFAULT_ECDH_CURVE: string; /** * The default value of the maxVersion option of * tls.createSecureContext(). It can be assigned any of the supported TLS * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to * 'TLSv1.3'. If multiple of the options are provided, the highest maximum * is used. */ let DEFAULT_MAX_VERSION: SecureVersion; /** * The default value of the minVersion option of tls.createSecureContext(). * It can be assigned any of the supported TLS protocol versions, * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless * changed using CLI options. Using --tls-min-v1.0 sets the default to * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options * are provided, the lowest minimum is used. */ let DEFAULT_MIN_VERSION: SecureVersion; /** * An immutable array of strings representing the root certificates (in PEM * format) used for verifying peer certificates. This is the default value * of the ca option to tls.createSecureContext(). */ const rootCertificates: ReadonlyArray<string>; } declare module 'node:tls' { export * from 'tls'; }
the_stack
import { Dialog, Dropdown, ICommandBarItemProps, Icon, IconButton, IDropdownOption, LayerHost, Position, ProgressIndicator, SpinButton, Stack, Toggle, TooltipHost } from '@fluentui/react'; import { useBoolean, useId } from '@fluentui/react-hooks'; import { FormEvent, KeyboardEvent, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { CommandBar, DemoMode, DeviceView, DeviceViewRef, ErrorDialogContext, ExternalLink } from '../../components'; import { CommonStackTokens } from '../../styles'; import { formatSpeed, useSpeed, withDisplayName } from '../../utils'; import { useAdbDevice } from '../type'; import { Decoder, DecoderConstructor } from "./decoder"; import { AndroidCodecLevel, AndroidCodecProfile, AndroidKeyCode, AndroidMotionEventAction, fetchServer, ScrcpyClient, ScrcpyClientOptions, ScrcpyLogLevel, ScrcpyScreenOrientation, ScrcpyServerVersion } from './server'; import { TinyH264DecoderWrapper } from "./tinyh264"; import { WebCodecsDecoder } from "./webcodecs/decoder"; const DeviceServerPath = '/data/local/tmp/scrcpy-server.jar'; const decoders: { name: string; factory: DecoderConstructor; }[] = [{ name: 'TinyH264 (Software)', factory: TinyH264DecoderWrapper, }]; if (typeof window.VideoDecoder === 'function') { decoders.push({ name: 'WebCodecs', factory: WebCodecsDecoder, }); } function clamp(value: number, min: number, max: number): number { if (value < min) { return min; } if (value > max) { return max; } return value; } export const Scrcpy = withDisplayName('Scrcpy')((): JSX.Element | null => { const { show: showErrorDialog } = useContext(ErrorDialogContext); const device = useAdbDevice(); const [running, setRunning] = useState(false); const [canvasKey, setCanvasKey] = useState(decoders[0].name); const canvasRef = useRef<HTMLCanvasElement | null>(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const handleCanvasRef = useCallback((canvas: HTMLCanvasElement | null) => { canvasRef.current = canvas; if (canvas) { canvas.addEventListener('touchstart', e => { e.preventDefault(); }); canvas.addEventListener('contextmenu', e => { e.preventDefault(); }); } }, []); const [connecting, setConnecting] = useState(false); const [serverTotalSize, setServerTotalSize] = useState(0); const [serverDownloadedSize, setServerDownloadedSize] = useState(0); const [debouncedServerDownloadedSize, serverDownloadSpeed] = useSpeed(serverDownloadedSize, serverTotalSize); const [serverUploadedSize, setServerUploadedSize] = useState(0); const [debouncedServerUploadedSize, serverUploadSpeed] = useSpeed(serverUploadedSize, serverTotalSize); const [settingsVisible, { toggle: toggleSettingsVisible }] = useBoolean(false); const [selectedDecoder, setSelectedDecoder] = useState(decoders[0]); const decoderRef = useRef<Decoder | undefined>(undefined); const handleSelectedDecoderChange = useCallback((e?: FormEvent<HTMLElement>, option?: IDropdownOption) => { if (!option) { return; } setSelectedDecoder(option.data as { name: string; factory: DecoderConstructor; }); }, []); useLayoutEffect(() => { if (!running) { // Different decoders may need different canvas context, // but it's impossible to change context type on a canvas element, // so re-render canvas element after stopped setCanvasKey(selectedDecoder.name); } }, [running, selectedDecoder]); const [encoders, setEncoders] = useState<string[]>([]); const [currentEncoder, setCurrentEncoder] = useState<string>(); const handleCurrentEncoderChange = useCallback((e?: FormEvent<HTMLElement>, option?: IDropdownOption) => { if (!option) { return; } setCurrentEncoder(option.key as string); }, []); const [resolution, setResolution] = useState(1080); const handleResolutionChange = useCallback((e: any, value?: string) => { if (value === undefined) { return; } setResolution(+value); }, []); const [bitRate, setBitRate] = useState(4_000_000); const handleBitRateChange = useCallback((e: any, value?: string) => { if (value === undefined) { return; } setBitRate(+value); }, []); const [tunnelForward, setTunnelForward] = useState(false); const handleTunnelForwardChange = useCallback((event: React.MouseEvent<HTMLElement>, checked?: boolean) => { if (checked === undefined) { return; } setTunnelForward(checked); }, []); const scrcpyClientRef = useRef<ScrcpyClient>(); const [demoModeVisible, { toggle: toggleDemoModeVisible }] = useBoolean(false); const start = useCallback(() => { if (!device) { return; } (async () => { try { if (!selectedDecoder) { throw new Error('No available decoder'); } setServerTotalSize(0); setServerDownloadedSize(0); setServerUploadedSize(0); setConnecting(true); const serverBuffer = await fetchServer(([downloaded, total]) => { setServerDownloadedSize(downloaded); setServerTotalSize(total); }); const sync = await device.sync(); await sync.write( DeviceServerPath, serverBuffer, undefined, undefined, setServerUploadedSize ); let tunnelForward!: boolean; setTunnelForward(current => { tunnelForward = current; return current; }); const encoders = await ScrcpyClient.getEncoders({ device, path: DeviceServerPath, version: ScrcpyServerVersion, logLevel: ScrcpyLogLevel.Debug, bitRate: 4_000_000, tunnelForward, }); if (encoders.length === 0) { throw new Error('No available encoder found'); } setEncoders(encoders); // Run scrcpy once will delete the server file // Re-push it await sync.write( DeviceServerPath, serverBuffer, ); const options: ScrcpyClientOptions = { device, path: DeviceServerPath, version: ScrcpyServerVersion, logLevel: ScrcpyLogLevel.Debug, maxSize: 1080, bitRate: 4_000_000, orientation: ScrcpyScreenOrientation.Unlocked, tunnelForward, // TinyH264 only supports Baseline profile profile: AndroidCodecProfile.Baseline, level: AndroidCodecLevel.Level4, }; setCurrentEncoder(current => { if (current) { options.encoder = current; return current; } else { options.encoder = encoders[0]; return encoders[0]; } }); setResolution(current => { options.maxSize = current; return current; }); setBitRate(current => { options.bitRate = current; return current; }); const client = new ScrcpyClient(options); client.onDebug(message => { console.debug('[server] ' + message); }); client.onInfo(message => { console.log('[server] ' + message); }); client.onError(({ message }) => { showErrorDialog(message); }); client.onClose(stop); const decoder = new selectedDecoder.factory(canvasRef.current!); decoderRef.current = decoder; client.onSizeChanged(async (config) => { const { croppedWidth, croppedHeight, } = config; setWidth(croppedWidth); setHeight(croppedHeight); const canvas = canvasRef.current!; canvas.width = croppedWidth; canvas.height = croppedHeight; await decoder.configure(config); }); client.onVideoData(async ({ data }) => { await decoder.decode(data); }); client.onClipboardChange(content => { window.navigator.clipboard.writeText(content); }); await client.start(); scrcpyClientRef.current = client; setRunning(true); } catch (e: any) { showErrorDialog(e.message); } finally { setConnecting(false); } })(); }, [device, selectedDecoder]); const stop = useCallback(() => { (async () => { if (!scrcpyClientRef.current) { return; } await scrcpyClientRef.current.close(); scrcpyClientRef.current = undefined; decoderRef.current?.dispose(); setRunning(false); })(); }, []); const deviceViewRef = useRef<DeviceViewRef | null>(null); const commandBarItems = useMemo((): ICommandBarItemProps[] => { const result: ICommandBarItemProps[] = []; if (running) { result.push({ key: 'stop', iconProps: { iconName: 'Stop' }, text: 'Stop', onClick: stop, }); } else { result.push({ key: 'start', disabled: !device, iconProps: { iconName: 'Play' }, text: 'Start', onClick: start, }); } result.push({ key: 'fullscreen', disabled: !running, iconProps: { iconName: 'Fullscreen' }, text: 'Fullscreen', onClick: () => { deviceViewRef.current?.enterFullscreen(); }, }); return result; }, [device, running, start]); const commandBarFarItems = useMemo((): ICommandBarItemProps[] => [ { key: 'Settings', iconProps: { iconName: 'Settings' }, checked: settingsVisible, text: 'Settings', onClick: toggleSettingsVisible, }, { key: 'DemoMode', iconProps: { iconName: 'Personalize' }, checked: demoModeVisible, text: 'Demo Mode Settings', onClick: toggleDemoModeVisible, }, { key: 'info', iconProps: { iconName: 'Info' }, iconOnly: true, tooltipHostProps: { content: ( <> <p> <ExternalLink href="https://github.com/Genymobile/scrcpy" spaceAfter>Scrcpy</ExternalLink> developed by Genymobile can display the screen with low latency (1~2 frames) and control the device, all without root access. </p> <p> I reimplemented the protocol in JavaScript, a pre-built server binary from Genymobile is used. </p> <p> It uses tinyh264 as decoder to achieve low latency. But since it's a software decoder, high CPU usage and sub-optimal compatibility are expected. </p> </> ), calloutProps: { calloutMaxWidth: 300, } }, } ], [settingsVisible, demoModeVisible]); const injectTouch = useCallback(( action: AndroidMotionEventAction, e: React.PointerEvent<HTMLCanvasElement> ) => { const view = canvasRef.current!.getBoundingClientRect(); const pointerViewX = e.clientX - view.x; const pointerViewY = e.clientY - view.y; const pointerScreenX = clamp(pointerViewX / view.width, 0, 1) * width; const pointerScreenY = clamp(pointerViewY / view.height, 0, 1) * height; scrcpyClientRef.current?.injectTouch({ action, pointerId: BigInt(e.pointerId), pointerX: pointerScreenX, pointerY: pointerScreenY, pressure: e.pressure * 65535, buttons: 0, }); }, [width, height]); const handlePointerDown = useCallback((e: React.PointerEvent<HTMLCanvasElement>) => { if (e.button !== 0) { return; } canvasRef.current!.focus(); e.currentTarget.setPointerCapture(e.pointerId); injectTouch(AndroidMotionEventAction.Down, e); }, [injectTouch]); const handlePointerMove = useCallback((e: React.PointerEvent<HTMLCanvasElement>) => { if (e.buttons !== 1) { return; } injectTouch(AndroidMotionEventAction.Move, e); }, [injectTouch]); const handlePointerUp = useCallback((e: React.PointerEvent<HTMLCanvasElement>) => { if (e.button !== 0) { return; } e.currentTarget.releasePointerCapture(e.pointerId); injectTouch(AndroidMotionEventAction.Up, e); }, [injectTouch]); const handleKeyDown = useCallback((e: KeyboardEvent<HTMLCanvasElement>) => { const key = e.key; if (key.match(/^[a-z0-9]$/i)) { scrcpyClientRef.current!.injectText(key); return; } const keyCode = ({ Backspace: AndroidKeyCode.Delete, } as Record<string, AndroidKeyCode | undefined>)[key]; if (keyCode) { scrcpyClientRef.current!.injectKeyCode({ keyCode, metaState: 0, repeat: 0, }); } }, []); const handleBackClick = useCallback(() => { scrcpyClientRef.current!.pressBackOrTurnOnScreen(); }, []); const handleHomeClick = useCallback(() => { scrcpyClientRef.current!.injectKeyCode({ keyCode: AndroidKeyCode.Home, repeat: 0, metaState: 0, }); }, []); const handleAppSwitchClick = useCallback(() => { scrcpyClientRef.current!.injectKeyCode({ keyCode: AndroidKeyCode.AppSwitch, repeat: 0, metaState: 0, }); }, []); const bottomElement = ( <Stack verticalFill horizontalAlign="center" style={{ background: '#999' }}> <Stack verticalFill horizontal style={{ width: '100%', maxWidth: 300 }} horizontalAlign="space-evenly" verticalAlign="center"> <IconButton iconProps={{ iconName: 'Play' }} style={{ transform: 'rotate(180deg)', color: 'white' }} onClick={handleBackClick} /> <IconButton iconProps={{ iconName: 'LocationCircle' }} style={{ color: 'white' }} onClick={handleHomeClick} /> <IconButton iconProps={{ iconName: 'Stop' }} style={{ color: 'white' }} onClick={handleAppSwitchClick} /> </Stack> </Stack> ); const layerHostId = useId('layerHost'); return ( <> <CommandBar items={commandBarItems} farItems={commandBarFarItems} /> <Stack horizontal grow styles={{ root: { height: 0 } }}> <DeviceView ref={deviceViewRef} width={width} height={height} bottomElement={bottomElement} bottomHeight={40} > <canvas key={canvasKey} ref={handleCanvasRef} style={{ display: 'block', outline: 'none' }} tabIndex={-1} onPointerDown={handlePointerDown} onPointerMove={handlePointerMove} onPointerUp={handlePointerUp} onPointerCancel={handlePointerUp} onKeyDown={handleKeyDown} /> </DeviceView> <div style={{ padding: 12, overflow: 'hidden auto', display: settingsVisible ? 'block' : 'none', width: 300 }}> <div>Changes will take effect on next connection</div> <Dropdown label="Encoder" options={encoders.map(item => ({ key: item, text: item }))} selectedKey={currentEncoder} placeholder="Connect once to retrieve encoder list" onChange={handleCurrentEncoderChange} /> {decoders.length > 1 && ( <Dropdown label="Decoder" options={decoders.map(item => ({ key: item.name, text: item.name, data: item }))} selectedKey={selectedDecoder.name} onChange={handleSelectedDecoderChange} /> )} <SpinButton label="Max Resolution (longer side, 0 = unlimited)" labelPosition={Position.top} value={resolution.toString()} min={0} max={2560} step={100} onChange={handleResolutionChange} /> <SpinButton label="Max Bit Rate" labelPosition={Position.top} value={bitRate.toString()} min={100} max={10_000_000} step={100} onChange={handleBitRateChange} /> <Toggle label={ <> <span>Use forward connection{' '}</span> <TooltipHost content="Old Android devices may not support reverse connection when using ADB over WiFi"> <Icon iconName="Info" /> </TooltipHost> </> } checked={tunnelForward} onChange={handleTunnelForwardChange} /> </div> <DemoMode device={device} style={{ display: demoModeVisible ? 'block' : 'none' }} /> </Stack> {connecting && <LayerHost id={layerHostId} style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, margin: 0 }} />} <Dialog hidden={!connecting} modalProps={{ layerProps: { hostId: layerHostId } }} dialogContentProps={{ title: 'Connecting...' }} > <Stack tokens={CommonStackTokens}> <ProgressIndicator label="1. Downloading scrcpy server..." percentComplete={serverTotalSize ? serverDownloadedSize / serverTotalSize : undefined} description={formatSpeed(debouncedServerDownloadedSize, serverTotalSize, serverDownloadSpeed)} /> <ProgressIndicator label="2. Pushing scrcpy server to device..." progressHidden={serverTotalSize === 0 || serverDownloadedSize !== serverTotalSize} percentComplete={serverUploadedSize / serverTotalSize} description={formatSpeed(debouncedServerUploadedSize, serverTotalSize, serverUploadSpeed)} /> <ProgressIndicator label="3. Starting scrcpy server on device..." progressHidden={serverTotalSize === 0 || serverUploadedSize !== serverTotalSize} /> </Stack> </Dialog> </> ); });
the_stack
import { RangeModel, Workbook, getCell, SheetModel, RowModel, CellModel, getSheetIndex, getSheetName } from '../base/index'; import { insertModel, ExtendedRange, InsertDeleteModelArgs, workbookFormulaOperation, checkUniqueRange, ConditionalFormatModel } from '../../workbook/common/index'; import { insert, insertMerge, MergeArgs, InsertDeleteEventArgs, refreshClipboard, refreshInsertDelete } from '../../workbook/common/index'; import { beforeInsert, ModelType, CellStyleModel, updateRowColCount, beginAction, ActionEventArgs, getRangeIndexes, getRangeAddress } from '../../workbook/common/index'; import { insertFormatRange } from '../../workbook/index'; /** * The `WorkbookInsert` module is used to insert cells, rows, columns and sheets in to workbook. */ export class WorkbookInsert { private parent: Workbook; /** * Constructor for the workbook insert module. * * @param {Workbook} parent - Specifies the workbook. * @private */ constructor(parent: Workbook) { this.parent = parent; this.addEventListener(); } // tslint:disable-next-line private insertModel(args: InsertDeleteModelArgs): void { if (args.modelType === 'Column') { if (typeof (args.start) === 'number') { for (let i: number = 0; i <= this.parent.getActiveSheet().usedRange.rowIndex + 1; i++) { const uniqueArgs: { cellIdx: number[], isUnique: boolean } = { cellIdx: [i, args.start], isUnique: false }; this.parent.notify(checkUniqueRange, uniqueArgs); if (uniqueArgs.isUnique) { return; } } } } else if (args.modelType === 'Row') { if (typeof (args.start) === 'number') { for (let j: number = 0; j <= this.parent.getActiveSheet().usedRange.colIndex + 1; j++) { const uniqueArgs: { cellIdx: number[], isUnique: boolean } = { cellIdx: [args.start, j], isUnique: false }; this.parent.notify(checkUniqueRange, uniqueArgs); if (uniqueArgs.isUnique) { return; } } } } if (!args.model) { return; } let index: number; let model: RowModel[] = []; let mergeCollection: MergeArgs[]; let isModel: boolean; let maxHgtObj: object[]; if (typeof (args.start) === 'number') { index = args.start; args.end = args.end || index; if (index > args.end) { index = args.end; args.end = args.start; } if (args.modelType === 'Row' && index < args.model.maxHgts.length) { maxHgtObj = []; } for (let i: number = index; i <= args.end; i++) { model.push({}); if (maxHgtObj) { maxHgtObj.push(null); } } } else { if (args.start) { index = args.start[0].index || 0; model = args.start; isModel = true; } else { index = 0; model.push({}); } if (args.modelType === 'Row' && index < args.model.maxHgts.length) { maxHgtObj = []; model.forEach((): void => { maxHgtObj.push(null); }); } } const eventArgs: InsertDeleteEventArgs = { model: model, index: index, modelType: args.modelType, insertType: args.insertType, cancel: false, isUndoRedo: args.isUndoRedo }; const actionArgs: ActionEventArgs = { eventArgs: eventArgs, action: 'insert' }; if (args.isAction) { this.parent.notify(beginAction, actionArgs); if (eventArgs.cancel) { return; } delete eventArgs.cancel; eventArgs.isAction = args.isAction; } const insertArgs: InsertDeleteEventArgs = { startIndex: index, endIndex: index + model.length - 1, modelType: args.modelType, sheet: args.model, isInsert: true }; if (args.modelType === 'Row') { if (args.checkCount !== undefined && args.model.rows && args.checkCount === args.model.rows.length) { return; } this.parent.notify(refreshInsertDelete, insertArgs); args.model = <SheetModel>args.model; if (!args.model.rows) { args.model.rows = []; } if (isModel && args.model.usedRange.rowIndex > -1 && index > args.model.usedRange.rowIndex) { for (let i: number = args.model.usedRange.rowIndex; i < index - 1; i++) { model.splice(0, 0, {}); } } const frozenRow: number = this.parent.frozenRowCount(args.model); if (index < frozenRow) { this.parent.setSheetPropertyOnMute(args.model, 'frozenRows', args.model.frozenRows + model.length); eventArgs.freezePane = true; } args.model.rows.splice(index, 0, ...model); if (maxHgtObj) { args.model.maxHgts.splice(index, 0, ...maxHgtObj); } //this.setInsertInfo(args.model, index, model.length, 'count'); this.setRowColCount(insertArgs.startIndex, insertArgs.endIndex, args.model, 'row'); if (index > args.model.usedRange.rowIndex) { this.parent.setUsedRange(index + (model.length - 1), args.model.usedRange.colIndex, args.model, true); } else { this.parent.setUsedRange(args.model.usedRange.rowIndex + model.length, args.model.usedRange.colIndex, args.model, true); } const curIdx: number = index + model.length; let style: CellStyleModel; let cell: CellModel; for (let i: number = 0; i <= args.model.usedRange.colIndex; i++) { if (args.model.rows[curIdx] && args.model.rows[curIdx].cells && args.model.rows[curIdx].cells[i]) { cell = args.model.rows[curIdx].cells[i]; if (cell.rowSpan !== undefined && cell.rowSpan < 0 && cell.colSpan === undefined) { this.parent.notify(insertMerge, <MergeArgs>{ range: [curIdx, i, curIdx, i], insertCount: model.length, insertModel: 'Row' }); } if (cell.style && getCell(index - 1, i, args.model, false, true).style) { style = this.checkBorder(cell.style, args.model.rows[index - 1].cells[i].style); if (style !== {}) { model.forEach((row: RowModel): void => { if (!row.cells) { row.cells = []; } if (!row.cells[i]) { row.cells[i] = {}; } if (!row.cells[i].style) { row.cells[i].style = {}; } Object.assign(row.cells[i].style, style); }); } } } } eventArgs.sheetCount = args.model.rows.length; } else if (args.modelType === 'Column') { if (args.checkCount !== undefined && args.model.columns && args.checkCount === args.model.columns.length) { return; } this.parent.notify(refreshInsertDelete, insertArgs); args.model = <SheetModel>args.model; if (!args.model.columns) { args.model.columns = []; } if (index && !args.model.columns[index - 1]) { args.model.columns[index - 1] = {}; } args.model.columns.splice(index, 0, ...model); const frozenCol: number = this.parent.frozenColCount(args.model); if (index < frozenCol) { this.parent.setSheetPropertyOnMute(args.model, 'frozenColumns', args.model.frozenColumns + model.length); eventArgs.freezePane = true; } //this.setInsertInfo(args.model, index, model.length, 'fldLen', 'Column'); this.setRowColCount(insertArgs.startIndex, insertArgs.endIndex, args.model, 'col'); if (index > args.model.usedRange.colIndex) { this.parent.setUsedRange(args.model.usedRange.rowIndex, index + (model.length - 1), args.model, true); } else { this.parent.setUsedRange(args.model.usedRange.rowIndex, args.model.usedRange.colIndex + model.length, args.model, true); } if (!args.model.rows) { args.model.rows = []; } const cellModel: CellModel[] = []; if (!args.columnCellsModel) { args.columnCellsModel = []; } for (let i: number = 0; i < model.length; i++) { cellModel.push(null); } mergeCollection = []; let cell: CellModel; let style: CellStyleModel; for (let i: number = 0; i <= args.model.usedRange.rowIndex; i++) { if (!args.model.rows[i]) { args.model.rows[i] = { cells: [] }; } else if (!args.model.rows[i].cells) { args.model.rows[i].cells = []; } if (index && !args.model.rows[i].cells[index - 1]) { args.model.rows[i].cells[index - 1] = {}; } args.model.rows[i].cells.splice(index, 0, ...(args.columnCellsModel[i] && args.columnCellsModel[i].cells ? args.columnCellsModel[i].cells : cellModel)); const curIdx: number = index + model.length; if (args.model.rows[i].cells[curIdx]) { cell = args.model.rows[i].cells[curIdx]; if (cell.colSpan !== undefined && cell.colSpan < 0 && cell.rowSpan === undefined) { mergeCollection.push(<MergeArgs>{ range: [i, curIdx, i, curIdx], insertCount: cellModel.length, insertModel: 'Column' }); } if (cell.style && getCell(i, index - 1, args.model, false, true).style) { style = this.checkBorder(cell.style, args.model.rows[i].cells[index - 1].style); if (style !== {}) { for (let j: number = index; j < curIdx; j++) { if (!args.model.rows[i].cells[j]) { args.model.rows[i].cells[j] = {}; } if (!args.model.rows[i].cells[j].style) { args.model.rows[i].cells[j].style = {}; } Object.assign(args.model.rows[i].cells[j].style, style); } } } } } mergeCollection.forEach((mergeArgs: MergeArgs): void => { this.parent.notify(insertMerge, mergeArgs); }); eventArgs.sheetCount = args.model.columns.length; } else { if (args.checkCount !== undefined && args.checkCount === this.parent.sheets.length) { return; } const sheetModel: SheetModel[] = model as SheetModel[]; const sheetName: string = getSheetName(this.parent); const isFromUpdateAction: boolean = (args as unknown as { isFromUpdateAction: boolean }).isFromUpdateAction; for (let i: number = 0; i < sheetModel.length; i++) { if (sheetModel[i].name) { for (let j: number = 0; j < this.parent.sheets.length; j++) { if (sheetModel[i].name === this.parent.sheets[j].name) { sheetModel.splice(i, 1); i--; break; } } } } if (!sheetModel.length) { return; } delete model[0].index; this.parent.createSheet(index, model); let id: number; if (args.activeSheetIndex) { eventArgs.activeSheetIndex = args.activeSheetIndex; this.parent.setProperties({ activeSheetIndex: args.activeSheetIndex }, true); } else if (!args.isAction && args.start < this.parent.activeSheetIndex) { this.parent.setProperties({ activeSheetIndex: this.parent.skipHiddenSheets(this.parent.activeSheetIndex) }, true); } if (isFromUpdateAction) { this.parent.setProperties({ activeSheetIndex: getSheetIndex(this.parent, sheetName) }, true); } model.forEach((sheet: SheetModel): void => { if (isModel) { this.updateRangeModel(sheet.ranges); } id = sheet.id; this.parent.notify(workbookFormulaOperation, { action: 'addSheet', visibleName: sheet.name, sheetName: 'Sheet' + id, sheetId: id }); }); eventArgs.activeSheetIndex = args.activeSheetIndex; eventArgs.sheetCount = this.parent.sheets.length; } if (args.modelType !== 'Sheet') { this.insertConditionalFormats(args); this.parent.notify( refreshClipboard, { start: index, end: index + model.length - 1, modelType: args.modelType, model: args.model, isInsert: true }); eventArgs.activeSheetIndex = getSheetIndex(this.parent, args.model.name); } this.parent.notify(insert, actionArgs); } private setRowColCount(startIdx: number, endIdx: number, sheet: SheetModel, layout: string): void { const prop: string = layout + 'Count'; this.parent.setSheetPropertyOnMute(sheet, prop, sheet[prop] + ((endIdx - startIdx) + 1)); if (sheet.id === this.parent.getActiveSheet().id) { this.parent.notify(updateRowColCount, { index: sheet[prop] - 1, update: layout, isInsert: true, start: startIdx, end: endIdx }); } } private updateRangeModel(ranges: RangeModel[]): void { ranges.forEach((range: RangeModel): void => { if (range.dataSource) { range.startCell = range.startCell || 'A1'; range.showFieldAsHeader = range.showFieldAsHeader === undefined || range.showFieldAsHeader; range.template = range.template || ''; range.address = range.address || 'A1'; } }); } private checkBorder(style: CellStyleModel, adjStyle: CellStyleModel): CellStyleModel { const matchedStyle: CellStyleModel = {}; if (style.borderLeft && style.borderLeft === adjStyle.borderLeft) { matchedStyle.borderLeft = style.borderLeft; } if (style.borderRight && style.borderRight === adjStyle.borderRight) { matchedStyle.borderRight = style.borderRight; } if (style.borderTop && style.borderTop === adjStyle.borderTop) { matchedStyle.borderTop = style.borderTop; } if (style.borderBottom && style.borderBottom === adjStyle.borderBottom) { matchedStyle.borderBottom = style.borderBottom; } return matchedStyle; } private setInsertInfo(sheet: SheetModel, startIndex: number, count: number, totalKey: string, modelType: ModelType = 'Row'): void { const endIndex: number = count = startIndex + (count - 1); sheet.ranges.forEach((range: ExtendedRange): void => { if (range.info && startIndex < range.info[totalKey]) { if (!range.info[`insert${modelType}Range`]) { range.info[`insert${modelType}Range`] = [[startIndex, endIndex]]; } else { range.info[`insert${modelType}Range`].push([startIndex, endIndex]); } range.info[totalKey] += ((endIndex - startIndex) + 1); } }); } private insertConditionalFormats(args: InsertDeleteModelArgs): void { let cfCollection: ConditionalFormatModel[] = args.model.conditionalFormats; if (args.prevAction === "delete") { this.parent.setSheetPropertyOnMute(args.model, 'conditionalFormats', args.conditionalFormats); } else if (cfCollection) { for (let i: number = 0, cfLength: number = cfCollection.length; i < cfLength; i++) { cfCollection[i].range = getRangeAddress(insertFormatRange(args, getRangeIndexes(cfCollection[i].range), !args.isAction && !args.isUndoRedo)); } } } private addEventListener(): void { this.parent.on(insertModel, this.insertModel, this); } /** * Destroy workbook insert module. * * @returns {void} - destroy the workbook insert module. */ public destroy(): void { this.removeEventListener(); this.parent = null; } private removeEventListener(): void { if (!this.parent.isDestroyed) { this.parent.off(insertModel, this.insertModel); } } /** * Get the workbook insert module name. * * @returns {string} - Return the string. */ public getModuleName(): string { return 'workbookinsert'; } }
the_stack
import { _FirebaseService, _getProvider, FirebaseApp, getApp } from '@firebase/app'; import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; import { Provider } from '@firebase/component'; import { getModularInstance, createMockUserToken, EmulatorMockTokenOptions } from '@firebase/util'; import { AppCheckTokenProvider } from '../core/AppCheckTokenProvider'; import { AuthTokenProvider, EmulatorTokenProvider, FirebaseAuthTokenProvider } from '../core/AuthTokenProvider'; import { Repo, repoInterrupt, repoResume, repoStart } from '../core/Repo'; import { RepoInfo } from '../core/RepoInfo'; import { parseRepoInfo } from '../core/util/libs/parser'; import { newEmptyPath, pathIsEmpty } from '../core/util/Path'; import { fatal, log, enableLogging as enableLoggingImpl } from '../core/util/util'; import { validateUrl } from '../core/util/validation'; import { ReferenceImpl } from './Reference_impl'; export { EmulatorMockTokenOptions } from '@firebase/util'; /** * This variable is also defined in the firebase Node.js Admin SDK. Before * modifying this definition, consult the definition in: * * https://github.com/firebase/firebase-admin-node * * and make sure the two are consistent. */ const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST'; /** * Creates and caches `Repo` instances. */ const repos: { [appName: string]: { [dbUrl: string]: Repo; }; } = {}; /** * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes). */ let useRestClient = false; /** * Update an existing `Repo` in place to point to a new host/port. */ function repoManagerApplyEmulatorSettings( repo: Repo, host: string, port: number, tokenProvider?: AuthTokenProvider ): void { repo.repoInfo_ = new RepoInfo( `${host}:${port}`, /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams ); if (tokenProvider) { repo.authTokenProvider_ = tokenProvider; } } /** * This function should only ever be called to CREATE a new database instance. * @internal */ export function repoManagerDatabaseFromApp( app: FirebaseApp, authProvider: Provider<FirebaseAuthInternalName>, appCheckProvider?: Provider<AppCheckInternalComponentName>, url?: string, nodeAdmin?: boolean ): Database { let dbUrl: string | undefined = url || app.options.databaseURL; if (dbUrl === undefined) { if (!app.options.projectId) { fatal( "Can't determine Firebase Database URL. Be sure to include " + ' a Project ID when calling firebase.initializeApp().' ); } log('Using default host for project ', app.options.projectId); dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; } let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); let repoInfo = parsedUrl.repoInfo; let isEmulator: boolean; let dbEmulatorHost: string | undefined = undefined; if (typeof process !== 'undefined') { dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]; } if (dbEmulatorHost) { isEmulator = true; dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`; parsedUrl = parseRepoInfo(dbUrl, nodeAdmin); repoInfo = parsedUrl.repoInfo; } else { isEmulator = !parsedUrl.repoInfo.secure; } const authTokenProvider = nodeAdmin && isEmulator ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) : new FirebaseAuthTokenProvider(app.name, app.options, authProvider); validateUrl('Invalid Firebase Database URL', parsedUrl); if (!pathIsEmpty(parsedUrl.path)) { fatal( 'Database URL must point to the root of a Firebase Database ' + '(not including a child path).' ); } const repo = repoManagerCreateRepo( repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider) ); return new Database(repo, app); } /** * Remove the repo and make sure it is disconnected. * */ function repoManagerDeleteRepo(repo: Repo, appName: string): void { const appRepos = repos[appName]; // This should never happen... if (!appRepos || appRepos[repo.key] !== repo) { fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`); } repoInterrupt(repo); delete appRepos[repo.key]; } /** * Ensures a repo doesn't already exist and then creates one using the * provided app. * * @param repoInfo - The metadata about the Repo * @returns The Repo object for the specified server / repoName. */ function repoManagerCreateRepo( repoInfo: RepoInfo, app: FirebaseApp, authTokenProvider: AuthTokenProvider, appCheckProvider: AppCheckTokenProvider ): Repo { let appRepos = repos[app.name]; if (!appRepos) { appRepos = {}; repos[app.name] = appRepos; } let repo = appRepos[repoInfo.toURLString()]; if (repo) { fatal( 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.' ); } repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider); appRepos[repoInfo.toURLString()] = repo; return repo; } /** * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. */ export function repoManagerForceRestClient(forceRestClient: boolean): void { useRestClient = forceRestClient; } /** * Class representing a Firebase Realtime Database. */ export class Database implements _FirebaseService { /** Represents a `Database` instance. */ readonly 'type' = 'database'; /** Track if the instance has been used (root or repo accessed) */ _instanceStarted: boolean = false; /** Backing state for root_ */ private _rootInternal?: ReferenceImpl; /** @hideconstructor */ constructor( public _repoInternal: Repo, /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */ readonly app: FirebaseApp ) {} get _repo(): Repo { if (!this._instanceStarted) { repoStart( this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride'] ); this._instanceStarted = true; } return this._repoInternal; } get _root(): ReferenceImpl { if (!this._rootInternal) { this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath()); } return this._rootInternal; } _delete(): Promise<void> { if (this._rootInternal !== null) { repoManagerDeleteRepo(this._repo, this.app.name); this._repoInternal = null; this._rootInternal = null; } return Promise.resolve(); } _checkNotDeleted(apiName: string) { if (this._rootInternal === null) { fatal('Cannot call ' + apiName + ' on a deleted database.'); } } } /** * Returns the instance of the Realtime Database SDK that is associated * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with * with default settings if no instance exists or if the existing instance uses * a custom database URL. * * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime * Database instance is associated with. * @param url - The URL of the Realtime Database instance to connect to. If not * provided, the SDK connects to the default instance of the Firebase App. * @returns The `Database` instance of the provided app. */ export function getDatabase( app: FirebaseApp = getApp(), url?: string ): Database { return _getProvider(app, 'database').getImmediate({ identifier: url }) as Database; } /** * Modify the provided instance to communicate with the Realtime Database * emulator. * * <p>Note: This method must be called before performing any other operation. * * @param db - The instance to modify. * @param host - The emulator host (ex: localhost) * @param port - The emulator port (ex: 8080) * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules */ export function connectDatabaseEmulator( db: Database, host: string, port: number, options: { mockUserToken?: EmulatorMockTokenOptions | string; } = {} ): void { db = getModularInstance(db); db._checkNotDeleted('useEmulator'); if (db._instanceStarted) { fatal( 'Cannot call useEmulator() after instance has already been initialized.' ); } const repo = db._repoInternal; let tokenProvider: EmulatorTokenProvider | undefined = undefined; if (repo.repoInfo_.nodeAdmin) { if (options.mockUserToken) { fatal( 'mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".' ); } tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER); } else if (options.mockUserToken) { const token = typeof options.mockUserToken === 'string' ? options.mockUserToken : createMockUserToken(options.mockUserToken, db.app.options.projectId); tokenProvider = new EmulatorTokenProvider(token); } // Modify the repo to apply emulator settings repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider); } /** * Disconnects from the server (all Database operations will be completed * offline). * * The client automatically maintains a persistent connection to the Database * server, which will remain active indefinitely and reconnect when * disconnected. However, the `goOffline()` and `goOnline()` methods may be used * to control the client connection in cases where a persistent connection is * undesirable. * * While offline, the client will no longer receive data updates from the * Database. However, all Database operations performed locally will continue to * immediately fire events, allowing your application to continue behaving * normally. Additionally, each operation performed locally will automatically * be queued and retried upon reconnection to the Database server. * * To reconnect to the Database and begin receiving remote events, see * `goOnline()`. * * @param db - The instance to disconnect. */ export function goOffline(db: Database): void { db = getModularInstance(db); db._checkNotDeleted('goOffline'); repoInterrupt(db._repo); } /** * Reconnects to the server and synchronizes the offline Database state * with the server state. * * This method should be used after disabling the active connection with * `goOffline()`. Once reconnected, the client will transmit the proper data * and fire the appropriate events so that your client "catches up" * automatically. * * @param db - The instance to reconnect. */ export function goOnline(db: Database): void { db = getModularInstance(db); db._checkNotDeleted('goOnline'); repoResume(db._repo); } /** * Logs debugging information to the console. * * @param enabled - Enables logging if `true`, disables logging if `false`. * @param persistent - Remembers the logging state between page refreshes if * `true`. */ export function enableLogging(enabled: boolean, persistent?: boolean); /** * Logs debugging information to the console. * * @param logger - A custom logger function to control how things get logged. */ export function enableLogging(logger: (message: string) => unknown); export function enableLogging( logger: boolean | ((message: string) => unknown), persistent?: boolean ): void { enableLoggingImpl(logger, persistent); }
the_stack
A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ export class Random { private N = 624; private M = 397; private MATRIX_A = 0x9908b0df; private UPPER_MASK = 0x80000000; private LOWER_MASK = 0x7fffffff; private mt: int[]; private mti: int; public pythonCompatibility: boolean = false; private skip = false; private LOG4 = Math.log(4.0); private SG_MAGICCONST = 1.0 + Math.log(4.5); private lastNormal = NaN; constructor(seed: int) { "use speedyjs"; this.mt = new Array<int>(this.N); /* the array for the state vector */ this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */ //this.init_genrand(seed); this.init_by_array([seed], 1); } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ init_by_array(init_key: int[], key_length: int) { "use speedyjs"; this.init_genrand(19650218); let i = 1; let j = 0; let k = this.N > key_length ? this.N : key_length; for (; k; --k) { const s = this.mt[i-1] ^ (this.mt[i-1] >>> 30); this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) + init_key[j] + j; /* non linear */ this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ ++i; ++j; if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; } if (j>=key_length) j=0; } for (k=this.N-1; k; --k) { const s = this.mt[i-1] ^ (this.mt[i-1] >>> 30); this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i; /* non linear */ this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ ++i; if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; } } this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ } /* initializes mt[N] with a seed */ init_genrand(s: int) { "use speedyjs"; this.mt[0] = s >>> 0; for (this.mti=1; this.mti<this.N; ++this.mti) { const s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30); this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ this.mt[this.mti] >>>= 0; /* for >32 bit machines */ } } /* generates a random number on [0,0xffffffff]-interval */ genrand_int32(): int { "use speedyjs"; const mag01 = [0x0, this.MATRIX_A]; /* mag01[x] = x * MATRIX_A for x=0,1 */ let y: int; if (this.mti >= this.N) { /* generate N words at one time */ let kk: int; if (this.mti === this.N+1) /* if init_genrand() has not been called, */ this.init_genrand(5489); /* a default initial seed is used */ for (kk=0;kk<this.N-this.M;++kk) { y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK); this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (;kk<this.N-1;++kk) { y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK); this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK); this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; this.mti = 0; } y = this.mt[this.mti]; ++this.mti; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y >>> 0; } /* generates a random number on [0,0x7fffffff]-interval */ genrand_int31(): int { return (this.genrand_int32()>>>1); } /* generates a random number on [0,1]-real-interval */ genrand_real1(): number { return (this.genrand_int32() as number) *(1.0/4294967295.0); } /* generates a random number on [0,1)-real-interval */ random(): number { "use speedyjs"; if (this.pythonCompatibility) { if (this.skip) { this.genrand_int32(); } this.skip = true; } // this is essentially not needed for js but is for speedy js. The issue is that speedyjs does not have a uint32 // type. However, >>> returns a uint as result and is, therefore, in the range of 0... 2^32. As the return value // of spdy is an int, we need to handle negative values explicitly const rand = this.genrand_int32() as number; const randNumber = rand < 0.0 ? 4294967296.0 + rand : rand; return randNumber*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on (0,1)-real-interval */ genrand_real3 (): number { return ((this.genrand_int32() as number)+ 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on [0,1) with 53-bit resolution*/ genrand_res53(): number { const a=this.genrand_int32()>>>5; const b=this.genrand_int32()>>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } /* These real versions are due to Isaku Wada, 2002/01/09 added */ /**************************************************************************/ exponential(lambda: number) { const r = this.random(); return -Math.log(r) / lambda; } gamma(alpha: number, beta: number) { /* Based on Python 2.6 source code of random.py. */ if (alpha > 1.0) { const ainv = Math.sqrt(2.0 * alpha - 1.0); const bbb = alpha - this.LOG4; const ccc = alpha + ainv; while (true) { const u1 = this.random(); if ((u1 < 1e-7)) { continue; } const u2 = 1.0 - this.random(); const v = Math.log(u1 / (1.0 - u1)) / ainv; const x = alpha * Math.exp(v); const z = u1 * u1 * u2; const r = bbb + ccc * v - x; if ((r + this.SG_MAGICCONST - 4.5 * z >= 0.0) || (r >= Math.log(z))) { return x * beta; } } } else if (alpha == 1.0) { let u = this.random(); while (u <= 1e-7) { u = this.random(); } return - Math.log(u) * beta; } else { let x: number; while (true) { const u = this.random(); const b = (Math.E + alpha) / Math.E; const p = b * u; if (p <= 1.0) { x = Math.pow(p, 1.0 / alpha); } else { x = - Math.log((b - p) / alpha); } const u1 = this.random(); if (p > 1.0) { if (u1 <= Math.pow(x, (alpha - 1.0))) { break; } } else if (u1 <= Math.exp(-x)) { break; } } return x * beta; } } normal(mu: number, sigma: number) { "use speedyjs"; let z = this.lastNormal; this.lastNormal = NaN; if (isNaN(z)) { const a = this.random() * 2.0 * Math.PI; const b = Math.sqrt(-2.0 * Math.log(1.0 - this.random())); z = Math.cos(a) * b; this.lastNormal = Math.sin(a) * b; } return mu + z * sigma; } pareto(alpha: number) { const u = this.random(); return 1.0 / Math.pow((1 - u), 1.0 / alpha); } triangular(lower: number, upper: number, mode: number) { const c = (mode - lower) / (upper - lower); const u = this.random(); if (u <= c) { return lower + Math.sqrt(u * (upper - lower) * (mode - lower)); } else { return upper - Math.sqrt((1 - u) * (upper - lower) * (upper - mode)); } } uniform(lower: number, upper: number): number { return lower + this.random() * (upper - lower); } weibull(alpha: number, beta: number): number { const u = 1.0 - this.random(); return alpha * Math.pow(-Math.log(u), 1.0 / beta); } } export async function simjs(seed: int, runs: int) { "use speedyjs"; const random = new Random(seed); let sum = 0.0; for (let i = 0; i < runs; ++i) { sum += random.normal(1.0, 1.2); } return sum; }
the_stack
declare const COMMAND_WAIT = 0; declare const COMMAND_ANIMATE = 1; declare const COMMAND_FACE_NORTH = 2; declare const COMMAND_FACE_NORTHEAST = 3; declare const COMMAND_FACE_EAST = 4; declare const COMMAND_FACE_SOUTHEAST = 5; declare const COMMAND_FACE_SOUTH = 6; declare const COMMAND_FACE_SOUTHWEST = 7; declare const COMMAND_FACE_WEST = 8; declare const COMMAND_FACE_NORTHWEST = 9; declare const COMMAND_MOVE_NORTH = 10; declare const COMMAND_MOVE_EAST = 11; declare const COMMAND_MOVE_SOUTH = 12; declare const COMMAND_MOVE_WEST = 13; declare const EDGE_LEFT = 0; declare const EDGE_TOP = 1; declare const EDGE_RIGHT = 2; declare const EDGE_BOTTOM = 3; declare const KEY_ESCAPE = 0; declare const KEY_F1 = 1; declare const KEY_F2 = 2; declare const KEY_F3 = 3; declare const KEY_F4 = 4; declare const KEY_F5 = 5; declare const KEY_F6 = 6; declare const KEY_F7 = 7; declare const KEY_F8 = 8; declare const KEY_F9 = 9; declare const KEY_F10 = 10; declare const KEY_F11 = 11; declare const KEY_F12 = 12; declare const KEY_TILDE = 13; declare const KEY_0 = 14; declare const KEY_1 = 15; declare const KEY_2 = 16; declare const KEY_3 = 17; declare const KEY_4 = 18; declare const KEY_5 = 19; declare const KEY_6 = 20; declare const KEY_7 = 21; declare const KEY_8 = 22; declare const KEY_9 = 23; declare const KEY_MINUS = 24; declare const KEY_EQUALS = 25; declare const KEY_BACKSPACE = 26; declare const KEY_TAB = 27; declare const KEY_A = 28; declare const KEY_B = 29; declare const KEY_C = 30; declare const KEY_D = 31; declare const KEY_E = 32; declare const KEY_F = 33; declare const KEY_G = 34; declare const KEY_H = 35; declare const KEY_I = 36; declare const KEY_J = 37; declare const KEY_K = 38; declare const KEY_L = 39; declare const KEY_M = 40; declare const KEY_N = 41; declare const KEY_O = 42; declare const KEY_P = 43; declare const KEY_Q = 44; declare const KEY_R = 45; declare const KEY_S = 46; declare const KEY_T = 47; declare const KEY_U = 48; declare const KEY_V = 49; declare const KEY_W = 50; declare const KEY_X = 51; declare const KEY_Y = 52; declare const KEY_Z = 53; declare const KEY_SHIFT = 54; declare const KEY_CTRL = 55; declare const KEY_ALT = 56; declare const KEY_SPACE = 57; declare const KEY_OPENBRACE = 58; declare const KEY_CLOSEBRACE = 59; declare const KEY_SEMICOLON = 60; declare const KEY_APOSTROPHE = 61; declare const KEY_COMMA = 62; declare const KEY_PERIOD = 63; declare const KEY_SLASH = 64; declare const KEY_BACKSLASH = 65; declare const KEY_ENTER = 66; declare const KEY_INSERT = 67; declare const KEY_DELETE = 68; declare const KEY_HOME = 69; declare const KEY_END = 70; declare const KEY_PAGEUP = 71; declare const KEY_PAGEDOWN = 72; declare const KEY_UP = 73; declare const KEY_RIGHT = 74; declare const KEY_DOWN = 75; declare const KEY_LEFT = 76; declare const KEY_NUM_0 = 77; declare const KEY_NUM_1 = 78; declare const KEY_NUM_2 = 79; declare const KEY_NUM_3 = 80; declare const KEY_NUM_4 = 81; declare const KEY_NUM_5 = 82; declare const KEY_NUM_6 = 83; declare const KEY_NUM_7 = 84; declare const KEY_NUM_8 = 85; declare const KEY_NUM_9 = 86; declare const KEY_CAPSLOCK = 87; declare const KEY_NUMLOCK = 88; declare const KEY_SCROLLOCK = 89; declare const SCRIPT_ON_ENTER_MAP = 0; declare const SCRIPT_ON_LEAVE_MAP = 1; declare const SCRIPT_ON_LEAVE_MAP_NORTH = 2; declare const SCRIPT_ON_LEAVE_MAP_EAST = 3; declare const SCRIPT_ON_LEAVE_MAP_SOUTH = 4; declare const SCRIPT_ON_LEAVE_MAP_WEST = 5; declare const SCRIPT_ON_CREATE = 0; declare const SCRIPT_ON_DESTROY = 1; declare const SCRIPT_ON_ACTIVATE_TOUCH = 2; declare const SCRIPT_ON_ACTIVATE_TALK = 3; /** Called when the command queue for the person runs out */ declare const SCRIPT_COMMAND_GENERATOR = 4; /** default for drawing */ declare const BLEND = 0; declare const REPLACE = 1; declare const RGB_ONLY = 2; declare const ALPHA_ONLY = 3; declare const ADD = 4; declare const SUBTRACT = 5; /** default for masking */ declare const MULTIPLY = 6; declare const AVERAGE = 7; declare const INVERT = 8; /** * A Sphere 1.x color object * * Note that the RGBA properties of Sphere 1.x color objects are integers between 0 and 255, but * the properties of miniSphere `Color` classes are floating point numbers between 0.0 and 1.0 * * Objects from the 1.x API should generally only be used for Sphere 1.x API functions * that require them. */ interface Sphere1Color { red: number; green: number; blue: number; alpha: number; } /** * A Sphere 1.x font object * * Objects from the 1.x API should generally only be used for Sphere 1.x API functions * that require them. */ interface Sphere1Font { setColorMask(color: Sphere1Color): void; getColorMask(): Sphere1Color; drawText(x: number, y: number, text: any): void; drawZoomedText(x: number, y: number, scale: number, text: any): void; drawTextBox(x: number, y: number, w: number, h: number, offset: number, text: any): void; wordWrapString(string: any, width: number): any[]; getHeight(): number; getStringWidth(string: any): number; getStringHeight(string: any, width: number): number; clone(): Sphere1Font; getCharacterImage(code: number): Sphere1Image; setCharacterImage(code: number, image: Sphere1Image): void; } /** * A Sphere 1.x image object * * Objects from the 1.x API should generally only be used for Sphere 1.x API functions * that require them. */ interface Sphere1Image { width: number; height: number; blit(x: number, y: number, blendMode?: number): void; blitMask(x: number, y: number, mask: Sphere1Color, blendMode?: number, maskBlendMode?: number): void; rotateBlit(x: number, y: number, radians: number, blendMode?: number): void; rotateBlitMask( x: number, y: number, radians: number, mask: Sphere1Color, blendMode?: number, maskBlendMode?: number, ): void; zoomBlit(x: number, y: number, factor: number, blendmode?: number): void; zoomBlitMask( x: number, y: number, factor: number, color: Sphere1Color, blendmode?: number, maskBlendMode?: number, ): void; transformBlit( x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, blendmode?: number, ): void; transformBlitMask( x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, mask: Sphere1Color, blendmode?: number, maskBlendMode?: number, ): void; createSurface(): Sphere1Surface; } interface Sphere1Point { x: number; y: number; } /** * A Sphere 1.x surface object * * Objects from the 1.x API should generally only be used for Sphere 1.x API functions * that require them. */ interface Sphere1Surface { width: number; height: number; applyLookup( x: number, y: number, w: number, h: number, redLookup: number[], greenLookup: number[], blueLookup: number[], alphaLookup: number[], ): void; applyColorFX(x: number, y: number, w: number, h: number, colorMatrix: any): void; applyColorFX4( x: number, y: number, w: number, h: number, matrixUL: any, matrixUR: any, matrixLL: any, matrixLR: any, ): void; blit(x: number, y: number): void; blitSurface(surface: Sphere1Surface, x: number, y: number): void; blitMaskSurface(surface: Sphere1Surface, x: number, y: number, mask: Sphere1Color, maskBlendMode: number): void; rotateBlitSurface(surface: Sphere1Surface, x: number, y: number, radians: number): void; rotateBlitMaskSurface( surface: Sphere1Surface, x: number, y: number, radians: number, mask: Sphere1Color, maskBlendMode: number, ): void; zoomBlitSurface(surface: Sphere1Surface, x: number, y: number, factor: number): void; zoomBlitMaskSurface( surface: Sphere1Surface, x: number, y: number, factor: number, mask: Sphere1Color, maskBlendMode?: number, ): void; transformBlitSurface( surface: Sphere1Surface, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, ): void; transformBlitMaskSurface( surface: Sphere1Surface, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, mask: Sphere1Color, maskBlendMode?: number, ): void; createImage(): Sphere1Image; setBlendMode(mode: number): void; getPixel(x: number, y: number): Sphere1Color; setPixel(x: number, y: number, color: Sphere1Color): void; setAlpha(alpha: number): void; replaceColor(oldColor: Sphere1Color, newColor: Sphere1Color): void; findColor(aColor: Sphere1Color): boolean; floodFill(x: number, y: number, color: Sphere1Color): void; pointSeries(array: Sphere1Color[], color: Sphere1Color): void; line(x1: number, y1: number, x2: number, y2: number, color: Sphere1Color): void; gradientLine(x1: number, y1: number, x2: number, y2: number, color1: Sphere1Color, color2: Sphere1Color): void; lineSeries(array: Sphere1Point[], color: Sphere1Color, type?: number): void; bezierCurve( color: Sphere1Color, step: number, Ax: number, Ay: number, Bx: number, By: number, Cx: number, Cy: number, Dx?: number, Dy?: number, ): void; outlinedRectangle(x: number, y: number, width: number, height: number, color: Sphere1Color, size?: number): void; rectangle(x: number, y: number, width: number, height: number, color: Sphere1Color): void; gradientRectangle( x: number, y: number, width: number, colorUL: Sphere1Color, colorUR: Sphere1Color, colorLR: Sphere1Color, colorLL: Sphere1Color, ): void; triangle(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, color: Sphere1Color): void; gradientTriangle( x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, c1: Sphere1Color, c2: Sphere1Color, c3: Sphere1Color, ): void; polygon(array: Sphere1Point[], color: Sphere1Color, invert: boolean): void; outlinedEllipse(x: number, y: number, rx: number, ry: number, c: Sphere1Color): void; filledEllipse(x: number, y: number, rx: number, ry: number, c: Sphere1Color): void; outlinedCircle(x: number, y: number, radius: number, color: Sphere1Color, antialias?: boolean): void; filledCircle(x: number, y: number, radius: number, color: Sphere1Color, antialias?: boolean): void; gradientCircle( x: number, y: number, radius: number, color1: Sphere1Color, color2: Sphere1Color, antialias: boolean, ): void; rotate(radians: number, resize: boolean): void; resize(w: number, h: number): void; rescale(w: number, h: number): void; flipHorizontally(): void; flipVertically(): void; clone(): Sphere1Surface; cloneSection(x: number, y: number, w: number, h: number): Sphere1Surface; drawText(font: Sphere1Font, x: number, y: number, text: string): void; drawZoomedText(font: Sphere1Font, x: number, y: number, scale: number, text: string): void; drawTextBox(font: Sphere1Font, x: number, y: number, w: number, h: number, offset: number, text: string): void; save(filename: string): void; } interface SphereGame { name: string; directory: string; author: string; description: string; } interface SpherePersonData { /** the number of frames for the person's current direction */ num_frames: number; /** the number of directions for the person */ num_directions: number; /** the width of the spriteset's current frame */ width: number; /** the height of the spriteset's current frame */ height: number; /** the person that `name` is following, or "" if no-one */ leader: string; } interface SphereSpriteset { /* Spriteset base obstruction object */ base: SphereSpritesetBase; /** The filename that the spriteset was loaded with */ filename: string; /** Array of image objects */ images: Sphere1Image[]; /** Array of spriteset_direction objects */ directions: any[]; /** Saves the spriteset object to `filename` */ save(filename: string): void; /** Returns a copy of the spriteset object */ clone(): SphereSpriteset; } interface SphereSpritesetBase { x1: number; y1: number; x2: number; y2: number; } interface SphereSpritesetDirection { /** Name of the direction */ name: string; /** Array of spriteset frame objects */ frames: SphereSpritesetFrame[]; } interface SphereSpritesetFrame { /** Index into images array */ index: number; /** Number of frames before animation should switch */ delay: number; } interface SphereWindowStyle { /** * Draws the window at `x`,`y` with the width and height of `w` and `h`. * Note that window corners and edges are drawn outside of the width * and height of the window. */ drawWindow(x: number, y: number, w: number, h: number): void; /** * Sets the color mask for a windowstyle to `color` * @see ApplyColorMask */ setColorMask(color: Sphere1Color): void; /** * Gets the color mask being used by the windowstyle object */ getColorMask(): Sphere1Color; /** * Return the border size (height or width) in pixels for the windowstyle object. * You can use EDGE_LEFT, EDGE_TOP, EDGE_RIGHT and EDGE_BOTTOM as parameters. * Note that the corner sizes are ignored. */ getBorder(border: number): number; } /* * Sphere 1.x functions */ /** * Returns the Sphere API version (2 for miniSphere) */ declare function GetVersion(): number; /** * Returns the API version string (v2.0 for miniSphere) */ declare function GetVersionString(): string; /** * Invoke the garbage collector (you shouldn't need to use this in most cases) */ declare function GarbageCollect(): void; /** * Returns an array of object literals with properties describing the games in * `$HOME/Documents/miniSphere/Games/` for creating a startup game loader */ declare function GetGameList(): SphereGame[]; /** * Runs a Sphere game, given its directory */ declare function ExecuteGame(directory: string): void; /** * Restarts the current game (use Sphere.restart() instead) * @deprecated */ declare function RestartGame(): void; /** * Exits miniSphere (use Sphere.shutDown() instead) * @deprecated */ declare function Exit(): void; /** * Displays the given message and exits (use Sphere.abort() instead) * @deprecated */ declare function Abort(message: any): void; /** * Opens `filename` as a log file */ declare function OpenLog( filename: string, ): { /** * writes `text` to the log file */ write(text: string): void; /** * Begins an indented block in the text file with `name` as the block title */ beginBlock(name: string): void; /** * Closes the current block */ endBlock(): void; }; /** * Returns the number of milliseconds since some arbitrary time * @example * let start = GetTime(); * while (GetTime() < start + 1000) { * // do stuff * } */ declare function GetTime(): number; /** * Creates and returns a Sphere 1.x color object. `r`, `g`, `b`, and `a` should be 0-255 */ declare function CreateColor(r: number, g: number, b: number, a: number): Sphere1Color; /** * Blends `c1` and `c2` and returns the result */ declare function BlendColors(c1: Sphere1Color, c2: Sphere1Color): Sphere1Color; /** * Blends `c1` and `c2` with custom weights * @example * BlendColorsWeighted(a,b,1,1) // blends a and b equally * BlendColorsWeighted(a,b,1,2) // 33% a, 66% b */ declare function BlendColorsWeighted( c1: Sphere1Color, c2: Sphere1Color, c1_weight: number, c2_weight: number, ): Sphere1Color; /** * Creates a colormatrix that is used to transform the colors contained in a pixel */ declare function CreateColorMatrix( rn: number, rr: number, rg: number, rb: number, gn: number, gr: number, gg: number, gb: number, bn: number, br: number, bg: number, bb: number, ): any; /** * Returns an object representing the map engine */ declare function GetMapEngine(): { /** * Saves the loaded map to `filename` */ save(filename: string): void; /** * Adds a new layer filled with tile index */ layerAppend(width: number, height: number, tile: string): void; }; /** * Starts the map engine with the map specified and runs at `fps` frames per second */ declare function MapEngine(filename: string, fps: number): void; /** * Changes the current map */ declare function ChangeMap(filename: string): void; /** * Exits the map engine. Note: This tells the map engine to shut * down. This does not mean the engine shuts down immediately. You * must wait for the original call to MapEngine() to return before you * can start a new map engine. */ declare function ExitMapEngine(): void; /** * Returns `true` if the map engine is running */ declare function IsMapEngineRunning(): boolean; /** * Updates the map engine (entity states, color masks, etc) */ declare function UpdateMapEngine(): void; /** * Sets the frame rate of the map engine */ declare function SetMapEngineFrameRate(fps: number): void; /** * Returns the map engine's framerate */ declare function GetMapEngineFrameRate(): number; /** * Calls the given map script. `which` can be one of the following: * `SCRIPT_ON_ENTER_MAP`, `SCRIPT_ON_LEAVE_MAP`, * `SCRIPT_ON_LEAVE_MAP_NORTH`, `SCRIPT_ON_LEAVE_MAP_EAST`, * `SCRIPT_ON_LEAVE_MAP_SOUTH`, or `SCRIPT_ON_LEAVE_MAP_WEST` */ declare function CallMapScript(which: number): void; /** * Specifies that `script` should be called before the `which` map script. * The map engine doesn't necessarily need to be running. */ declare function SetDefaultMapScript(which: number, script: string): void; /** * Calls the default `which` map script. */ declare function CallDefaultMapScript(which: number): void; /** * Returns the number of layers in the loaded map */ declare function GetNumLayers(): number; /** * Returns the name of the layer at `index`, with 0 as the bottom layer */ declare function GetLayerName(index: number): string; /** * Returns the width (in tiles) of the layer at `index`, with 0 as the bottom layer */ declare function GetLayerWidth(index: number): number; /** * Returns the height (in tiles) of the layer at `index`, with 0 as the bottom layer */ declare function GetLayerHeight(index: number): number; /** * Returns `true` if the layer at `index` is visible, with 0 as the bottom layer */ declare function IsLayerVisible(index: number): boolean; /** * Sets the visibility of the layer at `index` to `visible`, with 0 as the bottom layer */ declare function SetLayerVisible(index: number, visible: boolean): void; /** * Returns true if the layer at `index` is reflective, with 0 as the bottom layer */ declare function IsLayerReflective(index: number): boolean; /** * Makes the layer at `index` reflective if `reflective` is true, with 0 as the bottom layer */ declare function SetLayerReflective(index: number, reflective: boolean): void; /** * Sets the color mask of the layer at `index` to `mask`, with 0 as the bottom layer */ declare function SetLayerMask(index: number, mask: Sphere1Color): void; /** * Returns the color mask of the layer at `index, with 0 as the bottom layer */ declare function GetLayerMask(index: number): Sphere1Color; /** * Sets the x zoom/scale factor for the layer at `index` to `factorX` * @example * SetLayerScaleFactor(0, 0.5); // makes bottom layer zoom out to half the normal size */ declare function SetLayerScaleFactorX(index: number, factorX: number): void; /** * Gets the angle (in radians) for the layer at `index` * @example * let angle = GetLayerAngle(0) // gets the angle of the bottom layer */ declare function GetLayerAngle(index: number): number; /** * Sets the angle (in radians) for the layer at `index`, with 0 as the bottom layer */ declare function SetLayerAngle(index: number, angle: number): void; /** * Returns the number of tiles in the loaded map */ declare function GetNumTiles(): number; /** * Changes the specified tile on the loaded map to `tile`, with 0 as the bottom layer */ declare function SetTile(x: number, y: number, layer: number, tile: number): void; /** * Returns the tile index at the specified location, with 0 as the bottom layer */ declare function GetTile(x: number, y: number, layer: number): number; /** * Returns the name of the tile at `index` */ declare function GetTileName(index: number): string; /** * Returns the width in pixels of the tiles on the loaded map */ declare function GetTileWidth(): number; /** * Returns the height in pixels of the tiles on the loaded map */ declare function GetTileHeight(): number; /** * Returns the Sphere 1.x image of the tile at `index` */ declare function GetTileImage(index: number): Sphere1Image; /** * Sets the tile image at `index` to `image` */ declare function SetTileImage(index: number, image: Sphere1Image): void; /** * Returns the surface of the tile at `index` */ declare function GetTileSurface(index: number): Sphere1Surface; /** * Sets the tile surface at `index` to `surface` */ declare function SetTileSurface(index: number, surface: Sphere1Surface): void; /** * Gets the animation delay of the tile at `tile`. If it returns 0, the tile is not animated */ declare function GetTileDelay(tile: number): number; /** * Sets the animation delay of the tile at `tile` to `delay`. A delay of 0 is considered not animated */ declare function SetTileDelay(tile: number, delay: number): void; /** * Gets the next tile index in the animation sequence of `tile`. If the return value is `tile`, the tile is not animated */ declare function GetNextAnimatedTile(tile: number): number; /** * Sets the next tile in the animation sequence of `tile` to `nextTile`. If both have the same value, it won't be animated. */ declare function SetNextAnimatedTile(tile: number, nextTile: number): void; /** * Replaces all `oldTile` tiles with `newTile` on layer `layer`, with 0 as the bottom layer */ declare function ReplaceTilesOnLayer(layer: number, oldTile: number, newTile: number): void; /** * Returns true if there is a trigger at `mapX`,`mapY`,`layer`. * `mapX` and `mapY` are per-pixel coordinates. */ declare function IsTriggerAt(mapX: number, mapY: number, layer: number): boolean; /** * Activates the trigger positioned at `mapX`,`mapY`,`layer` if one exists. * `mapX` and `mapY` are per-pixel coordinates. */ declare function ExecuteTrigger(mapX: number, mapY: number, layer: number): void; /** * Returns true if there are any zones at `mapX`,`mapY`,`layer` * `mapX` and `mapY` are per-pixel coordinates. */ declare function AreZonesAt(mapX: number, mapY: number, layer: number): boolean; /** * Executes all the zones containing `mapX`,`mapY`,`layer`. * `mapX` and `mapY` are per-pixel coordinates. */ declare function ExecuteZones(mapX: number, mapY: number, layer: number): void; /** * Returns the number of zones in the loaded map */ declare function GetNumZones(): number; /** * Returns the index of the current script's zone. This should be called from inside a ZoneScript handler. */ declare function GetCurrentZone(): number; /** * Returns the x value of zone `zone` */ declare function GetZoneX(zone: number): number; /** * Returns the y value of zone `zone` */ declare function GetZoneY(zone: number): number; /** * Returns the width of zone `zone` */ declare function GetZoneWidth(zone: number): number; /** * Returns the height of zone `zone` */ declare function GetZoneHeight(zone: number): number; /** * Returns the layer of zone `zone` */ declare function GetZoneLayer(zone: number): number; /** * Changes the layer of `zone` to `layer` */ declare function SetZoneLayer(zone: number, layer: number): void; /** * Executes the script for the zone `zone` */ declare function ExecuteZoneScript(zone: number): void; /** * Renders the map into the video buffer */ declare function RenderMap(): void; /** * Applies a color mask to things drawn by the map engine for `numFrames` frames */ declare function SetColorMask(color: Sphere1Color, numFrames: number): void; /** * Execute `script` (as a string, not a filename) after `numFrames` frames have passed */ declare function SetDelayScript(numFrames: number, script: string): void; /** * Makes `person` respond to input */ declare function AttachInput(person: string): void; /** * Releases input from the attached person entity */ declare function DetachInput(): void; /** * Returns true if a person is attached to the input */ declare function IsInputAttached(): boolean; /** * Returns the name of the person who currently holds input */ declare function GetInputPerson(): string; /** * Makes `person` respond to the input. `playerIndex` should be from 0-3 (max four players) * Note: AttachInput is equilivent to AttachPlayerInput(person, 0) */ declare function AttachPlayerInput(person: string, playerIndex: number): void; /** * Releases input from `personEntity` */ declare function DetachPlayerInput(personEntity: string): void; /** * Calls `script` after each frame (don't draw stuff in here!) */ declare function SetUpdateScript(script: string): void; /** * Calls `script` after all map layers are rendered */ declare function SetRenderScript(script: string): void; /** * Calls `script` after `layer` has been rendered. Only one rendering script can be used for each layer */ declare function SetLayerRenderer(layer: number, script: string): void; /** * Attaches the camera view to `person` */ declare function AttachCamera(person: string): void; /** * Detaches camera so it can be controlled directly */ declare function DetachCamera(): void; /** * Returns true if the camera is attached to a person */ declare function IsCameraAttached(): boolean; /** * Returns the name of the person whom the camera is attached to */ declare function GetCameraPerson(): string; /** * Sets the x value of the map camera (the center of the screen, if possible) */ declare function SetCameraX(x: number): void; /** * Sets the y value of the map camera (the center of the screen, if possible) */ declare function SetCameraY(y: number): void; /** * Returns the x value of the map camera (the center of the screen, if possible) */ declare function GetCameraX(): number; /** * Returns the y value of the map camera (the center of the screen, if possible) */ declare function GetCameraY(): number; /** * Returns the x value of the screen's position on the map */ declare function MapToScreenX(layer: number, x: number): number; /** * Returns the y value of the screen's position on the map */ declare function MapToScreenY(layer: number, y: number): number; /** * Returns the x value of the map's position on the screen */ declare function ScreenToMapX(layer: number, x: number): number; /** * Returns the y value of the map's position on the screen */ declare function ScreenToMapY(layer: number, y: number): number; /** * Returns an array of strings representing the current person entities */ declare function GetPersonList(): string[]; /** * Creates a person with `name` from `spriteset`. If the file is unable to be opened, * miniSphere will show an error message and exit. If `destroyWithMap` is true, the spriteset * will be destroyed when the current map is changed. */ declare function CreatePerson(name: string, spriteset: string, destroyWithMap: boolean): void; /** * Destroys the person with `name` */ declare function DestroyPerson(name: string): void; /** * Returns the x offset of `name` */ declare function GetPersonOffsetX(name: string): number; /** * Sets the horizontal offset to use for drawing frames for `name`. * e.g. setting `x` to 10 would result in `name` always being drawn 10 pixels * to the right, with the actual x position remaining unchanged */ declare function SetPersonOffsetX(name: string, x: number): void; /** * Returns the y offset of `name` */ declare function GetPersonOffsetY(name: string): number; /** * Sets the vertical offset to use for drawing frames for `name`. * e.g. setting `y` to 10 would result in `name` always being drawn 10 pixels * to the bottom, with the actual y position remaining unchanged */ declare function SetPersonOffsetY(name: string, y: number): void; /** * Returns the x position of `name` */ declare function GetPersonX(name: string): number; /** * Returns the y position of `name` */ declare function GetPersonY(name: string): number; /** * Sets the x position of `name` */ declare function SetPersonX(name: string, x: number): void; /** * Sets the y position of `name` */ declare function SetPersonY(name: string, y: number): void; /** * Returns the layer of `name` */ declare function GetPersonLayer(name: string): number; /** * Change the layer of `name` to `layer` */ declare function SetPersonLayer(name: string, layer: number): void; /** * Get the x position of `name` with floating point accuracy */ declare function GetPersonXFloat(name: string): number; /** * Get the y position of `name` with floating point accuracy */ declare function GetPersonYFloat(name: string): number; /** * Sets the position of `name` to `x`,`y` with floating point accuracy */ declare function SetPersonXYFloat(name: string, x: number, y: number): void; /** * Returns the direction of `name` */ declare function GetPersonDirection(name: string): string; /** * Sets the direction of `name` to `direction` */ declare function SetPersonDirection(name: string, direction: string): void; /** * Returns the direction animation frame number of `name` */ declare function GetPersonFrame(name: string): number; /** * Sets the direction animation frame of `name` to `frame` */ declare function SetPersonFrame(name: string, frame: number): void; /** * Returns the x movement speed of `name` */ declare function GetPersonSpeedX(name: string): number; /** * Returns the y movement speed of `name` */ declare function GetPersonSpeedY(name: string): number; /** * Sets the movement speed for both x and y of `name` to `speed` */ declare function SetPersonSpeed(name: string, speed: number): void; /** * Set the x and y movement speed of `name` to `speedX`,`speedY` respectively */ declare function SetPersonSpeedXY(name: string, speedX: number, speedY: number): void; /** * Returns the number of animation frames to delay for `name` between the first and last frame */ declare function GetPersonFrameRevert(name: string): number; /** * Sets the number of animation frames to delay for `name` between the first and last frame */ declare function SetPersonFrameRevert(name: string, delay: number): void; /** * Rescales `name`'s spriteset by a factor of `scaleW`,`scaleH` * (e.g. 1.0 = original size, 1.5 = 1.5 times the original size, etc) */ declare function SetPersonScaleFactor(name: string, scaleW: number, scaleH: number): void; /** * Rescales `name`'s spriteset to exactly `width`,`height` pixels */ declare function SetPersonScaleAbsolute(name: string, width: number, height: number): void; /** * Returns the person's spriteset */ declare function GetPersonSpriteset(name: string): SphereSpriteset; /** * Set `name`'s spriteset to `spriteset * @example SetPersonSpriteset("Jimmy", LoadSpriteset("jimmy.running.rss")); */ declare function SetPersonSpriteset(name: string, spriteset: SphereSpriteset): void; /** * Returns the person's base obstruction object. */ declare function GetPersonBase(name: string): SphereSpritesetBase; /** Returns the person's angle in radians */ declare function GetPersonAngle(name: string): number; /** * Sets the angle of `name` in radians (obstruction base is unaffected) */ declare function SetPersonAngle(name: string, angle: number): void; /** * Sets a color multiplier to use when drawing sprites for `name` * @example * SetPersonMask("Jimmy", CreateColor(255, 0, 0, 255)); // only red elements are drawn * SetPersonMask("Jimmy", CreateColor(255, 255, 128)); // draw at half transparency */ declare function SetPersonMask(name: string, color: Sphere1Color): void; /** * Returns the color mask of `name` */ declare function GetPersonMask(name: string): Sphere1Color; /** * Returns true if `name` is visible */ declare function IsPersonVisible(name: string): boolean; /** * Sets the visibility status of `name` to `visible` */ declare function SetPersonVisible(name: string, visible: boolean): void; /** * Returns a data object associated with the person `name` with the following default properties: * @example * let data = GetPersonData("Jimmy"); * let num_frames = data["num_frames"]; */ declare function GetPersonData(name: string): SpherePersonData; /** * Sets the data object associated with `name` to `data` * @example * let data = GetPersonData("Jimmy"); * data["talked_to_jimmy"] = true; * SetPersonData("Jimmy", data); */ declare function SetPersonData(name: string, data: SpherePersonData): void; /** * Sets a specific data value of `name` to `value` * @see SetPersonData * @see GetPersonData */ declare function SetPersonValue(name: string, key: string, value: any): void; /** * Gets a specific data value from `name` * @see SetPersonData * @see GetPersonData */ declare function GetPersonValue(name: string, key: string): any; /** * Makes the sprite of `name` follow `pixels` behind the sprite of `leader`. * If `leader` is "", it will detach from anyone it is following */ declare function FollowPerson(name: string, leader: string, pixels: number): void; /** * Sets `script` to be called during `which` event for `name` * @example * SetPersonScript("Jimmy", SCRIPT_ON_DESTROY, "SSj.log('Jimmy spriteset destroyed'") */ declare function SetPersonScript(name: string, which: number, script: string): void; /** * Calls `which` script for `name` */ declare function CallPersonScript(name: string, which: number): void; /** * Returns the name of the person for whom the current script is running. * This should be called from inside a PersonScript handler. */ declare function GetCurrentPerson(): string; /** * Adds a command to the `name`'s command queue. If `immediate` is true, it will be executed immediately. * Otherwise it will wait until the next frame. */ declare function QueuePersonCommand(name: string, command: number, immediate: boolean): void; /** * Adds `script` to `name`'s queue. If `immediate` is true, it will be executed immediately. * Otherwise it will wait until the next frame. */ declare function QueuePersonScript(name: string, script: string, immediate: boolean): void; /** * Clears the command queue of `name` */ declare function ClearPersonCommands(name: string): void; /** * Returns true if `name` has an empty command queue */ declare function IsCommandQueueEmpty(name: string): boolean; /** * Returns true if `name` would be obstructed at `x`,`y` */ declare function IsPersonObstructed(name: string, x: number, y: number): boolean; /** * Returns the tile index of the tile `name` would be obstructed by at `x`,`y` or -1 * if it isn't obstructed at that position */ declare function GetObstructingTile(name: string, x: number, y: number): number; /** * Returns the name of the person who `name` would be obstructed by at `x`,`y` * or "" if it isn't obstructed by a person at that position */ declare function GetObstructingPerson(name: string, x: number, y: number): string; /** * Sets whether `person` should ignore other spriteset obstruction bases */ declare function IgnorePersonObstructions(person: string, ignore: boolean): void; /** * Returns true if `person` is ignoring person obstructions, else false */ declare function IsIgnoringPersonObstructions(person: string): boolean; /** * Sets whether `person` should ignore tile obstructions */ declare function IgnoreTileObstructions(person: string, ignore: boolean): void; /** * Returns true if `person` is ignoring tile obstructions, else false */ declare function IsIgnoringTileObstructions(person: string): boolean; /** * Returns a list of people that `name` is ignoring */ declare function GetPersonIgnoreList(person: string): string[]; /** * Tells `person` to ignore everyone in `ignoreList` * @example SetPersonIgnoreList("White-Bomberman", ["bomb", "powerup"]); */ declare function SetPersonIgnoreList(person: string, ignoreList: string[]): void; /** * Get the (Sphere 1.x) key used to activate talk scripts */ declare function GetTalkActivationKey(): number; /** * Set the (Sphere 1.x) key used to activate talk scripts */ declare function SetTalkActivationKey(key: number): void; /** * Returns the distance between the input person and another person required for talk script activation */ declare function GetTalkDistance(): number; /** * Set the distance between the input person and another person required for talk script activation */ declare function SetTalkDistance(pixels: number): void; /** * Returns a spriteset object from `filename`. If the file is unable to be opened, * an error will be shown and miniSphere will exit */ declare function LoadSpriteset(filename: string): SphereSpriteset; /** * Returns a blank spriteset object with the given dimensions */ declare function CreateSpriteset( frameWidth: number, frameHeight: number, numImages: number, numDirections: number, numFrames: number, ): SphereSpriteset;
the_stack
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. https://www.cocos.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license to use Cocos Creator solely to develop games on your target platforms. You shall not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @packageDocumentation * @module physics */ import { ccclass, help, disallowMultiple, executeInEditMode, menu, executionOrder, tooltip, displayOrder, visible, type, serializable, } from 'cc.decorator'; import { DEBUG } from 'internal:constants'; import { Vec3 } from '../../../core/math'; import { Component, error, warn } from '../../../core'; import { IRigidBody } from '../../spec/i-rigid-body'; import { selector, createRigidBody } from '../physics-selector'; import { ERigidBodyType } from '../physics-enum'; import { PhysicsSystem } from '../physics-system'; /** * @en * Rigid body component. * @zh * 刚体组件。 */ @ccclass('cc.RigidBody') @help('i18n:cc.RigidBody') @menu('Physics/RigidBody') @executeInEditMode @disallowMultiple @executionOrder(-1) export class RigidBody extends Component { /** * @en * Enumeration of rigid body types. * @zh * 刚体类型的枚举。 */ static readonly Type = ERigidBodyType; /// PUBLIC PROPERTY GETTER\SETTER /// /** * @en * Gets or sets the group of the rigid body. * @zh * 获取或设置分组。 */ @type(PhysicsSystem.PhysicsGroup) @displayOrder(-2) @tooltip('i18n:physics3d.rigidbody.group') public get group (): number { return this._group; } public set group (v: number) { if (DEBUG && !Number.isInteger(Math.log2(v >>> 0))) warn('[Physics]: The group should only have one bit.'); this._group = v; if (this._body) { // The judgment is added here because the data exists in two places if (this._body.getGroup() !== v) this._body.setGroup(v); } } /** * @en * Gets or sets the type of rigid body. * @zh * 获取或设置刚体类型。 */ @type(ERigidBodyType) @displayOrder(-1) @tooltip('i18n:physics3d.rigidbody.type') public get type (): ERigidBodyType { return this._type; } public set type (v: ERigidBodyType) { if (this._type === v) return; this._type = v; if (this._body) this._body.setType(v); } /** * @en * Gets or sets the mass of the rigid body. * @zh * 获取或设置刚体的质量。 */ @visible(isDynamicBody) @displayOrder(0) @tooltip('i18n:physics3d.rigidbody.mass') public get mass () { return this._mass; } public set mass (value) { if (DEBUG && value <= 0) warn('[Physics]: The mass should be greater than zero.'); if (this._mass === value) return; value = value <= 0 ? 0.0001 : value; this._mass = value; if (this._body) this._body.setMass(value); } /** * @en * Gets or sets whether hibernation is allowed. * @zh * 获取或设置是否允许休眠。 */ @visible(isDynamicBody) @displayOrder(0.5) @tooltip('i18n:physics3d.rigidbody.allowSleep') public get allowSleep (): boolean { return this._allowSleep; } public set allowSleep (v: boolean) { this._allowSleep = v; if (this._body) this._body.setAllowSleep(v); } /** * @en * Gets or sets linear damping. * @zh * 获取或设置线性阻尼。 */ @visible(isDynamicBody) @displayOrder(1) @tooltip('i18n:physics3d.rigidbody.linearDamping') public get linearDamping () { return this._linearDamping; } public set linearDamping (value) { if (DEBUG && (value < 0 || value > 1)) warn('[Physics]: The damping should be between zero to one.'); this._linearDamping = value; if (this._body) this._body.setLinearDamping(value); } /** * @en * Gets or sets the rotation damping. * @zh * 获取或设置旋转阻尼。 */ @visible(isDynamicBody) @displayOrder(2) @tooltip('i18n:physics3d.rigidbody.angularDamping') public get angularDamping () { return this._angularDamping; } public set angularDamping (value) { if (DEBUG && (value < 0 || value > 1)) warn('[Physics]: The damping should be between zero to one.'); this._angularDamping = value; if (this._body) this._body.setAngularDamping(value); } /** * @en * Gets or sets whether a rigid body uses gravity. * @zh * 获取或设置刚体是否使用重力。 */ @visible(isDynamicBody) @displayOrder(4) @tooltip('i18n:physics3d.rigidbody.useGravity') public get useGravity () { return this._useGravity; } public set useGravity (value) { this._useGravity = value; if (this._body) this._body.useGravity(value); } /** * @en * Gets or sets the linear velocity factor that can be used to control the scaling of the velocity in each axis direction. * @zh * 获取或设置线性速度的因子,可以用来控制每个轴方向上的速度的缩放。 */ @visible(isDynamicBody) @displayOrder(6) @tooltip('i18n:physics3d.rigidbody.linearFactor') public get linearFactor () { return this._linearFactor; } public set linearFactor (value: Vec3) { Vec3.copy(this._linearFactor, value); if (this._body) { this._body.setLinearFactor(this._linearFactor); } } /** * @en * Gets or sets the rotation speed factor that can be used to control the scaling of the rotation speed in each axis direction. * @zh * 获取或设置旋转速度的因子,可以用来控制每个轴方向上的旋转速度的缩放。 */ @visible(isDynamicBody) @displayOrder(7) @tooltip('i18n:physics3d.rigidbody.angularFactor') public get angularFactor () { return this._angularFactor; } public set angularFactor (value: Vec3) { Vec3.copy(this._angularFactor, value); if (this._body) { this._body.setAngularFactor(this._angularFactor); } } /** * @en * Gets or sets the speed threshold for going to sleep. * @zh * 获取或设置进入休眠的速度临界值。 */ public get sleepThreshold (): number { if (this._isInitialized) { return this._body!.getSleepThreshold(); } return 0.1; } public set sleepThreshold (v: number) { if (this._isInitialized) { this._body!.setSleepThreshold(v); } } /** * @en * Turning on or off continuous collision detection. * @zh * 开启或关闭连续碰撞检测。 */ public get useCCD (): boolean { if (this._isInitialized) { return this._body!.isUsingCCD(); } return false; } public set useCCD (v: boolean) { if (this._isInitialized) { this._body!.useCCD(v); } } /** * @en * Gets whether it is the state of awake. * @zh * 获取是否是唤醒的状态。 */ public get isAwake (): boolean { if (this._isInitialized) return this._body!.isAwake; return false; } /** * @en * Gets whether you can enter a dormant state. * @zh * 获取是否是可进入休眠的状态。 */ public get isSleepy (): boolean { if (this._isInitialized) return this._body!.isSleepy; return false; } /** * @en * Gets whether the state is dormant. * @zh * 获取是否是正在休眠的状态。 */ public get isSleeping (): boolean { if (this._isInitialized) return this._body!.isSleeping; return false; } /** * @en * Gets or sets whether the rigid body is static. * @zh * 获取或设置刚体是否是静态类型的(静止不动的)。 */ public get isStatic (): boolean { return this._type === ERigidBodyType.STATIC; } public set isStatic (v: boolean) { if ((v && this.isStatic) || (!v && !this.isStatic)) return; this.type = v ? ERigidBodyType.STATIC : ERigidBodyType.DYNAMIC; } /** * @en * Gets or sets whether the rigid body moves through physical dynamics. * @zh * 获取或设置刚体是否是动力学态类型的(将根据物理动力学控制运动)。 */ public get isDynamic (): boolean { return this._type === ERigidBodyType.DYNAMIC; } public set isDynamic (v: boolean) { if ((v && this.isDynamic) || (!v && !this.isDynamic)) return; this.type = v ? ERigidBodyType.DYNAMIC : ERigidBodyType.KINEMATIC; } /** * @en * Gets or sets whether a rigid body is controlled by users. * @zh * 获取或设置刚体是否是运动态类型的(将由用户来控制运动)。 */ public get isKinematic () { return this._type === ERigidBodyType.KINEMATIC; } public set isKinematic (v: boolean) { if ((v && this.isKinematic) || (!v && !this.isKinematic)) return; this.type = v ? ERigidBodyType.KINEMATIC : ERigidBodyType.DYNAMIC; } /** * @en * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ public get body () { return this._body; } private _body: IRigidBody | null = null; /// PRIVATE PROPERTY /// @serializable private _group: number = PhysicsSystem.PhysicsGroup.DEFAULT; @serializable private _type: ERigidBodyType = ERigidBodyType.DYNAMIC; @serializable private _mass = 1; @serializable private _allowSleep = true; @serializable private _linearDamping = 0.1; @serializable private _angularDamping = 0.1; @serializable private _useGravity = true; @serializable private _linearFactor: Vec3 = new Vec3(1, 1, 1); @serializable private _angularFactor: Vec3 = new Vec3(1, 1, 1); protected get _isInitialized (): boolean { const r = this._body === null; if (r) { error('[Physics]: This component has not been call onLoad yet, please make sure the node has been added to the scene.'); } return !r; } /// COMPONENT LIFECYCLE /// protected onLoad () { if (!selector.runInEditor) return; this._body = createRigidBody(); this._body.initialize(this); } protected onEnable () { if (this._body) this._body.onEnable!(); } protected onDisable () { if (this._body) this._body.onDisable!(); } protected onDestroy () { if (this._body) this._body.onDestroy!(); } /// PUBLIC METHOD /// /** * @en * Apply force to a world point. This could, for example, be a point on the Body surface. * @zh * 在世界空间中,相对于刚体的质心的某点上对刚体施加作用力。 * @param force - 作用力 * @param relativePoint - 作用点,相对于刚体的质心 */ public applyForce (force: Vec3, relativePoint?: Vec3) { if (this._isInitialized) this._body!.applyForce(force, relativePoint); } /** * @en * Apply force to a local point. This could, for example, be a point on the Body surface. * @zh * 在本地空间中,相对于刚体的质心的某点上对刚体施加作用力。 * @param force - 作用力 * @param localPoint - 作用点 */ public applyLocalForce (force: Vec3, localPoint?: Vec3) { if (this._isInitialized) this._body!.applyLocalForce(force, localPoint); } /** * @en * In world space, impulse is applied to the rigid body at some point relative to the center of mass of the rigid body. * @zh * 在世界空间中,相对于刚体的质心的某点上对刚体施加冲量。 * @param impulse - 冲量 * @param relativePoint - 作用点,相对于刚体的中心点 */ public applyImpulse (impulse: Vec3, relativePoint?: Vec3) { if (this._isInitialized) this._body!.applyImpulse(impulse, relativePoint); } /** * @en * In local space, impulse is applied to the rigid body at some point relative to the center of mass of the rigid body. * @zh * 在本地空间中,相对于刚体的质心的某点上对刚体施加冲量。 * @param impulse - 冲量 * @param localPoint - 作用点 */ public applyLocalImpulse (impulse: Vec3, localPoint?: Vec3) { if (this._isInitialized) this._body!.applyLocalImpulse(impulse, localPoint); } /** * @en * In world space, torque is applied to the rigid body. * @zh * 在世界空间中,对刚体施加扭矩。 * @param torque - 扭矩 */ public applyTorque (torque: Vec3) { if (this._isInitialized) this._body!.applyTorque(torque); } /** * @zh * 在本地空间中,对刚体施加扭矩。 * @param torque - 扭矩 */ public applyLocalTorque (torque: Vec3) { if (this._isInitialized) this._body!.applyLocalTorque(torque); } /** * @en * Wake up the rigid body. * @zh * 唤醒刚体。 */ public wakeUp () { if (this._isInitialized) this._body!.wakeUp(); } /** * @en * Dormancy of rigid body. * @zh * 休眠刚体。 */ public sleep () { if (this._isInitialized) this._body!.sleep(); } /** * @en * Clear the forces and velocity of the rigid body. * @zh * 清除刚体受到的力和速度。 */ public clearState () { if (this._isInitialized) this._body!.clearState(); } /** * @en * Clear the forces of the rigid body. * @zh * 清除刚体受到的力。 */ public clearForces () { if (this._isInitialized) this._body!.clearForces(); } /** * @en * Clear velocity of the rigid body. * @zh * 清除刚体的速度。 */ public clearVelocity () { if (this._isInitialized) this._body!.clearVelocity(); } /** * @en * Gets the linear velocity. * @zh * 获取线性速度。 * @param out 速度 Vec3 */ public getLinearVelocity (out: Vec3) { if (this._isInitialized) this._body!.getLinearVelocity(out); } /** * @en * Sets the linear velocity. * @zh * 设置线性速度。 * @param value 速度 Vec3 */ public setLinearVelocity (value: Vec3): void { if (this._isInitialized) this._body!.setLinearVelocity(value); } /** * @en * Gets the angular velocity. * @zh * 获取旋转速度。 * @param out 速度 Vec3 */ public getAngularVelocity (out: Vec3) { if (this._isInitialized) this._body!.getAngularVelocity(out); } /** * @en * Sets the angular velocity. * @zh * 设置旋转速度。 * @param value 速度 Vec3 */ public setAngularVelocity (value: Vec3): void { if (this._isInitialized) this._body!.setAngularVelocity(value); } /// GROUP MASK /// /** * @en * Gets the group value. * @zh * 获取分组值。 * @returns 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public getGroup (): number { if (this._isInitialized) return this._body!.getGroup(); return 0; } /** * @en * Sets the group value. * @zh * 设置分组值。 * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public setGroup (v: number): void { if (this._isInitialized) this._body!.setGroup(v); } /** * @en * Add a grouping value to fill in the group you want to join. * @zh * 添加分组值,可填要加入的 group。 * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public addGroup (v: number) { if (this._isInitialized) this._body!.addGroup(v); } /** * @en * Subtract the grouping value to fill in the group to be removed. * @zh * 减去分组值,可填要移除的 group。 * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public removeGroup (v: number) { if (this._isInitialized) this._body!.removeGroup(v); } /** * @en * Gets the mask value. * @zh * 获取掩码值。 * @returns 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public getMask (): number { if (this._isInitialized) return this._body!.getMask(); return 0; } /** * @en * Sets the mask value. * @zh * 设置掩码值。 * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public setMask (v: number) { if (this._isInitialized) this._body!.setMask(v); } /** * @en * Add mask values to fill in groups that need to be checked. * @zh * 添加掩码值,可填入需要检查的 group。 * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public addMask (v: number) { if (this._isInitialized) this._body!.addMask(v); } /** * @en * Subtract the mask value to fill in the group that does not need to be checked. * @zh * 减去掩码值,可填入不需要检查的 group。 * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 */ public removeMask (v: number) { if (this._isInitialized) this._body!.removeMask(v); } } function isDynamicBody (this: RigidBody) { return this.isDynamic; } export namespace RigidBody { export type Type = EnumAlias<typeof ERigidBodyType>; }
the_stack
import { logger, OrNull, parseColor } from '@pintora/core' import { StyleParam } from '../util/style' export interface WrappedText { text: string wrap: boolean } type ParsedDescription = WrappedText export enum LINETYPE { SOLID = 0, DOTTED = 1, NOTE = 2, SOLID_CROSS = 3, DOTTED_CROSS = 4, SOLID_OPEN = 5, DOTTED_OPEN = 6, LOOP_START = 10, LOOP_END = 11, ALT_START = 12, ALT_ELSE = 13, ALT_END = 14, OPT_START = 15, OPT_END = 16, ACTIVE_START = 17, ACTIVE_END = 18, PAR_START = 19, PAR_AND = 20, PAR_END = 21, RECT_START = 22, RECT_END = 23, SOLID_POINT = 24, DOTTED_POINT = 25, DIVIDER = 26, } export const ARROWTYPE = { FILLED: 0, OPEN: 1, } export enum PLACEMENT { LEFTOF = 0, RIGHTOF = 1, OVER = 2, } export type Actor = { name: string description: string wrap: boolean classifier?: string prevActorId?: OrNull<string> nextActorId?: OrNull<string> } export interface Message extends WrappedText { from: string to: string text: string wrap: any id?: string answer?: any type?: LINETYPE placement?: any attrs?: GroupAttrs } export interface Note extends WrappedText { actor: string | string[] placement: any } const GROUP_TYPE_CONFIGS: Record<string, { startSignalType: LINETYPE; endSignalType: LINETYPE }> = { loop: { startSignalType: LINETYPE.LOOP_START, endSignalType: LINETYPE.LOOP_END }, par: { startSignalType: LINETYPE.PAR_START, endSignalType: LINETYPE.PAR_END }, opt: { startSignalType: LINETYPE.OPT_START, endSignalType: LINETYPE.OPT_END }, alt: { startSignalType: LINETYPE.ALT_START, endSignalType: LINETYPE.ALT_END }, else: { startSignalType: LINETYPE.ALT_ELSE, endSignalType: LINETYPE.ALT_END }, and: { startSignalType: LINETYPE.PAR_AND, endSignalType: LINETYPE.PAR_END }, } export type GroupAttrs = { background: string | null } export type SequenceDiagramIR = { messages: Message[] notes: Note[] actors: { [key: string]: Actor } title: string showSequenceNumbers: boolean // titleWrapped: boolean styleParams: StyleParam[] } class SequenceDB { prevActorId: string | null = null messages: Message[] = [] notes: Note[] = [] actors: { [key: string]: Actor } = {} title = '' titleWrapped = false wrapEnabled = false showSequenceNumbers = false styleParams: SequenceDiagramIR['styleParams'] = [] addActor(param: AddActorParam) { const { actor: name, classifier } = param let { description } = param const id = name // Don't allow description nulling const old = this.actors[id] if (old && name === old.name && description == null) return // Don't allow null descriptions, either if (description == null || description.text == null) { description = { text: name, wrap: false } } this.actors[id] = { name: name, description: description.text, wrap: (description.wrap === undefined && this.wrapEnabled) || !!description.wrap, prevActorId: this.prevActorId, classifier, } if (this.prevActorId && this.actors[this.prevActorId]) { this.actors[this.prevActorId].nextActorId = id } this.prevActorId = id } addMessage(idFrom: string, idTo: string, message: Message, answer: any) { this.messages.push({ from: idFrom, to: idTo, text: message.text, wrap: (message.wrap === undefined && this.wrapEnabled) || !!message.wrap, answer: answer, }) } addSignal( from: { actor: string } | string, to: { actor: string } | string, message: WrappedText = { text: '', wrap: false }, messageType: LINETYPE, ) { if (typeof from === 'string') { from = { actor: from } } if (typeof to === 'string') { to = { actor: to } } if (messageType === LINETYPE.ACTIVE_END) { const cnt = activationCount(this, from.actor) if (cnt < 1) { // Bail out as there is an activation signal from an inactive participant const error = new SError('Trying to inactivate an inactive participant (' + from.actor + ')') error.hash = { text: '->>-', token: '->>-', line: '1', loc: { first_line: 1, last_line: 1, first_column: 1, last_column: 1 }, expected: ["'ACTIVE_PARTICIPANT'"], } throw error } } this.messages.push({ from: from.actor, to: to ? to.actor : '', text: message.text || '', wrap: (message.wrap === undefined && this.wrapEnabled) || !!message.wrap, type: messageType, }) return true } addSignalWithoutActor(message: WrappedText = { text: '', wrap: false }, messageType: LINETYPE, attrs?: GroupAttrs) { this.messages.push({ from: undefined, to: undefined, text: message.text || '', wrap: (message.wrap === undefined && this.wrapEnabled) || !!message.wrap, type: messageType, attrs, }) } addGroupStart(groupType: string, text: WrappedText, attrs: GroupAttrs) { const groupConfig = GROUP_TYPE_CONFIGS[groupType] if (!groupConfig) return if (attrs.background) { attrs.background = parseColor(attrs.background).color } this.addSignalWithoutActor(text, groupConfig.startSignalType, attrs) } addGroupEnd(groupType: string) { const groupConfig = GROUP_TYPE_CONFIGS[groupType] if (!groupConfig) return this.addSignalWithoutActor(undefined, groupConfig.endSignalType) } addNote(actor: string | string[], placement: any, message: ParsedDescription) { const note: Note = { actor: actor, placement, text: message.text, wrap: (message.wrap === undefined && this.wrapEnabled) || !!message.wrap, } const fromActor = Array.isArray(actor) ? actor[0] : actor const toActor = Array.isArray(actor) ? actor[1] : actor this.notes.push(note) this.messages.push({ from: fromActor, to: toActor, text: message.text, wrap: (message.wrap === undefined && this.wrapEnabled) || !!message.wrap, type: LINETYPE.NOTE, placement: placement, }) // console.log('addNote, message', actor, this.messages[this.messages.length - 1]) } setTitle(titleWrap: WrappedText) { this.title = titleWrap.text this.titleWrapped = (titleWrap.wrap === undefined && this.wrapEnabled) || !!titleWrap.wrap } parseMessage(str: string) { const _str = str.trim() const message = { text: _str.replace(/\\n/, '\n'), wrap: false, } logger.debug('parseMessage:', message) return message } addStyle(sp: StyleParam) { this.styleParams.push(sp) } getActor(id: string) { return this.actors[id] } getActorKeys() { return Object.keys(this.actors) } clear() { this.prevActorId = null this.messages = [] this.notes = [] this.actors = {} this.title = '' this.showSequenceNumbers = false this.styleParams = [] } getDiagramIR(): SequenceDiagramIR { return { messages: this.messages, notes: this.notes, actors: this.actors, title: this.title, showSequenceNumbers: this.showSequenceNumbers, styleParams: this.styleParams, } } apply(param: ApplyParam | ApplyParam[]) { if (!param) return if (param instanceof Array) { param.forEach(item => { this.apply(item) }) } else { logger.debug('apply', param) switch (param.type) { case 'addActor': // db.addActor(param.actor, param.actor, param.description) db.addActor(param) break case 'activeStart': case 'activeEnd': db.addSignal(param.actor, undefined, undefined, param.signalType) break case 'addNote': db.addNote(param.actor, param.placement, param.text) break case 'addSignal': db.addSignal(param.from, param.to, param.msg, param.signalType) break case 'groupStart': db.addGroupStart(param.groupType, param.text, { background: param.background }) break case 'groupEnd': db.addGroupEnd(param.groupType) break // case 'rectStart': // addSignal(undefined, undefined, param.color, param.signalType) // break // case 'rectEnd': // addSignal(undefined, undefined, undefined, param.signalType) // break case 'setTitle': db.setTitle(param.text) break case 'addDivider': db.addSignalWithoutActor({ text: param.text, wrap: false }, param.signalType) break case 'addStyle': db.addStyle({ key: param.key, value: param.value }) break } } } } const db = new SequenceDB() class SError extends Error { hash: any } const activationCount = (db: SequenceDB, part: string) => { let i let count = 0 for (i = 0; i < db.messages.length; i++) { if (db.messages[i].type === LINETYPE.ACTIVE_START) { if (db.messages[i].from === part) { count++ } } if (db.messages[i].type === LINETYPE.ACTIVE_END) { if (db.messages[i].from === part) { count-- } } } return count } export function enableSequenceNumbers() { db.showSequenceNumbers = true } type AddActorParam = { actor: string description: WrappedText classifier?: string } /** * action param that will be handled by `apply` */ type ApplyParam = | ({ type: 'addActor' } & AddActorParam) | { type: 'activeStart' | 'activeEnd' actor: { type: string; actor: string } signalType: LINETYPE } | { type: 'addNote' actor: string | string[] placement: PLACEMENT text: WrappedText } | { type: 'addSignal' from: { actor: string } to: { actor: string } msg: WrappedText signalType: LINETYPE } | { type: 'setTitle' text: WrappedText } | { type: 'groupStart' groupType: string text: WrappedText background: string | null } | { type: 'groupEnd' groupType: string } | { type: 'addDivider' signalType: LINETYPE text: string } | { type: 'addStyle' key: string value: string } export { db } export default { addActor: db.addActor, addMessage: db.addMessage, addSignal: db.addSignal, enableSequenceNumbers, parseMessage: db.parseMessage, LINETYPE, ARROWTYPE, PLACEMENT, addNote: db.addNote, setTitle: db.setTitle, apply: db.apply, }
the_stack
import { EventEmitter as EE } from '../src/ee' interface A { foo(): void bar(a: number, b: number): number } test('nullish listeners', () => { let ee = new EE<A>() ee.on('foo', undefined) ee.on({ foo: null }) expect(ee[EE.ev]).toEqual({}) }) /** * Recurring listeners */ test('add a recurring listener', () => { let ee = new EE<A>() let fn = jest.fn() expect(ee.on('foo', fn)).toBe(fn) ee.emit('foo') expect(fn.mock.calls.length).toBe(1) ee.emit('foo') expect(fn.mock.calls.length).toBe(2) }) test('add multiple recurring listeners', () => { let ee = new EE<A>() let fn = jest.fn() expect( ee.on({ foo: fn, bar: fn, }) ).toBe(ee) ee.emit('foo') ee.emit('bar', 1, 2) ee.emit('foo') ee.emit('bar', 3, 4) expect(fn.mock.calls).toEqual([[], [1, 2], [], [3, 4]]) }) test('emit returns last return value (excluding undefined)', () => { let ee = new EE<A>() ee.on('bar', () => {}) ee.on('bar', () => 1) ee.on('bar', () => {}) ee.on('bar', () => 2) ee.on('bar', () => {}) expect(ee.emit('bar', 1, 2)).toBe(2) }) /** * One-time listeners */ test('add a one-time listener', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => {}) ee.one('foo', fn) ee.on('foo', () => {}) ee.emit('foo') expect(EE.count(ee, 'foo')).toBe(2) expect(fn).toHaveBeenCalledTimes(1) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) }) test('add multiple one-time listeners', () => { let ee = new EE<A>() let f1 = ee.one('foo', jest.fn()) let f2 = ee.one('foo', jest.fn()) ee.emit('foo') ee.emit('foo') expect(f1).toHaveBeenCalledTimes(1) expect(f2).toHaveBeenCalledTimes(1) expect(EE.count(ee, 'foo')).toBe(0) }) test('remove a one-time listener', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => {}) ee.one('foo', fn) ee.on('foo', () => {}) ee.off('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(2) }) test('multiple consecutive one-time listeners', () => { let ee = new EE<A>() let fn = jest.fn() ee.one('foo', fn) ee.one('foo', fn) ee.emit('foo') ee.emit('foo') expect(fn).toHaveBeenCalledTimes(2) expect(EE.count(ee, 'foo')).toBe(0) }) /** * Removed listeners */ test('remove a recurring listener', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => {}) ee.on('foo', fn) ee.on('foo', () => {}) ee.off('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(2) }) test('remove the only listener of an event', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', fn) ee.off('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(0) }) test('remove the first listener of an event', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', fn) ee.on('foo', () => {}) ee.off('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(1) }) test('remove the last listener of an event', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => {}) ee.on('foo', fn) ee.off('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(1) }) test('remove all listeners of an event', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => fn()) ee.on('foo', () => fn()) ee.on('foo', () => fn()) ee.off('foo') ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(0) }) test('remove all listeners of all events', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => fn()) ee.on('bar', () => fn()) ee.off('*') ee.emit('foo') ee.emit('bar', 1, 2) expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(0) expect(EE.count(ee, 'bar')).toBe(0) }) test('remove current listener during emit', () => { let ee = new EE<A>() let fn = jest.fn(() => { ee.off('foo', fn) }) ee.on('foo', () => {}) ee.on('foo', fn) ee.on('foo', () => {}) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) expect(EE.count(ee, 'foo')).toBe(2) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) }) test('remove pending listener during emit', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', () => ee.off('foo', fn)) ee.on('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(0) expect(EE.count(ee, 'foo')).toBe(1) }) test('remove finished listener during emit', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', fn) ee.on('foo', () => ee.off('foo', fn)) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) expect(EE.count(ee, 'foo')).toBe(1) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) }) test('remove a listener that was added twice', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', fn) ee.on('foo', () => ee.off('foo', fn)) ee.on('foo', fn) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) expect(EE.count(ee, 'foo')).toBe(1) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) }) test('remove a listener that was never added', () => { let ee = new EE<A>() let fn = jest.fn() ee.on('foo', fn) ee.off('foo', () => {}) ee.emit('foo') expect(fn).toHaveBeenCalledTimes(1) }) /** * Listeners iterable */ test('iterate over listeners', () => { let ee = new EE<A>() let fn1 = ee.on('foo', jest.fn()) let fn2 = ee.on('foo', jest.fn()) expect([...ee.listeners('foo')]).toEqual([fn1, fn2]) }) test('try iterating over event with no listeners', () => { let ee = new EE<A>() expect([...ee.listeners('foo')]).toEqual([]) }) /** * Disposables */ test('pass an array to collect disposables', () => { let ee = new EE<A>() let list: Array<{ dispose(): void }> = [] let fn1 = ee.on('foo', jest.fn(), list) let fn2 = ee.on('foo', jest.fn(), list) ee.emit('foo') // Dispose the first listener. list[0].dispose() ee.emit('foo') expect(fn1).toBeCalledTimes(1) expect(fn2).toBeCalledTimes(2) // Dispose the second listener. list[1].dispose() ee.emit('foo') expect(fn2).toBeCalledTimes(2) }) test('disposables can be collected for listener maps', () => { let ee = new EE<A>() let list: Array<{ dispose(): void }> = [] let foo = jest.fn() ee.on({ foo }, list) ee.emit('foo') // Dispose the listener. list[0].dispose() ee.emit('foo') expect(foo).toBeCalledTimes(1) }) /** * Loose event names */ test('loose event names', () => { interface B { [type: string]: () => number } let ee = new EE<B>() let result: number | void = ee.emit('whatever') expect(result).toBe(undefined) }) /** * Static functions */ describe('has(ee, "*")', () => { it('returns true if "ee" has any listeners', () => { let ee = new EE<A>() expect(EE.has(ee, '*')).toBeFalsy() let foo = ee.on('foo', () => {}) expect(EE.has(ee, '*')).toBeTruthy() ee.off('foo', foo) expect(EE.has(ee, '*')).toBeFalsy() ee.on('bar', () => {}) expect(EE.has(ee, '*')).toBeTruthy() }) }) describe('has(ee, key)', () => { it('returns true if "ee" has any listeners for the given event key', () => { let ee = new EE<A>() expect(EE.has(ee, 'foo')).toBeFalsy() expect(EE.has(ee, 'bar')).toBeFalsy() let foo = ee.on('foo', () => {}) expect(EE.has(ee, 'foo')).toBeTruthy() expect(EE.has(ee, 'bar')).toBeFalsy() ee.off('foo', foo) expect(EE.has(ee, 'foo')).toBeFalsy() expect(EE.has(ee, 'bar')).toBeFalsy() ee.on('bar', () => {}) expect(EE.has(ee, 'foo')).toBeFalsy() expect(EE.has(ee, 'bar')).toBeTruthy() }) }) describe('keys(ee)', () => { it('returns an array of event keys that have listeners', () => { let ee = new EE<A>() expect(EE.keys(ee)).toEqual([]) ee.on('foo', () => {}) expect(EE.keys(ee)).toEqual(['foo']) ee.on('bar', () => {}) expect(EE.keys(ee)).toEqual(['foo', 'bar']) }) }) describe('unhandle(ee, key, listener)', () => { it('handles an event when no other listeners exist', () => { let ee = new EE<A>() let foo = jest.fn() EE.unhandle(ee, 'foo', foo) ee.emit('foo') expect(foo).toBeCalledTimes(1) let fn = ee.on('foo', jest.fn()) ee.emit('foo') expect(fn).toBeCalledTimes(1) expect(foo).toBeCalledTimes(1) ee.off('foo', fn) ee.emit('foo') expect(foo).toBeCalledTimes(2) }) }) /** * _onEventHandled && _onEventUnhandled */ class Foo extends EE<A> { handled: jest.Mock unhandled: jest.Mock constructor() { super() this.handled = jest.fn() this.unhandled = jest.fn() } _onEventHandled<T extends keyof A>(type: T): void { this.handled() } _onEventUnhandled<T extends keyof A>(type: T): void { this.unhandled() } } test('on() triggers _onEventHandled()', () => { let ee = new Foo() ee.on('foo', () => {}) expect(ee.handled).toBeCalled() }) test('on({}) triggers _onEventHandled()', () => { let ee = new Foo() ee.on({ foo: () => {}, }) expect(ee.handled).toBeCalled() }) test('one() triggers _onEventHandled()', () => { let ee = new Foo() ee.one('foo', () => {}) expect(ee.handled).toBeCalled() }) test('one({}) triggers _onEventHandled()', () => { let ee = new Foo() ee.one({ foo: () => {}, }) expect(ee.handled).toBeCalled() }) test('off() triggers _onEventUnhandled()', () => { let ee = new Foo() let fn = () => {} // Remove an unknown listener. ee.off('foo', fn) expect(ee.unhandled).not.toBeCalled() // Remove a known listener. ee.on('foo', fn) ee.off('foo', fn) expect(ee.unhandled).toBeCalled() // Remove all known listeners for a specific key. ee.on('foo', fn) ee.off('foo') expect(ee.unhandled).toBeCalledTimes(2) // Remove all known listeners. ee.on('foo', fn) ee.off('*') expect(ee.unhandled).toBeCalledTimes(3) }) test('emit() triggers _onEventUnhandled()', () => { let ee = new Foo() ee.one('foo', () => {}) ee.emit('foo') expect(ee.unhandled).toBeCalled() })
the_stack
import * as events from 'events'; import * as tls from 'tls'; import {ConnectionOptions} from 'tls'; import {ErrorCode, INVALID_ENCODING_MSG_PREFIX, NatsError} from './error'; import {createInbox, extend} from './util'; import {ProtocolHandler} from './protocolhandler'; import { DEFAULT_JITTER, DEFAULT_JITTER_TLS, DEFAULT_MAX_PING_OUT, DEFAULT_MAX_RECONNECT_ATTEMPTS, DEFAULT_PING_INTERVAL, DEFAULT_PRE, DEFAULT_RECONNECT_TIME_WAIT, DEFAULT_URI } from './const' import {next} from 'nuid'; export {ErrorCode, NatsError} /** Version of the ts-nats library */ export const VERSION = require('../package.json').version; /** * @internal */ export interface Base { subject: string; callback: MsgCallback; received: number; timeout?: NodeJS.Timer; max?: number | undefined; draining?: boolean; } /** * @internal */ export function defaultSub(): Sub { return {sid: 0, subject: '', received: 0} as Sub; } /** ServerInfo received from the server */ export interface ServerInfo { tls_required?: boolean; tls_verify?: boolean; connect_urls?: string[]; max_payload: number; client_id: number; proto: number; server_id: string; version: string; echo?: boolean; nonce?: string; nkey?: string; } /** Argument provided to `subscribe` and `unsubscribe` event handlers. */ export interface SubEvent { /** subscription subject */ subject: string; /** subscription id */ sid: number; /** subscription queue name if a queue subscription */ queue?: string; } /** Argument provided to `serversChanged` event handlers. */ export interface ServersChangedEvent { /** Server URLs learned via cluster gossip */ added: string[]; /** Removed server URLs (only added servers are removed). */ deleted: string[]; } /** * @internal */ export interface Sub extends Base { sid: number; queue?: string | null; } /** * @internal */ export interface Req extends Base { token: string; } /** * Message object provided to subscription and requests. */ export interface Msg { /** subject used to publish the message */ subject: string; /** optional reply subject where replies may be sent. */ reply?: string; /** optional payload for the message. Type is controlled by [[NatsConnectionOptions.payload]]. */ data?: any; /** Internal subscription id */ sid: number; /** Number of bytes in the payload */ size: number; } /** * Payload specifies the type of [[Msg.data]] that will be sent and received by the client. * The payload affects all client subscribers and publishers. If using mixed types, either * create multiple connections, or select [[Payload.BINARY]] and perform your own decoding. */ export enum Payload { /** Specifies a string payload. This is default [[NatsConnectionOptions.payload]] setting */ STRING = 'string', /** Specifies payloads are JSON. */ JSON = 'json', /** Specifies payloads are binary (Buffer) */ BINARY = 'binary' } /** Optional callback interface for 'connect' and 'reconnect' events */ export interface ConnectReconnectCallback { (connection: Client, serverURL: string, info: ServerInfo): void } /** Optional callback interface for 'disconnect' and 'reconnecting' events */ export interface ReconnectingDisconnectCallback { (serverURL: string): void } /** Optional callback interface for 'permissionError' events */ export interface PermissionsErrorCallback { (err: NatsError): void } /** Optional callback for 'serversChanged' events */ export interface ServersChangedCallback { (e: ServersChangedEvent): void; } /** Optional callback for 'subscribe' and 'unsubscribe' events */ export interface SubscribeUnsubscribeCallback { (e: SubEvent): void } /** Optional callback for 'yield'events */ export interface YieldCallback { (): void } /** Optional callback argument for [[Client.flush]] */ export interface FlushCallback { (err?: NatsError): void; } /** [[Client.subscribe]] callbacks. First argument will be an error if an error occurred (such as a timeout) or null. Message argument is the received message (which should be treated as debug information when an error is provided). */ export interface MsgCallback { (err: NatsError | null, msg: Msg): void; } /** Signs a challenge from the server with an NKEY, a function matching this interface must be provided when manually signing nonces via the `nonceSigner` connect option. */ export interface NonceSigner { (nonce: string): Buffer; } /** Returns an user JWT - can be specified in `userJWT` connect option as a way of dynamically providing a JWT when required. */ export interface JWTProvider { (): string; } /** Additional options that can be provided to [[Client.subscribe]]. */ export interface SubscriptionOptions { /** Name of the queue group for the subscription */ queue?: string; /** Maximum number of messages expected. When this number of messages is received the subscription auto [[Subscription.unsubscribe]]. */ max?: number; } /** @hidden */ export interface RequestOptions { max?: number; timeout?: number; } export interface NatsConnectionOptions { /** Requires server support 1.2.0+. When set to `true`, the server will not forward messages published by the client * to the client's subscriptions. By default value is ignored unless it is set to `true` explicitly */ noEcho?: boolean; /** Sets the encoding type used when dealing with [[Payload.STRING]] messages. Only node-supported encoding allowed. */ encoding?: BufferEncoding; /** Maximum number of client PINGs that can be outstanding before the connection is considered stale. */ maxPingOut?: number; /** Maximum number of consecutive reconnect attempts before the client closes the connection. Specify `-1` to retry forever. */ maxReconnectAttempts?: number; /** A name for the client. Useful for identifying a client on the server monitoring and logs. */ name?: string; /** When `true` does not randomize the order of servers provided to connect. */ noRandomize?: boolean; /** User password. */ pass?: string; /** Specifies the payload type of the message. See [[Payload]]. Payload determines [[Msg.data]] types and types published. */ payload?: Payload; /** @hidden */ pedantic?: boolean; /** Interval in milliseconds that the client will send PINGs to the server. See [[NatsConnectionOptions.maxPingOut]] */ pingInterval?: number; /** Specifies the port on the localhost to make a connection. */ port?: number; /** Specifies whether the client should attempt reconnects. */ reconnect?: boolean; /** Specifies the interval in milliseconds between reconnect attempts. */ reconnectTimeWait?: number; /** Random number between 0 and specified value to add to reconnectTimeWait */ reconnectJitter?: number; /** Random number between 0 and specified value to add to reconnectTimeWait when TLS options are specified. */ reconnectJitterTLS?: number; /** Specifies a function that determines how long to wait before the next connection attempt if the server has not been connected to. When specified, * this disables `reconnectTimeWait`, `reconnectJitter` and `reconnectJitterTLS`. */ reconnectDelayHandler?: () => number; /** A list of server URLs where the client should attempt a connection. */ servers?: Array<string>; /** If true, or set as a tls.TlsOption object, requires the connection to be secure. Fine grain tls settings, such as certificates can be specified by using a tls.TlsOptions object. */ tls?: boolean | tls.TlsOptions; /** Token to use for authentication. */ token?: string; /** Server URL where the client should attempt a connection */ url?: string; /** NATS username. */ user?: string; /** @hidden */ verbose?: boolean; /** If true, the client will perform reconnect logic if it fails to connect when first started. Normal behaviour is for the client to try the supplied list of servers and close if none succeed. */ waitOnFirstConnect?: boolean; /** Specifies the max amount of time the client is allowed to process inbound messages before yielding for other IO tasks. When exceeded the client will yield. */ yieldTime?: number; /** Nonce signer - a function that signs the nonce challenge sent by the server. */ nonceSigner?: NonceSigner; /** Public NKey Identifying the user. */ nkey?: string; /** A JWT identifying the user. Can be a static JWT string, or a function that returns a JWT when called. */ userJWT?: string | JWTProvider; /** Credentials file path - will automatically setup an `nkey` and `nonceSigner` that references the specified credentials file.*/ userCreds?: string; /** nkey file path - will automatically setup an `nkey` and `nonceSigner` that references the specified nkey seed file.*/ nkeyCreds?: string; /** number of milliseconds when making a connection to wait for the connection to succeed. Must be greater than zero. */ timeout?:number } /** @internal */ function defaultReq(): Req { return {token: '', subject: '', received: 0, max: 1} as Req; } /** * NATS server Client object. */ export class Client extends events.EventEmitter { /** Returns an unique and properly formatted inbox subject that can be used for replies */ createInbox = createInbox; private protocolHandler!: ProtocolHandler; /** @internal */ constructor() { super(); events.EventEmitter.call(this); // this.addDebugHandlers() } // private addDebugHandlers() { // let events = [ // 'close', // 'connect', // 'connecting', // 'disconnect', // 'error', // 'permissionError', // 'pingcount', // 'pingtimer', // 'reconnect', // 'reconnecting', // 'serversChanged', // 'subscribe', // 'unsubscribe', // 'yield', // ]; // // function handler(name: string) { // return function(arg: any) { // console.log('debughdlr', name, [arg]); // } // } // // events.forEach((e) => { // this.on(e, handler(e)); // }); // } /** @internal */ static connect(opts?: NatsConnectionOptions | string | number): Promise<Client> { return new Promise((resolve, reject) => { let options = Client.parseOptions(opts); let client = new Client(); ProtocolHandler.connect(client, options) .then((ph) => { client.protocolHandler = ph; resolve(client); }).catch((ex) => { reject(ex); }); }); } /** * @internal */ private static defaultOptions(): ConnectionOptions { return { encoding: 'utf8', maxPingOut: DEFAULT_MAX_PING_OUT, maxReconnectAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS, noRandomize: false, pedantic: false, pingInterval: DEFAULT_PING_INTERVAL, reconnect: true, reconnectJitter: DEFAULT_JITTER, reconnectJitterTLS: DEFAULT_JITTER_TLS, reconnectTimeWait: DEFAULT_RECONNECT_TIME_WAIT, tls: undefined, verbose: false, waitOnFirstConnect: false } as ConnectionOptions; } /** * @internal */ private static parseOptions(args?: string | number | NatsConnectionOptions): NatsConnectionOptions { if (args === undefined || args === null) { args = {url: DEFAULT_URI} as NatsConnectionOptions; } if (typeof args === 'number') { args = {url: DEFAULT_PRE + args} as NatsConnectionOptions; } else if (typeof args === 'string') { args = {url: args.toString()} as NatsConnectionOptions; } else if (typeof args === 'object') { if (args.port !== undefined) { args.url = DEFAULT_PRE + args.port; } } // override defaults with provided options. // non-standard aliases are not handled // FIXME: may need to add uri and pass // uri, password, urls, NoRandomize, dontRandomize, secure, client let options = extend(Client.defaultOptions(), args); // Authentication - make sure authentication is valid. if (options.user && options.token) { throw NatsError.errorForCode(ErrorCode.BAD_AUTHENTICATION); } // if specified nonceSigner must be a function if (options.nonceSigner && typeof options.nonceSigner !== 'function') { throw NatsError.errorForCode(ErrorCode.NONCE_SIGNER_NOTFUNC); } // Encoding - make sure its valid. let bufEncoding = options.encoding as BufferEncoding; if (!Buffer.isEncoding(bufEncoding)) { throw new NatsError(INVALID_ENCODING_MSG_PREFIX + options.encoding, ErrorCode.INVALID_ENCODING); } if (options.reconnectDelayHandler && typeof options.reconnectDelayHandler !== 'function') { throw NatsError.errorForCode(ErrorCode.RECONNECT_DELAY_NOTFUNC); } else { options.reconnectDelayHandler = () => { let extra = options.tls ? options.reconnectJitterTLS : options.reconnectJitter if (extra) { extra++ extra = Math.floor(Math.random() * extra) } return options.reconnectTimeWait + extra } } return options; } /** * Flush outbound queue to server and call optional callback when server has processed all data. * @param cb is optional, if not provided a Promise is returned. Flush is completed when promise resolves. * @return Promise<void> or void if a callback was provided. */ flush(cb?: FlushCallback): Promise<void> | void { if (cb === undefined) { return new Promise((resolve, reject) => { this.protocolHandler.flush((err) => { if (!err) { resolve(); } else { reject(err); } }); }); } else { this.protocolHandler.flush(cb); } } /** * Publish a message to the given subject, with optional payload and reply subject. * @param subject * @param data optional (can be a string, JSON object, or Buffer. Must match [[NatsConnectionOptions.payload].) * @param reply optional */ publish(subject: string, data: any = undefined, reply: string = ''): void { if (!subject) { throw NatsError.errorForCode(ErrorCode.BAD_SUBJECT); } this.protocolHandler.publish(subject, data, reply); } /** * Subscribe to a given subject. Messages are passed to the provided callback. * @param subject * @param cb * @param opts Optional subscription options * @return Promise<Subscription> */ subscribe(subject: string, cb: MsgCallback, opts: SubscriptionOptions = {}): Promise<Subscription> { return new Promise<Subscription>((resolve, reject) => { if (!subject) { reject(NatsError.errorForCode(ErrorCode.BAD_SUBJECT)); } if (!cb) { reject(new NatsError('subscribe requires a callback', ErrorCode.API_ERROR)); } let s = defaultSub(); extend(s, opts); s.subject = subject; s.callback = cb; resolve(this.protocolHandler.subscribe(s)); }); } /** * Drains all subscriptions. Returns a Promise that when resolved, indicates that all subscriptions have finished, * and the client closed. Note that after calling drain, it is impossible to create new * subscriptions or make any requests. As soon as all messages for the draining subscriptions are processed, * it is also impossible to publish new messages. * A drained connection is closed when the Promise resolves. * @see [[Subscription.drain]] */ drain(): Promise<any> { return this.protocolHandler.drain(); } /** * Publish a request message with an implicit inbox listener as the reply. Message is optional. * This should be treated as a subscription. The subscription is auto-cancelled after the * first reply is received or the timeout in millisecond is reached. * * If a timeout is reached, the promise is rejected. Returns the received message if resolved. * * @param subject * @param timeout * @param data optional (can be a string, JSON object, or Buffer. Must match specified Payload option) * @return Promise<Msg> */ request(subject: string, timeout: number = 1000, data: any = undefined): Promise<Msg> { return new Promise<Msg>((resolve, reject) => { if (this.isClosed()) { reject(NatsError.errorForCode(ErrorCode.CONN_CLOSED)); } if (!subject) { reject(NatsError.errorForCode(ErrorCode.BAD_SUBJECT)); } let r = defaultReq(); let opts = {max: 1} as RequestOptions; extend(r, opts); r.token = next(); let request = this.protocolHandler.request(r); r.timeout = setTimeout(() => { request.cancel(); reject(NatsError.errorForCode(ErrorCode.REQ_TIMEOUT)); }, timeout); r.callback = (error: Error | null, msg?: Msg) => { if (error) { reject(error); } else { resolve(msg); } }; try { this.publish(subject, data, `${this.protocolHandler.muxSubscriptions.baseInbox}${r.token}`); } catch (err) { reject(err); request.cancel(); } }); }; /** * Closes the connection to the NATS server. A closed client cannot be reconnected. */ close(): void { this.protocolHandler.close(); } /** * @return true if the NATS client is closed. */ isClosed(): boolean { return this.protocolHandler.isClosed(); } /** * Report number of subscriptions on this connection. * * @return {Number} */ numSubscriptions(): number { return this.protocolHandler.numSubscriptions(); } } /** * Creates a NATS [[Client]] by connecting to the specified server, port or using the specified [[NatsConnectionOptions]]. * @param opts * @return Promise<Client> */ export function connect(opts?: NatsConnectionOptions | string | number): Promise<Client> { return Client.connect(opts); } /** * Type returned when a subscribe call resolved. Provides methods to manage the subscription. */ export class Subscription { sid: number; private protocol: ProtocolHandler; /** * @hidden */ constructor(sub: Sub, protocol: ProtocolHandler) { this.sid = sub.sid; this.protocol = protocol; } /** * @hidden */ static cancelTimeout(s: Sub | null): void { if (s && s.timeout) { clearTimeout(s.timeout); delete s.timeout; } } /** * Cancels the subscription after the specified number of messages has been received. * If max is not specified, the subscription cancels immediately. A cancelled subscription * will not process messages that are inbound but not yet handled. * @param max * @see [[drain]] */ unsubscribe(max?: number): void { this.protocol.unsubscribe(this.sid, max); } /** * Draining a subscription is similar to unsubscribe but inbound pending messages are * not discarded. When the last in-flight message is processed, the subscription handler * is removed. * @return a Promise that resolves when the draining a subscription completes * @see [[unsubscribe]] */ drain(): Promise<any> { return this.protocol.drainSubscription(this.sid); } /** * Returns true if the subscription has an associated timeout. */ hasTimeout(): boolean { let sub = this.protocol.subscriptions.get(this.sid); return sub !== null && sub.hasOwnProperty('timeout'); } /** * Cancels a timeout associated with the subscription */ cancelTimeout(): void { let sub = this.protocol.subscriptions.get(this.sid); Subscription.cancelTimeout(sub); } /** * Sets a timeout on a subscription. The timeout will fire by calling * the subscription's callback with an error argument if the expected * number of messages (specified via max) has not been received by the * subscription before the timer expires. If max is not specified, * the subscription times out if no messages are received within the timeout * specified. * * Returns `true` if the subscription was found and the timeout was registered. * * @param millis */ setTimeout(millis: number): boolean { let sub = this.protocol.subscriptions.get(this.sid); Subscription.cancelTimeout(sub); if (sub) { sub.timeout = setTimeout(() => { if (sub && sub.callback) { sub.callback(NatsError.errorForCode(ErrorCode.SUB_TIMEOUT), {} as Msg); } this.unsubscribe(); }, millis); return true; } return false; } /** * Returns the number of messages received by the subscription. */ getReceived(): number { let sub = this.protocol.subscriptions.get(this.sid); if (sub) { return sub.received; } return 0; } /** * Returns the number of messages expected by the subscription. * If `0`, the subscription was not found or was auto-cancelled. * If `-1`, the subscription didn't specify a count for expected messages. */ getMax(): number { let sub = this.protocol.subscriptions.get(this.sid); if (!sub) { return 0; } if (sub && sub.max) { return sub.max; } return -1; } /** * @return true if the subscription is not found. */ isCancelled(): boolean { return this.protocol.subscriptions.get(this.sid) === null; } /** * @return true if the subscription is draining. * @see [[drain]] */ isDraining(): boolean { let sub = this.protocol.subscriptions.get(this.sid); if (sub) { return sub.draining === true; } return false; } }
the_stack
import './ndarray-image-visualizer'; import './ndarray-logits-visualizer'; import './model-layer'; // tslint:disable-next-line:max-line-length import {Array1D, Array3D, DataStats, FeedEntry, Graph, InCPUMemoryShuffledInputProviderBuilder, Initializer, InMemoryDataset, MetricReduction, MomentumOptimizer, SGDOptimizer, RMSPropOptimizer, AdagradOptimizer, AdadeltaOptimizer, AdamOptimizer, NDArray, NDArrayMath, NDArrayMathCPU, NDArrayMathGPU, Optimizer, OnesInitializer, Scalar, Session, Tensor, util, VarianceScalingInitializer, xhr_dataset, XhrDataset, XhrDatasetConfig, ZerosInitializer} from 'deeplearn'; import {NDArrayImageVisualizer} from './ndarray-image-visualizer'; import {NDArrayLogitsVisualizer} from './ndarray-logits-visualizer'; import {PolymerElement, PolymerHTMLElement} from './polymer-spec'; import {LayerBuilder, LayerWeightsDict} from './layer_builder'; import {ModelLayer} from './model-layer'; import * as model_builder_util from './model_builder_util'; import {Normalization} from './tensorflow'; import {getRandomInputProvider} from './my_input_provider'; import {MyGraphRunner, MyGraphRunnerEventObserver} from './my_graph_runner'; const DATASETS_CONFIG_JSON = 'model-builder-datasets-config.json'; /** How often to evaluate the model against test data. */ const EVAL_INTERVAL_MS = 1500; /** How often to compute the cost. Downloading the cost stalls the GPU. */ const COST_INTERVAL_MS = 500; /** How many inference examples to show when evaluating accuracy. */ const INFERENCE_EXAMPLE_COUNT = 15; const INFERENCE_IMAGE_SIZE_PX = 100; /** * How often to show inference examples. This should be less often than * EVAL_INTERVAL_MS as we only show inference examples during an eval. */ const INFERENCE_EXAMPLE_INTERVAL_MS = 3000; // Smoothing factor for the examples/s standalone text statistic. const EXAMPLE_SEC_STAT_SMOOTHING_FACTOR = .7; const TRAIN_TEST_RATIO = 5 / 6; const IMAGE_DATA_INDEX = 0; const LABEL_DATA_INDEX = 1; // tslint:disable-next-line:variable-name export let GANPlaygroundPolymer: new () => PolymerHTMLElement = PolymerElement({ is: 'gan-playground', properties: { inputShapeDisplay: String, isValid: Boolean, inferencesPerSec: Number, inferenceDuration: Number, generationsPerSec: Number, generationDuration: Number, examplesTrained: Number, examplesPerSec: Number, totalTimeSec: String, applicationState: Number, modelInitialized: Boolean, showTrainStats: Boolean, datasetDownloaded: Boolean, datasetNames: Array, selectedDatasetName: String, modelNames: Array, genModelNames: Array, discSelectedOptimizerName: String, genSelectedOptimizerName: String, optimizerNames: Array, discLearningRate: Number, genLearningRate: Number, discMomentum: Number, genMomentum: Number, discNeedMomentum: Boolean, genNeedMomentum: Boolean, discGamma: Number, genGamma: Number, discBeta1: Number, genBeta1: Number, discBeta2: Number, genBeta2: Number, discNeedGamma: Boolean, genNeedGamma: Boolean, discNeedBeta: Boolean, genNeedBeta: Boolean, batchSize: Number, selectedModelName: String, genSelectedModelName: String, selectedNormalizationOption: {type: Number, value: Normalization.NORMALIZATION_NEGATIVE_ONE_TO_ONE}, // Stats showDatasetStats: Boolean, statsInputMin: Number, statsInputMax: Number, statsInputShapeDisplay: String, statsLabelShapeDisplay: String, statsExampleCount: Number, } }); export enum ApplicationState { IDLE = 1, TRAINING = 2 } export class GANPlayground extends GANPlaygroundPolymer { // Polymer properties. private isValid: boolean; private totalTimeSec: string; private applicationState: ApplicationState; private modelInitialized: boolean; private showTrainStats: boolean; private selectedNormalizationOption: number; // Datasets and models. private graphRunner: MyGraphRunner; private graph: Graph; private session: Session; private discOptimizer: Optimizer; private genOptimizer: Optimizer; private xTensor: Tensor; private labelTensor: Tensor; private costTensor: Tensor; private accuracyTensor: Tensor; private predictionTensor: Tensor; private discPredictionReal: Tensor; private discPredictionFake: Tensor; private discLoss: Tensor; private genLoss: Tensor; private generatedImage: Tensor; private datasetDownloaded: boolean; private datasetNames: string[]; private selectedDatasetName: string; private modelNames: string[]; private genModelNames: string[]; private selectedModelName: string; private genSelectedModelName: string; private optimizerNames: string[]; private discSelectedOptimizerName: string; private genSelectedOptimizerName: string; private loadedWeights: LayerWeightsDict[]|null; private dataSets: {[datasetName: string]: InMemoryDataset}; private dataSet: InMemoryDataset; private xhrDatasetConfigs: {[datasetName: string]: XhrDatasetConfig}; private datasetStats: DataStats[]; private discLearningRate: number; private genLearningRate: number; private discMomentum: number; private genMomentum: number; private discNeedMomentum: boolean; private genNeedMomentum: boolean; private discGamma: number; private genGamma: number; private discBeta1: number; private discBeta2: number; private genBeta1: number; private genBeta2: number; private discNeedGamma: boolean; private genNeedGamma: boolean; private discNeedBeta: boolean; private genNeedBeta: boolean private batchSize: number; // Stats. private showDatasetStats: boolean; private statsInputRange: string; private statsInputShapeDisplay: string; private statsLabelShapeDisplay: string; private statsExampleCount: number; // Charts. private costChart: Chart; private accuracyChart: Chart; private examplesPerSecChart: Chart; private costChartData: ChartPoint[]; private accuracyChartData: ChartPoint[]; private examplesPerSecChartData: ChartPoint[]; private trainButton: HTMLButtonElement; // Visualizers. private inputNDArrayVisualizers: NDArrayImageVisualizer[]; private outputNDArrayVisualizers: NDArrayLogitsVisualizer[]; private inputShape: number[]; private labelShape: number[]; private randVectorShape: number[]; private examplesPerSec: number; private examplesTrained: number; private inferencesPerSec: number; private inferenceDuration: number; private generationsPerSec: number; private generationDuration: number; private inputLayer: ModelLayer; private hiddenLayers: ModelLayer[]; private layersContainer: HTMLDivElement; private math: NDArrayMath; // Keep one instance of each NDArrayMath so we don't create a user-initiated // number of NDArrayMathGPU's. private mathGPU: NDArrayMathGPU; private mathCPU: NDArrayMathCPU; ready() { this.mathGPU = new NDArrayMathGPU(); this.mathCPU = new NDArrayMathCPU(); this.math = this.mathGPU; const eventObserver: MyGraphRunnerEventObserver = { batchesTrainedCallback: (batchesTrained: number) => this.displayBatchesTrained(batchesTrained), discCostCallback: (cost: Scalar) => this.displayCost(cost, 'disc'), genCostCallback: (cost: Scalar) => this.displayCost(cost, 'gen'), metricCallback: (metric: Scalar) => this.displayAccuracy(metric), inferenceExamplesCallback: (inputFeeds: FeedEntry[][], inferenceOutputs: NDArray[][]) => this.displayInferenceExamplesOutput(inputFeeds, inferenceOutputs), // console.log(inputFeeds, inferenceOutputs), inferenceExamplesPerSecCallback: (examplesPerSec: number) => this.displayInferenceExamplesPerSec(examplesPerSec), trainExamplesPerSecCallback: (examplesPerSec: number) => this.displayExamplesPerSec(examplesPerSec), totalTimeCallback: (totalTimeSec: number) => this.totalTimeSec = totalTimeSec.toFixed(1), }; this.graphRunner = new MyGraphRunner(this.math, this.session, eventObserver); // Set up datasets. this.populateDatasets(); // this.createModel(); this.querySelector('#dataset-dropdown .dropdown-content') .addEventListener( // tslint:disable-next-line:no-any 'iron-activate', (event: any) => { // Update the dataset. const datasetName = event.detail.selected; this.updateSelectedDataset(datasetName); // TODO(nsthorat): Remember the last model used for each dataset. this.removeAllLayers('gen'); this.removeAllLayers('disc'); }); this.querySelector('#model-dropdown .dropdown-content') .addEventListener( // tslint:disable-next-line:no-any 'iron-activate', (event: any) => { // Update the model. const modelName = event.detail.selected; this.updateSelectedModel(modelName, 'disc'); }); this.querySelector('#gen-model-dropdown .dropdown-content') .addEventListener( // tslint:disable-next-line:no-any 'iron-activate', (event: any) => { // Update the model. const modelName = event.detail.selected; this.updateSelectedModel(modelName, 'gen'); }); { const normalizationDropdown = this.querySelector('#normalization-dropdown .dropdown-content'); // tslint:disable-next-line:no-any normalizationDropdown.addEventListener('iron-activate', (event: any) => { const selectedNormalizationOption = event.detail.selected; this.applyNormalization(selectedNormalizationOption); this.setupDatasetStats(); }); } this.querySelector("#disc-optimizer-dropdown .dropdown-content") // tslint:disable-next-line:no-any .addEventListener('iron-activate', (event: any) => { // Activate, deactivate hyper parameter inputs. this.refreshHyperParamRequirements(event.detail.selected, 'disc'); }); this.querySelector("#gen-optimizer-dropdown .dropdown-content") // tslint:disable-next-line:no-any .addEventListener('iron-activate', (event: any) => { // Activate, deactivate hyper parameter inputs. this.refreshHyperParamRequirements(event.detail.selected, 'gen'); }); this.discLearningRate = 0.01; this.genLearningRate = 0.01; this.discMomentum = 0.1; this.genMomentum = 0.1; this.discNeedMomentum = false; this.genNeedMomentum = false; this.discGamma = 0.1; this.genGamma = 0.1; this.discBeta1 = 0.9; this.discBeta2 = 0.999; this.genBeta1 = 0.9; this.genBeta2 = 0.999; this.discNeedGamma = false; this.genNeedGamma = false; this.discNeedBeta = false; this.genNeedBeta = true; this.batchSize = 15; // Default optimizer is momentum this.discSelectedOptimizerName = "sgd"; this.genSelectedOptimizerName = "adam"; this.optimizerNames = ["sgd", "momentum", "rmsprop", "adagrad", "adadelta", "adam"]; this.applicationState = ApplicationState.IDLE; this.loadedWeights = null; this.modelInitialized = false; this.showTrainStats = false; this.showDatasetStats = false; const addButton = this.querySelector('#add-layer'); addButton.addEventListener('click', () => this.addLayer('disc')); const genAddButton = this.querySelector('#gen-add-layer'); genAddButton.addEventListener('click', () => this.addLayer('gen')); /* const downloadModelButton = this.querySelector('#download-model'); downloadModelButton.addEventListener('click', () => this.downloadModel()); const uploadModelButton = this.querySelector('#upload-model'); uploadModelButton.addEventListener('click', () => this.uploadModel()); this.setupUploadModelButton(); const uploadWeightsButton = this.querySelector('#upload-weights'); uploadWeightsButton.addEventListener('click', () => this.uploadWeights()); this.setupUploadWeightsButton(); */ const stopButton = this.querySelector('#stop'); stopButton.addEventListener('click', () => { this.applicationState = ApplicationState.IDLE; this.graphRunner.stopTraining(); }); this.trainButton = this.querySelector('#train') as HTMLButtonElement; this.trainButton.addEventListener('click', () => { this.createModel(); this.startTraining(); }); this.querySelector('#environment-toggle') .addEventListener('change', (event) => { this.math = // tslint:disable-next-line:no-any (event.target as any).active ? this.mathGPU : this.mathCPU; this.graphRunner.setMath(this.math); }); this.discHiddenLayers = []; this.genHiddenLayers = []; this.examplesPerSec = 0; this.inferencesPerSec = 0; this.generationsPerSec = 0; this.randVectorShape = [100]; } isTraining(applicationState: ApplicationState): boolean { return applicationState === ApplicationState.TRAINING; } isIdle(applicationState: ApplicationState): boolean { return applicationState === ApplicationState.IDLE; } private getTestData(): NDArray[][] { const data = this.dataSet.getData(); if (data == null) { return null; } const [images, labels] = this.dataSet.getData() as [NDArray[], NDArray[]]; const start = Math.floor(TRAIN_TEST_RATIO * images.length); return [images.slice(start), labels.slice(start)]; } private getTrainingData(): NDArray[][] { const [images, labels] = this.dataSet.getData() as [NDArray[], NDArray[]]; const end = Math.floor(TRAIN_TEST_RATIO * images.length); return [images.slice(0, end), labels.slice(0, end)]; } private getData(): NDArray[][] { return this.dataSet.getData() as [NDArray[], NDArray[]]; } private getImageDataOnly(): NDArray[] { const [images, labels] = this.dataSet.getData() as [NDArray[], NDArray[]]; return images } private startInference() { const data = this.getImageDataOnly(); if(data == null) { return; } if (this.isValid && (data != null)) { const shuffledInputProviderGenerator = new InCPUMemoryShuffledInputProviderBuilder([data]); const [inputImageProvider] = shuffledInputProviderGenerator.getInputProviders(); const oneInputProvider = { getNextCopy(math: NDArrayMath): NDArray { return Array1D.new([0, 1]); }, disposeCopy(math: NDArrayMath, copy: NDArray) { copy.dispose(); } } const zeroInputProvider = { getNextCopy(math: NDArrayMath): NDArray { return Array1D.new([1, 0]); }, disposeCopy(math: NDArrayMath, copy: NDArray) { copy.dispose(); } } const inferenceFeeds = [ {tensor: this.xTensor, data: inputImageProvider}, {tensor: this.randomTensor, data: getRandomInputProvider(this.randVectorShape)}, {tensor: this.oneTensor, data: oneInputProvider}, {tensor: this.zeroTensor, data: zeroInputProvider} ] this.graphRunner.infer( this.generatedImage, this.discPredictionFake, this.discPredictionReal, inferenceFeeds, INFERENCE_EXAMPLE_INTERVAL_MS, INFERENCE_EXAMPLE_COUNT ); } } private resetHyperParamRequirements(which: string) { if (which === 'gen') { this.genNeedMomentum = false; this.genNeedGamma = false; this.genNeedBeta = false; } else { this.discNeedMomentum = false; this.discNeedGamma = false; this.discNeedBeta = false; } } /** * Set flag to disable input by optimizer selection. */ private refreshHyperParamRequirements(optimizerName: string, which: string) { this.resetHyperParamRequirements(which); switch (optimizerName) { case "sgd": { // No additional hyper parameters break; } case "momentum": { if (which === 'gen') { this.genNeedMomentum = true; } else { this.discNeedMomentum = true; } break; } case "rmsprop": { if (which === 'gen') { this.genNeedMomentum = true; this.genNeedGamma = true; } else { this.discNeedMomentum = true; this.discNeedGamma = true; } break; } case "adagrad": { break; } case 'adadelta': { if (which === 'gen') { this.genNeedGamma = true; } else { this.discNeedGamma = true; } break; } case 'adam': { if (which === 'gen') { this.genNeedBeta = true; } else { this.discNeedBeta = true; } break; } default: { throw new Error(`Unknown optimizer`); } } } private createOptimizer(which: string) { if (which === 'gen') { var selectedOptimizerName = this.genSelectedOptimizerName; var learningRate = this.genLearningRate; var momentum = this.genMomentum; var gamma = this.genGamma; var beta1 = this.genBeta1; var beta2 = this.genBeta2; var varName = 'generator'; } else { var selectedOptimizerName = this.discSelectedOptimizerName; var learningRate = this.discLearningRate; var momentum = this.discMomentum; var gamma = this.discGamma; var beta1 = this.discBeta1; var beta2 = this.discBeta2; var varName = 'discriminator'; } switch (selectedOptimizerName) { case 'sgd': { return new SGDOptimizer(+learningRate, this.graph.getNodes().filter((x) => x.name.startsWith(varName))); } case 'momentum': { return new MomentumOptimizer(+learningRate, +momentum, this.graph.getNodes().filter((x) => x.name.startsWith(varName))); } case 'rmsprop': { return new RMSPropOptimizer(+learningRate, +gamma, this.graph.getNodes().filter((x) => x.name.startsWith(varName))); } case 'adagrad': { return new AdagradOptimizer(+learningRate, this.graph.getNodes().filter((x) => x.name.startsWith(varName))); } case 'adadelta': { return new AdadeltaOptimizer(+learningRate, +gamma, this.graph.getNodes().filter((x) => x.name.startsWith(varName))); } case 'adam': { return new AdamOptimizer(+learningRate, +beta1, +beta2, this.graph.getNodes().filter((x) => x.name.startsWith(varName))); } default: { throw new Error(`Unknown optimizer`); } } } private startTraining() { const data = this.getImageDataOnly(); // Recreate optimizer with the selected optimizer and hyperparameters. this.discOptimizer = this.createOptimizer('disc'); this.genOptimizer = this.createOptimizer('gen'); if (this.isValid && data != null) { this.recreateCharts(); this.graphRunner.resetStatistics(); const shuffledInputProviderGenerator = new InCPUMemoryShuffledInputProviderBuilder([data]); const [inputImageProvider] = shuffledInputProviderGenerator.getInputProviders(); const oneInputProvider = { getNextCopy(math: NDArrayMath): NDArray { return Array1D.new([0, 1]); }, disposeCopy(math: NDArrayMath, copy: NDArray) { copy.dispose(); } } const zeroInputProvider = { getNextCopy(math: NDArrayMath): NDArray { return Array1D.new([1, 0]); }, disposeCopy(math: NDArrayMath, copy: NDArray) { copy.dispose(); } } const discFeeds = [ {tensor: this.xTensor, data: inputImageProvider}, {tensor: this.randomTensor, data: getRandomInputProvider(this.randVectorShape)}, {tensor: this.oneTensor, data: oneInputProvider}, {tensor: this.zeroTensor, data: zeroInputProvider} ] const genFeeds = [ {tensor: this.randomTensor, data: getRandomInputProvider(this.randVectorShape)}, {tensor: this.oneTensor, data: oneInputProvider}, {tensor: this.zeroTensor, data: zeroInputProvider} ] this.graphRunner.train( this.discLoss, this.genLoss, discFeeds, genFeeds, this.batchSize, this.discOptimizer, this.genOptimizer, undefined, COST_INTERVAL_MS); this.showTrainStats = true; this.applicationState = ApplicationState.TRAINING; } } private createModel() { if (this.session != null) { this.session.dispose(); } this.modelInitialized = false; if (this.isValid === false) { return; } // Construct graph this.graph = new Graph(); const g = this.graph; this.randomTensor = g.placeholder('random', this.randVectorShape); this.xTensor = g.placeholder('input', this.inputShape); this.oneTensor = g.placeholder('one', [2]); this.zeroTensor = g.placeholder('zero', [2]); const varianceInitializer: Initializer = new VarianceScalingInitializer() const zerosInitializer: Initializer = new ZerosInitializer() const onesInitializer: Initializer = new OnesInitializer(); // Construct generator let gen = this.randomTensor; for (let i = 0; i < this.genHiddenLayers.length; i++) { let weights: LayerWeightsDict|null = null; if (this.loadedWeights != null) { weights = this.loadedWeights[i]; } [gen] = this.genHiddenLayers[i].addLayerMultiple(g, [gen], 'generator', weights); } gen = g.tanh(gen); // Construct discriminator let disc1 = gen; let disc2 = this.xTensor; for (let i = 0; i < this.discHiddenLayers.length; i++) { let weights: LayerWeightsDict|null = null; if (this.loadedWeights != null) { weights = this.loadedWeights[i]; } [disc1, disc2] = this.discHiddenLayers[i].addLayerMultiple(g, [disc1, disc2], 'discriminator', weights); } this.discPredictionReal = disc2; this.discPredictionFake = disc1; this.generatedImage = gen; const discLossReal = g.softmaxCrossEntropyCost( this.discPredictionReal, this.oneTensor ); const discLossFake = g.softmaxCrossEntropyCost( this.discPredictionFake, this.zeroTensor ); this.discLoss = g.add(discLossReal, discLossFake); this.genLoss = g.softmaxCrossEntropyCost( this.discPredictionFake, this.oneTensor ); this.session = new Session(g, this.math); this.graphRunner.setSession(this.session); this.startInference(); this.modelInitialized = true; } private populateDatasets() { this.dataSets = {}; xhr_dataset.getXhrDatasetConfig(DATASETS_CONFIG_JSON) .then( xhrDatasetConfigs => { for (const datasetName in xhrDatasetConfigs) { if (xhrDatasetConfigs.hasOwnProperty(datasetName)) { this.dataSets[datasetName] = new XhrDataset(xhrDatasetConfigs[datasetName]); } } this.datasetNames = Object.keys(this.dataSets); this.selectedDatasetName = this.datasetNames[0]; this.xhrDatasetConfigs = xhrDatasetConfigs; this.updateSelectedDataset(this.datasetNames[0]); }, error => { throw new Error('Dataset config could not be loaded: ' + error); }); } private updateSelectedDataset(datasetName: string) { if (this.dataSet != null) { this.dataSet.removeNormalization(IMAGE_DATA_INDEX); } this.graphRunner.stopTraining(); this.graphRunner.stopInferring(); if (this.dataSet != null) { this.dataSet.dispose(); } this.selectedDatasetName = datasetName; this.selectedModelName = ''; this.dataSet = this.dataSets[datasetName]; this.datasetDownloaded = false; this.showDatasetStats = false; this.dataSet.fetchData().then(() => { this.datasetDownloaded = true; this.applyNormalization(this.selectedNormalizationOption); this.setupDatasetStats(); if (this.isValid) { this.createModel(); } // Get prebuilt models. this.populateModelDropdown(); }); this.inputShape = this.dataSet.getDataShape(IMAGE_DATA_INDEX); //this.labelShape = this.dataSet.getDataShape(LABEL_DATA_INDEX); this.labelShape = [2]; this.layersContainer = this.querySelector('#hidden-layers') as HTMLDivElement; this.genLayersContainer = this.querySelector('#gen-hidden-layers') as HTMLDivElement; this.inputLayer = this.querySelector('#input-layer') as ModelLayer; this.inputLayer.outputShapeDisplay = model_builder_util.getDisplayShape(this.inputShape); this.genInputLayer = this.querySelector('#gen-input-layer') as ModelLayer; this.genInputLayer.outputShapeDisplay = model_builder_util.getDisplayShape(this.randVectorShape); const labelShapeDisplay = model_builder_util.getDisplayShape(this.labelShape); const costLayer = this.querySelector('#cost-layer') as ModelLayer; costLayer.inputShapeDisplay = labelShapeDisplay; costLayer.outputShapeDisplay = labelShapeDisplay; const genCostLayer = this.querySelector('#gen-cost-layer') as ModelLayer; genCostLayer.inputShapeDisplay = model_builder_util.getDisplayShape(this.inputShape); genCostLayer.outputShapeDisplay = model_builder_util.getDisplayShape(this.inputShape); const outputLayer = this.querySelector('#output-layer') as ModelLayer; outputLayer.inputShapeDisplay = labelShapeDisplay; const genOutputLayer = this.querySelector('#gen-output-layer') as ModelLayer; genOutputLayer.inputShapeDisplay = model_builder_util.getDisplayShape(this.inputShape); this.buildRealImageContainer(); this.buildFakeImageContainer(); } /* Helper function for building out container for images*/ private buildRealImageContainer() { const inferenceContainer = this.querySelector('#real-container') as HTMLElement; inferenceContainer.innerHTML = ''; this.inputNDArrayVisualizers = []; this.outputNDArrayVisualizers = []; for (let i = 0; i < INFERENCE_EXAMPLE_COUNT; i++) { const inferenceExampleElement = document.createElement('div'); inferenceExampleElement.className = 'inference-example'; // Set up the input visualizer. const ndarrayImageVisualizer = document.createElement('ndarray-image-visualizer') as NDArrayImageVisualizer; ndarrayImageVisualizer.setShape(this.inputShape); ndarrayImageVisualizer.setSize( INFERENCE_IMAGE_SIZE_PX, INFERENCE_IMAGE_SIZE_PX); this.inputNDArrayVisualizers.push(ndarrayImageVisualizer); inferenceExampleElement.appendChild(ndarrayImageVisualizer); // Set up the output ndarray visualizer. const ndarrayLogitsVisualizer = document.createElement('ndarray-logits-visualizer') as NDArrayLogitsVisualizer; ndarrayLogitsVisualizer.initialize( INFERENCE_IMAGE_SIZE_PX, INFERENCE_IMAGE_SIZE_PX); this.outputNDArrayVisualizers.push(ndarrayLogitsVisualizer); inferenceExampleElement.appendChild(ndarrayLogitsVisualizer); inferenceContainer.appendChild(inferenceExampleElement); } } private buildFakeImageContainer() { const inferenceContainer = this.querySelector('#generated-container') as HTMLElement; inferenceContainer.innerHTML = ''; this.fakeInputNDArrayVisualizers = []; this.fakeOutputNDArrayVisualizers = []; for (let i = 0; i < INFERENCE_EXAMPLE_COUNT; i++) { const inferenceExampleElement = document.createElement('div'); inferenceExampleElement.className = 'inference-example'; // Set up the input visualizer. const ndarrayImageVisualizer = document.createElement('ndarray-image-visualizer') as NDArrayImageVisualizer; ndarrayImageVisualizer.setShape(this.inputShape); ndarrayImageVisualizer.setSize( INFERENCE_IMAGE_SIZE_PX, INFERENCE_IMAGE_SIZE_PX); this.fakeInputNDArrayVisualizers.push(ndarrayImageVisualizer); inferenceExampleElement.appendChild(ndarrayImageVisualizer); // Set up the output ndarray visualizer. const ndarrayLogitsVisualizer = document.createElement('ndarray-logits-visualizer') as NDArrayLogitsVisualizer; ndarrayLogitsVisualizer.initialize( INFERENCE_IMAGE_SIZE_PX, INFERENCE_IMAGE_SIZE_PX); this.fakeOutputNDArrayVisualizers.push(ndarrayLogitsVisualizer); inferenceExampleElement.appendChild(ndarrayLogitsVisualizer); inferenceContainer.appendChild(inferenceExampleElement); } } private populateModelDropdown() { const modelNames = ['Custom']; const genModelNames = ['Custom']; const modelConfigs = this.xhrDatasetConfigs[this.selectedDatasetName].modelConfigs; for (const modelName in modelConfigs) { if (modelConfigs.hasOwnProperty(modelName)) { if (modelName.endsWith('(disc)')) { modelNames.push(modelName); } else { genModelNames.push(modelName); } } } this.modelNames = modelNames; this.genModelNames = genModelNames; this.selectedModelName = modelNames[modelNames.length - 1]; this.genSelectedModelName = genModelNames[genModelNames.length - 1]; this.updateSelectedModel(this.selectedModelName, 'disc'); this.updateSelectedModel(this.genSelectedModelName, 'gen'); } private updateSelectedModel(modelName: string, which: string) { this.removeAllLayers(which); if (modelName === 'Custom') { // TODO(nsthorat): Remember the custom layers. return; } this.loadModelFromPath(this.xhrDatasetConfigs[this.selectedDatasetName] .modelConfigs[modelName] .path, which); } private loadModelFromPath(modelPath: string, which: string) { const xhr = new XMLHttpRequest(); xhr.open('GET', modelPath); xhr.onload = () => { this.loadModelFromJson(xhr.responseText, which); }; xhr.onerror = (error) => { throw new Error( 'Model could not be fetched from ' + modelPath + ': ' + error); }; xhr.send(); } private setupDatasetStats() { this.datasetStats = this.dataSet.getStats(); this.statsExampleCount = this.datasetStats[IMAGE_DATA_INDEX].exampleCount; this.statsInputRange = '[' + this.datasetStats[IMAGE_DATA_INDEX].inputMin + ', ' + this.datasetStats[IMAGE_DATA_INDEX].inputMax + ']'; this.statsInputShapeDisplay = model_builder_util.getDisplayShape( this.datasetStats[IMAGE_DATA_INDEX].shape); this.statsLabelShapeDisplay = model_builder_util.getDisplayShape( this.datasetStats[LABEL_DATA_INDEX].shape); this.showDatasetStats = true; } private applyNormalization(selectedNormalizationOption: number) { switch (selectedNormalizationOption) { case Normalization.NORMALIZATION_NEGATIVE_ONE_TO_ONE: { this.dataSet.normalizeWithinBounds(IMAGE_DATA_INDEX, -1, 1); break; } case Normalization.NORMALIZATION_ZERO_TO_ONE: { this.dataSet.normalizeWithinBounds(IMAGE_DATA_INDEX, 0, 1); break; } case Normalization.NORMALIZATION_NONE: { this.dataSet.removeNormalization(IMAGE_DATA_INDEX); break; } default: { throw new Error('Normalization option must be 0, 1, or 2'); } } this.setupDatasetStats(); } private recreateCharts() { this.costChartData = []; if (this.costChart != null) { this.costChart.destroy(); } this.costChart = this.createChart('cost-chart', 'Discriminator Cost', this.costChartData, 0); if (this.accuracyChart != null) { this.accuracyChart.destroy(); } this.accuracyChartData = []; this.accuracyChart = this.createChart( 'accuracy-chart', 'Generator Cost', this.accuracyChartData, 0); if (this.examplesPerSecChart != null) { this.examplesPerSecChart.destroy(); } this.examplesPerSecChartData = []; this.examplesPerSecChart = this.createChart( 'examplespersec-chart', 'Examples/sec', this.examplesPerSecChartData, 0); } private createChart( canvasId: string, label: string, data: ChartData[], min?: number, max?: number): Chart { const context = (document.getElementById(canvasId) as HTMLCanvasElement) .getContext('2d') as CanvasRenderingContext2D; return new Chart(context, { type: 'line', data: { datasets: [{ data, fill: false, label, pointRadius: 0, borderColor: 'rgba(75,192,192,1)', borderWidth: 1, lineTension: 0, pointHitRadius: 8 }] }, options: { animation: {duration: 0}, responsive: false, scales: { xAxes: [{type: 'linear', position: 'bottom'}], yAxes: [{ ticks: { max, min, } }] } } }); } displayBatchesTrained(totalBatchesTrained: number) { this.examplesTrained = this.batchSize * totalBatchesTrained; } displayCost(cost: Scalar, which: String) { if (which === 'disc') { this.costChartData.push( {x: this.graphRunner.getTotalBatchesTrained(), y: cost.get()}); this.costChart.update(); } else { this.accuracyChartData.push( {x: this.graphRunner.getTotalBatchesTrained(), y: cost.get()}); this.accuracyChart.update(); } } displayAccuracy(accuracy: Scalar) { this.accuracyChartData.push({ x: this.graphRunner.getTotalBatchesTrained(), y: accuracy.get() * 100 }); this.accuracyChart.update(); } displayInferenceExamplesPerSec(examplesPerSec: number) { this.inferencesPerSec = this.smoothExamplesPerSec(this.inferencesPerSec, examplesPerSec); this.inferenceDuration = Number((1000 / examplesPerSec).toPrecision(3)); this.generationsPerSec = this.inferencesPerSec; this.generationDuration = this.inferenceDuration; } displayExamplesPerSec(examplesPerSec: number) { this.examplesPerSecChartData.push( {x: this.graphRunner.getTotalBatchesTrained(), y: examplesPerSec}); this.examplesPerSecChart.update(); this.examplesPerSec = this.smoothExamplesPerSec(this.examplesPerSec, examplesPerSec); } private smoothExamplesPerSec( lastExamplesPerSec: number, nextExamplesPerSec: number): number { return Number((EXAMPLE_SEC_STAT_SMOOTHING_FACTOR * lastExamplesPerSec + (1 - EXAMPLE_SEC_STAT_SMOOTHING_FACTOR) * nextExamplesPerSec) .toPrecision(3)); } displayInferenceExamplesOutput( inputFeeds: FeedEntry[][], inferenceOutputs: NDArray[][]) { let realImages: Array3D[] = []; const realLabels: Array1D[] = []; const realLogits: Array1D[] = []; let fakeImages: Array3D[] = [] const fakeLabels: Array1D[] = []; const fakeLogits: Array1D[] = []; for (let i = 0; i < inputFeeds.length; i++) { realImages.push(inputFeeds[i][0].data as Array3D); realLabels.push(inputFeeds[i][2].data as Array1D); realLogits.push(inferenceOutputs[2][i] as Array1D); fakeImages.push((inferenceOutputs[0][i] as Array3D)); fakeLabels.push(inputFeeds[i][3].data as Array1D); fakeLogits.push(inferenceOutputs[1][i] as Array1D); } realImages = this.dataSet.unnormalizeExamples(realImages, IMAGE_DATA_INDEX) as Array3D[]; fakeImages = this.dataSet.unnormalizeExamples(fakeImages, IMAGE_DATA_INDEX) as Array3D[]; // Draw the images. for (let i = 0; i < inputFeeds.length; i++) { this.inputNDArrayVisualizers[i].saveImageDataFromNDArray(realImages[i]); this.fakeInputNDArrayVisualizers[i].saveImageDataFromNDArray(fakeImages[i]); } // Draw the logits. for (let i = 0; i < inputFeeds.length; i++) { const realSoftmaxLogits = this.math.softmax(realLogits[i]); const fakeSoftmaxLogits = this.math.softmax(fakeLogits[i]); this.outputNDArrayVisualizers[i].drawLogits( realSoftmaxLogits, realLabels[i]); this.fakeOutputNDArrayVisualizers[i].drawLogits( fakeSoftmaxLogits, fakeLabels[i]); this.inputNDArrayVisualizers[i].draw(); this.fakeInputNDArrayVisualizers[i].draw(); realSoftmaxLogits.dispose(); fakeSoftmaxLogits.dispose(); } } addLayer(which: string): ModelLayer { var layersContainer: HTMLDivElement; var hiddenLayers: ModelLayer[]; var inputShape: number[]; if (which === 'gen') { layersContainer = this.genLayersContainer; hiddenLayers = this.genHiddenLayers; inputShape = this.randVectorShape; } else { layersContainer = this.layersContainer; hiddenLayers = this.discHiddenLayers; inputShape = this.inputShape; } const modelLayer = document.createElement('model-layer') as ModelLayer; modelLayer.className = 'layer'; layersContainer.appendChild(modelLayer); const lastHiddenLayer = hiddenLayers[hiddenLayers.length - 1]; const lastOutputShape = lastHiddenLayer != null ? lastHiddenLayer.getOutputShape() : inputShape; hiddenLayers.push(modelLayer); modelLayer.initialize(this, lastOutputShape, which); return modelLayer; } removeLayer(modelLayer: ModelLayer, which: string) { if (which === 'gen') { this.genLayersContainer.removeChild(modelLayer); this.genHiddenLayers.splice(this.genHiddenLayers.indexOf(modelLayer), 1); } else { this.layersContainer.removeChild(modelLayer); this.discHiddenLayers.splice(this.discHiddenLayers.indexOf(modelLayer), 1); } this.layerParamChanged(); } private removeAllLayers(which: string) { if (which === 'gen') { for (let i = 0; i < this.genHiddenLayers.length; i++) { this.genLayersContainer.removeChild(this.genHiddenLayers[i]); } this.genHiddenLayers = []; } else { for (let i = 0; i < this.discHiddenLayers.length; i++) { this.layersContainer.removeChild(this.discHiddenLayers[i]); } this.discHiddenLayers = []; } this.layerParamChanged(); } private validateModel() { let valid = true; for (let i = 0; i < this.discHiddenLayers.length; ++i) { valid = valid && this.discHiddenLayers[i].isValid(); } if (this.discHiddenLayers.length > 0) { const lastLayer = this.discHiddenLayers[this.discHiddenLayers.length - 1]; valid = valid && util.arraysEqual(this.labelShape, lastLayer.getOutputShape()); } valid = valid && (this.discHiddenLayers.length > 0); for (let i = 0; i < this.genHiddenLayers.length; ++i) { valid = valid && this.genHiddenLayers[i].isValid(); } if (this.genHiddenLayers.length > 0) { const lastLayer = this.genHiddenLayers[this.genHiddenLayers.length - 1]; valid = valid && util.arraysEqual(this.inputShape, lastLayer.getOutputShape()); } valid = valid && (this.genHiddenLayers.length > 0); this.isValid = valid; } layerParamChanged() { // Go through each of the model layers and propagate shapes. let lastOutputShape = this.inputShape; for (let i = 0; i < this.discHiddenLayers.length; i++) { lastOutputShape = this.discHiddenLayers[i].setInputShape(lastOutputShape); } lastOutputShape = this.randVectorShape; for (let i = 0; i < this.genHiddenLayers.length; i++) { lastOutputShape = this.genHiddenLayers[i].setInputShape(lastOutputShape); } this.validateModel(); if (this.isValid) { this.createModel(); } } private downloadModel() { const modelJson = this.getModelAsJson(); const blob = new Blob([modelJson], {type: 'text/json'}); const textFile = window.URL.createObjectURL(blob); // Force a download. const a = document.createElement('a'); document.body.appendChild(a); a.style.display = 'none'; a.href = textFile; // tslint:disable-next-line:no-any (a as any).download = this.selectedDatasetName + '_model'; a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(textFile); } private uploadModel() { (this.querySelector('#model-file') as HTMLInputElement).click(); } private setupUploadModelButton() { // Show and setup the load view button. const fileInput = this.querySelector('#model-file') as HTMLInputElement; fileInput.addEventListener('change', event => { const file = fileInput.files[0]; // Clear out the value of the file chooser. This ensures that if the user // selects the same file, we'll re-read it. fileInput.value = ''; const fileReader = new FileReader(); fileReader.onload = (evt) => { this.removeAllLayers('disc'); const modelJson: string = fileReader.result; this.loadModelFromJson(modelJson, 'disc'); }; fileReader.readAsText(file); }); } private getModelAsJson(): string { const layerBuilders: LayerBuilder[] = []; for (let i = 0; i < this.discHiddenLayers.length; i++) { layerBuilders.push(this.discHiddenLayers[i].layerBuilder); } return JSON.stringify(layerBuilders); } private loadModelFromJson(modelJson: string, which: string) { var lastOutputShape: number[]; var hiddenLayers: ModelLayer[]; if (which === 'disc') { lastOutputShape = this.inputShape; hiddenLayers = this.discHiddenLayers; } else { lastOutputShape = this.randVectorShape; hiddenLayers = this.genHiddenLayers; } const layerBuilders = JSON.parse(modelJson) as LayerBuilder[]; for (let i = 0; i < layerBuilders.length; i++) { const modelLayer = this.addLayer(which); modelLayer.loadParamsFromLayerBuilder(lastOutputShape, layerBuilders[i]); lastOutputShape = hiddenLayers[i].setInputShape(lastOutputShape); } this.validateModel(); } private uploadWeights() { (this.querySelector('#weights-file') as HTMLInputElement).click(); } private setupUploadWeightsButton() { // Show and setup the load view button. const fileInput = this.querySelector('#weights-file') as HTMLInputElement; fileInput.addEventListener('change', event => { const file = fileInput.files[0]; // Clear out the value of the file chooser. This ensures that if the user // selects the same file, we'll re-read it. fileInput.value = ''; const fileReader = new FileReader(); fileReader.onload = (evt) => { const weightsJson: string = fileReader.result; this.loadWeightsFromJson(weightsJson); this.createModel(); }; fileReader.readAsText(file); }); } private loadWeightsFromJson(weightsJson: string) { this.loadedWeights = JSON.parse(weightsJson) as LayerWeightsDict[]; } } document.registerElement(GANPlayground.prototype.is, GANPlayground);
the_stack
import { CommonModule } from '@angular/common'; import { Component, DebugElement } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { DropDownMenuDirective } from './dropdown-menu.directive'; import { DropDownToggleDirective } from './dropdown-toggle.directive'; import { DropDownDirective } from './dropdown.directive'; import { DropDownModule } from './dropdown.moudule'; @Component({ template: ` <div class="height-expand" *ngIf="expand"></div> <div dDropDown [trigger]="trigger" (toggleEvent)="onToggle($event)" [disabled]="disabled" [isOpen]="defaultOpen" [closeScope]="closeScope" [closeOnMouseLeaveMenu] = "closeOnMouseLeaveMenu" #dropdown="d-dropdown"> <a dDropDownToggle class="devui-dropdown-default devui-dropdown-origin"> 更多操作 <span class="icon icon-chevron-down"></span> </a> <ul dDropDownMenu> <li role="menuitem"> <a class="devui-dropdown-item">菜单一</a> </li> <li class="disabled" role="menuitem"> <a class="devui-dropdown-item disabled">菜单二(禁用)</a> </li> <li role="menuitem"> <a class="devui-dropdown-item">菜单三</a> </li> <li role="menuitem"> <a class="devui-dropdown-item">菜单四</a> </li> <li role="menuitem"> <input type="text" class="devui-input devui-input-sm devui-search-in-dropdown" placeholder="输入框" /> <div class="icon-in-search"> <i class="icon icon-search"></i> </div> </li> <li role="menuitem"> <textarea class="devui-input devui-input-sm devui-search-in-dropdown" placeholder="输入框"></textarea> </li> <li role="menuitem"> <a id="close" class="devui-dropdown-item" (click)="dropdown.toggle()">关闭</a> </li> </ul> </div> <div class="toggle" (click)="dropdown.toggle()">打开/关闭</div> `, styles: [` .height-expand { height: calc( 100vh - 100px)} `] }) class TestDropdownComponent { trigger: 'hover'| 'click'| 'manually' = 'click'; count = 0; isOpen: boolean; disabled: boolean; defaultOpen; closeScope; closeOnMouseLeaveMenu; expand = false; onToggle(event) { this.count++; this.isOpen = event; } } @Component({ template: ` <div class="area" #area [ngClass]="{'devui-dropdown-origin': alignOriginFlag}"> <div dDropDown appendToBody [trigger]="trigger" [appendToBodyDirections]="directions" [alignOrigin]="alignOriginFlag ? area : undefined" [closeOnMouseLeaveMenu]="closeOnMouseLeaveMenu"> <a dDropDownToggle class="devui-dropdown-default" [ngClass]="{'devui-dropdown-origin': !alignOriginFlag}"> 更多操作 <span class="icon icon-chevron-down"></span> </a> <ul dDropDownMenu> <li role="menuitem"> <a class="devui-dropdown-item">菜单一</a> </li> <li class="disabled" role="menuitem"> <a class="devui-dropdown-item disabled">菜单二(禁用)</a> </li> <li role="menuitem"> <a class="devui-dropdown-item">菜单三</a> </li> <li role="menuitem"> <a class="devui-dropdown-item">菜单四</a> </li> </ul> </div> </div> `, styles: [` .area { width: 500px; height: 600px; } `] }) class TestDropdownAppendToBodyComponent { trigger: 'hover'| 'click' | 'manually' = 'click'; alignOriginFlag = false; directions = ['rightDown']; closeOnMouseLeaveMenu; } @Component({ template: ` <div class="area" *ngIf="init"> <div dDropDown> <a dDropDownToggle class="devui-dropdown-default devui-dropdown-origin" [autoFocus]="autoFocus" [toggleOnFocus]="toggleOnFocus"> 更多操作 <span class="icon icon-chevron-down"></span> </a> <ul dDropDownMenu> <li role="menuitem"> <a class="devui-dropdown-item">菜单一</a> </li> <li class="disabled" role="menuitem"> <a class="devui-dropdown-item disabled">菜单二(禁用)</a> </li> <li role="menuitem"> <a class="devui-dropdown-item">菜单三</a> </li> <li role="menuitem"> <a class="devui-dropdown-item">菜单四</a> </li> </ul> </div> </div> `, }) class TestDropdownToggleComponent { autoFocus = false; toggleOnFocus = false; init = true; } @Component({ template: `<section> <div class="btn-group g-dropdown" dDropDown appendToBody [trigger]="trigger1" [closeOnMouseLeaveMenu]="closeOnMouseLeaveMenu"> <a id="item-0" dDropDownToggle class="devui-dropdown-default devui-dropdown-origin"> 更多选择 <span class="icon icon-chevron-down"></span> </a> <ul id="menu1" dDropDownMenu class="devui-dropdown-menu devui-scrollbar" role="menu"> <li role="menuitem" dDropDown appendToBody [trigger]="trigger2" [appendToBodyDirections]="subMenuDirections"> <a class="devui-dropdown-item" dDropDownToggle id="item-1">内容1 <span class="icon icon-chevron-right"></span></a> <ul id="menu2" dDropDownMenu class="devui-dropdown-menu devui-scrollbar" role="menu"> <li role="menuitem" dDropDown appendToBody [trigger]="trigger2" [appendToBodyDirections]="subMenuDirections"> <a class="devui-dropdown-item" dDropDownToggle id="item-11">内容1-1 <span class="icon icon-chevron-right"></span></a> <ul id="menu3" dDropDownMenu class="devui-dropdown-menu devui-scrollbar" role="menu"> <li role="menuitem"> <a class="devui-dropdown-item" id="item-111">内容1-1-1</a> </li> <li role="menuitem"> <a class="devui-dropdown-item" id="item-112">内容1-1-2</a> </li> <li role="menuitem"> <a class="devui-dropdown-item" id="item-113">内容1-1-3</a> </li> </ul> </li> <li role="menuitem" dDropDown appendToBody [trigger]="trigger2" [appendToBodyDirections]="subMenuDirections"> <a class="devui-dropdown-item" dDropDownToggle id="item-12">内容1-2 <span class="icon icon-chevron-right"></span></a> <ul id="menu5" dDropDownMenu class="devui-dropdown-menu devui-scrollbar" role="menu"> <li role="menuitem"> <a class="devui-dropdown-item" id="item-121">内容1-2-1</a> </li> </ul> </li> <li role="menuitem"> <a class="devui-dropdown-item" id="item-13">内容1-3</a> </li> </ul> </li> <li role="menuitem" dDropDown appendToBody [trigger]="trigger2" [appendToBodyDirections]="subMenuDirections"> <a class="devui-dropdown-item" dDropDownToggle id="item-2">内容2 <span class="icon icon-chevron-right"></span></a> <ul id="menu4" dDropDownMenu class="devui-dropdown-menu devui-scrollbar" role="menu"> <li role="menuitem"> <a class="devui-dropdown-item" id="item-21">内容2-1</a> </li> </ul> </li> <li role="menuitem"> <a class="devui-dropdown-item" id="item-3">内容2</a> </li> </ul> </div> </section> ` }) class TestMultiLevelComponent { trigger1 = 'click'; trigger2 = 'click'; closeOnMouseLeaveMenu = false; subMenuDirections = [{ originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top', }, { originX: 'end', originY: 'bottom', overlayX: 'start', overlayY: 'bottom', offsetY: 5, // 菜单底部有个padding: 5px,刚好让菜单对齐父菜单 }, { originX: 'start', originY: 'top', overlayX: 'end', overlayY: 'top', }, { originX: 'start', originY: 'bottom', overlayX: 'end', overlayY: 'bottom', offsetY: 5, }]; } describe('dropdown', () => { let fixture: ComponentFixture<any>; beforeEach(() => { TestBed.configureTestingModule({ imports: [ CommonModule, DropDownModule, NoopAnimationsModule ], declarations: [ TestDropdownComponent, TestDropdownAppendToBodyComponent, TestDropdownToggleComponent, TestMultiLevelComponent ] }); }); describe('basic', () => { let debugEl: DebugElement; let component: TestDropdownComponent; let dropdownElement: DebugElement; let dropdownToggleElement: DebugElement; let dropdownMenuElement: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestDropdownComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; dropdownElement = debugEl.query(By.directive(DropDownDirective)); dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); fixture.detectChanges(); }); it('component has created successfully', () => { expect(component).toBeTruthy(); expect(dropdownElement).toBeTruthy(); expect(dropdownToggleElement).toBeTruthy(); expect(dropdownMenuElement).toBeTruthy(); }); describe('dropdown static style', () => { it ('dropdown directives should exist', () => { expect(dropdownElement.classes['devui-dropdown']).toBe(true); }); it ('dropdown toggle directive should exist', () => { expect(dropdownToggleElement.classes['devui-dropdown-toggle']).toBe(true); }); it ('dropdown menu directive should ', () => { expect(dropdownMenuElement.classes['devui-dropdown-menu']).toBe(true); }); }); describe('dropdown trigger', () => { it('click show menu', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time, NOTICE:NoopAnimation animation squash to 0 million second expect(dropdownMenuElement.styles['display']).toBe('block'); })); describe('after click show menu', () => { beforeEach(fakeAsync(() => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time })); it('click menu hide', fakeAsync(() => { dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('none'); })); it('click outside hide', fakeAsync(() => { document.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); it('hover show menu', fakeAsync(() => { component.trigger = 'hover'; fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseenter', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); tick(50); // debounce time fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); })); describe('after hover show menu', () => { beforeEach(fakeAsync(() => { component.trigger = 'hover'; fixture.detectChanges(); dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseenter', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); tick(50); // debounce time fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); })); it('mouseleave dropdown to others hide', fakeAsync(() => { dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': document, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // debounce time fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); describe('complete manually control', () => { beforeEach(fakeAsync(() => { component.trigger = 'manually'; fixture.detectChanges(); })); it('click should not show menu', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('none'); })); it('set isOpen should show menu', fakeAsync(() => { component.defaultOpen = true; fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); component.defaultOpen = false; fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); }); describe('dropdown isOpen', () => { it('isOpen true, should open menu, set to false should close', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); component.defaultOpen = true; fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); component.defaultOpen = false; fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); it('disabled, isOpen true, should not toggle', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); component.disabled = true; fixture.detectChanges(); component.defaultOpen = true; fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); describe('dropdown disabled', () => { it('disabled should not trigger, change to not disabled should recover', fakeAsync(() => { const count = component.count; component.disabled = true; fixture.detectChanges(); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); expect(component.count).toBe(count); component.disabled = false; fixture.detectChanges(); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); expect(component.count).toBe(count + 1); expect(component.isOpen).toBe(true); })); }); describe('dropdown closeScope', () => { const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; describe('default, click input textarea not close', () => { it('click input textarea not close', fakeAsync(() => { clickToggle(); const input = dropdownMenuElement.nativeElement.querySelector('input'); input.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); const textarea = dropdownMenuElement.nativeElement.querySelector('textarea'); textarea.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); })); }); describe('closeScope = all, same as default', () => { it('click input textarea not close', fakeAsync(() => { component.closeScope = 'all'; fixture.detectChanges(); clickToggle(); const input = dropdownMenuElement.nativeElement.querySelector('input'); input.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); const textarea = dropdownMenuElement.nativeElement.querySelector('textarea'); textarea.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); })); }); describe('closeScope = blank, click outside to close', () => { beforeEach(fakeAsync(() => { component.closeScope = 'blank'; fixture.detectChanges(); clickToggle(); })); it('click inside not to close', fakeAsync(() => { dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('block'); })); it('click outside to close', fakeAsync(() => { document.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); describe('closeScope = none, manually handle close', () => { beforeEach(fakeAsync(() => { component.closeScope = 'none'; fixture.detectChanges(); clickToggle(); })); it('click inside not to close', fakeAsync(() => { dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('block'); })); it('click outside not to close', fakeAsync(() => { document.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('block'); })); it('manually handle close', fakeAsync(() => { const closeBtn = dropdownMenuElement.nativeElement.querySelector('#close'); closeBtn.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); }); describe('dropdown closeOnMouseLeaveMenu', () => { const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; beforeEach(fakeAsync(() => { component.closeOnMouseLeaveMenu = true; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); })); it('trigger = click && closeOnMouseLeaveMenu = true, menu should close after leaving menu', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('block'); dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': document, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // debounce time fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); describe('dropdown toggleEvent', () => { it('toggle should trigger count++', fakeAsync(() => { const count = component.count; dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(component.count).toBe(count + 1); expect(component.isOpen).toBe(true); dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(component.count).toBe(count + 2); expect(component.isOpen).toBe(false); })); }); describe('dropdown public api function toggle', () => { it('toggle api should toggle dropdown', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); const toggleElement = debugEl.nativeElement.querySelector('.toggle'); toggleElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); toggleElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); it('disabled, toggle api should not toggle dropdown', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); component.disabled = true; fixture.detectChanges(); const toggleElement = debugEl.nativeElement.querySelector('.toggle'); toggleElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); }); describe('dropdownToggle', () => { let debugEl: DebugElement; let component: TestDropdownToggleComponent; let dropdownToggleElement: DebugElement; let dropdownMenuElement: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestDropdownToggleComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; fixture.detectChanges(); }); describe('dropdownToggle toggleOnFocus', () => { it('toggleOnFocus true, when focus, menu should show', fakeAsync(() => { component.toggleOnFocus = true; fixture.detectChanges(); dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('focus', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); })); }); describe('dropdownToggle autoFocus', () => { it('autoFocus true, when init, toggle should focus', fakeAsync(() => { component.init = false; fixture.detectChanges(); tick(); // wait dropdown destroy component.autoFocus = true; component.init = true; fixture.detectChanges(); tick(); // wait dropdown init fixture.detectChanges(); dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); expect(document.activeElement).toEqual(dropdownToggleElement.nativeElement); })); }); describe('dropdownToggle autoFocus combine toggleOnFocus', () => { // 并发会有问题,目前屏蔽 xit('autoFocus true, when init, menu should show', fakeAsync(() => { component.init = false; fixture.detectChanges(); tick(); // wait dropdown destroy // window.focus(); // need window to be in the front , otherwise not working component.autoFocus = true; component.toggleOnFocus = true; fixture.detectChanges(); component.init = true; fixture.detectChanges(); tick(200); // wait dropdown init fixture.detectChanges(); dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); expect(document.activeElement).toEqual(dropdownToggleElement.nativeElement); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); // 这行不稳定,需要浏览器处于激活状态 })); }); }); describe('dropdown append to body', () => { let debugEl: DebugElement; let component: TestDropdownAppendToBodyComponent; let dropdownElement: DebugElement; let dropdownToggleElement: DebugElement; let dropdownMenuElement: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestDropdownAppendToBodyComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; dropdownElement = debugEl.query(By.directive(DropDownDirective)); dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); fixture.detectChanges(); }); describe('dropdown basic trigger', () => { it('click show menu', fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeNull(); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); })); describe('after click show menu', () => { beforeEach(fakeAsync(() => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); })); it('click menu hide', fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBe(null); })); it('click outside hide', fakeAsync(() => { document.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBe(null); })); }); it('hover show menu', fakeAsync(() => { component.trigger = 'hover'; fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeNull(); dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseenter', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); tick(50); // hoverDebounceTime fixture.detectChanges(); tick(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(true); })); describe('after hover show menu', () => { beforeEach(fakeAsync(() => { component.trigger = 'hover'; fixture.detectChanges(); dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseenter', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); tick(50); fixture.detectChanges(); tick(); fixture.detectChanges(); })); it('mouseleave dropdown to others hide', fakeAsync(() => { dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': document, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // hoverDebounceTime fixture.detectChanges(); tick(); // animationTime fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBe(null); })); it('mouseleave toggle to menu show', fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': dropdownMenuElement.nativeElement, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // hoverDebounceTime fixture.detectChanges(); tick(); // animationTime fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(true); })); describe('after mouseleave toggle to menu show', () => { beforeEach(fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': dropdownMenuElement.nativeElement, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // hoverDebounceTime fixture.detectChanges(); tick(); // animationTime fixture.detectChanges(); })); it('mouseleave menu to others hide', fakeAsync(() => { dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': document, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // hoverDebounceTime fixture.detectChanges(); tick(); // animationTime fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBe(null); })); it('mouseleave menu to toggle show', fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': dropdownToggleElement.nativeElement, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // hoverDebounceTime fixture.detectChanges(); tick(); // animationTime fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(true); })); }); }); }); describe('dropdown basic closeOnMouseLeaveMenu', () => { const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; beforeEach(fakeAsync(() => { component.closeOnMouseLeaveMenu = true; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); })); it('trigger = click && closeOnMouseLeaveMenu = true, menu should close after leaving menu', fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(true); // appendToBody的 需要mouseleave dropdown menu dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': document, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // debounce time fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(false); })); it('trigger = click && closeOnMouseLeaveMenu = true, menu should not close after leaving menu to toggle', fakeAsync(() => { dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); expect(dropdownMenuElement).toBeTruthy(); expect(dropdownMenuElement.styles['display']).toBe('block'); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(true); dropdownMenuElement.nativeElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': dropdownToggleElement.nativeElement, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); // debounce time fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(document.contains(dropdownMenuElement.nativeElement)).toBe(true); })); }); describe('dropdown alignOrigin', () => { const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; it('normal case should align to toggle element', fakeAsync(() => { clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x === menuRect.x).toBe(true); expect(originRect.y + originRect.height + verticalBorderOverlayWidth).toBeCloseTo(menuRect.y); })); it('align to area', fakeAsync(() => { component.alignOriginFlag = true; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = debugEl.nativeElement.querySelector('.area').getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x === menuRect.x).toBe(true); expect(originRect.y + originRect.height + verticalBorderOverlayWidth).toBeCloseTo(menuRect.y); })); }); describe('dropdown appendToBodyDirections', () => { const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; it('rightDown should in the right place', fakeAsync(() => { component.directions = ['rightDown']; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x === menuRect.x).toBe(true); expect(originRect.y + originRect.height + verticalBorderOverlayWidth).toBeCloseTo(menuRect.y); })); it('leftDown should in the right place', fakeAsync(() => { component.directions = ['leftDown']; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x + originRect.width).toBeCloseTo(menuRect.x + menuRect.width, 0); expect(originRect.y + originRect.height + verticalBorderOverlayWidth).toBeCloseTo(menuRect.y); })); it('centerDown should in the right place', fakeAsync(() => { component.directions = ['centerDown']; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect((originRect.x + (originRect.width / 2)) - ((menuRect.x + menuRect.width / 2))).toBeLessThan(1); expect(originRect.y + originRect.height + verticalBorderOverlayWidth).toBeCloseTo(menuRect.y); })); it('rightUp should in the right place', fakeAsync(() => { component.directions = ['rightUp']; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x === menuRect.x).toBe(true); expect(originRect.y).toBeCloseTo(menuRect.y + menuRect.height + verticalBorderOverlayWidth); })); it('leftUp should in the right place', fakeAsync(() => { component.directions = ['leftUp']; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x + originRect.width).toBeCloseTo(menuRect.x + menuRect.width, 0); expect(originRect.y).toBeCloseTo(menuRect.y + menuRect.height + verticalBorderOverlayWidth, 0); })); it('centerUp should in the right place', fakeAsync(() => { component.directions = ['centerUp']; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect((originRect.x + (originRect.width / 2)) - ((menuRect.x + menuRect.width / 2))).toBeLessThan(1); expect(originRect.y).toBeCloseTo(menuRect.y + menuRect.height + verticalBorderOverlayWidth); })); }); }); describe('dropdown Advance feature', () => { describe('dropdown cascade dropdown', () => { let debugEl: DebugElement; let component: TestMultiLevelComponent; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(TestMultiLevelComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; fixture.detectChanges(); })); const clickToggle = (id) => { const clickElement = document.querySelector(`#${id}`); clickElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); return clickElement; }; const hoverToggle = (id) => { const mouseenterElement = document.querySelector(`#${id}`).parentElement; mouseenterElement.dispatchEvent(new MouseEvent('mouseenter', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); tick(50); fixture.detectChanges(); tick(); return mouseenterElement; }; const leaveToggle = (id, relatedTarget?) => { const toggleElement = document.querySelector(`#${id}`).parentElement; toggleElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': relatedTarget, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); fixture.detectChanges(); tick(); return toggleElement; }; const leaveMenu = (id, relatedTarget?) => { const menuElement = document.querySelector(`#${id}`); menuElement.dispatchEvent(new MouseEvent('mouseleave', { 'relatedTarget': relatedTarget, 'bubbles': false, 'cancelable': false })); fixture.detectChanges(); tick(50); fixture.detectChanges(); tick(); return menuElement; }; const getRelatedTarget = (id) => { return document.querySelector(`#${id}`); }; const isMenuShow = (id) => { fixture.detectChanges(); const menuElement = document.querySelector(`#${id}`); return document.contains(menuElement); }; describe('click', () => { beforeEach(fakeAsync(() => { component.trigger1 = 'click'; component.trigger2 = 'click'; fixture.detectChanges(); })); describe('cascade child show, ancestor still display', () => { // 单击toggle 单击菜单一, 展开菜单二 it('cascade display', fakeAsync(() => { clickToggle('item-0'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); clickToggle('item-1'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); clickToggle('item-11'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(true); })); }); describe('click menu hide,ancestor hide, children hide', () => { beforeEach(fakeAsync(() => { // 全部展开 clickToggle('item-0'); fixture.detectChanges(); clickToggle('item-1'); fixture.detectChanges(); clickToggle('item-11'); fixture.detectChanges(); })); it('click outside should hide all', fakeAsync(() => { // 单击外部全部隐藏 document.body.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('top parent close, all children close', fakeAsync(() => { // 单击toggle全隐藏 clickToggle('item-0'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('first menu parent close, children close', fakeAsync(() => { // 单击菜单一选项全隐藏 clickToggle('item-3'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('second menu parent close, children close', fakeAsync(() => { // 单击菜单二的选项 clickToggle('item-13'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('third menu parent close, children close', fakeAsync(() => { // 单击菜单三的选项 clickToggle('item-111'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); }); describe('switch menu, old menu hide, new menu display, ancestor still display', () => { beforeEach(fakeAsync(() => { // 全部展开 clickToggle('item-0'); fixture.detectChanges(); clickToggle('item-1'); fixture.detectChanges(); clickToggle('item-11'); fixture.detectChanges(); })); it('first menu switch, children close, new menu show', fakeAsync(() => { // 菜单一切换 老的菜单二三隐藏 新的菜单二出现 clickToggle('item-2'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); expect(isMenuShow('menu4')).toBe(true); })); it('second menu parent close, children close', fakeAsync(() => { // 菜单二切换 老的菜单三隐藏, 新的菜单三出现, 老的菜单一仍然在 clickToggle('item-12'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(false); expect(isMenuShow('menu5')).toBe(true); })); }); }); describe('hover', () => { beforeEach(fakeAsync(() => { component.trigger1 = 'hover'; component.trigger2 = 'hover'; fixture.detectChanges(); })); describe('cascade child show, ancestor still display', () => { // 悬停toggle 悬停菜单一, 悬停菜单二 it('cascade display', fakeAsync(() => { hoverToggle('item-0'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); hoverToggle('item-1'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); hoverToggle('item-11'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(true); })); }); describe('click menu hide,ancestor hide, children hide', () => { beforeEach(fakeAsync(() => { // 全部展开 hoverToggle('item-0'); fixture.detectChanges(); hoverToggle('item-1'); fixture.detectChanges(); hoverToggle('item-11'); fixture.detectChanges(); })); it('top parent close, all children close', fakeAsync(() => { // 单击toggle全隐藏 clickToggle('item-0'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('second menu parent close, children close', fakeAsync(() => { // 单击菜单一选项全隐藏 clickToggle('item-3'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('third menu parent close, children close', fakeAsync(() => { // 单击菜单二的选项 clickToggle('item-13'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('second menu parent close, children close', fakeAsync(() => { // 单击菜单三的选项 clickToggle('item-111'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); }); describe('mouseleave to ancestor normal option, menu hide', () => { beforeEach(fakeAsync(() => { // 全部展开 hoverToggle('item-0'); fixture.detectChanges(); hoverToggle('item-1'); fixture.detectChanges(); hoverToggle('item-11'); fixture.detectChanges(); })); it('mouse leave to second menu', fakeAsync(() => { leaveMenu('menu3', getRelatedTarget('item-13')); hoverToggle('item-13'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(false); })); }); describe('switch menu, old menu hide, new menu display, ancestor still display', () => { beforeEach(fakeAsync(() => { // 全部展开 hoverToggle('item-0'); fixture.detectChanges(); hoverToggle('item-1'); fixture.detectChanges(); hoverToggle('item-11'); fixture.detectChanges(); })); it('first menu switch, children close,new menu show', fakeAsync(() => { // 菜单一切换 老的菜单二三隐藏 新的菜单二出现 leaveMenu('menu3', getRelatedTarget('item-2')); hoverToggle('item-2'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); expect(isMenuShow('menu4')).toBe(true); })); it('second menu parent close, children close', fakeAsync(() => { // 菜单二切换 老的菜单三隐藏, 新的菜单三出现, 老的菜单一仍然在 leaveMenu('menu3', getRelatedTarget('item-12')); hoverToggle('item-12'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(false); expect(isMenuShow('menu5')).toBe(true); })); }); }); describe('first click width closeOnMouseLeaveMenu, second hover', () => { beforeEach(fakeAsync(() => { component.trigger1 = 'click'; component.trigger2 = 'hover'; component.closeOnMouseLeaveMenu = true; fixture.detectChanges(); })); describe('cascade display', () => { describe('cascade child show, ancestor still display', () => { // 点击toggle 悬停菜单一, 悬停菜单二 it('cascade display', fakeAsync(() => { clickToggle('item-0'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); hoverToggle('item-1'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); hoverToggle('item-11'); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(true); })); }); describe('mouseleave close menu1', () => { // 离开子菜单,top菜单为click的也关闭 it('mouseleave hide menu1', fakeAsync(() => { clickToggle('item-0'); fixture.detectChanges(); hoverToggle('item-1'); fixture.detectChanges(); hoverToggle('item-11'); fixture.detectChanges(); leaveMenu('menu3', document); fixture.detectChanges(); tick(50); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(false); expect(isMenuShow('menu2')).toBe(false); expect(isMenuShow('menu3')).toBe(false); })); it('mouseleave to menu2, menu1 still display', fakeAsync(() => { clickToggle('item-0'); fixture.detectChanges(); hoverToggle('item-1'); fixture.detectChanges(); hoverToggle('item-11'); fixture.detectChanges(); leaveMenu('menu3', getRelatedTarget('item-12')); fixture.detectChanges(); tick(50); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(isMenuShow('menu1')).toBe(true); expect(isMenuShow('menu2')).toBe(true); expect(isMenuShow('menu3')).toBe(false); })); }); }); }); }); }); describe('dropdown implied feature', () => { describe('dropdown auto direction', () => { let debugEl: DebugElement; let component: TestDropdownComponent; let dropdownToggleElement: DebugElement; let dropdownMenuElement: DebugElement; const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; beforeEach(() => { fixture = TestBed.createComponent(TestDropdownComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); fixture.detectChanges(); }); it('bottom enough, render down', fakeAsync(() => { component.expand = false; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x === menuRect.x).toBe(true); expect(originRect.y + originRect.height + verticalBorderOverlayWidth === menuRect.y).toBe(true); clickToggle(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); it('bottom not enough, render up', fakeAsync(() => { component.expand = true; fixture.detectChanges(); clickToggle(); fixture.detectChanges(); const originRect = dropdownToggleElement.nativeElement.getBoundingClientRect(); const menuRect = dropdownMenuElement.nativeElement.getBoundingClientRect(); const verticalBorderOverlayWidth = 4; // 有个间距 expect(originRect.x === menuRect.x).toBe(true); expect(originRect.y === menuRect.y + menuRect.height + verticalBorderOverlayWidth).toBe(true); clickToggle(); // to test fadeout function (Branches coverage) expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); describe('dropdown keyboard event', () => { let debugEl: DebugElement; let dropdownToggleElement: DebugElement; let dropdownMenuElement: DebugElement; const clickToggle = () => { dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(); // animation time }; beforeEach(() => { fixture = TestBed.createComponent(TestDropdownComponent); debugEl = fixture.debugElement; dropdownToggleElement = debugEl.query(By.directive(DropDownToggleDirective)); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); fixture.detectChanges(); }); it('toggle Element focus,press enter toggle menu open', fakeAsync(() => { expect(dropdownMenuElement.styles['display']).toBe('none'); dropdownToggleElement.nativeElement.dispatchEvent(new MouseEvent('focus', {'bubbles': false, 'cancelable': false})); fixture.detectChanges(); dropdownToggleElement.nativeElement.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); dropdownToggleElement.nativeElement.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); it('menu open, press escape close menu', fakeAsync(() => { clickToggle(); fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('block'); document.body.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'})); fixture.detectChanges(); tick(); // animation time fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); describe('dropdown mouse enter and leave ( debounce time < gap < animation time) should normally open and close', () => { let debugEl: DebugElement; let dropdownElement: DebugElement; let dropdownMenuElement: DebugElement; beforeEach(() => { fixture = TestBed.createComponent(TestDropdownComponent); debugEl = fixture.debugElement; dropdownElement = debugEl.query(By.directive(DropDownDirective)); dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective)); fixture.detectChanges(); }); it('menu open, press escape close menu', fakeAsync(() => { dropdownElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(100); // gap time dropdownElement.nativeElement.dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true})); fixture.detectChanges(); tick(100); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(dropdownMenuElement.styles['display']).toBe('none'); })); }); }); });
the_stack
import ora, { Ora } from "ora"; import { exec } from "child_process"; import fs from "fs"; import path from "path"; import { Octokit } from "@octokit/core"; import dotenv from "dotenv"; import chalk from "chalk"; import walk from "../lib/walk"; import { Repositories, Repository } from "../lib/repositories"; import { Algorithm } from "../lib/models"; import { normalize, normalizeAlgorithm, normalizeCategory, normalizeTitle, normalizeWeak, } from "../lib/normalize"; import highlightCode from "../lib/highlight"; import locales from "../lib/locales"; import renderMarkdown from "../lib/markdown"; import renderNotebook from "../lib/notebookjs"; dotenv.config(); const octokit = new Octokit( process.env.GH_TOKEN ? { auth: process.env.GH_TOKEN } : {} ); let algorithms: { [key: string]: Algorithm } = {}; let categories: { [category: string]: string[] } = {}; let categoryNames: { [category: string]: string } = {}; let languages: { [language: string]: string[] } = {}; let authors: { [email: string]: { name: string; login?: string; email: string; avatar?: string; algorithms: Algorithm[]; }; } = {}; let spinner: Ora; // Algorithms which are ignored const algorithmsToIgnore = ["rungradientdescent", "class"]; // Categories where algorithms are ignored const categoriesToIgnore = [ "projecteuler", "test", "github", "ipynbcheckpoints", "leetcode", "spec", // Because of weird swift algorithm structure "minimax", ]; // Categories where algorithms are included, but not the category const categoriesToSkip = ["main", "src", "algorithms", "problems"]; (async () => { spinner = ora("Downloading repositories").start(); if (fs.existsSync("public/data")) await fs.promises.rm("public/data", { recursive: true }); await fs.promises.mkdir("public/data"); await fs.promises.mkdir("public/data/repositories"); process.chdir("public/data/repositories"); await Promise.all( [...Object.keys(Repositories), "algorithms-explanation"].map( (repo) => new Promise<void>((resolve, reject) => { exec( `git clone https://github.com/TheAlgorithms/${repo}.git`, (err) => { if (err) reject(err); else resolve(); } ); }) ) ); spinner.succeed(); spinner = ora("Collecting algorithms and rendering code").start(); for await (const language of Object.keys(Repositories).filter( (x) => !!Repositories[x].baseDir )) { const repo: Repository = Repositories[language]; languages[language] = []; for await (const dir of walk(path.join(language, repo.baseDir))) { let valid = false; for (const validFilename of repo.allowedFiles) { if (dir.endsWith(validFilename)) valid = true; } if (!valid) continue; if (!isValidCategory(dir)) continue; if ( dir.split(path.sep).length - path.join(language, repo.baseDir).split(path.sep).length < 2 ) continue; // Ignore top level files const name = normalizeTitle( dir.split(path.sep).pop().split(".")[0].replace(/_/g, " ") ); const nName = normalize(name); if (algorithmsToIgnore.includes(nName)) continue; const lCategories = dir .split(path.sep) .slice( path.join(language, repo.baseDir).split(path.sep).length, dir.split(path.sep).length - 1 ) .filter((category) => !categoriesToSkip.includes(normalize(category))) .map(normalizeTitle) .map(normalizeCategory); if ( normalize(lCategories[lCategories.length - 1] || "") === normalize(normalizeCategory(normalizeTitle(name))) ) lCategories.pop(); if (!algorithms[nName]) { algorithms[nName] = { slug: normalizeWeak(name), name, categories: lCategories.map(normalize), body: {}, implementations: {}, contributors: [], explanationUrl: {}, }; for (const category of lCategories) { if (!categories[normalize(category)]) { categories[normalize(category)] = []; } categories[normalize(category)].push(normalizeWeak(name)); } } for (const category of lCategories) { if (!categoryNames[normalize(category)]) { categoryNames[normalize(category)] = category; } } algorithms[nName].implementations[language] = { dir: path.join(...dir.split(path.sep).slice(1)), url: `https://github.com/TheAlgorithms/${language}/tree/master/${path.join( ...dir.split(path.sep).slice(1) )}`, code: highlightCode( (await fs.promises.readFile(dir)).toString(), language ), }; languages[language].push(algorithms[nName].slug); } } // Fetch the C# repo process.chdir("c-sharp"); await (async () => { const directory = (await fs.promises.readFile("README.md")).toString(); let aCategories = []; languages["c-sharp"] = []; await Promise.all( directory.split("\n").map(async (line) => { for (let i = 0; i < 6; i += 1) { if ( line.startsWith(`${" ".repeat(i)}*`) || line.startsWith(`${" ".repeat(i)}*`) ) { const algorithmMatch = line .substr(2 * i + 1) .match(/\[(.+)\]\((.+\/(.+)(?:\.cs))\)/); const categoryMatch = line .substr(2 * i + 1) .match(/\[(.+)\]\((.+)\)/); aCategories.length = i; if (algorithmMatch) { const name = algorithmMatch[1]; const nName = normalizeAlgorithm(name); const dir = algorithmMatch[2].replace( "https://github.com/TheAlgorithms/C-Sharp/blob/master/", "" ); if (!algorithms[nName]) { algorithms[nName] = { slug: normalizeWeak(name), name, categories: aCategories .filter((x) => !!x && x !== "Algorithms") .map(normalizeTitle) .map(normalizeCategory) .map(normalize), body: {}, implementations: {}, contributors: [], explanationUrl: {}, }; for (const category of aCategories .filter((x) => !!x && x !== "Algorithms") .map(normalizeTitle) .map(normalizeCategory)) { if (!categories[normalizeCategory(category)]) categories[normalizeCategory(category)] = []; if (!categoryNames[normalize(category)]) { categoryNames[normalize(category)] = category; } categories[normalizeCategory(category)].push( normalizeWeak(name) ); } } languages["c-sharp"].push(algorithms[nName].slug); let file: string; try { file = (await fs.promises.readFile(dir)).toString(); } catch { console.warn(`\nFailed to get ${dir}`); continue; } algorithms[nName].implementations["c-sharp"] = { dir, url: path.join( "https://github.com/TheAlgorithms/C-Sharp/tree/master", algorithmMatch[2] ), code: highlightCode(file, "c-sharp"), }; } else if (categoryMatch) { // eslint-disable-next-line prefer-destructuring aCategories[i] = categoryMatch[1]; } } } }) ); })(); process.chdir(".."); spinner.succeed(); spinner = ora("Fetching GitHub stars").start(); // Fetch stars let stars: { [key: string]: number } = {}; let errors = []; await Promise.all( Object.keys(Repositories).map<void>(async (repo) => { let repoStars = 0; try { const { data } = await octokit.request("GET /repos/{owner}/{repo}", { owner: "TheAlgorithms", repo, }); repoStars = data.stargazers_count; } catch { errors.push(repo); } stars[repo] = repoStars; }) ); if (errors.length > 0) spinner.warn( `Failed to get stars for ${errors.length} ${ errors.length === 1 ? "repository" : "repositories" }, using 0 as values instead (likely API rate limit exceeded)` ); else spinner.succeed(); spinner = ora("Collecting and rendering explanations").start(); process.chdir("./algorithms-explanation"); await Promise.all( locales.map(async (locale) => { if (fs.existsSync(locale.code)) { for await (const dir of walk(locale.code)) { const match = dir.replace(/\\/g, "/").match(/(?:.+)\/(.+)\.md/); if (match) { const algorithm = algorithms[normalizeAlgorithm(match[1])]; if (algorithm) { algorithm.explanationUrl[ locale.code ] = `https://github.com/TheAlgorithms/Algorithms-Explanation/tree/master/${dir}`; algorithm.body[locale.code] = await renderMarkdown( (await fs.promises.readFile(dir)) .toString() .split("\n") .slice(1) .join("\n") ); } } } } }) ); process.chdir(".."); await Promise.all( Object.values(algorithms).flatMap((algorithm) => Object.keys(algorithm.implementations).flatMap(async (language) => { if (language === "jupyter") { const render = await renderNotebook( ( await fs.promises.readFile( path.join(language, algorithm.implementations[language].dir) ) ).toString() ); locales.forEach((locale) => { if (algorithm.body[locale.code]) algorithm.body[locale.code] += `\n${render}`; else algorithm.body[locale.code] = render; }); } }) ) ); spinner.succeed(); spinner = ora( `Collecting contributors ${ !process.env.GH_TOKEN ? chalk.gray("(without GitHub token)") : "" }` ).start(); let requests = 0; let possibleAuthors: { [login: string]: any } = {}; await Promise.all( Object.keys(Repositories).map<void>( (repo) => new Promise<void>((resolve, reject) => { exec( "git log --name-status", { cwd: repo, maxBuffer: 1024 * 1024 * 2 }, (err, stdout) => { if (err) reject(err); let author = ""; for (const line of stdout.split("\n")) { if (line.startsWith("Author:")) author = line.slice(8); if (line.startsWith("M\t") || line.startsWith("A\t")) { const [, name, email] = author.match(/^(.*) <(.+)>$/); if (email) { if (!authors[email]) authors[email] = { name, email, algorithms: [], }; authors[email].algorithms.push( algorithms[ normalize(line.slice(8).split("/").pop().split(".")[0]) ] ); } } } async function collectContributors(page = 0) { requests += 1; const { data } = await octokit.request( `GET /repos/{owner}/{repo}/contributors`, { owner: "TheAlgorithms", repo, per_page: 100, page, } ); for (const contributor of data) { if (!possibleAuthors[contributor.login]) possibleAuthors[contributor.login] = contributor; } if (data.length === 100) { await collectContributors(page + 1); } } if (process.env.GH_TOKEN) collectContributors(0).then(() => { resolve(); }); else resolve(); } ); }) ) ); // Try to get GitHub avatars and usernames (uses arround 1400/5000 requests to GitHub API) // This is needed because the GitHub API somehow // doesn't give me the user email before await Promise.all( Object.values(possibleAuthors).map<void>(async (author: any) => { requests += 1; const { data } = await octokit.request(`GET /users/{username}`, { username: author.login, }); author.email = data.email; author.login = data.login; }) ); Object.values(authors).forEach((author) => { if (author.name === "github-actions") return; const authorFromApi = Object.values(possibleAuthors).find( (x) => x.email === author.email || `${x.login}@users.noreply.github.com` === author.email ); if (authorFromApi) { author.login = authorFromApi.login; author.avatar = `${authorFromApi.avatar_url}&s=80`; } author.algorithms.forEach((algorithm) => { if (algorithm) { const existing = algorithm.contributors.find( (x) => x.email === author.email ); if (!existing) { const contributor = { ...author, commits: 1 }; delete contributor.algorithms; algorithm.contributors.push(contributor); } else { existing.commits += 1; } } }); }); Object.values(algorithms).forEach((algorithm) => algorithm.contributors.sort((a, b) => a.commits - b.commits) ); if (process.env.GH_TOKEN) spinner.text += chalk.gray(` (${requests} requests sent to GitHub API)`); spinner.succeed(); process.chdir(".."); spinner = ora("Writing algorithms to files").start(); await fs.promises.mkdir("algorithms"); await Promise.all( Object.values(algorithms).map(async (algorithm) => { await fs.promises.writeFile( path.join("algorithms", `${algorithm.slug}.json`), JSON.stringify(algorithm, null, 2) ); }) ); await fs.promises.mkdir("algorithms-min"); await Promise.all( Object.values(algorithms).map(async (algorithm) => { delete algorithm.body; Object.keys(algorithm.implementations).forEach((key) => { algorithm.implementations[key] = ""; }); await fs.promises.writeFile( path.join("algorithms-min", `${algorithm.slug}.json`), JSON.stringify(algorithm, null, 2) ); }) ); await fs.promises.writeFile( "algorithms.json", JSON.stringify(Object.values(algorithms)) ); await fs.promises.writeFile( "algorithms-min.json", JSON.stringify( Object.values(algorithms).map((algorithm) => { const minAlgorithm = { name: algorithm.name, slug: algorithm.slug, categories: algorithm.categories, implementations: {}, }; Object.keys(algorithm.implementations).forEach((language) => { minAlgorithm.implementations[language] = { url: algorithm.implementations[language].url, }; }); return minAlgorithm; }) ) ); await fs.promises.writeFile("stars.json", JSON.stringify(stars)); await fs.promises.writeFile("categories.json", JSON.stringify(categories)); await fs.promises.writeFile("languages.json", JSON.stringify(languages)); const oldLocalesCategories: { [key: string]: string } = fs.existsSync( "../locales/en/categories.json" ) ? JSON.parse( (await fs.promises.readFile("../locales/en/categories.json")).toString() ) : {}; const localesCategories: { [key: string]: string } = {}; Object.keys(categoryNames) .sort() .forEach((key) => { localesCategories[key] = oldLocalesCategories[key] || categoryNames[key]; }); await fs.promises.writeFile( "../locales/en/categories.json", JSON.stringify(localesCategories, null, 4) ); await fs.promises.rm("repositories", { recursive: true }); spinner.succeed(); })(); function isValidCategory(name: string) { if (normalize(name).match(/problem\d+/)) return false; for (const exclude of categoriesToIgnore) { if (normalize(name).includes(exclude)) return false; } for (const exclude of ["__init__", "mod.rs"]) { if (name.includes(exclude)) return false; } return true; }
the_stack
import React, { useEffect, useMemo, useState } from 'react'; import { notification, Spin, Button, Popover } from 'antd'; import { contexts, useUserAccounts, WalletSigner, useWallet } from '@oyster/common'; import { Input } from '../Input'; import './style.less'; import { ASSET_CHAIN, chainToName } from '../../utils/assets'; import { displayBalance, fromSolana, ProgressUpdate, toSolana, TransferRequest, } from '@solana/bridge-sdk'; import { useEthereum } from '../../contexts'; import { TokenDisplay } from '../TokenDisplay'; import { useTokenChainPairState } from '../../contexts/chainPair'; import { LABELS } from '../../constants'; import { useCorrectNetwork } from '../../hooks/useCorrectNetwork'; import { RecentTransactionsTable } from '../RecentTransactionsTable'; import { useBridge } from '../../contexts/bridge'; import { WarningOutlined } from '@ant-design/icons'; const { useConnection } = contexts.Connection; export const typeToIcon = (type: string, isLast: boolean) => { const style: React.CSSProperties = { marginRight: 5 }; switch (type) { case 'user': return <span style={style}>🪓 </span>; case 'done': return <span style={style}>✅ </span>; case 'error': return <span style={style}>❌ </span>; case 'wait': return isLast ? <Spin /> : <span style={style}> ✅ </span>; default: return null; } }; export const Transfer = () => { const connection = useConnection(); const bridge = useBridge(); const wallet = useWallet(); const { provider, tokenMap } = useEthereum(); const { userAccounts } = useUserAccounts(); const hasCorrespondingNetworks = useCorrectNetwork(); const { A, B, mintAddress, setMintAddress, setLastTypedAccount, } = useTokenChainPairState(); const [popoverVisible, setPopoverVisible] = useState(true) const [request, setRequest] = useState<TransferRequest>({ from: ASSET_CHAIN.Ethereum, to: ASSET_CHAIN.Solana, }); useEffect(() => { if (mintAddress && !request.asset) { setRequest({ ...request, asset: mintAddress, }); } }, [mintAddress]); const setAssetInformation = async (asset: string) => { setMintAddress(asset); }; useEffect(() => { setRequest({ ...request, amount: A.amount, asset: mintAddress, from: A.chain, to: B.chain, info: A.info, }); }, [A, B, mintAddress, A.info]); const tokenAccounts = useMemo( () => userAccounts.filter(u => u.info.mint.toBase58() === request.info?.mint), [request.info?.mint], ); return ( <> <div className="exchange-card"> <Input title={`From`} asset={request.asset} balance={displayBalance(A.info)} setAsset={asset => setAssetInformation(asset)} chain={A.chain} amount={A.amount} onChain={(chain: ASSET_CHAIN) => { const from = A.chain; A.setChain(chain); if (B.chain === chain) { B.setChain(from); } }} onInputChange={amount => { setLastTypedAccount(A.chain); A.setAmount(amount || 0); }} className={'left'} /> <Popover placement="top" title={<span style={{cursor: "pointer"}} onClick={() => setPopoverVisible(false)}>x</span>} content={<span style={{textAlign: "center"}}> <WarningOutlined style={{ fontSize: '40px', color: '#ccae00' }} /> <p>This website should be only used to migrate liquidity from Wormhole v1. <br/>Wormhole is upgrading on-chain contracts to v2 in next 2 weeks.</p> <p>To see the tokens you need to connect both wallets first</p> <p>If your SOL -&gt; ETH transaction is taking more than 1 hour, make sure to <br/> to look at the recent transactions table below and click on retry Icon <br/> if the transaction failed</p> </span>} visible={popoverVisible} > <Button className="swap-button" style={{ padding: 0 }} disabled={false} onClick={() => { return; // const from = A.chain; // const toChain = B.chain; // if (from !== undefined && toChain !== undefined) { // A.setChain(toChain); // B.setChain(from); // } }} > <span></span> </Button> </Popover> <Input title={`To`} asset={request.asset} balance={displayBalance(B.info)} setAsset={asset => setAssetInformation(asset)} chain={B.chain} amount={B.amount} onChain={(chain: ASSET_CHAIN) => { const to = B.chain; B.setChain(chain); if (A.chain === chain) { A.setChain(to); } }} onInputChange={amount => { setLastTypedAccount(B.chain); B.setAmount(amount || 0); }} className={'right'} /> </div> <Button className={'transfer-button'} type="primary" size="large" disabled={!(A.amount && B.amount) || !wallet.connected || !provider} onClick={async () => { if (!wallet || !provider) { return; } const token = tokenMap.get(request.asset?.toLowerCase() || ''); const NotificationContent = () => { const [activeSteps, setActiveSteps] = useState<ProgressUpdate[]>( [], ); useEffect(() => { (async () => { let steps: ProgressUpdate[] = []; try { if (request.from === ASSET_CHAIN.Solana) { await fromSolana( connection, wallet, request, provider, update => { if (update.replace) { steps.pop(); steps = [...steps, update]; } else { steps = [...steps, update]; } setActiveSteps(steps); }, bridge, ); } if (request.to === ASSET_CHAIN.Solana) { await toSolana( connection, wallet, request, provider, update => { if (update.replace) { steps.pop(); steps = [...steps, update]; } else { steps = [...steps, update]; } setActiveSteps(steps); }, ); } } catch (err) { // TODO... console.log(err); } })(); }, [setActiveSteps]); return ( <div> <div style={{ display: 'flex' }}> <div> <h5>{`${chainToName(request.from)} Mainnet -> ${chainToName( request.to, )} Mainnet`}</h5> <h2> {request.amount?.toString()} {request.info?.name} </h2> </div> <div style={{ display: 'flex', marginLeft: 'auto', marginRight: 10, }} > <TokenDisplay asset={request.asset} chain={request.from} token={token} /> <span style={{ margin: 15 }}>{'➔'}</span> <TokenDisplay asset={request.asset} chain={request.to} token={token} /> </div> </div> <div style={{ textAlign: 'left', display: 'flex', flexDirection: 'column', }} > {(() => { let group = ''; return activeSteps.map((step, i) => { let prevGroup = group; group = step.group; let newGroup = prevGroup !== group; return ( <> {newGroup && <span>{group}</span>} <span style={{ marginLeft: 15 }}> {typeToIcon( step.type, activeSteps.length - 1 === i, )}{' '} {step.message} </span> </> ); }); })()} </div> </div> ); }; notification.open({ message: '', duration: 0, placement: 'bottomLeft', description: <NotificationContent />, className: 'custom-class', style: { width: 500, }, }); }} > {hasCorrespondingNetworks ? !(A.amount && B.amount) ? LABELS.ENTER_AMOUNT : LABELS.TRANSFER : LABELS.SET_CORRECT_WALLET_NETWORK} </Button> <RecentTransactionsTable tokenAccounts={tokenAccounts} /> </> ); };
the_stack
import { Memoize } from 'typescript-memoize'; import { Deferred } from './deferred'; import { Container as ContainerInterface, Factory, isFactoryByCreateMethod } from './container'; let nonce = 0; export class Container implements ContainerInterface { private cache = new Map() as Map<CacheKey, CacheEntry>; private tearingDown: Deferred<void> | undefined; constructor(private registry: Registry) {} async lookup<K extends keyof KnownServices>(name: K): Promise<KnownServices[K]>; async lookup(name: string): Promise<unknown>; async lookup(name: string): Promise<any> { let { promise, instance } = this._lookup(name); await promise; return instance; } private _lookup(name: string): CacheEntry { let cached = this.cache.get(name); if (cached) { return cached; } let factory = this.lookupFactory(name); return this.provideInjections(() => { let instance: any; if (isFactoryByCreateMethod(factory)) { instance = factory.create(); } else { instance = new factory(); } return instance; }, name); } private lookupFactory(name: string): Factory<any> { let factory = mappings.get(this.registry)!.get(name); if (!factory) { throw new Error(`no such service "${name}"`); } return factory; } // When this is called we'll always instantiate a new instance for each // invocation of instantiate(), as opposed to when .lookup() is used, where // there will only ever be 1 instance in the container. Consider the example // of using instantiate() to create an indexer for each realm. The desired // behavior is that there is a separate indexer instance for each realm--not // that they are all using the same indexer instance. // // When you use instantiate, you are responsible for calling teardown on the // returned object. async instantiate<T, A extends unknown[]>(factory: Factory<T, A>, ...args: A): Promise<T> { let { instance, promise } = this.provideInjections(() => { if (isFactoryByCreateMethod(factory)) { return factory.create(...args); } else { return new factory(...args); } }); await promise; return instance; } private provideInjections<T>(create: () => T, cacheKey?: CacheKey): CacheEntry { let pending = new Map() as PendingInjections; pendingInstantiationStack.unshift(pending); let result: CacheEntry; try { let instance = create(); ownership.set(instance, this); result = new CacheEntry(cacheKey ?? `anonymous_${nonce++}`, instance, pending); if (cacheKey) { this.cache.set(cacheKey, result); } for (let [name, entry] of pending.entries()) { entry.cacheEntry = this._lookup(name); } } finally { pendingInstantiationStack.shift(); } return result; } async teardown() { if (!this.tearingDown) { this.tearingDown = new Deferred(); this.tearingDown.fulfill( (async () => { // first phase: everybody's willTeardown resolves. Each instance // promises that it will not *initiate* new calls to its injections // after resolving willTeardown. You may still call your injections in // response to being called by someone who injected you. await Promise.all( [...this.cache.values()].map(async ({ promise, instance }) => { try { await promise; } catch (e) { // whoever originally called instantiate or lookup received a rejected promise and its their responsibility to handle it } if (typeof instance?.willTeardown === 'function') { await instance.willTeardown(); } }) ); // Once everybody has resolved willTeardown, we know there are no more // inter-instance functions that will run, so we can destroy // everything. await Promise.all( [...this.cache.values()].map(async ({ instance }) => { if (typeof instance?.teardown === 'function') { await instance.teardown(); } }) ); })() ); } await this.tearingDown.promise; } } class CacheEntry { private deferredPartial: Deferred<void> | undefined; private deferredPromise: Deferred<void> | undefined; private deferredInjections: Map<string, Deferred<void>> = new Map(); constructor(private identityKey: CacheKey, readonly instance: any, private injections: PendingInjections) {} // resolves when this CacheEntry is fully ready to be used get promise(): Promise<void> { if (!this.deferredPromise) { this.deferredPromise = new Deferred(); this.deferredPromise.fulfill(this.prepareSubgraph()); } return this.deferredPromise.promise; } private async prepareSubgraph(): Promise<void> { let subgraph = this.subgraph(); await Promise.all([...subgraph].map((entry) => entry.partial)); for (let entry of subgraph) { for (let [name, pending] of entry.injections) { entry.installInjection(name, pending); } } } private installInjection(name: string, pending: PendingInjection) { if (pending.isReady) { return; } let { opts, cacheEntry } = pending; if (!this.instance[opts.as] || this.instance[opts.as].injectionNotReadyYet !== name) { throw new Error( `To assign 'inject("${name}")' to a property other than '${name}' you must pass the 'as' argument to inject().` ); } this.instance[opts.as] = cacheEntry!.instance; pending.isReady = true; } @Memoize() private subgraph(): Set<CacheEntry> { let subgraph = new Set() as Set<CacheEntry>; let queue: CacheEntry[] = [this]; while (true) { let entry = queue.shift(); if (!entry) { break; } subgraph.add(entry); for (let { cacheEntry } of entry.injections.values()) { if (!subgraph.has(cacheEntry!)) { queue.push(cacheEntry!); } } } return subgraph; } // resolves when the instance's ready hook has run. This implies that any // forced-eager injections that ready() uses will be present, but does *not* // imply that all other injections are present. get partial(): Promise<void> { if (!this.deferredPartial) { this.deferredPartial = new Deferred(); this.deferredPartial.fulfill(this.runReady()); } return this.deferredPartial.promise; } async prepareInjectionEagerly(name: string): Promise<void> { let cached = this.deferredInjections.get(name); if (cached) { await cached.promise; return; } cached = new Deferred(); this.deferredInjections.set(name, cached); cached.fulfill( (async () => { let pending = this.injections.get(name)!; if (pending.cacheEntry?.subgraph().has(this)) { throw new Error( `circular dependency: ${this.identityKey} tries to eagerly inject ${name}, which depends on ${this.identityKey}` ); } await pending.cacheEntry!.promise; this.installInjection(name, pending); })() ); await cached.promise; } private async runReady(): Promise<void> { if (typeof this.instance.ready === 'function') { await this.instance.ready(); } } } type CacheKey = string; let mappings = new WeakMap() as WeakMap<Registry, Map<string, Factory<any>>>; let pendingInstantiationStack = [] as PendingInjections[]; let ownership = new WeakMap() as WeakMap<any, Container>; export class Registry { constructor() { mappings.set(this, new Map()); } register<T>(name: string, factory: Factory<T>) { // non-null because our constructor initializes weakmap. mappings.get(this)!.set(name, factory); } } // This exists to be extended by authors of services // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface KnownServices {} interface InjectOptions { // if you are storing your injection in a property whose name doesn't match // the key it was registered under, you need to pass the property name here. as: string; } interface PendingInjection { opts: InjectOptions; cacheEntry: CacheEntry | null; isReady: boolean; } type PendingInjections = Map<string, PendingInjection>; /* Dependency Injection HOWTO import { inject, injectionReady } from '@cardstack/hub/di/dependency-injection'; class YourClass { // the default pattern is to use the same name for your local property as // the name of the service you're looking up. thing = inject('thing'); // If you want a different local property name, you need to tell inject // about it. We can't see it otherwise. weirdName = inject('something', { as: 'weirdName' }); constructor() { // your injections aren't available in the constructor! If you try // to access them here you'll find they are just placeholder objects. } someMethod() { // they are available everywhere else (except the ready hook, see below) return this.thing; } async ready() { // if you have asynchronous setup work to do, implement a `ready` hook. // Other objects that inject you won't see you until after your ready resolves. // The Container will call your ready() method before returning your // instance to anyone. // ready is *not* guaranteed to have access to the injections, because // that would require us to make all of them eager, which makes dependency // cycles into deadlock even when they're not actually needed during ready(). // // Instead, if you want to use an injection during ready() you need to use // await injectionReady: await injectionReady(this, 'thing'); this.thing.doStuff(); } } // This is the type declaration for what other people will get // when they inject you or do container.lookup(). Notice that you // may want to register a slightly different interface here than // your actual implementation, because others will only see you after // ready() has resolved, which may make your public interface cleaner. declare module "@cardstack/hub/di/dependency-injection" { interface KnownServices { yourClass: YourClass; } } */ export function inject<K extends keyof KnownServices>(name: K, opts?: InjectOptions): KnownServices[K]; export function inject(name: string, opts?: Partial<InjectOptions>): unknown { let pending = pendingInstantiationStack[0]; if (!pending) { throw new Error(`Tried to directly instantiate an object with injections. Look it up in the container instead.`); } let completeOpts = Object.assign( { as: name, }, opts ); pending.set(name, { opts: completeOpts, cacheEntry: null, isReady: false }); return { injectionNotReadyYet: name }; } export function getOwner(obj: any): Container { let container = ownership.get(obj); if (!container) { throw new Error(`Tried to getOwner of an object that didn't come from the container`); } return container; } export async function injectionReady(instance: any, name: string): Promise<void> { let container = getOwner(instance); // accessing a private member variable let cache: Container['cache'] = (container as any).cache; for (let entry of cache.values()) { if (entry.instance === instance) { await entry.prepareInjectionEagerly(name); return; } } }
the_stack
const AlTrackballState = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }; // Mouse button binds to actions const AlMouseButtons = { ROTATE: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT }; export class AlTrackballControls extends THREE.EventDispatcher { public object; public target: THREE.Vector3; public get up0(): THREE.Vector3 { return this._up0.clone(); } // tslint:disable-next-line: no-any public domElement: any; // API public enabled: boolean; public screen = { left: 0, top: 0, width: 0, height: 0 }; public rotateSpeed: number; public zoomSpeed: number; public panSpeed: number; public noRotate: boolean; public noZoom: boolean; public noPan: boolean; public staticMoving: boolean; public dynamicDampingFactor: number; public minDistance: number; public maxDistance: number; // =============================== private EPS: number; private _lastPosition: THREE.Vector3; private _state: number; private _eye: THREE.Vector3; private _movePrev: THREE.Vector2; private _moveCurr: THREE.Vector2; private _lastAxis: THREE.Vector3; private _lastAngle: number; private _zoomStart: THREE.Vector2; private _zoomEnd: THREE.Vector2; private _touchZoomDistanceStart: number; private _touchZoomDistanceEnd: number; private _panStart: THREE.Vector2; private _panEnd: THREE.Vector2; private _target0: THREE.Vector3; private _position0: THREE.Vector3; private _up0: THREE.Vector3; // events private _changeEvent = { type: "change" }; private _startEvent = { type: "start" }; private _endEvent = { type: "end" }; // tslint:disable-next-line: no-any constructor(object: any, domElement: HTMLElement | Document) { super(); this.object = object; this.domElement = domElement !== undefined ? domElement : document; // ======== API ======== this.enabled = true; this.screen = { left: 0, top: 0, width: 0, height: 0 }; this.rotateSpeed = 1.0; this.zoomSpeed = 1.2; this.panSpeed = 0.3; this.noRotate = false; this.noZoom = false; this.noPan = false; this.staticMoving = false; this.dynamicDampingFactor = 0.2; this.minDistance = 0; this.maxDistance = Infinity; // ===================== // ===== internals ===== // for reset this.target = new THREE.Vector3(); this.EPS = 0.000001; this._lastPosition = new THREE.Vector3(); this._state = AlTrackballState.NONE; this._eye = new THREE.Vector3(); this._movePrev = new THREE.Vector2(); this._moveCurr = new THREE.Vector2(); this._lastAxis = new THREE.Vector3(); this._lastAngle = 0; this._zoomStart = new THREE.Vector2(); this._zoomEnd = new THREE.Vector2(); this._touchZoomDistanceStart = 0; this._touchZoomDistanceEnd = 0; this._panStart = new THREE.Vector2(); this._panEnd = new THREE.Vector2(); this._target0 = this.target.clone(); this._position0 = this.object.position.clone(); this._up0 = this.object.up.clone(); this._bindMethods(); this._addListeners(); this.update(); } private _bindMethods() { this._mouseDown = this._mouseDown.bind(this); this._mouseMove = this._mouseMove.bind(this); this._mouseUp = this._mouseUp.bind(this); this._mouseWheel = this._mouseWheel.bind(this); this._touchStart = this._touchStart.bind(this); this._touchEnd = this._touchEnd.bind(this); this._touchMove = this._touchMove.bind(this); this._resize = this._resize.bind(this); } private _addListeners() { this.domElement.addEventListener("mousedown", this._mouseDown, { capture: false, once: false, passive: true }); window.addEventListener("mousemove", this._mouseMove, { capture: false, once: false, passive: true }); window.addEventListener("mouseup", this._mouseUp, { capture: false, once: false, passive: true }); this.domElement.addEventListener("wheel", this._mouseWheel, { capture: false, once: false, passive: false }); this.domElement.addEventListener("touchstart", this._touchStart, { capture: false, once: false, passive: true }); window.addEventListener("touchend", this._touchEnd, { capture: false, once: false, passive: true }); window.addEventListener("touchmove", this._touchMove, { capture: false, once: false, passive: true }); } private _mouseDown(event: MouseEvent) { if (this.enabled === false) { return; } if (this._state === AlTrackballState.NONE) { switch (event.button) { case AlMouseButtons.ROTATE: this._state = AlTrackballState.ROTATE; if (!this.noRotate) { this._moveCurr.copy( this._getMouseOnCircle(event.pageX, event.pageY) ); this._movePrev.copy(this._moveCurr); } break; case AlMouseButtons.ZOOM: this._state = AlTrackballState.ZOOM; if (!this.noZoom) { this._zoomStart.copy( this._getMouseOnScreen(event.pageX, event.pageY) ); this._zoomEnd.copy(this._zoomStart); } break; case AlMouseButtons.PAN: this._state = AlTrackballState.PAN; if (!this.noPan) { this._panStart.copy( this._getMouseOnScreen(event.pageX, event.pageY) ); this._panEnd.copy(this._panStart); } break; default: this._state = AlTrackballState.NONE; } } this.dispatchEvent(this._startEvent); this.update(); } private _mouseMove(event: MouseEvent) { if (this.enabled === false) { return; } if (this._state === AlTrackballState.ROTATE && !this.noRotate) { this._movePrev.copy(this._moveCurr); this._moveCurr.copy(this._getMouseOnCircle(event.pageX, event.pageY)); } else if (this._state === AlTrackballState.ZOOM && !this.noZoom) { this._zoomEnd.copy(this._getMouseOnScreen(event.pageX, event.pageY)); } else if (this._state === AlTrackballState.PAN && !this.noPan) { this._panEnd.copy(this._getMouseOnScreen(event.pageX, event.pageY)); } this.update(); } private _mouseUp(_event: MouseEvent) { if (this.enabled === false) { return; } this._state = AlTrackballState.NONE; this.dispatchEvent(this._endEvent); this.update(); } private _mouseWheel(event: WheelEvent) { if (this.enabled === false || this.noZoom === true) { return; } event.preventDefault(); event.stopPropagation(); switch (event.deltaMode) { case 2: // Zoom in pages this._zoomStart.y -= event.deltaY * 0.025; break; case 1: // Zoom in lines this._zoomStart.y -= event.deltaY * 0.01; break; default: // undefined, 0, assume pixels this._zoomStart.y -= event.deltaY * 0.00025; break; } this.dispatchEvent(this._startEvent); this.dispatchEvent(this._endEvent); this.update(); } private _touchStart(event: TouchEvent) { if (this.enabled === false) { return; } switch (event.touches.length) { case 1: this._state = AlTrackballState.TOUCH_ROTATE; this._moveCurr.copy( this._getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY) ); this._movePrev.copy(this._moveCurr); break; default: // 2 or more this._state = AlTrackballState.TOUCH_ZOOM_PAN; const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy ); const x = (event.touches[0].pageX + event.touches[1].pageX) / 2; const y = (event.touches[0].pageY + event.touches[1].pageY) / 2; this._panStart.copy(this._getMouseOnScreen(x, y)); this._panEnd.copy(this._panStart); break; } this.dispatchEvent(this._startEvent); this.update(); } private _touchEnd(event: TouchEvent) { if (this.enabled === false) { return; } switch (event.touches.length) { case 0: this._state = AlTrackballState.NONE; break; case 1: this._state = AlTrackballState.TOUCH_ROTATE; this._moveCurr.copy( this._getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY) ); this._movePrev.copy(this._moveCurr); break; default: { break; } } this.dispatchEvent(this._endEvent); this.update(); } private _touchMove(event: TouchEvent) { if (this.enabled === false) { return; } switch (event.touches.length) { case 1: this._movePrev.copy(this._moveCurr); this._moveCurr.copy( this._getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY) ); break; default: // 2 or more const dx = event.touches[0].pageX - event.touches[1].pageX; const dy = event.touches[0].pageY - event.touches[1].pageY; this._touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy); const x = (event.touches[0].pageX + event.touches[1].pageX) / 2; const y = (event.touches[0].pageY + event.touches[1].pageY) / 2; this._panEnd.copy(this._getMouseOnScreen(x, y)); break; } this.update(); } public _resize() { if (this.domElement === document) { this.screen.left = 0; this.screen.top = 0; this.screen.width = window.innerWidth; this.screen.height = window.innerHeight; } else { const box = this.domElement.getBoundingClientRect(); // adjustments come from similar code in the jquery offset() function const d = this.domElement.ownerDocument.documentElement; this.screen.left = box.left + window.pageXOffset - d.clientLeft; this.screen.top = box.top + window.pageYOffset - d.clientTop; this.screen.width = box.width; this.screen.height = box.height; } } private _getMouseOnScreen(pageX: number, pageY: number): THREE.Vector2 { const vector = new THREE.Vector2(); vector.set( (pageX - this.screen.left) / this.screen.width, (pageY - this.screen.top) / this.screen.height ); return vector; } private _getMouseOnCircle(pageX: number, pageY: number): THREE.Vector2 { const vector = new THREE.Vector2(); vector.set( (pageX - this.screen.width * 0.5 - this.screen.left) / (this.screen.width * 0.5), (this.screen.height + 2 * (this.screen.top - pageY)) / this.screen.width // screen.width intentional ); return vector; } private _rotateCamera() { const axis = new THREE.Vector3(); const quaternion = new THREE.Quaternion(); const eyeDirection = new THREE.Vector3(); const objectUpDirection = new THREE.Vector3(); const objectSidewaysDirection = new THREE.Vector3(); const moveDirection = new THREE.Vector3(); let angle; moveDirection.set( this._moveCurr.x - this._movePrev.x, this._moveCurr.y - this._movePrev.y, 0 ); angle = moveDirection.length(); if (angle) { this._eye.copy(this.object.position).sub(this.target); eyeDirection.copy(this._eye).normalize(); objectUpDirection.copy(this.object.up).normalize(); objectSidewaysDirection .crossVectors(objectUpDirection, eyeDirection) .normalize(); objectUpDirection.setLength(this._moveCurr.y - this._movePrev.y); objectSidewaysDirection.setLength(this._moveCurr.x - this._movePrev.x); moveDirection.copy(objectUpDirection.add(objectSidewaysDirection)); axis.crossVectors(moveDirection, this._eye).normalize(); angle *= this.rotateSpeed; quaternion.setFromAxisAngle(axis, angle); this._eye.applyQuaternion(quaternion); this.object.up.applyQuaternion(quaternion); this._lastAxis.copy(axis); this._lastAngle = angle; } else if (!this.staticMoving && this._lastAngle) { this._lastAngle *= Math.sqrt(1.0 - this.dynamicDampingFactor); this._eye.copy(this.object.position).sub(this.target); quaternion.setFromAxisAngle(this._lastAxis, this._lastAngle); this._eye.applyQuaternion(quaternion); this.object.up.applyQuaternion(quaternion); } this._movePrev.copy(this._moveCurr); } private _zoomCamera() { let factor; if (this._state === AlTrackballState.TOUCH_ZOOM_PAN) { factor = this._touchZoomDistanceStart / this._touchZoomDistanceEnd; this._touchZoomDistanceStart = this._touchZoomDistanceEnd; this._eye.multiplyScalar(factor); } else { factor = 1.0 + (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed; if (factor !== 1.0 && factor > 0.0) { this._eye.multiplyScalar(factor); } if (this.staticMoving) { this._zoomStart.copy(this._zoomEnd); } else { this._zoomStart.y += (this._zoomEnd.y - this._zoomStart.y) * this.dynamicDampingFactor; } } } private _panCamera() { const mouseChange = new THREE.Vector2(); const objectUp = new THREE.Vector3(); const pan = new THREE.Vector3(); mouseChange.copy(this._panEnd).sub(this._panStart); if (mouseChange.lengthSq()) { mouseChange.multiplyScalar(this._eye.length() * this.panSpeed); pan .copy(this._eye) .cross(this.object.up) .setLength(mouseChange.x); pan.add(objectUp.copy(this.object.up).setLength(mouseChange.y)); this.object.position.add(pan); this.target.add(pan); if (this.staticMoving) { this._panStart.copy(this._panEnd); } else { this._panStart.add( mouseChange .subVectors(this._panEnd, this._panStart) .multiplyScalar(this.dynamicDampingFactor) ); } } } private _checkDistances() { if (!this.noZoom || !this.noPan) { if (this._eye.lengthSq() > this.maxDistance * this.maxDistance) { this.object.position.addVectors( this.target, this._eye.setLength(this.maxDistance) ); this._zoomStart.copy(this._zoomEnd); } if (this._eye.lengthSq() < this.minDistance * this.minDistance) { this.object.position.addVectors( this.target, this._eye.setLength(this.minDistance) ); this._zoomStart.copy(this._zoomEnd); } } } public update() { this._eye.subVectors(this.object.position, this.target); if (!this.noRotate) { this._rotateCamera(); } if (!this.noZoom) { this._zoomCamera(); } if (!this.noPan) { this._panCamera(); } this.object.position.addVectors(this.target, this._eye); this._checkDistances(); this.object.lookAt(this.target); if (this._lastPosition.distanceToSquared(this.object.position) > this.EPS) { this.dispatchEvent(this._changeEvent); this._lastPosition.copy(this.object.position); } } public reset() { this._state = AlTrackballState.NONE; this.target.copy(this._target0); this.object.position.copy(this._position0); this.object.up.copy(this._up0); this._eye.subVectors(this.object.position, this.target); this.object.lookAt(this.target); this.dispatchEvent(this._changeEvent); this._lastPosition.copy(this.object.position); } public dispose() { this._removeListeners(); } private _removeListeners() { this.domElement.removeEventListener("mousedown", this._mouseDown, false); window.removeEventListener("mousemove", this._mouseMove, false); window.removeEventListener("mouseup", this._mouseUp, false); this.domElement.removeEventListener("wheel", this._mouseWheel, false); this.domElement.removeEventListener("touchstart", this._touchStart, false); window.removeEventListener("touchend", this._touchEnd, false); window.removeEventListener("touchmove", this._touchMove, false); } }
the_stack
import { Task } from 'klasa'; import { Bank, Monsters } from 'oldschooljs'; import { Emoji, Events } from '../../lib/constants'; import { defaultFarmingContract, PatchTypes } from '../../lib/minions/farming'; import { FarmingContract } from '../../lib/minions/farming/types'; import { ClientSettings } from '../../lib/settings/types/ClientSettings'; import { UserSettings } from '../../lib/settings/types/UserSettings'; import { calcVariableYield } from '../../lib/skilling/functions/calcsFarming'; import Farming from '../../lib/skilling/skills/farming'; import { SkillsEnum } from '../../lib/skilling/types'; import { ItemBank } from '../../lib/types'; import { FarmingActivityTaskOptions } from '../../lib/types/minions'; import { bankHasItem, channelIsSendable, rand, roll } from '../../lib/util'; import chatHeadImage from '../../lib/util/chatHeadImage'; import { handleTripFinish } from '../../lib/util/handleTripFinish'; import itemID from '../../lib/util/itemID'; export default class extends Task { async run(data: FarmingActivityTaskOptions) { const { plantsName, patchType, getPatchType, quantity, upgradeType, payment, userID, channelID, planting, duration, currentDate, autoFarmed } = data; const user = await this.client.fetchUser(userID); const currentFarmingLevel = user.skillLevel(SkillsEnum.Farming); const currentWoodcuttingLevel = user.skillLevel(SkillsEnum.Woodcutting); let baseBonus = 1; let bonusXP = 0; let plantXp = 0; let harvestXp = 0; let compostXp = 0; let checkHealthXp = 0; let rakeXp = 0; let woodcuttingXp = 0; let payStr = ''; let wcStr = ''; let rakeStr = ''; let plantingStr = ''; const infoStr: string[] = []; let alivePlants = 0; let chopped = false; let farmingXpReceived = 0; let chanceOfDeathReduction = 1; let cropYield = 0; let lives = 3; let bonusXpMultiplier = 0; let farmersPiecesCheck = 0; let loot: ItemBank = {}; const plant = Farming.Plants.find(plant => plant.name === plantsName); const userBank = user.settings.get(UserSettings.Bank); if ( bankHasItem(userBank, itemID('Magic secateurs')) || user.hasItemEquippedAnywhere(itemID('Magic secateurs')) ) { baseBonus += 0.1; } if ( bankHasItem(userBank, itemID('Farming cape')) || bankHasItem(userBank, itemID('Farming cape(t)')) || user.hasItemEquippedAnywhere(itemID('Farming cape')) || user.hasItemEquippedAnywhere(itemID('Farming cape(t)')) ) { baseBonus += 0.05; } if (upgradeType === 'compost') compostXp = 18; if (upgradeType === 'supercompost') compostXp = 26; if (upgradeType === 'ultracompost') compostXp = 36; // initial lives = 3. Compost, super, ultra, increases lives by 1 respectively and reduces chanceofdeath as well. // Payment = 0% chance of death if (patchType.lastUpgradeType === 'compost') { lives += 1; chanceOfDeathReduction = 1 / 2; } else if (patchType.lastUpgradeType === 'supercompost') { lives += 2; chanceOfDeathReduction = 1 / 5; } else if (patchType.lastUpgradeType === 'ultracompost') { lives += 3; chanceOfDeathReduction = 1 / 10; } if (patchType.lastPayment) chanceOfDeathReduction = 0; // check bank for farmer's items if (user.hasItemEquippedOrInBank("Farmer's strawhat")) { bonusXpMultiplier += 0.004; farmersPiecesCheck++; } if (user.hasItemEquippedOrInBank("Farmer's jacket") || user.hasItemEquippedOrInBank("Farmer's shirt")) { bonusXpMultiplier += 0.008; farmersPiecesCheck++; } if (user.hasItemEquippedOrInBank("Farmer's boro trousers")) { bonusXpMultiplier += 0.006; farmersPiecesCheck++; } if (user.hasItemEquippedOrInBank("Farmer's boots")) { bonusXpMultiplier += 0.002; farmersPiecesCheck++; } if (farmersPiecesCheck === 4) bonusXpMultiplier += 0.005; if (!patchType.patchPlanted) { if (!plant) { this.client.wtf(new Error(`${user.sanitizedName}'s new patch had no plant found.`)); return; } rakeXp = quantity * 4 * 3; // # of patches * exp per weed * # of weeds plantXp = quantity * (plant.plantXp + compostXp); farmingXpReceived = plantXp + harvestXp + rakeXp; loot[itemID('Weeds')] = quantity * 3; let str = `${user}, ${user.minionName} finished raking ${quantity} patches and planting ${quantity}x ${ plant.name }.\n\nYou received ${plantXp.toLocaleString()} XP from planting and ${rakeXp.toLocaleString()} XP from raking for a total of ${farmingXpReceived.toLocaleString()} Farming XP.`; bonusXP += Math.floor(farmingXpReceived * bonusXpMultiplier); if (bonusXP > 0) { str += ` You received an additional ${bonusXP.toLocaleString()} in bonus XP.`; } await user.addXP({ skillName: SkillsEnum.Farming, amount: Math.floor(farmingXpReceived + bonusXP) }); const newLevel = user.skillLevel(SkillsEnum.Farming); if (newLevel > currentFarmingLevel) { str += `\n${user.minionName}'s Farming level is now ${newLevel}!`; } if (Object.keys(loot).length > 0) { str += `\n\nYou received: ${new Bank(loot)}.`; } await this.client.settings.update( ClientSettings.EconomyStats.FarmingLootBank, new Bank(this.client.settings.get(ClientSettings.EconomyStats.FarmingLootBank)).add(loot).bank ); await user.addItemsToBank(loot, true); const updatePatches: PatchTypes.PatchData = { lastPlanted: plant.name, patchPlanted: true, plantTime: currentDate + duration, lastQuantity: quantity, lastUpgradeType: upgradeType, lastPayment: payment ?? false }; await user.settings.update(getPatchType, updatePatches); str += `\n\n${user.minionName} tells you to come back after your plants have finished growing!`; const channel = this.client.channels.cache.get(channelID); if (!channelIsSendable(channel)) return; handleTripFinish( this.client, user, channelID, str, autoFarmed ? ['m', [], true, 'autofarm'] : undefined, undefined, data, null ); } else if (patchType.patchPlanted) { const plantToHarvest = Farming.Plants.find(plant => plant.name === patchType.lastPlanted); if (!plantToHarvest) return; if (!plant) return; let quantityDead = 0; for (let i = 0; i < patchType.lastQuantity; i++) { for (let j = 0; j < plantToHarvest.numOfStages - 1; j++) { const deathRoll = Math.random(); if (deathRoll < Math.floor(plantToHarvest.chanceOfDeath * chanceOfDeathReduction) / 128) { quantityDead += 1; break; } } } alivePlants = patchType.lastQuantity - quantityDead; if (planting) { plantXp = quantity * (plant.plantXp + compostXp); } checkHealthXp = alivePlants * plantToHarvest.checkXp; if (plantToHarvest.givesCrops) { if (!plantToHarvest.outputCrop) return; if (plantToHarvest.variableYield) { cropYield = calcVariableYield( plantToHarvest, patchType.lastUpgradeType, currentFarmingLevel, alivePlants ); } else if (plantToHarvest.fixedOutput) { if (!plantToHarvest.fixedOutputAmount) return; cropYield = plantToHarvest.fixedOutputAmount; } else { const plantChanceFactor = Math.floor( Math.floor( plantToHarvest.chance1 + (plantToHarvest.chance99 - plantToHarvest.chance1) * ((user.skillLevel(SkillsEnum.Farming) - 1) / 98) ) * baseBonus ) + 1; const chanceToSaveLife = (plantChanceFactor + 1) / 256; if (plantToHarvest.seedType === 'bush') lives = 4; cropYield = 0; const livesHolder = lives; for (let k = 0; k < alivePlants; k++) { lives = livesHolder; for (let n = 0; lives > 0; n++) { if (Math.random() > chanceToSaveLife) { lives -= 1; cropYield += 1; } else { cropYield += 1; } } } } if (quantity > patchType.lastQuantity) { loot[plantToHarvest.outputCrop] = cropYield; loot[itemID('Weeds')] = quantity - patchType.lastQuantity; } else { loot[plantToHarvest.outputCrop] = cropYield; } if (plantToHarvest.name === 'Limpwurt') { harvestXp = plantToHarvest.harvestXp * alivePlants; } else { harvestXp = cropYield * plantToHarvest.harvestXp; } } if (plantToHarvest.needsChopForHarvest) { if (!plantToHarvest.treeWoodcuttingLevel) return; if (currentWoodcuttingLevel >= plantToHarvest.treeWoodcuttingLevel) { chopped = true; } else { await user.settings.sync(true); const GP = user.settings.get(UserSettings.GP); const gpToCutTree = plantToHarvest.seedType === 'redwood' ? 2000 * alivePlants : 200 * alivePlants; if (GP < gpToCutTree) { throw `You do not have the required woodcutting level or enough GP to clear your patches, in order to be able to plant more. You need ${gpToCutTree} GP.`; } else { payStr = `*You did not have the woodcutting level required, so you paid a nearby farmer ${gpToCutTree} GP to remove the previous trees.*`; await user.removeGP(gpToCutTree); } harvestXp = 0; } if (plantToHarvest.givesLogs && chopped) { if (!plantToHarvest.outputLogs) return; if (!plantToHarvest.woodcuttingXp) return; const amountOfLogs = rand(5, 10) * alivePlants; loot[plantToHarvest.outputLogs] = amountOfLogs; if (plantToHarvest.outputRoots) { loot[plantToHarvest.outputRoots] = rand(1, 4) * alivePlants; } woodcuttingXp += amountOfLogs * plantToHarvest.woodcuttingXp; wcStr = ` You also received ${woodcuttingXp.toLocaleString()} Woodcutting XP.`; harvestXp = 0; } else if (plantToHarvest.givesCrops && chopped) { if (!plantToHarvest.outputCrop) return; loot[plantToHarvest.outputCrop] = cropYield * alivePlants; harvestXp = cropYield * alivePlants * plantToHarvest.harvestXp; } } if (quantity > patchType.lastQuantity) { loot[itemID('Weeds')] = (quantity - patchType.lastQuantity) * 3; rakeXp = (quantity - patchType.lastQuantity) * 3 * 4; rakeStr += ` ${rakeXp} XP for raking, `; } farmingXpReceived = plantXp + harvestXp + checkHealthXp + rakeXp; let deathStr = ''; if (quantityDead > 0) { deathStr = ` During your harvest, you found that ${quantityDead}/${patchType.lastQuantity} of your plants died.`; } if (planting) { plantingStr = `${user}, ${user.minionName} finished planting ${quantity}x ${plant.name} and `; } else { plantingStr = `${user}, ${user.minionName} finished `; } infoStr.push( `${plantingStr}harvesting ${patchType.lastQuantity}x ${ plantToHarvest.name }.${deathStr}${payStr}\n\nYou received ${plantXp.toLocaleString()} XP for planting, ${rakeStr}${harvestXp.toLocaleString()} XP for harvesting, and ${checkHealthXp.toLocaleString()} XP for checking health for a total of ${farmingXpReceived.toLocaleString()} Farming XP.${wcStr}` ); bonusXP += Math.floor(farmingXpReceived * bonusXpMultiplier); if (bonusXP > 0) { infoStr.push( `\nYou received an additional ${bonusXP.toLocaleString()} bonus XP from your farmer's outfit.` ); } await user.addXP({ skillName: SkillsEnum.Farming, amount: Math.floor(farmingXpReceived + bonusXP) }); await user.addXP({ skillName: SkillsEnum.Woodcutting, amount: Math.floor(woodcuttingXp) }); const newFarmingLevel = user.skillLevel(SkillsEnum.Farming); const newWoodcuttingLevel = user.skillLevel(SkillsEnum.Woodcutting); if (newFarmingLevel > currentFarmingLevel) { infoStr.push(`\n${user.minionName}'s Farming level is now ${newFarmingLevel}!`); } if (newWoodcuttingLevel > currentWoodcuttingLevel) { infoStr.push(`\n\n${user.minionName}'s Woodcutting level is now ${newWoodcuttingLevel}!`); } let tangleroot = false; if (plantToHarvest.seedType === 'hespori') { await user.incrementMonsterScore(Monsters.Hespori.id); const hesporiLoot = Monsters.Hespori.kill(1, { farmingLevel: currentFarmingLevel }); loot = hesporiLoot.bank; if (hesporiLoot.amount('Tangleroot')) tangleroot = true; } else if ( patchType.patchPlanted && plantToHarvest.petChance && alivePlants > 0 && roll((plantToHarvest.petChance - user.skillLevel(SkillsEnum.Farming) * 25) / alivePlants) ) { loot[itemID('Tangleroot')] = 1; tangleroot = true; } if (plantToHarvest.seedType !== 'hespori') { let hesporiSeeds = 0; for (let i = 0; i < alivePlants; i++) { if (roll(plantToHarvest.petChance / 500)) { hesporiSeeds++; } } if (hesporiSeeds > 0) loot[itemID('Hespori seed')] = hesporiSeeds; } if (tangleroot) { infoStr.push('\n```diff'); infoStr.push("\n- You have a funny feeling you're being followed..."); infoStr.push('```'); this.client.emit( Events.ServerNotification, `${Emoji.Farming} **${user.username}'s** minion, ${user.minionName}, just received a Tangleroot while farming ${patchType.lastPlanted} at level ${currentFarmingLevel} Farming!` ); } let updatePatches: PatchTypes.PatchData = { lastPlanted: null, patchPlanted: false, plantTime: 0, lastQuantity: 0, lastUpgradeType: null, lastPayment: false }; if (planting) { updatePatches = { lastPlanted: plant.name, patchPlanted: true, plantTime: currentDate + duration, lastQuantity: quantity, lastUpgradeType: upgradeType, lastPayment: payment ? payment : false }; } await user.settings.update(getPatchType, updatePatches); const currentContract = user.settings.get(UserSettings.Minion.FarmingContract) ?? { ...defaultFarmingContract }; const { contractsCompleted } = currentContract; let janeMessage = false; if (currentContract.hasContract && plantToHarvest.name === currentContract.plantToGrow && alivePlants > 0) { const farmingContractUpdate: FarmingContract = { hasContract: false, difficultyLevel: null, plantToGrow: currentContract.plantToGrow, plantTier: currentContract.plantTier, contractsCompleted: contractsCompleted + 1 }; user.settings.update(UserSettings.Minion.FarmingContract, farmingContractUpdate); loot[itemID('Seed pack')] = 1; janeMessage = true; } if (Object.keys(loot).length > 0) { infoStr.push(`\nYou received: ${new Bank(loot)}.`); } if (!planting) { infoStr.push('\nThe patches have been cleared. They are ready to have new seeds planted.'); } else { infoStr.push(`\n${user.minionName} tells you to come back after your plants have finished growing!`); } await this.client.settings.update( ClientSettings.EconomyStats.FarmingLootBank, new Bank(this.client.settings.get(ClientSettings.EconomyStats.FarmingLootBank)).add(loot).bank ); await user.addItemsToBank(loot, true); handleTripFinish( this.client, user, channelID, infoStr.join('\n'), autoFarmed ? ['m', [], true, 'autofarm'] : undefined, janeMessage ? await chatHeadImage({ content: `You've completed your contract and I have rewarded you with 1 Seed pack. Please open this Seed pack before asking for a new contract!\nYou have completed ${ contractsCompleted + 1 } farming contracts.`, head: 'jane' }) : undefined, data, null ); } } }
the_stack
import { _Image, _ScrollView, _Text, _View, DefaultSectionT, FlatListProps, NativeSyntheticEvent, SectionListProps } from 'react-native'; import { nanoid } from 'nanoid/non-secure'; import * as React from 'react'; type AnimatedValue = Value; type AnimatedValueXY = ValueXY; class Animated { // Internal class, no public API. } class AnimatedWithChildren extends Animated { // Internal class, no public API. } class AnimatedInterpolation extends AnimatedWithChildren { interpolate(config: InterpolationConfigType): AnimatedInterpolation { return new AnimatedInterpolation(); } } type ExtrapolateType = 'extend' | 'identity' | 'clamp'; type InterpolationConfigType = { inputRange: number[]; outputRange: number[] | string[]; easing?: (input: number) => number; extrapolate?: ExtrapolateType; extrapolateLeft?: ExtrapolateType; extrapolateRight?: ExtrapolateType; }; type ValueListenerCallback = (state: { value: number }) => void; /** * Standard value for driving animations. One `Animated.Value` can drive * multiple properties in a synchronized fashion, but can only be driven by one * mechanism at a time. Using a new mechanism (e.g. starting a new animation, * or calling `setValue`) will stop any previous ones. */ export class Value extends AnimatedWithChildren { value: number; offset: number; private changeListeners = {}; constructor(value: number) { super(); this.value = value; } /** * Directly set the value. This will stop any animations running on the value * and update all the bound properties. */ setValue(value: number): void { this.value = value; } /** * Sets an offset that is applied on top of whatever value is set, whether via * `setValue`, an animation, or `Animated.event`. Useful for compensating * things like the start of a pan gesture. */ setOffset(offset: number): void { this.offset = offset; } /** * Merges the offset value into the base value and resets the offset to zero. * The final output of the value is unchanged. */ flattenOffset(): void { this.value += this.offset; this.offset = 0; } /** * Sets the offset value to the base value, and resets the base value to zero. * The final output of the value is unchanged. */ extractOffset(): void { this.offset = this.value; this.value = 0; } /** * Adds an asynchronous listener to the value so you can observe updates from * animations. This is useful because there is no way to * synchronously read the value because it might be driven natively. */ addListener(callback: ValueListenerCallback): string { const id = nanoid(); this.changeListeners[id] = id; return id; } removeListener(id: string): void { delete this.changeListeners[id]; } removeAllListeners(): void { Object.keys(this.changeListeners).forEach(this.removeListener); } /** * Stops any running animation or tracking. `callback` is invoked with the * final value after stopping the animation, which is useful for updating * state to match the animation position with layout. */ stopAnimation(callback?: (value: number) => void): void {} /** * Interpolates the value before updating the property, e.g. mapping 0-1 to * 0-10. */ interpolate(config: InterpolationConfigType): AnimatedInterpolation { return new AnimatedInterpolation(); } } type ValueXYListenerCallback = (value: { x: number; y: number }) => void; /** * 2D Value for driving 2D animations, such as pan gestures. Almost identical * API to normal `Animated.Value`, but multiplexed. Contains two regular * `Animated.Value`s under the hood. */ export class ValueXY extends AnimatedWithChildren { x: AnimatedValue; y: AnimatedValue; private offsetX: number; private offsetY: number; private changeListeners: {}; constructor(valueIn?: { x: number | AnimatedValue; y: number | AnimatedValue }) { super(); this.x = typeof valueIn.x === 'number' ? new Value(valueIn.x) : valueIn.x; this.y = typeof valueIn.y === 'number' ? new Value(valueIn.y) : valueIn.y; } setValue(value: { x: number; y: number }): void { this.x = new Value(value.x); this.y = new Value(value.y); } setOffset(offset: { x: number; y: number }): void { this.offsetX = offset.x; this.offsetY = offset.y; } flattenOffset(): void { this.x.setValue(this.x.value + this.offsetX); this.y.setValue(this.y.value + this.offsetY); this.offsetX = 0; this.offsetY = 0; } extractOffset(): void { this.offsetX = this.x.value; this.offsetY = this.y.value; this.x.setValue(0); this.y.setValue(0); } stopAnimation(callback?: (value: { x: number; y: number }) => void): void {} addListener(callback: ValueXYListenerCallback): string { const id = nanoid(); this.changeListeners[id] = id; return id; } removeListener(id: string): void { delete this.changeListeners[id]; } /** * Converts `{x, y}` into `{left, top}` for use in style, e.g. * *```javascript * style={this.state.anim.getLayout()} *``` */ getLayout(): { [key: string]: AnimatedValue } { return { left: this.x, top: this.y }; } /** * Converts `{x, y}` into a useable translation transform, e.g. * *```javascript * style={{ * transform: this.state.anim.getTranslateTransform() * }} *``` */ getTranslateTransform(): [{ translateX: AnimatedValue }, { translateY: AnimatedValue }] { return [ { translateX: this.x }, { translateY: this.y } ]; } } type EndResult = { finished: boolean }; type EndCallback = (result: EndResult) => void; export interface CompositeAnimation { /** * Animations are started by calling start() on your animation. * start() takes a completion callback that will be called when the * animation is done or when the animation is done because stop() was * called on it before it could finish. * * @param callback - Optional function that will be called * after the animation finished running normally or when the animation * is done because stop() was called on it before it could finish * * @example * Animated.timing({}).start(({ finished }) => { * // completion callback * }); */ start: (callback?: EndCallback) => void; /** * Stops any running animation. */ stop: () => void; /** * Stops any running animation and resets the value to its original. */ reset: () => void; } class EmptyCompositeAnimation implements CompositeAnimation { reset(): void {} start(callback: EndCallback | undefined): void {} stop(): void {} } interface AnimationConfig { isInteraction?: boolean; useNativeDriver: boolean; } /** * Animates a value from an initial velocity to zero based on a decay * coefficient. */ export function decay(value: AnimatedValue | AnimatedValueXY, config: DecayAnimationConfig): CompositeAnimation { return new EmptyCompositeAnimation(); } interface DecayAnimationConfig extends AnimationConfig { velocity: number | { x: number; y: number }; deceleration?: number; } /** * Animates a value along a timed easing curve. The `Easing` module has tons * of pre-defined curves, or you can use your own function. */ export const timing: ( value: AnimatedValue | AnimatedValueXY, config: TimingAnimationConfig ) => CompositeAnimation = () => { return new EmptyCompositeAnimation(); }; interface TimingAnimationConfig extends AnimationConfig { toValue: number | AnimatedValue | { x: number; y: number } | AnimatedValueXY | AnimatedInterpolation; easing?: (value: number) => number; duration?: number; delay?: number; } interface SpringAnimationConfig extends AnimationConfig { toValue: number | AnimatedValue | { x: number; y: number } | AnimatedValueXY; overshootClamping?: boolean; restDisplacementThreshold?: number; restSpeedThreshold?: number; velocity?: number | { x: number; y: number }; bounciness?: number; speed?: number; tension?: number; friction?: number; stiffness?: number; mass?: number; damping?: number; delay?: number; } interface LoopAnimationConfig { iterations?: number; // default -1 for infinite /** * Defaults to `true` */ resetBeforeIteration?: boolean; } /** * Creates a new Animated value composed from two Animated values added * together. */ export function add(a: Animated, b: Animated): AnimatedAddition { return new AnimatedAddition(); } class AnimatedAddition extends AnimatedInterpolation {} /** * Creates a new Animated value composed by subtracting the second Animated * value from the first Animated value. */ export function subtract(a: Animated, b: Animated): AnimatedSubtraction { return new AnimatedSubtraction(); } class AnimatedSubtraction extends AnimatedInterpolation {} /** * Creates a new Animated value composed by dividing the first Animated * value by the second Animated value. */ export function divide(a: Animated, b: Animated): AnimatedDivision { return new AnimatedDivision(); } class AnimatedDivision extends AnimatedInterpolation {} /** * Creates a new Animated value composed from two Animated values multiplied * together. */ export function multiply(a: Animated, b: Animated): AnimatedMultiplication { return new AnimatedMultiplication(); } class AnimatedMultiplication extends AnimatedInterpolation {} /** * Creates a new Animated value that is the (non-negative) modulo of the * provided Animated value */ export function modulo(a: Animated, modulus: number): AnimatedModulo { return new AnimatedModulo(); } class AnimatedModulo extends AnimatedInterpolation {} /** * Create a new Animated value that is limited between 2 values. It uses the * difference between the last value so even if the value is far from the bounds * it will start changing when the value starts getting closer again. * (`value = clamp(value + diff, min, max)`). * * This is useful with scroll events, for example, to show the navbar when * scrolling up and to hide it when scrolling down. */ export function diffClamp(a: Animated, min: number, max: number): AnimatedDiffClamp { return new AnimatedDiffClamp(); } class AnimatedDiffClamp extends AnimatedInterpolation {} /** * Starts an animation after the given delay. */ export function delay(time: number): CompositeAnimation { return new EmptyCompositeAnimation(); } /** * Starts an array of animations in order, waiting for each to complete * before starting the next. If the current running animation is stopped, no * following animations will be started. */ export function sequence(animations: Array<CompositeAnimation>): CompositeAnimation { return new EmptyCompositeAnimation(); } /** * Array of animations may run in parallel (overlap), but are started in * sequence with successive delays. Nice for doing trailing effects. */ export function stagger(time: number, animations: Array<CompositeAnimation>): CompositeAnimation { return new EmptyCompositeAnimation(); } /** * Loops a given animation continuously, so that each time it reaches the end, * it resets and begins again from the start. Can specify number of times to * loop using the key 'iterations' in the config. Will loop without blocking * the UI thread if the child animation is set to 'useNativeDriver'. */ export function loop(animation: CompositeAnimation, config?: LoopAnimationConfig): CompositeAnimation { return new EmptyCompositeAnimation(); } /** * Spring animation based on Rebound and Origami. Tracks velocity state to * create fluid motions as the `toValue` updates, and can be chained together. */ export function spring(value: AnimatedValue | AnimatedValueXY, config: SpringAnimationConfig): CompositeAnimation { return new EmptyCompositeAnimation(); } type ParallelConfig = { stopTogether?: boolean; // If one is stopped, stop all. default: true }; /** * Starts an array of animations all at the same time. By default, if one * of the animations is stopped, they will all be stopped. You can override * this with the `stopTogether` flag. */ export function parallel(animations: Array<CompositeAnimation>, config?: ParallelConfig): CompositeAnimation { return new EmptyCompositeAnimation(); } type Mapping = { [key: string]: Mapping } | AnimatedValue; interface EventConfig<T> { listener?: (event: NativeSyntheticEvent<T>) => void; useNativeDriver: boolean; } /** * Takes an array of mappings and extracts values from each arg accordingly, * then calls `setValue` on the mapped outputs. e.g. * *```javascript * onScroll={Animated.event( * [{nativeEvent: {contentOffset: {x: this._scrollX}}}] * {listener}, // Optional async listener * ) * ... * onPanResponderMove: Animated.event([ * null, // raw event arg ignored * {dx: this._panX}, // gestureState arg * ]), *``` */ export function event<T>(argMapping: Array<Mapping | null>, config?: EventConfig<T>): (...args: any[]) => void { return () => {}; } export type ComponentProps<T> = T extends React.ComponentType<infer P> | React.Component<infer P> ? P : never; export type LegacyRef<C> = { getNode(): C }; type Nullable = undefined | null; type Primitive = string | number | boolean | symbol; type Builtin = Function | Date | Error | RegExp; interface WithAnimatedArray<P> extends Array<WithAnimatedValue<P>> {} type WithAnimatedObject<T> = { [K in keyof T]: WithAnimatedValue<T[K]>; }; export type WithAnimatedValue<T> = T extends Builtin | Nullable ? T : T extends Primitive ? T | Value | AnimatedInterpolation // add `Value` and `AnimatedInterpolation` but also preserve original T : T extends Array<infer P> ? WithAnimatedArray<P> : T extends {} ? WithAnimatedObject<T> : T; // in case it's something we don't yet know about (for .e.g bigint) type NonAnimatedProps = 'key' | 'ref'; type TAugmentRef<T> = T extends React.Ref<infer R> ? React.Ref<R | LegacyRef<R>> : never; export type AnimatedProps<T> = { [key in keyof T]: key extends NonAnimatedProps ? key extends 'ref' ? TAugmentRef<T[key]> : T[key] : WithAnimatedValue<T[key]>; }; export interface AnimatedComponent<T extends React.ComponentType<any>> extends React.FC<AnimatedProps<React.ComponentPropsWithRef<T>>> {} const AnimatedComponentImpl = () => null; /** * Make any React component Animatable. Used to create `Animated.View`, etc. */ export function createAnimatedComponent<T extends React.ComponentType<any>>(component: T): AnimatedComponent<T> { return AnimatedComponentImpl; } /** * Animated variants of the basic native views. Accepts Animated.Value for * props and style. */ export const View: AnimatedComponent<typeof _View> = AnimatedComponentImpl; export const Image: AnimatedComponent<typeof _Image> = AnimatedComponentImpl; export const Text: AnimatedComponent<typeof _Text> = AnimatedComponentImpl; export const ScrollView: AnimatedComponent<typeof _ScrollView> = AnimatedComponentImpl; /** * FlatList and SectionList infer generic Type defined under their `data` and `section` props. */ export class FlatList<ItemT = any> extends React.Component<AnimatedProps<FlatListProps<ItemT>>> {} export class SectionList<ItemT = any, SectionT = DefaultSectionT> extends React.Component< AnimatedProps<SectionListProps<ItemT, SectionT>> > {}
the_stack
const InitKeyPair = function () { const keyPair: keypair = { publicKey: null, privateKey: null, keyLength: null, nikeName: null, createDate: null, email: null, passwordOK: false, verified: false, publicKeyID: null, _password: null } return keyPair } const makeKeyPairData = function ( view: view_layout.view, keypair: keypair ) { const length = keypair.publicKeyID.length keypair.publicKeyID = keypair.publicKeyID.substr ( length - 16 ) let keyPairPasswordClass = new keyPairPassword ( function ( _imapData: IinputData, passwd: string, sessionHash: string ) { // password OK keypair.keyPairPassword ( keyPairPasswordClass = null ) keypair.passwordOK = true keypair._password = passwd keypair.showLoginPasswordField ( false ) view.keyPairCalss = new encryptoClass ( keypair ) view.showKeyPair ( false ) if ( _imapData && _imapData.imapTestResult ) { return view.imapSetupClassExit ( _imapData, sessionHash ) } let uu = null return view.imapSetup ( uu = new imapForm ( keypair.email, _imapData, function ( imapData: IinputData ) { view.imapSetup ( uu = null ) view.imapSetupClassExit ( imapData, sessionHash ) })) }) keypair.keyPairPassword = ko.observable( keyPairPasswordClass ) keypair.showLoginPasswordField = ko.observable ( false ) keypair.delete_btn_view = ko.observable ( true ) keypair.showConform = ko.observable ( false ) keypair['showDeleteKeyPairNoite'] = ko.observable ( false ) keypair.delete_btn_click = function () { keypair.delete_btn_view ( false ) return keypair.showConform ( true ) } keypair.deleteKeyPairNext = function () { view.connectInformationMessage.sockEmit ( 'deleteKeyPairNext', () => { view.showIconBar ( false ) view.connectedCoNET ( false ) view.connectToCoNET ( false ) view.CoNETConnect (view.CoNETConnectClass = null) view.imapSetup ( view.imapFormClass = null ) keypair.showDeleteKeyPairNoite ( false ) return keypair.delete_btn_view ( false ) }) } } const initPopupArea = function () { const popItem = $( '.activating.element' ).popup('hide') const inline = popItem.hasClass ('inline') return popItem.popup({ on: 'focus', movePopup: false, position: 'top left', inline: inline }) } class showWebPageClass { public showLoading = ko.observable ( true ) public htmlIframe = ko.observable ( null ) public showErrorMessage = ko.observable ( false ) public showHtmlCodePage = ko.observable ( false ) public showImgPage = ko.observable ( true ) public showErrorMessageProcess () { this.showLoading ( false ) this.showErrorMessage ( true ) } public png = ko.observable ('') public close () { this.showImgPage ( false ) this.showHtmlCodePage ( false ) this.png ( null ) this.exit () } public imgClick () { this.showHtmlCodePage ( false ) this.showImgPage ( true ) } public htmlClick () { this.showHtmlCodePage ( true ) this.showImgPage ( false ) } constructor ( public showUrl: string, private zipBase64Stream: string, private zipBase64StreamUuid: string, private exit: ()=> void ) { const self = this _view.showIconBar ( false ) _view.keyPairCalss.decryptMessageToZipStream ( zipBase64Stream, ( err, data ) => { if ( err ) { return self.showErrorMessageProcess () } showHTMLComplete ( zipBase64StreamUuid, data, ( err, data: { img: string, html: string, folder: [ { filename: string, data: string }]} ) => { if ( err ) { return self.showErrorMessageProcess () } _view.bodyBlue ( false ) const getData = ( filename: string, _data: string ) => { const regex = new RegExp (`${ filename }`,'g') const index = html.indexOf ( `${ filename }` ) if ( index > -1 ) { if ( /js$/.test ( filename )) { _data = _data.replace ( /^data:text\/plain;/, 'data:application/javascript;') } else if ( /css$/.test ( filename )) { _data = _data.replace ( /^data:text\/plain;/, 'data:text/css;') } else if ( /html$|htm$/.test ( filename )) { _data = _data.replace ( /^data:text\/plain;/, 'data:text/html;') } else if ( /pdf$/.test ( filename )) { _data = _data.replace ( /^data:text\/plain;/, 'data:text/html;') } else { const kkk = _data } html = html.replace ( regex, _data ) } } let html = data.html data.folder.forEach ( n => { getData ( n.filename, n.data ) }) self.png ( data.img ) const htmlBolb = new Blob ([ html ], { type: 'text/html'}) const _url = window.URL.createObjectURL ( htmlBolb ) const fileReader = new FileReader() fileReader.onloadend = evt => { return window.URL.revokeObjectURL ( _url ) } self.showLoading ( false ) self.htmlIframe ( _url ) }) }) } } module view_layout { export class view { public connectInformationMessage = new connectInformationMessage( '/' ) public sectionLogin = ko.observable ( false ) public sectionAgreement = ko.observable ( false ) public sectionWelcome = ko.observable ( true ) public isFreeUser = ko.observable ( true ) public QTTransferData = ko.observable ( false ) public LocalLanguage = 'up' public menu = Menu public modalContent = ko.observable ('') public keyPairGenerateForm: KnockoutObservable< keyPairGenerateForm> = ko.observable () public tLang = ko.observable ( initLanguageCookie ()) public languageIndex = ko.observable ( lang [ this.tLang() ]) public localServerConfig: KnockoutObservable < install_config > = ko.observable () public keyPair: KnockoutObservable < keypair > = ko.observable ( InitKeyPair ()) public hacked = ko.observable ( false ) public imapSetup: KnockoutObservable < imapForm > = ko.observable () public showIconBar = ko.observable ( false ) public connectToCoNET = ko.observable ( false ) public connectedCoNET = ko.observable ( false ) public showKeyPair = ko.observable ( false ) public CoNETConnectClass: CoNETConnect = null public imapFormClass: imapForm = null public CoNETConnect: KnockoutObservable < CoNETConnect > = ko.observable ( null ) public bodyBlue = ko.observable ( true ) public CanadaBackground = ko.observable ( false ) public keyPairCalss: encryptoClass = null public appsManager: KnockoutObservable< appsManager > = ko.observable ( null ) public AppList = ko.observable ( false ) public imapData: IinputData = null public newVersion = ko.observable ( null ) public sessionHash = '' public showLanguageSelect = ko.observable ( true ) private demoTimeout private demoMainElm private afterInitConfig ( ) { this.keyPair ( this.localServerConfig ().keypair ) if ( this.keyPair() && this.keyPair().keyPairPassword() && typeof this.keyPair().keyPairPassword().inputFocus ==='function' ) { this.keyPair().keyPairPassword().inputFocus( true ) this.sectionLogin ( false ) } } private initConfig ( config: install_config ) { const self = this this.showKeyPair ( true ) if ( config.keypair && config.keypair.publicKeyID ) { /** * * Key pair ready * */ makeKeyPairData ( this, config.keypair ) if ( ! config.keypair.passwordOK ) { config.keypair.showLoginPasswordField ( true ) } } else { /** * * No key pair * */ this.svgDemo_showLanguage () this.clearImapData () config.keypair = null let _keyPairGenerateForm = new keyPairGenerateForm ( function ( _keyPair: keypair, sessionHash: string ) { /** * key pair ready */ makeKeyPairData ( self, _keyPair ) _keyPair.passwordOK = true let keyPairPassword = _keyPair.keyPairPassword () _keyPair.keyPairPassword ( keyPairPassword = null ) config.keypair = _keyPair self.keyPair ( _keyPair ) self.showKeyPair ( false ) initPopupArea () let uu = null self.keyPairCalss = new encryptoClass ( self.keyPair () ) self.imapSetup ( uu = new imapForm ( config.account, null, function ( imapData: IinputData ) { self.imapSetup ( uu = null ) return self.imapSetupClassExit ( imapData, sessionHash ) })) return self.keyPairGenerateForm ( _keyPairGenerateForm = null ) }) this.keyPairGenerateForm ( _keyPairGenerateForm ) } this.localServerConfig ( config ) this.afterInitConfig () } private clearImapData () { let imap = this.imapSetup() this.imapSetup( imap = null ) } private socketListen () { let self = this this.connectInformationMessage.sockEmit ( 'init', ( err, config: install_config) => { if ( err ) { return } return self.initConfig ( config ) }) this.connectInformationMessage.socketIo.on ('init', ( err, config: install_config ) => { if ( err ) { return } return self.initConfig ( config ) }) } constructor () { this.socketListen () this.CanadaBackground.subscribe ( val => { if ( val ) { $.ajax ({ url:'/scripts/CanadaSvg.js' }).done ( data => { eval ( data ) }) } }) } // change language public selectItem ( that?: any, site?: () => number ) { const tindex = lang [ this.tLang ()] let index = tindex + 1 if ( index > 3 ) { index = 0 } this.languageIndex ( index ) this.tLang( lang [ index ]) $.cookie ( 'langEH', this.tLang(), { expires: 180, path: '/' }) const obj = $( "span[ve-data-bind]" ) obj.each ( function ( index, element ) { const ele = $( element ) const data = ele.attr ( 've-data-bind' ) if ( data && data.length ) { ele.text ( eval ( data )) } }) $('.languageText').shape (`flip ${ this.LocalLanguage }`) $('.KnockoutAnimation').transition('jiggle') return initPopupArea() } // start click public openClick () { clearTimeout ( this.demoTimeout ) if ( this.demoMainElm && typeof this.demoMainElm.remove === 'function' ) { this.demoMainElm.remove() this.demoMainElm = null } if ( !this.connectInformationMessage.socketIoOnline ) { return this.connectInformationMessage.showSystemError () } this.sectionWelcome ( false ) /* if ( this.localServerConfig().firstRun ) { return this.sectionAgreement ( true ) } */ this.sectionLogin ( true ) return initPopupArea () } public deletedKeypairResetView () { this.imapSetup (null) } public agreeClick () { this.connectInformationMessage.sockEmit ( 'agreeClick' ) this.sectionAgreement ( false ) this.localServerConfig().firstRun = false return this.openClick() } public refresh () { if ( typeof require === 'undefined' ) { this.modalContent ( infoDefine[ this.languageIndex() ].emailConform.formatError [ 11 ] ) return this.hacked ( true ) } const { remote } = require ('electron') if ( remote && remote.app && typeof remote.app.quit === 'function' ) { return remote.app.quit() } } public showKeyInfoClick () { this.sectionLogin ( true ) this.showKeyPair ( true ) this.AppList ( false ) this.appsManager ( null ) } public imapSetupClassExit ( _imapData: IinputData, sessionHash: string ) { const self = this this.imapData = _imapData this.sessionHash = sessionHash return this.CoNETConnect ( this.CoNETConnectClass = new CoNETConnect ( _imapData.imapUserName, this.keyPair().verified, _imapData.confirmRisk, this.keyPair().email, function ConnectReady ( err ) { if ( typeof err ==='number' && err > -1 ) { self.CoNETConnect ( this.CoNETConnectClass = null ) return self.imapSetup ( this.imapFormClass = new imapForm ( _imapData.account, null, function ( imapData: IinputData ) { self.imapSetup ( this.imapFormClass = null ) return self.imapSetupClassExit ( imapData, sessionHash ) })) } self.connectedCoNET ( true ) self.homeClick () })) } public reFreshLocalServer () { location.reload() } public homeClick () { this.AppList ( true ) this.sectionLogin ( false ) const connectMainMenu = () => { let am = null this.appsManager ( am = new appsManager (() => { am = null return connectMainMenu () })) } connectMainMenu () this.showKeyPair ( false ) $('.dimmable').dimmer ({ on: 'hover' }) $('.comeSoon').popup ({ on: 'focus', movePopup: false, position: 'top left', inline: true }) _view.connectInformationMessage.socketIo.removeEventListener ('tryConnectCoNETStage', this.CoNETConnectClass.listenFun ) } /** * * T/t = Translate (t is relative, T is absolute) R/r = rotate(r is relative, R is absolute) S/s = scale(s is relative, S is absolute) */ private svgDemo_showLanguage () { if ( !this.sectionWelcome()) { return } let i = 0 const changeLanguage = () => { if ( ++i === 1 ) { backGround_mask_circle.attr ({ stroke: "#FF000090", }) return setTimeout (() => { changeLanguage() }, 1000 ) } if ( i > 5 || !this.sectionWelcome() ) { main.remove() return this.demoMainElm = main = null } this.selectItem () this.demoTimeout = setTimeout (() => { changeLanguage () }, 2000 ) } const width = window.innerWidth const height = window.outerHeight let main = this.demoMainElm = Snap( width, height ) const backGround_mask_circle = main.circle( width / 2, height / 2, width / 1.7 ).attr({ fill:'#00000000', stroke: "#FF000020", strokeWidth: 5, }) const wT = width/2 - 35 const wY = 30 - height / 2 backGround_mask_circle.animate ({ transform: `t${ wT } ${ wY }`, r: 60 }, 3000, mina.easeout, changeLanguage ) } } } const _view = new view_layout.view () ko.applyBindings ( _view , document.getElementById ( 'body' )) $(`.${ _view.tLang()}`).addClass('active')
the_stack
import { afterAll, expect, test } from '@jest/globals'; import 'reflect-metadata'; import { JSONError, ValidationError, ValidationErrorItem } from '@deepkit/rpc'; import { appModuleForControllers, closeAllCreatedServers, createServerClientPair, subscribeAndWait } from './util'; import { Observable } from 'rxjs'; import { bufferCount, first, skip } from 'rxjs/operators'; import { Entity, getClassSchema, PropertySchema, t } from '@deepkit/type'; import { ObserverTimer } from '@deepkit/core-rxjs'; import { isArray } from '@deepkit/core'; import { ClientProgress, rpc } from '@deepkit/rpc'; import { fail } from 'assert'; import ws from 'ws'; // @ts-ignore global['WebSocket'] = ws; afterAll(async () => { await closeAllCreatedServers(); }); @Entity('controller-basic/user') class User { constructor(@t public name: string) { this.name = name; } } @Entity('error:custom-error') class MyCustomError { @t additional?: string; constructor(@t public readonly message: string) { } } test('basic setup and methods', async () => { @rpc.controller('test') class TestController { @rpc.action() @t.array(String) names(last: string): string[] { return ['a', 'b', 'c', last]; } @rpc.action() user(name: string): User { return new User(name); } @rpc.action() myErrorNormal() { throw new Error('Nothing to see here'); } @rpc.action() myErrorJson() { throw new JSONError([{ path: 'name', name: 'missing' }]); } @rpc.action() myErrorCustom(): any { const error = new MyCustomError('Shit dreck'); error.additional = 'hi'; throw error; } @rpc.action() validationError(user: User) { } } const schema = getClassSchema(TestController); { const u = schema.getMethodProperties('validationError')[0]; expect(u).toBeInstanceOf(PropertySchema); expect(u.type).toBe('class'); expect(u.classType).toBe(User); expect(u.toJSON()).toMatchObject({ name: 'user', type: 'class', classType: 'controller-basic/user' }); } const { client, close } = await createServerClientPair('basic setup and methods', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); const names = await controller.names('d'); expect(names).toEqual(['a', 'b', 'c', 'd']); { try { const error = await controller.myErrorNormal(); fail('should error'); } catch (error) { expect(error).toBeInstanceOf(Error); expect(error.message).toBe('Nothing to see here'); } } { try { const error = await controller.myErrorJson(); fail('should error'); } catch (error) { expect(error).toBeInstanceOf(JSONError); expect((error as JSONError).json).toEqual([{ path: 'name', name: 'missing' }]); } } { try { const error = await controller.myErrorCustom(); fail('should error'); } catch (error) { expect(error).toBeInstanceOf(MyCustomError); expect((error as MyCustomError).message).toEqual('Shit dreck'); expect((error as MyCustomError).additional).toEqual('hi'); } } { try { const user = new User('asd'); (user as any).name = undefined; const error = await controller.validationError(user); fail('should error'); } catch (error) { expect(error).toBeInstanceOf(ValidationError); expect((error as ValidationError).errors[0]).toBeInstanceOf(ValidationErrorItem); expect((error as ValidationError).errors[0]).toEqual({ code: 'required', message: 'Required value is undefined', path: 'user.name' }); } } const user = await controller.user('pete'); expect(user).toBeInstanceOf(User); expect(user.name).toEqual('pete'); await close(); }); test('basic serialisation return: entity', async () => { @rpc.controller('test') class TestController { @rpc.action() async user(name: string): Promise<User> { return new User(name); } @rpc.action() async optionalUser(@t.optional returnUser: boolean = false): Promise<User | undefined> { return returnUser ? new User('optional') : undefined; } @rpc.action() @t.array(User) async users(name: string): Promise<User[]> { return [new User(name)]; } @rpc.action() @t.any async allowPlainObject(name: string): Promise<{ mowla: boolean, name: string, date: Date }> { return { mowla: true, name, date: new Date('1987-12-12T11:00:00.000Z') }; } @rpc.action() async observable(name: string): Promise<Observable<User>> { return new Observable((observer) => { observer.next(new User(name)); }); } } const { client, close } = await createServerClientPair('basic serialisation entity', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); const user = await controller.user('peter'); expect(user).toBeInstanceOf(User); const users = await controller.users('peter'); expect(users.length).toBe(1); expect(users[0]).toBeInstanceOf(User); expect(users[0].name).toBe('peter'); const optionalUser = await controller.optionalUser(); expect(optionalUser).toBeUndefined(); const optionalUser2 = await controller.optionalUser(true); expect(optionalUser2).toBeInstanceOf(User); expect(optionalUser2!.name).toBe('optional'); const struct = await controller.allowPlainObject('peter'); expect(struct.mowla).toBe(true); expect(struct.name).toBe('peter'); expect(struct.date).toBeInstanceOf(Date); expect(struct.date).toEqual(new Date('1987-12-12T11:00:00.000Z')); { const u = await (await controller.observable('peter')).pipe(first()).toPromise(); expect(u).toBeInstanceOf(User); } await close(); }); test('basic serialisation param: entity', async () => { @rpc.controller('test') class TestController { @rpc.action() user(user: User): boolean { return user instanceof User && user.name === 'peter2'; } } const { client, close } = await createServerClientPair('serialisation param: entity', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); const userValid = await controller.user(new User('peter2')); expect(userValid).toBe(true); await close(); }); test('basic serialisation partial param: entity', async () => { @Entity('user3') class User { @t defaultVar: string = 'yes'; @t birthdate?: Date; constructor(@t public name: string) { this.name = name; } } @rpc.controller('test') class TestController { @rpc.action() failUser(user: Partial<User>) { } @rpc.action() failPartialUser(name: string, date: Date): Partial<User> { return { name: name, birthdate: date }; } @rpc.action() @t.partial(User) partialUser(name: string, date: Date): Partial<User> { return { name: name, birthdate: date }; } @rpc.action() user(@t.partial(User) user: Partial<User>): boolean { return !(user instanceof User) && user.name === 'peter2' && !user.defaultVar; } } const { client, close } = await createServerClientPair('serialisation partial param: entity', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); // // try { // await test.failUser({name: 'asd'}); // fail('Should fail'); // } catch (e) { // expect(e.message).toMatch('test::failUser argument 0 is an Object with unknown structure. '); // } // // const date = new Date('1987-12-12T11:00:00.000Z'); // // try { // await test.failPartialUser('asd', date); // fail('Should fail'); // } catch (e) { // expect(e.message).toMatch('test::failPartialUser result is an Object with unknown structure.'); // } const a = await controller.user({ name: 'peter2' }); expect(a).toBeTruthy(); // const partialUser = await test.partialUser('peter2', date); // expect(partialUser.name).toBe('peter2'); // expect(partialUser.birthdate).toEqual(date); await close(); }); test('test basic promise', async () => { @rpc.controller('test') class TestController { @rpc.action() @t.array(String) async names(last: string): Promise<string[]> { return ['a', 'b', 'c', last]; } @rpc.action() @t.type(User) async user(name: string): Promise<User> { return new User(name); } } const { client, close } = await createServerClientPair('test basic promise', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); const names = await controller.names('d'); expect(names).toEqual(['a', 'b', 'c', 'd']); const user = await controller.user('pete'); expect(user).toBeInstanceOf(User); expect(user.name).toEqual('pete'); await close(); }); test('test observable', async () => { @rpc.controller('test') class TestController { @rpc.action() @t.generic(t.string) observer(): Observable<string> { return new Observable((observer) => { observer.next('a'); const timer = new ObserverTimer(observer); timer.setTimeout(() => { observer.next('b'); }, 100); timer.setTimeout(() => { observer.next('c'); }, 200); timer.setTimeout(() => { observer.complete(); }, 300); }); } @rpc.action() @t.generic(User) user(name: string): Observable<User> { return new Observable((observer) => { observer.next(new User('first')); const timer = new ObserverTimer(observer); timer.setTimeout(() => { observer.next(new User(name)); }, 200); }); } } const { client, close } = await createServerClientPair('test observable', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); const observable = await controller.observer(); await subscribeAndWait(observable.pipe(bufferCount(3)), async (next) => { expect(next).toEqual(['a', 'b', 'c']); }); await subscribeAndWait((await controller.user('pete')).pipe(bufferCount(2)), async (next) => { expect(next[0]).toBeInstanceOf(User); expect(next[1]).toBeInstanceOf(User); expect(next[0].name).toEqual('first'); expect(next[1].name).toEqual('pete'); }); await close(); }); test('test param serialization', async () => { @rpc.controller('test') class TestController { @rpc.action() actionString(@t.type(String) array: string): boolean { return 'string' === typeof array; } @rpc.action() actionArray(@t.array(String) array: string[]): boolean { return isArray(array) && 'string' === typeof array[0]; } } const { client, close } = await createServerClientPair('test param serialization', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); expect(await controller.actionArray(['b'])).toBe(true); await close(); }); test('test batcher', async () => { @rpc.controller('test') class TestController { @rpc.action() uploadBig(@t.type(Buffer) file: Buffer): boolean { return file.length === 550_000; } @rpc.action() downloadBig(): Buffer { return new Buffer(650_000); } } const { client, close } = await createServerClientPair('test batcher', appModuleForControllers([TestController])); const controller = client.controller<TestController>('test'); const progress = ClientProgress.track(); let hit = 0; progress.download.pipe(skip(1)).subscribe(() => { expect(progress.download.total).toBeGreaterThan(0); expect(progress.download.current).toBeLessThanOrEqual(progress.download.total); expect(progress.download.progress).toBeLessThanOrEqual(1); hit++; }); const file = await controller.downloadBig(); expect(file.length).toBe(650_000); expect(hit).toBeGreaterThan(3); expect(progress.download.done).toBe(true); expect(progress.download.progress).toBe(1); const uploadFile = new Buffer(550_000); await close(); });
the_stack
import { Capabilities } from '@wdio/types' import { sessionEnvironmentDetector, capabilitiesEnvironmentDetector } from '../src/envDetector' import appiumResponse from './__fixtures__/appium.response.json' import experitestResponse from './__fixtures__/experitest.response.json' import chromedriverResponse from './__fixtures__/chromedriver.response.json' import geckodriverResponse from './__fixtures__/geckodriver.response.json' import ghostdriverResponse from './__fixtures__/ghostdriver.response.json' import safaridriverResponse from './__fixtures__/safaridriver.response.json' import safaridriverdockerNpNResponse from './__fixtures__/safaridriverdockerNpN.response.json' import safaridriverdockerNbVResponse from './__fixtures__/safaridriverdockerNbV.response.json' import safaridriverLegacyResponse from './__fixtures__/safaridriver.legacy.response.json' import edgedriverResponse from './__fixtures__/edgedriver.response.json' import seleniumstandaloneResponse from './__fixtures__/standaloneserver.response.json' import seleniumstandalone4Response from './__fixtures__/standaloneserver4.response.json' describe('sessionEnvironmentDetector', () => { const chromeCaps = chromedriverResponse.value as WebDriver.Capabilities const appiumCaps = appiumResponse.value.capabilities as WebDriver.Capabilities const experitestAppiumCaps = experitestResponse.appium.capabilities as WebDriver.Capabilities const geckoCaps = geckodriverResponse.value.capabilities as WebDriver.Capabilities const edgeCaps = edgedriverResponse.value.capabilities as WebDriver.Capabilities const phantomCaps = ghostdriverResponse.value as WebDriver.Capabilities const safariCaps = safaridriverResponse.value.capabilities as WebDriver.Capabilities const safariDockerNpNCaps = safaridriverdockerNpNResponse.value.capabilities as WebDriver.Capabilities // absent capability.platformName const safariDockerNbVCaps = safaridriverdockerNbVResponse.value.capabilities as WebDriver.Capabilities // absent capability.browserVersion const safariLegacyCaps = safaridriverLegacyResponse.value as WebDriver.Capabilities const standaloneCaps = seleniumstandaloneResponse.value as WebDriver.DesiredCapabilities const standalonev4Caps = seleniumstandalone4Response.value as WebDriver.DesiredCapabilities it('isMobile', () => { const requestedCapabilities = { browserName: '' } const appiumReqCaps = { 'appium:options': {} } const appiumW3CCaps = { alwaysMatch: { 'appium:options': {} }, firstMatch: [] } expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isMobile).toBe(false) expect(sessionEnvironmentDetector({ capabilities: experitestAppiumCaps, requestedCapabilities }).isMobile).toBe(true) expect(sessionEnvironmentDetector({ capabilities: appiumCaps, requestedCapabilities }).isMobile).toBe(true) expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities }).isMobile).toBe(false) // doesn't matter if there are Appium capabilities if returned session details don't show signs of Appium expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities: appiumReqCaps }).isMobile).toBe(false) expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities: appiumW3CCaps }).isMobile).toBe(false) const newCaps = { ...chromeCaps, 'appium:options': {} } expect(sessionEnvironmentDetector({ capabilities: newCaps, requestedCapabilities }).isMobile).toBe(true) }) it('isW3C', () => { const requestedCapabilities = { browserName: '' } expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isW3C).toBe(false) expect(sessionEnvironmentDetector({ capabilities: appiumCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: experitestAppiumCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: geckoCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: safariCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: safariDockerNbVCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: safariDockerNpNCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: edgeCaps, requestedCapabilities }).isW3C).toBe(true) expect(sessionEnvironmentDetector({ capabilities: safariLegacyCaps, requestedCapabilities }).isW3C).toBe(false) expect(sessionEnvironmentDetector({ capabilities: phantomCaps, requestedCapabilities }).isW3C).toBe(false) expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities }).isW3C).toBe(false) }) it('isChrome', () => { const requestedCapabilities = { browserName: '' } expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isChrome).toBe(false) expect(sessionEnvironmentDetector({ capabilities: appiumCaps, requestedCapabilities }).isChrome).toBe(false) expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities }).isChrome).toBe(true) expect(sessionEnvironmentDetector({ capabilities: geckoCaps, requestedCapabilities }).isChrome).toBe(false) expect(sessionEnvironmentDetector({ capabilities: phantomCaps, requestedCapabilities }).isChrome).toBe(false) }) it('isFirefox', () => { const requestedCapabilities = { browserName: '' } expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isFirefox).toBe(false) expect(sessionEnvironmentDetector({ capabilities: appiumCaps, requestedCapabilities }).isFirefox).toBe(false) expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities }).isFirefox).toBe(false) expect(sessionEnvironmentDetector({ capabilities: geckoCaps, requestedCapabilities }).isFirefox).toBe(true) expect(sessionEnvironmentDetector({ capabilities: phantomCaps, requestedCapabilities }).isFirefox).toBe(false) }) it('isSauce', () => { const capabilities = { browserName: 'chrome' } let requestedCapabilities: WebDriver.DesiredCapabilities = {} expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isSauce).toBe(false) expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(false) requestedCapabilities.extendedDebugging = true expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(true) requestedCapabilities = {} expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(false) requestedCapabilities['sauce:options'] = { extendedDebugging: true } expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(true) }) it('isSauce (w3c)', () => { const capabilities = { browserName: 'chrome' } let requestedCapabilities: Capabilities.W3CCapabilities = { alwaysMatch: {}, firstMatch: [] } expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isSauce).toBe(false) expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(false) requestedCapabilities.alwaysMatch = { 'sauce:options': { extendedDebugging: true } } expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(true) requestedCapabilities.alwaysMatch = { 'sauce:options': {} } expect(sessionEnvironmentDetector({ capabilities, requestedCapabilities }).isSauce).toBe(false) }) it('isSeleniumStandalone', () => { const requestedCapabilities = { browserName: '' } expect(sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: {} }).isSeleniumStandalone).toBe(false) expect(sessionEnvironmentDetector({ capabilities: appiumCaps, requestedCapabilities }).isSeleniumStandalone).toBe(false) expect(sessionEnvironmentDetector({ capabilities: chromeCaps, requestedCapabilities }).isSeleniumStandalone).toBe(false) expect(sessionEnvironmentDetector({ capabilities: geckoCaps, requestedCapabilities }).isSeleniumStandalone).toBe(false) expect(sessionEnvironmentDetector({ capabilities: standaloneCaps, requestedCapabilities }).isSeleniumStandalone).toBe(true) expect(sessionEnvironmentDetector({ capabilities: standalonev4Caps, requestedCapabilities }).isSeleniumStandalone).toBe(true) }) it('should not detect mobile app for browserName===undefined', function () { const requestedCapabilities = { browserName: '' } const capabilities = {} const { isMobile, isIOS, isAndroid } = sessionEnvironmentDetector({ capabilities, requestedCapabilities }) expect(isMobile).toEqual(false) expect(isIOS).toEqual(false) expect(isAndroid).toEqual(false) }) it('should not detect mobile app for browserName==="firefox"', function () { const capabilities = { browserName: 'firefox' } const requestedCapabilities = { browserName: '' } const { isMobile, isIOS, isAndroid } = sessionEnvironmentDetector({ capabilities, requestedCapabilities }) expect(isMobile).toEqual(false) expect(isIOS).toEqual(false) expect(isAndroid).toEqual(false) }) it('should not detect mobile app for browserName==="chrome"', function () { const capabilities = { browserName: 'chrome' } const requestedCapabilities = { browserName: '' } const { isMobile, isIOS, isAndroid } = sessionEnvironmentDetector({ capabilities, requestedCapabilities }) expect(isMobile).toEqual(false) expect(isIOS).toEqual(false) expect(isAndroid).toEqual(false) }) it('should detect mobile app for browserName===""', function () { const capabilities = { browserName: '' } const requestedCapabilities = { browserName: '' } const { isMobile, isIOS, isAndroid } = sessionEnvironmentDetector({ capabilities, requestedCapabilities }) expect(isMobile).toEqual(true) expect(isIOS).toEqual(false) expect(isAndroid).toEqual(false) }) it('should detect Android mobile app', function () { const capabilities = { platformName: 'Android', platformVersion: '4.4', deviceName: 'LGVS450PP2a16334', app: 'foo.apk' } const requestedCapabilities = { browserName: '' } const { isMobile, isIOS, isAndroid } = sessionEnvironmentDetector({ capabilities, requestedCapabilities }) expect(isMobile).toEqual(true) expect(isIOS).toEqual(false) expect(isAndroid).toEqual(true) }) it('should detect Android mobile app without upload', function () { const capabilities = { platformName: 'Android', platformVersion: '4.4', deviceName: 'LGVS450PP2a16334', appPackage: 'com.example', appActivity: 'com.example.gui.LauncherActivity', noReset: true, appWaitActivity: 'com.example.gui.LauncherActivity' } const requestedCapabilities = { browserName: '' } const { isMobile, isIOS, isAndroid } = sessionEnvironmentDetector({ capabilities, requestedCapabilities }) expect(isMobile).toEqual(true) expect(isIOS).toEqual(false) expect(isAndroid).toEqual(true) }) }) describe('capabilitiesEnvironmentDetector', () => { it('should return env flags without isW3C and isSeleniumStandalone', () => { const sessionFlags = sessionEnvironmentDetector({ capabilities: {}, requestedCapabilities: { browserName: '' } }) const capabilitiesFlags = capabilitiesEnvironmentDetector({}, 'webdriver') const expectedFlags = Object.keys(sessionFlags).filter(flagName => !['isW3C', 'isSeleniumStandalone'].includes(flagName)) expect(Object.keys(capabilitiesFlags)).toEqual(expectedFlags) }) it('should return devtools env flags if automationProtocol is devtools', () => { const capabilitiesFlags = capabilitiesEnvironmentDetector({}, 'devtools') expect((capabilitiesFlags as any).isDevTools).toBe(true) expect((capabilitiesFlags as any).isSeleniumStandalone).toBe(false) expect(capabilitiesFlags.isChrome).toBe(false) expect(capabilitiesFlags.isMobile).toBe(false) }) })
the_stack
import { AfterViewInit, ChangeDetectionStrategy, Component, ContentChild, ElementRef, EventEmitter, forwardRef, Injector, Input, NgZone, OnDestroy, OnInit, Output, QueryList, Renderer2, TemplateRef, ViewChild, ViewChildren, ChangeDetectorRef } from "@angular/core"; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; import {AbstractJigsawComponent} from "../../common/common"; import {CallbackRemoval, CommonUtils} from "../../common/core/utils/common-utils"; import {ArrayCollection} from "../../common/core/data/array-collection"; import {JigsawInput} from "../input/input"; import {AffixUtils} from "../../common/core/utils/internal-utils"; import {JigsawTag} from "../tag/tag"; import {DropDownTrigger, JigsawFloat} from "../../common/directive/float/float"; import {PopupOptions, PopupService} from "../../common/service/popup.service"; import {RequireMarkForCheck} from "../../common/decorator/mark-for-check"; export class ComboSelectValue { [index: string]: any; closable?: boolean; } @Component({ selector: 'jigsaw-combo-select, j-combo-select', templateUrl: 'combo-select.html', host: { '[style.min-width]': 'width', '[class.jigsaw-combo-select-host]': 'true', '[class.jigsaw-combo-select-error]': '!valid' }, providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawComboSelect), multi: true}, ], changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawComboSelect extends AbstractJigsawComponent implements ControlValueAccessor, OnDestroy, OnInit, AfterViewInit { private _removeRefreshCallback: CallbackRemoval; constructor(private _renderer: Renderer2, private _elementRef: ElementRef, private _popupService: PopupService, protected _zone: NgZone, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector, private _cdr: ChangeDetectorRef) { super(_zone); } private _value: ArrayCollection<ComboSelectValue> = new ArrayCollection(); /** * @NoMarkForCheckRequired */ @Input() public get value(): ArrayCollection<ComboSelectValue> | ComboSelectValue[] { return this._value; } public set value(value: ArrayCollection<ComboSelectValue> | ComboSelectValue[]) { if (!value || this._value === value) { return; } this._value = value instanceof ArrayCollection ? value : new ArrayCollection(value); this._propagateChange(this._value); if (this.initialized) { this.writeValue(value); } } @Output() public valueChange = new EventEmitter<any[]>(); /** * @NoMarkForCheckRequired */ @Input() public labelField: string = 'label'; @Output() public select = new EventEmitter<any>(); @Output() public remove = new EventEmitter<any>(); @Input() @RequireMarkForCheck() public placeholder: string = ''; private _disabled: boolean; @Input() @RequireMarkForCheck() public get disabled(): boolean { return this._disabled; } public set disabled(value: boolean) { this._disabled = value; if (value) { this.open = false; } } private _openTrigger: DropDownTrigger = DropDownTrigger.mouseenter; @Input() @RequireMarkForCheck() public get openTrigger(): 'mouseenter' | 'click' | 'none' | DropDownTrigger { return this.disabled ? 'none' : this._openTrigger; } public set openTrigger(value: 'mouseenter' | 'click' | 'none' | DropDownTrigger) { //从模板过来的值,不会受到类型的约束 this._openTrigger = typeof value === 'string' ? DropDownTrigger[value] : value; } private _closeTrigger: DropDownTrigger = DropDownTrigger.mouseleave; @Input() @RequireMarkForCheck() public get closeTrigger(): 'mouseleave' | 'click' | 'none' | DropDownTrigger { return this._closeTrigger; } public set closeTrigger(value: 'mouseleave' | 'click' | 'none' | DropDownTrigger) { //从模板过来的值,不会受到类型的约束 this._closeTrigger = typeof value === 'string' ? DropDownTrigger[value] : value; } /** * @NoMarkForCheckRequired */ @Input() public maxWidth: string; /** * @internal */ @ContentChild(TemplateRef) public _$contentTemplateRef: any; @ViewChild(JigsawFloat) private _jigsawFloat: JigsawFloat; /** * @internal */ public _$opened: boolean = false; @Input() @RequireMarkForCheck() public get open(): boolean { return this._$opened; } public set open(value: boolean) { if (value === this._$opened || (this.disabled && value && this.openTrigger != DropDownTrigger.none)) { // 设置值等于当前值 // 控件disabled,并且想打开下拉 return; } this.runMicrotask(() => { // toggle open 外部控制时,用异步触发变更检查 // 初始化open,等待组件初始化后执行 if (value) { if (this._editor) { this._editor.focus(); } } else { this.searchKeyword = ''; } }); this._$opened = value; } /** * @internal */ public _$comboOpenChange(value) { if (value) { // 同步dropdown宽度 this._autoWidth(); if (this._editor) { this._editor.select(); } } this._onTouched(); this.openChange.emit(value); } @Output() public openChange: EventEmitter<boolean> = new EventEmitter<boolean>(); /** * @internal */ public _$options: PopupOptions = {}; private _showBorder: boolean = true; /** * @NoMarkForCheckRequired */ @Input() public set showBorder(value: boolean) { this._showBorder = value; this._$options.showBorder = this.showBorder; } public get showBorder(): boolean { return this._showBorder; } /** * @NoMarkForCheckRequired */ @Input() public autoClose: boolean; //自动关闭dropdown /** * @NoMarkForCheckRequired */ @Input() public autoWidth: boolean; //自动同步dropdown宽度,与combo-select宽度相同 /** * @NoMarkForCheckRequired */ @Input() public clearable: boolean = false; @ViewChild('editor') private _editor: JigsawInput; @ViewChild('editor', {read: ElementRef}) private _editorElementRef: ElementRef; @ViewChildren(JigsawTag) private _tags: QueryList<JigsawTag>; @Input() @RequireMarkForCheck() public searchable: boolean = false; /** * @NoMarkForCheckRequired */ @Input() public searching: boolean = false; /** * @NoMarkForCheckRequired */ @Input() public searchKeyword: string = ''; /** * @NoMarkForCheckRequired */ @Input() public searchBoxMinWidth: number = 40; @Output() public searchKeywordChange = new EventEmitter<any>(); /** * 当用户输入非法时,组件给予样式上的提示,以提升易用性,常常和表单配合使用。 * * @NoMarkForCheckRequired * * $demo = form/template-driven */ @Input() public valid: boolean = true; public get _$trackByFn() { return CommonUtils.toTrackByFunction(this.labelField); }; @Output() public clear = new EventEmitter<any>(); /** * @internal */ public _$clearValue() { this._value.splice(0, this._value.length); this._value.refresh(); this._autoWidth(); this.clear.emit(); } /** * @internal */ public _$removeTag(tag) { const index = this._value.indexOf(tag); if (index != -1) { this._value.splice(index, 1); this._value.refresh(); this.remove.emit(tag); } this._autoWidth(); } private _autoWidth() { if (!this.autoWidth || !this._jigsawFloat || !this._jigsawFloat.popupElement) { return; } this.runAfterMicrotasks(() => { if (!this._jigsawFloat || !this._jigsawFloat.popupElement) { return; } this._renderer.setStyle(this._jigsawFloat.popupElement, 'width', this._elementRef.nativeElement.offsetWidth + 'px'); this._renderer.setStyle(this._jigsawFloat.popupElement, 'min-width', this._elementRef.nativeElement.offsetWidth + 'px'); }); } private _autoClose() { if (this.autoClose) { this.open = false; } } private _autoEditorWidth() { if (!this.searchable || !this._editorElementRef) { return; } // 组件的空白长度 + 图标宽度 const hostPaddingGap = 36; if (this._tags.last) { const host = this._elementRef.nativeElement; const lastTag = this._tags.last._elementRef.nativeElement; let editorWidth: any = host.offsetWidth - (AffixUtils.offset(lastTag).left - AffixUtils.offset(host).left + lastTag.offsetWidth + hostPaddingGap); editorWidth = editorWidth > this.searchBoxMinWidth ? editorWidth + 'px' : '100%'; this._renderer.setStyle(this._editorElementRef.nativeElement, 'width', editorWidth); } else { this._renderer.setStyle(this._editorElementRef.nativeElement, 'width', '100%'); } } private _autoPopupPos() { if (!this.autoClose && this._jigsawFloat) { this.runAfterMicrotasks(() => { this._popupService.setPosition(this._jigsawFloat._getPopupOption(), this._jigsawFloat.popupElement) }) } } /** * @internal */ public _$tagClick(tagItem) { // 返回选中的tag this.select.emit(tagItem); // 控制下拉状态;(如果没有打开下拉内容,下拉,如果已经下拉保持不变;) if (this._openTrigger === DropDownTrigger.mouseenter || this.open || this.disabled) { return; } this.open = true; } /** * @internal */ public _$handleSearchBoxChange() { if (this.searchKeyword) { this.open = true; } this.searchKeywordChange.emit(this.searchKeyword); } public ngOnInit() { super.ngOnInit(); // 设置初始值 if (CommonUtils.isDefined(this.value)) { this.writeValue(this.value, false); } let maxWidth: string | number = CommonUtils.getCssValue(this.maxWidth); if (maxWidth && !maxWidth.match(/%/)) { maxWidth = parseInt(maxWidth.replace('px', '')); this._renderer.setStyle(this._elementRef.nativeElement.querySelector('.jigsaw-combo-select-selection-rendered'), 'max-width', (maxWidth - 39) + 'px') } } public ngAfterViewInit() { const change = this._tags.changes.subscribe(() => { this._autoEditorWidth(); change.unsubscribe() }) } public ngOnDestroy() { super.ngOnDestroy(); this.open = false; if (this._removeRefreshCallback) { this._removeRefreshCallback(); this._removeRefreshCallback = null; } } private _propagateChange: any = () => { }; private _onTouched: any = () => { }; public writeValue(value: any, emit = true): void { if (value && this._value != value) { // 初始表单值的赋值 this._value = value instanceof ArrayCollection ? value : new ArrayCollection(value); this._cdr.markForCheck(); } if (emit) { this.runMicrotask(() => this.valueChange.emit(this._value)); } this._autoWidth(); this._autoClose(); this._autoPopupPos(); if (this._removeRefreshCallback) { this._removeRefreshCallback() } this._removeRefreshCallback = this._value.onRefresh(() => { this.valueChange.emit(this._value); this._propagateChange(this._value); this._autoWidth(); this._autoClose(); this._autoPopupPos(); }); } public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { this._onTouched = fn; } /** * @internal */ public _$onClick($event: Event): void { $event.preventDefault(); $event.stopPropagation(); this._onTouched(); } public setDisabledState(disabled: boolean): void { this.disabled = disabled; } }
the_stack
import { CST } from './parse-cst' import { AST, Scalar, Schema, YAMLMap, YAMLSeq } from './types' import { Type, YAMLError, YAMLWarning } from './util' export { AST, CST } export { default as parseCST } from './parse-cst' /** * `yaml` defines document-specific options in three places: as an argument of * parse, create and stringify calls, in the values of `YAML.defaultOptions`, * and in the version-dependent `YAML.Document.defaults` object. Values set in * `YAML.defaultOptions` override version-dependent defaults, and argument * options override both. */ export const defaultOptions: Options export interface Options extends Schema.Options { /** * Default prefix for anchors. * * Default: `'a'`, resulting in anchors `a1`, `a2`, etc. */ anchorPrefix?: string /** * The number of spaces to use when indenting code. * * Default: `2` */ indent?: number /** * Whether block sequences should be indented. * * Default: `true` */ indentSeq?: boolean /** * Allow non-JSON JavaScript objects to remain in the `toJSON` output. * Relevant with the YAML 1.1 `!!timestamp` and `!!binary` tags as well as BigInts. * * Default: `true` */ keepBlobsInJSON?: boolean /** * Include references in the AST to each node's corresponding CST node. * * Default: `false` */ keepCstNodes?: boolean /** * Store the original node type when parsing documents. * * Default: `true` */ keepNodeTypes?: boolean /** * When outputting JS, use Map rather than Object to represent mappings. * * Default: `false` */ mapAsMap?: boolean /** * Prevent exponential entity expansion attacks by limiting data aliasing count; * set to `-1` to disable checks; `0` disallows all alias nodes. * * Default: `100` */ maxAliasCount?: number /** * Include line position & node type directly in errors; drop their verbose source and context. * * Default: `false` */ prettyErrors?: boolean /** * When stringifying, require keys to be scalars and to use implicit rather than explicit notation. * * Default: `false` */ simpleKeys?: boolean /** * The YAML version used by documents without a `%YAML` directive. * * Default: `"1.2"` */ version?: '1.0' | '1.1' | '1.2' } /** * Some customization options are availabe to control the parsing and * stringification of scalars. Note that these values are used by all documents. */ export const scalarOptions: { binary: scalarOptions.Binary bool: scalarOptions.Bool int: scalarOptions.Int null: scalarOptions.Null str: scalarOptions.Str } export namespace scalarOptions { interface Binary { /** * The type of string literal used to stringify `!!binary` values. * * Default: `'BLOCK_LITERAL'` */ defaultType: Scalar.Type /** * Maximum line width for `!!binary`. * * Default: `76` */ lineWidth: number } interface Bool { /** * String representation for `true`. With the core schema, use `'true' | 'True' | 'TRUE'`. * * Default: `'true'` */ trueStr: string /** * String representation for `false`. With the core schema, use `'false' | 'False' | 'FALSE'`. * * Default: `'false'` */ falseStr: string } interface Int { /** * Whether integers should be parsed into BigInt values. * * Default: `false` */ asBigInt: false } interface Null { /** * String representation for `null`. With the core schema, use `'null' | 'Null' | 'NULL' | '~' | ''`. * * Default: `'null'` */ nullStr: string } interface Str { /** * The default type of string literal used to stringify values * * Default: `'PLAIN'` */ defaultType: Scalar.Type doubleQuoted: { /** * Whether to restrict double-quoted strings to use JSON-compatible syntax. * * Default: `false` */ jsonEncoding: boolean /** * Minimum length to use multiple lines to represent the value. * * Default: `40` */ minMultiLineLength: number } fold: { /** * Maximum line width (set to `0` to disable folding). * * Default: `80` */ lineWidth: number /** * Minimum width for highly-indented content. * * Default: `20` */ minContentWidth: number } } } export class Document extends AST.Collection { cstNode?: CST.Document constructor(options?: Options) tag: never type: Type.DOCUMENT /** * Anchors associated with the document's nodes; * also provides alias & merge node creators. */ anchors: Document.Anchors /** The document contents. */ contents: AST.AstNode | null /** Errors encountered during parsing. */ errors: YAMLError[] /** * The schema used with the document. Use `setSchema()` to change or * initialise. */ schema?: Schema /** * Array of prefixes; each will have a string `handle` that * starts and ends with `!` and a string `prefix` that the handle will be replaced by. */ tagPrefixes: Document.TagPrefix[] /** * The parsed version of the source document; * if true-ish, stringified output will include a `%YAML` directive. */ version?: string /** Warnings encountered during parsing. */ warnings: YAMLWarning[] /** * List the tags used in the document that are not in the default * `tag:yaml.org,2002:` namespace. */ listNonDefaultTags(): string[] /** Parse a CST into this document */ parse(cst: CST.Document): this /** * When a document is created with `new YAML.Document()`, the schema object is * not set as it may be influenced by parsed directives; call this with no * arguments to set it manually, or with arguments to change the schema used * by the document. **/ setSchema( id?: Options['version'] | Schema.Name, customTags?: (Schema.TagId | Schema.Tag)[] ): void /** Set `handle` as a shorthand string for the `prefix` tag namespace. */ setTagPrefix(handle: string, prefix: string): void /** * A plain JavaScript representation of the document `contents`. * * @param arg Used by `JSON.stringify` to indicate the array index or property * name. If its value is a `string` and the document `contents` has a scalar * value, the `keepBlobsInJSON` option has no effect. * @param onAnchor If defined, called with the resolved `value` and reference * `count` for each anchor in the document. * */ toJSON(arg?: string, onAnchor?: (value: any, count: number) => void): any /** A YAML representation of the document. */ toString(): string } export namespace Document { interface Parsed extends Document { /** The schema used with the document. */ schema: Schema } interface Anchors { /** * Create a new `Alias` node, adding the required anchor for `node`. * If `name` is empty, a new anchor name will be generated. */ createAlias(node: AST.Node, name?: string): AST.Alias /** * Create a new `Merge` node with the given source nodes. * Non-`Alias` sources will be automatically wrapped. */ createMergePair(...nodes: AST.Node[]): AST.Merge /** The anchor name associated with `node`, if set. */ getName(node: AST.Node): undefined | string /** The node associated with the anchor `name`, if set. */ getNode(name: string): undefined | AST.Node /** * Find an available anchor name with the given `prefix` and a * numerical suffix. */ newName(prefix: string): string /** * Associate an anchor with `node`. If `name` is empty, a new name will be generated. * To remove an anchor, use `setAnchor(null, name)`. */ setAnchor(node: AST.Node | null, name?: string): void | string } interface TagPrefix { handle: string prefix: string } } /** * Recursively turns objects into collections. Generic objects as well as `Map` * and its descendants become mappings, while arrays and other iterable objects * result in sequences. * * The primary purpose of this function is to enable attaching comments or other * metadata to a value, or to otherwise exert more fine-grained control over the * stringified output. To that end, you'll need to assign its return value to * the `contents` of a Document (or somewhere within said contents), as the * document's schema is required for YAML string output. * * @param wrapScalars If undefined or `true`, also wraps plain values in * `Scalar` objects; if `false` and `value` is not an object, it will be * returned directly. * @param tag Use to specify the collection type, e.g. `"!!omap"`. Note that * this requires the corresponding tag to be available based on the default * options. To use a specific document's schema, use `doc.schema.createNode`. */ export function createNode( value: any, wrapScalars?: true, tag?: string ): YAMLMap | YAMLSeq | Scalar /** * YAML.createNode recursively turns objects into Map and arrays to Seq collections. * Its primary use is to enable attaching comments or other metadata to a value, * or to otherwise exert more fine-grained control over the stringified output. * * Doesn't wrap plain values in Scalar objects. */ export function createNode( value: any, wrapScalars: false, tag?: string ): YAMLMap | YAMLSeq | string | number | boolean | null /** * Parse an input string into a single YAML.Document. */ export function parseDocument(str: string, options?: Options): Document.Parsed /** * Parse the input as a stream of YAML documents. * * Documents should be separated from each other by `...` or `---` marker lines. */ export function parseAllDocuments( str: string, options?: Options ): Document.Parsed[] /** * Parse an input string into JavaScript. * * Only supports input consisting of a single YAML document; for multi-document * support you should use `YAML.parseAllDocuments`. May throw on error, and may * log warnings using `console.warn`. * * @param str A string with YAML formatting. * @returns The value will match the type of the root value of the parsed YAML * document, so Maps become objects, Sequences arrays, and scalars result in * nulls, booleans, numbers and strings. */ export function parse(str: string, options?: Options): any /** * @returns Will always include \n as the last character, as is expected of YAML documents. */ export function stringify(value: any, options?: Options): string
the_stack
import classNames from "classnames"; import React, { FunctionComponent } from "react"; import { useTranslation } from "react-i18next"; import { ButtonBase, ButtonProps, Fade, lighten, makeStyles, styled, Theme, Typography, useMediaQuery, useTheme, withStyles, } from "@material-ui/core"; import { Skeleton, ToggleButton, ToggleButtonGroup, ToggleButtonGroupProps, ToggleButtonProps, } from "@material-ui/lab"; import { GatewaySession } from "@renproject/ren-tx"; import { CompletedIcon, EmptyIcon, GatewayIcon, NavigateNextIcon, NavigatePrevIcon, } from "../../../components/icons/RenIcons"; import { depositNavigationBreakpoint } from "../../../components/layout/Paper"; import { ProgressWithContent, ProgressWithContentProps, PulseIndicator, } from "../../../components/progress/ProgressHelpers"; import { BridgeChainConfig } from "../../../utils/assetConfigs"; import { HMSCountdown } from "../../transactions/components/TransactionsHelpers"; import { DepositEntryStatus, DepositPhase, } from "../../transactions/transactionsUtils"; import { depositSorter, getDepositParams, getLockAndMintBasicParams, getRemainingGatewayTime, } from "../mintUtils"; const useBigNavButtonStyles = makeStyles((theme) => ({ root: { color: theme.palette.primary.main, fontSize: 90, transition: "all 1s, border 0.5s", display: "inline-flex", cursor: "pointer", "&:hover": { color: theme.palette.primary.dark, }, }, disabled: { opacity: 0.2, cursor: "default", }, hidden: { display: "none", opacity: 0, }, })); type BigNavButtonProps = ButtonProps & { direction: "next" | "prev"; }; export const BigNavButton: FunctionComponent<BigNavButtonProps> = ({ direction, disabled, hidden, className, onClick, }) => { const styles = useBigNavButtonStyles(); const rootClassName = classNames(styles.root, className, { [styles.disabled]: disabled, [styles.hidden]: hidden, }); const Icon = direction === "prev" ? NavigatePrevIcon : NavigateNextIcon; return ( <ButtonBase className={rootClassName} disabled={disabled} onClick={onClick}> <Icon fontSize="inherit" /> </ButtonBase> ); }; export const BigPrevButton: FunctionComponent<ButtonProps> = (props) => ( <BigNavButton direction="prev" {...props} /> ); export const BigNextButton: FunctionComponent<ButtonProps> = (props) => ( <BigNavButton direction="next" {...props} /> ); const offsetTop = 38; const offsetHorizontal = -42; export const DepositPrevButton = styled(BigPrevButton)({ position: "absolute", top: offsetTop, left: offsetHorizontal, }); export const DepositNextButton = styled(BigNextButton)({ position: "absolute", top: offsetTop, right: offsetHorizontal, }); type CircledIconContainerProps = { background?: string; color?: string; opacity?: number; size?: number; className?: string; }; const transition = "all 1s ease-out, border 0.5s ease-out"; const useCircledIconContainerStyles = makeStyles< Theme, CircledIconContainerProps >((theme) => ({ root: { borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", height: ({ size }) => size, width: ({ size }) => size, backgroundColor: ({ background = theme.palette.grey[400], opacity = 1 }) => opacity !== 1 ? lighten(background, 1 - opacity) : background, color: ({ color = "inherit" }) => color, }, })); export const CircledIconContainer: FunctionComponent<CircledIconContainerProps> = ({ background, color, size = 54, opacity, className, children, }) => { const styles = useCircledIconContainerStyles({ size, background, color, opacity, }); return <div className={classNames(styles.root, className)}>{children}</div>; }; export const useDepositToggleButtonStyles = makeStyles< Theme, DepositToggleButtonProps >((theme) => ({ root: { transition, background: theme.palette.common.white, padding: `2px 15px 2px 15px`, [theme.breakpoints.up(depositNavigationBreakpoint)]: { padding: 12, minWidth: 240, textAlign: "left", boxShadow: `0px 1px 3px rgba(0, 27, 58, 0.05)`, border: `2px solid ${theme.palette.common.white}!important`, "&:hover": { background: theme.palette.common.white, border: (props) => props.gateway ? "2px solid transparent" : `2px solid ${theme.palette.primary.main}!important`, }, }, [theme.breakpoints.up("lg")]: { minWidth: 280, }, "&:first-child": { paddingLeft: 2, marginRight: 1, [theme.breakpoints.up(depositNavigationBreakpoint)]: { paddingLeft: 12, marginRight: 0, }, }, "&:last-child": { paddingRight: 2, [theme.breakpoints.up(depositNavigationBreakpoint)]: { paddingRight: 12, }, }, }, selected: { [theme.breakpoints.up(depositNavigationBreakpoint)]: { background: `${theme.palette.common.white}!important`, border: (props) => props.gateway ? "2px solid transparent" : `2px solid ${theme.palette.primary.main}!important`, }, }, label: { [theme.breakpoints.up(depositNavigationBreakpoint)]: { width: "100%", display: "flex", alignItems: "center", justifyContent: "flex-start", }, }, })); type DepositToggleButtonProps = ToggleButtonProps & { gateway?: boolean; }; const DepositToggleButton: FunctionComponent<DepositToggleButtonProps> = ({ gateway, ...props }) => { const classes = useDepositToggleButtonStyles({ gateway }); return <ToggleButton classes={classes} {...props} />; }; export const DepositIndicator: FunctionComponent = () => { const theme = useTheme(); return ( <CircledIconContainer size={42} background={theme.palette.common.black} color={theme.palette.grey[200]} > <GatewayIcon fontSize="large" color="inherit" /> </CircledIconContainer> ); }; const useCircledProgressWithContentStyles = makeStyles({ container: { position: "relative", }, indicator: { position: "absolute", top: "8%", right: "8%", }, }); type CircledProgressWithContentProps = ProgressWithContentProps & { indicator?: boolean; }; export const CircledProgressWithContent: FunctionComponent<CircledProgressWithContentProps> = ({ color, size = 42, indicator = false, ...rest }) => { const styles = useCircledProgressWithContentStyles(); return ( <CircledIconContainer background={color} opacity={0.1} size={Math.floor(1.28 * size)} className={styles.container} > <ProgressWithContent color={color} size={size} {...rest} /> {indicator && <PulseIndicator className={styles.indicator} pulsing />} </CircledIconContainer> ); }; type DepositNavigationProps = ToggleButtonGroupProps & { tx: GatewaySession<any>; }; export const DepositNavigationResolver: FunctionComponent<DepositNavigationProps> = ( props ) => { const theme = useTheme(); const desktop = useMediaQuery(theme.breakpoints.up("md")); return ( <> {/*<Fade in={!desktop}>*/} {/* <MobileDepositNavigation {...props} />*/} {/*</Fade>*/} <Fade in={desktop}> <ResponsiveDepositNavigation {...props} /> </Fade> </> ); }; const StyledToggleButtonGroup = withStyles((theme) => ({ root: { transition, [theme.breakpoints.up(depositNavigationBreakpoint)]: { background: theme.customColors.whiteDarker, borderRadius: 20, }, }, grouped: { transition, [theme.breakpoints.up(depositNavigationBreakpoint)]: { border: "none", "&:first-child": { borderTopLeftRadius: 20, borderTopRightRadius: 20, }, "&:only-child": { borderBottomLeftRadius: 20, borderBottomRightRadius: 20, }, "&:not(:first-child)": { borderRadius: 46, marginLeft: 12, marginRight: 12, marginTop: 12, }, "&:last-child:not(:only-child)": { marginBottom: 12, }, }, }, }))(ToggleButtonGroup); const useResponsiveDepositNavigationStyles = makeStyles((theme) => ({ root: { transition, position: "absolute", left: 0, right: 0, top: -152, display: "flex", alignItems: "center", justifyContent: "center", [theme.breakpoints.up(depositNavigationBreakpoint)]: { display: "block", top: -72, left: 390, }, }, })); const useMoreInfoStyles = makeStyles((theme) => ({ root: { display: "none", marginLeft: 12, [theme.breakpoints.up(depositNavigationBreakpoint)]: { display: "flex", }, }, gateway: { marginLeft: 23, }, })); type MoreInfoProps = { gateway?: boolean; }; const MoreInfo: FunctionComponent<MoreInfoProps> = ({ gateway, children }) => { const styles = useMoreInfoStyles(); const className = classNames(styles.root, { [styles.gateway]: gateway, }); return <div className={className}>{children}</div>; }; export const ResponsiveDepositNavigation: FunctionComponent<DepositNavigationProps> = ({ value, onChange, tx, }) => { const { t } = useTranslation(); const styles = useResponsiveDepositNavigationStyles(); const theme = useTheme(); const mobile = !useMediaQuery( theme.breakpoints.up(depositNavigationBreakpoint) ); const sortedDeposits = Object.values(tx.transactions).sort(depositSorter); const { lockChainConfig, mintChainConfig } = getLockAndMintBasicParams(tx); return ( <div className={styles.root}> <StyledToggleButtonGroup exclusive size="large" onChange={onChange} value={value} orientation={mobile ? "horizontal" : "vertical"} > <DepositToggleButton gateway value="gateway"> <CircledIconContainer> <DepositIndicator /> </CircledIconContainer> <MoreInfo gateway> <div> <Typography variant="body1" color="textPrimary"> {t("mint.deposit-navigation-gateway-address-label")} </Typography> <Typography variant="body2"> {t("mint.deposit-navigation-active-for-label")}:{" "} <Typography variant="body2" component="span" color="primary"> <HMSCountdown milliseconds={getRemainingGatewayTime(tx.expiryTime)} /> </Typography> </Typography> </div> </MoreInfo> </DepositToggleButton> {sortedDeposits.map((deposit) => { const hash = deposit.sourceTxHash; const { lockCurrencyConfig } = getLockAndMintBasicParams(tx); const { lockConfirmations, lockTargetConfirmations, lockTxAmount, depositStatus, depositPhase, } = getDepositParams(tx, deposit); const StatusIcon = getDepositStatusIcon({ depositStatus, depositPhase, mintChainConfig, lockChainConfig, }); const isProcessing = depositPhase === DepositPhase.NONE || depositStatus === DepositEntryStatus.COMPLETING; const requiresAction = depositStatus === DepositEntryStatus.ACTION_REQUIRED; const completed = depositStatus === DepositEntryStatus.COMPLETED; const completing = depositStatus === DepositEntryStatus.COMPLETING; const confirmationProps = completed || completing ? {} : { confirmations: lockConfirmations, targetConfirmations: lockTargetConfirmations, }; let InfoContent: any = null; if (depositStatus === DepositEntryStatus.COMPLETED) { InfoContent = ( <div> <Typography variant="body1" color="textPrimary"> {lockTxAmount} {lockCurrencyConfig.short} </Typography> <Typography variant="body2" color="primary"> {t("mint.deposit-navigation-completed-label")} </Typography> </div> ); } else if (depositStatus === DepositEntryStatus.COMPLETING) { InfoContent = ( <div> <Typography variant="body1" color="textPrimary"> {lockTxAmount} {lockCurrencyConfig.short} </Typography> <Typography variant="body2" color="textSecondary"> {t("mint.deposit-navigation-completing-label")} </Typography> </div> ); } else if (depositStatus === DepositEntryStatus.PENDING) { InfoContent = ( <div> <Typography variant="body1" color="textPrimary"> {lockTxAmount} {lockCurrencyConfig.short} </Typography> {lockTargetConfirmations !== 0 ? ( <Typography variant="body2" color="textSecondary"> {t("mint.deposit-navigation-confirmations-label", { confirmations: lockConfirmations, targetConfirmations: lockTargetConfirmations, })} </Typography> ) : ( <Skeleton variant="text" width={100} height={14} /> )} </div> ); } else if (depositStatus === DepositEntryStatus.ACTION_REQUIRED) { InfoContent = ( <div> <Typography variant="body1" color="textPrimary"> {lockTxAmount} {lockCurrencyConfig.short} </Typography> {/* TODO: Differentiate between submitting and ready to mint */} {/* <Typography variant="body2" color="primary"> {t("mint.deposit-navigation-ready-to-mint-label")} </Typography> */} </div> ); } const Info = () => InfoContent; return ( <DepositToggleButton key={hash} value={hash}> <CircledProgressWithContent color={ completed ? theme.customColors.blue : lockCurrencyConfig.color } {...confirmationProps} processing={isProcessing} indicator={requiresAction} > <StatusIcon fontSize="large" /> </CircledProgressWithContent> <MoreInfo> <Info /> </MoreInfo> </DepositToggleButton> ); })} </StyledToggleButtonGroup> </div> ); }; type GetDepositStatusIconFnParams = { depositStatus: DepositEntryStatus; depositPhase: DepositPhase; lockChainConfig: BridgeChainConfig; mintChainConfig: BridgeChainConfig; }; export const getDepositStatusIcon = ({ depositStatus, depositPhase, lockChainConfig, mintChainConfig, }: GetDepositStatusIconFnParams) => { let StatusIcon = EmptyIcon; if (depositStatus === DepositEntryStatus.COMPLETED) { StatusIcon = CompletedIcon; } else if (depositPhase === DepositPhase.LOCK) { StatusIcon = lockChainConfig.Icon; } else if (depositPhase === DepositPhase.MINT) { StatusIcon = mintChainConfig.Icon; } return StatusIcon; };
the_stack
import * as Throttle from '../src/throttle'; import {Result} from '../src/throttle'; interface Person { firstName: string; lastName: string; } describe('Throttle test', function() { describe('raw', function() { it('should return the same amount of tasks', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'}, {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const {taskResults: formattedNames} = await Throttle.raw(tasks); /* Then */ expect(formattedNames).toHaveLength(10); }); it('should return in the same order', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const {taskResults: formattedNames} = await Throttle.raw(tasks); /* Then */ expect(formattedNames).not.toBeNull(); names.forEach((nameObject, index) => { expect(formattedNames[index]).toEqual(nameObject.firstName + ' ' + nameObject.lastName); }); }); it('should return in the same order with delayed tasks', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { setTimeout(() => resolve(firstName + ' ' + lastName), Math.random() * (1000 - 500) + 500); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const {taskResults: formattedNames} = await Throttle.raw(tasks); /* Then */ expect(formattedNames).not.toBeNull(); names.forEach((nameObject, index) => { expect(formattedNames[index]).toEqual(nameObject.firstName + ' ' + nameObject.lastName); }); }); it('should continue when a error occurred', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { reject(new Error()); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const {taskResults: formattedNames} = await Throttle.raw(tasks); /* Then */ expect(formattedNames).not.toBeNull(); expect(formattedNames).toHaveLength(5); }); it('should abort on the first error occurred', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { reject(new Error()); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ try { const {taskResults: formattedNames} = await Throttle.raw(tasks, {maxInProgress: 1, failFast: true}); } catch (failed) { expect(failed.taskResults[0]).toBeInstanceOf(Error); return; } /* Then */ throw new Error("Throttle didn't abort"); }); it('should resolve immediately on a empty task array', async function() { /* Given */ const names: Person[] = []; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const {taskResults: formattedNames} = await Throttle.raw(tasks); /* Then */ expect(formattedNames).not.toBeNull(); expect(formattedNames).toHaveLength(0); }); it('should gracefully handle the tasks even if maxInProgress is higher then the amount of tasks', async function() { /* Given */ const names: Person[] = [{firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const {taskResults: formattedNames} = await Throttle.raw(tasks); /* Then */ expect(formattedNames).not.toBeNull(); expect(formattedNames).toHaveLength(2); }); it('should allow overriding of the nextCheck method and allow it to throw a error, and this error should propagate', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise<string>((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const nextCheck = (status: Result<string>) => { return new Promise<boolean>((resolve, reject) => { if (status.amountStarted > 2) { return reject(new Error('Throw after 2 tasks started')); } resolve(true); }); }; try { const {taskResults: formattedNames} = await Throttle.raw(tasks, { maxInProgress: 2, failFast: false, nextCheck }); } catch (error) { //got error, everything good return; } throw new Error("Expected an error, didn't get one"); }); it("should throw when a task isn't a function", async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise<string>((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); tasks[2] = 'a string' as any; /* When */ try { const {taskResults: formattedNames} = await Throttle.raw(tasks); } catch (error) { //got error, everything good return; } throw new Error("Expected an error, didn't get one"); }); it('should return the task if its not a function and the ignoreIsFunctionCheck is true', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise<string>((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); tasks[2] = 'a string' as any; /* When */ const progressCallback = jest.fn(); const {taskResults: formattedNames} = await Throttle.raw(tasks, { ignoreIsFunctionCheck: true, progressCallback }); /* Then */ expect(progressCallback).toHaveBeenCalledTimes(5); expect(formattedNames[2]).toBe('a string'); }); it('should call the callback function every time a task is done', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise<string>((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const progressCallback = jest.fn(); const {taskResults: formattedNames} = await Throttle.raw(tasks, {progressCallback}); /* Then */ expect(progressCallback).toHaveBeenCalledTimes(5); }); it('should eventually stop if the nextTaskCheck returns false', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'}, {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise<string>((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const nextCheck = (status: Result<string>) => { return new Promise<boolean>((resolve, reject) => { if (status.amountStarted >= 6) { return resolve(false); } resolve(true); }); }; const result = await Throttle.raw(tasks, {maxInProgress: 2, failFast: false, nextCheck}); /* Then */ expect(result.taskResults).toHaveLength(6); expect(result.amountDone).toEqual(10); expect(result.nextCheckFalseyIndexes).toHaveLength(4); expect(result.amountStarted).toEqual(6); }); }); describe('all', function() { it('should only return the taskResults', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const formattedNames = await Throttle.all(tasks); /* Then */ expect(formattedNames).toBeInstanceOf(Array); expect(formattedNames).toHaveLength(5); }); it('should only return a single Error if a task failed', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { reject(new Error('noes')); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* Then */ try { const formattedNames = await Throttle.all(tasks); } catch (error) { expect(error).toBeInstanceOf(Error); expect(error.message).toEqual('noes'); return; } throw Error('expected error tho throw'); }); it('should continue if a error occurred when failFast is false', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { reject(new Error('noes')); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const formattedNames = await Throttle.all(tasks, {failFast: false}); /* Then */ expect(formattedNames).toHaveLength(5); }); it("should throw if one task isn't a function", async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); tasks[2] = 'a string' as any; /* When */ try { const result = await Throttle.all(tasks); } catch (error) { expect(error).toBeInstanceOf(Error); return; } throw new Error("Expected an error, didn't get one"); }); }); describe('sync', function() { it('should only return the taskResults', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const formattedNames = await Throttle.sync(tasks); /* Then */ expect(formattedNames).toBeInstanceOf(Array); expect(formattedNames).toHaveLength(5); }); it('should only return a single Error if a task failed', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { reject(new Error('noes')); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* Then */ try { const formattedNames = await Throttle.sync(tasks); } catch (error) { expect(error).toBeInstanceOf(Error); expect(error.message).toEqual('noes'); return; } throw Error('expected error to throw'); }); it('should continue if a error occurred when failFast is false', async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { reject(new Error('noes')); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); /* When */ const formattedNames = await Throttle.sync(tasks, {failFast: false}); /* Then */ expect(formattedNames).toHaveLength(5); }); it("should throw if one task isn't a function", async function() { /* Given */ const names: Person[] = [ {firstName: 'Irene', lastName: 'Pullman'}, {firstName: 'Sean', lastName: 'Parr'}, {firstName: 'Joe', lastName: 'Slater'}, {firstName: 'Karen', lastName: 'Turner'}, {firstName: 'Tim', lastName: 'Black'} ]; const combineNames = (firstName: string, lastName: string): Promise<string> => { return new Promise((resolve, reject) => { resolve(firstName + ' ' + lastName); }); }; //Create a array of functions to be run const tasks = names.map(u => () => combineNames(u.firstName, u.lastName)); tasks[2] = 'a string' as any; /* When */ try { const result = await Throttle.sync(tasks); } catch (error) { expect(error).toBeInstanceOf(Error); return; } throw new Error("Expected an error, didn't get one"); }); }); });
the_stack
import { Component, NgModule, ViewChild, } from '@angular/core'; import { TsSortDirective, TsSortHeaderComponent, } from '@terminus/ui/sort'; import { TsTableColumnsChangeEvent, TsTableComponent, TsTableDataSource, TsTableDensity, TsTableModule, } from '@terminus/ui/table'; import { FakeDataSource, TestData, } from './test-helpers'; @Component({ template: ` <table ts-table [dataSource]="dataSource" [density]="density" [columns]="columns" [id]="myId" (columnsChange)="columnsChanged($event)" #myTable="tsTable" > <ng-container tsColumnDef="column_a"> <th ts-header-cell *tsHeaderCellDef> Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> </ng-container> <ng-container tsColumnDef="column_b"> <th ts-header-cell *tsHeaderCellDef> Column B</th> <td ts-cell *tsCellDef="let row">{{ row.b }}</td> </ng-container> <ng-container tsColumnDef="column_c"> <th ts-header-cell *tsHeaderCellDef> Column C</th> <td ts-cell *tsCellDef="let row">{{ row.c }}</td> </ng-container> <ng-container tsColumnDef="special_column"> <td ts-cell *tsCellDef="let row">fourth_row</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="myTable.columnNames"></tr> <tr ts-row *tsRowDef="let row; columns: myTable.columnNames"></tr> <tr ts-row *tsRowDef="let row; columns: ['special_column']; when: isFourthRow"></tr> </table> `, }) export class TableApp { @ViewChild(TsTableComponent, { static: true }) public table!: TsTableComponent<TestData>; public density: TsTableDensity = 'comfy'; public dataSource: FakeDataSource | null = new FakeDataSource(); public columnsToRender = ['column_a', 'column_b', 'column_c']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); public myId = 'foobar'; public isFourthRow = (i: number, _rowData: TestData) => i === 3; public columnsChanged(e: TsTableColumnsChangeEvent) {} } @Component({ template: ` <table ts-table [dataSource]="dataSource" [columns]="columns"> <ng-container tsColumnDef="column_a"> <th ts-header-cell *tsHeaderCellDef> Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> </ng-container> <ng-container tsColumnDef="special_column"> <td ts-cell *tsCellDef="let row">fourth_row</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="['column_a']"></tr> <tr ts-row *tsRowDef="let row; columns: ['column_a']"></tr> <tr ts-row *tsRowDef="let row; columns: ['special_column']; when: isFourthRow"></tr> </table> `, }) export class TableWithWhenRowApp { @ViewChild(TsTableComponent, { static: true }) public table!: TsTableComponent<TestData>; public dataSource: FakeDataSource | null = new FakeDataSource(); public isFourthRow = (i: number, _rowData: TestData) => i === 3; public columnsToRender = ['column_a']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); } @Component({ template: ` <table ts-table [dataSource]="dataSource" [columns]="columns" tsSort> <ng-container tsColumnDef="column_a" noWrap="true"> <th ts-header-cell *tsHeaderCellDef ts-sort-header="a">Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> </ng-container> <ng-container tsColumnDef="column_b" noWrap="true"> <th ts-header-cell *tsHeaderCellDef>Column B</th> <td ts-cell *tsCellDef="let row">{{ row.b }}</td> </ng-container> <ng-container tsColumnDef="column_c"> <th ts-header-cell *tsHeaderCellDef>Column C</th> <td ts-cell *tsCellDef="let row">{{ row.c }}</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="columnsToRender"></tr> <tr ts-row *tsRowDef="let row; columns: columnsToRender"></tr> </table> `, }) export class ArrayDataSourceTableApp { public underlyingDataSource = new FakeDataSource(); public dataSource = new TsTableDataSource<TestData>(); public columnsToRender = ['column_a', 'column_b', 'column_c']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); @ViewChild(TsTableComponent, { static: true }) public table!: TsTableComponent<TestData>; @ViewChild(TsSortDirective, { static: true }) public sort!: TsSortDirective; @ViewChild(TsSortHeaderComponent, { static: true }) public sortHeader!: TsSortHeaderComponent; public constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } } @Component({ template: ` <table ts-table [dataSource]="dataSource" [columns]="columns" tsSort> <ng-container tsColumnDef="column_a" alignment="left"> <th ts-header-cell *tsHeaderCellDef>Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> </ng-container> <ng-container tsColumnDef="column_b" alignment="center"> <th ts-header-cell *tsHeaderCellDef>Column B</th> <td ts-cell *tsCellDef="let row">{{ row.b }}</td> </ng-container> <ng-container tsColumnDef="column_c" alignment="right"> <th ts-header-cell *tsHeaderCellDef>Column C</th> <td ts-cell *tsCellDef="let row">{{ row.c }}</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="columnsToRender"></tr> <tr ts-row *tsRowDef="let row; columns: columnsToRender"></tr> </table> `, }) export class TableColumnAlignmentTableApp { public underlyingDataSource = new FakeDataSource(); public dataSource = new TsTableDataSource<TestData>(); public columnsToRender = ['column_a', 'column_b', 'column_c']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); @ViewChild(TsTableComponent, { static: true }) public table!: TsTableComponent<TestData>; public constructor() { this.underlyingDataSource.data = []; // Add a row of data this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } } @Component({ template: ` <table ts-table [dataSource]="dataSource" [columns]="columns" tsSort> <ng-container tsColumnDef="column_a" alignment="top"> <th ts-header-cell *tsHeaderCellDef>Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="columnsToRender"></tr> <tr ts-row *tsRowDef="let row; columns: columnsToRender"></tr> </table> `, }) export class TableColumnInvalidAlignmentTableApp { public underlyingDataSource = new FakeDataSource(); public dataSource = new TsTableDataSource<TestData>(); public columnsToRender = ['column_a']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); @ViewChild(TsTableComponent, { static: true }) public table!: TsTableComponent<TestData>; public constructor() { this.underlyingDataSource.data = []; // Add a row of data this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } } @Component({ template: ` <table ts-table [dataSource]="dataSource" [columns]="columns"> <ng-container tsColumnDef="column_a" sticky> <th ts-header-cell *tsHeaderCellDef> Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> <td ts-footer-cell *tsFooterCellDef> Footer A</td> </ng-container> <ng-container tsColumnDef="column_b"> <th ts-header-cell *tsHeaderCellDef> Column B</th> <td ts-cell *tsCellDef="let row">{{ row.b }}</td> <td ts-footer-cell *tsFooterCellDef> Footer B</td> </ng-container> <ng-container tsColumnDef="column_c" stickyEnd> <th ts-header-cell *tsHeaderCellDef> Column C</th> <td ts-cell *tsCellDef="let row">{{ row.c }}</td> <td ts-footer-cell *tsFooterCellDef> Footer C</td> </ng-container> <ng-container tsColumnDef="special_column"> <td ts-cell *tsCellDef="let row">fourth_row</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="columnsToRender; sticky: true"></tr> <tr ts-row *tsRowDef="let row; columns: columnsToRender"></tr> <tr ts-row *tsRowDef="let row; columns: ['special_column']; when: isFourthRow"></tr> <tr ts-footer-row *tsFooterRowDef="columnsToRender; sticky: true"></tr> </table> `, }) export class PinnedTableHeaderColumn { @ViewChild(TsTableComponent, { static: true }) public table!: TsTableComponent<TestData>; public dataSource: FakeDataSource | null = new FakeDataSource(); public columnsToRender = ['column_a', 'column_b', 'column_c']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); public isFourthRow = (i: number, _rowData: TestData) => i === 3; } @Component({ template: ` <div style="width: 250px;"> <table ts-table [dataSource]="dataSource" [columns]="columns" (columnsChange)="columnsChanged($event)" #myTable="tsTable" > <ng-container tsColumnDef="column_a"> <th ts-header-cell *tsHeaderCellDef> Column A</th> <td ts-cell *tsCellDef="let row">{{ row.a }}</td> </ng-container> <ng-container tsColumnDef="column_b"> <th ts-header-cell *tsHeaderCellDef> Column B</th> <td ts-cell *tsCellDef="let row">{{ row.b }}</td> </ng-container> <ng-container tsColumnDef="column_c"> <th ts-header-cell *tsHeaderCellDef> Column C</th> <td ts-cell *tsCellDef="let row">{{ row.c }}</td> </ng-container> <tr ts-header-row *tsHeaderRowDef="myTable.columnNames"></tr> <tr ts-row *tsRowDef="let row; columns: myTable.columnNames"></tr> </table> </div> `, }) export class ScrollingTable { public dataSource: FakeDataSource | null = new FakeDataSource(); public columnsToRender = ['column_a', 'column_b', 'column_c']; public columns = this.columnsToRender.map(c => ({ name: c, width: 100, })); public columnsChanged(e: TsTableColumnsChangeEvent) {} } /** * NOTE: Currently all exported Components must belong to a module. So this is our useless module to avoid the build error. */ @NgModule({ imports: [ TsTableModule, ], declarations: [ ArrayDataSourceTableApp, PinnedTableHeaderColumn, ScrollingTable, TableApp, TableColumnAlignmentTableApp, TableColumnInvalidAlignmentTableApp, TableWithWhenRowApp, ], }) export class TsTableTestComponentsModule {}
the_stack
interface HttpClientBase { get(url: string, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: Object, headersHandler?: () => { [header: string]: string } ); post(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ); put(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ); patch(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ); delete(url: string, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, headersHandler?: () => { [header: string]: string } ); } class HttpClient implements HttpClientBase { /** location.origin may not be working in some releases of IE. And locationOrigin is an alternative implementation **/ public static locationOrigin: string = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/'; /** **/ get(url: string, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: Object, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, null, "GET", callback, errorCalback, statusCodeCallback, null, headersHandler); } post(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, dataToSave, "POST", callback, errorCalback, statusCodeCallback, contentType, headersHandler); } put(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, dataToSave, "PUT", callback, errorCalback, statusCodeCallback, contentType, headersHandler); } patch(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, dataToSave, "PATCH", callback, errorCalback, statusCodeCallback, contentType, headersHandler); } delete(url: string, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, null, "DELETE", callback, errorCalback, statusCodeCallback, null, headersHandler); } private executeAjax(url: string, dataToSave: any, httpVerb: string, callback: (data: any) => any, errorCallback: (xhr, ajaxOptions, thrown) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { jQuery.ajax(url, { data: JSON.stringify(dataToSave), type: httpVerb, success: (data: any, textStatus: string, jqXHR: JQueryXHR): any => { if (callback !== null) { callback(data); } }, error: (xhr, ajaxOptions, thrown) => { if (errorCallback != null) { errorCallback(xhr, ajaxOptions, thrown); } }, statusCode: statusCodeCallback, contentType: contentType, headers: headersHandler ? headersHandler() : undefined }); } } class AuthHttpClient implements HttpClientBase { /** location.origin may not be working in some releases of IE. And locationOrigin is an alternative implementation **/ public static locationOrigin: string = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/'; get(url: string, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: Object, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, null, "GET", callback, errorCalback, statusCodeCallback, null, headersHandler); } post(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, dataToSave, "POST", callback, errorCalback, statusCodeCallback, contentType, headersHandler); } put(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, dataToSave, "PUT", callback, errorCalback, statusCodeCallback, contentType, headersHandler); } patch(url: string, dataToSave: any, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, dataToSave, "PATCH", callback, errorCalback, statusCodeCallback, contentType, headersHandler); } delete(url: string, callback: (data: any) => any, errorCalback: (xhr: JQueryXHR, ajaxOptions: string, thrown: string) => any, statusCodeCallback: { [key: string]: any; }, headersHandler?: () => { [header: string]: string } ) { this.executeAjax(url, null, "DELETE", callback, errorCalback, statusCodeCallback, null, headersHandler); } private executeAjax(url: string, dataToSave: any, httpVerb: string, callback: (data: any) => any, errorCallback: (xhr, ajaxOptions, thrown) => any, statusCodeCallback: { [key: string]: any; }, contentType: string, headersHandler?: () => { [header: string]: string } ) { //http://api.jquery.com/JQ.ajax/ jQuery.ajax(url, { data: JSON.stringify(dataToSave), type: httpVerb, success: (data: any, textStatus: string, jqXHR: JQueryXHR): any => { if (callback !== null) { callback(data); } }, error: (xhr, ajaxOptions, thrown) => { if (errorCallback != null) { errorCallback(xhr, ajaxOptions, thrown); } }, statusCode: statusCodeCallback, contentType: contentType, headers: headersHandler ? headersHandler() : undefined, beforeSend: (xhr, settings) => { xhr.setRequestHeader('Authorization', 'bearer ' + sessionStorage.getItem('access_token')); } }); } /** * Get oAuth token through username and password. The token will be saved in sessionStorage. */ getToken(url: string, username: string, password: string, callback: (data: any) => any, errorCallback: (xhr, ajaxOptions, thrown) => any, statusCodeCallback: { [key: string]: any; }) { jQuery.ajax(url + 'token', { data: { 'grant_type': 'password', 'username': username, 'password': password }, type: 'POST', success: (data: any, textStatus: string, jqXHR: JQueryXHR): any => { if (data != null && data != '') { sessionStorage.setItem("access_token", data.access_token); sessionStorage.setItem("expires_in", data.expires_in); } if (callback !== null) { callback(data); } }, error: (xhr, ajaxOptions, thrown) => { if (errorCallback != null) { errorCallback(xhr, ajaxOptions, thrown); } }, statusCode: statusCodeCallback, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', headers: { Accept: 'text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8', } }); } }
the_stack
import { expect } from "chai"; import { BSplineCurve3d } from "../../bspline/BSplineCurve"; import { InterpolationCurve3d, InterpolationCurve3dOptions } from "../../bspline/InterpolationCurve3d"; import { Arc3d } from "../../curve/Arc3d"; import { AnyCurve } from "../../curve/CurveChain"; import { GeometryQuery } from "../../curve/GeometryQuery"; import { LineSegment3d } from "../../curve/LineSegment3d"; import { LineString3d } from "../../curve/LineString3d"; import { Loop } from "../../curve/Loop"; import { RegionOps } from "../../curve/RegionOps"; import { DirectSpiral3d } from "../../curve/spiral/DirectSpiral3d"; import { AxisScaleSelect, Geometry } from "../../Geometry"; import { Angle } from "../../geometry3d/Angle"; import { FrameBuilder } from "../../geometry3d/FrameBuilder"; import { Matrix3d } from "../../geometry3d/Matrix3d"; import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d"; import { Range3d } from "../../geometry3d/Range"; import { Transform } from "../../geometry3d/Transform"; import { MomentData } from "../../geometry4d/MomentData"; import { IModelJson } from "../../serialization/IModelJsonSchema"; import { Checker } from "../Checker"; import { GeometryCoreTestIO } from "../GeometryCoreTestIO"; import { prettyPrint } from "../testFunctions"; import { MatrixTests } from "./Point3dVector3d.test"; /* eslint-disable no-console */ describe("FrameBuilder", () => { it("HelloWorldA", () => { const ck = new Checker(); const builder = new FrameBuilder(); ck.testFalse(builder.hasOrigin, "frameBuilder.hasOrigin at start"); for (const points of [ [Point3d.create(0, 0, 0), Point3d.create(1, 0, 0), Point3d.create(0, 1, 0)], [Point3d.create(0, 0, 0), Point3d.create(1, 0, 0), Point3d.create(1, 1, 0)], [Point3d.create(1, 2, -1), Point3d.create(1, 3, 5), Point3d.create(-2, 1, 7)], ]) { builder.clear(); const point0 = points[0]; const point1 = points[1]; const point2 = points[2]; ck.testUndefined(builder.getValidatedFrame(), "frame in progress"); const count0 = builder.announcePoint(point0); const count1 = builder.announcePoint(point0); // exercise the quick out. ck.testExactNumber(count0, count1, "repeat point ignored"); ck.testTrue(builder.hasOrigin, "frameBuilder.hasOrigin with point"); ck.testUndefined(builder.getValidatedFrame(), "no frame for minimal data"); ck.testUndefined(builder.getValidatedFrame(), "frame in progress"); builder.announcePoint(point1); ck.testUndefined(builder.getValidatedFrame(), "frame in progress"); ck.testCoordinate(1, builder.savedVectorCount(), "expect 1 good vector"); ck.testUndefined(builder.getValidatedFrame(), "frame in progress"); builder.announcePoint(point2); ck.testUndefined(builder.getValidatedFrame(true), "frame in progress"); const rFrame = builder.getValidatedFrame(false); if (ck.testPointer(rFrame, "expect right handed frame") && rFrame && ck.testBoolean(true, rFrame.matrix.isRigid(), "good frame")) { const inverse = rFrame.inverse(); if (ck.testPointer(inverse, "invertible frame") && inverse) { const product = rFrame.multiplyTransformTransform(inverse); ck.testBoolean(true, product.isIdentity, "correct inverse"); const q0 = inverse.multiplyPoint3d(point0); const q1 = inverse.multiplyPoint3d(point1); const q2 = inverse.multiplyPoint3d(point2); ck.testCoordinate(0.0, q0.x, "point0 is origin"); ck.testCoordinate(0.0, q0.y, "point0 is origin"); ck.testCoordinate(0.0, q0.z, "point0 is origin"); ck.testCoordinate(0.0, q1.y, "point1 on x axis"); ck.testCoordinate(0.0, q1.z, "point1 on x axis"); ck.testCoordinate(0.0, q2.z, "point2 on xy plane"); ck.testCoordinateOrder(0.0, q2.y, "point1 in positive y plane"); } } } ck.checkpoint("FrameBuilder"); expect(ck.getNumErrors()).equals(0); }); it("BsplineCurve", () => { const ck = new Checker(); const builder = new FrameBuilder(); for (const points of [ [Point3d.create(0, 0, 0), Point3d.create(1, 0, 0), Point3d.create(0, 1, 0)], [Point3d.create(0, 0, 0), Point3d.create(1, 0, 0), Point3d.create(1, 1, 0), Point3d.create(2, 1, 0)], [Point3d.create(1, 2, -1), Point3d.create(1, 3, 5), Point3d.create(2, 4, 3), Point3d.create(-2, 1, 7)], ]) { builder.clear(); const linestring = LineString3d.create(points); const bcurve = BSplineCurve3d.createUniformKnots(points, 3); builder.clear(); builder.announce(linestring); const frameA = builder.getValidatedFrame(); builder.clear(); builder.announce(bcurve); const frameB = builder.getValidatedFrame(); if (ck.testDefined(frameA) && frameA && ck.testDefined(frameB) && frameB) { ck.testTransform(frameA, frameB, "Frame from linestring versus bspline"); } } expect(ck.getNumErrors()).equals(0); }); it("InterpolationCurve", () => { const ck = new Checker(); const builder = new FrameBuilder(); for (const points of [ [Point3d.create(0, 0, 0), Point3d.create(1, 0, 0), Point3d.create(0, 1, 0)], [Point3d.create(0, 0, 0), Point3d.create(1, 0, 0), Point3d.create(1, 1, 0), Point3d.create(2, 1, 0)], [Point3d.create(1, 2, -1), Point3d.create(1, 3, 5), Point3d.create(2, 4, 3), Point3d.create(-2, 1, 7)], ]) { builder.clear(); const linestring = LineString3d.create(points); const curve = InterpolationCurve3d.create(InterpolationCurve3dOptions.create({fitPoints: points})); builder.clear(); builder.announce(linestring); const frameA = builder.getValidatedFrame(); builder.clear(); builder.announce(curve); const frameB = builder.getValidatedFrame(); if (ck.testDefined(frameA) && frameA && ck.testDefined(frameB) && frameB) ck.testTransform(frameA, frameB, "Frame from linestring versus interpolation curve"); } expect(ck.getNumErrors()).equals(0); }); it("GenericCurve", () => { const ck = new Checker(); const allGeometry: GeometryQuery[] = []; const builder = new FrameBuilder(); const localToWorld = Transform.createOriginAndMatrix(Point3d.createZero(), Matrix3d.createRotationAroundAxisIndex(2, Angle.createDegrees(55))); const spiral = DirectSpiral3d.createCzechCubic(localToWorld, 20, 21); GeometryCoreTestIO.captureCloneGeometry(allGeometry, spiral); builder.announce(spiral); const frame = builder.getValidatedFrame(); if (ck.testDefined(frame) && frame) ck.testTransform(localToWorld, frame, "Frame from spiral ctor versus frenet"); GeometryCoreTestIO.saveGeometry(allGeometry, "FrameBuilder", "GenericCurve"); expect(ck.getNumErrors()).equals(0); }); it("HelloVectors", () => { const ck = new Checker(); const builder = new FrameBuilder(); ck.testFalse(builder.hasOrigin, "frameBuilder.hasOrigin at start"); builder.announcePoint(Point3d.create(0, 1, 1)); ck.testExactNumber(0, builder.savedVectorCount()); ck.testExactNumber(0, builder.savedVectorCount()); builder.announceVector(Vector3d.create(0, 0, 0)); ck.testExactNumber(0, builder.savedVectorCount()); // loop body assumes each set of points has 3 leading independent vectors for (const vectors of [ [Vector3d.create(1, 0, 0), Vector3d.create(0, 1, 0), Vector3d.create(0, 0, 1)], ]) { builder.clear(); const vector0 = vectors[0]; const vector1 = vectors[1]; const vector2 = vectors[2]; builder.announce(Point3d.create(1, 2, 3)); ck.testUndefined(builder.getValidatedFrame(), "frame in progress"); builder.announce(vector0); ck.testExactNumber(1, builder.savedVectorCount()); builder.announce(vector0); ck.testExactNumber(1, builder.savedVectorCount()); ck.testExactNumber(2, builder.announceVector(vector1)); ck.testExactNumber(2, builder.announceVector(vector1.plusScaled(vector0, 2.0))); ck.testExactNumber(3, builder.announceVector(vector2)); } ck.checkpoint("FrameBuilder"); expect(ck.getNumErrors()).equals(0); }); it("HelloWorldB", () => { const ck = new Checker(); const nullRangeLocalToWorld = FrameBuilder.createLocalToWorldTransformInRange(Range3d.createNull(), AxisScaleSelect.Unit, 0, 0, 0, 2.0); ck.testTransform(Transform.createIdentity(), nullRangeLocalToWorld, "frame in null range"); for (const range of [Range3d.createXYZXYZ(1, 2, 3, 5, 7, 9)] ) { for (const select of [ AxisScaleSelect.Unit, AxisScaleSelect.LongestRangeDirection, AxisScaleSelect.NonUniformRangeContainment]) { const localToWorld = FrameBuilder.createLocalToWorldTransformInRange(range, select, 0, 0, 0, 2.0); if (ck.testPointer(localToWorld)) { MatrixTests.checkProperties(ck, localToWorld.matrix, select === AxisScaleSelect.Unit, // unit axes in range are identity select === AxisScaleSelect.Unit, // and of course unitPerpendicular select === AxisScaleSelect.Unit, // and of course rigid. true, // always invertible true); // always diagonal const worldCorners = range.corners(); worldCorners.push(range.fractionToPoint(0.5, 0.5, 0.5)); } } } expect(ck.getNumErrors()).equals(0); }); it("NonPlanarCurves", () => { const ck = new Checker(); const allGeometry: GeometryQuery[] = []; const a = 10.0; let x0 = 0.0; const y0 = 0.0; for (const zz of [-1, 0, 1]) { const loop = new Loop(); loop.tryAddChild(LineString3d.create(Point3d.create(0, 0, 0), Point3d.create(a, 0, 0), Point3d.create(a, a, 0), Point3d.create(0, a, 0))); loop.tryAddChild(Arc3d.createCircularStartMiddleEnd( Point3d.create(0, a, 0), Point3d.create(-a / 2, a / 2, zz), Point3d.create(0, 0, 0))); ck.testBoolean( Geometry.isSmallMetricDistance(zz), curvesToPlane(loop) !== undefined, "planarity test"); const rawSums = RegionOps.computeXYAreaMoments(loop)!; console.log("curves", prettyPrint(IModelJson.Writer.toIModelJson(loop))); console.log("raw moment products", prettyPrint(rawSums.toJSON())); const principalMoments = MomentData.inertiaProductsToPrincipalAxes(rawSums.origin, rawSums.sums)!; console.log("inertia", prettyPrint(principalMoments.toJSON())); GeometryCoreTestIO.captureGeometry(allGeometry, loop, x0, y0, 0); GeometryCoreTestIO.showMomentData(allGeometry, rawSums, false, x0, y0, 0); x0 += 2.0 * a; } ck.testUndefined(curvesToPlane(LineSegment3d.createXYZXYZ(1, 2, 4, 5, 2, 3))); GeometryCoreTestIO.saveGeometry(allGeometry, "FrameBuilder", "NonPlanarCurves"); expect(ck.getNumErrors()).equals(0); }); }); /** test if a curve collection is planar within tolerance. * * The plane considered is as returned by FrameBuilder.createRightHandedFrame () */ function curvesToPlane(curves: AnyCurve, tolerance: number = Geometry.smallMetricDistance): Transform | undefined { const localToWorldA = FrameBuilder.createRightHandedFrame(undefined, curves)!; if (!localToWorldA) return undefined; const worldToLocalA = localToWorldA.inverse()!; const rangeA = curves.range(worldToLocalA); if (rangeA.zLength() <= tolerance) return localToWorldA; return undefined; }
the_stack
declare const openpgp: any const requestTimeOut = 1000 * 180 const KloakNode_publicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- mDMEXjMkUBYJKwYBBAHaRw8BAQdAFD5n6LecvYdEOn65nCjOvn/C2bco7JPkGg2a xY0rGoa0NEtsb2FrIEluZm9ybWF0aW9uIFRlY2hub2xvZ2llcyBJbmMuIDxub2Rl QEtsb2FrLmFwcD6IeAQQFgoAIAUCXjMkUAYLCQcIAwIEFQgKAgQWAgEAAhkBAhsD Ah4BAAoJEIZGYoUSMbEZH4sA/06bmj/UPFTsEnsL20hJqNs3hgf9/3cSSoCLTLix BM93AP9LlfBWMgUtF5N1Aah6pDABTtgCAk+dlODe1vh8PuwHB9HfxN/CARAAAQEA AAAAAAAAAAAAAAD/2P/gABBKRklGAAEBAABIAEgAAP/hAExFeGlmAABNTQAqAAAA CAABh2kABAAAAAEAAAAaAAAAAAADoAEAAwAAAAEAAQAAoAIABAAAAAEAAAD4oAMA BAAAAAEAAAD6AAAAAP/tADhQaG90b3Nob3AgMy4wADhCSU0EBAAAAAAAADhCSU0E JQAAAAAAENQdjNmPALIE6YAJmOz4Qn7/wgARCAD6APgDASIAAhEBAxEB/8QAHwAA AQUBAQEBAQEAAAAAAAAAAwIEAQUABgcICQoL/8QAwxAAAQMDAgQDBAYEBwYECAZz AQIAAxEEEiEFMRMiEAZBUTIUYXEjB4EgkUIVoVIzsSRiMBbBctFDkjSCCOFTQCVj FzXwk3OiUESyg/EmVDZklHTCYNKEoxhw4idFN2WzVXWklcOF8tNGdoDjR1ZmtAkK GRooKSo4OTpISUpXWFlaZ2hpand4eXqGh4iJipCWl5iZmqClpqeoqaqwtba3uLm6 wMTFxsfIycrQ1NXW19jZ2uDk5ebn6Onq8/T19vf4+fr/xAAfAQADAQEBAQEBAQEB AAAAAAABAgADBAUGBwgJCgv/xADDEQACAgEDAwMCAwUCBQIEBIcBAAIRAxASIQQg MUETBTAiMlEUQAYzI2FCFXFSNIFQJJGhQ7EWB2I1U/DRJWDBROFy8ReCYzZwJkVU kiei0ggJChgZGigpKjc4OTpGR0hJSlVWV1hZWmRlZmdoaWpzdHV2d3h5eoCDhIWG h4iJipCTlJWWl5iZmqCjpKWmp6ipqrCys7S1tre4ubrAwsPExcbHyMnK0NPU1dbX 2Nna4OLj5OXm5+jp6vLz9PX29/j5+v/bAEMADAwMDAwMFAwMFB0UFBQdJx0dHR0n MScnJycnMTsxMTExMTE7Ozs7Ozs7O0dHR0dHR1NTU1NTXV1dXV1dXV1dXf/bAEMB Dg8PGBYYKBYWKGFCNkJhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh YWFhYWFhYWFhYWFhYWFhYf/aAAwDAQACEQMRAAAB5TbVttW21bbVst4QwNaG0FYS 9dE8yrqlE8ijr2RPNBsZJqItW+YZZaMhttW21bbVttW21bbVtl0l87f6ZtH908Mx f6c322B2ya3LRXdBW6CZoYXODMG1s2Jp4smOCD2yDbattq22rbEpV0q20xFerlG0 RIZW2m2w6nlYjoCQ3/NaISXrhXqptBTMlwzLnbGkVQO0r8EHtkG21bbVN8zu2xPf IKG0ThpGmITsKM8pBtxN24lUq6C6rNWvnYHfPkvTl2wSzGgou8BoeGRYMdWrUvWX Om2wsQdtLZP2s6c1+fk3Q16PVr9dF5LGLrlYd7K3bdKydLB9xHV460mZW+osTiJz 4myVDbTDWYvO1zvc15b8i58rXdBU2jHbZDdPQ9KcbZ4JJLCrJYaZV7fpYm5pfREL Vr9eARl4VbSdbUO9L1HPdLRiDJgi1JUNZ5Dr2jvzVxzl1pi6mJyyb851nMt0U0OG +bWl/UXZ539SUbKS1Wa0bTKqjKmZGXqRl6kUt7zDmL+qtwiyIXnKVEjSdtNWct3n M6l4SmuRzTS3Var86zsK+16GwYu7lm+E9GiBETNpyqiZ00ZpTtdAw5xGtb1OfvWT 0RubFZG9IdOgq+dNtq/QGSH9ryoFaehpXIzt2b1pllzdbaMT0Xl1QdAOW3mJXohK 4pMxUFbChZvNVYv367ClbY2vQV+0eoHrFgyBhw/M6Ay0DJOnHWAOVh6A7hhbdaye V+PNQV76vui26Lk+lXm6BYF2hBj58y2xnmmSDIUuJFDUFra/pG2m9QK2cs9ZaFRn gkaxkITKXfTCrWSQtWTzvUYFdTdcyormTlsms9Ry11ZdausbHNDhbtwFBBiiUzIt RSCBOTIvImEolBMDlbM3TYoOzJekssqCrKXBFUHK29Ed2aNsjjB0Oqd0V2/NZiII kYiCJS9YWYn87Z9DavtKlubSPNitEJJXZ1dyu5kqyb1TSxrtUKURpSQqhAr651X2 +22Y22pXQ844KdeemfuhQrEXS6ZQU6MnPrRrCuGlsS4UyrSlJK7OnVadKijhdXTc RGjmAEWoVMGcaNsBttW21bbU7uebcMnSywNpFTkl1SjWZMjSkyNBaYiMp0FplKrQ hQNgzqrSyJU22wTbYW21bbVttW21Ls6nEdAqlfbB9LdTMaQqBJkTSoTEV4IyXIm4 mJQtm+arRtgu21bbVttW21bbVttW21bbURwzxFkSpz1xNNmNuir1WAmmUkHtmNtq 22rbattq22r/2gAIAQEAAQUC/mxGovkvlJfLS8EPlpfLS+U8Ff6kAJYhYSAwhSmL WUsWT9zjfucT9zjctqI0Oj4sxhkEf6gTC6ANFutbRbRp+8SAJ5zK08XiGUnsY/51 KSoojCGiNUjjgSj75ISJ5zKWj7hALKaMgFlJT/NIQVlKQgRQ5MCn31KCRNOZTHFm 5PbCqPN5vN5DsU9lJx/mEpKilIQIYaun31KCRNMZTFFk+A4sW1X7m/c2bORqt5kv gwos0U+LUMfvxR4CGPL+YUoIE0xlMMGTo5umNAqpDH3FIQtyWTUlSCyKg6fdgRVo TmUig+8taUCWVUpt40yKo6O8PTAOpLH3lxpkE0JhLWPuJGRAxES0paVg/eWtMaZZ VSlMKlJBKFQzCUO7NZbcaBj7q1pjEl4tT1URFIeyhQ9rZLAqygvUNM60tNwgsGvZ dxGhySKkMUPaWLNgqQqGYSiU5SQjp+7LKmJK5FSKRBVhIT2uEUUsadkJxTbp0VSk mIHFmNYdSGSS0xrU0QBP3Joc2FKQri0D711lzoMa95U5IfBxDKTi0EALVQKUVGKO nbEF4p+/coTSMVWn70sQlSpKo1RSZjvIMVycbYao4hyLzMUdXT+auy7cdQ+/cw81 KVFCgQodrkdUnC2HRG5F1caMikM/zVyay246f5i7ixMC6HtcjpX7Nv8AusqBKcih IAP8wSEtV1EGbxTUSoxCiO6loQ1XqAzeyP3yZpvnlHOhQKFIVml3H7tXCD91SrjR QffXPGhrullkk9gKtEQY7KWlAku1F6qIjUXyg+UGYiwVIMqxK7ZXaf8AdeUH7qEf fklRG5Lha2AVNMDloCAw09pbgIalKWUwksJCfurjy7Rmi3cfujwtvYg+9LcvUlML AA7HiGGCEiScqaUlTRGEfzEyOw4XPsK9m1LhPUO6lBIlmMjSkqaUhP3Jo3Wj5hZJ LRASwAkfzBTUNPs3R1k4QGkiTRXZawgSSFZSiv31RIU/d0tMaU/zmCauZWUknFg5 CM5JUoIC1FZRH/qeRWCGTUu2VVMS8WtZWY4/uhhLwZH3wmr5bKHSn3rpbWaDshWC nEiv3kB8Oywz90NCe1KtafuqUEJJKis1PeBdRGvE/dj7q4K+6lo4dpOw73EuZUaD 7gJBQoLTGuv3UKYWC8g1rZP3atC3kGVhqV2HaeXEMmp+7GvAg1aV1+5Vhb5jKq/f CqPmPP7kkuAOrWqv8xHJg6sKr/qJcuLLWv8AmkSFDCgoZfz/AAapOyl1/nAopKZQ rtX+cK2SSyoBlRP8+mRSWJEntV5OodQ6h1DyDzeR7FQDKyf9RhRDExfNS8kuo75J fMSzKyon/fV//9oACAEDEQE/Ae2+ymvomX5Ndtt6EdxlaI9hNMDZt3RQRqR2Tl6M B2kWgUEedb7JGg2ibehkif56T8I1NDy+6+dMh9GwB20xPo5EIQ5Y+umM6S/FoI8N NNNIDPyjUfkyjRYedJeWEfVPbdJYh4Hl3xeD4cg4tj50P4uwzTkPojgJRH1LLN6R 0CC+Qw86T8okmSSnSGWuC+9H0ZTMtAjQTpx+dMg4b7Nha1ARHsgKGpFFppA50yjX GNCljGynWUbY/k007mXLTTHhvSnx2yixl6FMUxdrtdqIoDT47yEWHc8O12taGX1r 7//aAAgBAhEBPwHsAtGP837A7oNwKcQTiP0RH80z/JJ1hCuSy8oJTUmUK7hwk32Q hXJQmUXdFoej/hZRrsCT2Rjt5KZsfCdRk/N8pFa07WmmMabZwrlPEezaB5TNlyL0 Gtu5ttjL0ch1hKizHrpHUN9sPLPz2Ql6JCPLLzoT2CJKMbwEoiSjEB5dsUwHoy8I ZdgFoACZ6SYw9S7vy7QyRoB2Rn+bvCZWjstDLyhr6O7s8DuOg1loNAGZ9NQeza1q Q7NT9o7Qfo1aSIpN9wNIkC01pTtLQHlll/L6QJD7hfdfdKch7//aAAgBAQAGPwL+ b4PU9+Hfj/qXR9T0fSKvXR6qfEvzfEsry4d9Xo9f9QVU9HroH6/eqXQez97T+doH 8Xo/j9+pdB7P8xr/ADdA6B1Vw/mKl/yXU8Gaff0/mqB0DyV/MZKfwdTw78X7T9p6 EP2e+j1/mPi8jw/mMlP4PJXDsWPvdQq6xn7HRWnajp93Mun8xkp68H1eXl3Cf5mi n8O1fuYh0DoXp97JTqXV1GhD+PanoHX79VOiNA/V8Pu5/c11euj07epdVPJXao4u o0Ifxaj8WPvVLqp1W9O2Xq69wl5dte3Dtq9A6q1+5kni6jQ/zBy+x68fuHuO1HUu peR49tQ+H38/Nj79C6HiH8fuEdie/wAHkf5tKXX+YqPaDq6jvXsT2xD+H858nX+Z 5ieBeJ7g96On81ro9NX0h5Fj7nUaPpFXoA/J9afwZAdDxDr3LDp/M68X06Op7696 qdI9H6/c0dRoWF/m82U9j2Dr9/qdBoHo+p4J+7ROpdVavq0en3ajj2B+59rP3qR/ j26np92pdE6B6P4/zGXcDsR92pfw7afcyHfV1Vo6D+Zp2DA7Bg96l6up/mOL0H85 lTXsT3r2qXUup/1OT2r2x9Hq6vI/6ow+5Xtkf9UZF1P3cC6f6oxHAfeqHV4n/U2K ePav36j/AFLpxdS6fzFPJ1D1/wBRUHF1LoP5r4Oo/wBQ0T2oP5yoeun89p/qP0/n dP8AUej17cfuce2n++v/xAAzEAEAAwACAgICAgMBAQAAAgsBEQAhMUFRYXGBkaGx wfDREOHxIDBAUGBwgJCgsMDQ4P/aAAgBAQABPyH/APL/ANkoqHcrfXf8E3016pr4 Ul1PxeP/ANDVgze5fReDRebPhesfK/8AhFO9L/ia9YUYL0SxLBVHJUOCarnF4V/+ gM9PqgIEXe+1dNJ+6AEH/wCFEkBXOMfun/lSi42+mk7+NRGH/wDMgDdLnyr3j5u3 z5P/AONw8BeEA68/8HL/APg5St8KbFMb/wDlfkA/8QL1/DzQIBAf/jTvAWKGDgrL /wC+segZ+LAiLLxZeLDxS4je+kEhqL1/+QD5n/mbAfwUhX/8SdIC+Hngqf5zWJug rqfNbn+th/8AF9f1ouReUT8bdUONFztGnPxUBFKo/wDx8ny5svpfuhH/AON6kBZK 4OCp+P8Adzhdvzn5sS90UTYLH/DIKg6XtYzyqzTmUKl/+Gd0HHzV8Lunh/8AjRpB ZzgcFcK/s/6QeUz+LJPwUZ/+PFebvdXD/wAnI8n/AOBR5GmPEUfgXugamiP/AOGc F6C9Hi9A+D/hAeKnk/7k0eTeFVn/APBLeC/mG7qzGV+bwLqQw3C/7yr4LIih92Uz G+GPdz9PdASpsxrTIH1F/A48WT9ZYsL/AO//AJiHg55P+ao7FKf951LwebNqXor9 A8UqDH/MJx/Kzer/AL6MKI1y0pzeDS9WFQc3nZfF6DF5Av8AwbvB+rFixYH/ANNm XBQlHmwFKU/76R/C/wAd/wDwR7s0vONSSeLGfv8AFCUWcuqfRH/JkHtWK8IaFwD6 sWLFixYpo8lHzf3KjKU//B3+6fFQ50Dfhz/+D5Roifm/FyKZ+NgEtX0OL6n1Zmti xYsWLFixYv8AOWReH/BT/wDD9Jnv1Yh6pnif+wnzKMvixeQ08t9Q7us8KU1Qf/lT p4BfvGlKf/izbyfN8ZPH/fiDRKoge1phctSNRUcF4/8A5B0sHu9i+NZwnztU8jtj nqlP+CyVZDfpU8Cn/wAFb+yhZSJvkq/mbE/8jfyX9K/yf5olDmnF+f8Ajtj/APDk qfAuHj+6jLL7/wCIoL7OmClk3BcEj57qzGU3lMp3N9rS7qzngs4EcP8Aa6L8n/Y8 vhrn7KG9qcf9j/oGt8d38MRXoM3tf0VRGA5slMcU0v8A42lkJK7GH7oUGP8A8ICj jL8+f85PkvP8VSzxS4U4/wDwYa3/ABn6r7S3u/GgQIP+TnPm+lNkjBf/AHsa/But z5Vr/wDhiwZ+6YzXIfVceQ3mun32Bnkq/wCybgqUGeN+E/4A/wCrL99FwsPFRlS3 q1+7CGCta/8A4ChSd91EYpgHxfg5NXHy35dl+aKWf+NZN9C+s2Iw/wDxaiQ+r7V8 nef+Na1/6UpQs8w9v+fgCrB4ooydUxPZYV+v+5mv+jr/APgP/wAbWv8A+ApSlP8A oMx/xKP2KbTi2YuOi/0Na1/4Js9UWD/k2bNa/wDAJ6sdaFKU/wCSIetb9jn/AFx/ OyJJZfQVrWv/ACegCD/g8lw2bNmrdNKJf+IENipSlKx6K55m8Lwf/g84HF2HDWta 3uvf/wAEts2bNWrf/wAC9vf/AAUv+TjeO5f/AMJLmLCP3YXZWtathpG1HuyWRs2b NWkGx0XukMs9P+C+UnPqqBLWmf8A4ln6eSiB8sGHmrVq0hVP+EqbNmzZs1KLW2Zp SlFy1KksmHB/+Q6lroElvC5Vr/2bNmzZs2f/AMBSlDs0laSeP/8AKY8+FmzRGNme P/xTZ/8AxFkEtV6KoEtbxP8A8yYMXK0sxTzszx/+VIc0SuQvO6+Kzv8A+fgcni+/ e/8Aky+3/L2X2X2f8UdFW9XW8u/i5mD/APQ+TRegmi8yUfgWThP+KGLUOlR93wLy 7/8Aqr//2gAMAwEAAhEDEQAAEPPPPN9wvHG09vPPPPPPCUWQAIof+uPPPPOFI9wB BNwz3B9PPPB80BQjirE0Wp/FfK8pATahLy8w7oFKPOlKEjjDj4DglMQVNon+GmMc ccpJwNYFtUC1m7Thedr3IxLZ0jAcU8vEcNmVYOzlbE/aSeTdLV3bXZ+z9+R6fxvG SVC2P42JnPS1cbQL4CHkLkqtfPO7kqZASrOsU84XPPPDn5RVQUFUO7vfPPPPPgMb yUBsZfvPPPPPPPH/AOz3z7zzzzz/xAAzEQEBAQADAAECBQUBAQABAQkBABEhMRBB UWEgcfCRgaGx0cHh8TBAUGBwgJCgsMDQ4P/aAAgBAxEBPxD8ChfbcxGWZf8A8deI fJg9C4uRUGw/EzwsDW3fRGs7K5OZPUZ8TYfg+JYmvmebL2tuOzCI+u7kzzQbtzMc MF6tspt8LI+dhUgkOx10W4086pwMGQ2yb34y5S6I+HjPueobgTxbF1j5MfgDmlsM eLTVwU49y53zrk7BZ6iLWd6s719CDkm/2LqmHKOpLQ7iO53HCOB4M8YFXXxhyWlD hMc3cWWc9y7mwSh0lOY9NuZsN1Pdpr6RxhkktDZx3ZBaSkEy3MeJvDcIxGG8vB3i yCLwQ8BfHuTjuW8prh8pXgmoasucAcPw68nfi6deD4HoSqRd/EL3fBgvZYvmxYgX BfQ/+WWeba/H/9oACAECEQE/EPwL0vlVnZfYhGZJ64jdcyZw/wDwM5mPER79++Jb BQ4mb8v4gDWX0EH1kt5gPNr823a56m7Tr8B+W0fQ3ggHySLPvPnwc6mOI4LZngbG ifplHcJ4Ijr3B6boOrgE+ArhBd730S6D1ztsX7J34+RdRPgbN8CSfCSY5HUPmedt tttzj2PvzbJzyEL4Ittusg+WDplrt1t2S+gTueEF03YhzHXqcC5VkeoMMlYy/GD5 s8kOZc3SS3tDgnzAyJdSdvB4sZjzLfA02/B7p6RxAtlljs9HSPOvvIJcePibRvge 4NnzEmzTFkFr4zLFcJn3Pw58Nm8n4M/ALpEfeRa/ifpdpfbasYX0hLuO+CrvL/8A HpGC7h/SfiJfzKvL+L//2gAIAQEAAT8Q/wDywpED3j+b1Q+Cf9UH9AXGJfMt9X8/ 7V18/blXyH3P9X/0j/U3fIPt+uaioSH/APQ5sF6pZ/iPNLg/bv8ANYj44v7u+D9p f1NL+n/Y0H80H9X2f5fFb/JD/VakBwNliJKIORvJhToD5XYkeHSvRB76/wDzwVgJ WxmLw5+/FiWHgsMUnfJ+D/diob3s/HFBCAcB/wDhMMKVeAu51Ydo7f6LJLwT/wA5 sh8l1Mv3U5CfI3qF8uPpro0Tp/8AzA0xf0eWm/Y/0sJEDl8H+6GE/wArDqxDT/8A CFI8q9XbbM7ez/RW5fR/+AHG+S6fPlYUccJyWIcXhOH/APK4+BqcBfvuryvuwk3T 2/0KabhBxZLyzT/8ABjyrdnM+T2+/wCKQkB+fhQIAkA4jFeOHub618wp3Ko5Y+aD iJf78/1XRyNgDq4f/wAgo5/R7vTnlXlfNkyBy/ft9Uj7qyKFP/wHg5S3ujP/AHfd UDQ8H+OLIgiVHoqV7KfzeoPj/wBUXv8A4+at/u/90SfnZP6aHJHmP8NqRBDpxvhy gcXfyrwpHqylo8Pr/wDECsGrQxd68evqwoaYeX+qZ9/8ixT/AL/PyXo93+DC/b7s SEdHf/ihAEBwVnaAH2i/Z78beyzqFYWLCuezfp5rRlPlPp/3UyR6f5Huopeai+h8 NUjCY/8A4TU9Y/u+qZOcl4KGDAEB4P8A8D/2BkflfB7v6HDP/aMBNeXt8UIQEB/x H3Lr4H/tl/8AM2Kxn/Gz/wBTHHT2PkeqcF9++E8/8+/D2f8An/4Ofxj/AN+rwTMF Wiol5Fy4fTeEf/woIAcHa+CyGgcfA/37qjmSW7/1TiKvsbooP/7nqxYwcEfbv+r9 aPxRALFSpp/xgcuPK+A7raP5j/osoU9sprhAntIP3UQdMRsr15Pj/uvW/wDarEum H0pJJDxjYAR+Z+SwCv3D8lh0D2MlQJIPLUn2hPt4s9OODgeq0Bzle/b/AMlAQD/4 +aCVV/g2ckf/AE56u+SKD4MP4sV8k/nf+hmxH/PE1Hyv9eWtpxgcB4CkDvQefvxY 8z65/NLBj5fhzc4b/F/4E4Uu+0+XX90ENIPiwpOM+bsEmBoQcpgC7KDzqiNl6Uv7 ZFahCp5cPy1ocHg6f7//AAAUCAceH+6QQn/6JUHso/NIg4CP+ii8/wDO74PTHX3z 7pa/J4j17/6WCf7AqAeBxrq8qLOvAy+NVh82kculWJHEeWoO7g8Hi4Rhh4P90rW+ QBrs/HD/APGAY2Ao8v7LFfD+lgH/AEKf8aYHe9f680Il3/xPV6A4X9/8KeG+GjHw 2EPSfsyzt6B9v/l1fCalvAErcjnA/uyAMcPL5qKDKUUf/jARAe3/AAf3fWQPz/8A KIA/6FP+jCY/R/jKOxVCeTsawEhNKWLvd8lm8lH5/wDl+BH8H/tkfiLyvPLy/wCq nzJ79UEIiDCkg8tChQsWLFixYsV8f3L/ADYku78Gf/ghT/8ABGQFgnXl9/zZtu30 f/f+Fk9Y/JfgcP7shiJHzsVnxTX1TmZ2+CmgjgP7sfl1ddaFCxYsWL7JwosyNPSD 8sXK9+lf1VVl1fLfIQPy7/0LEee3X4ObILfLj+39VvL+Ff5o2VXp/wDVkAUeT+n/ AHTbxw48Geri9An44aYfKb8nNLMnhLDbyv8Aie1LjKwvbna8t4KFS3FChYsWZg3v fvos+J6t/Jr1LdqX/kOZqod/HBYk/wCIieqeX4O7Pew9X9FcL2TKt3iH3z+KDnfj K9Yfigyx8cNMKTic1QCKM4Y4H8Nja5/9KX9k/m/4Tw1JPSD81ZDyj6pAB4/5BWgo WR6ODqsykvyPy2UVerx/4zzVgeWOV9vqu5eKYAQWdKerIR8S/wCEtlFXz/AWG+M7 f6sMHt3+a/8AQrAIH7qKUQl8XYfhylcD5D91Iowy/i+9z9hZDwI1yP8ArVBQA1Ww T8av6f3U5Zd8rZob6f20mYOil9ylPzNBB0j/AJQrF5/qisy4v+EF188vR80KHuX9 eP8Ao/8AAoUrIeOf7VQDpm+zw3/NGCuH9R+7r+wH1n93/ISKZjZLNcwj9+itJi48 vbVMzstGgb2vLVRo2DcjpOnzWpdBRA9xZcOqbASeHt/qhCB0f9FX/gUf8OhxFQM0 YqcgB/FnL2L7sB/wF1HE398fuL4VNfDzVFKRN8Ha+rJ+A4OAqww6HmgAEBRo0aNG psm7x/5Q2VTxn+rtAeTX8tf+FVV/wooo/wCGoXo2hYO4GHwZZ/BT+abaFSfJeJ4n 82d+Ql8lWL8Ha+KqbejoPBYAHev9qK2aNVGjRs2atVVVf+FFFFFFHtwg+XizLL3z fFi58f8AJDavof8A3+al0FP2f7qLEZ4Cxge9H+aP+i1HlXgTQJSrU/8ARpVVFtMk VXkRXX/JpooWdufkPBZeOcP7/wCmvgYHkebAJIkieKHc2Hl//A1V2yw82MH/AAR5 P/wAf+A1zLj/AJECyE8UQx/yaLxrH8vRWWlZfulF4h78v/4Jlu33Oz6uy/1vmquu uzilH/rDdL/of+ArYmOn/oTo6/8AwPRN9fP/AIv16PXl/wDwqzCSUVm8Dw+LoOOH yV11/wDCYbTE4aJOvin8Lrf9H/g36XuPNEnHzVU5bMdrqrs+2ejp/tqJ4DVrr6Dw f/ijvcvIf7LN2WiU+JP7/wDwUIpLmNWnN5D/APAGmmksqBzc0o3LXXeWQYePbVEh dVv/ANRnz/8Aka9Rp49lNER0SmODy811VaNP/wAIGmlq/wDFXXSWD9BVSSuq0it7 Pn/z/wDKgxpz/Y8XcA78nze4SxEqatmzZs/9Jq2f+H/GwwHmluDz21A8BytkMP3f n/8AMLSB+/mxn9a/DZKRi+H90HJP/Js2bNn/APAhlAe7gGXy8VWXNz/gP78WRPOg 4P8A880LH2/rxcRfR/tZ7Ke180PSj9xfUvofmp9Kl3PxQ8j83jo+FVJVW50j41Z/ S8c/n/8AQ+f/AE6/FDh+xl/mAT/F/lUx/NEAheIStQgDzCheU/JP8XiF+B/uKnEf tZuU8PRh+D/9Vf/ZiJAEExYIADgWIQRzaBIzcn3PCZmgip+GRmKFEjGxGQUCXjMn ngIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRCGRmKFEjGxGZfCAQCyUAqZ zM/b2CYU2Ywz4fkF3vS07qHdTsVwkPevBgJDUwEAhLAKN2DgWVcdn8Bo2btA+JmY 6NCtmhS858t58dQOSgK4OAReMyRQEgorBgEEAZdVAQUBAQdApsFVu9L0Oa4HDdJz QgTM/D9wFNIrso9x0CkdaOhIGgIDAQgHiGEEGBYIAAkFAl4zJFACGwwACgkQhkZi hRIxsRnazAEArDx0bSaVYspsD2TdRDeAD9Sbtb8MHgr+bjU4mHlKzeYA/RpmFn1D PT17OWXpUfDuuSaA+2Px8WMtc9trMDIiGCEM =mdDQ -----END PGP PUBLIC KEY BLOCK----- ` const Kloak_API_PublicKey = ` -----BEGIN PGP PUBLIC KEY BLOCK----- mDMEXqT4zhYJKwYBBAHaRw8BAQdA7/0QRxAraH+3wvR4nWaAW9cFl32CS5J9JC+B vUspCDm0E0FQSSA8QVBJQEtsb2FrLmFwcD6IeAQQFgoAIAUCXqT4zgYLCQcIAwIE FQgKAgQWAgEAAhkBAhsDAh4BAAoJEF9YG3WhPvBOzkcA/3f9B3e8PE78qFJHPy37 Cd6BIESJmXEGqheucTRczOOLAQCCChwHN8zArHRKdE+4bZ42iqKCW84fM8sXazbe XPFQDbg4BF6k+M4SCisGAQQBl1UBBQEBB0B7NFm+kreqw0D9mUp9qPDK54xeKmor /hnICKjiRxtpVAMBCAeIYQQYFggACQUCXqT4zgIbDAAKCRBfWBt1oT7wTkycAQC7 LLsNzS2Zra2hm9kvKafeTYpTmiEUQbxIuyPEySP9xQEAkB70RnDuoJQzKuEeeAEd ToNMnoWOMu0xq5gTORcSDgI= =jcgy -----END PGP PUBLIC KEY BLOCK----- ` /** * * @param public_key * * * @param private_key * https://github.com/openpgpjs/openpgpjs/issues/97 */ const signPublicKey = ( public_key, private_key ) => { // Returns a new public key which is public_key + signature(public_key) var dataToSign = { userid: public_key.users[0].userId, key: public_key.primaryKey } const signaturePacket = new openpgp.packet.Signature () signaturePacket.signatureType = openpgp.enums.signature.cert_generic signaturePacket.publicKeyAlgorithm = 1 signaturePacket.hashAlgorithm = 2 signaturePacket.keyFlags = [ openpgp.enums.keyFlags.certify_keys | openpgp.enums.keyFlags.sign_data ] signaturePacket.preferredSymmetricAlgorithms = [] signaturePacket.preferredSymmetricAlgorithms.push (openpgp.enums.symmetric.aes256 ) signaturePacket.preferredSymmetricAlgorithms.push (openpgp.enums.symmetric.aes192 ) signaturePacket.preferredSymmetricAlgorithms.push (openpgp.enums.symmetric.aes128 ) signaturePacket.preferredSymmetricAlgorithms.push (openpgp.enums.symmetric.cast5 ) signaturePacket.preferredSymmetricAlgorithms.push ( openpgp.enums.symmetric.tripledes ) signaturePacket.preferredHashAlgorithms = [] signaturePacket.preferredHashAlgorithms.push ( openpgp.enums.hash.sha256 ) signaturePacket.preferredHashAlgorithms.push ( openpgp.enums.hash.sha1 ) signaturePacket.preferredHashAlgorithms.push ( openpgp.enums.hash.sha512 ) signaturePacket.preferredCompressionAlgorithms = [] signaturePacket.preferredCompressionAlgorithms.push ( openpgp.enums.compression.zlib ) signaturePacket.preferredCompressionAlgorithms.push ( openpgp.enums.compression.zip ) signaturePacket.sign ( private_key.getEncryptionKeyPacket(), dataToSign ) var originalPackets = public_key.toPacketlist () var packetlist = new openpgp.packet.List () for ( let i = 0; i < originalPackets.length; i++ ) { packetlist.push ( originalPackets [i] ) } packetlist.push ( public_key.users[0].userId ) packetlist.push ( signaturePacket ) return new openpgp.key.Key ( packetlist ) } class encryptoClass { private _privateKey = null private KloakNode_publicKey = null private Kloak_API_PublicKey = null private Kloak_AP_publicKey = null private myPublicKey = null public imapData: IinputData = null public localServerPublicKey = "" private requestPool: Map < string, { CallBack: ( err?: Error, cmd?: QTGateAPIRequestCommand ) => void, cmd: QTGateAPIRequestCommand, timeOut: NodeJS.Timeout } > = new Map () private makeKeyReady = ( CallBack ) => { openpgp.key.readArmored ( this._keypair.privateKey ).then ( data => { this._privateKey = data.keys return this._privateKey[0].decrypt ( this.password ).then ( data => { return openpgp.key.readArmored ( this._keypair.publicKey ).then ( data => { this.myPublicKey = data.keys return openpgp.key.readArmored ( KloakNode_publicKey ).then ( data => { this.KloakNode_publicKey = data.keys return openpgp.key.readArmored ( Kloak_API_PublicKey ).then ( data => { this.Kloak_API_PublicKey = data return this.readImapIInputData ( CallBack ) }) }) }) }) }) } public decryptMessage = ( encryptoText: string, CallBack ) => { return this.decryptMessageToZipStream ( encryptoText, async ( err, _data ) => { if ( err ) { return CallBack ( err ) } let ret = null const data = Buffer.from ( _data, 'base64' ).toString () if ( /^-----BEGIN PGP/i.test ( data )) { CallBack () return this.Kloak_AP_publicKey = ( await openpgp.key.readArmored( data )).keys } try { ret = JSON.parse ( data ) } catch ( ex ) { return CallBack ( ex ) } return CallBack ( null, ret ) }) } public decryptMessageToZipStream ( encryptoText: string, CallBack ) { const option = { privateKeys: this._privateKey, publicKeys: this.Kloak_API_PublicKey, message: null } let ret = false return openpgp.message.readArmored ( encryptoText ).then ( data => { option.message = data return openpgp.decrypt( option ) }).then ( _plaintext => { if ( !ret) { ret = true return CallBack ( null, _plaintext.data ) } }) /* .catch ( ex => { if ( !ret) { ret = true return CallBack ( ex ) } }) */ } private onDoingRequest = async ( encryptoText: string, uuid: string ) => { const self = this const request = this.requestPool.get ( uuid ) if ( !request ) { return } return this.decryptMessage ( encryptoText, ( err, obj: QTGateAPIRequestCommand ) => { if ( err ) { return self.connectInformationMessage.showErrorMessage ( err ) } if ( obj.error !== -1 ) { clearTimeout ( request.timeOut ) } return request.CallBack ( null, obj ) }) } constructor ( private _keypair: keypair, private password: string, private connectInformationMessage: connectInformationMessage, ready: ( err?: Error ) => void ) { this.makeKeyReady (() => { return this.getServerPublicKey ( ready ) }) connectInformationMessage.socketIo.on ( 'doingRequest', ( encryptoText: string, uuid: string ) => { return this.onDoingRequest ( encryptoText, uuid ) }) } public getServerPublicKey ( CallBack ) { const publicKey = this._keypair.publicKey const self = this return this.connectInformationMessage.sockEmit ( 'keypair', publicKey, async ( err, data ) => { if ( err ) { self.connectInformationMessage.showErrorMessage ( err ) return CallBack ( err ) } const uu = await openpgp.key.readArmored ( data ) self.localServerPublicKey = uu.keys return CallBack () }) } public encrypt ( message, CallBack ) { const option = { privateKeys: this._privateKey, publicKeys: this.KloakNode_publicKey, message: openpgp.message.fromText ( message ), compression: openpgp.enums.compression.zip } const self = this return openpgp.encrypt ( option ).then ( ciphertext => { return CallBack ( null, ciphertext.data ) }).catch ( err => { return CallBack ( 'systemError' ) }) } public emitRequest ( cmd: QTGateAPIRequestCommand, CallBack ) { const uuid = cmd.requestSerial = uuid_generate() const self = this const option = { privateKeys: this._privateKey, publicKeys: this.Kloak_AP_publicKey, message: openpgp.message.fromText ( JSON.stringify ( cmd )), compression: openpgp.enums.compression.zip } this.requestPool.set ( uuid, { CallBack: CallBack, cmd: cmd, timeOut: setTimeout(() => { self.requestPool.delete ( uuid ) return CallBack ( new Error ( 'timeOut' )) }, requestTimeOut )}) return openpgp.encrypt ( option ).then ( ciphertext => { return self.connectInformationMessage.sockEmit ( 'doingRequest' , uuid, ciphertext.data, err => { return CallBack ( err ) }) }).catch ( err => { return CallBack ( 'systemError' ) }) } public async decrypt_withMyPublicKey ( message, CallBack ) { const option = { privateKeys: this._privateKey, publicKeys: this.myPublicKey, message: await openpgp.message.readArmored ( message ) } return openpgp.decrypt( option ).then ( data => { if ( data.signatures[0].valid ) { return CallBack ( null, data.data ) } return ( new Error ('signatures error!')) }).catch ( ex => { return CallBack ( ex ) }) } public encrypt_withMyPublicKey ( message, CallBack ) { const option = { privateKeys: this._privateKey, publicKeys: this.myPublicKey, message: openpgp.message.fromText ( message ), compression: openpgp.enums.compression.zip } return openpgp.encrypt ( option ).then ( ciphertext => { return CallBack ( null, ciphertext.data ) }).catch ( err => { return CallBack ( err ) }) } public saveImapIInputData ( CallBack ) { return this.encrypt_withMyPublicKey ( JSON.stringify ( this.imapData ), ( err, data ) => { if ( err ) { return CallBack ( err ) } localStorage.setItem ( "imapData", data ) return CallBack () }) } public emitLocalCommand ( emitName: string, command: any, CallBack ) { const self = this const option = { privateKeys: this._privateKey, publicKeys: this.localServerPublicKey, message: openpgp.message.fromText ( JSON.stringify ( command )), compression: openpgp.enums.compression.zip } return openpgp.encrypt ( option ).then ( ciphertext => { return self.connectInformationMessage.sockEmit ( emitName, ciphertext.data, CallBack ) }).catch ( err => { return CallBack ( err ) }) } public async decrypt_withLocalServerKey ( command, CallBack ) { const self = this const option = { privateKeys: this._privateKey, publicKeys: this.localServerPublicKey, message: await openpgp.message.readArmored ( command ) } const data = await openpgp.decrypt( option ) if ( ! data.signatures[0].valid ) { return CallBack ( new Error ('Key signatures error!')) } let ret = null try { ret = JSON.parse ( data.data ) } catch ( ex ) { return CallBack ( ex ) } return CallBack ( null, ret ) } public readImapIInputData ( CallBack ) { const data = localStorage.getItem ( "imapData" ) if ( !data || !data.length ) { return CallBack () } return this.decrypt_withMyPublicKey ( data, ( err, data ) => { if ( err ) { return CallBack () } try { this.imapData = JSON.parse ( data ) } catch ( ex ) { return CallBack ( ) } return CallBack () }) } }
the_stack
import type { Driver } from "@effect/core/io/Schedule/Driver" import type { SinkInternal } from "@effect/core/stream/Sink/operations/_internal/SinkInternal" import { concreteSink } from "@effect/core/stream/Sink/operations/_internal/SinkInternal" import { Handoff } from "@effect/core/stream/Stream/operations/_internal/Handoff" import { HandoffSignal } from "@effect/core/stream/Stream/operations/_internal/HandoffSignal" import { concreteStream, StreamInternal } from "@effect/core/stream/Stream/operations/_internal/StreamInternal" import { SinkEndReason } from "@effect/core/stream/Stream/SinkEndReason" /** * Aggregates elements using the provided sink until it completes, or until * the delay signalled by the schedule has passed. * * This operator divides the stream into two asynchronous islands. Operators * upstream of this operator run on one fiber, while downstream operators run * on another. Elements will be aggregated by the sink until the downstream * fiber pulls the aggregated value, or until the schedule's delay has passed. * * Aggregated elements will be fed into the schedule to determine the delays * between pulls. * * @param sink Used for the aggregation * @param schedule Used for signalling for when to stop the aggregation * * @tsplus fluent ets/Stream aggregateWithinEither */ export function aggregateWithinEither_<R, E, A, R2, E2, A2, S, R3, B, C>( self: Stream<R, E, A>, sink: LazyArg<Sink<R2, E2, A | A2, A2, B>>, schedule: LazyArg<Schedule<S, R3, Option<B>, C>>, __tsplusTrace?: string ): Stream<R | R2 | R3, E | E2, Either<C, B>> { type EndReason = SinkEndReason type Signal = HandoffSignal<E | E2, A> return Stream.fromEffect( Effect.tuple( Handoff.make<Signal>(), Ref.make<EndReason>(SinkEndReason.ScheduleEnd), Ref.make(Chunk.empty<A2>()), schedule().driver(), Ref.make(false) ) ).flatMap(({ tuple: [handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed] }) => { const handoffProducer: Channel< never, E | E2, Chunk<A>, unknown, never, never, unknown > = Channel.readWithCause( (input: Chunk<A>) => Channel.fromEffect(handoff.offer(HandoffSignal.Emit(input))) > handoffProducer, (cause) => Channel.fromEffect(handoff.offer(HandoffSignal.Halt(cause))), () => Channel.fromEffect(handoff.offer(HandoffSignal.End(SinkEndReason.UpstreamEnd))) ) const handoffConsumer: Channel< never, unknown, unknown, unknown, E | E2, Chunk<A | A2>, void > = Channel.unwrap( sinkLeftovers.getAndSet(Chunk.empty<A | A2>()).flatMap((leftovers) => leftovers.isNonEmpty() ? consumed.set(true).zipRight(Effect.succeed(Channel.write(leftovers) > handoffConsumer)) : handoff.take().map((signal) => { switch (signal._tag) { case "Emit": { return Channel.fromEffect(consumed.set(true)) > Channel.write(signal.elements) > handoffConsumer } case "Halt": { return Channel.failCause(signal.error) } case "End": { return ( signal.reason._tag === "ScheduleEnd" ? consumed.get().map((p) => p ? Channel.fromEffect(sinkEndReason.set(SinkEndReason.ScheduleEnd)) : Channel.fromEffect(sinkEndReason.set(SinkEndReason.ScheduleEnd)) > handoffConsumer ) : Channel.fromEffect(sinkEndReason.set(signal.reason)) ) as Channel< never, unknown, unknown, unknown, E | E2, Chunk<A | A2>, void > } } }) ) ) const sink0 = sink() concreteStream(self) concreteSink(sink0) const stream = Do(($) => { $((self.channel >> handoffProducer).runScoped().forkScoped()) const sinkFiber = $(handoffConsumer.pipeToOrFail(sink0.channel).doneCollect().runScoped().forkScoped()) const scheduleFiber = $(timeout(scheduleDriver, Option.none).forkScoped()) return new StreamInternal( scheduledAggregator( sink0, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, sinkFiber, scheduleFiber ) ) }) return Stream.unwrapScoped(stream) }) } /** * Aggregates elements using the provided sink until it completes, or until * the delay signalled by the schedule has passed. * * This operator divides the stream into two asynchronous islands. Operators * upstream of this operator run on one fiber, while downstream operators run * on another. Elements will be aggregated by the sink until the downstream * fiber pulls the aggregated value, or until the schedule's delay has passed. * * Aggregated elements will be fed into the schedule to determine the delays * between pulls. * * @param sink Used for the aggregation * @param schedule Used for signalling for when to stop the aggregation * * @tsplus static ets/Stream/Aspects aggregateWithinEither */ export const aggregateWithinEither = Pipeable(aggregateWithinEither_) function timeout<S, R, A, B>( scheduleDriver: Driver<S, R, Option<A>, B>, last: Option<A> ): Effect<R, Option<never>, B> { return scheduleDriver.next(last) } function handleSide<S, R, R2, E, A, A2, B, C>( sink: SinkInternal<R, E, A | A2, A2, B>, handoff: Handoff<HandoffSignal<E, A>>, sinkEndReason: Ref<SinkEndReason>, sinkLeftovers: Ref<Chunk<A2>>, scheduleDriver: Driver<S, R2, Option<B>, C>, consumed: Ref<boolean>, handoffProducer: Channel<never, E, Chunk<A>, unknown, never, never, unknown>, handoffConsumer: Channel<never, unknown, unknown, unknown, E, Chunk<A | A2>, void>, forkSink: Effect<Scope | R, never, Fiber.Runtime<E, Tuple<[Chunk<Chunk<A2>>, B]>>>, leftovers: Chunk<Chunk<A | A2>>, b: B, c: Option<C>, __tsplusTrace?: string ): Channel< R | R2, unknown, unknown, unknown, E, Chunk<Either<C, B>>, unknown > { return Channel.unwrap( sinkLeftovers.set(leftovers.flatten()) > sinkEndReason.get().map((reason) => { switch (reason._tag) { case "ScheduleEnd": { return Channel.unwrapScoped( Do(($) => { const isConsumed = $(consumed.get()) const sinkFiber = $(forkSink) const scheduleFiber = $(timeout(scheduleDriver, Option.some(b)).forkScoped()) const toWrite = c.fold( Chunk.single(Either.right(b)), (c) => Chunk(Either.right(b), Either.left(c)) ) return isConsumed ? Channel.write(toWrite) > scheduledAggregator( sink, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, sinkFiber, scheduleFiber ) : scheduledAggregator( sink, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, sinkFiber, scheduleFiber ) }) ) } case "UpstreamEnd": { return Channel.unwrap( consumed.get().map((p) => p ? Channel.write(Chunk.single(Either.right(b))) : Channel.unit) ) } } }) ) } function scheduledAggregator<S, R2, R3, E2, A, A2, B, C>( sink: SinkInternal<R2, E2, A | A2, A2, B>, handoff: Handoff<HandoffSignal<E2, A>>, sinkEndReason: Ref<SinkEndReason>, sinkLeftovers: Ref<Chunk<A2>>, scheduleDriver: Driver<S, R3, Option<B>, C>, consumed: Ref<boolean>, handoffProducer: Channel<never, E2, Chunk<A>, unknown, never, never, unknown>, handoffConsumer: Channel<never, unknown, unknown, unknown, E2, Chunk<A | A2>, void>, sinkFiber: Fiber.Runtime<E2, Tuple<[Chunk<Chunk<A | A2>>, B]>>, scheduleFiber: Fiber.Runtime<Option<never>, C>, __tsplusTrace?: string ): Channel< R2 | R3, unknown, unknown, unknown, E2, Chunk<Either<C, B>>, unknown > { concreteSink(sink) const forkSink = consumed.set(false).zipRight( handoffConsumer .pipeToOrFail(sink.channel) .doneCollect() .runScoped() .forkScoped() ) return Channel.unwrap( sinkFiber .join() .raceWith( scheduleFiber.join(), (sinkExit, scheduleFiber) => scheduleFiber.interrupt() > Effect.done(sinkExit).map(({ tuple: [leftovers, b] }) => handleSide( sink, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, forkSink, leftovers, b, Option.none ) ), (scheduleExit, sinkFiber) => Effect.done(scheduleExit).foldCauseEffect( (cause) => cause.failureOrCause().fold( () => handoff.offer(HandoffSignal.End(SinkEndReason.ScheduleEnd)).forkDaemon() .zipRight( sinkFiber.join().map(({ tuple: [leftovers, b] }) => handleSide( sink, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, forkSink, leftovers, b, Option.none ) ) ), (cause) => handoff.offer(HandoffSignal.Halt(cause)).forkDaemon() > sinkFiber.join().map(({ tuple: [leftovers, b] }) => handleSide( sink, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, forkSink, leftovers, b, Option.none ) ) ), (c) => handoff.offer(HandoffSignal.End(SinkEndReason.ScheduleEnd)).forkDaemon() > sinkFiber.join().map(({ tuple: [leftovers, b] }) => handleSide( sink, handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, handoffProducer, handoffConsumer, forkSink, leftovers, b, Option.some(c) ) ) ) ) ) }
the_stack
process.env.LOG_LEVEL = "SILENT"; import pull from "../pull"; /* UNCHANGED - Note should remain unchanged if not DELETED || NEW || UPDATED DELETED - Delete notes that were synced (having sync?.file.id) but deleted from the remote NEW - Add new notes created in the remote (file.id not present in any of notes) UPDATED - Update notes name/content if updated in the remote (file.modifiedTime > note.modifiedTime) */ const notes = { Article: { // UNCHANGED content: "Article content", createdTime: "2020-04-20T09:01:00Z", modifiedTime: "2020-04-20T09:01:01Z", sync: { file: { id: "4360", name: "Article", createdTime: "2020-04-20T09:01:00Z", modifiedTime: "2020-04-20T09:01:01Z", } } }, Todo: { // UPDATED (new content only) content: "buy milk", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:02:02Z", sync: { file: { id: "6073", name: "Todo", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:02:02Z", } } }, Cooking: { // DELETED content: "Cooking content", createdTime: "2020-04-20T09:03:00Z", modifiedTime: "2020-04-20T09:03:03Z", sync: { file: { id: "ecb5", name: "Cooking", createdTime: "2020-04-20T09:03:00Z", modifiedTime: "2020-04-20T09:03:03Z", } } }, Books: { // UPDATED (new content only) content: "The Great Gatsby", createdTime: "2020-04-20T09:04:00Z", modifiedTime: "2020-04-20T09:04:04Z", sync: { file: { id: "9d13", name: "Books", createdTime: "2020-04-20T09:04:00Z", modifiedTime: "2020-04-20T09:04:04Z", } } }, Radio: { // UNCHANGED content: "some radio stations", createdTime: "2020-04-20T09:05:00Z", modifiedTime: "2020-04-20T09:05:05Z", }, Shopping: { // UPDATED (new name AND new content; new name - "Amazon") content: "things to buy", createdTime: "2020-04-20T09:06:00Z", modifiedTime: "2020-04-20T09:06:06Z", sync: { file: { id: "df29", name: "Shopping", createdTime: "2020-04-20T09:06:00Z", modifiedTime: "2020-04-20T09:06:06Z", } } }, Clipboard: { // DELETED content: "Clipboard content", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:07Z", sync: { file: { id: "2931", name: "Clipboard", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:07Z", } } }, News: { // DELETED content: "news for today", createdTime: "2020-04-20T09:08:00Z", modifiedTime: "2020-04-20T09:08:08Z", sync: { file: { id: "f745", name: "News", createdTime: "2020-04-20T09:08:00Z", modifiedTime: "2020-04-20T09:08:08Z", } } }, Math: { // UPDATED (new content only; name conflict; content should be appended and sync?.file set) content: "some equations", createdTime: "2020-04-20T09:09:00Z", modifiedTime: "2020-04-20T09:09:09Z", }, Vacation: { // UPDATED (new name AND new content; new name - "Trip") content: "places to go", createdTime: "2020-04-20T09:10:00Z", modifiedTime: "2020-04-20T09:10:10Z", sync: { file: { id: "9e0e", name: "Vacation", createdTime: "2020-04-20T09:10:00Z", modifiedTime: "2020-04-20T09:10:10Z", } } } // NEW: // - Phones // - TV // - Lamps }; const files = [ // UNCHANGED (either not having a file, or file.modifiedTime is unchanged) { id: "4360", name: "Article", createdTime: "2020-04-20T09:01:00Z", modifiedTime: "2020-04-20T09:01:01Z" }, // "Radio" // UPDATED { id: "6073", name: "Todo", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:02:07Z" }, { id: "9d13", name: "Books", createdTime: "2020-04-20T09:04:00Z", modifiedTime: "2020-04-20T09:04:09Z" }, { id: "df29", name: "Amazon", createdTime: "2020-04-20T09:06:00Z", modifiedTime: "2020-04-20T09:06:11Z" }, // before "Shopping" { id: "777f", name: "Math", createdTime: "2020-04-20T09:25:00Z", modifiedTime: "2020-04-20T09:25:25Z" }, // name conflict = add content to existing note { id: "9e0e", name: "Trip", createdTime: "2020-04-20T09:10:00Z", modifiedTime: "2020-04-20T09:10:15Z" }, // before "Vacation" // DELETED // { id: "ecb5", ... } // "Cooking" // { id: "f745", ... } // "News" // { id: "2931", ... } // "Clipboard" // NEW { id: "2b18", name: "Phones", createdTime: "2020-04-20T09:11:00Z", modifiedTime: "2020-04-20T09:11:11Z" }, { id: "0dc9", name: "TV", createdTime: "2020-04-20T09:12:00Z", modifiedTime: "2020-04-20T09:12:12Z" }, { id: "b378", name: "Lamps", createdTime: "2020-04-20T09:13:00Z", modifiedTime: "2020-04-20T09:13:13Z" }, ]; const getFile = (fileId: string): Promise<string> => Promise.resolve(`CONTENT OF ${fileId}`); it("pulls new and updated notes, and deletes notes if deleted in Google Drive", async () => { const updatedNotes = await pull(notes, files, { getFile }); expect(Object.keys(updatedNotes).length === 11); // 10 original, -2 deleted, +3 new // Article expect(updatedNotes.Article.content === "Article content"); expect(updatedNotes.Article.createdTime === "2020-04-20T09:01:00Z"); expect(updatedNotes.Article.modifiedTime === "2020-04-20T09:01:01Z"); expect(updatedNotes.Article.sync?.file.id === "4360"); expect(updatedNotes.Article.sync?.file.name === "Article"); expect(updatedNotes.Article.sync?.file.createdTime === "2020-04-20T09:01:00Z"); expect(updatedNotes.Article.sync?.file.modifiedTime === "2020-04-20T09:01:01Z"); expect(Object.keys(updatedNotes.Article.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // Todo expect(updatedNotes.Todo.content === "CONTENT OF 6073"); expect(updatedNotes.Todo.createdTime === "2020-04-20T09:02:00Z"); expect(updatedNotes.Todo.modifiedTime === "2020-04-20T09:02:07Z"); expect(updatedNotes.Todo.sync?.file.id === "6073"); expect(updatedNotes.Todo.sync?.file.name === "Todo"); expect(updatedNotes.Todo.sync?.file.createdTime === "2020-04-20T09:02:00Z"); expect(updatedNotes.Todo.sync?.file.modifiedTime === "2020-04-20T09:02:07Z"); expect(Object.keys(updatedNotes.Todo.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // deleted Cooking expect("Cooking" in updatedNotes === false); // Books expect(updatedNotes.Books.content === "CONTENT OF 9d13"); expect(updatedNotes.Books.createdTime === "2020-04-20T09:04:00Z"); expect(updatedNotes.Books.modifiedTime === "2020-04-20T09:04:09Z"); expect(updatedNotes.Books.sync?.file.id === "9d13"); expect(updatedNotes.Books.sync?.file.name === "Books"); expect(updatedNotes.Books.sync?.file.createdTime === "2020-04-20T09:04:00Z"); expect(updatedNotes.Books.sync?.file.modifiedTime === "2020-04-20T09:04:09Z"); expect(Object.keys(updatedNotes.Books.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // Radio expect(updatedNotes.Radio.content === "some radio stations"); expect(updatedNotes.Radio.createdTime === "2020-04-20T09:05:00Z"); expect(updatedNotes.Radio.modifiedTime === "2020-04-20T09:05:05Z"); expect("sync" in updatedNotes.Radio === false); // Amazon (before "Shopping") expect(updatedNotes.Amazon.content === "CONTENT OF df29"); expect(updatedNotes.Amazon.createdTime === "2020-04-20T09:06:00Z"); expect(updatedNotes.Amazon.modifiedTime === "2020-04-20T09:06:11Z"); expect(updatedNotes.Amazon.sync?.file.id === "df29"); expect(updatedNotes.Amazon.sync?.file.name === "Amazon"); expect(updatedNotes.Amazon.sync?.file.createdTime === "2020-04-20T09:06:00Z"); expect(updatedNotes.Amazon.sync?.file.modifiedTime === "2020-04-20T09:06:11Z"); expect(Object.keys(updatedNotes.Amazon.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } expect("Shopping" in updatedNotes === false); // renamed to "Amazon" // deleted Clipboard expect("Clipboard" in updatedNotes === false); // deleted News expect("News" in updatedNotes === false); // Math expect(updatedNotes.Math.content === "some equations<br><br>CONTENT OF 777f"); expect(updatedNotes.Math.createdTime === "2020-04-20T09:25:00Z"); expect(updatedNotes.Math.modifiedTime === "2020-04-20T09:25:25Z"); expect(updatedNotes.Math.sync?.file.id === "777f"); expect(updatedNotes.Math.sync?.file.name === "Math"); expect(updatedNotes.Math.sync?.file.createdTime === "2020-04-20T09:25:00Z"); expect(updatedNotes.Math.sync?.file.modifiedTime === "2020-04-20T09:25:25Z"); expect(Object.keys(updatedNotes.Math.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // Trip (before "Vacation") expect(updatedNotes.Trip.content === "CONTENT OF 9e0e"); expect(updatedNotes.Trip.createdTime === "2020-04-20T09:10:00Z"); expect(updatedNotes.Trip.modifiedTime === "2020-04-20T09:10:15Z"); expect(updatedNotes.Trip.sync?.file.id === "9e0e"); expect(updatedNotes.Trip.sync?.file.name === "Trip"); expect(updatedNotes.Trip.sync?.file.createdTime === "2020-04-20T09:10:00Z"); expect(updatedNotes.Trip.sync?.file.modifiedTime === "2020-04-20T09:10:15Z"); expect(Object.keys(updatedNotes.Trip.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } expect("Vacation" in updatedNotes === false); // renamed to "Trip" // Phones expect(updatedNotes.Phones.content === "CONTENT OF 2b18"); expect(updatedNotes.Phones.createdTime === "2020-04-20T09:11:00Z"); expect(updatedNotes.Phones.modifiedTime === "2020-04-20T09:11:11Z"); expect(updatedNotes.Phones.sync?.file.id === "2b18"); expect(updatedNotes.Phones.sync?.file.name === "Phones"); expect(updatedNotes.Phones.sync?.file.createdTime === "2020-04-20T09:11:00Z"); expect(updatedNotes.Phones.sync?.file.modifiedTime === "2020-04-20T09:11:11Z"); expect(Object.keys(updatedNotes.Phones.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // TV expect(updatedNotes.TV.content === "CONTENT OF 0dc9"); expect(updatedNotes.TV.createdTime === "2020-04-20T09:12:00Z"); expect(updatedNotes.TV.modifiedTime === "2020-04-20T09:12:12Z"); expect(updatedNotes.TV.sync?.file.id === "0dc9"); expect(updatedNotes.TV.sync?.file.name === "TV"); expect(updatedNotes.TV.sync?.file.createdTime === "2020-04-20T09:12:00Z"); expect(updatedNotes.TV.sync?.file.modifiedTime === "2020-04-20T09:12:12Z"); expect(Object.keys(updatedNotes.TV.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // Lamps expect(updatedNotes.Lamps.content === "CONTENT OF b378"); expect(updatedNotes.Lamps.createdTime === "2020-04-20T09:13:00Z"); expect(updatedNotes.Lamps.modifiedTime === "2020-04-20T09:13:13Z"); expect(updatedNotes.Lamps.sync?.file.id === "b378"); expect(updatedNotes.Lamps.sync?.file.name === "Lamps"); expect(updatedNotes.Lamps.sync?.file.createdTime === "2020-04-20T09:13:00Z"); expect(updatedNotes.Lamps.sync?.file.modifiedTime === "2020-04-20T09:13:13Z"); expect(Object.keys(updatedNotes.Lamps.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } }); // Relink the notes, and: // - leave the content unchanged, if the file and note are the same (Todo) // - append the file content, if the file and note are NOT the same (Clipboard) it("links notes to files with same name in Google Drive", async () => { const notes = { Todo: { content: "buy milk", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:02:02Z", }, Clipboard: { content: "my clipboard", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:07Z", }, }; const files = [ // SAME modifiedTime { id: "6073", name: "Todo", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:02:02Z" }, // UPDATED { id: "2931", name: "Clipboard", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:12Z" }, ]; const updatedNotes = await pull(notes, files, { getFile }); expect(Object.keys(updatedNotes).length === 2); // { Todo, Clipboard } // Todo expect(updatedNotes.Todo.content === "buy milk"); // unchanged expect(updatedNotes.Todo.createdTime === "2020-04-20T09:02:00Z"); expect(updatedNotes.Todo.modifiedTime === "2020-04-20T09:02:02Z"); expect(updatedNotes.Todo.sync?.file.id === "6073"); expect(updatedNotes.Todo.sync?.file.name === "Todo"); expect(updatedNotes.Todo.sync?.file.createdTime === "2020-04-20T09:02:00Z"); expect(updatedNotes.Todo.sync?.file.modifiedTime === "2020-04-20T09:02:02Z"); expect(Object.keys(updatedNotes.Todo.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // Clipboard expect(updatedNotes.Clipboard.content === "my clipboard<br><br>CONTENT OF 2931"); // appended (not replaced) expect(updatedNotes.Clipboard.createdTime === "2020-04-20T09:07:00Z"); expect(updatedNotes.Clipboard.modifiedTime === "2020-04-20T09:07:12Z"); expect(updatedNotes.Clipboard.sync?.file.id === "2931"); expect(updatedNotes.Clipboard.sync?.file.name === "Clipboard"); expect(updatedNotes.Clipboard.sync?.file.createdTime === "2020-04-20T09:07:00Z"); expect(updatedNotes.Clipboard.sync?.file.modifiedTime === "2020-04-20T09:07:12Z"); expect(Object.keys(updatedNotes.Clipboard.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } }); it("links notes to the last file in Google Drive if having the same name in Google Drive", async () => { const notes = { Todo: { content: "buy milk", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:02:02Z", }, Clipboard: { content: "my clipboard", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:07Z", }, }; const files = [ // "Todo" renamed to "Clipboard" (UPDATED) { id: "6073", name: "Clipboard", createdTime: "2020-04-20T09:02:00Z", modifiedTime: "2020-04-20T09:07:17Z" }, // "Clipboard" (UPDATED) { id: "2931", name: "Clipboard", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:12Z" }, ]; const updatedNotes = await pull(notes, files, { getFile }); expect(Object.keys(updatedNotes).length === 2); // { Todo, Clipboard } // Todo expect(updatedNotes.Todo.content === "buy milk"); expect(updatedNotes.Todo.createdTime === "2020-04-20T09:02:00Z"); expect(updatedNotes.Todo.modifiedTime === "2020-04-20T09:02:02Z"); expect("sync" in updatedNotes.Todo === false); // Clipboard (last file with the same name used) expect(updatedNotes.Clipboard.content === "CONTENT OF 2931"); expect(updatedNotes.Clipboard.createdTime === "2020-04-20T09:07:00Z"); expect(updatedNotes.Clipboard.modifiedTime === "2020-04-20T09:07:12Z"); expect(updatedNotes.Clipboard.sync?.file.id === "2931"); expect(updatedNotes.Clipboard.sync?.file.name === "Clipboard"); expect(updatedNotes.Clipboard.sync?.file.createdTime === "2020-04-20T09:07:00Z"); expect(updatedNotes.Clipboard.sync?.file.modifiedTime === "2020-04-20T09:07:12Z"); expect(Object.keys(updatedNotes.Clipboard.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } }); // Since last sync, renamed the note, renamed the linked file as well // Expected: update the note name, content, linked file name it("renames the note if linked but renamed in Google Drive", async () => { const notes = { Cooking: { // renamed since last sync (before: "Kitchen") content: "Cooking content", createdTime: "2020-04-20T09:03:00Z", modifiedTime: "2020-04-20T09:03:08Z", sync: { file: { id: "ecb5", name: "Kitchen", createdTime: "2020-04-20T09:03:00Z", modifiedTime: "2020-04-20T09:03:03Z", } } }, Clipboard: { content: "my clipboard", createdTime: "2020-04-20T09:07:00Z", modifiedTime: "2020-04-20T09:07:07Z", }, }; const files = [ // UPDATED, renamed as well { id: "ecb5", name: "Recipes", createdTime: "2020-04-20T09:03:00Z", modifiedTime: "2020-04-20T09:03:13Z" }, ]; const updatedNotes = await pull(notes, files, { getFile }); expect(Object.keys(updatedNotes).length === 2); // { Recipes, Clipboard } // Recipes expect(updatedNotes.Recipes.content === "CONTENT OF ecb5"); expect(updatedNotes.Recipes.createdTime === "2020-04-20T09:03:00Z"); expect(updatedNotes.Recipes.modifiedTime === "2020-04-20T09:03:13Z"); expect(updatedNotes.Recipes.sync?.file.id === "ecb5"); expect(updatedNotes.Recipes.sync?.file.name === "Recipes"); expect(updatedNotes.Recipes.sync?.file.createdTime === "2020-04-20T09:03:00Z"); expect(updatedNotes.Recipes.sync?.file.modifiedTime === "2020-04-20T09:03:13Z"); expect(Object.keys(updatedNotes.Recipes.sync?.file || {}).length === 4); // { id, name, createdTime, modifiedTime } // Clipboard expect(updatedNotes.Clipboard.content === "my clipboard"); expect(updatedNotes.Clipboard.createdTime === "2020-04-20T09:07:00Z"); expect(updatedNotes.Clipboard.modifiedTime === "2020-04-20T09:07:07Z"); expect("sync" in updatedNotes.Clipboard === false); });
the_stack
import { Component, Input, ElementRef, ViewChild, SimpleChanges, OnDestroy, OnInit, OnChanges, EventEmitter, Output } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { LoggerService } from '../../../shared/services/logger.service'; import * as d3 from 'd3-selection'; import * as d3Shape from 'd3-shape'; import * as d3Scale from 'd3-scale'; import * as d3Array from 'd3-array'; import * as d3Axis from 'd3-axis'; import { DatepickerOptions } from 'ng2-datepicker'; import { CommonResponseService } from '../../../shared/services/common-response.service'; import { environment } from './../../../../environments/environment'; import { UtilsService } from '../../../shared/services/utils.service'; @Component({ selector: 'app-vuln-trend-graph', templateUrl: './vuln-trend-graph.component.html', styleUrls: ['./vuln-trend-graph.component.css'] }) export class VulnTrendGraphComponent implements OnChanges, OnInit, OnDestroy { @Input() graphResponse; @Input() axisValues; @Input() graphData; @Input() svgId; @Input() maxVal; @Input() months; @Input() selectedMonth; @Input() parentWidth; @Input() adminAccess; @Input() infoActive = true; @Input() agName; @Input() notesData = []; @Input() notesResponse; @Input() selectedAssetGroup; @Output() fetchNewNotes = new EventEmitter(); agList; openNotesModal = false; graphX = {}; graphY = {}; activeScope; editMode = false; notesText = ''; recentData = []; currentNoteId; dateSelected; options: DatepickerOptions = { displayFormat: 'MMM D[,] YYYY', maxDate: new Date(), minDate: new Date('1970-01-01') }; updateNoteState = 1; updateNoteSubscription: Subscription; deleteNoteSubscription: Subscription; @ViewChild('container') vulnReportGraph: ElementRef; constructor(private logger: LoggerService, private commonResponseService: CommonResponseService, private utils: UtilsService) { } ngOnInit() { this.setCurrentScopeAndAgList(); } ngOnChanges(changes: SimpleChanges) { try { const DataChange = changes['graphData']; const widthChange = changes['parentWidth']; const agName = changes['agName']; if (DataChange && DataChange.currentValue ) { this.plotGraph(DataChange.currentValue); this.agList = [{id: 'global', text: 'Global'}, { text: this.agName, id: this.selectedAssetGroup}]; this.activeScope = [{id: this.selectedAssetGroup, text: this.agName}]; } else if (widthChange && widthChange.currentValue) { const currentWidth = widthChange.currentValue; const prevWidth = widthChange.previousValue; if (currentWidth !== prevWidth && this.parentWidth && this.graphData) { setTimeout(() => { this.plotGraph(this.graphData); }, 10); } } else if (agName && agName.currentValue) { this.agName = agName.currentValue; this.setCurrentScopeAndAgList(); } } catch (e) { this.logger.log('error', e); } } setCurrentScopeAndAgList() { this.agList = [{id: 'global', text: 'Global'}, { text: this.agName, id: this.selectedAssetGroup}]; this.activeScope = [{id: this.selectedAssetGroup, text: this.agName}]; } plotGraph(data) { const newData = data; const ele = this.vulnReportGraph.nativeElement; if (ele) { ele.innerHTML = ''; } const graphThis = this; const margin = { top: 45, right: 20, bottom: 20, left: 70 }, width = parseInt(this.parentWidth, 10) - margin.left - margin.right, height = 200 - margin.top - margin.bottom; const x = d3Scale.scalePoint().range([0, width]); x.domain(newData.map(d => d['date'])); const y0 = d3Scale.scaleLinear().range([height, 0]); // Scale the range of the data for each axes y0.domain([ d3Array.min(newData, function(d) { return Math.min( d['new'], d['open'], 5 ); }), d3Array.max(newData, function(d) { return Math.max( d['new'], d['open'], 5 ); }) ]); // Area plotting of graph under line const area1 = d3Shape.area() .x(function(d) { return x(d['date']); }) .y0(height) .y1(function(d) { return y0(d['open']); }); const area2 = d3Shape.area() .x(function(d) { return x(d['date']); }) .y0(height) .y1(function(d) { return y0(d['new']); }); // Line plot definition const valueline1 = d3Shape .line() .x(function(d) { return x(d['date']); }) .y(function(d) { graphThis.findMaxVal(d); return y0(d['open']); }); const valueline2 = d3Shape .line() .x(function(d) { return x(d['date']); }) .y(function(d) { graphThis.findMaxVal(d); return y0(d['new']); }); // set dimentions of svg const svg = d3 .select('#' + this.svgId) .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // format the data newData.forEach(function(d) { d['date'] = new Date(d['date']); d['open'] = +d['open']; d['new'] = +d['new']; }); // Add the X Bottom Axis svg .append('g') .attr('transform', 'translate(0,' + height + ')') .attr('class', 'bottomAxis') .call(d3Axis.axisBottom(x)) .call(make_x_gridlines().tickSize(-height).tickValues(x.domain().filter(function(d, i) { return !(i % (graphThis.months[graphThis.selectedMonth] * 4 )); }))) .selectAll('text') .style('text-anchor', 'end') .attr('dx', '1.3em') .attr('dy', '1.3em') .text(function(d, i) { return newData[i * (graphThis.months[graphThis.selectedMonth] * 4 )].dateStr; }); // Add areas and lines respectively svg.append('g') .classed('labels-group', true) .selectAll('text') .data(data) .enter() .append('text') .classed('label', true) .text(function(d) { return ''; }) .style('font-size', '0px') .attr('x', function(d, i) { graphThis.graphY[d['dateStr']] = y0(d['open']); graphThis.graphX[d['dateStr']] = x(d['date']); return x(d['date']); }); svg.append('path') .data([data]) .attr('class', 'area') .style('clip-path', 'none') .attr('d', area1); svg.append('path') .data([data]) .attr('class', 'area') .style('clip-path', 'none') .style('fill', '#f2425f') .attr('d', area2); svg .append('path') .data([newData]) .attr('class', 'line') .style('stroke', '#60727f') .attr('d', valueline1); svg .append('path') .data([newData]) .attr('class', 'line') .style('stroke', '#f2425f') .style('stroke-width', '1px') .attr('d', valueline2); // Data text with rect as background at each plot point svg.append('g') .selectAll('rect') .data(data) .enter() .append('rect') .filter(function(d, i) { return !(i % (graphThis.months[graphThis.selectedMonth] * 4 )); }) .attr('fill', '#fff') .attr('fill-opacity', '0.6') .attr('height', '16px') .attr('rx', 3) .attr('ry', 3) .attr('width', '36px') .attr('x', function(d, i) { return x(d['date']); }) .attr('y', function(d, i) { return y0(d['new']) - y0(d['open']) > 8 ? y0(d['open']) : y0(d['new']) - 8; }) .style('transform', function(d, i) { return i === 0 ? 'translate(2px, -24px)' : 'translate(-18px, -24px)'; }); svg.append('g') .classed('labels-group', true) .selectAll('text') .data(data) .enter() .append('text') .filter(function(d, i) { return !(i % (graphThis.months[graphThis.selectedMonth] * 4 )); }) .classed('label', true) .text(function(d) { return d['open']; }) .style('font-size', '9px') .style('text-anchor', 'middle') .style('fill', '#60727f') .style('transform', function(d, i) { return i === 0 ? 'translate(19px, -8px)' : 'translate(0px, -8px)'; }) .attr('x', function(d, i) { return x(d['date']); }) .attr('y', function(d, i) { return y0(d['new']) - y0(d['open']) > 8 ? y0(d['open']) : y0(d['new']) - 8; }) .attr('dy', '-5'); svg.append('g') .selectAll('rect') .data(data) .enter() .append('rect') .filter(function(d, i) { return !(i % (graphThis.months[graphThis.selectedMonth] * 4 )); }) .attr('fill', '#fff') .attr('fill-opacity', '0.6') .attr('height', '16px') .attr('rx', 3) .attr('ry', 3) .attr('width', '36px') .attr('x', function(d, i) { return x(d['date']); }) .attr('y', function(d, i) { return y0(d['new']); }) .style('transform', function(d, i) { return i === 0 ? 'translate(2px, -16px)' : 'translate(-18px, -16px)'; }); svg.append('g') .classed('labels-group', true) .selectAll('text') .data(data) .enter() .append('text') .filter(function(d, i) { return !(i % (graphThis.months[graphThis.selectedMonth] * 4 )); }) .classed('label', true) .text(function(d) { return d['new']; }) .style('font-size', '9px') .style('fill', '#ed0004') .style('transform', function(d, i) { return i === 0 ? 'translateX(19px)' : 'translateX(0px)'; }) .style('text-anchor', 'middle') .attr('x', function(d, i) { return x(d['date']); }) .attr('y', function(d, i) { return y0(d['new']); }) .attr('dy', '-5'); // gridlines in x axis function function make_x_gridlines() { return d3Axis.axisBottom(x).ticks(5); } } findMaxVal(obj) { try { if ( !isNaN(obj.open) && !isNaN(obj.new) ) { this.maxVal[0] = Math.max( this.maxVal[0], obj['open'], obj['new'] ); for ( let i = 5; i > 0; i--) { this.axisValues['y0'].push(Math.ceil(this.maxVal[0] / 5 * i)); } this.axisValues['y0'] = this.axisValues['y0'].slice( this.axisValues['y0'].length - 5 ); if (this.axisValues['y0'][0] < 5) { this.axisValues['y0'] = [5, 4, 3, 2, 1]; } } } catch (e) { this.logger.log('error', e); } } graphClicked(data, index, from? ) { try { if ( this.adminAccess && this.notesResponse > 0 ) { let newNote = true; this.recentData = []; const firstDate = new Date(this.graphData[0].date); firstDate.setDate(firstDate.getDate() - 1); this.options['minDate'] = firstDate; this.options['maxDate'] = this.graphData[this.graphData.length - 1].date; this.dateSelected = data.date; this.recentData.push({date: this.graphData[index].dateStr, data: this.graphData[index].open, selectedDate: true}); if ( index !== this.graphData.length - 1) { this.recentData.push({date: this.graphData[index + 1].dateStr, data: this.graphData[index + 1].open, selectedDate: false}); } if (index !== 0) { this.recentData.unshift({date: this.graphData[index - 1].dateStr, data: this.graphData[index - 1].open, selectedDate: false}); } for ( let i = 0; i < this.notesData.length; i++ ) { if ( data.dateStr === this.notesData[i].dateStr ) { if (this.notesData[i].data.length === 1 ) { newNote = false; // edit existing note this.openNotesModal = true; this.editMode = true; if ( data.dateStr === this.notesData[i].dateStr ) { this.currentNoteId = this.notesData[i].data[0].noteId; this.notesText = this.notesData[i].data[0].note; if ( this.notesData[i].data[0].type === 'Global') { this.activeScope = [{id: 'global', text: 'Global'}]; } else { this.activeScope = [{id: this.selectedAssetGroup, text: this.agName}]; } } } else { newNote = false; if (!from) { // handle multiple notes this.openNotesModal = false; this.notesData[i].vibrate = true; const self = this; setTimeout(function(){ self.notesData[i].vibrate = false; }, 400); } if (from === 'datepicker') { for ( let j = 0; j < this.notesData[i].data.length; j++ ) { if ( (this.activeScope[0].id === 'global' && this.notesData[i].data[j].type === 'Global') || ( this.activeScope[0].id !== 'global' && this.notesData[i].data[j].type !== 'Global' )) { this.notesText = this.notesData[i].data[j].note; this.editMode = true; } } } } break; } } if (newNote) { // handle new note this.openNotesModal = true; this.notesText = ''; this.editMode = false; this.activeScope = [{id: this.selectedAssetGroup, text: this.agName}]; } } } catch (e) { this.logger.log('error', e); } } selectAg(tag) { this.activeScope[0] = tag; let newNote = true; for ( let i = 0; i < this.notesData.length; i++) { if ( this.dateSelected.toISOString().slice(0, 10) === this.notesData[i].date.toISOString().slice(0, 10) ) { if (this.notesData[i].data.length === 1) { if ( (this.notesData[i].data[0].type === 'Global' && this.activeScope[0].id === 'global') || (this.notesData[i].data[0].type === 'AssetGroup' && this.activeScope[0].id !== 'global') ) { this.notesText = this.notesData[i].data[0].note; this.editMode = true; newNote = false; } } else { for ( let j = 0; j < this.notesData[i].data.length; j++ ) { if ( (this.activeScope[0].id === 'global' && this.notesData[i].data[j].type === 'Global') || (this.activeScope[0].id !== 'global' && this.notesData[i].data[j].type === 'AssetGroup') ) { this.notesText = this.notesData[i].data[j].note; this.editMode = true; newNote = false; } } } break; } } if ( newNote ) { this.notesText = ''; this.editMode = false; } } noteClicked(data) { try { if ( this.adminAccess && this.notesResponse > 0 ) { this.openNotesModal = true; this.editMode = true; this.currentNoteId = data.noteId; const firstDate = new Date(this.graphData[0].date); firstDate.setDate(firstDate.getDate() - 1); this.options['minDate'] = firstDate; this.options['maxDate'] = this.graphData[this.graphData.length - 1].date; this.dateSelected = this.utils.getDateAndTime(data.date); //new Date(data.date); this.notesText = data.note; for ( let i = 0; i < this.graphData.length; i++) { this.recentData = []; if (this.graphData[i].dateStr.replace('/', '-') === (data.date).slice(-5)) { this.recentData.push({date: this.graphData[i].dateStr, data: this.graphData[i].open, selectedDate: true}); if ( i !== this.graphData.length - 1) { this.recentData.push({date: this.graphData[i + 1].dateStr, data: this.graphData[i + 1].open, selectedDate: false}); } if (i !== 0) { this.recentData.unshift({date: this.graphData[i - 1].dateStr, data: this.graphData[i - 1].open, selectedDate: false}); } break; } } if (data.type.toLowerCase() === 'assetgroup') { this.activeScope = [{id: this.selectedAssetGroup, text: this.agName}]; } else { this.activeScope = [{id: 'global', text: 'Global'}]; } } } catch (e) { this.logger.log('error', e); } } getDateData(date) { try { for (let i = 0; i < this.graphData.length; i++ ) { if (date.getDate() === (this.graphData[i].date).getDate() && date.getMonth() === (this.graphData[i].date).getMonth() ) { this.graphClicked(this.graphData[i], i, 'datepicker'); break; } } } catch (e) { this.logger.log('error', e); } } capitalizeFirstLetter(string) { if (string) { return string.charAt(0).toUpperCase() + string.slice(1); } } updateNote() { try { if (this.notesText.trim() && this.updateNoteState !== 0) { this.updateNoteState = 0; if (this.deleteNoteSubscription) { this.deleteNoteSubscription.unsubscribe(); } let notesPayload = {}; if (this.activeScope[0].id === 'global') { notesPayload = { 'ag': '', 'date': this.dateSelected.toISOString(), 'note': this.capitalizeFirstLetter(this.notesText) }; } else { notesPayload = { 'ag': this.activeScope[0].id, 'date': this.dateSelected.toISOString(), 'note': this.capitalizeFirstLetter(this.notesText) }; } const updateNoteParam = {}; const updateNoteUrl = environment.postVulnTrendNotes.url; const updateNoteMethod = environment.postVulnTrendNotes.method; this.updateNoteSubscription = this.commonResponseService.getData( updateNoteUrl, updateNoteMethod, notesPayload, updateNoteParam).subscribe( response => { try { this.openNotesModal = false; this.updateNoteState = 1; const self = this; setTimeout(() => { self.fetchNewNotes.emit(); }, 10); } catch (e) { this.logger.log('error', e); this.updateNoteState = -1; } }, error => { this.logger.log('error', error); this.updateNoteState = -1; }); } } catch (e) { this.logger.log('error', e); this.updateNoteState = -1; } } deleteNote() { try { if (this.updateNoteState !== 0 ) { if (this.updateNoteSubscription) { this.updateNoteSubscription.unsubscribe(); } this.updateNoteState = 0; const deleteNotePayload = {}; const deleteNoteParam = { noteId: this.currentNoteId }; const deleteNoteUrl = environment.deleteVulnNote.url + '/' + this.currentNoteId; const deleteNoteMethod = environment.deleteVulnNote.method; this.deleteNoteSubscription = this.commonResponseService.getData( deleteNoteUrl, deleteNoteMethod).subscribe( response => { try { this.openNotesModal = false; const self = this; setTimeout(() => { self.fetchNewNotes.emit(); }, 200); this.updateNoteState = 1; } catch (e) { this.logger.log('error', e); this.updateNoteState = -1; } }, error => { this.logger.log('error', error); this.updateNoteState = -1; }); } } catch (e) { this.logger.log('error', e); this.updateNoteState = -1; } } ngOnDestroy() { if (this.updateNoteSubscription) { this.updateNoteSubscription.unsubscribe(); } if (this.deleteNoteSubscription) { this.deleteNoteSubscription.unsubscribe(); } } }
the_stack
import { EventEmitter } from "events"; import { Socket, SocketConnectOpts } from "net"; import { Discover } from "./discover"; import { defaultLogger } from "./logger"; import { AdjustType, Color, Command, CommandType, DevicePropery, FlowState, ICommandResult, IConfig, IDevice, IEventResult, Scene, StartFlowAction, } from "./models"; import { ILogger } from "./models/logger"; const DEFAULT_PORT = 55443; /** * The client to connect and control the light */ export class Yeelight extends EventEmitter { public connected: boolean; public autoReconnect = false; public disablePing = false; public autoReconnectTime = 1000; public connectTimeout = 1000; private client: Socket; private commandId = 1; private sentCommands: { [commandId: string]: Command } = {}; private resultCommands: ICommandResult[]; private isConnecting = false; private isClosing = false; private isReconnecting = false; private reconnectTimeout: NodeJS.Timer | null = null; private pingTimeout: NodeJS.Timer | null = null; private readonly EVENT_NAME = "command_result"; /** * @constructor * @param {IConfig} options : The client config initial the client */ constructor(private options: IConfig, private logger?: ILogger) { super(); this.logger = logger || defaultLogger; this.resultCommands = new Array<ICommandResult>(); this.emit("ready", this); // Set default timeout if not provide this.options.timeout = this.options.timeout || 5000; } public onData(data: Buffer) { const messages = data.toString(); messages.split("\n").forEach((message) => { const json = message.toString(); if (json) { const result: ICommandResult = JSON.parse(json); this.onMessage(result); } }); } public onMessage(result: ICommandResult) { this.resultCommands.push(result); const commandId = "" + result.id; const originalCommand = this.sentCommands[commandId]; if (!originalCommand) { return; } const eventData: IEventResult = { action: originalCommand.method, command: originalCommand, result, success: true, }; this.logger.info("Light data recieved: ", result); this.emit(`${this.EVENT_NAME}_${result.id}`, eventData); this.emit(originalCommand.method, eventData); delete this.sentCommands[commandId]; if (result.id && result.result) { this.emit("commandSuccess", eventData); } if (result && result.error) { eventData.success = false; this.emit("commandError", eventData); } } /** * Drop connection/listerners and clean up resources. */ public disconnect(): Promise<void> { this.removeAllListeners(); this.emit("end"); // this.client.destroy(); this.client.removeAllListeners("data"); this.isClosing = true; return new Promise((resolve) => this.client.end(resolve as any)) .then(() => { return this.closeConnection(); }); } /** * establish connection to light, * @returns return promise of the current instance */ public async connect(): Promise<Yeelight> { if (this.isConnecting) { throw new Error("Already connecting"); } if (this.options.lightIp) { return this.connectToIp(this.options.lightIp, this.options.lightPort); } else if (this.options.lightId) { // If only the Id is given, start searching for that id: const discover = new Discover({ filter: (d: IDevice) => d.id === this.options.lightId, limit: 1, timeout: this.connectTimeout, }); const devices = await discover.start(); await discover.destroy(); const device = devices[0]; if (device) { return this.connectToIp(device.host, device.port); } else { throw new Error("Unable to connect, no device with id '" + this.options.lightId + "' found"); } } else { throw new Error("Unable to connect, neither config.lightIp or options.lightId is set"); } } /* * This method is used to switch on or off the smart LED (software managed on/off) * @param turnOn:boolean set status true is turn on, false is turn off * @param {"smooth"| "sudden"} effect support two values: "sudden" and "smooth". If effect is "sudden", * then the color temperature will be changed directly to target value, * under this case, the third parameter "duration" is ignored. If effect is "smooth", * then the color temperature will be changed to target value in a gradual fashion, under this case, * the total time of gradual change is specified in third parameter "duration". * @param {number} duration specifies the total time of the gradual changing. The unit is milliseconds. * The minimum support duration is 30 milliseconds. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setPower( turnOn = true, effect: "smooth" | "sudden" = "sudden", duration = 500, ): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_POWER, [(turnOn ? "on" : "off"), effect, duration])); } /** * This method is used to start a timer job on the smart LED. * Only accepted if the smart LED is currently in "on" state * @param type currently can only be 0. (means power off) * @param time the length of the timer (in minutes). Request * @returns {Promise<IEventResult>} return a promise of IEventResult */ public cronAdd(type: number, time: number): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.CRON_ADD, [0, time])); } /** * This method is used to retrieve the setting of the current cron job of the specified type. * @param type currently can only be 0. (means power off) * @returns {Promise<IEventResult>} return a promise of IEventResult */ public cronGet(type: number): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.CRON_GET, [type])); } /** * This method is used to retrieve the setting of the current cron job of the specified type. * @param type currently can only be 0. (means power off) * @returns {Promise<IEventResult>} return a promise of IEventResult */ public cronDelete(type: number): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.CRON_DEL, [type])); } /** * This method is used to toggle the smart LED. * This method is used to switch on or off the smart LED (software managed on/off) * @returns {Promise<ICommandResult>} Return the promise indicate the command success or reject * @returns {Promise<IEventResult>} return a promise of IEventResult */ public toggle(): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.TOGGLE, [])); } /** * This method is used to save current state of smart LED in persistent memory. * So if user powers off and then powers on the smart LED again (hard power reset), * the smart LED will show last saved state. * For example, if user likes the current color (red) and brightness (50%) * and want to make this state as a default initial state (every time the smart LED is powered), * then he can use set_default to do a snapshot. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setDefault(): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_DEFAULT, [])); } /** * This method is used to start a color flow. Color flow is a series of smart LED visible state changing. * It can be brightness changing, color changing or color temperature changing. This is the most powerful command. * All our recommended scenes, * e.g. Sunrise/Sunset effect is implemented using this method. * With the flow expression, user can actually “program” the light effect. * @param {FlowState[]} states: Each visible state changing is defined to be a flow tuple that contains 4 elements: * [duration, mode, value, brightness]. A flow expression is a series of flow tuples. * So for above request example, it means: change CT to 2700K & maximum brightness gradually in 1000ms, * then change color to red & 10% brightness gradually in 500ms, then stay at this state for 5 seconds, * then change CT to 5000K & minimum brightness gradually in 500ms. * After 4 changes reached, stopped the flow and power off the smart LED. * @param {StarFlowAction} action: is the action taken after the flow is stopped * @param {number} repeat is the total number of visible state changing before color flow * stopped. 0 means infinite loop on the state changing. @default infinity * @returns {Promise<IEventResult>} return a promise of IEventResult */ public startColorFlow(states: FlowState[], action: StartFlowAction = StartFlowAction.LED_STAY, repeat = 0): Promise<IEventResult> { const values = states.reduce((a, b) => [...a, ...b.getState()], []); return this.sendCommand(new Command(1, CommandType.START_COLOR_FLOW, [repeat, action, values.join(",")])); } /** * This method is used to stop a running color flow. */ public stopColorFlow(): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.STOP_COLOR_FLOW, [])); } /** * This method is used to set the smart LED directly to specified state. * If the smart LED is off, then it will turn on the smart LED firstly and then apply the specified command * @param scene type of scene to update * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setScene<T extends Scene>(scene: T): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_SCENE, scene.getData())); } /** * This method is used to retrieve current property of smart LED. * @param {string[]} params The parameter is a list of property names and the response contains a * list of corresponding property values. * the requested property name is not recognized by smart LED, then a empty string value ("") will be returned. * Request Example: {"id":1,"method":"get_prop","params":["power", "not_exist", "bright"]} * Example: {"id":1, "result":["on", "", "100"]} * @returns {Promise<IEventResult>} return a promise of IEventResult */ public getProperty(params: DevicePropery[]): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.GET_PROPS, params)); } /** * This method is used to change the color temperature of a smart LED. * @param {number} ct the target color temperature. The type is integer and range is 1700 ~ 6500 (k). * @param {"smooth"| "sudden"} effect support two values: "sudden" and "smooth". If effect is "sudden", * then the color temperature will be changed directly to target value, * under this case, the third parameter "duration" is ignored. If effect is "smooth", * then the color temperature will be changed to target value in a gradual fashion, under this case, * the total time of gradual change is specified in third parameter "duration". * @param {number} duration specifies the total time of the gradual changing. The unit is milliseconds. * The minimum support duration is 30 milliseconds. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setCtAbx( ct: number, effect: "smooth" | "sudden" = "sudden", duration = 500, ): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_CT_ABX, [ct, effect, duration])); } /** * This method is used to change the color of a smart LED. * Only accepted if the smart LED is currently in "on" state. * @param color the target color, whose type is integer. * It should be expressed in decimal integer ranges from 0 to 16777215 (hex: 0xFFFFFF). * can be initial by new Color(233,255,244) * @param {"smooth"| "sudden"} effect support two values: "sudden" and "smooth". If effect is "sudden", * then the color temperature will be changed directly to target value, * under this case, the third parameter "duration" is ignored. If effect is "smooth", * then the color temperature will be changed to target value in a gradual fashion, under this case, * the total time of gradual change is specified in third parameter "duration". * @param {number} duration specifies the total time of the gradual changing. The unit is milliseconds. * The minimum support duration is 30 milliseconds. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setRGB(color: Color, effect: "smooth" | "sudden", duration = 500): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_RGB, [color.getValue(), effect, duration])); } /** * This method is used to change the color of a smart LED. * Only accepted if the smart LED is currently in "on" state. * @param hue the target hue, whose type is integer. * It should be expressed in decimal integer ranges from 0 to 359. * @param sat the target saturation, whose type is integer. * It should be expressed in decimal integer ranges from 0 to 100. * @param {"smooth"| "sudden"} effect support two values: "sudden" and "smooth". If effect is "sudden", * then the color temperature will be changed directly to target value, * under this case, the third parameter "duration" is ignored. If effect is "smooth", * then the color temperature will be changed to target value in a gradual fashion, under this case, * the total time of gradual change is specified in third parameter "duration". * @param {number} duration specifies the total time of the gradual changing. The unit is milliseconds. * The minimum support duration is 30 milliseconds. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setHSV( hue: number, sat: number, effect: "smooth" | "sudden" = "sudden", duration = 500, ): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_HSV, [hue, sat, effect, duration])); } /** * This method is used to change the color of a smart LED. * Only accepted if the smart LED is currently in "on" state. * @param brightness is the target brightness. The type is integer and ranges from 1 to 100. * The brightness is a percentage instead of a absolute value. * 100 means maximum brightness while 1 means the minimum brightness. * @param {"smooth"| "sudden"} effect support two values: "sudden" and "smooth". If effect is "sudden", * then the color temperature will be changed directly to target value, * under this case, the third parameter "duration" is ignored. If effect is "smooth", * then the color temperature will be changed to target value in a gradual fashion, under this case, * the total time of gradual change is specified in third parameter "duration". * @param {number} duration specifies the total time of the gradual changing. The unit is milliseconds. * The minimum support duration is 30 milliseconds. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setBright( brightness: number, effect: "smooth" | "sudden" = "sudden", duration = 500, ): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_BRIGHT, [brightness, effect, duration])); } /** * @param command This method is used to change brightness, CT or color of a smart LED without * knowing the current value, it's main used by controllers. * @param {AdjustType} adjustType the direction of the adjustment. The valid value can be: * increase: increase the specified property * decrease: decrease the specified property * circle: increase the specified property, after it reaches the max value back to minimum value * @param {string} prop the property to adjust. The valid value can be: * “bright": adjust brightness. * “ct": adjust color temperature. * “color": adjust color. * (When “prop" is “color", the “action" can only be “circle", otherwise, it will be deemed as invalid request.) * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setAdjust(adjustType: AdjustType, prop: "bright" | "color" | "ct"): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_ADJUST, [adjustType, prop])); } /** * This method is used to start or stop music mode on a device. * Under music mode, no property will be reported and no message quota is checked. * @param action the action of set_music command. The valid value can be: * 0: turn off music mode. * 1: turn on music mode. * @param {string} host the IP address of the music server. * @param {number} port the TCP port music application is listening on. * When control device wants to start music mode, it needs start a TCP server firstly and then call “set_music” * command to let the device know the IP and Port of the TCP listen socket. After received the command, * LED device will try to connect the specified peer address. If the TCP connection can be established successfully, * then control device could send all supported commands through this channel without limit to simulate any music * effect. The control device can stop music mode by explicitly send a stop command or just by closing the socket. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setMusic(action: 0 | 1, host: string, port: number): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_MUSIC, [action, host, port])); } /** * This method is used to name the device. * The name will be stored on the device and reported in discovering response. * User can also read the name through “get_prop” method * @param {string} name the name of the device. * When using Yeelight official App, the device name is stored on cloud. * This method instead store the name on persistent memory of the device, so the two names could be different. * @returns {Promise<IEventResult>} return a promise of IEventResult */ public setName(name: string): Promise<IEventResult> { return this.sendCommand(new Command(1, CommandType.SET_NAME, [name])); } /** * This method is used to adjust the brightness by specified percentage within specified duration. * @param {number} percentage the percentage to be adjusted. The range is: -100 ~ 100 * @param {number} duration the milisecond of animation * @returns {Promise<IEventResult>} return a promise of IEventResult */ public adjust(type: CommandType.ADJUST_BRIGHT | CommandType.ADJUST_COLOR | CommandType.ADJUST_CT, percentage = 0, duration = 500): Promise<IEventResult> { return this.sendCommand(new Command(1, type, [percentage, duration])); } /** * This method is used to just check if the connection is alive */ public ping(): Promise<null> { return this.sendCommand(new Command(1, CommandType.PING, [])) .catch((command: IEventResult) => { // Expect a response: {"id":6, "error":{"code":-1, "message":"method not supported"}} const result = command.result; if ( !result || !result.error || result.error.code !== -1 || !(result.error.message + "").match(/not supported/i) ) { throw command; } }) .then(() => { // do nothing with the response return null; }); } /** * Use this function to send any command to the light, * please refer to specification to know the structure of command data * @param {Command} command The command to send to light via socket write * @returns {Promise<IEventResult>} return a promise of IEventResult */ public sendCommand(command: Command): Promise<IEventResult> { if (!this.connected) { return Promise.reject("Connection is closed"); } return new Promise((resolve, reject) => { const commandId = this.commandId++; command.id = commandId; this.sentCommands["" + commandId] = command; const timer = setTimeout(() => { this.removeAllListeners(`${this.EVENT_NAME}_${command.id}`); this.emit("commandTimedout", command); this.wasDisconnected(); reject("Command timedout, no response from server."); }, this.options.timeout); this.once(`${this.EVENT_NAME}_${command.id}`, (commandResult: IEventResult) => { clearTimeout(timer); const result = commandResult.result; if (result.id && result.result) { resolve(commandResult); } else if (result.error) { reject(commandResult); } }); const msg = command.getString(); this.client.write(msg + "\r\n", () => { this.emit(command.method + "_sent", command); }); }); } private connectToIp(host: string, port: number): Promise<Yeelight> { return new Promise((resolve, reject) => { this.isConnecting = true; this.isClosing = false; if (this.client) { // close old socket: this.closeConnection(); } this.client = new Socket(); this.client.on("data", this.onData.bind(this)); this.client.on("connect", () => { this.wasConnected(); }); this.client.on("close", () => { this.wasDisconnected(); }); this.client.on("end", () => { this.wasDisconnected(); }); this.client.on("error", (err) => { this.emit("error", err); this.wasDisconnected(); }); this.client.connect(port || DEFAULT_PORT, host, () => { this.isConnecting = false; this.wasConnected(); // me.emit("connected", this); resolve(this); }); this.client.once("error", (err) => { this.isConnecting = false; reject(err); }); setTimeout(() => { this.isConnecting = false; reject("Connection timeout"); }, this.connectTimeout); }); } private wasConnected() { this.isReconnecting = false; if (!this.connected) { this.connected = true; this.emit("connected"); this.triggerPing(); } } private wasDisconnected() { if (this.connected) { this.connected = false; this.emit("disconnected"); } this._recoverNetworkError(); } private _recoverNetworkError() { if (this.autoReconnect && !this.isClosing) { this.isReconnecting = true; if (!this.reconnectTimeout) { this.reconnectTimeout = setTimeout(() => { this.reconnectTimeout = null; if (!this.connected) { if (!this.isConnecting) { this.connect() .catch((err) => { if (!err.toString().match(/timeout/)) { // ignore connection timeout this.emit("error", "Erorr during reconnect: " + err); } this._recoverNetworkError(); }); } else { this._recoverNetworkError(); } } }, this.autoReconnectTime); } } } private triggerPing() { if (this.connected && !this.disablePing) { this.ping() .then(() => { if (!this.pingTimeout) { this.pingTimeout = setTimeout(() => { this.pingTimeout = null; this.triggerPing(); }, this.connectTimeout); } }) .catch(() => { // swallow }); } } private closeConnection() { this.wasDisconnected(); if (this.client) { this.client.removeAllListeners(); this.client.destroy(); } } }
the_stack
* Common rules / configuration for WordPress webpack builder. * * To make webpack possible with *.ts "ts-node" is needed for the "interpret" package. */ import { resolve, join } from "path"; import fs from "fs"; import { Configuration, DefinePlugin, Compiler, Options, ProvidePlugin } from "webpack"; import { spawn, execSync } from "child_process"; import WebpackBar from "webpackbar"; import MiniCssExtractPlugin from "mini-css-extract-plugin"; import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin"; const CacheLoaderVersion = require("cache-loader/package.json").version; /** * An internal plugin which runs build:webpack:done script. */ class WebpackPluginDone { private pwd: string; constructor(pwd: string) { this.pwd = pwd; } public apply(compiler: Compiler) { const env = Object.create(process.env); env.TS_NODE_PROJECT = resolve(this.pwd, "tsconfig.json"); compiler.hooks.done.tap("WebpackPluginDone", () => { spawn("yarn --silent build:webpack:done", { stdio: "inherit", shell: true, cwd: this.pwd, env }).on("error", (err) => console.log(err)); }); } } /** * Convert a slug like "my-plugin" to "myPlugin". This can * be useful for library naming (window[""] is bad because the hyphens). * * @param slug * @returns */ function slugCamelCase(slug: string) { return slug.replace(/-([a-z])/g, (g) => g[1].toUpperCase()); } /** * Generate externals because for add-on development we never bundle the dependent to the add-on! * * @returns {object} */ function getPlugins(pwd: string) { const lernaList: LernaListItem[] = JSON.parse( execSync("yarn --silent lerna list --loglevel silent --json --all").toString() ); // Filter only plugins, not packages const pluginList = lernaList.filter(({ location }) => location.startsWith(resolve(pwd, "../..", "plugins"))); // We determine the externals due the entry points const tsFolder = "src/public/ts"; const plugins: Array< LernaListItem & { modulePath: string; moduleId: string; externalId: string; entrypointName: string; } > = []; pluginList.forEach((item) => fs .readdirSync(join(item.location, tsFolder), { withFileTypes: true }) .filter((f) => !f.isDirectory()) // Now we have all entry points available .forEach((f) => { const [entrypointName] = f.name.split(".", 1); const modulePath = resolve(item.location, tsFolder, f.name); const moduleId = `${item.name}/${tsFolder}/${entrypointName}`; const externalId = `${slugCamelCase( require(resolve(item.location, "package.json")).slug )}_${entrypointName}`; // see output.library plugins.push({ ...item, modulePath, moduleId, externalId, entrypointName }); }) ); return plugins; } /** * Generate externals because for add-on development we never bundle the dependent to the add-on! * * @returns {object} */ function getPackages(pwd: string, rootSlugCamelCased: string) { const lernaList: LernaListItem[] = JSON.parse( execSync("yarn --silent lerna list --loglevel silent --json --all").toString() ); // Filter only packages, not plugins const packageList = lernaList.filter(({ location }) => location.startsWith(resolve(pwd, "../..", "packages"))); // We determine the externals due the entry points const packages: Array< LernaListItem & { externalId: string; } > = []; packageList.forEach((item) => { packages.push({ ...item, externalId: `${rootSlugCamelCased}_${item.name.split("/")[1]}` }); }); return packages; } /** * The result of yarn lerna list as JSON. */ type LernaListItem = { name: string; version: string; private: boolean; location: string; }; type FactoryValues = { pwd: string; mode: string; rootPkg: any; pkg: any; plugins: ReturnType<typeof getPlugins>; slug: string; type: "plugin" | "package"; rootSlugCamelCased: string; slugCamelCased: string; outputPath: string; tsFolder: string; }; /** * Create default settings for the current working directory. * If you want to do some customizations you can pass an override function * which passes the complete default settings and you can mutate it. */ function createDefaultSettings( type: "plugin" | "package", { override, definePlugin = (processEnv) => processEnv, webpackBarOptions = (options) => options, skipExternals = [], skipEntrypoints = [], onlyEntrypoints = [], babelCacheIdentifier = "" }: { override?: (settings: Configuration[], factoryValues: FactoryValues) => void; definePlugin?: (processEnv: any) => any; webpackBarOptions?: (options: WebpackBar.Options) => WebpackBar.Options; /** * Allows to skip externals in `config.externals`. This can be useful to * force-bundle a package. */ skipExternals?: string[]; /** * Allows to skip found entrypoints in `config.entry`. */ skipEntrypoints?: string[]; /** * Allows e. g. to only allow one entrypoint. */ onlyEntrypoints?: string[]; /** * Use this if you e. g. set different babel options for a second webpack configuration. */ babelCacheIdentifier?: string; } = {} ) { const pwd = process.env.DOCKER_START_PWD || process.env.PWD; const NODE_ENV = (process.env.NODE_ENV as Configuration["mode"]) || "development"; const CI = !!process.env.CI; const nodeEnvFolder = NODE_ENV === "production" ? "dist" : "dev"; const rootPkg = require(resolve(pwd, "../../package.json")); const pkg = require(resolve(pwd, "package.json")); const settings: Configuration[] = []; const plugins = getPlugins(pwd); const slug = type === "plugin" ? pkg.slug : pkg.name.split("/")[1]; const NoopLoader = resolve(pwd, "../../common/webpack-loader-noop.js"); const rootSlugCamelCased = slugCamelCase(rootPkg.name); const packages = getPackages(pwd, rootSlugCamelCased); const slugCamelCased = slugCamelCase(slug); const outputPath = type === "plugin" ? join(pwd, "src/public", nodeEnvFolder) : join(pwd, nodeEnvFolder); const tsFolder = resolve(pwd, type === "plugin" ? "src/public/ts" : "lib"); // We need to copy so updates to this object are not reflected to other configurations // And also, we need to copy the targets from `browserslist` to `@babel/preset-env#targets` // Read more about this bug in https://github.com/babel/babel/issues/9962 const babelOptions = JSON.parse(JSON.stringify(pkg.babel)); for (const preset of babelOptions.presets) { if (preset?.[0] === "@babel/preset-env") { preset[1].targets = pkg.browserslist; } } const pluginSettings: Configuration = { context: pwd, mode: NODE_ENV, optimization: { usedExports: true, sideEffects: true, splitChunks: { cacheGroups: type === "plugin" ? { // Dynamically get the entries from first-level files so every entrypoint get's an own vendor file (https://git.io/Jv2XY) ...plugins .filter(({ location }) => location === pwd) .reduce((map: { [key: string]: Options.CacheGroupsOptions }, obj) => { map[`vendor-${obj.entrypointName}`] = { test: /node_modules.*(?<!\.css)(?<!\.scss)(?<!\.less)$/, chunks: (chunk) => chunk.name === obj.entrypointName, name: `vendor-${obj.entrypointName}`, enforce: true }; return map; }, {}) } : { vendor: { test: /node_modules.*(?<!\.css)(?<!\.scss)(?<!\.less)$/, name: (module, chunks, cacheGroupKey) => { const allChunksNames = chunks.map((item: any) => item.name).join("-"); return `${cacheGroupKey}-${allChunksNames}`; }, chunks: "initial", enforce: true } } } }, output: { path: outputPath, filename: "[name].js", library: `${type === "plugin" ? slugCamelCased : rootSlugCamelCased}_${ type === "plugin" ? "[name]" : slugCamelCased }` }, entry: type === "plugin" ? { // Dynamically get the entries from first-level files ...plugins .filter(({ location }) => location === pwd) .reduce((map: { [key: string]: string }, obj) => { map[obj.entrypointName] = obj.modulePath; return map; }, {}) } : { index: resolve(pwd, "lib/index.tsx") }, externals: { react: "React", "react-dom": "ReactDOM", jquery: "jQuery", mobx: "mobx", wp: "wp", _: "_", lodash: "lodash", wpApiSettings: "wpApiSettings", "@wordpress/i18n": "wp['i18n']", // @wordpress/i18n relies on moment, but it also includes moment-timezone which also comes with WP core moment: "moment", "moment-timezone": "moment", // Get dynamically a map of externals for add-on development ...plugins.reduce((map: { [key: string]: string }, obj) => { map[obj.moduleId] = obj.externalId; return map; }, {}), // Get dynamically a map of external package dependencies ...packages.reduce((map: { [key: string]: string }, obj) => { map[obj.name] = obj.externalId.replace(/-([a-z])/g, (g) => g[1].toUpperCase()); return map; }, {}) }, devtool: "#source-map", module: { rules: [ { test: /\.tsx$/, exclude: /(disposables)/, use: [ CI ? NoopLoader : { loader: "cache-loader", options: { cacheIdentifier: `cache-loader:${CacheLoaderVersion} ${NODE_ENV}${babelCacheIdentifier}` } }, CI ? NoopLoader : "thread-loader", { loader: "babel-loader?cacheDirectory", options: babelOptions } ] }, { test: /\.(scss|css)$/, exclude: /(disposables)/, use: [ MiniCssExtractPlugin.loader, "css-loader?url=false", { loader: "postcss-loader", options: { plugins: [ require("autoprefixer")({}), require(resolve(pwd, "../../common/postcss-plugin-clean"))({}) ] } }, "sass-loader" ] } ] }, resolve: { extensions: [".js", ".jsx", ".ts", ".tsx"] }, plugins: [ new WebpackBar( webpackBarOptions({ name: slug }) ), new ForkTsCheckerWebpackPlugin(), new DefinePlugin({ // NODE_ENV is used inside React to enable/disable features that should only be used in development "process.env": definePlugin({ NODE_ENV: JSON.stringify(NODE_ENV), env: JSON.stringify(NODE_ENV), rootSlug: JSON.stringify(rootPkg.name), slug: JSON.stringify(slug) }) }), new MiniCssExtractPlugin({ filename: "[name].css" }) ].concat(process.env.BUILD_PLUGIN ? [] : [new WebpackPluginDone(pwd)]) }; skipExternals.forEach((key) => { delete (pluginSettings.externals as any)[key]; }); skipEntrypoints.forEach((key) => { delete (pluginSettings.entry as any)[key]; }); onlyEntrypoints.length && Object.keys(pluginSettings.entry).forEach((key) => { if (onlyEntrypoints.indexOf(key) === -1) { delete (pluginSettings.entry as any)[key]; } }); settings.push(pluginSettings); override?.(settings, { pwd, mode: NODE_ENV, rootPkg, pkg, plugins, slug, type, rootSlugCamelCased, slugCamelCased, outputPath, tsFolder }); return settings; } /** * In some cases it is more than recommend to use a lightweight alternative * to React in your frontend. E. g. for plugin developers creating frontend * solutions to non-logged-in users to reduce load time. * * Note: You need to apply `skipExternals: ["react", "react-dom"]`, too! */ function applyPreact(config: Configuration, disableChunks = false) { // Disable splitChunks so no `vendor~banner.js` is created if (disableChunks) { delete config.optimization.splitChunks; } // Implement preact and JSX transform through babel and webpack // https://preactjs.com/guide/v10/getting-started#aliasing-in-webpack config.resolve.alias = { react: "preact/compat", "react-dom": "preact/compat" }; // https://preactjs.com/guide/v8/switching-to-preact/#2-jsx-pragma-transpile-to-h // https://babeljs.io/docs/en/babel-preset-react#pragma (config.module.rules[0].use as any[])[2].options.presets[2] = [ "@babel/preset-react", { pragma: "h" } ]; // https://github.com/preactjs/preact-compat/issues/161#issuecomment-590806041 config.plugins.push( new ProvidePlugin({ h: ["preact", "h"] }) ); } export { WebpackPluginDone, createDefaultSettings, slugCamelCase, getPlugins, applyPreact };
the_stack
import { simpleHash } from '@tamagui/helpers' import hyphenateStyleName from 'hyphenate-style-name' import normalizeCSSColor from 'normalize-css-color' import { TextStyle, ViewStyle } from 'react-native' import { isWeb } from '../constants/platform' import { prefixInlineStyles, prefixStyles } from './prefixStyles' export function expandStyles(style: any) { const res = {} for (const key in style) { updateReactDOMStyle(res, key, style[key]) } return res } // TODO can use for inline styles... /** * Compile simple style object to inline DOM styles. * No support for 'animationKeyframes', 'placeholderTextColor', 'scrollbarWidth', or 'pointerEvents'. */ export function inline(style: Style): Object { return prefixInlineStyles(expandStyles(style)) } type Rule = string type Rules = Array<Rule> export type RulesData = { property?: string value?: string identifier: string rules: Rules } type CompilerOutput = { [key: string]: RulesData } type Value = Object | Array<any> | string | number export type Style = { [key: string]: Value } const STYLE_SHORT_FORM_EXPANSIONS = { borderColor: ['borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'], borderRadius: [ 'borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius', ], borderStyle: ['borderTopStyle', 'borderRightStyle', 'borderBottomStyle', 'borderLeftStyle'], borderWidth: ['borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth'], margin: ['marginTop', 'marginRight', 'marginBottom', 'marginLeft'], marginHorizontal: ['marginRight', 'marginLeft'], marginVertical: ['marginTop', 'marginBottom'], overflow: ['overflowX', 'overflowY'], overscrollBehavior: ['overscrollBehaviorX', 'overscrollBehaviorY'], padding: ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'], paddingHorizontal: ['paddingRight', 'paddingLeft'], paddingVertical: ['paddingTop', 'paddingBottom'], } export const generateAtomicStyles = (style: ViewStyle & TextStyle): CompilerOutput => { const res = expandStyles(style) if ( style.shadowColor != null || style.shadowOffset != null || style.shadowOpacity != null || style.shadowRadius != null ) { boxShadowReducer(res, style) delete res['shadowColor'] delete res['shadowOffset'] delete res['shadowOpacity'] delete res['shadowRadius'] } if ( style.textShadowColor != null || style.textShadowOffset != null || style.textShadowRadius != null ) { textShadowReducer(res, style) delete res['textShadowColor'] delete res['textShadowOffset'] delete res['textShadowRadius'] } const out = {} for (const key in res) { const value = res[key] if (value != null) { const valueString = stringifyValueWithProperty(value, key) const cachedResult = cache.get(key, valueString) if (cachedResult != null) { const { identifier } = cachedResult out[identifier] = cachedResult } else { const identifier = createIdentifier('r', key, value) const rules = createAtomicRules(identifier, key, value) const cachedResult = cache.set(key, valueString, { property: key, value: stringifyValueWithProperty(value, key), identifier, rules, }) out[identifier] = cachedResult } } } return out } function updateReactDOMStyle(style: Object, key: string, value: any) { value = normalizeValueWithProperty(value, key) const out = expandStyle(key, value) if (out) { Object.assign(style, Object.fromEntries(out)) } else { style[key] = value } } export function expandStyle(key: string, value: any) { if (key === 'flex') { // The 'flex' property value in React Native must be a positive integer, // 0, or -1. if (value <= -1) { return [ ['flexGrow', 0], ['flexShrink', 1], ['flexBasis', 'auto'], ] } // normalizing to better align with native // see spec for flex shorthand https://developer.mozilla.org/en-US/docs/Web/CSS/flex if (value >= 0) { return [ ['flexGrow', value], ['flexShrink', 1], ] } return } // web only switch (key) { // Ignore some React Native styles case 'elevation': case 'overlayColor': case 'resizeMode': case 'tintColor': { break } case 'aspectRatio': { return [[key, value.toString()]] } // TODO: remove once this issue is fixed // https://github.com/rofrischmann/inline-style-prefixer/issues/159 case 'backgroundClip': { if (value === 'text') { return [ ['backgroundClip', value], ['WebkitBackgroundClip', value], ] } break } case 'textAlignVertical': { return [['verticalAlign', value === 'center' ? 'middle' : value]] } case 'textDecorationLine': { return [['textDecorationLine', value]] } case 'transform': { if (Array.isArray(value)) { return [[key, value.map(mapTransform).join(' ')]] } break } case 'writingDirection': { return [['direction', value]] } } const longKey = STYLE_SHORT_FORM_EXPANSIONS[key] if (longKey) { return longKey.map((key) => { return [key, value] }) } else { if (isWeb && Array.isArray(value)) { return [[key, value.join(',')]] } } } function createAtomicRules(identifier: string, property, value): Rules { const rules: string[] = [] const selector = `.${identifier}` // Handle non-standard properties and object values that require multiple // CSS rules to be created. switch (property) { case 'animationKeyframes': { const { animationNames, rules: keyframesRules } = processKeyframesValue(value) const block = createDeclarationBlock({ animationName: animationNames.join(',') }) rules.push(`${selector}${block}`, ...keyframesRules) break } // Equivalent to using '::placeholder' case 'placeholderTextColor': { const block = createDeclarationBlock({ color: value, opacity: 1 }) rules.push( `${selector}::-webkit-input-placeholder${block}`, `${selector}::-moz-placeholder${block}`, `${selector}:-ms-input-placeholder${block}`, `${selector}::placeholder${block}` ) break } // Polyfill for additional 'pointer-events' values // See d13f78622b233a0afc0c7a200c0a0792c8ca9e58 case 'pointerEvents': { let finalValue = value if (value === 'auto' || value === 'box-only') { finalValue = 'auto!important' if (value === 'box-only') { const block = createDeclarationBlock({ pointerEvents: 'none' }) rules.push(`${selector}>*${block}`) } } else if (value === 'none' || value === 'box-none') { finalValue = 'none!important' if (value === 'box-none') { const block = createDeclarationBlock({ pointerEvents: 'auto' }) rules.push(`${selector}>*${block}`) } } const block = createDeclarationBlock({ pointerEvents: finalValue }) rules.push(`${selector}${block}`) break } // Polyfill for draft spec // https://drafts.csswg.org/css-scrollbars-1/ case 'scrollbarWidth': { if (value === 'none') { rules.push(`${selector}::-webkit-scrollbar{display:none}`) } const block = createDeclarationBlock({ scrollbarWidth: value }) rules.push(`${selector}${block}`) break } default: { const block = createDeclarationBlock({ [property]: value }) rules.push(`${selector}${block}`) break } } return rules } /** * Create CSS keyframes rules and names from a StyleSheet keyframes object. */ function processKeyframesValue(keyframesValue: number | string[]) { if (typeof keyframesValue === 'number') { throw new Error(`Invalid CSS keyframes type: ${typeof keyframesValue}`) } const animationNames: string[] = [] const rules: string[] = [] const value = Array.isArray(keyframesValue) ? keyframesValue : [keyframesValue] for (const keyframes of value) { if (typeof keyframes === 'string') { // Support external animation libraries (identifiers only) animationNames.push(keyframes) } else { // Create rules for each of the keyframes const { identifier, rules: keyframesRules } = createKeyframes(keyframes) animationNames.push(identifier) rules.push(...keyframesRules) } } return { animationNames, rules } } /** * Create individual CSS keyframes rules. */ function createKeyframes(keyframes) { const prefixes = ['-webkit-', ''] const identifier = createIdentifier('r', 'animation', keyframes) const steps = '{' + Object.keys(keyframes) .map((stepName) => { const rule = keyframes[stepName] const block = createDeclarationBlock(rule) return `${stepName}${block}` }) .join('') + '}' const rules = prefixes.map((prefix) => { return `@${prefix}keyframes ${identifier}${steps}` }) return { identifier, rules } } /** * Creates a CSS declaration block from a StyleSheet object. */ function createDeclarationBlock(style: Style) { const domStyle = prefixStyles(expandStyles(style)) const declarationsString = Object.keys(domStyle) .map((property) => { const value = domStyle[property] const prop = hyphenateStyleName(property) // The prefixer may return an array of values: // { display: [ '-webkit-flex', 'flex' ] } // to represent "fallback" declarations // { display: -webkit-flex; display: flex; } if (Array.isArray(value)) { return value.map((v) => `${prop}:${v}`).join(';') } else { return `${prop}:${value}` } }) // Once properties are hyphenated, this will put the vendor // prefixed and short-form properties first in the list. .sort() .join(';') return `{${declarationsString};}` } function createIdentifier(prefix: string, name: string, value): string { const hashedString = simpleHash(name + stringifyValueWithProperty(value, name)) return `${prefix}-${hashedString}` } const cache = { get(property, value) { if ( cache[property] != null && cache[property].hasOwnProperty(value) && cache[property][value] != null ) { return cache[property][value] } }, set(property, value, object) { if (cache[property] == null) { cache[property] = {} } return (cache[property][value] = object) }, } function stringifyValueWithProperty(value: Value, property?: string): string { // e.g., 0 => '0px', 'black' => 'rgba(0,0,0,1)' const normalizedValue = normalizeValueWithProperty(value, property) return typeof normalizedValue !== 'string' ? JSON.stringify(normalizedValue || '') : normalizedValue } // { scale: 2 } => 'scale(2)' // { translateX: 20 } => 'translateX(20px)' // { matrix: [1,2,3,4,5,6] } => 'matrix(1,2,3,4,5,6)' const mapTransform = (transform) => { const type = Object.keys(transform)[0] const value = transform[type] if (type === 'matrix' || type === 'matrix3d') { return `${type}(${value.join(',')})` } else { const normalizedValue = normalizeValueWithProperty(value, type) return `${type}(${normalizedValue})` } } const colorProps = { backgroundColor: true, borderColor: true, borderTopColor: true, borderRightColor: true, borderBottomColor: true, borderLeftColor: true, color: true, shadowColor: true, textDecorationColor: true, textShadowColor: true, } function normalizeValueWithProperty(value: any, property?: string): any { if (process.env.TAMAGUI_TARGET === 'web') { if ( (property === undefined || property === null || !unitlessNumbers[property]) && typeof value === 'number' ) { return `${value}px` } } if (property && colorProps[property]) { return normalizeColor(value) } return value } const normalizeColor = (color?: number | string, opacity = 1): void | string => { if (color == null || color == undefined) { return } if (process.env.TAMAGUI_TARGET === 'web') { if (typeof color === 'string' && isWebColor(color)) { return color } } const colorInt = processColor(color) if (colorInt != null) { const r = (colorInt >> 16) & 255 const g = (colorInt >> 8) & 255 const b = colorInt & 255 const a = ((colorInt >> 24) & 255) / 255 const alpha = (a * opacity).toFixed(2) return `rgba(${r},${g},${b},${alpha})` } } const isWebColor = (color: string): boolean => color === 'currentcolor' || color === 'currentColor' || color === 'inherit' || color.indexOf('var(') === 0 const processColor = (color?: number | string): number | undefined | null => { if (color === undefined || color === null) { return color } let intColor = normalizeCSSColor(color) if (intColor === undefined || intColor === null) { return undefined } return ((+intColor << 24) | (+intColor >>> 8)) >>> 0 } const unitlessNumbers = { animationIterationCount: true, aspectRatio: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFleGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexOrder: true, flexPositive: true, flexShrink: true, flexNegative: true, fontWeight: true, gridRow: true, gridRowEnd: true, gridRowGap: true, gridRowStart: true, gridColumn: true, gridColumnEnd: true, gridColumnGap: true, gridColumnStart: true, lineClamp: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true, scale: true, scaleX: true, scaleY: true, scaleZ: true, shadowOpacity: true, } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ const prefixes = ['ms', 'Moz', 'O', 'Webkit'] const prefixKey = (prefix: string, key: string) => { return prefix + key.charAt(0).toUpperCase() + key.substring(1) } Object.keys(unitlessNumbers).forEach((prop) => { prefixes.forEach((prefix) => { unitlessNumbers[prefixKey(prefix, prop)] = unitlessNumbers[prop] }) }) const resolveShadowValue = (style: ViewStyle): void | string => { const { shadowColor, shadowOffset, shadowOpacity, shadowRadius } = style const { height, width } = shadowOffset || defaultOffset const offsetX = normalizeValueWithProperty(width) const offsetY = normalizeValueWithProperty(height) const blurRadius = normalizeValueWithProperty(shadowRadius || 0) // @ts-ignore const color = normalizeColor(shadowColor || 'black', shadowOpacity) if (color != null && offsetX != null && offsetY != null && blurRadius != null) { return `${offsetX} ${offsetY} ${blurRadius} ${color}` } } function boxShadowReducer(resolvedStyle, style) { const { boxShadow } = style const shadow = resolveShadowValue(style) if (shadow != null) { resolvedStyle.boxShadow = boxShadow ? `${boxShadow}, ${shadow}` : shadow } } const defaultOffset = { height: 0, width: 0 } function textShadowReducer(resolvedStyle, style) { const { textShadowColor, textShadowOffset, textShadowRadius } = style const { height, width } = textShadowOffset || defaultOffset const radius = textShadowRadius || 0 const offsetX = normalizeValueWithProperty(width) const offsetY = normalizeValueWithProperty(height) const blurRadius = normalizeValueWithProperty(radius) const color = normalizeValueWithProperty(textShadowColor, 'textShadowColor') if ( color && (height !== 0 || width !== 0 || radius !== 0) && offsetX != null && offsetY != null && blurRadius != null ) { resolvedStyle.textShadow = `${offsetX} ${offsetY} ${blurRadius} ${color}` } }
the_stack
import '../fetchProxy'; import { QnaApiService } from './qnaApiService'; const mockArmToken = 'bm90aGluZw.eyJ1cG4iOiJnbGFzZ293QHNjb3RsYW5kLmNvbSJ9.7gjdshgfdsk98458205jfds9843fjds'; const mockResponsesTemplate = [ { value: [ { id: '/subscriptions/1234', subscriptionId: '1234', tenantId: '1234', displayName: 'Pretty nice Service', state: 'Enabled', subscriptionPolicies: { locationPlacementId: 'Public_2014-09-01', quotaId: 'MSDN_2014-09-01', spendingLimit: 'On', }, authorizationSource: 'Legacy', }, { id: '/subscriptions/1234', subscriptionId: '1234', tenantId: '43211', displayName: 'A useful service', state: 'Enabled', subscriptionPolicies: { locationPlacementId: 'Internal_2014-09-01', quotaId: 'Internal_2014-09-01', spendingLimit: 'Off', }, authorizationSource: 'RoleBased', }, ], }, { value: [ { id: '/subscriptions/1234', name: 'QnaMaker', type: 'Microsoft.CognitiveServices/accounts', etag: "'4321'", location: 'westus', sku: { name: 'F0', }, kind: 'QnAMaker', properties: { endpoint: 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0', internalId: '0000', dateCreated: '2018-08-03T17:06:20.8718086Z', apiProperties: { qnaRuntimeEndpoint: 'https://juwilabyqnamaker.azurewebsites.net', }, provisioningState: 'Succeeded', }, }, ], }, { value: [ { id: '/subscriptions/12324', name: 'FAQ2', type: 'Microsoft.CognitiveServices/accounts', etag: "'1234'", location: 'westus', sku: { name: 'F0', }, kind: 'QnAMaker', properties: { endpoint: 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0', internalId: '4321', dateCreated: '2018-05-08T14:55:01.0888756Z', apiProperties: { qnaRuntimeEndpoint: 'https://faq2.azurewebsites.net', }, provisioningState: 'Succeeded', }, }, ], }, { key1: 4444 }, { key1: 5555 }, { primaryEndpointKey: 'primary-endpoint-key-1', secondaryEndpointKey: 'secondary-endpoint-key-1', }, { knowledgebases: [ { id: '1234', hostName: 'https://localhost', lastAccessedTimestamp: '2018-08-21T20:27:35Z', lastChangedTimestamp: '2018-08-03T17:12:44Z', name: 'HIThere#1', userId: '1234', urls: ['https://localhost'], sources: [], }, ], }, { primaryEndpointKey: 'primary-endpoint-key-2', secondaryEndpointKey: 'secondary-endpoint-key-2', }, { knowledgebases: [ { id: '9876543', hostName: 'https://localhost', lastAccessedTimestamp: '2018-08-21T20:27:35Z', lastChangedTimestamp: '2018-08-03T17:12:44Z', name: 'HIThere#2', userId: '9876543', urls: ['https://localhost'], sources: [], }, ], }, ]; const mockArgsPassedToFetch = []; let mockResponses; (global as any).fetch = jest.fn(); (fetch as any).mockImplementation((url, headers) => { mockArgsPassedToFetch.push({ url, headers }); return { ok: true, json: async () => mockResponses.shift(), text: async () => mockResponses.shift(), }; }); describe('The QnaApiService happy path', () => { let result; beforeAll(() => (mockResponses = JSON.parse(JSON.stringify(mockResponsesTemplate)))); beforeEach(async () => { mockArgsPassedToFetch.length = 0; result = await getResult(); }); it('should retrieve the QnA Kbs when given an arm token', async () => { expect(result.services.length).toBe(2); expect(mockArgsPassedToFetch.length).toBe(9); expect(mockArgsPassedToFetch[0]).toEqual({ headers: { headers: { 'x-ms-date': jasmine.any(String), Accept: 'application/json, text/plain, */*', Authorization: 'Bearer bm90aGluZw.eyJ1cG4iOiJnbGFzZ293QHNjb3RsYW5kLmNvbSJ9.7gjdshgfdsk98458205jfds9843fjds', }, }, url: 'https://management.azure.com/subscriptions?api-version=2018-07-01', }); expect(mockArgsPassedToFetch[1]).toEqual({ headers: { headers: { 'x-ms-date': jasmine.any(String), Accept: 'application/json, text/plain, */*', Authorization: 'Bearer bm90aGluZw.eyJ1cG4iOiJnbGFzZ293QHNjb3RsYW5kLmNvbSJ9.7gjdshgfdsk98458205jfds9843fjds', }, }, url: 'https://management.azure.com//subscriptions/1234/providers' + '/Microsoft.CognitiveServices/accounts?api-version=2017-04-18', }); expect(mockArgsPassedToFetch[2]).toEqual({ headers: { headers: { 'x-ms-date': jasmine.any(String), Accept: 'application/json, text/plain, */*', Authorization: 'Bearer bm90aGluZw.eyJ1cG4iOiJnbGFzZ293QHNjb3RsYW5kLmNvbSJ9.7gjdshgfdsk98458205jfds9843fjds', }, }, url: 'https://management.azure.com//subscriptions/1234/providers/Microsoft.CognitiveServices/accounts' + '?api-version=2017-04-18', }); expect(mockArgsPassedToFetch[3]).toEqual({ url: 'https://management.azure.com//subscriptions/1234/listKeys?api-version=2017-04-18', headers: { headers: { 'x-ms-date': jasmine.any(String), Authorization: 'Bearer bm90aGluZw.eyJ1cG4iOiJnbGFzZ293QHNjb3RsYW5kLmNvbSJ9.7gjdshgfdsk98458205jfds9843fjds', Accept: 'application/json, text/plain, */*', }, method: 'POST', }, }); expect(mockArgsPassedToFetch[4]).toEqual({ url: 'https://management.azure.com//subscriptions/12324/listKeys?api-version=2017-04-18', headers: { headers: { 'x-ms-date': jasmine.any(String), Authorization: 'Bearer bm90aGluZw.eyJ1cG4iOiJnbGFzZ293QHNjb3RsYW5kLmNvbSJ9.7gjdshgfdsk98458205jfds9843fjds', Accept: 'application/json, text/plain, */*', }, method: 'POST', }, }); expect(mockArgsPassedToFetch[5]).toEqual({ url: 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/endpointkeys/', headers: { headers: { 'Ocp-Apim-Subscription-Key': 5555, 'Content-Type': 'application/json; charset=utf-8', }, }, }); expect(mockArgsPassedToFetch[6]).toEqual({ url: 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/', headers: { headers: { 'Ocp-Apim-Subscription-Key': 5555, 'Content-Type': 'application/json; charset=utf-8', }, }, }); expect(mockArgsPassedToFetch[7]).toEqual({ url: 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/endpointkeys/', headers: { headers: { 'Ocp-Apim-Subscription-Key': 4444, 'Content-Type': 'application/json; charset=utf-8', }, }, }); expect(mockArgsPassedToFetch[8]).toEqual({ url: 'https://westus.api.cognitive.microsoft.com/qnamaker/v4.0/knowledgebases/', headers: { headers: { 'Ocp-Apim-Subscription-Key': 4444, 'Content-Type': 'application/json; charset=utf-8', }, }, }); expect(result.services).toEqual([ { endpointKey: 'primary-endpoint-key-1', hostname: 'https://localhost/qnamaker', id: '1234', kbId: '1234', name: 'HIThere#1', subscriptionKey: 4444, type: 'qna', }, { endpointKey: 'primary-endpoint-key-2', hostname: 'https://localhost/qnamaker', id: '9876543', kbId: '9876543', name: 'HIThere#2', subscriptionKey: 5555, type: 'qna', }, ]); }); }); describe('The QnAMakerApi sad path', () => { beforeEach(() => { mockResponses = JSON.parse(JSON.stringify(mockResponsesTemplate)); }); it('should return an empty payload with an error if no subscriptions are found', async () => { mockResponses = [{ value: [] }, { value: [] }]; const result = await getResult(); expect(result).toEqual({ services: [], code: 1 }); }); it('should return an empty payload with an error if no accounts are found', async () => { mockResponses[1] = mockResponses[2] = { value: [] }; const result = await getResult(); expect(result).toEqual({ services: [], code: 2 }); }); it('should return an empty payload with an error if no keys are found', async () => { mockResponses[3] = mockResponses[4] = { value: [] }; const result = await getResult(); expect(result).toEqual({ services: [], code: 2 }); }); it('should return an empty payload if endpointKey request fails', async () => { (fetch as any).mockImplementation(url => { let ok = true; if (url.includes('endpointkeys')) { ok = false; mockResponses.shift(); } return { ok, json: async () => mockResponses.shift(), text: async () => mockResponses.shift(), }; }); const result = await getResult(); expect(result).toEqual({ services: [], code: 0 }); }); it('should return an empty payload if knowledgebase request fails', async () => { (fetch as any).mockImplementation(url => { let ok = true; if (url.includes('knowledgebases')) { ok = false; mockResponses.shift(); } return { ok, json: async () => mockResponses.shift(), text: async () => mockResponses.shift(), }; }); const result = await getResult(); expect(result).toEqual({ services: [], code: 0 }); }); }); async function getResult() { const it = QnaApiService.getKnowledgeBases(mockArmToken); let result = undefined; // eslint-disable-next-line no-constant-condition while (true) { const next = it.next(result); if (next.done) { result = next.value; break; } try { result = await next.value; } catch (e) { break; } } return result; }
the_stack
import { File, Storage } from "@google-cloud/storage"; import * as commander from "commander"; import * as faker from "faker"; import * as admin from "firebase-admin"; import * as lodash from "lodash"; import * as ora from "ora"; import * as winston from "winston"; import { Operation, OperationSet, Task } from "../functions/src"; import { CloudFunctionsServiceClient } from "@google-cloud/functions"; import * as inquirer from "inquirer"; import { Semaphore } from "await-semaphore"; import { GoogleAuth } from "google-auth-library"; class PromiseQueue { startIdx: number; endIdx: number; contents: { [index: number]: Promise<any> }; constructor() { this.startIdx = 0; this.endIdx = 0; this.contents = {}; } /** * Returns the current size of this Promise Queue. */ size() { return this.endIdx - this.startIdx; } /** * Enqueues a new Promise into the Promise Queue. */ enqueue(promise: Promise<any>) { this.contents[this.endIdx] = promise; this.endIdx++; } /** * Returns the oldest Promise in the Promise Queue. */ dequeue() { if (this.startIdx !== this.endIdx) { const promise = this.contents[this.startIdx]; delete this.contents[this.startIdx]; this.startIdx++; return promise; } throw "dequeue should not be called on empty PromiseQueue"; } /** * Returns a Promise that resolves when all the Promises inside the Promise Queue resolve. */ async onEmpty() { return Promise.all(Object.values(this.contents)); } } /** * Add a promise to the Promise Queue. * @param promises The Promise Queue to add to. * @param newPromise The new Promise to add to the Promise Queue. * @param maxConcurrentRequests The maximum number of concurrent requests. */ const addToPromiseQueue = async ( promises: PromiseQueue, newPromise: Promise<any>, maxConcurrentRequests: number ) => { // Limit the number of pending requests to save on memory. if (promises.size() >= maxConcurrentRequests) { await promises.dequeue(); } promises.enqueue(newPromise); }; /** * Create a Winston Logger for the given log file name. * @param logFile The file name for the log file to write to. */ const createLogger = (logFile: string): winston.Logger => { return winston.createLogger({ level: "info", format: winston.format.json(), levels: { // Levels are reversed because potentially many errors will be found and these need to be logged. // Both info and errors are logged to file, info logs are sent to the console. info: 0, error: 1, }, transports: [ new winston.transports.File({ filename: logFile, level: "error", }), new winston.transports.Console({ level: "info", format: winston.format.cli(), }), ], }); }; /** * Return the number of seconds between now and a given Epoch time in milliseconds. * @param time Time in milliseconds since Epoch time. */ const secondsSinceTime = (time: number): number => (Date.now() - time) / 1000; /** * Prune any leading, trailing or extraneous slashes from a file path prefix if there are any. * @param prefix The prefix to prune. */ const prunePrefix = (prefix: string): string => { return prefix .split("/") .filter((part) => part.length > 0) .join("/"); }; /** * Get the Firestore Item Document path from the given Object name. * @param constants Consistency Check constants. * @param bucket The bucket * @param name The Object name. */ const objectNameToFirestorePath = ( constants: CheckConstants, bucket: string, name: string ): string => { const parts = name.split("/"); const fileName = parts[parts.length - 1]; let prefix = `${constants.root}/${bucket}`; for (let i = 0; i < parts.length - 1; i++) { const part = parts[i]; prefix += `/${constants.prefixes}/${part}`; } return `${prefix}/${constants.items}/${fileName}`; }; interface WriteConfig { bucket: string; database: string; project: string; prefix: string; maxPendingTasks: number; setsPerTask: number; operationsPerSet: number; tasksPerSecond: number; interval: number; logFile: string; } interface WriteState { spinner: ora.Ora; logger: winston.Logger; mode: "running" | "waiting"; startTime: number; tasksInQueue: number; tasksLastPushed: number; tasksTotal: number; tasksNumErrors: number; tasksPerSecond: number; } const writeCmd: commander.Command = new commander.Command("write") .allowUnknownOption(false) .description("generate load tasks for stress test load runner in RTDB") .requiredOption("-b, --bucket <bucket>", "bucket to write to") .requiredOption( "-d, --database <database-name>", "the name of the realtime database instance to write tasks to, example: https://<database-name>.firebaseio.com" ) .option( "-p, --prefix <prefix>", "prefix for all generated file paths to be under (trailing slash optional)", "" ) .option("-t, --test <namespace>", "use local emulator with namespace") .option( "-m, --max-pending-tasks <number>", "maximum number of tasks in queue", "200" ) .option( "-s, --sets-per-task <number>", "number of operation sets per task to run in parallel", "5" ) .option( "-o, --operations-per-set <number>", "number of operations per operation set", "10" ) .option( "-n, --tasks-per-second <number>", "max number of tasks pushed per second", "50" ) .option( "-i, --interval <number>", "interval in milliseconds between pushing tasks", "1000" ) .option("-l, --log-file <filename>", "file to store all logs", "write.log") .option("--project <project_id>", "project to run this stress test on") .action(async (cmd: commander.Command) => { const config: WriteConfig = { bucket: cmd.bucket, database: cmd.database, project: cmd.project, prefix: cmd.prefix, maxPendingTasks: parseInt(cmd.maxPendingTasks), setsPerTask: parseInt(cmd.setsPerTask), operationsPerSet: parseInt(cmd.operationsPerSet), tasksPerSecond: parseInt(cmd.tasksPerSecond), interval: parseInt(cmd.interval), logFile: cmd.logFile, }; config.prefix = prunePrefix(config.prefix); const integerFields: (keyof WriteConfig)[] = [ "maxPendingTasks", "setsPerTask", "operationsPerSet", "tasksPerSecond", "interval", ]; integerFields.forEach((field) => { if (!(config[field] >= 1)) { throw new Error(`Invalid ${field}`); } }); if (!cmd.bucket) throw new Error("Bucket must be specified."); const state: WriteState = { spinner: ora(), logger: createLogger(config.logFile), mode: "running", startTime: Date.now(), tasksInQueue: 0, tasksLastPushed: 0, tasksTotal: 0, tasksNumErrors: 0, tasksPerSecond: 0, }; // Initialize Admin SDK using either local emulator or service account key file. if (cmd.test) { admin.initializeApp({ databaseURL: `http://localhost:9000/?ns=${cmd.test}`, }); state.logger.info( `Using local Emulator Database with Namespace: ${cmd.test}` ); } else { admin.initializeApp({ credential: admin.credential.applicationDefault(), databaseURL: `https://${config.database}.firebaseio.com/`, projectId: config.project, }); } // Setup finished, can start Stress Test. state.logger.info("Starting Stress Test with configuration:"); state.logger.info(JSON.stringify(config)); state.logger.info(`Logging to ${config.logFile}.`); const db = admin.database(); db.ref() .child("tasks") .on("value", (snapshot) => { state.tasksInQueue = snapshot.numChildren(); }); db.ref() .child("errors") .on("value", (snapshot) => { state.tasksNumErrors = snapshot.numChildren(); }); const taskPushInterval = setInterval(() => { const tasksPushed = pushTasks(config, state.tasksInQueue); const secondsElapsed = secondsSinceTime(state.startTime); state.tasksLastPushed = tasksPushed; state.tasksTotal += tasksPushed; state.tasksPerSecond = state.tasksTotal / secondsElapsed; }, config.interval); setInterval(() => { updateWriteSpinner(state); }, 1000); // Listen to stdin for events to stop the Stress Test or force-quit. if (!process.stdin.setRawMode) throw new Error("Stdin Raw Mode not supported."); process.stdin.setRawMode(true); process.stdin.resume(); process.stdin.on("data", async (data) => { const char = data.toString(); if (char === "q" || char === "Q") { state.logger.info("Force Quitting..."); process.exit(0); } if (state.mode === "running") { // Wait for the Task queue to clear out before continuing. clearInterval(taskPushInterval); state.mode = "waiting"; } else if (state.mode === "waiting") { state.spinner.stop(); state.logger.info("Cleaning up RTDB..."); const tasksTotal = state.tasksTotal; const tasksNumErrors = state.tasksNumErrors; const tasksPerSecond = state.tasksPerSecond; const avgQps = tasksPerSecond * config.setsPerTask * config.operationsPerSet; const secondsElapsed = secondsSinceTime(state.startTime); await db.ref().child("tasks").remove(); await db.ref().child("errors").remove(); state.logger.info( `Pushed ${tasksTotal} tasks total at a rate of ${tasksPerSecond}/s over ${secondsElapsed} seconds with ${tasksNumErrors} task errors. Average QPS: ${avgQps}\n` ); process.exit(0); } }); state.spinner.start(); }); /** * Update the spinner with relevant text for the current Stess Test writing state. * @param state The current Stress Test write state. */ const updateWriteSpinner = (state: WriteState) => { const secondsElapsed = secondsSinceTime(state.startTime); if (state.mode === "running") { state.spinner.text = `Pushing tasks: ${ state.tasksInQueue } Tasks in queue, ${state.tasksTotal} Tasks pushed so far, ${ state.tasksNumErrors } Task Errors so far, pushed ${ state.tasksLastPushed } last interval, average: ${state.tasksPerSecond.toFixed(2)}/s\n`; state.spinner.text += `Press 'q' to Force Quit, press any key to stop.\n`; } else if (state.mode === "waiting") { if (state.tasksInQueue > 0) { state.spinner.text = `Waiting for tasks to finish... ${state.tasksInQueue} tasks left in queue.\n`; } else { state.spinner.text = "No tasks remaining.\n"; } state.spinner.text += "Press any key to clean up and exit or press 'q' to exit without cleaning up.\n"; } state.spinner.text += `Running for ${secondsElapsed} seconds.\n`; }; /** * Generate a random file path to be written to. If a Prefix is configured it will be prefixed with it. * @param prefix The prefix for the generated file paths. */ const createPath = (prefix: string): string => { // Number added at the end to improve uniqueness. const filePath = faker.system.filePath().substr(1) + faker.random.number().toString(); if (prefix.length > 0) { return `${prefix}/${filePath}`; } return `${filePath}`; }; /** * Generate a random Operation using the provided path, and operation type. * @param path The path to be used in the Operation. * @param type The Operation Type that should be generated. * @param minFileSize Minimum file size for the file being written. * @param maxFileSize Maximum file size for the file being written. */ const createOperation = ( path: string, type: Operation["type"], minFileSize?: number, maxFileSize?: number ): Operation => { switch (type) { case "write": if (!maxFileSize || !minFileSize) throw new Error( "File sizes need to be specified for Write operations." ); return { type: "write", path, size: selectFileSize(maxFileSize, minFileSize), }; case "update": return { type: "update", path, metadata: { [faker.name.firstName()]: faker.name.lastName() }, }; case "delete": return { type: "delete", path }; } }; /** * Generate a random Operation using the provided path, and operation type. * @param path The path to be used in the Operation. * @param type The Operation Type that should be generated. */ const createOperationSet = ( path: string, operationsPerSet: number ): OperationSet => { const minFileSize = 2; const maxFileSize = 100; const set: OperationSet = []; // Operation Sets need to start with a write, can't update or delete a file that doesn't exist. set.push(createOperation(path, "write", minFileSize, maxFileSize)); for (let i = 1; i < operationsPerSet; i++) { if (set[i - 1].type === "delete") { // Can only write after deleting. set.push(createOperation(path, "write", minFileSize, maxFileSize)); continue; } set.push( createOperation(path, selectOperation(), minFileSize, maxFileSize) ); } return set; }; const selectOperation = (): Operation["type"] => { const rand = Math.random(); if (rand < 0.33) { return "write"; } else if (rand < 0.66) { return "update"; } else { return "delete"; } }; const selectFileSize = (max: number, min: number): number => Math.floor(Math.random() * max) + min; /** * Generate a Task using whatever configuration values were set. * @param bucket GCS Bucket for files to be written to. * @param prefix The prefix for the generated file paths. * @param setsPerTask The number of Operation Sets to be run in parallel in a task. * @param operationsPerSet The number of Operations in each Operation Set to be run sequentially. */ const createTask = ( bucket: string, prefix: string, setsPerTask: number, operationsPerSet: number ): Task => { // Create n Operation Sets for the Task. const operationSets = []; for (let i = 0; i < setsPerTask; i++) { const path = createPath(prefix); operationSets.push(createOperationSet(path, operationsPerSet)); } return { bucket: bucket, operations: operationSets, }; }; /** * Push tasks to RTDB, the number of Tasks pushed depends on the state of the Task queue and the * configured settings. * @param config The Stress Test Configuration. * @param tasksInQueue The number of tasks currently enqueued. */ const pushTasks = (config: WriteConfig, tasksInQueue: number): number => { const db = admin.database(); const updates: any = {}; // Whatever is less, the max Tasks/second or the difference between the current number of Tasks and the max. // Push these tasks divided across `intervals` every second. const numTasksToPush = Math.floor( Math.min( config.tasksPerSecond, Math.max(0, config.maxPendingTasks - tasksInQueue) ) / (1000 / config.interval) ); if (numTasksToPush === 0) return 0; // Create n tasks and batch the update for RTDB. for (let i = 0; i < numTasksToPush; i++) { const task = createTask( config.bucket, config.prefix, config.setsPerTask, config.operationsPerSet ); const key = db.ref().child("tasks").push().key; if (key == null) break; updates[key] = task; } db.ref().child("tasks").update(updates); return numTasksToPush; }; interface CheckConfig { bucket: string; prefix: string; logFile: string; checkFirestore: boolean; checkGcs: boolean; project: string; } interface CheckState { spinner: ora.Ora; logger: winston.Logger; startTime: number; numInconsistencies: number; firestoreNumItems: number; firestoreNumItemsChecked: number; firestorePrefixesRemaining: number; storageNumFiles: number; storageNumFilesChecked: number; storagePrefixesRemaining: number; } interface CheckConstants { items: string; prefixes: string; root: string; metadataField: string; customMetadata: string; maxConcurrentRequests: number; } async function confirm(prompt: string): Promise<boolean> { const questions: inquirer.QuestionCollection = [ { type: "confirm", name: "confirmed", message: prompt, }, ]; const answers = await inquirer.prompt(questions); return answers["confirmed"]; } const backfillCmd = new commander.Command("backfill") .allowUnknownOption(false) .description("backfill data from gcs into firestore") .option( "--project <project_id>", "project id which has the extension installed" ) .option( "--instance-id <extension_instance_id>", "instance id of the extension (which can be found with `firebase ext:list`)." ) .option( "-c, --concurrency <concurrency>", "Number of requests in flight at a time.", "50" ) // TODO: Add option to specify a prefix. .action(async (command: commander.Command) => { interface CommandWithOpts extends commander.Command { project?: string; instanceId?: string; concurrency: string; } const cmd = command as CommandWithOpts; const concurrency = parseInt(cmd.concurrency); if (!(concurrency >= 1)) { throw "Invalid concurrency"; } const clientOptions = cmd.project ? { projectId: cmd.project } : undefined; const client = new CloudFunctionsServiceClient(clientOptions); const projectId = await client.getProjectId(); console.log(`Using project: ${projectId}`); const parent = `projects/${projectId}/locations/-`; // The page size is 1001 to ensure that the results come back in one page. const [allFunctions] = await client.listFunctions({ parent: parent, pageSize: 1001, }); // Get all of the mirrorObjectPathHttp functions. const mirrorFunctions = allFunctions.filter((f) => { // All functions installed for extensions have labels. if (!f.labels) { return false; } // Make sure the function is part of this extension. const isExtension = f.labels["deployment-tool"] === "firebase-extensions" && f.labels["goog-firebase-ext"] === "storage-mirror-firestore"; if (!isExtension) { return false; } // If the user specified an extension instance id, filter on that. if (cmd.instanceId) { if (f.labels["goog-firebase-ext-iid"] !== cmd.instanceId) { return false; } } return f.entryPoint === "mirrorObjectPathHttp"; }); if (mirrorFunctions.length === 0) { throw "Extension doesn't appear to be installed for this project"; } let extensionId = ""; if (mirrorFunctions.length > 1) { const extIds = mirrorFunctions.map((f) => { return f.labels!["goog-firebase-ext-iid"]!; }); const questions: inquirer.QuestionCollection = [ { type: "list", choices: extIds, name: "extension-id", message: "Choose an extension id", }, ]; const answer = await inquirer.prompt(questions); extensionId = answer["extension-id"]; } else { extensionId = mirrorFunctions[0].labels!["goog-firebase-ext-iid"]!; } const httpFunction = mirrorFunctions.find( (f) => f.labels!["goog-firebase-ext-iid"] === extensionId )!; const config = httpFunction.environmentVariables!; const bucketName = config["BUCKET"]!; { const prompt = `Are you sure you want to mirror objects from ${bucketName} into Firestore for the project ${projectId}?`; if (!(await confirm(prompt))) { throw "aborted"; } } const authClient = new GoogleAuth({ projectId: projectId, }); // This calls our http trigger for one path. const mirrorPath = async (path: string): Promise<void> => { await authClient.request({ url: httpFunction.httpsTrigger!.url!, method: "POST", data: { path: path }, retryConfig: { retry: 3, }, }); }; console.log(`Mirroring objects in bucket: ${bucketName}`); let succeeded = 0; const spinner = ora("Starting"); spinner.start(); const startTime = Date.now(); const intervalId = setInterval(() => { // TODO: display more recent qps (with an exponential filter). const elapsed = Math.floor((Date.now() - startTime) / 1000); const speed = Math.floor((10 * succeeded) / elapsed) / 10; // Hack to get one digit after the decimal point. spinner.text = `Mirrored ${succeeded} paths in ${elapsed}s. Avg throughput: ${speed} tasks/sec.`; }, 1000); const semaphore = new Semaphore(concurrency); try { const storage = new Storage(); const bucket = storage.bucket(bucketName); let erroredPath: [string, any] | undefined = undefined; let pageToken = ""; while (pageToken != null) { const [files, _, response] = await bucket.getFiles({ autoPaginate: false, pageToken, }); for (let f of files) { const path = f.name; const release = await semaphore.acquire(); if (erroredPath) { console.error( `Error attempting to mirror path ${erroredPath[0]}`, erroredPath[1] ); throw erroredPath[1]; } mirrorPath(path) .then((_) => { succeeded += 1; release(); }) .catch((err) => { if (!erroredPath) { erroredPath = [path, err]; } release(); }); } pageToken = response.nextPageToken || null; } // To wait for requests to finish, we acquire all the semaphore capacity. for (let i = 0; i < concurrency; i++) { await semaphore.acquire(); if (erroredPath) { console.error( `Error attempting to mirror path ${erroredPath[0]}`, erroredPath[1] ); throw erroredPath[1]; } } } catch (e) { clearInterval(intervalId); spinner.fail(); throw e; } clearInterval(intervalId); const elapsed = Math.floor((Date.now() - startTime) / 1000); spinner.succeed(`Mirrored ${succeeded} paths in ${elapsed}s.`); }); const checkCmd = new commander.Command("check") .allowUnknownOption(false) .description("check for consistency between GCS and Firestore") .requiredOption("-b, --bucket <bucket>", "bucket to check") .option( "-p, --prefix <prefix>", "prefix for all generated file paths to be under", "" ) .option( "-l, --log-file <filename>", "file to store all logs", "consistency.log" ) .option("--no-firestore", "skip firestore check") .option("--no-gcs", "skip gcs check") .option("--project <project_id>", "project to run this stress test on") .action(async (cmd: commander.Command) => { const constants = { items: "items", prefixes: "prefixes", root: "gcs-mirror", metadataField: "gcsMetadata", customMetadata: "metadata", maxConcurrentRequests: 100, }; const config: CheckConfig = { bucket: cmd.bucket, project: cmd.project, prefix: cmd.prefix, logFile: cmd.logFile, checkFirestore: cmd.firestore ? true : false, checkGcs: cmd.gcs ? true : false, }; if (!cmd.bucket) throw new Error("Bucket must be specified."); const state: CheckState = { spinner: ora(), logger: createLogger(config.logFile), startTime: Date.now(), numInconsistencies: 0, firestoreNumItems: 0, firestoreNumItemsChecked: 0, firestorePrefixesRemaining: 0, storageNumFiles: 0, storageNumFilesChecked: 0, storagePrefixesRemaining: 0, }; config.prefix = prunePrefix(config.prefix); admin.initializeApp({ credential: admin.credential.applicationDefault(), projectId: config.project, }); // Setup finished, can start consistency check. state.logger.info("Starting Consistency Check with configuration:"); state.logger.info(JSON.stringify(config)); state.logger.info( `Any inconsistencies will be logged to ${config.logFile}.` ); state.spinner.start(); setInterval(() => { updateCheckSpinner(state); }, 1000); await consistencyCheck(config, state, constants); state.spinner.stop(); state.logger.info(`${state.numInconsistencies} Inconsistencies found.`); state.logger.info( `${state.firestoreNumItemsChecked} Firestore Documents for ${state.storageNumFilesChecked} GCS Objects.` ); const secondsElapsed = secondsSinceTime(state.startTime); state.logger.info(`Consistency Check finished in ${secondsElapsed}s`); process.exit(0); }); /** * Update the spinner with relevant text for the current consistency check state. * @param state The current consistency check state. */ const updateCheckSpinner = (state: CheckState) => { state.spinner.text = `Checking Consistency... \n`; state.spinner.text += `Checking Firestore Documents for non-existent paths: ${state.firestoreNumItemsChecked}/${state.firestoreNumItems} Documents checked`; if ( state.firestorePrefixesRemaining > 0 || state.firestoreNumItemsChecked <= state.firestoreNumItems ) { state.spinner.text += `, Prefixes Remaining: ${state.firestorePrefixesRemaining}\n`; } else { state.spinner.text += `, Finished! ✔️\n`; } state.spinner.text += `Checking GCS for corresponding Firestore Documents: ${state.storageNumFilesChecked}/${state.storageNumFiles} Files checked`; if ( state.storagePrefixesRemaining > 0 || state.storageNumFilesChecked <= state.storageNumFiles ) { state.spinner.text += `, Prefixes Remaining: ${state.storagePrefixesRemaining}\n`; } else { state.spinner.text += `, Finished! ✔️\n`; } state.spinner.text += `${state.numInconsistencies} Inconsistencies found so far.\n`; state.spinner.text += `Running for ${secondsSinceTime( state.startTime )} seconds.\n`; }; /** * Run a consistency check on Firestore against GCS contents and GCS against the mirrored data in Firestore. * @param config The Consistency Check Config. * @param state The Consistency Check State. * @param constants The Consistency Check Constants. */ const consistencyCheck = async ( config: CheckConfig, state: CheckState, constants: CheckConstants ) => { const checks = []; // Check Firestore for consistency. if (config.checkFirestore) { checks.push( checkFirestore(config, state, constants, (err) => { state.logger.error(err); state.numInconsistencies += 1; }) ); } // Check GCS for consistency. if (config.checkGcs) { checks.push( checkStorage(config, state, constants, (err) => { state.logger.error(err); state.numInconsistencies += 1; }) ); } await Promise.all(checks); }; /** * Check Firestore for consistency with GCS, run the provided callback if a Firestore document exists but * a corresponding GCS Object cannot be found. * @param config The Consistency Check Config. * @param state The Consistency Check State. * @param constants The Consistency Check Constants. * @param onInconsistency Callback function to run in the case of an inconsistency. */ const checkFirestore = async ( config: CheckConfig, state: CheckState, constants: CheckConstants, onInconsistency: (name: string) => void ): Promise<void> => { const firestore = admin.firestore(); const bucket = admin.storage().bucket(config.bucket); // Create the root Prefix Document path. let rootPrefix = `${constants.root}/${config.bucket}`; if (config.prefix.length > 0) { const parts = config.prefix.split("/"); parts.forEach((part) => { rootPrefix += `/${constants.prefixes}/${part}`; }); } // Depth-first traversal through Firestore, adding newly discovered Prefixes onto the stack. const prefixes = [rootPrefix]; const promises = new PromiseQueue(); while (prefixes.length > 0) { const currPrefix = prefixes.pop() as string; // Paginate requests to Firestore to preserve memory. const prefixesPromise = new Promise(async (resolve, reject) => { const prefixesSnapshot = await firestore .collection(`${currPrefix}/${constants.prefixes}`) .get(); const prefixDocs = prefixesSnapshot.docs; // Add discovered Prefixes to the stack. prefixDocs.forEach((doc) => prefixes.push(doc.ref.path)); resolve(prefixDocs.length); }); const itemPromise = new Promise(async (resolve, reject) => { let length = 0; let itemsSnapshot = null; while (itemsSnapshot == null || itemsSnapshot.docs.length > 0) { itemsSnapshot = await firestore .collection(`${currPrefix}/${constants.items}`) .orderBy(`${constants.metadataField}.name`) .startAfter( itemsSnapshot ? itemsSnapshot.docs[itemsSnapshot.docs.length - 1] : null ) .limit(1000) .get(); const itemDocs = itemsSnapshot.docs; length += itemDocs.length; state.firestoreNumItems += itemDocs.length; // Consistency check for discovered Item Documents. for (let i = 0; i < itemDocs.length; i++) { const doc = itemDocs[i]; const name = doc.data()[constants.metadataField].name; const fileExistsPromise = bucket .file(name) .exists() .then(([exists]) => { state.firestoreNumItemsChecked += 1; if (!exists) { // The Item Document should correspond to a Object in GCS. onInconsistency( `The Firestore Document(${doc.ref.path}) represents a non-existent GCS location: ${name}` ); } }); await addToPromiseQueue( promises, fileExistsPromise, constants.maxConcurrentRequests ); } } resolve(length); }); const [prefixDocsLength, itemDocsLength] = (await Promise.all([ prefixesPromise, itemPromise, ])) as [number, number]; // Consistency check for Prefix Document. if (itemDocsLength === 0 && prefixDocsLength === 0) { if (currPrefix === rootPrefix) { onInconsistency( `The Root Prefix Document(${currPrefix}) for ${config.prefix} does not exist or is empty.` ); } // The Prefix Document should contain members. onInconsistency( `The Prefix Document(${currPrefix}) exists but does not contain any Items or Prefixes, it should have been Tombstoned.` ); } state.firestorePrefixesRemaining = prefixes.length; state.firestoreNumItems += itemDocsLength; } // Remaining requests need to finish before exiting. await promises.onEmpty(); }; /** * Check GCS for consistency with Firestore, each GCS Object should have a corresponding Firestore Document * that contains the correct fields. A callback is run for each inconsistent Object. * @param config The Consistency Check Config. * @param state The Consistency Check State. * @param constants The Consistency Check Constants. * @param onInconsistency Callback function to run in the case of an inconsistency. */ const checkStorage = async ( config: CheckConfig, state: CheckState, constants: CheckConstants, onInconsistency: (err: string) => void ): Promise<void> => { const firestore = admin.firestore(); const bucket = admin.storage().bucket(config.bucket); const prefixes = [config.prefix]; // Depth-first traversal through GCS, adding newly discovered Prefixes onto the stack. const promises = new PromiseQueue(); while (prefixes.length > 0) { const currPrefix = prefixes.pop() as string; // Paginate GCS query to preserve memory. Keep querying this Prefix until a pageToken is not returned. let pageToken = ""; while (pageToken != null) { const [files, _, response] = await bucket.getFiles({ autoPaginate: false, delimiter: "/", prefix: currPrefix, pageToken, }); pageToken = response.nextPageToken || null; // Prefixes field might be missing from response. const newPrefixes = response.prefixes || ([] as string[]); // Add newly discovered Prefixes to stack. newPrefixes.forEach((prefix: string) => prefixes.push(prefix)); // Construct Firestore path for Prefix Document. let path = `${constants.root}/${config.bucket}`; const parts = currPrefix.split("/").filter((s) => s.length > 0); parts.forEach((part) => { path += `/${constants.prefixes}/${part}`; }); // Check Prefix for consistency. const prefixDocExistsPromise = firestore .doc(path) .get() .then((doc) => { if (!doc.exists && files.length > 0) { // GCS Prefix should have a corresponding Document in Firestore. onInconsistency( `The Prefix Document(${doc.ref.path}) for ${path} is missing in Firestore even though the Prefix exists in GCS.` ); } }); await addToPromiseQueue( promises, prefixDocExistsPromise, constants.maxConcurrentRequests ); state.storageNumFiles += files.length; state.storagePrefixesRemaining = prefixes.length; // Check Files for consistency. for (let i = 0; i < files.length; i++) { const file = files[i]; const firestorePath = objectNameToFirestorePath( constants, config.bucket, file.name ); const itemDocExistsPromise = firestore .doc(firestorePath) .get() .then((snapshot) => { state.storageNumFilesChecked += 1; // Check the corresponding Firestore Document for consistency. const err = validateDocument(constants, snapshot, file); if (err) { onInconsistency(err); } }); await addToPromiseQueue( promises, itemDocExistsPromise, constants.maxConcurrentRequests ); } } } // Remaining requests need to finish before exiting. await promises.onEmpty(); }; /** * Check the given Firestore Document Snapshot against it's corresponding GCS Object for consistency. * @param constants The Consistency Check Constants. * @param snapshot Firestore Document Snapshot. * @param file File data corresponding to the GCS Object. */ const validateDocument = ( constants: CheckConstants, snapshot: FirebaseFirestore.DocumentSnapshot, file: File ): string | null => { if (!snapshot.exists) { // Item Document should exist for each GCS Object. return `The Item Document(${snapshot.ref.path}) for ${file.name} is missing in Firestore even though it exists in GCS.`; } else if ( snapshot.data()![constants.metadataField].size !== Number(file.metadata.size) ) { // Item Document should have correct size if the file was overwritten. return `The Item Document(${snapshot.ref.path}) for ${file.name} is stale in Firestore. It contains the incorrect size.`; } else if ( !lodash.isEqual( snapshot.data()![constants.metadataField][constants.customMetadata], file.metadata.metadata ) ) { // Item Document should have the correct custom metadata. return `The Item Document(${snapshot.ref.path}) for ${file.name} is stale in Firestore. It contains out-of-date custom metadata.`; } // No inconsistencies were found. return null; }; interface CleanConfig { bucket: string; project: string; prefix: string; logFile: string; cleanFirestore: boolean; cleanGcs: boolean; } interface CleanState { spinner: ora.Ora; logger: winston.Logger; firestoreNumItems: number; firestoreNumItemsDeleted: number; firestorePrefixesRemaining: number; storageNumItems: number; storageNumItemsDeleted: number; } interface CleanConstants { items: string; prefixes: string; root: string; metadataField: string; maxConcurrentRequests: number; } const cleanCmd = new commander.Command("clean") .allowUnknownOption(false) .description("clean up stress test from gcs and firestore") .requiredOption("-b, --bucket <bucket>", "bucket that was used when writing") .option("-p, --prefix <prefix>", "prefix that was used when writing", "") .option("--no-firestore", "skip firestore clean up") .option("--no-gcs", "skip gcs clean up") .option("-l, --log-file <filename>", "file to store all logs", "clean.log") .option("--project <project_id>", "project to run this stress test on") .action(async (cmd: commander.Command) => { const constants: CleanConstants = { items: "items", prefixes: "prefixes", root: "gcs-mirror", metadataField: "gcsMetadata", maxConcurrentRequests: 5000, }; const config: CleanConfig = { bucket: cmd.bucket, project: cmd.project, prefix: cmd.prefix, logFile: cmd.logFile, cleanFirestore: cmd.firestore ? true : false, cleanGcs: cmd.gcs ? true : false, }; if (!cmd.bucket) throw new Error("Bucket must be specified."); const state: CleanState = { spinner: ora(), logger: createLogger(config.logFile), firestoreNumItems: 0, firestoreNumItemsDeleted: 0, firestorePrefixesRemaining: 0, storageNumItems: 0, storageNumItemsDeleted: 0, }; config.prefix = prunePrefix(config.prefix); admin.initializeApp({ credential: admin.credential.applicationDefault(), projectId: config.project, }); // Setup finished, can start cleaning up. state.logger.info("Starting clean-up with configuration:"); state.logger.info(JSON.stringify(config)); state.logger.info(`Logging to ${config.logFile}.`); state.spinner.start(); setInterval(() => { updateCleanSpinner(state); }, 1000); const cleanUpTasks: Promise<any>[] = []; // Clean up GCS. if (config.cleanGcs) { cleanUpTasks.push(cleanStorage(constants, config, state)); } // Clean up Firestore. if (config.cleanFirestore) { cleanUpTasks.push(cleanFirestore(constants, config, state)); } await Promise.all(cleanUpTasks); state.logger.info("Finished clean up!"); state.logger.info( `Deleted ${state.firestoreNumItemsDeleted} Documents from Firestore.` ); state.logger.info( `Deleted ${state.storageNumItemsDeleted} Objects from GCS.` ); process.exit(0); }); const updateCleanSpinner = (state: CleanState) => { state.spinner.text = `Cleaning up Firestore: ${state.firestoreNumItemsDeleted}/${state.firestoreNumItems} Documents deleted. Prefixes Remaining: ${state.firestorePrefixesRemaining}\n`; state.spinner.text += `Cleaning up GCS: ${state.storageNumItemsDeleted}/${state.storageNumItems} items deleted.\n`; }; /** * Remove the GCS Objects generated by the Stress Test. * @param constants The Clean Up Constants. * @param config The Clean Up Config. * @param state The Clean Up State. */ const cleanStorage = async ( constants: CleanConstants, config: CleanConfig, state: CleanState ) => { const bucket = admin.storage().bucket(config.bucket); const promises = new PromiseQueue(); // Paginate GCS query to preserve memory. Keep querying this Prefix until a `pageToken` is not returned. let pageToken = ""; while (pageToken != null) { const [files, _, response] = await bucket.getFiles({ autoPaginate: false, prefix: config.prefix, pageToken, }); pageToken = response.nextPageToken || null; state.storageNumItems += files.length; // Delete Files from GCS. for (let i = 0; i < files.length; i++) { const file = files[i]; const deleteFilePromise = file .delete() .then(() => { state.storageNumItemsDeleted += 1; }) .catch((err) => state.logger.error("Error deleting Object from GCS", err) ); await addToPromiseQueue( promises, deleteFilePromise, constants.maxConcurrentRequests ); } } await promises.onEmpty(); }; /** * Remove the Firestore Documents generated by the Stress Test. * @param constants The Clean Up Constants. * @param config The Clean Up Config. * @param state The Clean Up State. */ const cleanFirestore = async ( constants: CleanConstants, config: CleanConfig, state: CleanState ) => { const firestore = admin.firestore(); // Construct the Root Prefix Document path. let rootPrefix = `${constants.root}/${config.bucket}`; if (config.prefix.length > 0) { const parts = config.prefix.split("/"); parts.forEach((part) => { rootPrefix += `/${constants.prefixes}/${part}`; }); } const prefixes = [rootPrefix]; try { // Depth-first traversal through Firestore, adding newly discovered Prefixes onto the stack. const promises = new PromiseQueue(); while (prefixes.length > 0) { const currPrefix = prefixes.pop() as string; // Paginate requests to Firestore to preserve memory. const prefixesPromise = new Promise(async (resolve, reject) => { const prefixesSnapshot = await firestore .collection(`${currPrefix}/${constants.prefixes}`) .get(); const prefixDocs = prefixesSnapshot.docs; // Add the newly discovered Prefixes to the stack. prefixDocs.forEach((doc) => { prefixes.push(doc.ref.path); }); resolve(); }); const itemsPromise = new Promise(async (resolve, reject) => { let length = 0; let itemsSnapshot = null; while (itemsSnapshot == null || itemsSnapshot.docs.length > 0) { itemsSnapshot = await firestore .collection(`${currPrefix}/${constants.items}`) .orderBy(`${constants.metadataField}.name`) .startAfter( itemsSnapshot ? itemsSnapshot.docs[itemsSnapshot.docs.length - 1] : null ) .limit(1000) .get(); const itemDocs = itemsSnapshot.docs; length += itemDocs.length; // Delete the Item Documents. for (let i = 0; i < itemDocs.length; i++) { const doc = itemDocs[i]; const deleteItemDocPromise = doc.ref .delete() .then(() => (state.firestoreNumItemsDeleted += 1)); await addToPromiseQueue( promises, deleteItemDocPromise, constants.maxConcurrentRequests ); } } resolve(length); }); const [_, itemsDocsLength] = (await Promise.all([ prefixesPromise, itemsPromise, ])) as [void, number]; state.firestorePrefixesRemaining = prefixes.length; state.firestoreNumItems += itemsDocsLength; // Delete the Prefix Document. const currPrefixSnapshot = firestore.doc(currPrefix); const deletePrefixDocPromise = currPrefixSnapshot.delete(); await addToPromiseQueue( promises, deletePrefixDocPromise, constants.maxConcurrentRequests ); } } catch (e) { state.logger.error("Error cleaning up Firestore:", e); } }; const rootCmd = new commander.Command("driver") .addCommand(writeCmd) .addCommand(checkCmd) .addCommand(backfillCmd) .addCommand(cleanCmd); rootCmd.parseAsync(process.argv).catch((e) => { console.error(e); process.exit(1); });
the_stack
import {assert, assertNotReached} from '../../assert.js'; import {AsyncJobQueue} from '../../async_job_queue.js'; import * as Comlink from '../../lib/comlink.js'; import runFFmpeg from '../../lib/ffmpeg.js'; import {WaitableEvent} from '../../waitable_event.js'; import {AsyncWriter} from '../async_writer.js'; import {VideoProcessor} from '../video_processor_interface.js'; import {VideoProcessorArgs} from './video_processor_args.js'; /** * A file stream in Emscripten. */ interface FileStream { position: number; } /** * The set of callbacks for an emulated device in Emscripten. ref: * https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.registerDevice */ interface FileOps { open(stream: FileStream): void; close(stream: FileStream): void; read( stream: FileStream, buffer: Int8Array, offset: number, length: number, position: number): number; write( stream: FileStream, buffer: Int8Array, offset: number, length: number, position?: number): number; llseek(stream: FileStream, offset: number, whence: number): number; } type ReadableCallback = (deviceReadable: number) => void; /** * An emulated input device backed by Int8Array. */ class InputDevice { /** * The data to be read from the device. */ private readonly data: Int8Array[] = []; /** * Whether the writing is canceled. */ private isCanceled = false; /** * Whether the writing is ended. If true, no more data would be pushed. */ private ended = false; /** * The callback to be triggered when the device is ready to read(). The * callback would be called only once and reset to null afterward. It should * be called with 1 if the device is readable or 0 if it is canceled. */ private readableCallback: ReadableCallback|null = null; /** * Returns 1 if the device is readable or 0 if it is canceled. */ private isDeviceReadable(): number { return this.isCanceled ? 0 : 1; } /** * Notifies and resets the readable callback, if any. */ consumeReadableCallback(): void { if (this.readableCallback === null) { return; } const callback = this.readableCallback; this.readableCallback = null; callback(this.isDeviceReadable()); } /** * Pushes a chunk of data into the device. */ push(data: Int8Array): void { assert(!this.ended); this.data.push(data); this.consumeReadableCallback(); } /** * Closes the writing pipe. */ endPush(): void { this.ended = true; this.consumeReadableCallback(); } /** * Implements the read() operation for the emulated device. * @param buffer The destination buffer. * @param offset The destination buffer offset. * @param length The maximum length to read. * @param position The position to read from stream. * @return The numbers of bytes read. */ read( stream: FileStream, buffer: Int8Array, offset: number, length: number, position: number): number { assert(position === stream.position, 'stdin is not seekable'); if (this.data.length === 0) { assert(this.ended); return 0; } let bytesRead = 0; while (this.data.length > 0 && length > 0) { const data = this.data[0]; const len = Math.min(data.length, length); buffer.set(data.subarray(0, len), offset); if (len === data.length) { this.data.shift(); } else { this.data[0] = data.subarray(len); } offset += len; length -= len; bytesRead += len; } return bytesRead; } getFileOps(): FileOps { return { open: () => { // Do nothing. }, close: () => { // Do nothing. }, read: (...args) => this.read(...args), write: () => assertNotReached('write should not be called on stdin'), llseek: () => assertNotReached('llseek should not be called on stdin'), }; } /** * Sets the readable callback. The callback would be called immediately if * the device is in a readable state. */ setReadableCallback(callback: ReadableCallback) { if (this.data.length > 0 || this.ended) { callback(this.isDeviceReadable()); return; } assert(this.readableCallback === null); this.readableCallback = callback; } /** * Marks the input device as canceled so that ffmpeg can handle it properly. */ cancel() { this.isCanceled = true; this.endPush(); } } /** * An emulated output device. */ class OutputDevice { private readonly closed = new WaitableEvent(); /** * @param output Where should the device write to. */ constructor(private readonly output: AsyncWriter) {} /** * Implements the write() operation for the emulated device. * @param buffer The source buffer. * @param offset The source buffer offset. * @param length The maximum length to be write. * @param position The position to write in stream. * @return The numbers of bytes written. */ write( stream: FileStream, buffer: Int8Array, offset: number, length: number, position?: number): number { assert(!this.closed.isSignaled()); const blob = new Blob([buffer.subarray(offset, offset + length)]); assert( position === undefined || position === stream.position, 'combined seek-and-write operation is not supported'); this.output.write(blob); return length; } /** * Implements the llseek() operation for the emulated device. * Only SEEK_SET (0) is supported as |whence|. Reference: * https://emscripten.org/docs/api_reference/Filesystem-API.html#FS.llseek * @param offset The offset in bytes relative to |whence|. * @param whence The reference position to be used. * @return The resulting file position. */ llseek(stream: FileStream, offset: number, whence: number): number { assert(whence === 0, 'only SEEK_SET is supported'); assert(this.output.seekable()); if (stream.position !== offset) { this.output.seek(offset); } return offset; } /** * Implements the close() operation for the emulated device. */ close(): void { this.closed.signal(); } /** * @return Resolved when the device is closed. */ async waitClosed(): Promise<void> { await this.closed.wait(); } getFileOps(): FileOps { return { open: () => { // Do nothing. }, close: () => this.close(), read: () => assertNotReached('read should not be called on output'), write: (...args) => this.write(...args), llseek: (...args) => this.llseek(...args), }; } } /** * A ffmpeg-based video processor that can process input and output data * incrementally. */ class FFMpegVideoProcessor implements VideoProcessor { private readonly inputDevice = new InputDevice(); private readonly outputDevice: OutputDevice; private readonly jobQueue = new AsyncJobQueue(); /** * @param output The output writer. */ constructor( private readonly output: AsyncWriter, processorArgs: VideoProcessorArgs) { this.outputDevice = new OutputDevice(output); const outputFile = `/output.${processorArgs.outputExtension}`; const args = [ // Make the procssing pipeline start earlier by shorten the initial // analyze durtaion from the default 5s to 1s. This reduce the // stop-capture lantency significantly for short videos. '-analyzeduration', '1M', // input from stdin ...processorArgs.decoderArgs, '-i', 'pipe:0', // arguments for output format encoder ...processorArgs.encoderArgs, // show error log only '-hide_banner', '-loglevel', 'error', // do not ask anything '-nostdin', '-y', // output to file outputFile // eslint-disable-line comma-dangle ]; const config = { arguments: args, locateFile: (file) => { assert(file === 'ffmpeg.wasm'); return '/js/lib/ffmpeg.wasm'; }, noFSInit: true, // It would be setup in preRun(). preRun: () => { const fs = config['FS']; assert(fs !== null); // 80 is just a random major number that won't collide with other // default devices of the Emscripten runtime environment, which uses // major numbers 1, 3, 5, 6, 64, and 65. Ref: // https://github.com/emscripten-core/emscripten/blob/1ed6dd5cfb88d927ec03ecac8756f0273810d5c9/src/library_fs.js#L1331 const input = fs.makedev(80, 0); fs.registerDevice(input, this.inputDevice.getFileOps()); fs.mkdev('/dev/stdin', input); const output = fs.makedev(80, 1); fs.registerDevice(output, this.outputDevice.getFileOps()); fs.mkdev(outputFile, output); fs.symlink('/dev/tty1', '/dev/stdout'); fs.symlink('/dev/tty1', '/dev/stderr'); const stdin = fs.open('/dev/stdin', 'r'); const stdout = fs.open('/dev/stdout', 'w'); const stderr = fs.open('/dev/stderr', 'w'); assert(stdin.fd === 0); assert(stdout.fd === 1); assert(stderr.fd === 2); }, }; const initFFmpeg = () => { return new Promise<void>((resolve) => { // runFFmpeg() is a special function exposed by Emscripten that will // return an object with then(). The function passed into then() would // be called when the runtime is initialized. Note that because the // then() function will return the object itself again, using await here // would cause an infinite loop. runFFmpeg(config).then(() => resolve()); }); }; this.jobQueue.push(initFFmpeg); // This is a function to be called by ffmpeg before running read() in C. globalThis.waitReadable = (callback) => { this.inputDevice.setReadableCallback(callback); }; } /** * Writes a blob with mkv data into the processor. */ async write(blob: Blob): Promise<void> { this.jobQueue.push(async () => { const buf = await blob.arrayBuffer(); this.inputDevice.push(new Int8Array(buf)); }); } /** * Closes the writer. No more write operations are allowed. * @return Resolved when all write operations are finished. */ async close(): Promise<void> { // Flush and close the input device. this.jobQueue.push(async () => { this.inputDevice.endPush(); }); await this.jobQueue.flush(); // Wait until the output device is closed. await this.outputDevice.waitClosed(); // Flush and close the output writer. await this.output.close(); } /** * Cancels all the remaining tasks and notifies ffmpeg that the writing is * canceled. */ async cancel(): Promise<void> { // Clear and make sure there is no pending task. this.jobQueue.clear(); await this.jobQueue.flush(); this.inputDevice.cancel(); this.outputDevice.close(); } } /** * Expose the VideoProcessor constructor to given end point. */ function exposeVideoProcessor(endPoint: MessagePort) { Comlink.expose(FFMpegVideoProcessor, endPoint); } Comlink.expose({exposeVideoProcessor});
the_stack
import fetch from "isomorphic-unfetch"; import Utils from "web3-utils"; import { createApolloFetch } from "apollo-fetch"; import { applyMiddleware } from "graphql-middleware"; import graphqlFields from "graphql-fields"; import { makeExecutableSchema } from "@graphql-tools/schema"; import { stitchSchemas, ValidationLevel } from "@graphql-tools/stitch"; import { delegateToSchema } from "@graphql-tools/delegate"; import { introspectSchema, wrapSchema } from "@graphql-tools/wrap"; import { getBlockByNumber, getEstimatedBlockCountdown, mergeObjectsInUnique, } from "../lib/utils"; import { print } from "graphql"; import GraphQLJSON, { GraphQLJSONObject } from "graphql-type-json"; import typeDefs from "./types"; import resolvers from "./resolvers"; import { PRICING_TOOL_API } from "../lib/constants"; const schema = makeExecutableSchema({ typeDefs, resolvers: { ...resolvers, JSON: GraphQLJSON, JSONObject: GraphQLJSONObject, }, }); const createSchema = async () => { const executor = async ({ document, variables }) => { const query = print(document); const fetchResult = await fetch(process.env.NEXT_PUBLIC_SUBGRAPH, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query, variables }), }); return fetchResult.json(); }; const subgraphSchema = wrapSchema({ schema: await introspectSchema(executor), executor, }); const linkTypeDefs = ` extend type Transcoder { threeBoxSpace: ThreeBoxSpace price: Float scores: PerformanceLog successRates: PerformanceLog roundTripScores: PerformanceLog } type PerformanceLog { global: Float fra: Float mdw: Float sin: Float nyc: Float lax: Float lon: Float prg: Float } extend type ThreeBoxSpace { transcoder: Transcoder } extend type Protocol { totalStake(block: String): String } extend type Delegator { pendingStake: String pendingFees: String } extend type Poll { isActive: Boolean status: String totalVoteStake: String totalNonVoteStake: String estimatedTimeRemaining: Int endTime: Int } extend type Query { txs: [JSON] } `; async function getTotalStake(_ctx, _blockNumber) { const Web3 = require("web3"); const web3 = new Web3( process.env.NEXT_PUBLIC_NETWORK === "rinkeby" ? process.env.NEXT_PUBLIC_RPC_URL_4 : process.env.NEXT_PUBLIC_RPC_URL_1 ); const contract = new web3.eth.Contract( _ctx.livepeer.config.contracts.LivepeerToken.abi, _ctx.livepeer.config.contracts.LivepeerToken.address ); return await contract.methods .balanceOf( _blockNumber < 10686186 ? "0x8573f2f5a3bd960eee3d998473e50c75cdbe6828" : _ctx.livepeer.config.contracts.Minter.address ) .call({}, _blockNumber ? _blockNumber : null); } const gatewaySchema = stitchSchemas({ subschemas: [ { schema: subgraphSchema, batch: true }, { schema: schema, batch: true }, ], typeDefs: linkTypeDefs, typeMergingOptions: { validationScopes: { // TOD: rename transaction query type to avoid naming conflict with subgraph "Query.transaction": { validationLevel: ValidationLevel.Off, }, }, }, resolvers: { Transcoder: { threeBoxSpace: { async resolve(_transcoder, _args, _ctx, _info) { const threeBoxSpace = await delegateToSchema({ schema: schema, operation: "query", fieldName: "threeBoxSpace", args: { id: _transcoder.id, }, context: _ctx, info: _info, }); return threeBoxSpace; }, }, }, Delegator: { pendingStake: { async resolve(_delegator, _args, _ctx, _info) { const apolloFetch = createApolloFetch({ uri: process.env.NEXT_PUBLIC_SUBGRAPH, }); const { data } = await apolloFetch({ query: `{ protocol(id: "0") { id currentRound { id } } }`, }); return await _ctx.livepeer.rpc.getPendingStake( _delegator.id.toString(), data.protocol.currentRound.id.toString() ); }, }, pendingFees: { async resolve(_delegator, _args, _ctx, _info) { const apolloFetch = createApolloFetch({ uri: process.env.NEXT_PUBLIC_SUBGRAPH, }); const { data } = await apolloFetch({ query: `{ protocol(id: "0") { id currentRound { id } } }`, }); const pendingFees = await _ctx.livepeer.rpc.getPendingFees( _delegator.id, data.protocol.currentRound.id ); return Utils.fromWei(pendingFees); }, }, }, Protocol: { totalStake: { async resolve(_protocol, _args, _ctx, _info) { return await getTotalStake(_ctx, _args.blockNumber); }, }, }, Poll: { totalVoteStake: { async resolve(_poll, _args, _ctx, _info) { return +_poll?.tally?.no + +_poll?.tally?.yes; }, }, totalNonVoteStake: { async resolve(_poll, _args, _ctx, _info) { const { number: blockNumber } = await _ctx.livepeer.rpc.getBlock( "latest" ); const isActive = blockNumber <= parseInt(_poll.endBlock); const totalStake = await getTotalStake( _ctx, isActive ? blockNumber : _poll.endBlock ); const totalVoteStake = +_poll?.tally?.no + +_poll?.tally?.yes; return +Utils.fromWei(totalStake) - totalVoteStake; }, }, status: { async resolve(_poll, _args, _ctx, _info) { const { number: blockNumber } = await _ctx.livepeer.rpc.getBlock( "latest" ); const isActive = blockNumber <= parseInt(_poll.endBlock); const totalStake = await getTotalStake( _ctx, isActive ? blockNumber : _poll.endBlock ); const noVoteStake = +_poll?.tally?.no || 0; const yesVoteStake = +_poll?.tally?.yes || 0; const totalVoteStake = noVoteStake + yesVoteStake; const totalSupport = isNaN(yesVoteStake / totalVoteStake) ? 0 : (yesVoteStake / totalVoteStake) * 100; const totalParticipation = (totalVoteStake / +Utils.fromWei(totalStake)) * 100; if (isActive) { return "active"; } else if (totalParticipation > _poll.quorum / 10000) { if (totalSupport > _poll.quota / 10000) { return "passed"; } else { return "rejected"; } } else { return "Quorum not met"; } }, }, isActive: { async resolve(_poll, _args, _ctx, _info) { const { number: blockNumber } = await _ctx.livepeer.rpc.getBlock( "latest" ); return blockNumber <= parseInt(_poll.endBlock); }, }, estimatedTimeRemaining: { async resolve(_poll, _args, _ctx, _info) { const { number: blockNumber } = await _ctx.livepeer.rpc.getBlock( "latest" ); if (blockNumber > parseInt(_poll.endBlock)) { return null; } const countdownData = await getEstimatedBlockCountdown( _poll.endBlock ); return parseInt(countdownData.EstimateTimeInSec); }, }, endTime: { async resolve(_poll, _args, _ctx, _info) { const { number: blockNumber } = await _ctx.livepeer.rpc.getBlock( "latest" ); if (blockNumber < parseInt(_poll.endBlock)) { return null; } const endBlockData = await getBlockByNumber(_poll.endBlock); return endBlockData.timeStamp; }, }, }, }, }); // intercept and transform query responses with price and performance data const queryMiddleware = { Query: { delegator: async (resolve, parent, args, ctx, info) => { const delegator = await resolve(parent, args, ctx, info); const selectionSet = Object.keys(graphqlFields(info)); // if selection set does not include 'delegate', return delegator as is, otherwise fetch and merge price if (!delegator || !selectionSet.includes("delegate")) { return delegator; } const response = await fetch(PRICING_TOOL_API); const transcodersWithPrice = await response.json(); const transcoderWithPrice = transcodersWithPrice.filter( (t) => t.Address.toLowerCase() === delegator?.delegate?.id.toLowerCase() )[0]; if (delegator?.delegate) { delegator.delegate.price = transcoderWithPrice?.PricePerPixel ? transcoderWithPrice?.PricePerPixel : 0; } return delegator; }, transcoder: async (resolve, parent, args, ctx, info) => { const transcoder = await resolve(parent, args, ctx, info); const selectionSet = Object.keys(graphqlFields(info)); // if selection set does not include 'price', return transcoder as is, otherwise fetch and merge price if (!transcoder || !selectionSet.includes("price")) { return transcoder; } const response = await fetch(PRICING_TOOL_API); const transcodersWithPrice = await response.json(); const transcoderWithPrice = transcodersWithPrice.filter( (t) => t.Address.toLowerCase() === args.id.toLowerCase() )[0]; transcoder["price"] = transcoderWithPrice?.PricePerPixel ? transcoderWithPrice?.PricePerPixel : 0; return transcoder; }, transcoders: async (resolve, parent, args, ctx, info) => { const selectionSet = Object.keys(graphqlFields(info)); const transcoders = await resolve(parent, args, ctx, info); const prices = []; const performanceMetrics = []; //if selection set includes 'price', return transcoders merge prices and performance metrics if (selectionSet.includes("price")) { // get price data const response = await fetch(PRICING_TOOL_API); const transcodersWithPrice = await response.json(); for (const t of transcodersWithPrice) { if (transcoders.filter((a) => a.id === t.Address).length > 0) { prices.push({ id: t.Address, price: t.PricePerPixel, }); } } } function avg(obj, key) { const arr = Object.values(obj); const sum = (prev, cur) => ({ [key]: prev[key] + cur[key] }); return arr.reduce(sum)[key] / arr.length; } if (selectionSet.includes("scores")) { const metricsResponse = await fetch( `https://leaderboard-serverless.vercel.app/api/aggregated_stats?since=${ctx.since}` ); const metrics = await metricsResponse.json(); for (const key in metrics) { if (transcoders.filter((a) => a.id === key).length > 0) { performanceMetrics.push({ id: key, scores: { global: avg(metrics[key], "score") * 10000, fra: (metrics[key].FRA?.score || 0) * 10000, mdw: (metrics[key].MDW?.score || 0) * 10000, sin: (metrics[key].SIN?.score || 0) * 10000, nyc: (metrics[key].NYC?.score || 0) * 10000, lax: (metrics[key].LAX?.score || 0) * 10000, lon: (metrics[key].LON?.score || 0) * 10000, prg: (metrics[key].PRG?.score || 0) * 10000, }, successRates: { global: avg(metrics[key], "success_rate") * 100, fra: (metrics[key].FRA?.success_rate || 0) * 100, mdw: (metrics[key].MDW?.success_rate || 0) * 100, sin: (metrics[key].SIN?.success_rate || 0) * 100, nyc: (metrics[key].NYC?.success_rate || 0) * 100, lax: (metrics[key].LAX?.success_rate || 0) * 100, lon: (metrics[key].LON?.success_rate || 0) * 100, prg: (metrics[key].PRG?.success_rate || 0) * 100, }, roundTripScores: { global: avg(metrics[key], "round_trip_score") * 10000, fra: (metrics[key].FRA?.round_trip_score || 0) * 10000, mdw: (metrics[key].MDW?.round_trip_score || 0) * 10000, sin: (metrics[key].SIN?.round_trip_score || 0) * 10000, nyc: (metrics[key].NYC?.round_trip_score || 0) * 10000, lax: (metrics[key].LAX?.round_trip_score || 0) * 10000, lon: (metrics[key].LON?.round_trip_score || 0) * 10000, prg: (metrics[key].PRG?.round_trip_score || 0) * 10000, }, }); } } } // merge results return mergeObjectsInUnique( [...transcoders, ...prices, ...performanceMetrics], "id" ); }, }, }; return applyMiddleware(gatewaySchema, queryMiddleware); }; export default createSchema;
the_stack
import waitUntil from "wait-until-promise"; import { Directory, FileType, File, Problem, Project } from "../../src/models"; import { Service } from "../../src/service"; function getDirectoryStructure() { const a = new Directory("test"); const b = a.newFile("b", FileType.JavaScript, false); const c = a.newDirectory("c"); const cd = a.newFile("c/d", FileType.JavaScript, false); return { a, b, c, cd }; } declare var monaco: { editor, languages }; describe("File tests", () => { beforeAll(() => { // TODO: This is needed because of ugly hack in File.save (global as any).app = { state: { fiddle: "testFiddleName" }, forkIfNeeded: () => Promise.resolve(true) }; (global as any).fetch = jest.fn().mockImplementation(() => Promise.resolve({ ok: true, json: async () => { return {}; } })); (global as any).Headers = jest.fn().mockImplementation((arg) => arg); }); describe("constructor", () => { it("should be constructable", () => { const createModel = jest.spyOn(monaco.editor, "createModel"); const file = new File("file", FileType.JavaScript); expect(file.name).toEqual("file"); expect(file.type).toEqual(FileType.JavaScript); expect(file.data).toBeNull(); expect(file.isDirty).toEqual(false); expect(file.isBufferReadOnly).toEqual(false); expect(file.isTransient).toEqual(false); expect(file.bufferType).toEqual(FileType.JavaScript); expect(file.parent).toBeNull(); expect(createModel).toHaveBeenCalledWith(null, "javascript"); createModel.mockRestore(); }); it("should be constructable (Binary FileType)", () => { const createModel = jest.spyOn(monaco.editor, "createModel"); const file = new File("file", FileType.Wasm); expect(file.bufferType).toEqual(FileType.Unknown); expect(createModel).toHaveBeenCalledWith(""); createModel.mockRestore(); }); it("should call updateOptions on the created model", () => { const updateOptions = jest.spyOn(monaco.editor, "updateOptions"); const file = new File("file", FileType.JavaScript); expect(updateOptions).toHaveBeenCalledWith({ tabSize: 2, insertSpaces: true }); updateOptions.mockRestore(); }); it("should listen for onDidChangeContent events on the created model", () => { const onDidChangeContent = jest.spyOn(monaco.editor, "onDidChangeContent"); const setModelMarkers = jest.spyOn(monaco.editor, "setModelMarkers"); const onChangeBuffer = jest.fn(); const onDirtyChange = jest.fn(); const file = new File("file", FileType.JavaScript); const listener = onDidChangeContent.mock.calls[0][0]; file.onDidChangeDirty.register(onDirtyChange); file.onDidChangeBuffer.register(onChangeBuffer); listener({}); expect(onChangeBuffer).toHaveBeenCalled(); expect(onDirtyChange).toHaveBeenCalled(); expect(file.isDirty).toEqual(true); expect(setModelMarkers).toHaveBeenCalledWith(file.buffer, "compiler", []); onDidChangeContent.mockRestore(); setModelMarkers.mockRestore(); }); it("should handle flush flags when receiving onDidChangeContent events", () => { const onDidChangeContent = jest.spyOn(monaco.editor, "onDidChangeContent"); const setModelMarkers = jest.spyOn(monaco.editor, "setModelMarkers"); const callback = jest.fn(); const file = new File("file", FileType.JavaScript); const listener = onDidChangeContent.mock.calls[0][0]; file.onDidChangeBuffer.register(callback); listener({ isFlush: true }); expect(callback).not.toHaveBeenCalled(); expect(setModelMarkers).not.toHaveBeenCalled(); onDidChangeContent.mockRestore(); setModelMarkers.mockRestore(); }); it("should not dispatch onDidChangeDirty if file is already dirty", () => { const onDidChangeContent = jest.spyOn(monaco.editor, "onDidChangeContent"); const callback = jest.fn(); const file = new File("file", FileType.JavaScript); const listener = onDidChangeContent.mock.calls[0][0]; file.onDidChangeDirty.register(callback); file.isDirty = true; listener({}); expect(callback).not.toHaveBeenCalled(); expect(file.isDirty).toEqual(true); onDidChangeContent.mockRestore(); }); }); describe("setNameAndDescription", () => { it("should set the file's name and description", () => { const file = new File("file", FileType.JavaScript); const newName = "newName"; const newDescription = "newDescription"; file.setNameAndDescription(newName, newDescription); expect(file.name).toEqual(newName); expect(file.description).toEqual(newDescription); }); it("should dispatch an onDidChangeChildren event", () => { const parent = new Directory("parent"); const file = parent.newFile("file", FileType.JavaScript); const callback = jest.fn(); parent.onDidChangeChildren.register(callback); file.setNameAndDescription("newName", "newDescription"); expect(callback).toHaveBeenCalled(); }); }); describe("notifyDidChangeBuffer", () => { it("should dispatch an onDidChangeBuffer event", () => { const { a, b, c, cd } = getDirectoryStructure(); const callbackA = jest.fn(); const callbackB = jest.fn(); const callbackC = jest.fn(); a.onDidChangeBuffer.register(callbackA); c.onDidChangeBuffer.register(callbackB); cd.onDidChangeBuffer.register(callbackC); cd.notifyDidChangeBuffer(); expect(callbackA).toHaveBeenCalled(); expect(callbackB).toHaveBeenCalled(); expect(callbackC).toHaveBeenCalled(); }); }); describe("notifyDidChangeData", () => { it("should dispatch an onDidChangeData event", () => { const { a, b, c, cd } = getDirectoryStructure(); const callbackA = jest.fn(); const callbackB = jest.fn(); const callbackC = jest.fn(); a.onDidChangeData.register(callbackA); c.onDidChangeData.register(callbackB); cd.onDidChangeData.register(callbackC); cd.notifyDidChangeData(); expect(callbackA).toHaveBeenCalled(); expect(callbackB).toHaveBeenCalled(); expect(callbackC).toHaveBeenCalled(); }); }); describe("notifyDidChangeDirty", () => { it("it should dispatch an onDidChangeDirty event", () => { const { a, b, c, cd } = getDirectoryStructure(); const callbackA = jest.fn(); const callbackB = jest.fn(); const callbackC = jest.fn(); a.onDidChangeDirty.register(callbackA); c.onDidChangeDirty.register(callbackB); cd.onDidChangeDirty.register(callbackC); cd.notifyDidChangeDirty(); expect(callbackA).toHaveBeenCalled(); expect(callbackB).toHaveBeenCalled(); expect(callbackC).toHaveBeenCalled(); }); }); describe("setProblems", () => { it("should set the file's problems to the provided array of problems", () => { const { cd } = getDirectoryStructure(); const problems = [new Problem(cd, "", "info")]; cd.setProblems(problems); expect(cd.problems).toBe(problems); }); it("should dispatch an onDidChangeProblems event", () => { const { a, c, cd } = getDirectoryStructure(); const problems = [new Problem(cd, "", "info")]; const callbackA = jest.fn(); const callbackB = jest.fn(); const callbackC = jest.fn(); a.onDidChangeProblems.register(callbackA); c.onDidChangeProblems.register(callbackB); cd.onDidChangeProblems.register(callbackC); cd.setProblems(problems); expect(callbackA).toHaveBeenCalled(); expect(callbackB).toHaveBeenCalled(); expect(callbackC).toHaveBeenCalled(); }); }); describe("getEmitOutput", () => { it("should compile TypeScript files to JavaScript", async () => { const file = new File("file", FileType.TypeScript); const client = { getEmitOutput: jest.fn() }; const worker = jest.fn().mockImplementation(() => Promise.resolve(client)); const getTypeScriptWorker = jest.spyOn(monaco.languages.typescript, "getTypeScriptWorker"); getTypeScriptWorker.mockImplementation(() => Promise.resolve(worker)); const output = await file.getEmitOutput(); expect(getTypeScriptWorker).toHaveBeenCalled(); expect(worker).toHaveBeenCalled(); expect(client.getEmitOutput).toHaveBeenCalledWith("uri"); }); it("should resolve with empty string for non TypeScript files", async () => { const file = new File("file", FileType.JavaScript); const output = await file.getEmitOutput(); expect(output).toEqual(""); }); }); describe("setData", () => { it("should set the file's data to the provided data", () => { const file = new File("file", FileType.JavaScript); const data = "test"; file.setData(data); expect(file.data).toEqual(data); }); it("should dispatch an onDidChangeData event", () => { const file = new File("file", FileType.JavaScript); const callback = jest.fn(); file.onDidChangeData.register(callback); file.setData("test"); expect(callback).toHaveBeenCalled(); }); it("should assert that the provided data is not null", () => { const file = new File("file", FileType.JavaScript); expect(() => file.setData(null)).toThrowError(); }); describe("updateBuffer", () => { it("should reset dirty files and dispatch an onDidChangeDirty event", () => { const callback = jest.fn(); const file = new File("file", FileType.JavaScript); const data = "test"; file.isDirty = true; file.onDidChangeDirty.register(callback); file.setData(data); expect(file.isDirty).toEqual(false); expect(callback).toHaveBeenCalled(); }); it("should only dispatch an onDidChangeDirty event if the file is dirty", () => { const callback = jest.fn(); const file = new File("file", FileType.JavaScript); const data = "test"; file.onDidChangeDirty.register(callback); file.setData(data); expect(file.isDirty).toEqual(false); expect(callback).not.toHaveBeenCalled(); }); it("should set the buffer value", () => { const setValue = jest.spyOn(monaco.editor, "setValue"); const file = new File("file", FileType.JavaScript); const data = "test"; file.setData(data); expect(setValue).toHaveBeenCalledWith(data); setValue.mockRestore(); }); it("should dispatch an onDidChangeBuffer event", () => { const callback = jest.fn(); const file = new File("file", FileType.JavaScript); const data = "test"; file.onDidChangeBuffer.register(callback); file.setData(data); expect(callback).toHaveBeenCalled(); }); it("should handle updates for files of type FileType.Wasm", async () => { const setValue = jest.spyOn(monaco.editor, "setValue"); const setModelLanguage = jest.spyOn(monaco.editor, "setModelLanguage"); const disassembleWasm = jest.spyOn(Service, "disassembleWasm"); disassembleWasm.mockImplementation((data) => Promise.resolve(data)); const file = new File("file", FileType.Wasm); const data = "test"; file.setData(data, "status" as any); await waitUntil(() => file.data); // Wait until the file data is set expect(disassembleWasm).toHaveBeenCalledWith(data, "status"); expect(setValue).toHaveBeenCalledWith(data); expect(setModelLanguage).toHaveBeenCalledWith(file.buffer, "wat"); expect(file.bufferType).toEqual(FileType.Wat); expect(file.description).toEqual("This .wasm file is editable as a .wat file, and is automatically reassembled to .wasm when saved."); setValue.mockRestore(); setModelLanguage.mockRestore(); disassembleWasm.mockRestore(); }); }); }); describe("getData", () => { it("should return the file's data", () => { const file = new File("file", FileType.JavaScript); const data = "test"; file.setData(data); expect(file.getData()).toEqual(data); }); it("should dispatch an onDirtyFileUsed event if the file is dirty", () => { const callback = jest.fn(); const project = new Project(); const file = project.newFile("file", FileType.JavaScript); project.onDirtyFileUsed.register(callback); file.isDirty = true; file.getData(); expect(callback).toHaveBeenCalled(); }); it("should NOT dispatch an onDirtyFileUsed event if the file's buffer is readonly", () => { const callback = jest.fn(); const project = new Project(); const file = project.newFile("file", FileType.JavaScript); project.onDirtyFileUsed.register(callback); file.isBufferReadOnly = true; file.getData(); expect(callback).not.toHaveBeenCalled(); }); }); describe("getPath", () => { it("should return the path", () => { const { a, b, c, cd } = getDirectoryStructure(); expect(a.getPath()).toBe("test"); expect(b.getPath()).toBe("test/b"); expect(c.getPath()).toBe("test/c"); expect(cd.getPath()).toBe("test/c/d"); expect(cd.getPath(c)).toBe("d"); expect(cd.getPath(a)).toBe("c/d"); }); }); describe("getProject", () => { it("should return the project that the file belongs to", () => { const project = new Project(); const parent = project.newDirectory("parent"); const file = parent.newFile("file", FileType.JavaScript); expect(file.getProject()).toBe(project); }); it("should return null if file does not have a parent", () => { const file = new File("file", FileType.JavaScript); expect(file.getProject()).toBeNull(); }); it("should return null if file does not belong to a project", () => { const directory = new Directory("parent"); const file = directory.newFile("file", FileType.JavaScript); expect(file.getProject()).toBeNull(); }); }); describe("getDepth", () => { it("should return the file's depth", () => { const project = new Project(); const parent = project.newDirectory("parent"); const file = parent.newFile("file", FileType.JavaScript); expect(file.getDepth()).toEqual(2); }); it("should return 0 if the file does not have a parent", () => { const file = new File("file", FileType.JavaScript); expect(file.getDepth()).toEqual(0); }); }); describe("save", () => { it("should abort save if file is not dirty", async () => { const callback = jest.fn(); const file = new File("file", FileType.JavaScript); file.onDidChangeData.register(callback); await file.save("status" as any); expect(callback).not.toHaveBeenCalled(); }); it("should set the file's data from the buffer value", async () => { const file = new File("file", FileType.JavaScript); file.parent = new Project(); file.getProject().fiddleEditable = true; file.isDirty = true; const value = "value"; const getValue = jest.spyOn(monaco.editor, "getValue"); getValue.mockImplementation(() => value); await file.save("status" as any); expect(file.data).toEqual(value); getValue.mockRestore(); }); it("should dispatch an onDidChangeData event", async () => { const callback = jest.fn(); const file = new File("file", FileType.JavaScript); file.parent = new Project(); file.getProject().fiddleEditable = true; file.isDirty = true; file.onDidChangeData.register(callback); await file.save("status" as any); expect(callback).toHaveBeenCalled(); }); it("should reset the file's dirty state and dispatch an onDidChangeDirty event", async () => { const callback = jest.fn(); const file = new File("file", FileType.JavaScript); file.parent = new Project(); file.getProject().fiddleEditable = true; file.isDirty = true; file.onDidChangeDirty.register(callback); await file.save("status" as any); expect(callback).toHaveBeenCalled(); expect(file.isDirty).toEqual(false); }); it("should assemble wat (Wat -> Wasm)", async () => { const value = "value"; const status = "status" as any; const assembleWat = jest.spyOn(Service, "assembleWat"); const getValue = jest.spyOn(monaco.editor, "getValue"); getValue.mockImplementation(() => value); assembleWat.mockImplementation((value) => Promise.resolve(value)); const file = new File("file", FileType.Wasm); file.parent = new Project(); file.getProject().fiddleEditable = true; file.isDirty = true; file.bufferType = FileType.Wat; await file.save(status); expect(assembleWat).toHaveBeenCalledWith(value, status); expect(file.data).toEqual(value); }); it("should handle errors when assembling wat (Wat -> Wasm)", async () => { const value = "value"; const status = { logLn: jest.fn() } as any; const error = new Error("assemble error"); const assembleWat = jest.spyOn(Service, "assembleWat"); const getValue = jest.spyOn(monaco.editor, "getValue"); getValue.mockImplementation(() => value); assembleWat.mockImplementation((value) => { throw error; }); const file = new File("file", FileType.Wasm); file.isDirty = true; file.bufferType = FileType.Wat; file.save(status); expect(status.logLn).toHaveBeenCalledWith(error.message, "error"); }); }); describe("toString", () => { it("should return a string representation of the file", () => { const file = new File("fileName", FileType.JavaScript); expect(file.toString()).toEqual("File [fileName]"); }); }); describe("isDescendantOf", () => { it("should return true if the file is a direct child of the given element", () => { const { a, b } = getDirectoryStructure(); expect(b.isDescendantOf(a)).toBe(true); }); it("should return true if the file is a nested child of the given element", () => { const { a, cd } = getDirectoryStructure(); expect(cd.isDescendantOf(a)).toBe(true); }); it("should return false if the file is not a descendant of the given element", () => { const { a, b } = getDirectoryStructure(); expect(a.isDescendantOf(b)).toBe(false); }); it("should return false if called with itself as argument", () => { const { a } = getDirectoryStructure(); expect(a.isDescendantOf(a)).toBe(false); }); }); });
the_stack
import { Line } from './line'; import { Matrix } from './matrix'; import { Plane } from './plane'; import { Sylvester, InvalidOperationError } from './sylvester'; import { Vector } from './vector'; import { VectorOrList } from './likeness'; export class Polygon { /** * Plane on which the polygon lies. */ public readonly plane: Plane; /** * Polygon verticies. */ public readonly vertices: ReadonlyArray<Vertex>; private surfaceIntegralElements?: ReadonlyArray<Polygon>; private triangles?: ReadonlyArray<Polygon>; private convexVertices: Vertex[]; private reflexVertices: Vertex[]; /** * Creates a new polygon formed from the given points, optionally projected * onto the plane. */ constructor(points: ReadonlyArray<VectorOrList>, plane: Plane) { if (points.length === 0) { throw new InvalidOperationError('Cannot create a polygon with zero points'); } this.vertices = points.map(point => (point instanceof Vertex ? point : new Vertex(point))); this.plane = plane || Plane.fromPoints(...this.vertices); this.convexVertices = []; this.reflexVertices = []; this.vertices.forEach(node => { if (node.isConvex(this)) { this.convexVertices.push(node); } else { this.reflexVertices.push(node); } }); } /** * Returns whether the other polygon is equal to this one. * @param epsilon - precision used for calculating equality */ public eql(other: unknown, epsilon = Sylvester.precision) { if (!(other instanceof Polygon) || other.vertices.length !== this.vertices.length) { return false; } for (let i = 0; i < this.vertices.length; i++) { if (!other.vertices[i].eql(this.vertices[i], epsilon)) { return false; } } return true; } /** * Returns the vertex at the given position on the vertex list, numbered from 1. * @diagram Polygon.v */ public v(i: number) { i--; return i < 0 ? this.vertices[this.vertices.length - (-i % this.vertices.length)] : this.vertices[i % this.vertices.length]; } /** * Translates the polygon by the given vector and returns the polygon. * @diagram Polygon.translate */ public translate(vector: VectorOrList) { const elements = Vector.toElements(vector, 3); return new Polygon( this.vertices.map(v => v.add(elements)), this.plane.translate(elements), ); } /** * Rotates the polygon about the given line and returns the polygon. * @param t - degrees in radians * @diagram Polygon.rotate */ public rotate(t: number, line: Line) { const R = Matrix.Rotation(t, line.direction); return new Polygon( this.vertices.map(v => v.rotate3D(R, line)), this.plane.rotate(R, line), ); } /** * Scales the polygon relative to the given point and returns the polygon. * @param k - amount of scale * @param point - origin to scale from * @diagram Polygon.scale */ public scale(k: number, point: VectorOrList = Vector.Zero(3)) { const P = Vector.toElements(point, 3); return new Polygon( this.vertices.map(node => { const E = node.elements; return new Vector([ P[0] + k * (E[0] - P[0]), P[1] + k * (E[1] - P[1]), P[2] + k * (E[2] - P[2]), ]); }), new Plane(this.vertices[0], this.plane.normal), ); } /** * Returns true iff the polygon is a triangle. * @diagram Polygon.isTriangle */ isTriangle() { return this.vertices.length === 3; } /** * Returns a collection of triangles used for calculating area and center of mass. * Some of the triangles will not lie inside the polygon - this collection is essentially * a series of itervals in a surface integral, so some are 'negative'. If you want the * polygon broken into constituent triangles, use toTriangles(). This method is used * because it's much faster than toTriangles(). * The triangles generated share vertices with the original polygon, so they transform * with the polygon. They are cached after first calculation and should remain in sync * with changes to the parent polygon. * @private */ trianglesForSurfaceIntegral() { if (this.surfaceIntegralElements) { return this.surfaceIntegralElements; } const triangles: Polygon[] = []; const plane = this.plane; for (let i = 2; i < this.vertices.length; i++) { const a = this.vertices[0].elements; const b = this.vertices[i - 1].elements; const c = this.vertices[i].elements; // If the vertices lie on a straight line, give the polygon's own plane. If the // element has no area, it doesn't matter which way its normal faces. const colinear = (a[1] - b[1]) * (a[0] - c[0]) - (c[1] - a[1]) * (a[0] - b[0]) < Sylvester.precision; triangles.push( new Polygon( [this.vertices[0], this.vertices[i - 1], this.vertices[i]], colinear ? plane : Plane.fromPoints(a, b, c), ), ); } this.surfaceIntegralElements = triangles; return triangles; } /** * Returns the area of the polygon. Requires that the polygon * be converted to triangles, so use with caution. * @diagram Polygon.area */ area() { if (this.isTriangle()) { // Area is half the modulus of the cross product of two sides const a = this.vertices[0].elements; const b = this.vertices[1].elements; const c = this.vertices[2].elements; return ( 0.5 * new Vector([ (a[1] - b[1]) * (c[2] - b[2]) - (a[2] - b[2]) * (c[1] - b[1]), (a[2] - b[2]) * (c[0] - b[0]) - (a[0] - b[0]) * (c[2] - b[2]), (a[0] - b[0]) * (c[1] - b[1]) - (a[1] - b[1]) * (c[0] - b[0]), ]).magnitude() ); } const trigs = this.trianglesForSurfaceIntegral(); let area = 0; for (let i = 0; i < trigs.length; i++) { area += trigs[i].area() * trigs[i].plane.normal.dot(this.plane.normal); } return area; } /** * Returns the centroid of the polygon. Requires division into * triangles - use with caution. * @diagram Polygon.centroid */ centroid() { if (this.isTriangle()) { const A = this.v(1).elements; const B = this.v(2).elements; const C = this.v(3).elements; return new Vector([ (A[0] + B[0] + C[0]) / 3, (A[1] + B[1] + C[1]) / 3, (A[2] + B[2] + C[2]) / 3, ]); } let V = Vector.Zero(3); const trigs = this.trianglesForSurfaceIntegral(); let M = 0; let i = trigs.length; while (i--) { const A = trigs[i].area() * trigs[i].plane.normal.dot(this.plane.normal); M += A; const P = V.elements; const C = trigs[i].centroid().elements; V = new Vector([P[0] + C[0] * A, P[1] + C[1] * A, P[2] + C[2] * A]); } return V.x(1 / M); } /** * Returns the polygon's projection on the given plane as another polygon * @diagram Polygon.projectionOn */ public projectionOn(plane: Plane) { return new Polygon( this.vertices.map(node => plane.pointClosestTo(node)), plane, ); } /** * Removes the given vertex from the polygon as long as it's not triangular. * No-op if it is triangular, or if the vertex doesn't exist. * @diagram Polygon.removeVertex */ public removeVertex(vertex: Vector) { if (this.isTriangle()) { return this; } return new Polygon( this.vertices.filter(n => !vertex.eql(n)), this.plane, ); } /** * Returns true iff the point is strictly inside the polygon * @diagram Polygon.contains */ public contains(point: VectorOrList, epsilon = Sylvester.precision): boolean { return this.containsByWindingNumber(point, epsilon); } /** * Returns true iff the given point is strictly inside the polygon using * the winding number method. * @diagram Polygon.contains */ public containsByWindingNumber(point: VectorOrList, epsilon = Sylvester.precision): boolean { const P = Vector.toElements(point, 3); if (!this.plane.contains(P, epsilon)) { return false; } if (this.hasEdgeContaining(P, epsilon)) { return false; } let theta = 0; let loops = 0; const self = this; this.vertices.forEach((node, i) => { const V = node.elements; const W = this.v(i + 2).elements; const A = new Vector([V[0] - P[0], V[1] - P[1], V[2] - (P[2] || 0)]); const B = new Vector([W[0] - P[0], W[1] - P[1], W[2] - (P[2] || 0)]); const dt = A.angleFrom(B); if (dt === null || dt === 0) { return; } theta += (A.cross(B).isParallelTo(self.plane.normal) ? 1 : -1) * dt; if (theta >= 2 * Math.PI - epsilon) { loops++; theta -= 2 * Math.PI; } if (theta <= -2 * Math.PI + epsilon) { loops--; theta += 2 * Math.PI; } }); return loops !== 0; } /** * Returns true if the given point lies on an edge of the polygon * May cause problems with 'hole-joining' edges. * @diagram Polygon.hasEdgeContaining */ public hasEdgeContaining(point: VectorOrList, epsilon = Sylvester.precision): boolean { const P = Vector.toElements(point); return this.vertices.some((node, i) => new Line.Segment(node, this.v(i + 2)).contains(P, epsilon), ); } /** * Returns an array of 3-vertex polygons that the original has been split into. * @diagram Polygon.toTriangles */ toTriangles() { if (!this.triangles) { this.triangles = this.triangulateByEarClipping(); } return this.triangles; } /** * Implementation of ear clipping algorithm. Found in 'Triangulation by ear * clipping', by David Eberly at {@link http://www.geometrictools.com}. This * will not deal with overlapping sections - contruct your polygons sensibly. * @diagram Polygon.toTriangles */ triangulateByEarClipping() { let poly: Polygon = this; const triangles = []; while (!poly.isTriangle()) { let success = false; let trig: Polygon; let mainNode: number; // Ear tips must be convex vertices - let's pick one at random let offset = Math.floor(Math.random() * poly.convexVertices.length); for (let i = 0; !success && i < poly.convexVertices.length; i++) { const convexNode = poly.convexVertices[(offset + i) % poly.convexVertices.length]; mainNode = poly.vertices.indexOf(convexNode); const prev = poly.v(mainNode); const next = poly.v(mainNode + 2); // For convex vertices, this order will always be anticlockwise trig = new Polygon([convexNode, next, prev], this.plane); // Now test whether any reflex vertices lie within the ear success = !poly.reflexVertices.some(node => { // Don't test points belonging to this triangle. node won't be // equal to convexNode as node is reflex and vertex is convex. if (node !== prev && node !== next) { return trig.contains(node) || trig.hasEdgeContaining(node); } return false; }); } if (!success) { throw new Error('Could not find any candidate veritices, this is a bug'); } triangles.push(trig!); poly = poly.removeVertex(poly.vertices[mainNode!]); } // Need to do this to renumber the remaining vertices triangles.push(poly); return triangles; } /** * Returns a string representation of the polygon's vertices. */ public toString() { const points: string[] = []; this.vertices.forEach(node => { points.push(node.toString()); }); return `Polygon<${points.join(' -> ')}>`; } /** * Removes cached data, used for benchmarking. * @hidden */ public decache() { this.triangles = undefined; this.surfaceIntegralElements = undefined; } } export class Vertex extends Vector { constructor(point: VectorOrList) { super(Vector.toElements(point, 3)); } /** * Returns true iff the vertex's internal angle is 0 <= x < 180 * in the context of the given polygon object. * @throws A {@link InvalidOperationError} if the vertex is not in the polygon */ public isConvex(polygon: Polygon, epsilon = Sylvester.precision): boolean { const node = polygon.vertices.indexOf(this); if (node === -1) { throw new InvalidOperationError('Provided vertex is not in the polygon'); } const prev = polygon.v(node); const next = polygon.v(node + 2); const A = next.subtract(this); const B = prev.subtract(this); const theta = A.angleFrom(B); if (theta <= epsilon) { return true; } if (Math.abs(theta - Math.PI) <= epsilon) { return false; } return A.cross(B).dot(polygon.plane.normal) > 0; } /** * Returns true iff the vertex's internal angle is 180 <= x < 360. * @throws A {@link InvalidOperationError} if the vertex is not in the polygon */ isReflex(polygon: Polygon) { const result = this.isConvex(polygon); return !result; } }
the_stack
"use strict"; import { ParsedDiff } from "diff"; import * as diffMatchPatch from "diff-match-patch"; import { compareTwoStrings, findBestMatch, Rating } from "string-similarity"; import { MarkerLocation, MarkerLocationsById } from "../api/extensions"; import { Logger } from "../logger"; import { Id } from "../managers/entityManager"; import { CSLocationMeta, CSMarkerLocation } from "../protocol/api.protocol"; import { buildChangeset, Change, Changeset } from "./changeset"; export const MAX_RANGE_VALUE = 2147483647; const LINE_SIMILARITY_THRESHOLD = 0.5; const CHANGE_SIMILARITY_THRESHOLD = 0.5; const DELETED = -1; export async function findBestMatchingLine( text: string, lineContent: string, originalLineNumber: number ) { try { const dmp = new diffMatchPatch.diff_match_patch(); const lines = text.split("\n"); let guessOffset = 0; for (let i = 0; i < originalLineNumber - 1; i++) { guessOffset += lines[i].length + 1; } // patterns cannot be larger than 32 (number of bits in an int) const trimmedLineContent = lineContent.trim().substring(0, 32); const dmpOffset = dmp.match_main(text, trimmedLineContent, guessOffset); if (dmpOffset === -1) return -1; let dmpLineIndex = 0; let offset = 0; while (dmpOffset > offset + lines[dmpLineIndex].length + 1 && dmpLineIndex < lines.length) { offset += lines[dmpLineIndex].length + 1; dmpLineIndex++; } return dmpLineIndex + 1; } catch (e) { Logger.warn(`Error calculating location based on content: ${e.message}`); return -1; } } export async function calculateLocations( locations: MarkerLocationsById, diff: ParsedDiff ): Promise<MarkerLocationsById> { const calculation = new Calculation(locations, buildChangeset(diff)); return calculation.results(); } export async function calculateLocation( location: CSMarkerLocation, diff: ParsedDiff ): Promise<CSMarkerLocation> { const calculated = await calculateLocations(MarkerLocation.toLocationById(location), diff); return calculated[location.id]; } function sortNumber(a: number, b: number) { return a - b; } function sortMatches(a: Match, b: Match) { return a.rating.rating - b.rating.rating; } interface Match { change: Change; rating: Rating; } class CalculatedLine { newLine = 0; delContent = ""; addContent = ""; change?: Change; } class CalculatedLocation { readonly id: string; readonly lineStartOld: number; readonly lineEndOld: number; readonly colStartOld: number; readonly colEndOld: number; lineStartNew = 0; lineEndNew = 0; colStartNew = 0; colEndNew = 0; lineStartOldContent = ""; lineEndOldContent = ""; lineStartNewContent = ""; lineEndNewContent = ""; readonly meta: CSLocationMeta = {}; private lineMap: Map<number, CalculatedLine>; constructor(location: CSMarkerLocation, lineMap: Map<number, CalculatedLine>) { this.id = location.id; this.lineStartOld = location.lineStart; this.lineEndOld = location.lineEnd; this.colStartOld = location.colStart; this.colEndOld = location.colEnd; this.lineMap = lineMap; } trimLineStartChange() { const change = this.lineStartChange(); this.lineStartNew = change.addStart + change.adds.length; this.colStartNew = 1; this.meta.startWasDeleted = true; } trimLineEndChange() { const change = this.lineEndChange(); this.lineEndNew = change.addStart - 1; this.colEndNew = MAX_RANGE_VALUE; this.meta.endWasDeleted = true; } trimLineChange() { this.trimLineStartChange(); this.lineEndNew = this.lineStartNew; this.colEndNew = 1; this.meta.endWasDeleted = true; this.meta.entirelyDeleted = true; } isLineStartDeleted(): boolean { return this.lineStartNew === DELETED; } isLineEndDeleted(): boolean { return this.lineEndNew === DELETED; } isMultiLine(): boolean { return this.lineEndOld > 0; } isEntirelyDeleted(): boolean { if (this.isMultiLine()) { return ( this.isLineStartDeleted() && this.isLineEndDeleted() && this.lineStartChange() === this.lineEndChange() ); } else { return this.isLineStartDeleted(); } } lineStartCalc(): CalculatedLine { const calculatedLine = this.lineMap.get(this.lineStartOld); if (!calculatedLine) { throw new Error(`Could not find calculated starting line ${this.lineStartOld}`); } return calculatedLine; } lineEndCalc(): CalculatedLine { const calculatedLine = this.lineMap.get(this.lineEndOld); if (!calculatedLine) { throw new Error(`Could not find calculated ending line ${this.lineEndOld}`); } return calculatedLine; } lineStartChange(): Change { const change = this.lineStartCalc().change; if (!change) { throw new Error("Could not find change for starting line"); } return change; } lineEndChange(): Change { const change = this.lineEndCalc().change; if (!change) { throw new Error("Could not find change for ending line"); } return change; } lineStartChangeDelContent(): string { return this.lineStartChange().dels.join("\n"); } lineStartCalcDelContent(): string { return this.lineStartCalc().delContent; } lineEndCalcDelContent(): string { return this.lineEndCalc().delContent; } markerLocation(): CSMarkerLocation { return { id: this.id, lineStart: this.lineStartNew, colStart: this.colStartNew, lineEnd: this.lineEndNew, colEnd: this.colEndNew, meta: this.meta }; } } class Calculation { private readonly _lines: number[]; private readonly _locationsStarting = new Map<number, Id[]>(); private readonly _locationsEnding = new Map<number, Id[]>(); private readonly _activeLocations = new Set<Id>(); private readonly _calculatedLines: Map<number, CalculatedLine>; private readonly _calculatedLocations: Map<Id, CalculatedLocation>; private readonly _changes: Change[]; private _lineIndex: number; private _finalBalance: number; constructor(locations: MarkerLocationsById, changeset: Changeset) { const calculatedLocations = new Map<Id, CalculatedLocation>(); const linesOfInterest = new Set<number>(); const calculatedLines = new Map<number, CalculatedLine>(); for (const id in locations) { const location = locations[id]; calculatedLocations.set(location.id, new CalculatedLocation(location, calculatedLines)); if (location.lineStart !== DELETED) { linesOfInterest.add(location.lineStart); let starting = this._locationsStarting.get(location.lineStart); if (!starting) { starting = []; this._locationsStarting.set(location.lineStart, starting); } starting.push(location.id); } if (location.lineEnd !== DELETED) { linesOfInterest.add(location.lineEnd); let ending = this._locationsEnding.get(location.lineEnd); if (!ending) { ending = []; this._locationsEnding.set(location.lineEnd, ending); } ending.push(location.id); } } const lines = Array.from(linesOfInterest.values()).sort(sortNumber); for (const line of lines) { calculatedLines.set(line, new CalculatedLine()); } this._lines = lines; this._calculatedLines = calculatedLines; this._calculatedLocations = calculatedLocations; this._changes = changeset.changes; this._lineIndex = 0; this._finalBalance = 0; this.activateLocationsStartingAtCurrentLine(); } results(): MarkerLocationsById { for (const change of this._changes) { this.applyChange(change); } this.calculateLinesUntilEnd(); this.assignNewLines(); this.calculateMissingLocations(); this.calculateColumns(); const result: MarkerLocationsById = {}; for (const calcLoc of this._calculatedLocations.values()) { result[calcLoc.id] = calcLoc.markerLocation(); } return result; } private activateLocationsStartingAtCurrentLine() { const line = this.getCurrentLine(); const locationIds = this._locationsStarting.get(line); if (locationIds) { for (const id of locationIds) { this._activeLocations.add(id); } } } private deactivateLocationsEndingAtCurrentLine() { const line = this.getCurrentLine(); const locationIds = this._locationsEnding.get(line); if (locationIds) { for (const id of locationIds) { this._activeLocations.delete(id); } } } private getCurrentLine(): number { return this._lines[this._lineIndex]; } // @memoize private getAddContentFromChanges(): string[] { const addContents = []; for (const change of this._changes) { addContents.push(change.adds.join("\n")); } return addContents; } private nextLine() { this.deactivateLocationsEndingAtCurrentLine(); this._lineIndex++; this.activateLocationsStartingAtCurrentLine(); } private moveCurrentLineBy(delta: number) { const line = this.getCurrentLine(); const calculatedLine = this.getCalculatedLine(line); calculatedLine.newLine = line + delta; } private getCalculatedLine(line: number) { const calculatedLine = this._calculatedLines.get(line); if (!calculatedLine) { throw new Error(`Could not find calculated line ${line}`); } return calculatedLine; } private assignNewLines() { for (const location of this._calculatedLocations.values()) { if (location.lineStartOld !== DELETED) { const startLine = this.getCalculatedLine(location.lineStartOld); location.lineStartNew = startLine.newLine; location.lineStartOldContent = startLine.delContent; location.lineStartNewContent = startLine.addContent; } if (location.lineEndOld !== DELETED) { const endLine = this.getCalculatedLine(location.lineEndOld); location.lineEndNew = endLine.newLine; location.lineEndOldContent = endLine.delContent; location.lineEndNewContent = endLine.addContent; } } } private calculateColumns() { for (const location of this._calculatedLocations.values()) { // when locations are trimmed, colStartNew and/or colEndNew will be already set const colStartNew = location.colStartNew > 0 ? location.colStartNew : calculateColumn( location.colStartOld, location.lineStartOldContent, location.lineStartNewContent ); const colEndNew = location.colEndNew > 0 ? location.colEndNew : calculateColumn( location.colEndOld, location.lineEndOldContent, location.lineEndNewContent ); if (location.lineStartNew === location.lineEndNew && colStartNew > colEndNew) { location.colStartNew = 1; location.colEndNew = location.lineEndNewContent.length; } else { location.colStartNew = colStartNew; location.colEndNew = colEndNew; } } } private applyChange(change: Change) { this.calculateLinesUntil(change); this.calculateLinesIn(change); } private calculateLinesUntil(change: Change) { const balance = change.addStart - change.delStart; let line; while ((line = this.getCurrentLine()) && line < change.delStart) { this.moveCurrentLineBy(balance); this.nextLine(); } } private calculateLinesIn(change: Change) { this.setContentChangedInActiveLocations(); const initialBalance = change.addStart - change.delStart; const changeLen = change.adds.length - change.dels.length; const delEnd = change.delStart + change.dels.length; this._finalBalance = initialBalance + changeLen; let line; while ((line = this.getCurrentLine()) && line < delEnd) { const delIndex = line - change.delStart; const delContent = change.dels[delIndex]; const [addIndex, addContent] = bestMatch(delContent, change.adds); let newLine = change.addStart + addIndex; if (addIndex < 0) { newLine = DELETED; } const calculatedLine = this.getCalculatedLine(line); calculatedLine.newLine = newLine; calculatedLine.delContent = delContent; calculatedLine.addContent = addContent; calculatedLine.change = change; this.nextLine(); } } private calculateLinesUntilEnd() { while (this.getCurrentLine()) { this.moveCurrentLineBy(this._finalBalance); this.nextLine(); } } // Iterate over locations that had its starting line(s) and/or ending line(s) // deleted. If the location has at least some of its original content preserved, // then we simply trim the removed parts. If the location was entirely deleted, // then we try to find it by looking at all changes in the file. // // TODO room for improvement here: we could also look at changes in other files // to try to find blocks of code moved across files private calculateMissingLocations() { for (const location of this._calculatedLocations.values()) { if (location.isEntirelyDeleted()) { if (!this.findMovedLocation(location)) { location.trimLineChange(); } } else { if (location.isLineStartDeleted()) { location.trimLineStartChange(); } if (location.isLineEndDeleted()) { location.trimLineEndChange(); } } } } // Try to find a moved location. A location will only be considered moved if: // // - it is a single-line location, and was deleted in an change // - it is a multi-line location, and its entire range was deleted by a single // change - this is important as we don't want to chase around a location if // at least part of its content was preserved // // 1) we gather the contents of the change that deleted the location // 2) we find all changes that added new contents that match the contents // from (1) with a minimum similarity level defined by changeSimilarityThreshold // 3) we iterate over the changes from (2), in order of similarity (best matches first) // 4) for each change, we look at its added lines and find the lines that best // match the location's original starting and ending (if multi-line) lines // 5) if we find such lines and they have a minimum similarity level defined // by LINE_SIMILARITY_THRESHOLD, and they are in order (start < end), then // we say we found the location // 6) if we exhaust all changes from (4) without finding lines (5), then we // consider the location as deleted private findMovedLocation(location: CalculatedLocation): boolean { // if a multi-line location is considered moved, it means that both its // lineStartChange and lineEndChange are the same, so we can always get // the content from lineStartChange const delContent = location.lineStartChangeDelContent(); const matchingChanges = this.findChangesWithSimilarAddContent(delContent); for (const change of matchingChanges) { const adds = change.adds; const [lineStartIndex, lineStartContent] = bestMatch( location.lineStartCalcDelContent(), adds ); if (lineStartIndex === DELETED) { continue; } if (location.isMultiLine()) { const [lineEndIndex, lineEndContent] = bestMatch(location.lineEndCalcDelContent(), adds); if (lineEndIndex === DELETED) { continue; } if (lineStartIndex > lineEndIndex) { // TODO room for improvement - check 2nd, 3rd best matches. // that would require collecting and ranking candidates from // all matching changes before deciding which one is the most // similar continue; } location.lineEndNewContent = lineEndContent; location.lineEndNew = change.addStart + lineEndIndex; location.lineStartNewContent = lineStartContent; location.lineStartNew = change.addStart + lineStartIndex; return true; } else { location.lineStartNewContent = location.lineEndNewContent = lineStartContent; location.lineStartNew = location.lineEndNew = change.addStart + lineStartIndex; return true; } } return false; } private findChangesWithSimilarAddContent(content: string): Change[] { const addContentFromChanges = this.getAddContentFromChanges(); const ratings = findBestMatch(content, addContentFromChanges).ratings; const matches = []; for (let i = 0; i < addContentFromChanges.length; i++) { const rating = ratings[i]; if (rating.rating >= CHANGE_SIMILARITY_THRESHOLD) { matches.push({ change: this._changes[i], rating: rating }); } } return matches.sort(sortMatches).map(match => match.change); } private setContentChangedInActiveLocations() { for (const id of this._activeLocations) { const calculatedLocation = this._calculatedLocations.get(id); if (calculatedLocation) { calculatedLocation.meta.contentChanged = true; } else { Logger.warn( `Calculation error: cannot set flag contentsChanged=true in active location ${id} - calculated location object not found` ); } } } } // Recalculates a column number based on the line's old and new contents. In // order to find the corresponding column (position) in the new content, // we take into account: // // - pre: 3 characters before column oldCol // - mid: character at column oldCol // - pos: 3 characters after column oldCol // // Since the substring pre+mid+pos may occur more than once in the old line, // we calculate its specific index, which indicates which occurrence is located // around oldCol. // // Example: "aaaabcdefghbcdefgh" // 123456789012345678 // // oldCol: 8 => pre: bcd, mid: e, pos: fgh, specificIndex: 0 // oldCol: 15 => pre: bcd, mid: e, pos: fgh, specificIndex: 1 // oldCol: 1 => pre: , mid: a, pos: aaa, specificIndex: 0 // // In possession of pre, mid, pos and specificIndex, we search all occurrences // of pre+mid+pos in the new line and return the column number associated with // mid at the specificIndex. In case pre+mid+pos is not found in the new line, // we remove pre's first character and pos' last character and try again, until // pre and pos are both empty, at which point we give up and assume the content // is no longer present in the new line. // // Example: // oldLine: function foo() { // 1234567890123456 // newLine: function fooRenamed() { // 12345678901234567890123 // oldCol: 14 => pre: "oo(", mid: ")", pos: " {", specificIndex: 0 // // 1st attempt: "oo() {" => not found // 2nd attempt: "o() " => not found // 3rd attempt: "()" => found, with mid ")" at column 21 // // Therefore, newCol = 20 // // Example: // oldLine: return (foo && bar) || (baz && bar) // 12345678901234567890123456789012345 // newLine: return !(foo && bar) || !(baz && bar) // 1234567890123456789012345678901234567 // oldCol: 34 => pre: " ba", mid: "r", pos: ")", specificIndex: 1 // // 1st attempt: " bar)" => found, with mid "r" at columns 19 and 36 // // Therefore, since specificIndex is 1, newCol = 36 function calculateColumn(oldCol: number, oldContent: string, newContent: string) { if (!oldContent || !newContent || oldContent === newContent) { return oldCol; } if (oldCol <= 1) { return 1; } else if (oldCol > oldContent.length) { return newContent.length + 1; } let pre = oldContent.substring(oldCol - 4, oldCol - 1); const mid = oldContent.substring(oldCol - 1, oldCol); let pos = oldContent.substring(oldCol, oldCol + 3); let i; while (true) { const str = pre + mid + pos; const oldContentPositions = []; i = oldContent.indexOf(str); while (i > -1) { oldContentPositions.push(i + pre.length + 1); i = oldContent.indexOf(str, i + 1); } const specificIndex = oldContentPositions.indexOf(oldCol); const newContentPositions = []; i = newContent.indexOf(str); while (i > -1) { newContentPositions.push(i + pre.length + 1); i = oldContent.indexOf(str, i + 1); } const newColumn = newContentPositions[specificIndex] || newContentPositions[newContentPositions.length - 1]; if (newColumn) { return newColumn; } if (!pre.length && !pos.length) { break; } pre = pre.substring(1, pre.length); pos = pos.substring(0, pos.length - 1); } return DELETED; } function bestMatch(content: string, candidates: string[]): [number, string] { let winner = -1; let highScore = 0; for (let i = 0; i < candidates.length; i++) { const candidate = candidates[i]; const rating = compareTwoStrings(content, candidate); if (rating > highScore) { winner = i; highScore = rating; } } if (highScore >= LINE_SIMILARITY_THRESHOLD) { return [winner, candidates[winner]]; } else { return [-1, ""]; } }
the_stack
import * as path from 'path'; import * as util from 'util'; import { CancellationToken, Position, Range, TestController, TestItem, Uri } from 'vscode'; import { createDeferred, Deferred } from '../../common/utils/async'; import { Testing } from '../../common/utils/localize'; import { traceError } from '../../logging'; import { sendTelemetryEvent } from '../../telemetry'; import { EventName } from '../../telemetry/constants'; import { TestProvider } from '../types'; import { createErrorTestItem, DebugTestTag, ErrorTestItemOptions, RunTestTag } from './common/testItemUtilities'; import { DiscoveredTestItem, DiscoveredTestNode, DiscoveredTestType, ITestDiscoveryAdapter } from './common/types'; /** * This class exposes a test-provider-agnostic way of discovering tests. * * It gets instantiated by the `PythonTestController` class in charge of reflecting test data in the UI, * and then instantiates provider-specific adapters under the hood depending on settings. * * This class formats the JSON test data returned by the `[Unittest|Pytest]TestDiscoveryAdapter` into test UI elements, * and uses them to insert/update/remove items in the `TestController` instance behind the testing UI whenever the `PythonTestController` requests a refresh. */ export class WorkspaceTestAdapter { private discovering: Deferred<void> | undefined = undefined; private testData: DiscoveredTestNode | undefined; constructor( private testProvider: TestProvider, private discoveryAdapter: ITestDiscoveryAdapter, // TODO: Implement test running // private runningAdapter: ITestRunningAdapter, private workspaceUri: Uri, ) {} public async discoverTests( testController: TestController, token?: CancellationToken, isMultiroot?: boolean, workspaceFilePath?: string, ): Promise<void> { sendTelemetryEvent(EventName.UNITTEST_DISCOVERING, undefined, { tool: this.testProvider }); const workspacePath = this.workspaceUri.fsPath; // Discovery is expensive. If it is already running, use the existing promise. if (this.discovering) { return this.discovering.promise; } const deferred = createDeferred<void>(); this.discovering = deferred; let rawTestData; try { rawTestData = await this.discoveryAdapter.discoverTests(this.workspaceUri); deferred.resolve(); } catch (ex) { sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_DONE, undefined, { tool: this.testProvider, failed: true }); const cancel = token?.isCancellationRequested ? Testing.cancelUnittestDiscovery : Testing.errorUnittestDiscovery; traceError(`${cancel}\r\n`, ex); // Report also on the test view. const message = util.format(`${cancel} ${Testing.seePythonOutput}\r\n`, ex); const options = buildErrorNodeOptions(this.workspaceUri, message); const errorNode = createErrorTestItem(testController, options); testController.items.add(errorNode); deferred.reject(ex as Error); } finally { // Discovery has finished running, we have the data, // we don't need the deferred promise anymore. this.discovering = undefined; } if (!rawTestData) { // No test data is available return Promise.resolve(); } // Check if there were any errors in the discovery process. if (rawTestData.status === 'error') { const { errors } = rawTestData; traceError(Testing.errorUnittestDiscovery, '\r\n', errors!.join('\r\n\r\n')); let errorNode = testController.items.get(`DiscoveryError:${workspacePath}`); const message = util.format( `${Testing.errorUnittestDiscovery} ${Testing.seePythonOutput}\r\n`, errors!.join('\r\n\r\n'), ); if (errorNode === undefined) { const options = buildErrorNodeOptions(this.workspaceUri, message); errorNode = createErrorTestItem(testController, options); testController.items.add(errorNode); } errorNode.error = message; } else { // Remove the error node if necessary, // then parse and insert test data. testController.items.delete(`DiscoveryError:${workspacePath}`); // Wrap the data under a root node named after the test provider. const wrappedTests = rawTestData.tests; // If we are in a multiroot workspace scenario, wrap the current folder's test result in a tree under the overall root + the current folder name. let rootPath = workspacePath; let childrenRootPath = rootPath; let childrenRootName = path.basename(rootPath); if (isMultiroot) { rootPath = workspaceFilePath!; childrenRootPath = workspacePath; childrenRootName = path.basename(workspacePath); } const children = [ { path: childrenRootPath, name: childrenRootName, type_: 'folder' as DiscoveredTestType, children: wrappedTests ? [wrappedTests] : [], }, ]; // Update the raw test data with the wrapped data. rawTestData.tests = { path: rootPath, name: this.testProvider, type_: 'folder', children, }; const workspaceNode = testController.items.get(rootPath); if (rawTestData.tests) { // If the test root for this folder exists: Workspace refresh, update its children. // Otherwise, it is a freshly discovered workspace, and we need to create a new test root and populate the test tree. if (workspaceNode) { updateTestTree(testController, rawTestData.tests, this.testData, workspaceNode, token); } else { populateTestTree(testController, rawTestData.tests, undefined, token); } } else { // Delete everything from the test controller. testController.items.replace([]); } // Save new test data state. this.testData = rawTestData.tests; } sendTelemetryEvent(EventName.UNITTEST_DISCOVERY_DONE, undefined, { tool: this.testProvider, failed: false }); return Promise.resolve(); } } function isTestItem(test: DiscoveredTestNode | DiscoveredTestItem): test is DiscoveredTestItem { return test.type_ === 'test'; } function deleteTestTree(testController: TestController, root?: TestItem) { if (root) { const { children } = root; children.forEach((child) => { deleteTestTree(testController, child); const { id } = child; testController.items.delete(id); }); testController.items.delete(root.id); } } function updateTestTree( testController: TestController, updatedData: DiscoveredTestNode, localData: DiscoveredTestNode | undefined, testRoot: TestItem | undefined, token?: CancellationToken, ): void { // If testRoot is undefined, use the info of the root item of testTreeData to create a test item, and append it to the test controller. if (!testRoot) { testRoot = testController.createTestItem(updatedData.path, updatedData.name, Uri.file(updatedData.path)); testRoot.canResolveChildren = true; testRoot.tags = [RunTestTag, DebugTestTag]; testController.items.add(testRoot); } // Delete existing items if they don't exist in the updated tree. if (localData) { localData.children.forEach((local) => { if (!token?.isCancellationRequested) { const exists = updatedData.children.find( (node) => local.name === node.name && local.path === node.path && local.type_ === node.type_, ); if (!exists) { // Delete this node and all its children. const testItem = testController.items.get(local.path); deleteTestTree(testController, testItem); } } }); } // Go through the updated tree, update the existing nodes, and create new ones if necessary. updatedData.children.forEach((child) => { if (!token?.isCancellationRequested) { const root = testController.items.get(child.path); if (root) { root.busy = true; // Update existing test node or item. if (isTestItem(child)) { // Update the only property that can be updated. root.label = child.name; } else { const localNode = localData?.children.find( (node) => child.name === node.name && child.path === node.path && child.type_ === node.type_, ); updateTestTree(testController, child, localNode as DiscoveredTestNode, root, token); } root.busy = false; } else { // Create new test node or item. let testItem; if (isTestItem(child)) { testItem = testController.createTestItem(child.id_, child.name, Uri.file(child.path)); const range = new Range(new Position(child.lineno - 1, 0), new Position(child.lineno, 0)); testItem.canResolveChildren = false; testItem.tags = [RunTestTag, DebugTestTag]; testItem.range = range; testRoot!.children.add(testItem); } else { testItem = testController.createTestItem(child.path, child.name, Uri.file(child.path)); testItem.canResolveChildren = true; testItem.tags = [RunTestTag, DebugTestTag]; testRoot!.children.add(testItem); // Populate the test tree under the newly created node. populateTestTree(testController, child, testItem, token); } } } }); } function populateTestTree( testController: TestController, testTreeData: DiscoveredTestNode, testRoot: TestItem | undefined, token?: CancellationToken, ): void { // If testRoot is undefined, use the info of the root item of testTreeData to create a test item, and append it to the test controller. if (!testRoot) { testRoot = testController.createTestItem(testTreeData.path, testTreeData.name, Uri.file(testTreeData.path)); testRoot.canResolveChildren = true; testRoot.tags = [RunTestTag, DebugTestTag]; testController.items.add(testRoot); } // Recursively populate the tree with test data. testTreeData.children.forEach((child) => { if (!token?.isCancellationRequested) { if (isTestItem(child)) { const testItem = testController.createTestItem(child.id_, child.name, Uri.file(child.path)); const range = new Range(new Position(child.lineno - 1, 0), new Position(child.lineno, 0)); testItem.canResolveChildren = false; testItem.range = range; testItem.tags = [RunTestTag, DebugTestTag]; testRoot!.children.add(testItem); } else { let node = testController.items.get(child.path); if (!node) { node = testController.createTestItem(child.path, child.name, Uri.file(child.path)); node.canResolveChildren = true; node.tags = [RunTestTag, DebugTestTag]; testRoot!.children.add(node); } populateTestTree(testController, child, node, token); } } }); } function buildErrorNodeOptions(uri: Uri, message: string): ErrorTestItemOptions { return { id: `DiscoveryError:${uri.fsPath}`, label: `Unittest Discovery Error [${path.basename(uri.fsPath)}]`, error: message, }; }
the_stack
import * as spec from '@jsii/spec'; import * as fs from 'fs-extra'; import { TypeFingerprinter } from './jsii/fingerprinting'; import { TARGET_LANGUAGES } from './languages'; import * as logging from './logging'; import { TypeScriptSnippet, completeSource } from './snippet'; import { collectDependencies, validateAvailableDependencies, prepareDependencyDirectory } from './snippet-dependencies'; import { snippetKey } from './tablets/key'; import { LanguageTablet, TranslatedSnippet } from './tablets/tablets'; import { translateAll, TranslateAllResult } from './translate_all'; export interface RosettaTranslatorOptions { /** * Assemblies to use for fingerprinting * * The set of assemblies here are used to invalidate the cache. Any types that are * used in snippets are looked up in this set of assemblies. If found, their type * information is fingerprinted and compared to the type information at the time * compilation of the cached sample. If different, this is considered to be a cache * miss. * * You must use the same set of assemblies when generating and reading the cache * file, otherwise the fingerprint is guaranteed to be different and the cache will * be useless (e.g. if you generate the cache WITH assembly information but * read it without, or vice versa). * * @default No assemblies. */ readonly assemblies?: spec.Assembly[]; /** * Whether to include compiler diagnostics in the compilation results. * * @default false */ readonly includeCompilerDiagnostics?: boolean; /** * Allow reading dirty translations from cache * * @default false */ readonly allowDirtyTranslations?: boolean; } /** * Entry point for consumers that want to translate code on-the-fly * * If you want to generate and translate code on-the-fly, in ways that cannot * be achieved by the rosetta CLI, use this class. */ export class RosettaTranslator { /** * Tablet with fresh translations * * All new translations (not read from cache) are added to this tablet. */ public readonly tablet = new LanguageTablet(); public readonly cache = new LanguageTablet(); private readonly fingerprinter: TypeFingerprinter; private readonly includeCompilerDiagnostics: boolean; private readonly allowDirtyTranslations: boolean; public constructor(options: RosettaTranslatorOptions = {}) { this.fingerprinter = new TypeFingerprinter(options?.assemblies ?? []); this.includeCompilerDiagnostics = options.includeCompilerDiagnostics ?? false; this.allowDirtyTranslations = options.allowDirtyTranslations ?? false; } /** * @deprecated use `addToCache` instead */ public async loadCache(fileName: string) { try { await this.cache.load(fileName); } catch (e: any) { logging.warn(`Error reading cache ${fileName}: ${e.message}`); } } public async addToCache(filename: string) { const tab = await LanguageTablet.fromOptionalFile(filename); this.cache.addTablet(tab); } public addTabletsToCache(...tablets: LanguageTablet[]) { for (const tab of tablets) { this.cache.addTablet(tab); } } public hasCache() { return this.cache.count > 0; } /** * For all the given snippets, try to read translations from the cache * * Will remove the cached snippets from the input array. */ public readFromCache(snippets: TypeScriptSnippet[], addToTablet = true, compiledOnly = false): ReadFromCacheResults { const translations = new Array<TranslatedSnippet>(); const remaining = new Array<TypeScriptSnippet>(); let infusedCount = 0; let dirtyCount = 0; let dirtySourceCount = 0; let dirtyTypesCount = 0; let dirtyTranslatorCount = 0; let dirtyDidntCompile = 0; for (const snippet of snippets) { const fromCache = tryReadFromCache(snippet, this.cache, this.fingerprinter, compiledOnly); switch (fromCache.type) { case 'hit': if (addToTablet) { this.tablet.addSnippet(fromCache.snippet); } translations.push(fromCache.snippet); infusedCount += fromCache.infused ? 1 : 0; break; case 'dirty': dirtyCount += 1; dirtySourceCount += fromCache.dirtySource ? 1 : 0; dirtyTranslatorCount += fromCache.dirtyTranslator ? 1 : 0; dirtyTypesCount += fromCache.dirtyTypes ? 1 : 0; dirtyDidntCompile += fromCache.dirtyDidntCompile ? 1 : 0; if (this.allowDirtyTranslations) { translations.push(fromCache.translation); } else { remaining.push(snippet); } break; case 'miss': remaining.push(snippet); break; } } return { translations, remaining, infusedCount, dirtyCount, dirtySourceCount, dirtyTranslatorCount, dirtyTypesCount, dirtyDidntCompile, }; } public async translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>; public async translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>; public async translateAll( snippets: TypeScriptSnippet[], optionsOrAddToTablet?: boolean | TranslateAllOptions, ): Promise<TranslateAllResult> { const options = optionsOrAddToTablet && typeof optionsOrAddToTablet === 'object' ? optionsOrAddToTablet : { addToTablet: optionsOrAddToTablet }; const exampleDependencies = collectDependencies(snippets); let compilationDirectory; let cleanCompilationDir = false; if (options?.compilationDirectory) { // If the user provided a directory, we're going to trust-but-confirm. await validateAvailableDependencies(options.compilationDirectory, exampleDependencies); compilationDirectory = options.compilationDirectory; } else { compilationDirectory = await prepareDependencyDirectory(exampleDependencies); cleanCompilationDir = true; } const origDir = process.cwd(); // Easiest way to get a fixed working directory (for sources) in is to chdir process.chdir(compilationDirectory); let result; try { result = await translateAll(snippets, this.includeCompilerDiagnostics); } finally { process.chdir(origDir); if (cleanCompilationDir) { await fs.remove(compilationDirectory); } } const fingerprinted = result.translatedSnippets.map((snippet) => snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())), ); if (options?.addToTablet ?? true) { for (const translation of fingerprinted) { this.tablet.addSnippet(translation); } } return { translatedSnippets: fingerprinted, diagnostics: result.diagnostics, }; } } /** * Try to find the translation for the given snippet in the given cache * * Rules for cacheability are: * - id is the same (== visible source didn't change) * - complete source is the same (== fixture didn't change) * - all types involved have the same fingerprint (== API surface didn't change) * - the versions of all translations match the versions on the available translators (== translator itself didn't change) * * For the versions check: we could have selectively picked some translations * from the cache while performing others. However, since the big work is in * parsing the TypeScript, and the rendering itself is peanutes (assumption), it * doesn't really make a lot of difference. So, for simplification's sake, * we'll regen all translations if there's at least one that's outdated. */ function tryReadFromCache( sourceSnippet: TypeScriptSnippet, cache: LanguageTablet, fingerprinter: TypeFingerprinter, compiledOnly: boolean, ): CacheHit { const fromCache = cache.tryGetSnippet(snippetKey(sourceSnippet)); if (!fromCache) { return { type: 'miss' }; } // infused snippets won't pass the full source check or the fingerprinter // but there is no reason to try to recompile it, so return cached snippet // if there exists one. if (isInfused(sourceSnippet)) { return { type: 'hit', snippet: fromCache, infused: true }; } const dirtySource = completeSource(sourceSnippet) !== fromCache.snippet.fullSource; const dirtyTranslator = !Object.entries(TARGET_LANGUAGES).every( ([lang, translator]) => fromCache.snippet.translations?.[lang]?.version === translator.version, ); const dirtyTypes = fingerprinter.fingerprintAll(fromCache.fqnsReferenced()) !== fromCache.snippet.fqnsFingerprint; const dirtyDidntCompile = compiledOnly && !fromCache.snippet.didCompile; if (dirtySource || dirtyTranslator || dirtyTypes || dirtyDidntCompile) { return { type: 'dirty', translation: fromCache, dirtySource, dirtyTranslator, dirtyTypes, dirtyDidntCompile }; } return { type: 'hit', snippet: fromCache, infused: false }; } export type CacheHit = | { readonly type: 'miss' } | { readonly type: 'hit'; readonly snippet: TranslatedSnippet; readonly infused: boolean } | { readonly type: 'dirty'; readonly translation: TranslatedSnippet; readonly dirtySource: boolean; readonly dirtyTranslator: boolean; readonly dirtyTypes: boolean; readonly dirtyDidntCompile: boolean; }; function isInfused(snippet: TypeScriptSnippet) { return snippet.parameters?.infused !== undefined; } export interface ReadFromCacheResults { /** * Successful translations */ readonly translations: TranslatedSnippet[]; /** * Successful but dirty hits */ readonly remaining: TypeScriptSnippet[]; /** * How many successfully hit translations were infused */ readonly infusedCount: number; readonly dirtyCount: number; // Counts for dirtiness (a single snippet may be dirty for more than one reason) readonly dirtySourceCount: number; readonly dirtyTranslatorCount: number; readonly dirtyTypesCount: number; readonly dirtyDidntCompile: number; } export interface TranslateAllOptions { /** * @default - Create a temporary directory with all necessary packages */ readonly compilationDirectory?: string; /** * @default true */ readonly addToTablet?: boolean; }
the_stack
import Debug = ts.Debug; /** * All the line stuff as it is from session.ts */ const lineCollectionCapacity = 4; export class LineIndex { root: LineNode; // set this to true to check each edit for accuracy checkEdits = false; charOffsetToLineNumberAndPos(charOffset: number) { return this.root.charOffsetToLineNumberAndPos(1, charOffset); } lineNumberToInfo(lineNumber: number): ILineInfo { const lineCount = this.root.lineCount(); if (lineNumber <= lineCount) { const lineInfo = this.root.lineNumberToInfo(lineNumber, 0); lineInfo.line = lineNumber; return lineInfo; } else { return { line: lineNumber, offset: this.root.charCount() }; } } load(lines: string[]) { if (lines.length > 0) { const leaves: LineLeaf[] = []; for (let i = 0, len = lines.length; i < len; i++) { leaves[i] = new LineLeaf(lines[i]); } this.root = LineIndex.buildTreeFromBottom(leaves); } else { this.root = new LineNode(); } } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { this.root.walk(rangeStart, rangeLength, walkFns); } getText(rangeStart: number, rangeLength: number) { let accum = ""; if ((rangeLength > 0) && (rangeStart < this.root.charCount())) { this.walk(rangeStart, rangeLength, { goSubtree: true, done: false, leaf: (relativeStart: number, relativeLength: number, ll: LineLeaf) => { accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); } }); } return accum; } getLength(): number { return this.root.charCount(); } every(f: (ll: LineLeaf, s: number, len: number) => boolean, rangeStart: number, rangeEnd?: number) { if (!rangeEnd) { rangeEnd = this.root.charCount(); } const walkFns = { goSubtree: true, done: false, leaf: function (relativeStart: number, relativeLength: number, ll: LineLeaf) { if (!f(ll, relativeStart, relativeLength)) { this.done = true; } } }; this.walk(rangeStart, rangeEnd - rangeStart, walkFns); return !walkFns.done; } edit(pos: number, deleteLength: number, newText?: string) { function editFlat(source: string, s: number, dl: number, nt = "") { return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { // TODO: assert deleteLength === 0 if (newText) { this.load(LineIndex.linesFromText(newText).lines); return this; } } else { let checkText: string; if (this.checkEdits) { checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); } const walker = new EditWalker(); if (pos >= this.root.charCount()) { // insert at end pos = this.root.charCount() - 1; const endString = this.getText(pos, 1); if (newText) { newText = endString + newText; } else { newText = endString; } deleteLength = 0; walker.suppressTrailingText = true; } else if (deleteLength > 0) { // check whether last characters deleted are line break const e = pos + deleteLength; const lineInfo = this.charOffsetToLineNumberAndPos(e); if ((lineInfo && (lineInfo.offset === 0))) { // move range end just past line that will merge with previous line deleteLength += lineInfo.text.length; // store text by appending to end of insertedText if (newText) { newText = newText + lineInfo.text; } else { newText = lineInfo.text; } } } if (pos < this.root.charCount()) { this.root.walk(pos, deleteLength, walker); walker.insertLines(newText); } if (this.checkEdits) { const updatedText = this.getText(0, this.root.charCount()); Debug.assert(checkText == updatedText, "buffer edit mismatch"); } return walker.lineIndex; } } static buildTreeFromBottom(nodes: LineCollection[]): LineNode { const nodeCount = Math.ceil(nodes.length / lineCollectionCapacity); const interiorNodes: LineNode[] = []; let nodeIndex = 0; for (let i = 0; i < nodeCount; i++) { interiorNodes[i] = new LineNode(); let charCount = 0; let lineCount = 0; for (let j = 0; j < lineCollectionCapacity; j++) { if (nodeIndex < nodes.length) { interiorNodes[i].add(nodes[nodeIndex]); charCount += nodes[nodeIndex].charCount(); lineCount += nodes[nodeIndex].lineCount(); } else { break; } nodeIndex++; } interiorNodes[i].totalChars = charCount; interiorNodes[i].totalLines = lineCount; } if (interiorNodes.length === 1) { return interiorNodes[0]; } else { return this.buildTreeFromBottom(interiorNodes); } } static linesFromText(text: string) { const lineStarts = ts.computeLineStarts(text); if (lineStarts.length === 0) { return { lines: <string[]>[], lineMap: lineStarts }; } const lines = <string[]>new Array(lineStarts.length); const lc = lineStarts.length - 1; for (let lmi = 0; lmi < lc; lmi++) { lines[lmi] = text.substring(lineStarts[lmi], lineStarts[lmi + 1]); } const endText = text.substring(lineStarts[lc]); if (endText.length > 0) { lines[lc] = endText; } else { lines.length--; } return { lines: lines, lineMap: lineStarts }; } } export class LineNode implements LineCollection { totalChars = 0; totalLines = 0; children: LineCollection[] = []; isLeaf() { return false; } updateCounts() { this.totalChars = 0; this.totalLines = 0; for (let i = 0, len = this.children.length; i < len; i++) { const child = this.children[i]; this.totalChars += child.charCount(); this.totalLines += child.lineCount(); } } execWalk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker, childIndex: number, nodeType: CharRangeSection) { if (walkFns.pre) { walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType); } if (walkFns.goSubtree) { this.children[childIndex].walk(rangeStart, rangeLength, walkFns); if (walkFns.post) { walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType); } } else { walkFns.goSubtree = true; } return walkFns.done; } skipChild(relativeStart: number, relativeLength: number, childIndex: number, walkFns: ILineIndexWalker, nodeType: CharRangeSection) { if (walkFns.pre && (!walkFns.done)) { walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType); walkFns.goSubtree = true; } } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) let childIndex = 0; let child = this.children[0]; let childCharCount = child.charCount(); // find sub-tree containing start let adjustedStart = rangeStart; while (adjustedStart >= childCharCount) { this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, CharRangeSection.PreStart); adjustedStart -= childCharCount; child = this.children[++childIndex]; childCharCount = child.charCount(); } // Case I: both start and end of range in same subtree if ((adjustedStart + rangeLength) <= childCharCount) { if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, CharRangeSection.Entire)) { return; } } else { // Case II: start and end of range in different subtrees (possibly with subtrees in the middle) if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, CharRangeSection.Start)) { return; } let adjustedLength = rangeLength - (childCharCount - adjustedStart); child = this.children[++childIndex]; childCharCount = child.charCount(); while (adjustedLength > childCharCount) { if (this.execWalk(0, childCharCount, walkFns, childIndex, CharRangeSection.Mid)) { return; } adjustedLength -= childCharCount; child = this.children[++childIndex]; childCharCount = child.charCount(); } if (adjustedLength > 0) { if (this.execWalk(0, adjustedLength, walkFns, childIndex, CharRangeSection.End)) { return; } } } // Process any subtrees after the one containing range end if (walkFns.pre) { const clen = this.children.length; if (childIndex < (clen - 1)) { for (let ej = childIndex + 1; ej < clen; ej++) { this.skipChild(0, 0, ej, walkFns, CharRangeSection.PostEnd); } } } } charOffsetToLineNumberAndPos(lineNumber: number, charOffset: number): ILineInfo { const childInfo = this.childFromCharOffset(lineNumber, charOffset); if (!childInfo.child) { return { line: lineNumber, offset: charOffset, }; } else if (childInfo.childIndex < this.children.length) { if (childInfo.child.isLeaf()) { return { line: childInfo.lineNumber, offset: childInfo.charOffset, text: (<LineLeaf>(childInfo.child)).text, leaf: (<LineLeaf>(childInfo.child)) }; } else { const lineNode = <LineNode>(childInfo.child); return lineNode.charOffsetToLineNumberAndPos(childInfo.lineNumber, childInfo.charOffset); } } else { const lineInfo = this.lineNumberToInfo(this.lineCount(), 0); return { line: this.lineCount(), offset: lineInfo.leaf.charCount() }; } } lineNumberToInfo(lineNumber: number, charOffset: number): ILineInfo { const childInfo = this.childFromLineNumber(lineNumber, charOffset); if (!childInfo.child) { return { line: lineNumber, offset: charOffset }; } else if (childInfo.child.isLeaf()) { return { line: lineNumber, offset: childInfo.charOffset, text: (<LineLeaf>(childInfo.child)).text, leaf: (<LineLeaf>(childInfo.child)) }; } else { const lineNode = <LineNode>(childInfo.child); return lineNode.lineNumberToInfo(childInfo.relativeLineNumber, childInfo.charOffset); } } childFromLineNumber(lineNumber: number, charOffset: number) { let child: LineCollection; let relativeLineNumber = lineNumber; let i: number; let len: number; for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; const childLineCount = child.lineCount(); if (childLineCount >= relativeLineNumber) { break; } else { relativeLineNumber -= childLineCount; charOffset += child.charCount(); } } return { child: child, childIndex: i, relativeLineNumber: relativeLineNumber, charOffset: charOffset }; } childFromCharOffset(lineNumber: number, charOffset: number) { let child: LineCollection; let i: number; let len: number; for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; if (child.charCount() > charOffset) { break; } else { charOffset -= child.charCount(); lineNumber += child.lineCount(); } } return { child: child, childIndex: i, charOffset: charOffset, lineNumber: lineNumber }; } splitAfter(childIndex: number) { let splitNode: LineNode; const clen = this.children.length; childIndex++; const endLength = childIndex; if (childIndex < clen) { splitNode = new LineNode(); while (childIndex < clen) { splitNode.add(this.children[childIndex++]); } splitNode.updateCounts(); } this.children.length = endLength; return splitNode; } remove(child: LineCollection) { const childIndex = this.findChildIndex(child); const clen = this.children.length; if (childIndex < (clen - 1)) { for (let i = childIndex; i < (clen - 1); i++) { this.children[i] = this.children[i + 1]; } } this.children.length--; } findChildIndex(child: LineCollection) { let childIndex = 0; const clen = this.children.length; while ((this.children[childIndex] !== child) && (childIndex < clen)) childIndex++; return childIndex; } insertAt(child: LineCollection, nodes: LineCollection[]) { let childIndex = this.findChildIndex(child); const clen = this.children.length; const nodeCount = nodes.length; // if child is last and there is more room and only one node to place, place it if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) { this.add(nodes[0]); this.updateCounts(); return []; } else { const shiftNode = this.splitAfter(childIndex); let nodeIndex = 0; childIndex++; while ((childIndex < lineCollectionCapacity) && (nodeIndex < nodeCount)) { this.children[childIndex++] = nodes[nodeIndex++]; } let splitNodes: LineNode[] = []; let splitNodeCount = 0; if (nodeIndex < nodeCount) { splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity); splitNodes = <LineNode[]>new Array(splitNodeCount); let splitNodeIndex = 0; for (let i = 0; i < splitNodeCount; i++) { splitNodes[i] = new LineNode(); } let splitNode = <LineNode>splitNodes[0]; while (nodeIndex < nodeCount) { splitNode.add(nodes[nodeIndex++]); if (splitNode.children.length === lineCollectionCapacity) { splitNodeIndex++; splitNode = <LineNode>splitNodes[splitNodeIndex]; } } for (let i = splitNodes.length - 1; i >= 0; i--) { if (splitNodes[i].children.length === 0) { splitNodes.length--; } } } if (shiftNode) { splitNodes[splitNodes.length] = shiftNode; } this.updateCounts(); for (let i = 0; i < splitNodeCount; i++) { (<LineNode>splitNodes[i]).updateCounts(); } return splitNodes; } } // assume there is room for the item; return true if more room add(collection: LineCollection) { this.children[this.children.length] = collection; return (this.children.length < lineCollectionCapacity); } charCount() { return this.totalChars; } lineCount() { return this.totalLines; } } export class LineLeaf implements LineCollection { udata: any; constructor(public text: string) { } setUdata(data: any) { this.udata = data; } getUdata() { return this.udata; } isLeaf() { return true; } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { walkFns.leaf(rangeStart, rangeLength, this); } charCount() { return this.text.length; } lineCount() { return 1; } } export interface LineCollection { charCount(): number; lineCount(): number; isLeaf(): boolean; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; } export interface ILineInfo { line: number; offset: number; text?: string; leaf?: LineLeaf; } export enum CharRangeSection { PreStart, Start, Entire, Mid, End, PostEnd } export interface ILineIndexWalker { goSubtree: boolean; done: boolean; leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void; pre?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): LineCollection; post?(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineNode, nodeType: CharRangeSection): LineCollection; } class BaseLineIndexWalker implements ILineIndexWalker { goSubtree = true; done = false; leaf(rangeStart: number, rangeLength: number, ll: LineLeaf) { } } class EditWalker extends BaseLineIndexWalker { lineIndex = new LineIndex(); // path to start of range startPath: LineCollection[]; endBranch: LineCollection[] = []; branchNode: LineNode; // path to current node stack: LineNode[]; state = CharRangeSection.Entire; lineCollectionAtBranch: LineCollection; initialText = ""; trailingText = ""; suppressTrailingText = false; constructor() { super(); this.lineIndex.root = new LineNode(); this.startPath = [this.lineIndex.root]; this.stack = [this.lineIndex.root]; } insertLines(insertedText: string) { if (this.suppressTrailingText) { this.trailingText = ""; } if (insertedText) { insertedText = this.initialText + insertedText + this.trailingText; } else { insertedText = this.initialText + this.trailingText; } const lm = LineIndex.linesFromText(insertedText); const lines = lm.lines; if (lines.length > 1) { if (lines[lines.length - 1] == "") { lines.length--; } } let branchParent: LineNode; let lastZeroCount: LineCollection; for (let k = this.endBranch.length - 1; k >= 0; k--) { (<LineNode>this.endBranch[k]).updateCounts(); if (this.endBranch[k].charCount() === 0) { lastZeroCount = this.endBranch[k]; if (k > 0) { branchParent = <LineNode>this.endBranch[k - 1]; } else { branchParent = this.branchNode; } } } if (lastZeroCount) { branchParent.remove(lastZeroCount); } // path at least length two (root and leaf) let insertionNode = <LineNode>this.startPath[this.startPath.length - 2]; const leafNode = <LineLeaf>this.startPath[this.startPath.length - 1]; const len = lines.length; if (len > 0) { leafNode.text = lines[0]; if (len > 1) { let insertedNodes = <LineCollection[]>new Array(len - 1); let startNode = <LineCollection>leafNode; for (let i = 1, len = lines.length; i < len; i++) { insertedNodes[i - 1] = new LineLeaf(lines[i]); } let pathIndex = this.startPath.length - 2; while (pathIndex >= 0) { insertionNode = <LineNode>this.startPath[pathIndex]; insertedNodes = insertionNode.insertAt(startNode, insertedNodes); pathIndex--; startNode = insertionNode; } let insertedNodesLen = insertedNodes.length; while (insertedNodesLen > 0) { const newRoot = new LineNode(); newRoot.add(this.lineIndex.root); insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes); insertedNodesLen = insertedNodes.length; this.lineIndex.root = newRoot; } this.lineIndex.root.updateCounts(); } else { for (let j = this.startPath.length - 2; j >= 0; j--) { (<LineNode>this.startPath[j]).updateCounts(); } } } else { // no content for leaf node, so delete it insertionNode.remove(leafNode); for (let j = this.startPath.length - 2; j >= 0; j--) { (<LineNode>this.startPath[j]).updateCounts(); } } return this.lineIndex; } post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection { // have visited the path for start of range, now looking for end // if range is on single line, we will never make this state transition if (lineCollection === this.lineCollectionAtBranch) { this.state = CharRangeSection.End; } // always pop stack because post only called when child has been visited this.stack.length--; return undefined; } pre(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection) { // currentNode corresponds to parent, but in the new tree const currentNode = this.stack[this.stack.length - 1]; if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) { // if range is on single line, we will never make this state transition this.state = CharRangeSection.Start; this.branchNode = currentNode; this.lineCollectionAtBranch = lineCollection; } let child: LineCollection; function fresh(node: LineCollection): LineCollection { if (node.isLeaf()) { return new LineLeaf(""); } else return new LineNode(); } switch (nodeType) { case CharRangeSection.PreStart: this.goSubtree = false; if (this.state !== CharRangeSection.End) { currentNode.add(lineCollection); } break; case CharRangeSection.Start: if (this.state === CharRangeSection.End) { this.goSubtree = false; } else { child = fresh(lineCollection); currentNode.add(child); this.startPath[this.startPath.length] = child; } break; case CharRangeSection.Entire: if (this.state !== CharRangeSection.End) { child = fresh(lineCollection); currentNode.add(child); this.startPath[this.startPath.length] = child; } else { if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); this.endBranch[this.endBranch.length] = child; } } break; case CharRangeSection.Mid: this.goSubtree = false; break; case CharRangeSection.End: if (this.state !== CharRangeSection.End) { this.goSubtree = false; } else { if (!lineCollection.isLeaf()) { child = fresh(lineCollection); currentNode.add(child); this.endBranch[this.endBranch.length] = child; } } break; case CharRangeSection.PostEnd: this.goSubtree = false; if (this.state !== CharRangeSection.Start) { currentNode.add(lineCollection); } break; } if (this.goSubtree) { this.stack[this.stack.length] = <LineNode>child; } return lineCollection; } // just gather text from the leaves leaf(relativeStart: number, relativeLength: number, ll: LineLeaf) { if (this.state === CharRangeSection.Start) { this.initialText = ll.text.substring(0, relativeStart); } else if (this.state === CharRangeSection.Entire) { this.initialText = ll.text.substring(0, relativeStart); this.trailingText = ll.text.substring(relativeStart + relativeLength); } else { // state is CharRangeSection.End this.trailingText = ll.text.substring(relativeStart + relativeLength); } } }
the_stack
import BN from 'bn.js'; import BigNumber from 'bignumber.js'; import { PromiEvent, TransactionReceipt, EventResponse, EventData, Web3ContractContext, } from 'ethereum-abi-types-generator'; export interface CallOptions { from?: string; gasPrice?: string; gas?: number; } export interface SendOptions { from: string; value?: number | string | BN | BigNumber; gasPrice?: string; gas?: number; } export interface EstimateGasOptions { from?: string; value?: number | string | BN | BigNumber; gas?: number; } export interface MethodPayableReturnContext { send(options: SendOptions): PromiEvent<TransactionReceipt>; send( options: SendOptions, callback: (error: Error, result: any) => void ): PromiEvent<TransactionReceipt>; estimateGas(options: EstimateGasOptions): Promise<number>; estimateGas( options: EstimateGasOptions, callback: (error: Error, result: any) => void ): Promise<number>; encodeABI(): string; } export interface MethodConstantReturnContext<TCallReturn> { call(): Promise<TCallReturn>; call(options: CallOptions): Promise<TCallReturn>; call( options: CallOptions, callback: (error: Error, result: TCallReturn) => void ): Promise<TCallReturn>; encodeABI(): string; } export interface MethodReturnContext extends MethodPayableReturnContext {} export type ContractContext = Web3ContractContext< MultiFeeDistribution, MultiFeeDistributionMethodNames, MultiFeeDistributionEventsContext, MultiFeeDistributionEvents >; export type MultiFeeDistributionEvents = | 'OwnershipTransferred' | 'Recovered' | 'RewardAdded' | 'RewardPaid' | 'RewardsDurationUpdated' | 'Staked' | 'Withdrawn'; export interface MultiFeeDistributionEventsContext { OwnershipTransferred( parameters: { filter?: { previousOwner?: string | string[]; newOwner?: string | string[]; }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Recovered( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardAdded( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardPaid( parameters: { filter?: { user?: string | string[]; rewardsToken?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RewardsDurationUpdated( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Staked( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Withdrawn( parameters: { filter?: { user?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; } export type MultiFeeDistributionMethodNames = | 'new' | 'addReward' | 'approveRewardDistributor' | 'claimableRewards' | 'earnedBalances' | 'exit' | 'getReward' | 'getRewardForDuration' | 'lastTimeRewardApplicable' | 'lockDuration' | 'lockedBalances' | 'lockedSupply' | 'mint' | 'minters' | 'notifyRewardAmount' | 'owner' | 'recoverERC20' | 'renounceOwnership' | 'rewardData' | 'rewardDistributors' | 'rewardPerToken' | 'rewardTokens' | 'rewards' | 'rewardsDuration' | 'stake' | 'stakingToken' | 'totalBalance' | 'totalSupply' | 'transferOwnership' | 'unlockedBalance' | 'userRewardPerTokenPaid' | 'withdraw' | 'withdrawExpiredLocks' | 'withdrawableBalance'; export interface RewardsResponse { token: string; amount: string; } export interface EarningsDataResponse { amount: string; unlockTime: string; } export interface EarnedBalancesResponse { total: string; earningsData: EarningsDataResponse[]; } export interface LockDataResponse { amount: string; unlockTime: string; } export interface LockedBalancesResponse { total: string; unlockable: string; locked: string; lockData: LockDataResponse[]; } export interface RewardDataResponse { periodFinish: string; rewardRate: string; lastUpdateTime: string; rewardPerTokenStored: string; } export interface WithdrawableBalanceResponse { amount: string; penaltyAmount: string; } export interface MultiFeeDistribution { /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: constructor * @param _stakingToken Type: address, Indexed: false * @param _minters Type: address[], Indexed: false */ 'new'(_stakingToken: string, _minters: string[]): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _rewardsToken Type: address, Indexed: false * @param _distributor Type: address, Indexed: false */ addReward(_rewardsToken: string, _distributor: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _rewardsToken Type: address, Indexed: false * @param _distributor Type: address, Indexed: false * @param _approved Type: bool, Indexed: false */ approveRewardDistributor( _rewardsToken: string, _distributor: string, _approved: boolean ): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param account Type: address, Indexed: false */ claimableRewards(account: string): MethodConstantReturnContext<RewardsResponse[]>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param user Type: address, Indexed: false */ earnedBalances(user: string): MethodConstantReturnContext<EarnedBalancesResponse>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ exit(): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ getReward(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param _rewardsToken Type: address, Indexed: false */ getRewardForDuration(_rewardsToken: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param _rewardsToken Type: address, Indexed: false */ lastTimeRewardApplicable(_rewardsToken: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lockDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param user Type: address, Indexed: false */ lockedBalances(user: string): MethodConstantReturnContext<LockedBalancesResponse>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ lockedSupply(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param user Type: address, Indexed: false * @param amount Type: uint256, Indexed: false */ mint(user: string, amount: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ minters(parameter0: string): MethodConstantReturnContext<boolean>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _rewardsToken Type: address, Indexed: false * @param reward Type: uint256, Indexed: false */ notifyRewardAmount(_rewardsToken: string, reward: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ owner(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param tokenAddress Type: address, Indexed: false * @param tokenAmount Type: uint256, Indexed: false */ recoverERC20(tokenAddress: string, tokenAmount: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ renounceOwnership(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false */ rewardData(parameter0: string): MethodConstantReturnContext<RewardDataResponse>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false * @param parameter1 Type: address, Indexed: false */ rewardDistributors(parameter0: string, parameter1: string): MethodConstantReturnContext<boolean>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param _rewardsToken Type: address, Indexed: false */ rewardPerToken(_rewardsToken: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: uint256, Indexed: false */ rewardTokens(parameter0: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false * @param parameter1 Type: address, Indexed: false */ rewards(parameter0: string, parameter1: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ rewardsDuration(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false * @param lock Type: bool, Indexed: false */ stake(amount: string, lock: boolean): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ stakingToken(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param user Type: address, Indexed: false */ totalBalance(user: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ totalSupply(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param newOwner Type: address, Indexed: false */ transferOwnership(newOwner: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param user Type: address, Indexed: false */ unlockedBalance(user: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param parameter0 Type: address, Indexed: false * @param parameter1 Type: address, Indexed: false */ userRewardPerTokenPaid( parameter0: string, parameter1: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false */ withdraw(amount: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ withdrawExpiredLocks(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param user Type: address, Indexed: false */ withdrawableBalance(user: string): MethodConstantReturnContext<WithdrawableBalanceResponse>; }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/policiesMappers"; import * as Parameters from "../models/parameters"; import { BillingManagementClientContext } from "../billingManagementClientContext"; /** Class representing a Policies. */ export class Policies { private readonly client: BillingManagementClientContext; /** * Create a Policies. * @param {BillingManagementClientContext} client Reference to the service client. */ constructor(client: BillingManagementClientContext) { this.client = client; } /** * Lists the policies for a billing profile. This operation is supported only for billing accounts * with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param [options] The optional parameters * @returns Promise<Models.PoliciesGetByBillingProfileResponse> */ getByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase): Promise<Models.PoliciesGetByBillingProfileResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param callback The callback */ getByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.Policy>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param options The optional parameters * @param callback The callback */ getByBillingProfile(billingAccountName: string, billingProfileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Policy>): void; getByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Policy>, callback?: msRest.ServiceCallback<Models.Policy>): Promise<Models.PoliciesGetByBillingProfileResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, options }, getByBillingProfileOperationSpec, callback) as Promise<Models.PoliciesGetByBillingProfileResponse>; } /** * Updates the policies for a billing profile. This operation is supported only for billing * accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param parameters Request parameters that are provided to the update policies operation. * @param [options] The optional parameters * @returns Promise<Models.PoliciesUpdateResponse> */ update(billingAccountName: string, billingProfileName: string, parameters: Models.Policy, options?: msRest.RequestOptionsBase): Promise<Models.PoliciesUpdateResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param parameters Request parameters that are provided to the update policies operation. * @param callback The callback */ update(billingAccountName: string, billingProfileName: string, parameters: Models.Policy, callback: msRest.ServiceCallback<Models.Policy>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param parameters Request parameters that are provided to the update policies operation. * @param options The optional parameters * @param callback The callback */ update(billingAccountName: string, billingProfileName: string, parameters: Models.Policy, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Policy>): void; update(billingAccountName: string, billingProfileName: string, parameters: Models.Policy, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Policy>, callback?: msRest.ServiceCallback<Models.Policy>): Promise<Models.PoliciesUpdateResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, parameters, options }, updateOperationSpec, callback) as Promise<Models.PoliciesUpdateResponse>; } /** * Lists the policies for a customer. This operation is supported only for billing accounts with * agreement type Microsoft Partner Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param [options] The optional parameters * @returns Promise<Models.PoliciesGetByCustomerResponse> */ getByCustomer(billingAccountName: string, customerName: string, options?: msRest.RequestOptionsBase): Promise<Models.PoliciesGetByCustomerResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param callback The callback */ getByCustomer(billingAccountName: string, customerName: string, callback: msRest.ServiceCallback<Models.CustomerPolicy>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param options The optional parameters * @param callback The callback */ getByCustomer(billingAccountName: string, customerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CustomerPolicy>): void; getByCustomer(billingAccountName: string, customerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CustomerPolicy>, callback?: msRest.ServiceCallback<Models.CustomerPolicy>): Promise<Models.PoliciesGetByCustomerResponse> { return this.client.sendOperationRequest( { billingAccountName, customerName, options }, getByCustomerOperationSpec, callback) as Promise<Models.PoliciesGetByCustomerResponse>; } /** * Updates the policies for a customer. This operation is supported only for billing accounts with * agreement type Microsoft Partner Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param [options] The optional parameters * @returns Promise<Models.PoliciesUpdateCustomerResponse> */ updateCustomer(billingAccountName: string, customerName: string, options?: Models.PoliciesUpdateCustomerOptionalParams): Promise<Models.PoliciesUpdateCustomerResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param callback The callback */ updateCustomer(billingAccountName: string, customerName: string, callback: msRest.ServiceCallback<Models.CustomerPolicy>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param options The optional parameters * @param callback The callback */ updateCustomer(billingAccountName: string, customerName: string, options: Models.PoliciesUpdateCustomerOptionalParams, callback: msRest.ServiceCallback<Models.CustomerPolicy>): void; updateCustomer(billingAccountName: string, customerName: string, options?: Models.PoliciesUpdateCustomerOptionalParams | msRest.ServiceCallback<Models.CustomerPolicy>, callback?: msRest.ServiceCallback<Models.CustomerPolicy>): Promise<Models.PoliciesUpdateCustomerResponse> { return this.client.sendOperationRequest( { billingAccountName, customerName, options }, updateCustomerOperationSpec, callback) as Promise<Models.PoliciesUpdateCustomerResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getByBillingProfileOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Policy }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/policies/default", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.Policy, required: true } }, responses: { 200: { bodyMapper: Mappers.Policy }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getByCustomerOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", urlParameters: [ Parameters.billingAccountName, Parameters.customerName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.CustomerPolicy }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateCustomerOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/policies/default", urlParameters: [ Parameters.billingAccountName, Parameters.customerName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { viewCharges: [ "options", "viewCharges" ] }, mapper: { ...Mappers.CustomerPolicy, required: true } }, responses: { 200: { bodyMapper: Mappers.CustomerPolicy }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import assert from '../utils/assert' import { parsePostFromPaste, setClipboardData, parsePostFromDrop } from '../utils/parse-utils' import { filter, forEach } from '../utils/array-utils' import Key from '../utils/key' import TextInputHandler, { TextInputHandlerListener } from '../editor/text-input-handler' import SelectionManager from '../editor/selection-manager' import Browser from '../utils/browser' import Editor, { TextUnit, Format } from './editor' import { Logger } from '../utils/log-manager' import { PartialSelection } from '../utils/selection-utils' const ELEMENT_EVENT_TYPES = <const>[ 'keydown', 'keyup', 'cut', 'copy', 'paste', 'keypress', 'drop', 'compositionstart', 'compositionend', ] declare global { interface HTMLElementEventMap { compositionstart: CompositionEvent compositionend: CompositionEvent } } export type DOMEventType = typeof ELEMENT_EVENT_TYPES[number] export type DOMEventForType<T extends DOMEventType> = HTMLElementEventMap[T] export type DOMEvent = HTMLElementEventMap[DOMEventType] interface ModifierKeys { shift: boolean } type EventManagerListener = [ HTMLElement, DOMEventType, (event: CompositionEvent | KeyboardEvent | ClipboardEvent | DragEvent) => void ] export default class EventManager { editor: Editor logger: Logger modifierKeys: ModifierKeys started: boolean _isComposingOnBlankLine: boolean _listeners: EventManagerListener[] _textInputHandler: TextInputHandler _selectionManager: SelectionManager constructor(editor: Editor) { this.editor = editor this.logger = editor.loggerFor('event-manager') this._textInputHandler = new TextInputHandler(editor) this._listeners = [] this.modifierKeys = { shift: false, } this._selectionManager = new SelectionManager(this.editor, this.selectionDidChange.bind(this)) this.started = true this._isComposingOnBlankLine = false } init() { let { editor: { element }, } = this assert(`Cannot init EventManager without element`, !!element) ELEMENT_EVENT_TYPES.forEach(type => { this._addListener(element, type) }) this._selectionManager.start() } start() { this.started = true } stop() { this.started = false } registerInputHandler(inputHandler: TextInputHandlerListener) { this._textInputHandler.register(inputHandler) } unregisterInputHandler(name: string) { this._textInputHandler.unregister(name) } unregisterAllTextInputHandlers() { this._textInputHandler.destroy() this._textInputHandler = new TextInputHandler(this.editor) } _addListener(context: HTMLElement, type: DOMEventType) { assert(`Missing listener for ${type}`, !!this[type]) let listener: (event: DOMEventForType<typeof type>) => void = event => this._handleEvent(type, event) context.addEventListener(type, listener) this._listeners.push([context, type, listener]) } _removeListeners() { this._listeners.forEach(([context, type, listener]) => { context.removeEventListener(type, listener) }) this._listeners = [] } // This is primarily useful for programmatically simulating events on the // editor from the tests. _trigger(context: HTMLElement, type: DOMEventType, event: DOMEventForType<typeof type>) { forEach( filter(this._listeners, ([_context, _type]) => { return _context === context && _type === type }), ([context, , listener]) => { listener.call(context, event) } ) } destroy() { this._textInputHandler.destroy() this._selectionManager.destroy() this._removeListeners() } _handleEvent(type: DOMEventType, event: DOMEventForType<typeof type>) { let { target: element } = event if (!this.started) { // abort handling this event return true } if (!this.isElementAddressable(element! as HTMLElement)) { // abort handling this event return true } ;(this[type] as (evt: typeof event) => void)(event) } isElementAddressable(element: Node) { return this.editor.cursor.isAddressable(element) } selectionDidChange(selection: PartialSelection /*, prevSelection */) { let shouldNotify = true let { anchorNode } = selection if (!this.isElementAddressable(anchorNode!)) { if (!this.editor.range.isBlank) { // Selection changed from something addressable to something // not-addressable -- e.g., blur event, user clicked outside editor, // etc shouldNotify = true } else { // selection changes wholly outside the editor should not trigger // change notifications shouldNotify = false } } if (shouldNotify) { this.editor._readRangeFromDOM() } } keypress(event: KeyboardEvent) { let { editor, _textInputHandler } = this if (!editor.hasCursor()) { return } let key = Key.fromEvent(event) if (!key.isPrintable()) { return } else { event.preventDefault() } // Handle carriage returns if (!key.isEnter() && key.keyCode === 13) { _textInputHandler.handleNewLine() editor.handleNewline(event) return } _textInputHandler.handle(key.toString()) } keydown(event: KeyboardEvent) { let { editor } = this if (!editor.hasCursor()) { return } if (!editor.isEditable) { return } let key = Key.fromEvent(event) this._updateModifiersFromKey(key, { isDown: true }) if (editor.handleKeyCommand(event)) { return } if (editor.post.isBlank) { editor._insertEmptyMarkupSectionAtCursor() } let range = editor.range switch (true) { // Ignore keydown events when using an IME case key.isIME(): { break } // FIXME This should be restricted to only card/atom boundaries case key.isHorizontalArrowWithoutModifiersOtherThanShift(): { let newRange if (key.isShift()) { newRange = range.extend(key.direction * 1) } else { newRange = range.move(key.direction) } editor.selectRange(newRange) event.preventDefault() break } case key.isDelete(): { let { direction } = key let unit = TextUnit.CHAR if (key.altKey && Browser.isMac()) { unit = TextUnit.WORD } else if (key.ctrlKey && !Browser.isMac()) { unit = TextUnit.WORD } editor.performDelete({ direction, unit }) event.preventDefault() break } case key.isEnter(): this._textInputHandler.handleNewLine() editor.handleNewline(event) break case key.isTab(): // Handle tab here because it does not fire a `keypress` event event.preventDefault() this._textInputHandler.handle(key.toString()) break } } keyup(event: KeyboardEvent) { let { editor } = this if (!editor.hasCursor()) { return } let key = Key.fromEvent(event) this._updateModifiersFromKey(key, { isDown: false }) } // The mutation handler interferes with IMEs when composing // on a blank line. These two event handlers are for suppressing // mutation handling in this scenario. compositionstart(_event: KeyboardEvent) { let { editor } = this // Ignore compositionstart if not on a blank line if (editor.range.headMarker) { return } this._isComposingOnBlankLine = true if (editor.post.isBlank) { editor._insertEmptyMarkupSectionAtCursor() } // Stop listening for mutations on Chrome browsers and suppress // mutations by prepending a character for other browsers. // The reason why we treat these separately is because // of the way each browser processes IME inputs. if (Browser.isChrome()) { editor.setPlaceholder('') editor._mutationHandler.stopObserving() } else { this._textInputHandler.handle(' ') } } compositionend(event: CompositionEvent) { const { editor } = this // Ignore compositionend if not composing on blank line if (!this._isComposingOnBlankLine) { return } this._isComposingOnBlankLine = false // Start listening for mutations on Chrome browsers and // delete the prepended character introduced by compositionstart // for other browsers. if (Browser.isChrome()) { editor.insertText(event.data) editor.setPlaceholder(editor.placeholder) editor._mutationHandler.startObserving() } else { let startOfCompositionLine = editor.range.headSection!.toPosition(0) let endOfCompositionLine = editor.range.headSection!.toPosition(event.data.length) editor.run(postEditor => { postEditor.deleteAtPosition(startOfCompositionLine, 1, { unit: TextUnit.CHAR }) postEditor.setRange(endOfCompositionLine) }) } } cut(event: ClipboardEvent) { event.preventDefault() this.copy(event) this.editor.performDelete() } copy(event: ClipboardEvent) { event.preventDefault() let { editor, editor: { range, post }, } = this post = post.trimTo(range) let data = { html: editor.serializePost(post, Format.HTML), text: editor.serializePost(post, Format.TEXT), mobiledoc: editor.serializePost(post, Format.MOBILEDOC), } editor.runCallbacks('willCopy', [data]) setClipboardData(event, data, window) } paste(event: ClipboardEvent) { event.preventDefault() let { editor } = this let range = editor.range if (!range.isCollapsed) { editor.performDelete() } if (editor.post.isBlank) { editor._insertEmptyMarkupSectionAtCursor() } let position = editor.range.head let targetFormat = this.modifierKeys.shift ? 'text' : 'html' let pastedPost = parsePostFromPaste(event, editor, { targetFormat }) editor.run(postEditor => { let nextPosition = postEditor.insertPost(position, pastedPost!) postEditor.setRange(nextPosition) }) } drop(event: DragEvent) { event.preventDefault() let { clientX: x, clientY: y } = event let { editor } = this let position = editor.positionAtPoint(x, y) if (!position) { this.logger.log('Could not find drop position') return } let post = parsePostFromDrop(event, editor, { logger: this.logger }) if (!post) { this.logger.log('Could not determine post from drop event') return } editor.run(postEditor => { let nextPosition = postEditor.insertPost(position!, post!) postEditor.setRange(nextPosition) }) } _updateModifiersFromKey(key: Key, { isDown }: { isDown: boolean }) { if (key.isShiftKey()) { this.modifierKeys.shift = isDown } } }
the_stack
import { Glue42Core } from "../../../../glue"; import ClientRepository from "../../client/repository"; import { ServerMethodsPair } from "../../client/types"; import * as GW3Messages from "./messages"; import { SubscriptionCancelledMessage, EventMessage, SubscribedMessage, ErrorSubscribingMessage } from "./messages"; import { SubscribeError, SubscriptionInner } from "../../types"; import { Logger } from "../../../logger/logger"; import { UserSubscription } from "./subscription"; const STATUS_AWAITING_ACCEPT = "awaitingAccept"; // not even one server has accepted yet const STATUS_SUBSCRIBED = "subscribed"; // at least one server has responded as 'Accepting' const ERR_MSG_SUB_FAILED = "Subscription failed."; const ERR_MSG_SUB_REJECTED = "Subscription rejected."; const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; /** * Handles registering methods and sending data to clients */ export default class ClientStreaming { private subscriptionsList: { [key: number]: SubscriptionInner } = {}; private subscriptionIdToLocalKeyMap: { [key: string]: number } = {}; private nextSubLocalKey = 0; constructor(private session: Glue42Core.Connection.GW3DomainSession, private repository: ClientRepository, private logger: Logger) { session.on("subscribed", this.handleSubscribed); session.on("event", this.handleEventData); session.on("subscription-cancelled", this.handleSubscriptionCancelled); } public subscribe(streamingMethod: Glue42Core.AGM.MethodDefinition, params: Glue42Core.AGM.SubscriptionParams, targetServers: ServerMethodsPair[], success: (sub: Glue42Core.AGM.Subscription) => void, error: (err: SubscribeError) => void, existingSub: SubscriptionInner) { if (targetServers.length === 0) { error({ method: streamingMethod, called_with: params.arguments, message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", }); return; } // Note: used to find the subscription in subList. Do not confuse it with the gw-generated subscription_id const subLocalKey = this.getNextSubscriptionLocalKey(); const pendingSub = this.registerSubscription( subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub ); if (typeof pendingSub !== "object") { error({ method: streamingMethod, called_with: params.arguments, message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", }); return; } targetServers.forEach((target) => { const serverId = target.server.id; const method = target.methods.find((m) => m.name === streamingMethod.name); if (!method) { this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); return; } pendingSub.trackedServers.push({ serverId, subscriptionId: undefined, }); const msg: GW3Messages.SubscribeMessage = { type: "subscribe", server_id: serverId, method_id: method.gatewayId, arguments_kv: params.arguments, }; this.session.send<SubscribedMessage>(msg, { serverId, subLocalKey }) .then((m: SubscribedMessage) => this.handleSubscribed(m)) .catch((err: ErrorSubscribingMessage) => this.handleErrorSubscribing(err)); }); } public drainSubscriptions() { const existing = Object.values(this.subscriptionsList); this.subscriptionsList = {}; this.subscriptionIdToLocalKeyMap = {}; return existing; } private getNextSubscriptionLocalKey() { const current = this.nextSubLocalKey; this.nextSubLocalKey += 1; return current; } // This adds subscription and after timeout (30000 default) removes it if it isn't STATUS_SUBSCRIBED private registerSubscription(subLocalKey: number, method: Glue42Core.AGM.MethodDefinition, params: Glue42Core.Interop.SubscriptionParams, success: (sub: Glue42Core.AGM.Subscription) => void, error: (err: SubscribeError) => void, timeout: number, existingSub: SubscriptionInner) { const subsInfo: SubscriptionInner = { localKey: subLocalKey, status: STATUS_AWAITING_ACCEPT, method, params, success, error, trackedServers: [], handlers: { onData: existingSub?.handlers.onData || [], onClosed: existingSub?.handlers.onClosed || [], onConnected: existingSub?.handlers.onConnected || [], // onFailed: [] }, queued: { data: [], closers: [], }, timeoutId: undefined, close: () => this.closeSubscription(subLocalKey), subscription: existingSub?.subscription // only when re-connecting }; if (!existingSub) { if (params.onData) { subsInfo.handlers.onData.push(params.onData); } if (params.onClosed) { subsInfo.handlers.onClosed.push(params.onClosed); } if (params.onConnected) { subsInfo.handlers.onConnected.push(params.onConnected); } } this.subscriptionsList[subLocalKey] = subsInfo; subsInfo.timeoutId = setTimeout(() => { if (this.subscriptionsList[subLocalKey] === undefined) { return; // no such subscription } const pendingSub = this.subscriptionsList[subLocalKey]; if (pendingSub.status === STATUS_AWAITING_ACCEPT) { error({ method, called_with: params.arguments, message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", }); // None of the target servers has answered the subscription attempt delete this.subscriptionsList[subLocalKey]; } else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { // Clean the trackedServers, removing those without valid streamId pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { return (typeof server.subscriptionId !== "undefined"); }); delete pendingSub.timeoutId; if (pendingSub.trackedServers.length <= 0) { // There are no open streams, some servers accepted then closed very quickly // (that's why the status changed but there's no good server with a StreamId) // call the onClosed handlers this.callOnClosedHandlers(pendingSub); delete this.subscriptionsList[subLocalKey]; } } }, timeout); return subsInfo; } private handleErrorSubscribing = (errorResponse: ErrorSubscribingMessage) => { const tag = errorResponse._tag; const subLocalKey = tag.subLocalKey; const pendingSub = this.subscriptionsList[subLocalKey]; if (typeof pendingSub !== "object") { return; } pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { return server.serverId !== tag.serverId; }); if (pendingSub.trackedServers.length <= 0) { clearTimeout(pendingSub.timeoutId); if (pendingSub.status === STATUS_AWAITING_ACCEPT) { // Reject with reason const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? ' Publisher said "' + errorResponse.reason + '".' : " No reason given."; const callArgs = typeof pendingSub.params.arguments === "object" ? JSON.stringify(pendingSub.params.arguments) : "{}"; pendingSub.error({ message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, called_with: pendingSub.params.arguments, method: pendingSub.method, }); } else if (pendingSub.status === STATUS_SUBSCRIBED) { // The timeout may or may not have expired yet, // but the status is 'subscribed' and trackedServers is now empty this.callOnClosedHandlers(pendingSub); } delete this.subscriptionsList[subLocalKey]; } } private handleSubscribed = (msg: SubscribedMessage) => { const subLocalKey = msg._tag.subLocalKey; const pendingSub = this.subscriptionsList[subLocalKey]; if (typeof pendingSub !== "object") { return; } const serverId = msg._tag.serverId; // Add a subscription_id to this trackedServer const acceptingServer = pendingSub.trackedServers .filter((server) => { return server.serverId === serverId; })[0]; if (typeof acceptingServer !== "object") { return; } acceptingServer.subscriptionId = msg.subscription_id; this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); pendingSub.status = STATUS_SUBSCRIBED; if (isFirstResponse) { let reconnect: boolean = false; let sub = pendingSub.subscription; if (sub) { // re-connect case, we already have subscription object sub.setNewSubscription(pendingSub); pendingSub.success(sub); reconnect = true; } else { sub = new UserSubscription(this.repository, pendingSub); pendingSub.subscription = sub; // Pass in the subscription object pendingSub.success(sub); } for (const handler of pendingSub.handlers.onConnected) { try { handler(sub.serverInstance, reconnect); } catch (e) { // DO nothing } } } } private handleEventData = (msg: EventMessage) => { const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; if (typeof subLocalKey === "undefined") { return; } const subscription = this.subscriptionsList[subLocalKey]; if (typeof subscription !== "object") { return; } const trackedServersFound = subscription.trackedServers.filter((server) => { return server.subscriptionId === msg.subscription_id; }); if (trackedServersFound.length !== 1) { return; } // out_of_band. (main stream band) const isPrivateData = msg.oob; const sendingServerId = trackedServersFound[0].serverId; // Create the arrivedData object, new object for each handler call const receivedStreamData = (): Glue42Core.AGM.StreamData => { return { data: msg.data, server: this.repository.getServerById(sendingServerId).instance, requestArguments: subscription.params.arguments, message: undefined, private: isPrivateData, }; }; const onDataHandlers = subscription.handlers.onData; const queuedData = subscription.queued.data; if (onDataHandlers.length > 0) { onDataHandlers.forEach((callback) => { if (typeof callback === "function") { callback(receivedStreamData()); } }); } else { queuedData.push(receivedStreamData()); } } // called only on stream.close() multiple times for each subscription private handleSubscriptionCancelled = (msg: SubscriptionCancelledMessage) => { const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; if (typeof subLocalKey === "undefined") { return; } const subscription = this.subscriptionsList[subLocalKey]; if (typeof subscription !== "object") { return; } // Filter tracked servers const expectedNewLength = subscription.trackedServers.length - 1; subscription.trackedServers = subscription.trackedServers.filter((server) => { if (server.subscriptionId === msg.subscription_id) { subscription.queued.closers.push(server.serverId); return false; } else { return true; } }); // Check if a server was actually removed if (subscription.trackedServers.length !== expectedNewLength) { // TODO: Log some error return; } // Check if this was the last remaining server if (subscription.trackedServers.length <= 0) { clearTimeout(subscription.timeoutId); this.callOnClosedHandlers(subscription); delete this.subscriptionsList[subLocalKey]; } delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; } private callOnClosedHandlers(subscription: SubscriptionInner, reason?: string) { const closersCount = subscription.queued.closers.length; const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; let closingServer: Glue42Core.AGM.Instance; if (closingServerId !== undefined && typeof closingServerId === "string") { closingServer = this.repository.getServerById(closingServerId).instance; } subscription.handlers.onClosed.forEach((callback) => { if (typeof callback !== "function") { return; } callback({ message: reason || ON_CLOSE_MSG_SERVER_INIT, requestArguments: subscription.params.arguments || {}, server: closingServer, stream: subscription.method, }); }); } // called on client/server close (not on stream.close) private closeSubscription(subLocalKey: number) { const subscription = this.subscriptionsList[subLocalKey]; if (typeof subscription !== "object") { return; } // Tell each server that we're unsubscribing subscription.trackedServers.forEach((server) => { if (typeof server.subscriptionId === "undefined") { return; } subscription.queued.closers.push(server.serverId); this.session.sendFireAndForget({ type: "unsubscribe", subscription_id: server.subscriptionId, reason_uri: "", reason: ON_CLOSE_MSG_CLIENT_INIT, }); delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; }); subscription.trackedServers = []; this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); delete this.subscriptionsList[subLocalKey]; } }
the_stack
import { assert } from "chai"; import { Client, getClient } from "@azure-rest/core-client"; import { getLongRunningPoller } from "../src/getLongRunningHelper"; import { PipelineResponse, createHttpHeaders, HttpHeaders, HttpMethods, } from "@azure/core-rest-pipeline"; import { URL } from "./utils/url"; describe("LRO helper", () => { let client: Client; beforeEach(() => { client = getClient("http://localhost:3000", { allowInsecureConnection: true }); client.pipeline.getOrderedPolicies().forEach(({ name }) => { client.pipeline.removePolicy({ name }); }); }); it("LROs_put200Succeeded", async () => { // Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. const expectedBody = { properties: { provisioningState: "Succeeded" }, id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/200/succeeded", method: "PUT", response: { status: 200, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/200/succeeded").put(); const poller = getLongRunningPoller(client, initialResponse); const result = await poller.pollUntilDone(); assert.equal(result.status, "200"); assert.deepEqual(result.body, expectedBody); }); it("LROs_put201Succeeded", async () => { // Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. const expectedBody = { properties: { provisioningState: "Succeeded" }, id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/201/succeeded", method: "PUT", response: { status: 201, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/201/succeeded").put(); const poller = getLongRunningPoller(client, initialResponse); const result = await poller.pollUntilDone(); assert.equal(result.status, "201"); assert.deepEqual(result.body, expectedBody); }); it("LROs_post202List", async () => { // Long running put request, service returns a 202 with empty body to first request, returns a 200 with body [{ 'id': '100', 'name': 'foo' }]. const expectedBody = [{ id: "100", name: "foo" }]; mockResponse(client, [ { path: "/lro/list", method: "POST", response: { status: 202, headers: createHttpHeaders({ // Set the location for polling "azure-asyncoperation": "http://localhost:3000/lro/list/pollingGet", // Set location for getting the result once polling finished location: "http://localhost:3000/lro/list/finalGet", }), }, }, { path: "/lro/list/pollingGet", method: "GET", response: { status: 200, body: { status: "Succeeded" } }, }, { path: "/lro/list/finalGet", method: "GET", response: { status: 200, body: expectedBody } }, ]); const initialResponse = await client.pathUnchecked("/lro/list").post(); const poller = getLongRunningPoller(client, initialResponse, { intervalInMs: 1 }); const result = await poller.pollUntilDone(); assert.equal(result.status, "200"); assert.deepEqual(result.body, expectedBody); }); it("LROs_put200SucceededNoState", async () => { // Long running put request, service returns a 200 to the initial request, with an entity that does not contain ProvisioningState=’Succeeded’. const expectedBody = { id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/200/succeeded/nostate", method: "PUT", response: { status: 200, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/200/succeeded/nostate").put(); const poller = getLongRunningPoller(client, initialResponse); const result = await poller.pollUntilDone(); assert.equal(result.status, "200"); assert.deepEqual(result.body, expectedBody); }); it("LROs_put200UpdatingSucceeded200", async () => { // Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Updating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ const expectedBody = { properties: { provisioningState: "Succeeded" }, id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/200/updating/succeeded/200", method: "PUT", response: { status: 200, body: { properties: { provisioningState: "Updating" }, id: "100", name: "foo" }, }, }, { path: "/lro/put/200/updating/succeeded/200", method: "GET", response: { status: 200, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/200/updating/succeeded/200").put(); const poller = getLongRunningPoller(client, initialResponse, { intervalInMs: 1 }); const result = await poller.pollUntilDone(); assert.equal(result.status, "200"); assert.deepEqual(result.body, expectedBody); }); it("LROs_put201CreatingFailed200", async () => { // Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ const expectedBody = { "properties": { "provisioningState": "Succeeded"}, "id": "100", "name": "foo" } const expectedBody = { properties: { provisioningState: "Failed" }, id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/201/created/failed/200", method: "PUT", response: { status: 201, body: { properties: { provisioningState: "Created" }, id: "100", name: "foo" }, }, }, { path: "/lro/put/201/created/failed/200", method: "GET", response: { status: 200, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/201/created/failed/200").put(); const poller = getLongRunningPoller(client, initialResponse, { intervalInMs: 1 }); try { await poller.pollUntilDone(); assert.fail("Expected exception"); } catch (error) { assert.equal( error.message, "The long running operation has failed. The provisioning state: failed." ); } }); it("LROs_put200Acceptedcanceled200", async () => { // Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ const expectedBody = { "properties": { "provisioningState": "Succeeded"}, "id": "100", "name": "foo" } const expectedBody = { properties: { provisioningState: "canceled" }, id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/200/accepted/canceled/200", method: "PUT", response: { status: 200, body: { properties: { provisioningState: "Accepted" }, id: "100", name: "foo" }, }, }, { path: "/lro/put/200/accepted/canceled/200", method: "GET", response: { status: 200, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/200/accepted/canceled/200").put(); const poller = getLongRunningPoller(client, initialResponse, { intervalInMs: 1 }); try { await poller.pollUntilDone(); assert.fail("Expected exception"); } catch (error) { assert.equal( error.message, "The long running operation has failed. The provisioning state: canceled." ); } }); it("LROPutNoHeaderInRetry", async () => { // Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ const expectedBody = { "properties": { "provisioningState": "Succeeded"}, "id": "100", "name": "foo" } const expectedBody = { properties: { provisioningState: "Succeeded" }, id: "100", name: "foo" }; mockResponse(client, [ { path: "/lro/put/noheader/202/200", method: "PUT", response: { status: 200, body: { properties: { provisioningState: "Accepted" }, id: "100", name: "foo" }, headers: createHttpHeaders({ location: "http://localhost:3000/lro/put/noheader/operationresults", }), }, }, { path: "/lro/put/noheader/operationresults", method: "GET", response: { status: 202 } }, { path: "/lro/put/noheader/operationresults", method: "GET", response: { status: 200, body: expectedBody }, }, ]); const initialResponse = await client.pathUnchecked("/lro/put/noheader/202/200").put(); const poller = getLongRunningPoller(client, initialResponse, { intervalInMs: 1 }); const result = await poller.pollUntilDone(); assert.equal(result.status, "200"); assert.deepEqual(result.body, expectedBody); }); }); interface MockResponse { path: string; method: HttpMethods; response: { status: number; body?: any; headers?: HttpHeaders; }; } /** * Creates a pipeline with a mocked service call * @param client - client to mock requests for * @param response - Responses to return, the actual request url is matched to one of the paths in the responses and the defined object is returned. * if no path matches a 404 error is returned */ function mockResponse(client: Client, responses: MockResponse[]) { let count = 0; client.pipeline.addPolicy({ name: "mockClient", sendRequest: async (request, _next): Promise<PipelineResponse> => { if (count < responses.length) { count++; } const path = new URL(request.url).pathname; let responseIndex = -1; const response = responses.find((r, index) => { const match = r.path === path && r.method.toLocaleLowerCase() === request.method.toLocaleLowerCase(); if (match) { responseIndex = index; } return match; }); if (!response) { console.warn(`Didn't find a match for path ${path} and method: ${request.method}`); return { headers: createHttpHeaders(), request, status: 404, }; } const { body, status } = response.response; const bodyAsText = JSON.stringify(body); // remove the matched response from the list to avoid matching it again responses.splice(responseIndex, 1); return { headers: response.response.headers ?? createHttpHeaders(), request, status, bodyAsText, }; }, }); }
the_stack
import * as parser from '@babel/parser'; import generate from '@babel/generator'; import traverse, { NodePath } from '@babel/traverse'; import * as t from '@babel/types'; import { isIdentifier, Node } from '@babel/types'; import { OrderedSet } from './OrderedSet'; import { IScope } from '../types'; export class ParseError extends Error { readonly expr: string | t.Expression; readonly detail: unknown; constructor(expr: string | t.Expression, detail: unknown) { super(`Failed to parse expression "${typeof expr === 'string' ? expr : generate(expr)}"`); this.expr = expr; this.detail = detail; Object.setPrototypeOf(this, new.target.prototype); } } const MAYBE_EXPRESSIONS: { [k in Node['type']]?: { // fields: Array<keyof (Node & { type: k })> fields: string[] | ((node: Node) => string[]); }; } = { ArrayExpression: { fields: ['elements'] }, AssignmentExpression: { fields: ['left', 'right'] }, BinaryExpression: { fields: ['left', 'right'] }, CallExpression: { fields: ['arguments', 'callee'] }, ConditionalExpression: { fields: ['test', 'consequent', 'alternate'] }, DoWhileStatement: { fields: ['test'] }, ExpressionStatement: { fields: ['expression'] }, ForInStatement: { fields: ['right'] }, ForStatement: { fields: ['init', 'test', 'update'] }, IfStatement: { fields: ['test'] }, LogicalExpression: { fields: ['left', 'right'] }, MemberExpression: { fields: (node) => { return node.type === 'MemberExpression' && node.computed ? ['object', 'property'] : ['object']; }, }, NewExpression: { fields: ['callee', 'arguments'] }, ObjectMethod: { fields: (node) => { return node.type === 'ObjectMethod' && node.computed ? ['key'] : []; }, }, ObjectProperty: { fields: (node) => { return node.type === 'ObjectProperty' && node.computed ? ['key', 'value'] : ['value']; }, }, ReturnStatement: { fields: ['argument'] }, SequenceExpression: { fields: ['expressions'] }, ParenthesizedExpression: { fields: ['expression'] }, SwitchCase: { fields: ['test'] }, SwitchStatement: { fields: ['discriminant'] }, ThrowStatement: { fields: ['argument'] }, UnaryExpression: { fields: ['argument'] }, UpdateExpression: { fields: ['argument'] }, VariableDeclarator: { fields: ['init'] }, WhileStatement: { fields: ['test'] }, WithStatement: { fields: ['object'] }, AssignmentPattern: { fields: ['right'] }, ArrowFunctionExpression: { fields: ['body'] }, ClassExpression: { fields: ['superClass'] }, ClassDeclaration: { fields: ['superClass'] }, ExportDefaultDeclaration: { fields: ['declaration'] }, ForOfStatement: { fields: ['right'] }, ClassMethod: { fields: (node) => { return node.type === 'ClassMethod' && node.computed ? ['key'] : []; }, }, SpreadElement: { fields: ['argument'] }, TaggedTemplateExpression: { fields: ['tag'] }, TemplateLiteral: { fields: ['expressions'] }, YieldExpression: { fields: ['argument'] }, AwaitExpression: { fields: ['argument'] }, OptionalMemberExpression: { fields: (node) => { return node.type === 'OptionalMemberExpression' && node.computed ? ['object', 'property'] : ['object']; }, }, OptionalCallExpression: { fields: ['callee', 'arguments'] }, JSXSpreadAttribute: { fields: ['argument'] }, BindExpression: { fields: ['object', 'callee'] }, ClassProperty: { fields: (node) => { return node.type === 'ClassProperty' && node.computed ? ['key', 'value'] : ['value']; }, }, PipelineTopicExpression: { fields: ['expression'] }, PipelineBareFunction: { fields: ['callee'] }, ClassPrivateProperty: { fields: ['value'] }, Decorator: { fields: ['expression'] }, TupleExpression: { fields: ['elements'] }, TSDeclareMethod: { fields: (node) => { return node.type === 'TSDeclareMethod' && node.computed ? ['key'] : []; }, }, TSPropertySignature: { fields: (node) => { return node.type === 'TSPropertySignature' && node.computed ? ['key', 'initializer'] : ['initializer']; }, }, TSMethodSignature: { fields: (node) => { return node.type === 'TSMethodSignature' && node.computed ? ['key'] : []; }, }, TSAsExpression: { fields: ['expression'] }, TSTypeAssertion: { fields: ['expression'] }, TSEnumDeclaration: { fields: ['initializer'] }, TSEnumMember: { fields: ['initializer'] }, TSNonNullExpression: { fields: ['expression'] }, TSExportAssignment: { fields: ['expression'] }, }; export interface ParseExpressionGetGlobalVariablesOptions { filter?: (varName: string) => boolean; } const CROSS_THIS_SCOPE_TYPE_NODE: { [k in Node['type']]?: boolean; } = { ArrowFunctionExpression: false, // 箭头函数不跨越 this 的 scope FunctionExpression: true, FunctionDeclaration: true, // FunctionTypeAnnotation: false, // 这是 TS 定义 // FunctionTypeParam: false, // 这是 TS 定义 ClassDeclaration: true, ClassExpression: true, ClassBody: true, ClassImplements: true, ClassMethod: true, ClassPrivateMethod: true, ClassProperty: true, ClassPrivateProperty: true, DeclareClass: true, }; const JS_KEYWORDS = ['arguments', 'this', 'super']; export function parseExpressionGetKeywords(expr: string | null | undefined): string[] { if (!expr) { return []; } try { const keywordVars = new OrderedSet<string>(); const ast = parser.parse(`!(${expr});`); const addIdentifierIfNeeded = (x: Record<string, unknown> | number | null | undefined) => { if (typeof x === 'object' && isIdentifier(x) && JS_KEYWORDS.includes(x.name)) { keywordVars.add(x.name); } }; traverse(ast, { enter(path) { const { node } = path; const expressionFields = MAYBE_EXPRESSIONS[node.type]?.fields; if (expressionFields) { (typeof expressionFields === 'function' ? expressionFields(node) : expressionFields ).forEach((fieldName) => { const fieldValue = node[fieldName as keyof typeof node]; if (typeof fieldValue === 'object') { if (Array.isArray(fieldValue)) { fieldValue.forEach((item) => { addIdentifierIfNeeded(item); }); } else { addIdentifierIfNeeded(fieldValue as Record<string, unknown> | null); } } }); } }, }); return keywordVars.toArray().filter(Boolean); } catch (e) { throw new ParseError(expr, e); } } export function parseExpressionGetGlobalVariables( expr: string | null | undefined, { filter = () => true }: ParseExpressionGetGlobalVariablesOptions = {}, ): string[] { if (!expr) { return []; } try { const undeclaredVars = new OrderedSet<string>(); const ast = parser.parse(`!(${expr});`); const addUndeclaredIdentifierIfNeeded = ( x: Record<string, unknown> | number | null | undefined, path: NodePath<Node>, ) => { if (typeof x === 'object' && isIdentifier(x) && !path.scope.hasBinding(x.name)) { undeclaredVars.add(x.name); } }; traverse(ast, { enter(path) { const { node } = path; const expressionFields = MAYBE_EXPRESSIONS[node.type]?.fields; if (expressionFields) { (typeof expressionFields === 'function' ? expressionFields(node) : expressionFields ).forEach((fieldName) => { const fieldValue = node[fieldName as keyof typeof node]; if (typeof fieldValue === 'object') { if (Array.isArray(fieldValue)) { fieldValue.forEach((item) => { addUndeclaredIdentifierIfNeeded(item, path); }); } else { addUndeclaredIdentifierIfNeeded(fieldValue as Record<string, unknown> | null, path); } } }); } }, }); return undeclaredVars.toArray().filter(filter); } catch (e) { throw new ParseError(expr, e); } } export function parseExpressionConvertThis2Context( expr: string | t.Expression, contextName = '__$$context', localVariables: string[] = [], ): string { if (!expr) { return expr; } try { const exprAst = typeof expr === 'string' ? parser.parseExpression(expr) : expr; const exprWrapAst = t.expressionStatement(exprAst); const fileAst = t.file(t.program([exprWrapAst])); const localVariablesSet = new Set(localVariables); let thisScopeLevel = CROSS_THIS_SCOPE_TYPE_NODE[exprAst.type] ? -1 : 0; traverse(fileAst, { enter(path) { if (CROSS_THIS_SCOPE_TYPE_NODE[path.node.type]) { thisScopeLevel++; } }, exit(path) { if (CROSS_THIS_SCOPE_TYPE_NODE[path.node.type]) { thisScopeLevel--; } }, MemberExpression(path) { if (!path.isMemberExpression()) { return; } const obj = path.get('object'); if (!obj.isThisExpression()) { return; } // 处理局部变量 if (!path.node.computed) { const prop = path.get('property'); if (prop.isIdentifier() && localVariablesSet.has(prop.node.name)) { path.replaceWith(t.identifier(prop.node.name)); return; } } // 替换 this (只在顶层替换) if (thisScopeLevel <= 0) { obj.replaceWith(t.identifier(contextName)); } }, ThisExpression(path) { if (!path.isThisExpression()) { return; } // MemberExpression 中的 this.xxx 已经处理过了 if (path.parent.type === 'MemberExpression') { return; } if (thisScopeLevel <= 0) { path.replaceWith(t.identifier(contextName)); } }, }); const { code } = generate(exprWrapAst.expression, { sourceMaps: false }); return code; } catch (e) { throw new ParseError(expr, e); } } export function parseExpression(expr: string) { try { return parser.parseExpression(expr); } catch (e) { throw new ParseError(expr, e); } } export function transformExpressionLocalRef(expr: string, scope: IScope) { if (!expr) { return expr; } if (!scope) { throw new Error('transform expression without scope'); } try { const exprAst = typeof expr === 'string' ? parser.parseExpression(expr) : expr; const exprWrapAst = t.expressionStatement(exprAst); const fileAst = t.file(t.program([exprWrapAst])); traverse(fileAst, { MemberExpression(path) { if (!path.isMemberExpression()) { return; } const obj = path.get('object'); if (!obj.isThisExpression()) { return; } // 查看是否存在引用 local 值 const prop = path.get('property'); let memberName = ''; if (!path.node.computed && prop.isIdentifier()) { memberName = prop.node.name; } else if (path.node.computed && prop.isStringLiteral()) { memberName = prop.node.value; } if (memberName && scope.bindings && scope.bindings.hasBinding(memberName)) { path.replaceWith(t.identifier(memberName)); } }, }); const { code } = generate(exprWrapAst.expression, { sourceMaps: false }); return code; } catch (e) { throw new ParseError(expr, e); // throw e; } }
the_stack
import assert from 'assert'; import { r } from '../src'; import config from './config'; import { uuid } from './util/common'; describe('document manipulation', () => { let dbName: string; let tableName: string; before(async () => { await r.connectPool(config); dbName = uuid(); tableName = uuid(); const result1 = await r.dbCreate(dbName).run(); assert.equal(result1.dbs_created, 1); const result2 = await r .db(dbName) .tableCreate(tableName) .run(); assert.equal(result2.tables_created, 1); }); after(async () => { await r.getPoolMaster().drain(); }); it('`row => row` should work - 1', async () => { const result = await r .expr([1, 2, 3]) .map(row => row) .run(); assert.deepEqual(result, [1, 2, 3]); }); it('`row => row` should work - 2', async () => { let result = await r .db(dbName) .table(tableName) .insert({}) .run(); assert.equal(result.inserted, 1); result = await r .db(dbName) .table(tableName) .update(row => ({ idCopyUpdate: row('id') })) .run(); assert.equal(result.replaced, 1); }); it('`row => row` should work - 3', async () => { const result = await r .db(dbName) .table(tableName) .replace(row => row) .run(); assert.equal(result.replaced, 0); }); it('`row => row` should work - 4', async () => { const result = await r .db(dbName) .table(tableName) .replace(doc => doc.merge({ idCopyReplace: doc('id') })) .run(); assert.equal(result.replaced, 1); }); it('`row => row` should work - 5', async () => { const result = await r .db(dbName) .table(tableName) .delete() .run(); assert.equal(result.deleted, 1); }); it('`r.row` should work - 1', async () => { const result = await r .expr([1, 2, 3]) .map(r.row) .run(); assert.deepEqual(result, [1, 2, 3]); }); it('`r.row` should work - 2', async () => { const result1 = await r .db(dbName) .table(tableName) .insert({}) .run(); assert.equal(result1.inserted, 1); const result2 = await r .db(dbName) .table(tableName) .update({ idCopyUpdate: r.row('id') }) .run(); console.dir(result2); assert.equal(result2.replaced, 1); }); it('`r.row` should work - 3', async () => { const result = await r .db(dbName) .table(tableName) .replace(r.row) .run(); assert.equal(result.replaced, 0); }); it('`r.row` should work - 4', async () => { const result = await r .db(dbName) .table(tableName) .replace(doc => doc.merge({ idCopyReplace: doc('id') })) .run(); assert.equal(result.replaced, 1); }); it('`r.row` should work - 5', async () => { const result = await r .db(dbName) .table(tableName) .delete() .run(); assert.equal(result.deleted, 1); }); it('`pluck` should work', async () => { const result1 = await r .expr({ a: 0, b: 1, c: 2 }) .pluck('a', 'b') .run(); assert.deepEqual(result1, { a: 0, b: 1 }); const result2 = await r .expr([{ a: 0, b: 1, c: 2 }, { a: 0, b: 10, c: 20 }]) .pluck('a', 'b') .run(); assert.deepEqual(result2, [{ a: 0, b: 1 }, { a: 0, b: 10 }]); }); it('`pluck` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) .pluck() .run(); assert.fail('should trow'); } catch (e) { assert.equal( e.message, '`pluck` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`without` should work', async () => { const result1 = await r .expr({ a: 0, b: 1, c: 2 }) .without('c') .run(); assert.deepEqual(result1, { a: 0, b: 1 }); const result2 = await r .expr([{ a: 0, b: 1, c: 2 }, { a: 0, b: 10, c: 20 }]) .without('a', 'c') .run(); assert.deepEqual(result2, [{ b: 1 }, { b: 10 }]); }); it('`without` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) .without() .run(); } catch (e) { assert.equal( e.message, '`without` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`merge` should work', async () => { let result = await r .expr({ a: 0 }) .merge({ b: 1 }) .run(); assert.deepEqual(result, { a: 0, b: 1 }); result = await r .expr([{ a: 0 }, { a: 1 }, { a: 2 }]) .merge({ b: 1 }) .run(); assert.deepEqual(result, [{ a: 0, b: 1 }, { a: 1, b: 1 }, { a: 2, b: 1 }]); result = await r .expr({ a: 0, c: { l: 'tt' } }) .merge({ b: { c: { d: { e: 'fff' } }, k: 'pp' } }) .run(); assert.deepEqual(result, { a: 0, b: { c: { d: { e: 'fff' } }, k: 'pp' }, c: { l: 'tt' } }); result = await r .expr({ a: 1 }) .merge({ date: r.now() }) .run(); assert.equal(result.a, 1); assert(result.date instanceof Date); result = await r .expr({ a: 1 }) .merge(row => ({ nested: row }), { b: 2 }) .run(); assert.deepEqual(result, { a: 1, nested: { a: 1 }, b: 2 }); }); it('`merge` should take an anonymous function', async () => { let result = await r .expr({ a: 0 }) .merge(doc => ({ b: doc('a').add(1) })) .run(); assert.deepEqual(result, { a: 0, b: 1 }); result = await r .expr({ a: 0 }) .merge(row => ({ b: row('a').add(1) })) .run(); assert.deepEqual(result, { a: 0, b: 1 }); }); it('`literal` should work', async () => { const result = await r .expr({ a: { b: 1 } }) .merge({ a: r.literal({ c: 2 }) }) .run(); assert.deepEqual(result, { a: { c: 2 } }); }); it('`literal` is not defined after a term', async () => { try { await r .expr(1) // @ts-ignore .literal('foo') .run(); assert.fail('should throw'); } catch (e) { assert(e.message.endsWith('.literal is not a function')); } }); it('`merge` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) .merge() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`merge` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`literal` should work with no argument', async () => { const result = await r .expr({ foo: 'bar' }) .merge({ foo: r.literal() }) .run(); assert.deepEqual(result, {}); }); it('`append` should work', async () => { const result = await r .expr([1, 2, 3]) .append(4) .run(); assert.deepEqual(result, [1, 2, 3, 4]); }); it('`append` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .append() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`append` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`prepend` should work', async () => { const result = await r .expr([1, 2, 3]) .prepend(4) .run(); assert.deepEqual(result, [4, 1, 2, 3]); }); it('`prepend` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .prepend() .run(); assert.fail('sholud throw'); } catch (e) { assert.equal( e.message, '`prepend` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`difference` should work', async () => { const result = await r .expr([1, 2, 3]) .prepend(4) .run(); assert.deepEqual(result, [4, 1, 2, 3]); }); it('`difference` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .difference() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`difference` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`setInsert` should work', async () => { let result = await r .expr([1, 2, 3]) .setInsert(4) .run(); assert.deepEqual(result, [1, 2, 3, 4]); result = await r .expr([1, 2, 3]) .setInsert(2) .run(); assert.deepEqual(result, [1, 2, 3]); }); it('`setInsert` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .setInsert() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`setInsert` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`setUnion` should work', async () => { const result = await r .expr([1, 2, 3]) .setUnion([2, 4]) .run(); assert.deepEqual(result, [1, 2, 3, 4]); }); it('`setUnion` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .setUnion() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`setUnion` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`setIntersection` should work', async () => { const result = await r .expr([1, 2, 3]) .setIntersection([2, 4]) .run(); assert.deepEqual(result, [2]); }); it('`setIntersection` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .setIntersection() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`setIntersection` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`setDifference` should work', async () => { const result = await r .expr([1, 2, 3]) .setDifference([2, 4]) .run(); assert.deepEqual(result, [1, 3]); }); it('`setDifference` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .setDifference() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`setDifference` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`getField` should work', async () => { let result = await r .expr({ a: 0, b: 1 })('a') .run(); assert.equal(result, 0); result = await r .expr({ a: 0, b: 1 }) .getField('a') .run(); assert.equal(result, 0); result = await r .expr([{ a: 0, b: 1 }, { a: 1 }])('a') .run(); assert.deepEqual(result, [0, 1]); }); it('`(...)` should throw if no argument has been passed', async () => { try { // @ts-ignore await r .db(dbName) .table(tableName)() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`(...)` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`getField` should throw if no argument has been passed', async () => { try { // @ts-ignore await r .db(dbName) .table(tableName) .getField() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`getField` takes 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`hasFields` should work', async () => { const result = await r .expr([{ a: 0, b: 1, c: 2 }, { a: 0, b: 10, c: 20 }, { b: 1, c: 3 }]) .hasFields('a', 'c') .run(); assert.deepEqual(result, [{ a: 0, b: 1, c: 2 }, { a: 0, b: 10, c: 20 }]); }); it('`hasFields` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) .hasFields() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`hasFields` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`insertAt` should work', async () => { let result = await r .expr([1, 2, 3, 4]) .insertAt(0, 2) .run(); assert.deepEqual(result, [2, 1, 2, 3, 4]); result = await r .expr([1, 2, 3, 4]) .insertAt(3, 2) .run(); assert.deepEqual(result, [1, 2, 3, 2, 4]); }); it('`insertAt` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .insertAt() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`insertAt` takes 2 arguments, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`spliceAt` should work', async () => { const result = await r .expr([1, 2, 3, 4]) .spliceAt(1, [9, 9]) .run(); assert.deepEqual(result, [1, 9, 9, 2, 3, 4]); }); it('`spliceAt` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .spliceAt() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`spliceAt` takes 2 arguments, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`deleteAt` should work', async () => { let result = await r .expr([1, 2, 3, 4]) .deleteAt(1) .run(); assert.deepEqual(result, [1, 3, 4]); result = await r .expr([1, 2, 3, 4]) .deleteAt(1, 3) .run(); assert.deepEqual(result, [1, 4]); }); it('`deleteAt` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .deleteAt() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`deleteAt` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`deleteAt` should throw if too many arguments', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .deleteAt(1, 1, 1, 1) .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`deleteAt` takes at most 2 arguments, 4 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`changeAt` should work', async () => { const result = await r .expr([1, 2, 3, 4]) .changeAt(1, 3) .run(); assert.deepEqual(result, [1, 3, 3, 4]); }); it('`changeAt` should throw if no argument has been passed', async () => { try { await r .db(dbName) .table(tableName) // @ts-ignore .changeAt() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`changeAt` takes 2 arguments, 0 provided after:\nr.db("' + dbName + '").table("' + tableName + '")\n' ); } }); it('`keys` should work', async () => { const result = await r .expr({ a: 0, b: 1, c: 2 }) .keys() .orderBy(row => row) .run(); assert.deepEqual(result, ['a', 'b', 'c']); }); it('`keys` throw on a string', async () => { try { await r .expr('hello') .keys() .orderBy(row => row) .run(); assert.fail('should throw'); } catch (e) { assert( e.message.match(/^Cannot call `keys` on objects of type `STRING` in/) ); } }); it('`values` should work', async () => { const result = await r .expr({ a: 0, b: 1, c: 2 }) .values() .orderBy(row => row) .run(); assert.deepEqual(result, [0, 1, 2]); }); it('`object` should work', async () => { const result = await r.object('a', 1, r.expr('2'), 'foo').run(); assert.deepEqual(result, { a: 1, '2': 'foo' }); }); });
the_stack
export class App { constructor(gl: WebGLRenderingContext); /** * Simulate context loss. * @returns The App object. */ loseContext(): App; /** * Simulate context restoration. * @returns The App object. */ restoreContext(): App; /** * Set function to handle context restoration after loss. * @param fn - Context restored handler. * @returns The App object. */ onContextRestored(fn: (...params: any[]) => any): App; /** * Enable WebGL capability (e.g. depth testing, blending, etc.). * @param cap - Capability to enable. * @returns The App object. */ enable(cap: GLenum): App; /** * Disable WebGL capability (e.g. depth testing, blending, etc.). * @param cap - Capability to disable. * @returns The App object. */ disable(cap: GLenum): App; /** * Set the color mask to selectively enable or disable particular * color channels while rendering. * @param r - Red channel. * @param g - Green channel. * @param b - Blue channel. * @param a - Alpha channel. * @returns The App object. */ colorMask(r: boolean, g: boolean, b: boolean, a: boolean): App; /** * Set the clear color. * @param r - Red channel. * @param g - Green channel. * @param b - Blue channel. * @param a - Alpha channel. * @returns The App object. */ clearColor(r: number, g: number, b: number, a: number): App; /** * Set the clear mask bits to use when calling clear(). * E.g. app.clearMask(PicoGL.COLOR_BUFFER_BIT). * @param mask - Bit mask of buffers to clear. * @returns The App object. */ clearMask(mask: GLenum): App; /** * Clear the canvas * @returns The App object. */ clear(): App; /** * Bind a draw framebuffer to the WebGL context. * @param framebuffer - The Framebuffer object to bind. * @returns The App object. */ drawFramebuffer(framebuffer: Framebuffer): App; /** * Bind a read framebuffer to the WebGL context. * @param framebuffer - The Framebuffer object to bind. * @returns The App object. */ readFramebuffer(framebuffer: Framebuffer): App; /** * Switch back to the default framebuffer for drawing (i.e. draw to the screen). * Note that this method resets the viewport to match the default framebuffer. * @returns The App object. */ defaultDrawFramebuffer(): App; /** * Switch back to the default framebuffer for reading (i.e. read from the screen). * @returns The App object. */ defaultReadFramebuffer(): App; /** * Copy data from framebuffer attached to READ_FRAMEBUFFER to framebuffer attached to DRAW_FRAMEBUFFER. * @param mask - Write mask (e.g. PicoGL.COLOR_BUFFER_BIT). * @param [options] - Blit options. * @param [options.srcStartX = 0] - Source start x coordinate. * @param [options.srcStartY = 0] - Source start y coordinate. * @param [options.srcEndX = Width of the read framebuffer] - Source end x coordinate. * @param [options.srcEndY = Height of the read framebuffer] - Source end y coordinate. * @param [options.dstStartX = 0] - Destination start x coordinate. * @param [options.dstStartY = 0] - Destination start y coordinate. * @param [options.dstEndX = Width of the draw framebuffer] - Destination end x coordinate. * @param [options.dstEndY = Height of the draw framebuffer] - Destination end y coordinate. * @param [options.filter = NEAREST] - Sampling filter. * @returns The App object. */ blitFramebuffer(mask: GLenum, options?: { srcStartX?: number; srcStartY?: number; srcEndX?: number; srcEndY?: number; dstStartX?: number; dstStartY?: number; dstEndX?: number; dstEndY?: number; filter?: number; }): App; /** * Set the depth range. * @param near - Minimum depth value. * @param far - Maximum depth value. * @returns The App object. */ depthRange(near: number, far: number): App; /** * Enable or disable writing to the depth buffer. * @param mask - The depth mask. * @returns The App object. */ depthMask(mask: boolean): App; /** * Set the depth test function. E.g. app.depthFunc(PicoGL.LEQUAL). * @param func - The depth testing function to use. * @returns The App object. */ depthFunc(func: GLenum): App; /** * Set the blend function. E.g. app.blendFunc(PicoGL.ONE, PicoGL.ONE_MINUS_SRC_ALPHA). * @param src - The source blending weight. * @param dest - The destination blending weight. * @returns The App object. */ blendFunc(src: GLenum, dest: GLenum): App; /** * Set the blend function, with separate weighting for color and alpha channels. * E.g. app.blendFuncSeparate(PicoGL.ONE, PicoGL.ONE_MINUS_SRC_ALPHA, PicoGL.ONE, PicoGL.ONE). * @param csrc - The source blending weight for the RGB channels. * @param cdest - The destination blending weight for the RGB channels. * @param asrc - The source blending weight for the alpha channel. * @param adest - The destination blending weight for the alpha channel. * @returns The App object. */ blendFuncSeparate(csrc: GLenum, cdest: GLenum, asrc: GLenum, adest: GLenum): App; /** * Set the blend equation. E.g. app.blendEquation(PicoGL.MIN). * @param mode - The operation to use in combining source and destination channels. * @returns The App object. */ blendEquation(mode: GLenum): App; /** * Set the bitmask to use for tested stencil values. * E.g. app.stencilMask(0xFF). * NOTE: Only works if { stencil: true } passed as a * context attribute when creating the App! * @param mask - The mask value. * @returns The App object. */ stencilMask(mask: number): App; /** * Set the bitmask to use for tested stencil values for a particular face orientation. * E.g. app.stencilMaskSeparate(PicoGL.FRONT, 0xFF). * NOTE: Only works if { stencil: true } passed as a * context attribute when creating the App! * @param face - The face orientation to apply the mask to. * @param mask - The mask value. * @returns The App object. */ stencilMaskSeparate(face: GLenum, mask: number): App; /** * Set the stencil function and reference value. * E.g. app.stencilFunc(PicoGL.EQUAL, 1, 0xFF). * NOTE: Only works if { stencil: true } passed as a * context attribute when creating the App! * @param func - The testing function. * @param ref - The reference value. * @param mask - The bitmask to use against tested values before applying * the stencil function. * @returns The App object. */ stencilFunc(func: GLenum, ref: number, mask: GLenum): App; /** * Set the stencil function and reference value for a particular face orientation. * E.g. app.stencilFuncSeparate(PicoGL.FRONT, PicoGL.EQUAL, 1, 0xFF). * NOTE: Only works if { stencil: true } passed as a * context attribute when creating the App! * @param face - The face orientation to apply the function to. * @param func - The testing function. * @param ref - The reference value. * @param mask - The bitmask to use against tested values before applying * the stencil function. * @returns The App object. */ stencilFuncSeparate(face: GLenum, func: GLenum, ref: number, mask: GLenum): App; /** * Set the operations for updating stencil buffer values. * E.g. app.stencilOp(PicoGL.KEEP, PicoGL.KEEP, PicoGL.REPLACE). * NOTE: Only works if { stencil: true } passed as a * context attribute when creating the App! * @param stencilFail - Operation to apply if the stencil test fails. * @param depthFail - Operation to apply if the depth test fails. * @param pass - Operation to apply if the both the depth and stencil tests pass. * @returns The App object. */ stencilOp(stencilFail: GLenum, depthFail: GLenum, pass: GLenum): App; /** * Set the operations for updating stencil buffer values for a particular face orientation. * E.g. app.stencilOpSeparate(PicoGL.FRONT, PicoGL.KEEP, PicoGL.KEEP, PicoGL.REPLACE). * NOTE: Only works if { stencil: true } passed as a * context attribute when creating the App! * @param face - The face orientation to apply the operations to. * @param stencilFail - Operation to apply if the stencil test fails. * @param depthFail - Operation to apply if the depth test fails. * @param pass - Operation to apply if the both the depth and stencil tests pass. * @returns The App object. */ stencilOpSeparate(face: GLenum, stencilFail: GLenum, depthFail: GLenum, pass: GLenum): App; /** * Define the scissor box. * @param x - Horizontal position of the scissor box. * @param y - Vertical position of the scissor box. * @param width - Width of the scissor box. * @param height - Height of the scissor box. * @returns The App object. */ scissor(x: number, y: number, width: number, height: number): App; /** * Set the scale and units used. * @param factor - Scale factor used to create a variable depth offset for each polygon. * @param units - Constant depth offset. * @returns The App object. */ polygonOffset(factor: number, units: number): App; /** * Read a pixel's color value from the currently-bound framebuffer. * @param x - The x coordinate of the pixel. * @param y - The y coordinate of the pixel. * @param outColor - Typed array to store the pixel's color. * @param [options] - Options. * @param [options.type = UNSIGNED_BYTE] - Type of data stored in the read framebuffer. * @param [options.format = RGBA] - Read framebuffer data format. * @returns The App object. */ readPixel(x: number, y: number, outColor: ArrayBufferView, options?: { type?: GLenum; format?: GLenum; }): App; /** * Set the viewport. * @param x - Left bound of the viewport rectangle. * @param y - Lower bound of the viewport rectangle. * @param width - Width of the viewport rectangle. * @param height - Height of the viewport rectangle. * @returns The App object. */ viewport(x: number, y: number, width: number, height: number): App; /** * Set the viewport to the full canvas. * @returns The App object. */ defaultViewport(): App; /** * Resize the drawing surface. * @param width - The new canvas width. * @param height - The new canvas height. * @returns The App object. */ resize(width: number, height: number): App; /** * Create a program synchronously. It is highly recommended to use <b>createPrograms</b> instead as * that method will compile shaders in parallel where possible. * @param vertexShader - Vertex shader object or source code. * @param fragmentShader - Fragment shader object or source code. * @param [options] - Texture options. * @param [options.attributeLocations] - Map of attribute names to locations (useful when using GLSL 1). * @param [options.transformFeedbackVaryings] - Array of varying names used for transform feedback output. * @param [options.transformFeedbackMode] - Capture mode of the transform feedback. (Default: PicoGL.SEPARATE_ATTRIBS). * @returns New Program object. */ createProgram(vertexShader: Shader | string, fragmentShader: Shader | string, options?: { attributeLocations?: any; transformFeedbackVaryings?: any[]; transformFeedbackMode?: GLenum; }): Program; /** * Create several programs. Preferred method for program creation as it will compile shaders * in parallel where possible. * @param sources - Variable number of 2 or 3 element arrays, each containing: * <ul> * <li> (Shader|string) Vertex shader object or source code. * <li> (Shader|string) Fragment shader object or source code. * <li> (Object - optional) Optional program parameters. * <ul> * <li>(Object - optional) <strong><code>attributeLocations</code></strong> Map of attribute names to locations (useful when using GLSL 1). * <li>(Array - optional) <strong><code>transformFeedbackVaryings</code></strong> Array of varying names used for transform feedback output. * <li>(GLenum - optional) <strong><code>transformFeedbackMode</code></strong> Capture mode of the transform feedback. (Default: PicoGL.SEPARATE_ATTRIBS). * </ul> * </ul> * </ul> * @returns Promise that will resolve to an array of Programs when compilation and * linking are complete for all programs. */ createPrograms(...sources: any[][]): Promise<Program[]>; /** * Restore several programs after a context loss. Will do so in parallel where available. * @param sources - Variable number of programs to restore. * @returns Promise that will resolve once all programs have been restored. */ restorePrograms(...sources: Program[]): Promise<void>; /** * Create a shader. Creating a shader separately from a program allows for * shader reuse. * @param type - Shader type. * @param source - Shader source. * @returns New Shader object. */ createShader(type: GLenum, source: string): Shader; /** * Create a vertex array. * @returns New VertexArray object. */ createVertexArray(): VertexArray; /** * Create a transform feedback object. * @returns New TransformFeedback object. */ createTransformFeedback(): TransformFeedback; /** * Create a vertex buffer. * @param type - The data type stored in the vertex buffer. * @param itemSize - Number of elements per vertex. * @param data - Buffer data itself or the total * number of elements to be allocated. * @param [usage = STATIC_DRAW] - Buffer usage. * @returns New VertexBuffer object. */ createVertexBuffer(type: GLenum, itemSize: number, data: ArrayBufferView | number, usage?: GLenum): VertexBuffer; /** * Create a per-vertex matrix buffer. Matrix buffers ensure that columns * are correctly split across attribute locations. * @param type - The data type stored in the matrix buffer. Valid types * are FLOAT_MAT4, FLOAT_MAT4x2, FLOAT_MAT4x3, FLOAT_MAT3, FLOAT_MAT3x2, * FLOAT_MAT3x4, FLOAT_MAT2, FLOAT_MAT2x3, FLOAT_MAT2x4. * @param data - Matrix buffer data. * @param [usage = STATIC_DRAW] - Buffer usage. * @returns New VertexBuffer object. */ createMatrixBuffer(type: GLenum, data: ArrayBufferView, usage?: GLenum): VertexBuffer; /** * Create an buffer without any structure information. Structure * must be fully specified when binding to a VertexArray. * @param bytesPerVertex - Number of bytes per vertex. * @param data - Buffer data itself or the total * number of bytes to be allocated. * @param [usage = STATIC_DRAW] - Buffer usage. * @returns New VertexBuffer object. */ createInterleavedBuffer(bytesPerVertex: number, data: ArrayBufferView | number, usage?: GLenum): VertexBuffer; /** * Create an index buffer. If the `itemSize` is not specified, it defaults to 3 * @param type - The data type stored in the index buffer. * @param data - Index buffer data. * @param [usage = STATIC_DRAW] - Buffer usage. * @returns New VertexBuffer object. */ createIndexBuffer(type: GLenum, data: ArrayBufferView, usage?: GLenum): VertexBuffer; /** * Create an index buffer. * @param type - The data type stored in the index buffer. * @param itemSize - Number of elements per primitive. * @param data - Index buffer data. * @param [usage = STATIC_DRAW] - Buffer usage. * @returns New VertexBuffer object. */ createIndexBuffer(type: GLenum, itemSize: number, data: ArrayBufferView, usage?: GLenum): VertexBuffer; /** * Create a uniform buffer in std140 layout. NOTE: FLOAT_MAT2, FLOAT_MAT3x2, FLOAT_MAT4x2, * FLOAT_MAT3, FLOAT_MAT2x3, FLOAT_MAT4x3 are supported, but must be manually padded to * 4-float column alignment by the application! * @param layout - Array indicating the order and types of items to * be stored in the buffer. * @param [usage = DYNAMIC_DRAW] - Buffer usage. * @returns New UniformBuffer object. */ createUniformBuffer(layout: any[], usage?: GLenum): UniformBuffer; /** * Create empty 2D texture. * @param width - Texture width. Required for array or empty data. * @param height - Texture height. Required for array or empty data. * @param [options] - Texture options. * @param [options.internalFormat = RGBA8] - Texture data internal format. Must be a sized format. * @param [options.type] - Type of data stored in the texture. Default based on * <b>internalFormat</b>. * @param [options.flipY = false] - Whether the y-axis should be flipped when unpacking the texture. * @param [options.premultiplyAlpha = false] - Whether the alpha channel should be pre-multiplied when unpacking the texture. * @param [options.minFilter] - Minification filter. Defaults to * LINEAR_MIPMAP_NEAREST if image data is provided, NEAREST otherwise. * @param [options.magFilter] - Magnification filter. Defaults to LINEAR * if image data is provided, NEAREST otherwise. * @param [options.wrapS = REPEAT] - Horizontal wrap mode. * @param [options.wrapT = REPEAT] - Vertical wrap mode. * @param [options.compareMode = NONE] - Comparison mode. * @param [options.compareFunc = LEQUAL] - Comparison function. * @param [options.baseLevel] - Base mipmap level. * @param [options.maxLevel] - Maximum mipmap level. * @param [options.minLOD] - Mimimum level of detail. * @param [options.maxLOD] - Maximum level of detail. * @param [options.maxAnisotropy] - Maximum anisotropy in filtering. * @returns New Texture object. */ createTexture2D(width: number, height: number, options?: { internalFormat?: GLenum; type?: GLenum; flipY?: boolean; premultiplyAlpha?: boolean; minFilter?: GLenum; magFilter?: GLenum; wrapS?: GLenum; wrapT?: GLenum; compareMode?: GLenum; compareFunc?: GLenum; baseLevel?: GLenum; maxLevel?: GLenum; minLOD?: GLenum; maxLOD?: GLenum; maxAnisotropy?: GLenum; }): Texture; /** * Create a 2D texture from a DOM image element. * @param image - Image data. An array can be passed to manually set all levels * of the mipmap chain. If a single level is passed and mipmap filtering is being used, * generateMipmap() will be called to produce the remaining levels. * @param [options] - Texture options. * @param [options.internalFormat = RGBA8] - Texture data internal format. Must be a sized format. * @param [options.type] - Type of data stored in the texture. Default based on * <b>intrnalFormat</b>. * @param [options.flipY = false] - Whether the y-axis should be flipped when unpacking the texture. * @param [options.premultiplyAlpha = false] - Whether the alpha channel should be pre-multiplied when unpacking the texture. * @param [options.minFilter] - Minification filter. Defaults to * LINEAR_MIPMAP_NEAREST if image data is provided, NEAREST otherwise. * @param [options.magFilter] - Magnification filter. Defaults to LINEAR * if image data is provided, NEAREST otherwise. * @param [options.wrapS = REPEAT] - Horizontal wrap mode. * @param [options.wrapT = REPEAT] - Vertical wrap mode. * @param [options.compareMode = NONE] - Comparison mode. * @param [options.compareFunc = LEQUAL] - Comparison function. * @param [options.baseLevel] - Base mipmap level. * @param [options.maxLevel] - Maximum mipmap level. * @param [options.minLOD] - Mimimum level of detail. * @param [options.maxLOD] - Maximum level of detail. * @param [options.maxAnisotropy] - Maximum anisotropy in filtering. * @returns New Texture object. */ createTexture2D(image: HTMLImageElement | HTMLImageElement[], options?: { internalFormat?: GLenum; type?: GLenum; flipY?: boolean; premultiplyAlpha?: boolean; minFilter?: GLenum; magFilter?: GLenum; wrapS?: GLenum; wrapT?: GLenum; compareMode?: GLenum; compareFunc?: GLenum; baseLevel?: GLenum; maxLevel?: GLenum; minLOD?: GLenum; maxLOD?: GLenum; maxAnisotropy?: GLenum; }): Texture; /** * Create 2D texture from a typed array. * @param image - Image data. An array can be passed to manually set all levels * of the mipmap chain. If a single level is passed and mipmap filtering is being used, * generateMipmap() will be called to produce the remaining levels. * @param width - Texture width. Required for array or empty data. * @param height - Texture height. Required for array or empty data. * @param [options] - Texture options. * @param [options.internalFormat = RGBA8] - Texture data internal format. Must be a sized format. * @param [options.type] - Type of data stored in the texture. Default based on * <b>internalFormat</b>. * @param [options.flipY = false] - Whether the y-axis should be flipped when unpacking the texture. * @param [options.premultiplyAlpha = false] - Whether the alpha channel should be pre-multiplied when unpacking the texture. * @param [options.minFilter] - Minification filter. Defaults to * LINEAR_MIPMAP_NEAREST if image data is provided, NEAREST otherwise. * @param [options.magFilter] - Magnification filter. Defaults to LINEAR * if image data is provided, NEAREST otherwise. * @param [options.wrapS = REPEAT] - Horizontal wrap mode. * @param [options.wrapT = REPEAT] - Vertical wrap mode. * @param [options.compareMode = NONE] - Comparison mode. * @param [options.compareFunc = LEQUAL] - Comparison function. * @param [options.baseLevel] - Base mipmap level. * @param [options.maxLevel] - Maximum mipmap level. * @param [options.minLOD] - Mimimum level of detail. * @param [options.maxLOD] - Maximum level of detail. * @param [options.maxAnisotropy] - Maximum anisotropy in filtering. * @returns New Texture object. */ createTexture2D(image: ArrayBufferView | ArrayBufferView[], width: number, height: number, options?: { internalFormat?: GLenum; type?: GLenum; flipY?: boolean; premultiplyAlpha?: boolean; minFilter?: GLenum; magFilter?: GLenum; wrapS?: GLenum; wrapT?: GLenum; compareMode?: GLenum; compareFunc?: GLenum; baseLevel?: GLenum; maxLevel?: GLenum; minLOD?: GLenum; maxLOD?: GLenum; maxAnisotropy?: GLenum; }): Texture; /** * Create a 2D texture array. * @param image - Pixel data. An array can be passed to manually set all levels * of the mipmap chain. If a single level is passed and mipmap filtering is being used, * generateMipmap() will be called to produce the remaining levels. * @param width - Texture width. * @param height - Texture height. * @param size - Number of images in the array. * @param [options] - Texture options. * @param [options.internalFormat = RGBA8] - Texture data internal format. Must be a sized format. * @param [options.type] - Type of data stored in the texture. Default based on * <b>internalFormat</b>. * @param [options.flipY = false] - Whether the y-axis should be flipped when unpacking the texture. * @param [options.minFilter] - Minification filter. Defaults to * LINEAR_MIPMAP_NEAREST if image data is provided, NEAREST otherwise. * @param [options.magFilter] - Magnification filter. Defaults to LINEAR * if image data is provided, NEAREST otherwise. * @param [options.wrapS = REPEAT] - Horizontal wrap mode. * @param [options.wrapT = REPEAT] - Vertical wrap mode. * @param [options.wrapR = REPEAT] - Depth wrap mode. * @param [options.compareMode = NONE] - Comparison mode. * @param [options.compareFunc = LEQUAL] - Comparison function. * @param [options.baseLevel] - Base mipmap level. * @param [options.maxLevel] - Maximum mipmap level. * @param [options.minLOD] - Mimimum level of detail. * @param [options.maxLOD] - Maximum level of detail. * @param [options.maxAnisotropy] - Maximum anisotropy in filtering. * @returns New Texture object. */ createTextureArray(image: ArrayBufferView | any[], width: number, height: number, size: number, options?: { internalFormat?: GLenum; type?: GLenum; flipY?: boolean; minFilter?: GLenum; magFilter?: GLenum; wrapS?: GLenum; wrapT?: GLenum; wrapR?: GLenum; compareMode?: GLenum; compareFunc?: GLenum; baseLevel?: GLenum; maxLevel?: GLenum; minLOD?: GLenum; maxLOD?: GLenum; maxAnisotropy?: GLenum; }): Texture; /** * Create a 3D texture. * @param image - Pixel data. An array can be passed to manually set all levels * of the mipmap chain. If a single level is passed and mipmap filtering is being used, * generateMipmap() will be called to produce the remaining levels. * @param width - Texture width. * @param height - Texture height. * @param depth - Texture depth. * @param [options] - Texture options. * @param [options.internalFormat = RGBA8] - Texture data internal format. Must be a sized format. * @param [options.type] - Type of data stored in the texture. Default based on * <b>internalFormat</b>. * @param [options.flipY = false] - Whether the y-axis should be flipped when unpacking the texture. * @param [options.minFilter] - Minification filter. Defaults to * LINEAR_MIPMAP_NEAREST if image data is provided, NEAREST otherwise. * @param [options.magFilter] - Magnification filter. Defaults to LINEAR * if image data is provided, NEAREST otherwise. * @param [options.wrapS = REPEAT] - Horizontal wrap mode. * @param [options.wrapT = REPEAT] - Vertical wrap mode. * @param [options.wrapR = REPEAT] - Depth wrap mode. * @param [options.compareMode = NONE] - Comparison mode. * @param [options.compareFunc = LEQUAL] - Comparison function. * @param [options.baseLevel] - Base mipmap level. * @param [options.maxLevel] - Maximum mipmap level. * @param [options.minLOD] - Mimimum level of detail. * @param [options.maxLOD] - Maximum level of detail. * @param [options.maxAnisotropy] - Maximum anisotropy in filtering. * @returns New Texture object. */ createTexture3D(image: ArrayBufferView | any[], width: number, height: number, depth: number, options?: { internalFormat?: GLenum; type?: GLenum; flipY?: boolean; minFilter?: GLenum; magFilter?: GLenum; wrapS?: GLenum; wrapT?: GLenum; wrapR?: GLenum; compareMode?: GLenum; compareFunc?: GLenum; baseLevel?: GLenum; maxLevel?: GLenum; minLOD?: GLenum; maxLOD?: GLenum; maxAnisotropy?: GLenum; }): Texture; /** * Create a cubemap. * @param options - Texture options. * @param [options.negX] - The image data for the negative X direction. * Can be any format that would be accepted by texImage2D. * @param [options.posX] - The image data for the positive X direction. * Can be any format that would be accepted by texImage2D. * @param [options.negY] - The image data for the negative Y direction. * Can be any format that would be accepted by texImage2D. * @param [options.posY] - The image data for the positive Y direction. * Can be any format that would be accepted by texImage2D. * @param [options.negZ] - The image data for the negative Z direction. * Can be any format that would be accepted by texImage2D. * @param [options.posZ] - The image data for the positive Z direction. * Can be any format that would be accepted by texImage2D. * @param [options.width] - Cubemap side width. Defaults to the width of negX if negX is an image. * @param [options.height] - Cubemap side height. Defaults to the height of negX if negX is an image. * @param [options.internalFormat = RGBA8] - Texture data internal format. Must be a sized format. * @param [options.type] - Type of data stored in the texture. Default based on * <b>internalFormat</b>. * @param [options.flipY = false] - Whether the y-axis should be flipped when unpacking the image. * @param [options.premultiplyAlpha = false] - Whether the alpha channel should be pre-multiplied when unpacking the image. * @param [options.minFilter] - Minification filter. Defaults to * LINEAR_MIPMAP_NEAREST if image data is provided, NEAREST otherwise. * @param [options.magFilter] - Magnification filter. Defaults to LINEAR * if image data is provided, NEAREST otherwise. * @param [options.wrapS = REPEAT] - Horizontal wrap mode. * @param [options.wrapT = REPEAT] - Vertical wrap mode. * @param [options.compareMode = NONE] - Comparison mode. * @param [options.compareFunc = LEQUAL] - Comparison function. * @param [options.baseLevel] - Base mipmap level. * @param [options.maxLevel] - Maximum mipmap level. * @param [options.minLOD] - Mimimum level of detail. * @param [options.maxLOD] - Maximum level of detail. * @param [options.maxAnisotropy] - Maximum anisotropy in filtering. * @returns New Cubemap object. */ createCubemap(options: { negX?: HTMLElement | ArrayBufferView; posX?: HTMLElement | ArrayBufferView; negY?: HTMLElement | ArrayBufferView; posY?: HTMLElement | ArrayBufferView; negZ?: HTMLElement | ArrayBufferView; posZ?: HTMLElement | ArrayBufferView; width?: number; height?: number; internalFormat?: GLenum; type?: GLenum; flipY?: boolean; premultiplyAlpha?: boolean; minFilter?: GLenum; magFilter?: GLenum; wrapS?: GLenum; wrapT?: GLenum; compareMode?: GLenum; compareFunc?: GLenum; baseLevel?: GLenum; maxLevel?: GLenum; minLOD?: GLenum; maxLOD?: GLenum; maxAnisotropy?: GLenum; }): Cubemap; /** * Create a renderbuffer. * @param width - Renderbuffer width. * @param height - Renderbuffer height. * @param internalFormat - Internal arrangement of the renderbuffer data. * @param [samples = 0] - Number of MSAA samples. * @returns New Renderbuffer object. */ createRenderbuffer(width: number, height: number, internalFormat: GLenum, samples?: number): Renderbuffer; /** * Create a framebuffer. * @returns New Framebuffer object. */ createFramebuffer(): Framebuffer; /** * Create a query. * @param target - Information to query. * @returns New Query object. */ createQuery(target: GLenum): Query; /** * Create a timer. * @returns New Timer object. */ createTimer(): Timer; /** * Create a DrawCall. A DrawCall manages the state associated with * a WebGL draw call including a program and associated vertex data, textures, * uniforms and uniform blocks. * @param program - The program to use for this DrawCall. * @param [vertexArray = null] - Vertex data to use for drawing. * @returns New DrawCall object. */ createDrawCall(program: Program, vertexArray?: VertexArray): DrawCall; /** * The canvas on which this app drawing. */ canvas: HTMLElement; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * The width of the drawing surface. */ width: number; /** * The height of the drawing surface. */ height: number; /** * Tracked GL state. */ state: { drawFramebufferBinding: any; readFramebufferBinding: any; }; /** * Current clear mask to use with clear(). */ clearBits: GLenum; } /** * Cubemap for environment mapping. * @property gl - The WebGL context. * @property texture - Handle to the texture. * @property type - Type of data stored in the texture. * @property format - Layout of texture data. * @property internalFormat - Internal arrangement of the texture data. * @property currentUnit - The current texture unit this cubemap is bound to. * @property flipY - Whether the y-axis is flipped for this cubemap. * @property premultiplyAlpha - Whether alpha should be pre-multiplied when loading this cubemap. * @property appState - Tracked GL state. */ export class Cubemap { /** * Restore cubemap after context loss. * @param [options] - Texture options. * @param [options.negX] - The image data for the negative X direction. * Can be any format that would be accepted by texImage2D. * @param [options.posX] - The image data for the positive X direction. * Can be any format that would be accepted by texImage2D. * @param [options.negY] - The image data for the negative Y direction. * Can be any format that would be accepted by texImage2D. * @param [options.posY] - The image data for the positive Y direction. * Can be any format that would be accepted by texImage2D. * @param [options.negZ] - The image data for the negative Z direction. * Can be any format that would be accepted by texImage2D. * @param [options.posZ] - The image data for the positive Z direction. * Can be any format that would be accepted by texImage2D. * @returns The Cubemap object. */ restore(options?: { negX?: HTMLElement | ArrayBufferView; posX?: HTMLElement | ArrayBufferView; negY?: HTMLElement | ArrayBufferView; posY?: HTMLElement | ArrayBufferView; negZ?: HTMLElement | ArrayBufferView; posZ?: HTMLElement | ArrayBufferView; }): Cubemap; /** * Delete this cubemap. * @returns The Cubemap object. */ delete(): Cubemap; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Handle to the texture. */ texture: WebGLTexture; /** * Type of data stored in the texture. */ type: GLenum; /** * Layout of texture data. */ format: GLenum; /** * Internal arrangement of the texture data. */ internalFormat: GLenum; /** * The current texture unit this cubemap is bound to. */ currentUnit: number; /** * Whether the y-axis is flipped for this cubemap. */ flipY: boolean; /** * Whether alpha should be pre-multiplied when loading this cubemap. */ premultiplyAlpha: boolean; /** * Tracked GL state. */ appState: any; } /** * A DrawCall represents the program and values of associated * attributes, uniforms and textures for a single draw call. * @property gl - The WebGL context. * @property currentProgram - The program to use for this draw call. * @property currentVertexArray - Vertex array to use for this draw call. * @property currentTransformFeedback - Transform feedback to use for this draw call. * @property uniformBuffers - Ordered list of active uniform buffers. * @property uniformBlockNames - Ordered list of uniform block names. * @property uniformBlockCount - Number of active uniform blocks for this draw call. * @property uniformIndices - Map of uniform names to indices in the uniform arrays. * @property uniformNames - Ordered list of uniform names. * @property uniformValue - Ordered list of uniform values. * @property uniformCount - The number of active uniforms for this draw call. * @property textures - Array of active textures. * @property textureCount - The number of active textures for this draw call. * @property appState - Tracked GL state. * @property numElements - The number of element to draw. * @property numInstances - The number of instances to draw. */ export class DrawCall { /** * Set the current draw primitive for this draw call. * @param primitive - Primitive to draw. * @returns The DrawCall object. */ primitive(primitive: GLenum): DrawCall; /** * Set the current TransformFeedback object for draw. * @param transformFeedback - Transform Feedback to set. * @returns The DrawCall object. */ transformFeedback(transformFeedback: TransformFeedback): DrawCall; /** * Set the value for a uniform. Array uniforms are supported by * using appending "[0]" to the array name and passing a flat array * with all required values. * @param name - Uniform name. * @param value - Uniform value. * @returns The DrawCall object. */ uniform(name: string, value: any): DrawCall; /** * Set texture to bind to a sampler uniform. * @param name - Sampler uniform name. * @param texture - Texture or Cubemap to bind. * @returns The DrawCall object. */ texture(name: string, texture: Texture | Cubemap): DrawCall; /** * Set uniform buffer to bind to a uniform block. * @param name - Uniform block name. * @param buffer - Uniform buffer to bind. * @returns The DrawCall object. */ uniformBlock(name: string, buffer: UniformBuffer): DrawCall; /** * Ranges in the vertex array to draw. Multiple arguments can be provided to set up * a multi-draw. Note that after this method is called, draw counts will no longer * automatically be pulled from the VertexArray. * @param counts - Variable number of 2 or 3 element arrays, each containing: * <ul> * <li> (Number) Number of elements to skip at the start of the array. * <li> (Number) Number of elements to draw. * <li> (Number - optional) Number of instances to draw of the given range. * </ul> * @returns The DrawCall object. */ drawRanges(...counts: any[][]): DrawCall; /** * Draw based on current state. * @returns The DrawCall object. */ draw(): DrawCall; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * The program to use for this draw call. */ currentProgram: Program; /** * Vertex array to use for this draw call. */ currentVertexArray: VertexArray; /** * Transform feedback to use for this draw call. */ currentTransformFeedback: TransformFeedback; /** * Ordered list of active uniform buffers. */ uniformBuffers: any[]; /** * Ordered list of uniform block names. */ uniformBlockNames: any[]; /** * Number of active uniform blocks for this draw call. */ uniformBlockCount: number; /** * Map of uniform names to indices in the uniform arrays. */ uniformIndices: any; /** * Ordered list of uniform names. */ uniformNames: any[]; /** * Ordered list of uniform values. */ uniformValue: any[]; /** * The number of active uniforms for this draw call. */ uniformCount: number; /** * Array of active textures. */ textures: any[]; /** * The number of active textures for this draw call. */ textureCount: number; /** * Tracked GL state. */ appState: any; /** * The number of element to draw. */ numElements: GLsizei; /** * The number of instances to draw. */ numInstances: GLsizei; } /** * Offscreen drawing surface. * @property gl - The WebGL context. * @property framebuffer - Handle to the framebuffer. * @property width - Framebuffer width. * @property height - Framebuffer height. * @property colorAttachments - Array of color attachments. * @property depthAttachment - Depth attachment. * @property appState - Tracked GL state. */ export class Framebuffer { /** * Restore framebuffer after context loss. * @returns The Framebuffer object. */ restore(): Framebuffer; /** * Attach a color target to this framebuffer. * @param index - Color attachment index. * @param attachment - The texture, cubemap or renderbuffer to attach. * @param [target] - The texture target or layer to attach. If the texture is 3D or a texture array, * defaults to 0, otherwise to TEXTURE_2D. Ignored for renderbuffers. * @returns The Framebuffer object. */ colorTarget(index: number, attachment: Texture | Cubemap | Renderbuffer, target?: GLenum): Framebuffer; /** * Attach a depth target to this framebuffer. * @param texture - The texture, cubemap or renderbuffer to attach. * @param [target] - The texture target or layer to attach. If the texture is 3D or a texture array or renderbuffer, * defaults to 0, otherwise to TEXTURE_2D. Ignored for renderbuffers. * @returns The Framebuffer object. */ depthTarget(texture: Texture | Cubemap | Renderbuffer, target?: GLenum): Framebuffer; /** * Resize all attachments. * @param [width = app.width] - New width of the framebuffer. * @param [height = app.height] - New height of the framebuffer. * @returns The Framebuffer object. */ resize(width?: number, height?: number): Framebuffer; /** * Delete this framebuffer. * @returns The Framebuffer object. */ delete(): Framebuffer; /** * Get the current status of this framebuffer. * @returns The current status of this framebuffer. */ getStatus(): GLenum; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Handle to the framebuffer. */ framebuffer: WebGLFramebuffer; /** * Framebuffer width. */ width: number; /** * Framebuffer height. */ height: number; /** * Array of color attachments. */ colorAttachments: any[]; /** * Depth attachment. */ depthAttachment: Texture | Renderbuffer; /** * Tracked GL state. */ appState: any; } /** * Global PicoGL module. For convenience, all WebGL enums are stored * as properties of PicoGL (e.g. PicoGL.FLOAT, PicoGL.ONE_MINUS_SRC_ALPHA). */ export namespace PicoGL { var DEPTH_BUFFER_BIT: GLenum; var STENCIL_BUFFER_BIT: GLenum; var COLOR_BUFFER_BIT: GLenum; var POINTS: GLenum; var LINES: GLenum; var LINE_LOOP: GLenum; var LINE_STRIP: GLenum; var TRIANGLES: GLenum; var TRIANGLE_STRIP: GLenum; var TRIANGLE_FAN: GLenum; var ZERO: GLenum; var ONE: GLenum; var SRC_COLOR: GLenum; var ONE_MINUS_SRC_COLOR: GLenum; var SRC_ALPHA: GLenum; var ONE_MINUS_SRC_ALPHA: GLenum; var DST_ALPHA: GLenum; var ONE_MINUS_DST_ALPHA: GLenum; var DST_COLOR: GLenum; var ONE_MINUS_DST_COLOR: GLenum; var SRC_ALPHA_SATURATE: GLenum; var FUNC_ADD: GLenum; var BLEND_EQUATION: GLenum; var BLEND_EQUATION_RGB: GLenum; var BLEND_EQUATION_ALPHA: GLenum; var FUNC_SUBTRACT: GLenum; var FUNC_REVERSE_SUBTRACT: GLenum; var BLEND_DST_RGB: GLenum; var BLEND_SRC_RGB: GLenum; var BLEND_DST_ALPHA: GLenum; var BLEND_SRC_ALPHA: GLenum; var CONSTANT_COLOR: GLenum; var ONE_MINUS_CONSTANT_COLOR: GLenum; var CONSTANT_ALPHA: GLenum; var ONE_MINUS_CONSTANT_ALPHA: GLenum; var BLEND_COLOR: GLenum; var ARRAY_BUFFER: GLenum; var ELEMENT_ARRAY_BUFFER: GLenum; var ARRAY_BUFFER_BINDING: GLenum; var ELEMENT_ARRAY_BUFFER_BINDING: GLenum; var STREAM_DRAW: GLenum; var STATIC_DRAW: GLenum; var DYNAMIC_DRAW: GLenum; var BUFFER_SIZE: GLenum; var BUFFER_USAGE: GLenum; var CURRENT_VERTEX_ATTRIB: GLenum; var FRONT: GLenum; var BACK: GLenum; var FRONT_AND_BACK: GLenum; var CULL_FACE: GLenum; var BLEND: GLenum; var DITHER: GLenum; var STENCIL_TEST: GLenum; var DEPTH_TEST: GLenum; var SCISSOR_TEST: GLenum; var POLYGON_OFFSET_FILL: GLenum; var SAMPLE_ALPHA_TO_COVERAGE: GLenum; var SAMPLE_COVERAGE: GLenum; var NO_ERROR: GLenum; var INVALID_ENUM: GLenum; var INVALID_VALUE: GLenum; var INVALID_OPERATION: GLenum; var OUT_OF_MEMORY: GLenum; var CW: GLenum; var CCW: GLenum; var LINE_WIDTH: GLenum; var ALIASED_POINT_SIZE_RANGE: GLenum; var ALIASED_LINE_WIDTH_RANGE: GLenum; var CULL_FACE_MODE: GLenum; var FRONT_FACE: GLenum; var DEPTH_RANGE: GLenum; var DEPTH_WRITEMASK: GLenum; var DEPTH_CLEAR_VALUE: GLenum; var DEPTH_FUNC: GLenum; var STENCIL_CLEAR_VALUE: GLenum; var STENCIL_FUNC: GLenum; var STENCIL_FAIL: GLenum; var STENCIL_PASS_DEPTH_FAIL: GLenum; var STENCIL_PASS_DEPTH_PASS: GLenum; var STENCIL_REF: GLenum; var STENCIL_VALUE_MASK: GLenum; var STENCIL_WRITEMASK: GLenum; var STENCIL_BACK_FUNC: GLenum; var STENCIL_BACK_FAIL: GLenum; var STENCIL_BACK_PASS_DEPTH_FAIL: GLenum; var STENCIL_BACK_PASS_DEPTH_PASS: GLenum; var STENCIL_BACK_REF: GLenum; var STENCIL_BACK_VALUE_MASK: GLenum; var STENCIL_BACK_WRITEMASK: GLenum; var VIEWPORT: GLenum; var SCISSOR_BOX: GLenum; var COLOR_CLEAR_VALUE: GLenum; var COLOR_WRITEMASK: GLenum; var UNPACK_ALIGNMENT: GLenum; var PACK_ALIGNMENT: GLenum; var MAX_TEXTURE_SIZE: GLenum; var MAX_VIEWPORT_DIMS: GLenum; var SUBPIXEL_BITS: GLenum; var RED_BITS: GLenum; var GREEN_BITS: GLenum; var BLUE_BITS: GLenum; var ALPHA_BITS: GLenum; var DEPTH_BITS: GLenum; var STENCIL_BITS: GLenum; var POLYGON_OFFSET_UNITS: GLenum; var POLYGON_OFFSET_FACTOR: GLenum; var TEXTURE_BINDING_2D: GLenum; var SAMPLE_BUFFERS: GLenum; var SAMPLES: GLenum; var SAMPLE_COVERAGE_VALUE: GLenum; var SAMPLE_COVERAGE_INVERT: GLenum; var COMPRESSED_TEXTURE_FORMATS: GLenum; var DONT_CARE: GLenum; var FASTEST: GLenum; var NICEST: GLenum; var GENERATE_MIPMAP_HINT: GLenum; var BYTE: GLenum; var UNSIGNED_BYTE: GLenum; var SHORT: GLenum; var UNSIGNED_SHORT: GLenum; var INT: GLenum; var UNSIGNED_INT: GLenum; var FLOAT: GLenum; var DEPTH_COMPONENT: GLenum; var ALPHA: GLenum; var RGB: GLenum; var RGBA: GLenum; var LUMINANCE: GLenum; var LUMINANCE_ALPHA: GLenum; var UNSIGNED_SHORT_4_4_4_4: GLenum; var UNSIGNED_SHORT_5_5_5_1: GLenum; var UNSIGNED_SHORT_5_6_5: GLenum; var FRAGMENT_SHADER: GLenum; var VERTEX_SHADER: GLenum; var MAX_VERTEX_ATTRIBS: GLenum; var MAX_VERTEX_UNIFORM_VECTORS: GLenum; var MAX_VARYING_VECTORS: GLenum; var MAX_COMBINED_TEXTURE_IMAGE_UNITS: GLenum; var MAX_VERTEX_TEXTURE_IMAGE_UNITS: GLenum; var MAX_TEXTURE_IMAGE_UNITS: GLenum; var MAX_FRAGMENT_UNIFORM_VECTORS: GLenum; var SHADER_TYPE: GLenum; var DELETE_STATUS: GLenum; var LINK_STATUS: GLenum; var VALIDATE_STATUS: GLenum; var ATTACHED_SHADERS: GLenum; var ACTIVE_UNIFORMS: GLenum; var ACTIVE_ATTRIBUTES: GLenum; var SHADING_LANGUAGE_VERSION: GLenum; var CURRENT_PROGRAM: GLenum; var NEVER: GLenum; var LESS: GLenum; var EQUAL: GLenum; var LEQUAL: GLenum; var GREATER: GLenum; var NOTEQUAL: GLenum; var GEQUAL: GLenum; var ALWAYS: GLenum; var KEEP: GLenum; var REPLACE: GLenum; var INCR: GLenum; var DECR: GLenum; var INVERT: GLenum; var INCR_WRAP: GLenum; var DECR_WRAP: GLenum; var VENDOR: GLenum; var RENDERER: GLenum; var VERSION: GLenum; var NEAREST: GLenum; var LINEAR: GLenum; var NEAREST_MIPMAP_NEAREST: GLenum; var LINEAR_MIPMAP_NEAREST: GLenum; var NEAREST_MIPMAP_LINEAR: GLenum; var LINEAR_MIPMAP_LINEAR: GLenum; var TEXTURE_MAG_FILTER: GLenum; var TEXTURE_MIN_FILTER: GLenum; var TEXTURE_WRAP_S: GLenum; var TEXTURE_WRAP_T: GLenum; var TEXTURE_2D: GLenum; var TEXTURE: GLenum; var TEXTURE_CUBE_MAP: GLenum; var TEXTURE_BINDING_CUBE_MAP: GLenum; var TEXTURE_CUBE_MAP_POSITIVE_X: GLenum; var TEXTURE_CUBE_MAP_NEGATIVE_X: GLenum; var TEXTURE_CUBE_MAP_POSITIVE_Y: GLenum; var TEXTURE_CUBE_MAP_NEGATIVE_Y: GLenum; var TEXTURE_CUBE_MAP_POSITIVE_Z: GLenum; var TEXTURE_CUBE_MAP_NEGATIVE_Z: GLenum; var MAX_CUBE_MAP_TEXTURE_SIZE: GLenum; var TEXTURE0: GLenum; var TEXTURE1: GLenum; var TEXTURE2: GLenum; var TEXTURE3: GLenum; var TEXTURE4: GLenum; var TEXTURE5: GLenum; var TEXTURE6: GLenum; var TEXTURE7: GLenum; var TEXTURE8: GLenum; var TEXTURE9: GLenum; var TEXTURE10: GLenum; var TEXTURE11: GLenum; var TEXTURE12: GLenum; var TEXTURE13: GLenum; var TEXTURE14: GLenum; var TEXTURE15: GLenum; var TEXTURE16: GLenum; var TEXTURE17: GLenum; var TEXTURE18: GLenum; var TEXTURE19: GLenum; var TEXTURE20: GLenum; var TEXTURE21: GLenum; var TEXTURE22: GLenum; var TEXTURE23: GLenum; var TEXTURE24: GLenum; var TEXTURE25: GLenum; var TEXTURE26: GLenum; var TEXTURE27: GLenum; var TEXTURE28: GLenum; var TEXTURE29: GLenum; var TEXTURE30: GLenum; var TEXTURE31: GLenum; var ACTIVE_TEXTURE: GLenum; var REPEAT: GLenum; var CLAMP_TO_EDGE: GLenum; var MIRRORED_REPEAT: GLenum; var FLOAT_VEC2: GLenum; var FLOAT_VEC3: GLenum; var FLOAT_VEC4: GLenum; var INT_VEC2: GLenum; var INT_VEC3: GLenum; var INT_VEC4: GLenum; var BOOL: GLenum; var BOOL_VEC2: GLenum; var BOOL_VEC3: GLenum; var BOOL_VEC4: GLenum; var FLOAT_MAT2: GLenum; var FLOAT_MAT3: GLenum; var FLOAT_MAT4: GLenum; var SAMPLER_2D: GLenum; var SAMPLER_CUBE: GLenum; var VERTEX_ATTRIB_ARRAY_ENABLED: GLenum; var VERTEX_ATTRIB_ARRAY_SIZE: GLenum; var VERTEX_ATTRIB_ARRAY_STRIDE: GLenum; var VERTEX_ATTRIB_ARRAY_TYPE: GLenum; var VERTEX_ATTRIB_ARRAY_NORMALIZED: GLenum; var VERTEX_ATTRIB_ARRAY_POINTER: GLenum; var VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: GLenum; var IMPLEMENTATION_COLOR_READ_TYPE: GLenum; var IMPLEMENTATION_COLOR_READ_FORMAT: GLenum; var COMPILE_STATUS: GLenum; var LOW_FLOAT: GLenum; var MEDIUM_FLOAT: GLenum; var HIGH_FLOAT: GLenum; var LOW_INT: GLenum; var MEDIUM_INT: GLenum; var HIGH_INT: GLenum; var FRAMEBUFFER: GLenum; var RENDERBUFFER: GLenum; var RGBA4: GLenum; var RGB5_A1: GLenum; var RGB565: GLenum; var DEPTH_COMPONENT16: GLenum; var STENCIL_INDEX: GLenum; var STENCIL_INDEX8: GLenum; var DEPTH_STENCIL: GLenum; var RENDERBUFFER_WIDTH: GLenum; var RENDERBUFFER_HEIGHT: GLenum; var RENDERBUFFER_INTERNAL_FORMAT: GLenum; var RENDERBUFFER_RED_SIZE: GLenum; var RENDERBUFFER_GREEN_SIZE: GLenum; var RENDERBUFFER_BLUE_SIZE: GLenum; var RENDERBUFFER_ALPHA_SIZE: GLenum; var RENDERBUFFER_DEPTH_SIZE: GLenum; var RENDERBUFFER_STENCIL_SIZE: GLenum; var FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: GLenum; var FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: GLenum; var FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: GLenum; var FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: GLenum; var COLOR_ATTACHMENT0: GLenum; var DEPTH_ATTACHMENT: GLenum; var STENCIL_ATTACHMENT: GLenum; var DEPTH_STENCIL_ATTACHMENT: GLenum; var NONE: GLenum; var FRAMEBUFFER_COMPLETE: GLenum; var FRAMEBUFFER_INCOMPLETE_ATTACHMENT: GLenum; var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: GLenum; var FRAMEBUFFER_INCOMPLETE_DIMENSIONS: GLenum; var FRAMEBUFFER_UNSUPPORTED: GLenum; var FRAMEBUFFER_BINDING: GLenum; var RENDERBUFFER_BINDING: GLenum; var MAX_RENDERBUFFER_SIZE: GLenum; var INVALID_FRAMEBUFFER_OPERATION: GLenum; var UNPACK_FLIP_Y_WEBGL: GLenum; var UNPACK_PREMULTIPLY_ALPHA_WEBGL: GLenum; var CONTEXT_LOST_WEBGL: GLenum; var UNPACK_COLORSPACE_CONVERSION_WEBGL: GLenum; var BROWSER_DEFAULT_WEBGL: GLenum; var READ_BUFFER: GLenum; var UNPACK_ROW_LENGTH: GLenum; var UNPACK_SKIP_ROWS: GLenum; var UNPACK_SKIP_PIXELS: GLenum; var PACK_ROW_LENGTH: GLenum; var PACK_SKIP_ROWS: GLenum; var PACK_SKIP_PIXELS: GLenum; var COLOR: GLenum; var DEPTH: GLenum; var STENCIL: GLenum; var RED: GLenum; var RGB8: GLenum; var RGBA8: GLenum; var RGB10_A2: GLenum; var TEXTURE_BINDING_3D: GLenum; var UNPACK_SKIP_IMAGES: GLenum; var UNPACK_IMAGE_HEIGHT: GLenum; var TEXTURE_3D: GLenum; var TEXTURE_WRAP_R: GLenum; var MAX_3D_TEXTURE_SIZE: GLenum; var UNSIGNED_INT_2_10_10_10_REV: GLenum; var MAX_ELEMENTS_VERTICES: GLenum; var MAX_ELEMENTS_INDICES: GLenum; var TEXTURE_MIN_LOD: GLenum; var TEXTURE_MAX_LOD: GLenum; var TEXTURE_BASE_LEVEL: GLenum; var TEXTURE_MAX_LEVEL: GLenum; var MIN: GLenum; var MAX: GLenum; var DEPTH_COMPONENT24: GLenum; var MAX_TEXTURE_LOD_BIAS: GLenum; var TEXTURE_COMPARE_MODE: GLenum; var TEXTURE_COMPARE_FUNC: GLenum; var CURRENT_QUERY: GLenum; var QUERY_RESULT: GLenum; var QUERY_RESULT_AVAILABLE: GLenum; var STREAM_READ: GLenum; var STREAM_COPY: GLenum; var STATIC_READ: GLenum; var STATIC_COPY: GLenum; var DYNAMIC_READ: GLenum; var DYNAMIC_COPY: GLenum; var MAX_DRAW_BUFFERS: GLenum; var DRAW_BUFFER0: GLenum; var DRAW_BUFFER1: GLenum; var DRAW_BUFFER2: GLenum; var DRAW_BUFFER3: GLenum; var DRAW_BUFFER4: GLenum; var DRAW_BUFFER5: GLenum; var DRAW_BUFFER6: GLenum; var DRAW_BUFFER7: GLenum; var DRAW_BUFFER8: GLenum; var DRAW_BUFFER9: GLenum; var DRAW_BUFFER10: GLenum; var DRAW_BUFFER11: GLenum; var DRAW_BUFFER12: GLenum; var DRAW_BUFFER13: GLenum; var DRAW_BUFFER14: GLenum; var DRAW_BUFFER15: GLenum; var MAX_FRAGMENT_UNIFORM_COMPONENTS: GLenum; var MAX_VERTEX_UNIFORM_COMPONENTS: GLenum; var SAMPLER_3D: GLenum; var SAMPLER_2D_SHADOW: GLenum; var FRAGMENT_SHADER_DERIVATIVE_HINT: GLenum; var PIXEL_PACK_BUFFER: GLenum; var PIXEL_UNPACK_BUFFER: GLenum; var PIXEL_PACK_BUFFER_BINDING: GLenum; var PIXEL_UNPACK_BUFFER_BINDING: GLenum; var FLOAT_MAT2x3: GLenum; var FLOAT_MAT2x4: GLenum; var FLOAT_MAT3x2: GLenum; var FLOAT_MAT3x4: GLenum; var FLOAT_MAT4x2: GLenum; var FLOAT_MAT4x3: GLenum; var SRGB: GLenum; var SRGB8: GLenum; var SRGB8_ALPHA8: GLenum; var COMPARE_REF_TO_TEXTURE: GLenum; var RGBA32F: GLenum; var RGB32F: GLenum; var RGBA16F: GLenum; var RGB16F: GLenum; var VERTEX_ATTRIB_ARRAY_INTEGER: GLenum; var MAX_ARRAY_TEXTURE_LAYERS: GLenum; var MIN_PROGRAM_TEXEL_OFFSET: GLenum; var MAX_PROGRAM_TEXEL_OFFSET: GLenum; var MAX_VARYING_COMPONENTS: GLenum; var TEXTURE_2D_ARRAY: GLenum; var TEXTURE_BINDING_2D_ARRAY: GLenum; var R11F_G11F_B10F: GLenum; var UNSIGNED_INT_10F_11F_11F_REV: GLenum; var RGB9_E5: GLenum; var UNSIGNED_INT_5_9_9_9_REV: GLenum; var TRANSFORM_FEEDBACK_BUFFER_MODE: GLenum; var MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: GLenum; var TRANSFORM_FEEDBACK_VARYINGS: GLenum; var TRANSFORM_FEEDBACK_BUFFER_START: GLenum; var TRANSFORM_FEEDBACK_BUFFER_SIZE: GLenum; var TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: GLenum; var RASTERIZER_DISCARD: GLenum; var MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: GLenum; var MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: GLenum; var INTERLEAVED_ATTRIBS: GLenum; var SEPARATE_ATTRIBS: GLenum; var TRANSFORM_FEEDBACK_BUFFER: GLenum; var TRANSFORM_FEEDBACK_BUFFER_BINDING: GLenum; var RGBA32UI: GLenum; var RGB32UI: GLenum; var RGBA16UI: GLenum; var RGB16UI: GLenum; var RGBA8UI: GLenum; var RGB8UI: GLenum; var RGBA32I: GLenum; var RGB32I: GLenum; var RGBA16I: GLenum; var RGB16I: GLenum; var RGBA8I: GLenum; var RGB8I: GLenum; var RED_INTEGER: GLenum; var RGB_INTEGER: GLenum; var RGBA_INTEGER: GLenum; var SAMPLER_2D_ARRAY: GLenum; var SAMPLER_2D_ARRAY_SHADOW: GLenum; var SAMPLER_CUBE_SHADOW: GLenum; var UNSIGNED_INT_VEC2: GLenum; var UNSIGNED_INT_VEC3: GLenum; var UNSIGNED_INT_VEC4: GLenum; var INT_SAMPLER_2D: GLenum; var INT_SAMPLER_3D: GLenum; var INT_SAMPLER_CUBE: GLenum; var INT_SAMPLER_2D_ARRAY: GLenum; var UNSIGNED_INT_SAMPLER_2D: GLenum; var UNSIGNED_INT_SAMPLER_3D: GLenum; var UNSIGNED_INT_SAMPLER_CUBE: GLenum; var UNSIGNED_INT_SAMPLER_2D_ARRAY: GLenum; var DEPTH_COMPONENT32F: GLenum; var DEPTH32F_STENCIL8: GLenum; var FLOAT_32_UNSIGNED_INT_24_8_REV: GLenum; var FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: GLenum; var FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: GLenum; var FRAMEBUFFER_ATTACHMENT_RED_SIZE: GLenum; var FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: GLenum; var FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: GLenum; var FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: GLenum; var FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: GLenum; var FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: GLenum; var FRAMEBUFFER_DEFAULT: GLenum; var UNSIGNED_INT_24_8: GLenum; var DEPTH24_STENCIL8: GLenum; var UNSIGNED_NORMALIZED: GLenum; var DRAW_FRAMEBUFFER_BINDING: GLenum; var READ_FRAMEBUFFER: GLenum; var DRAW_FRAMEBUFFER: GLenum; var READ_FRAMEBUFFER_BINDING: GLenum; var RENDERBUFFER_SAMPLES: GLenum; var FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: GLenum; var MAX_COLOR_ATTACHMENTS: GLenum; var COLOR_ATTACHMENT1: GLenum; var COLOR_ATTACHMENT2: GLenum; var COLOR_ATTACHMENT3: GLenum; var COLOR_ATTACHMENT4: GLenum; var COLOR_ATTACHMENT5: GLenum; var COLOR_ATTACHMENT6: GLenum; var COLOR_ATTACHMENT7: GLenum; var COLOR_ATTACHMENT8: GLenum; var COLOR_ATTACHMENT9: GLenum; var COLOR_ATTACHMENT10: GLenum; var COLOR_ATTACHMENT11: GLenum; var COLOR_ATTACHMENT12: GLenum; var COLOR_ATTACHMENT13: GLenum; var COLOR_ATTACHMENT14: GLenum; var COLOR_ATTACHMENT15: GLenum; var FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: GLenum; var MAX_SAMPLES: GLenum; var HALF_FLOAT: GLenum; var RG: GLenum; var RG_INTEGER: GLenum; var R8: GLenum; var RG8: GLenum; var R16F: GLenum; var R32F: GLenum; var RG16F: GLenum; var RG32F: GLenum; var R8I: GLenum; var R8UI: GLenum; var R16I: GLenum; var R16UI: GLenum; var R32I: GLenum; var R32UI: GLenum; var RG8I: GLenum; var RG8UI: GLenum; var RG16I: GLenum; var RG16UI: GLenum; var RG32I: GLenum; var RG32UI: GLenum; var VERTEX_ARRAY_BINDING: GLenum; var R8_SNORM: GLenum; var RG8_SNORM: GLenum; var RGB8_SNORM: GLenum; var RGBA8_SNORM: GLenum; var SIGNED_NORMALIZED: GLenum; var COPY_READ_BUFFER: GLenum; var COPY_WRITE_BUFFER: GLenum; var COPY_READ_BUFFER_BINDING: GLenum; var COPY_WRITE_BUFFER_BINDING: GLenum; var UNIFORM_BUFFER: GLenum; var UNIFORM_BUFFER_BINDING: GLenum; var UNIFORM_BUFFER_START: GLenum; var UNIFORM_BUFFER_SIZE: GLenum; var MAX_VERTEX_UNIFORM_BLOCKS: GLenum; var MAX_FRAGMENT_UNIFORM_BLOCKS: GLenum; var MAX_COMBINED_UNIFORM_BLOCKS: GLenum; var MAX_UNIFORM_BUFFER_BINDINGS: GLenum; var MAX_UNIFORM_BLOCK_SIZE: GLenum; var MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: GLenum; var MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: GLenum; var UNIFORM_BUFFER_OFFSET_ALIGNMENT: GLenum; var ACTIVE_UNIFORM_BLOCKS: GLenum; var UNIFORM_TYPE: GLenum; var UNIFORM_SIZE: GLenum; var UNIFORM_BLOCK_INDEX: GLenum; var UNIFORM_OFFSET: GLenum; var UNIFORM_ARRAY_STRIDE: GLenum; var UNIFORM_MATRIX_STRIDE: GLenum; var UNIFORM_IS_ROW_MAJOR: GLenum; var UNIFORM_BLOCK_BINDING: GLenum; var UNIFORM_BLOCK_DATA_SIZE: GLenum; var UNIFORM_BLOCK_ACTIVE_UNIFORMS: GLenum; var UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES: GLenum; var UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER: GLenum; var UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER: GLenum; var INVALID_INDEX: GLenum; var MAX_VERTEX_OUTPUT_COMPONENTS: GLenum; var MAX_FRAGMENT_INPUT_COMPONENTS: GLenum; var MAX_SERVER_WAIT_TIMEOUT: GLenum; var OBJECT_TYPE: GLenum; var SYNC_CONDITION: GLenum; var SYNC_STATUS: GLenum; var SYNC_FLAGS: GLenum; var SYNC_FENCE: GLenum; var SYNC_GPU_COMMANDS_COMPLETE: GLenum; var UNSIGNALED: GLenum; var SIGNALED: GLenum; var ALREADY_SIGNALED: GLenum; var TIMEOUT_EXPIRED: GLenum; var CONDITION_SATISFIED: GLenum; var WAIT_FAILED: GLenum; var SYNC_FLUSH_COMMANDS_BIT: GLenum; var VERTEX_ATTRIB_ARRAY_DIVISOR: GLenum; var ANY_SAMPLES_PASSED: GLenum; var ANY_SAMPLES_PASSED_CONSERVATIVE: GLenum; var SAMPLER_BINDING: GLenum; var RGB10_A2UI: GLenum; var INT_2_10_10_10_REV: GLenum; var TRANSFORM_FEEDBACK: GLenum; var TRANSFORM_FEEDBACK_PAUSED: GLenum; var TRANSFORM_FEEDBACK_ACTIVE: GLenum; var TRANSFORM_FEEDBACK_BINDING: GLenum; var TEXTURE_IMMUTABLE_FORMAT: GLenum; var MAX_ELEMENT_INDEX: GLenum; var TEXTURE_IMMUTABLE_LEVELS: GLenum; var TIMEOUT_IGNORED: GLenum; var MAX_CLIENT_WAIT_TIMEOUT_WEBGL: GLenum; var QUERY_COUNTER_BITS_EXT: GLenum; var TIME_ELAPSED_EXT: GLenum; var TIMESTAMP_EXT: GLenum; var GPU_DISJOINT_EXT: GLenum; var TEXTURE_MAX_ANISOTROPY_EXT: GLenum; var MAX_TEXTURE_MAX_ANISOTROPY_EXT: GLenum; var UNMASKED_VENDOR_WEBGL: GLenum; var UNMASKED_RENDERER_WEBGL: GLenum; var COMPLETION_STATUS_KHR: GLenum; var COMPRESSED_RGB_S3TC_DXT1_EXT: GLenum; var COMPRESSED_RGBA_S3TC_DXT1_EXT: GLenum; var COMPRESSED_RGBA_S3TC_DXT3_EXT: GLenum; var COMPRESSED_RGBA_S3TC_DXT5_EXT: GLenum; var COMPRESSED_SRGB_S3TC_DXT1_EXT: GLenum; var COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: GLenum; var COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: GLenum; var COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: GLenum; var COMPRESSED_R11_EAC: GLenum; var COMPRESSED_SIGNED_R11_EAC: GLenum; var COMPRESSED_RG11_EAC: GLenum; var COMPRESSED_SIGNED_RG11_EAC: GLenum; var COMPRESSED_RGB8_ETC2: GLenum; var COMPRESSED_SRGB8_ETC2: GLenum; var COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: GLenum; var COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: GLenum; var COMPRESSED_RGBA8_ETC2_EAC: GLenum; var COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: GLenum; var COMPRESSED_RGB_PVRTC_4BPPV1_IMG: GLenum; var COMPRESSED_RGB_PVRTC_2BPPV1_IMG: GLenum; var COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: GLenum; var COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: GLenum; var COMPRESSED_RGBA_ASTC_4x4_KHR: GLenum; var COMPRESSED_RGBA_ASTC_5x4_KHR: GLenum; var COMPRESSED_RGBA_ASTC_5x5_KHR: GLenum; var COMPRESSED_RGBA_ASTC_6x5_KHR: GLenum; var COMPRESSED_RGBA_ASTC_6x6_KHR: GLenum; var COMPRESSED_RGBA_ASTC_8x5_KHR: GLenum; var COMPRESSED_RGBA_ASTC_8x6_KHR: GLenum; var COMPRESSED_RGBA_ASTC_8x8_KHR: GLenum; var COMPRESSED_RGBA_ASTC_10x5_KHR: GLenum; var COMPRESSED_RGBA_ASTC_10x6_KHR: GLenum; var COMPRESSED_RGBA_ASTC_10x8_KHR: GLenum; var COMPRESSED_RGBA_ASTC_10x10_KHR: GLenum; var COMPRESSED_RGBA_ASTC_12x10_KHR: GLenum; var COMPRESSED_RGBA_ASTC_12x12_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: GLenum; var COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: GLenum; /** * The version of PicoGL */ var version: string; /** * WebGL information about the current system */ var WEBGL_INFO: { [key: string]: any; }; /** * Create a PicoGL app. The app is the primary entry point to PicoGL. It stores * the canvas, the WebGL context and all WebGL state. * @param canvas - The canvas on which to create the WebGL context. * @param [contextAttributes] - Context attributes to pass when calling getContext(). * @returns New App object. */ function createApp(canvas: HTMLElement, contextAttributes?: any): App; } /** * This is a hack to be able to document the default export :( */ export default PicoGL; /** * WebGL program consisting of compiled and linked vertex and fragment * shaders. * @property gl - The WebGL context. * @property program - The WebGL program. * @property transformFeedbackVaryings - Names of transform feedback varyings, if any. * @property transformFeedbackMode - Capture mode of the transform feedback. * @property attributeLocations - Map of user-provided attribute names to indices, if any. * @property uniforms - Map of uniform names to handles. * @property appState - Tracked GL state. */ export class Program { /** * Restore program after context loss. Note that this * will stall for completion. <b>App.restorePrograms</b> * is the preferred method for program restoration as * it will parallelize compilation where available. * @returns The Program object. */ restore(): Program; /** * Get the vertex shader source translated for the platform's API. * @returns The translated vertex shader source. */ translatedVertexSource(): string; /** * Get the fragment shader source translated for the platform's API. * @returns The translated fragment shader source. */ translatedFragmentSource(): string; /** * Delete this program. * @returns The Program object. */ delete(): Program; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * The WebGL program. */ program: WebGLProgram; /** * Names of transform feedback varyings, if any. */ transformFeedbackVaryings: any[]; /** * Capture mode of the transform feedback. */ transformFeedbackMode: GlEnum; /** * Map of user-provided attribute names to indices, if any. */ attributeLocations: { [key: string]: number; }; /** * Map of uniform names to handles. */ uniforms: any; /** * Tracked GL state. */ appState: any; } /** * Generic query object. * @property gl - The WebGL context. * @property query - Query object. * @property target - The type of information being queried. * @property active - Whether or not a query is currently in progress. * @property result - The result of the query (only available after a call to ready() returns true). */ export class Query { /** * Restore query after context loss. * @returns The Query object. */ restore(): Query; /** * Begin a query. * @returns The Query object. */ begin(): Query; /** * End a query. * @returns The Query object. */ end(): Query; /** * Check if query result is available. * @returns If results are available. */ ready(): boolean; /** * Delete this query. * @returns The Query object. */ delete(): Query; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Query object. */ query: WebGLQuery; /** * The type of information being queried. */ target: GLenum; /** * Whether or not a query is currently in progress. */ active: boolean; /** * The result of the query (only available after a call to ready() returns true). */ result: any; } /** * Offscreen drawing attachment. * @property gl - The WebGL context. * @property renderbuffer - Handle to the renderbuffer. * @property width - Renderbuffer width. * @property height - Renderbuffer height. * @property internalFormat - Internal arrangement of the renderbuffer data. * @property samples - Number of MSAA samples. */ export class Renderbuffer { /** * Restore renderbuffer after context loss. * @returns The Renderbuffer object. */ restore(): Renderbuffer; /** * Resize the renderbuffer. * @param width - New width of the renderbuffer. * @param height - New height of the renderbuffer. * @returns The Renderbuffer object. */ resize(width: number, height: number): Renderbuffer; /** * Delete this renderbuffer. * @returns The Renderbuffer object. */ delete(): Renderbuffer; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Handle to the renderbuffer. */ renderbuffer: WebGLRenderbuffer; /** * Renderbuffer width. */ width: number; /** * Renderbuffer height. */ height: number; /** * Internal arrangement of the renderbuffer data. */ internalFormat: GLenum; /** * Number of MSAA samples. */ samples: number; } /** * WebGL shader. * @property gl - The WebGL context. * @property shader - The shader. */ export class Shader { /** * Restore shader after context loss. * @returns The Shader object. */ restore(): Shader; /** * Get the shader source translated for the platform's API. * @returns The translated shader source. */ translatedSource(): string; /** * Delete this shader. * @returns The Shader object. */ delete(): Shader; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * The shader. */ shader: WebGLShader; } /** * General-purpose texture. * @property gl - The WebGL context. * @property texture - Handle to the texture. * @property width - Texture width. * @property height - Texture height. * @property depth - Texture depth. * @property binding - Binding point for the texture. * @property type - Type of data stored in the texture. * @property format - Layout of texture data. * @property internalFormat - Internal arrangement of the texture data. * @property currentUnit - The current texture unit this texture is bound to. * @property is3D - Whether this texture contains 3D data. * @property flipY - Whether the y-axis is flipped for this texture. * @property premultiplyAlpha - Whether alpha should be pre-multiplied when loading this texture. * @property mipmaps - Whether this texture is using mipmap filtering * (and thus should have a complete mipmap chain). * @property appState - Tracked GL state. */ export class Texture { /** * Restore texture after context loss. * @param [image] - Image data. An array can be passed to manually set all levels * of the mipmap chain. If a single level is passed and mipmap filtering is being used, * generateMipmap() will be called to produce the remaining levels. * @returns The Texture object. */ restore(image?: HTMLElement | ArrayBufferView | any[]): Texture; /** * Re-allocate texture storage. * @param width - Image width. * @param height - Image height. * @param [depth] - Image depth or number of images. Required when passing 3D or texture array data. * @returns The Texture object. */ resize(width: number, height: number, depth?: number): Texture; /** * Set the image data for the texture. An array can be passed to manually set all levels * of the mipmap chain. If a single level is passed and mipmap filtering is being used, * generateMipmap() will be called to produce the remaining levels. * NOTE: the data must fit the currently-allocated storage! * @param data - Image data. If an array is passed, it will be * used to set mip map levels. * @returns The Texture object. */ data(data: HTMLImageElement | ArrayBufferView | any[]): Texture; /** * Delete this texture. * @returns The Texture object. */ delete(): Texture; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Handle to the texture. */ texture: WebGLTexture; /** * Texture width. */ width: number; /** * Texture height. */ height: number; /** * Texture depth. */ depth: number; /** * Binding point for the texture. */ binding: GLenum; /** * Type of data stored in the texture. */ type: GLenum; /** * Layout of texture data. */ format: GLenum; /** * Internal arrangement of the texture data. */ internalFormat: GLenum; /** * The current texture unit this texture is bound to. */ currentUnit: number; /** * Whether this texture contains 3D data. */ is3D: boolean; /** * Whether the y-axis is flipped for this texture. */ flipY: boolean; /** * Whether alpha should be pre-multiplied when loading this texture. */ premultiplyAlpha: boolean; /** * Whether this texture is using mipmap filtering (and thus should have a complete mipmap chain). */ mipmaps: boolean; /** * Tracked GL state. */ appState: any; } /** * Rendering timer. * @property gl - The WebGL context. * @property cpuTimer - Timer for CPU. Will be window.performance, if available, or window.Date. * @property gpuTimerQuery - Timer query object for GPU (if gpu timing is supported). * @property gpuTimerQueryInProgress - Whether a gpu timer query is currently in progress. * @property cpuStartTime - When the last CPU timing started. * @property cpuTime - Time spent on CPU during last timing. Only valid if ready() returns true. * @property gpuTime - Time spent on GPU during last timing. Only valid if ready() returns true. * Will remain 0 if extension EXT_disjoint_timer_query_webgl2 is unavailable. */ export class Timer { /** * Restore timer after context loss. * @returns The Timer object. */ restore(): Timer; /** * Start timing. * @returns The Timer object. */ start(): Timer; /** * Stop timing. * @returns The Timer object. */ end(): Timer; /** * Check if timing results are available. If * this method returns true, the cpuTime and * gpuTime properties will be set to valid * values. * @returns If results are available. */ ready(): boolean; /** * Delete this timer. * @returns The Timer object. */ delete(): Timer; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Timer for CPU. Will be window.performance, if available, or window.Date. */ cpuTimer: any; /** * Timer query object for GPU (if gpu timing is supported). */ gpuTimerQuery: WebGLQuery; /** * Whether a gpu timer query is currently in progress. */ gpuTimerQueryInProgress: boolean; /** * When the last CPU timing started. */ cpuStartTime: number; /** * Time spent on CPU during last timing. Only valid if ready() returns true. */ cpuTime: number; /** * Time spent on GPU during last timing. Only valid if ready() returns true. Will remain 0 if extension EXT_disjoint_timer_query_webgl2 is unavailable. */ gpuTime: number; } /** * Tranform feedback object. * @property gl - The WebGL context. * @property transformFeedback - Transform feedback object. * @property appState - Tracked GL state. */ export class TransformFeedback { /** * Restore transform feedback after context loss. * @returns The TransformFeedback object. */ restore(): TransformFeedback; /** * Bind a feedback buffer to capture transform output. * @param index - Index of transform feedback varying to capture. * @param buffer - Buffer to record output into. * @returns The TransformFeedback object. */ feedbackBuffer(index: number, buffer: VertexBuffer): TransformFeedback; /** * Delete this transform feedback. * @returns The TransformFeedback object. */ delete(): TransformFeedback; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Transform feedback object. */ transformFeedback: WebGLTransformFeedback; /** * Tracked GL state. */ appState: any; } /** * Storage for uniform data. Data is stored in std140 layout. * @property gl - The WebGL context. * @property buffer - Allocated buffer storage. * @property data - Buffer data. * @property dataViews - Map of base data types to matching ArrayBufferViews of the buffer data. * @property offsets - Offsets into the array for each item in the buffer. * @property sizes - Size of the item at the given offset. * @property types - The base type of the item at the given offset (FLOAT, INT or UNSIGNED_INT). * @property size - The size of the buffer (in 4-byte items). * @property usage - Usage pattern of the buffer. */ export class UniformBuffer { /** * Restore uniform buffer after context loss. * @returns The UniformBuffer object. */ restore(): UniformBuffer; /** * Update data for a given item in the buffer. NOTE: Data is not * sent the the GPU until the update() method is called! * @param index - Index in the layout of item to set. * @param value - Value to store at the layout location. * @returns The UniformBuffer object. */ set(index: number, value: ArrayBufferView): UniformBuffer; /** * Send stored buffer data to the GPU. * @returns The UniformBuffer object. */ update(): UniformBuffer; /** * Delete this uniform buffer. * @returns The UniformBuffer object. */ delete(): UniformBuffer; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Allocated buffer storage. */ buffer: WebGLBuffer; /** * Buffer data. */ data: Float32Array; /** * Map of base data types to matching ArrayBufferViews of the buffer data. */ dataViews: any; /** * Offsets into the array for each item in the buffer. */ offsets: any[]; /** * Size of the item at the given offset. */ sizes: any[]; /** * The base type of the item at the given offset (FLOAT, INT or UNSIGNED_INT). */ types: any[]; /** * The size of the buffer (in 4-byte items). */ size: number; /** * Usage pattern of the buffer. */ usage: GLenum; } /** * Organizes vertex buffer and attribute state. * @property gl - The WebGL context. * @property vertexArray - Vertex array object. * @property numElements - Number of elements in the vertex array. * @property indexed - Whether this vertex array is set up for indexed drawing. * @property indexType - Data type of the indices. * @property numInstances - Number of instances to draw with this vertex array. * @property appState - Tracked GL state. */ export class VertexArray { /** * Restore vertex array after context loss. * @returns The VertexArray object. */ restore(): VertexArray; /** * Bind an per-vertex attribute buffer to this vertex array. * @param attributeIndex - The attribute location to bind to. * @param vertexBuffer - The VertexBuffer to bind. * @param [options] - Attribute pointer options. These will override those provided in the * VertexBuffer. * @param [options.type] - Type of data stored in the buffer. * @param [options.size] - Number of components per vertex. * @param [options.stride] - Number of bytes between the start of data for each vertex. * @param [options.offset] - Number of bytes before the start of data for the first vertex. * @param [options.normalized] - Data is integer data that should be normalized to a float. * @param [options.integer] - Pass data as integers. * @returns The VertexArray object. */ vertexAttributeBuffer(attributeIndex: number, vertexBuffer: VertexBuffer, options?: { type?: GLenum; size?: GLenum; stride?: GLenum; offset?: GLenum; normalized?: GLenum; integer?: GLenum; }): VertexArray; /** * Bind an per-instance attribute buffer to this vertex array. * @param attributeIndex - The attribute location to bind to. * @param vertexBuffer - The VertexBuffer to bind. * @param [options] - Attribute pointer options. These will override those provided in the * VertexBuffer. * @param [options.type] - Type of data stored in the buffer. * @param [options.size] - Number of components per vertex. * @param [options.stride] - Number of bytes between the start of data for each vertex. * @param [options.offset] - Number of bytes before the start of data for the first vertex. * @param [options.normalized] - Data is integer data that should be normalized to a float. * @param [options.integer] - Pass data as integers. * @returns The VertexArray object. */ instanceAttributeBuffer(attributeIndex: number, vertexBuffer: VertexBuffer, options?: { type?: GLenum; size?: GLenum; stride?: GLenum; offset?: GLenum; normalized?: GLenum; integer?: GLenum; }): VertexArray; /** * Bind an index buffer to this vertex array. * @param vertexBuffer - The VertexBuffer to bind. * @returns The VertexArray object. */ indexBuffer(vertexBuffer: VertexBuffer): VertexArray; /** * Delete this vertex array. * @returns The VertexArray object. */ delete(): VertexArray; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Vertex array object. */ vertexArray: WebGLVertexArrayObject; /** * Number of elements in the vertex array. */ numElements: number; /** * Whether this vertex array is set up for indexed drawing. */ indexed: boolean; /** * Data type of the indices. */ indexType: GLenum; /** * Number of instances to draw with this vertex array. */ numInstances: number; /** * Tracked GL state. */ appState: any; } /** * Storage for vertex data. * @property gl - The WebGL context. * @property buffer - Allocated buffer storage. * @property type - The type of data stored in the buffer. * @property itemSize - Number of array elements per vertex. * @property numItems - Number of vertices represented. * @property usage - The usage pattern of the buffer. * @property indexArray - Whether this is an index array. * @property binding - GL binding point (ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER). * @property appState - Tracked GL state. */ export class VertexBuffer { /** * Restore vertex buffer after context loss. * @param data - Buffer data itself or the total * number of elements to be allocated. * @returns The VertexBuffer object. */ restore(data: ArrayBufferView | number): VertexBuffer; /** * Update data in this buffer. NOTE: the data must fit * the originally-allocated buffer! * @param data - Data to store in the buffer. * @param [offset = 0] - Byte offset into the buffer at which to start writing. * @returns The VertexBuffer object. */ data(data: ArrayBufferView, offset?: number): VertexBuffer; /** * Delete this array buffer. * @returns The VertexBuffer object. */ delete(): VertexBuffer; /** * The WebGL context. */ gl: WebGLRenderingContext; /** * Allocated buffer storage. */ buffer: WebGLBuffer; /** * The type of data stored in the buffer. */ type: GLenum; /** * Number of array elements per vertex. */ itemSize: number; /** * Number of vertices represented. */ numItems: number; /** * The usage pattern of the buffer. */ usage: GLenum; /** * Whether this is an index array. */ indexArray: boolean; /** * GL binding point (ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER). */ binding: GLenum; /** * Tracked GL state. */ appState: any; }
the_stack
import {Pt, Group, Bound} from "./Pt"; import {Num} from "./Num"; import {ITempoListener, ITempoStartFn, ITempoProgressFn, ITempoResponses} from "./Types"; import {ISoundAnalyzer, SoundType, PtLike, IPlayer} from "./Types"; /** * Tempo helps you create synchronized and rhythmic animations. */ export class Tempo implements IPlayer { protected _bpm: number; // beat per minute protected _ms: number; // millis per beat protected _listeners:{ [key:string]:ITempoListener } = {}; protected _listenerInc:number = 0; public animateID:string; /** * Construct a new Tempo instance by beats-per-minute. Alternatively, you can use [`Tempo.fromBeat`](#link) to create from milliseconds. * @param bpm beats per minute */ constructor( bpm:number ) { this.bpm = bpm; } /** * Create a new Tempo instance by specifying milliseconds-per-beat. * @param ms milliseconds per beat */ static fromBeat( ms:number ):Tempo { return new Tempo( 60000 / ms ); } /** * Beats-per-minute value */ get bpm():number { return this._bpm; } set bpm( n:number ) { this._bpm = n; this._ms = 60000 / this._bpm; } /** * Milliseconds per beat (Note that this is derived from the bpm value). */ get ms():number { return this._ms; } set ms( n:number ) { this._bpm = Math.floor( 60000/n ); this._ms = 60000 / this._bpm; } // Get a listener unique id protected _createID( listener:ITempoListener|Function ):string { let id:string = ''; if (typeof listener === 'function') { id = '_b'+(this._listenerInc++); } else { id = listener.name || '_b'+(this._listenerInc++); } return id; } /** * This is a core function that let you specify a rhythm and then define responses by calling the `start` and `progress` functions from the returned object. See [Animation guide](../guide/Animation-0700.html) for more details. * The `start` function lets you set a callback on every start. It takes a function ([`ITempoStartFn`](#link)). * The `progress` function lets you set a callback during progress. It takes a function ([`ITempoProgressFn`](#link)). Both functions let you optionally specify a time offset and a custom name. * See [Animation guide](../guide/animation-0700.html) for more details. * @param beats a rhythm in beats as a number or an array of numbers * @example `tempo.every(2).start( (count) => ... )`, `tempo.every([2,4,6]).progress( (count, t) => ... )` * @returns an object with chainable functions */ every( beats:number|number[] ):ITempoResponses { let self = this; let p = Array.isArray(beats) ? beats[0] : beats; return { start: function (fn:ITempoStartFn, offset:number=0, name?:string): string { let id = name || self._createID( fn ); self._listeners[id] = { name: id, beats: beats, period: p, index: 0, offset: offset, duration: -1, continuous: false, fn: fn }; return this; }, progress: function (fn:ITempoProgressFn, offset:number=0, name?:string ): string { let id = name || self._createID( fn ); self._listeners[id] = { name: id, beats: beats, period: p, index: 0, offset: offset, duration: -1, continuous: true, fn: fn }; return this; } }; } /** * Usually you can add a tempo instance to a space via [`Space.add`](#link) and it will track time automatically. * But if necessary, you can track time manually via this function. * @param time current time in milliseconds */ track( time ) { for (let k in this._listeners) { if (this._listeners.hasOwnProperty(k)) { let li = this._listeners[k]; let _t = (li.offset) ? time + li.offset : time; let ms = li.period * this._ms; // time per period let isStart = false; if (_t > li.duration + ms) { li.duration = _t - (_t % this._ms); // update if (Array.isArray( li.beats )) { // find next period from array li.index = (li.index + 1) % li.beats.length; li.period = li.beats[ li.index ]; } isStart = true; } let count = Math.max(0, Math.ceil( Math.floor(li.duration / this._ms)/li.period ) ); let params = (li.continuous) ? [count, Num.clamp( (_t - li.duration)/ms, 0, 1), _t, isStart] : [count]; if (li.continuous || isStart) { let done = li.fn.apply( li, params ); if (done) delete this._listeners[ li.name ]; } } } } /** * Remove a `start` or `progress` callback function from the list of callbacks. See [`Tempo.every`](#link) for details * @param name a name string specified when creating the callback function. */ stop( name:string ):void { if (this._listeners[name]) delete this._listeners[name]; } /** * IPlayer interface. Internal implementation that calls `track( time )`. */ animate( time, ftime ) { this.track( time ); } /** * IPlayer interface. Not implementated. */ resize( bound:Bound, evt?:Event ) { return; // not implemented in IPlayer } /** * IPlayer interface. Not implementated. */ action( type:string, px:number, py:number, evt:Event ) { return; } } /** * Sound class simplifies common tasks like audio inputs and visualizations using a subset of Web Audio API. It can be used with other audio libraries like tone.js, and extended to support additional web audio functions. See [the guide](../guide/Sound-0800.html) to get started. */ export class Sound { private _type:SoundType; /** The audio context */ _ctx:AudioContext; /** The audio node, which is usually a subclass liked OscillatorNode */ _node:AudioNode; /** * The audio node to be connected to AudioContext when playing, if different that _node * This is usefull when using the connect() function to filter, as typically the output would * come from the filtering nodes */ _outputNode:AudioNode; /** The audio stream when streaming from input device */ _stream:MediaStream; /** Audio src when loading from file */ _source:HTMLMediaElement; /* Audio buffer when using AudioBufferSourceNode */ _buffer:AudioBuffer; /** Analyzer if any */ analyzer:ISoundAnalyzer; protected _playing:boolean = false; protected _timestamp:number; // Tracking play time against ctx.currentTime /** * Construct a `Sound` instance. Usually, it's more convenient to use one of the static methods like [`Sound.load`](#function_load) or [`Sound.from`](#function_from). * @param type a `SoundType` string: "file", "input", or "gen" */ constructor( type:SoundType ) { this._type = type; // @ts-ignore let _ctx = window.AudioContext || window.webkitAudioContext || false; if (!_ctx) throw( new Error("Your browser doesn't support Web Audio. (No AudioContext)") ); this._ctx = (_ctx) ? new _ctx() : undefined; } /** * Create a `Sound` given an [AudioNode](https://developer.mozilla.org/en-US/docs/Web/API/AudioNode) and an [AudioContext](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) from Web Audio API. See also [this example](../guide/js/examples/tone.html) using tone.js in the [guide](../guide/Sound-0800.html). * @param node an AudioNode instance * @param ctx an AudioContext instance * @param type a string representing a type of input source: either "file", "input", or "gen". * @param stream Optionally include a MediaStream, if the type is "input" * @returns a `Sound` instance */ static from( node:AudioNode, ctx:AudioContext, type:SoundType="gen", stream?:MediaStream ) { let s = new Sound( type ); s._node = node; s._ctx = ctx; if (stream) s._stream = stream; return s; } /** * Create a `Sound` by loading from a sound file or an audio element. * @param source either an url string to load a sound file, or an audio element. * @param crossOrigin whether to support loading cross-origin. Default is "anonymous". * @returns a `Sound` instance * @example `Sound.load( '/path/to/file.mp3' )` */ static load( source:HTMLMediaElement|string, crossOrigin:string="anonymous" ):Promise<Sound> { return new Promise( (resolve, reject) => { let s = new Sound("file"); s._source = (typeof source === 'string') ? new Audio(source) : source; s._source.autoplay = false; (s._source as HTMLMediaElement).crossOrigin = crossOrigin; s._source.addEventListener("ended", function () { s._playing = false; } ); s._source.addEventListener('error', function () { reject("Error loading sound"); }); s._source.addEventListener('canplaythrough', function () { s._node = s._ctx.createMediaElementSource( s._source ); resolve( s ); }); }); } /** * Create a `Sound` by loading from a sound file url as `AudioBufferSourceNode`. This method is cumbersome since it can only be played once. * Use this method for now if you need to visualize sound in Safari and iOS. Once Apple has full support for FFT with streaming `HTMLMediaElement`, this method will likely be deprecated. * @param url an url to the sound file */ static loadAsBuffer( url:string ):Promise<Sound> { return new Promise( (resolve, reject) => { let request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; let s = new Sound("file"); request.onload = function() { s._ctx.decodeAudioData(request.response, function(buffer) { // Decode asynchronously s.createBuffer( buffer ); resolve( s ); }, (err) => reject("Error decoding audio") ); }; request.send(); }); } /** * Create or re-use an AudioBuffer. Only needed if you are using `Sound.loadAsBuffer`. * @param buf an AudioBuffer. Optionally, you can call this without parameters to re-use existing buffer. */ protected createBuffer( buf:AudioBuffer ):this { this._node = this._ctx.createBufferSource(); if (buf !== undefined) this._buffer = buf; (this._node as AudioBufferSourceNode).buffer = this._buffer; // apply or re-use buffer (this._node as AudioBufferSourceNode).onended = () => { this._playing = false; }; return this; } /** * Create a `Sound` by generating a waveform using [OscillatorNode](https://developer.mozilla.org/en-US/docs/Web/API/OscillatorNode). * @param type a string representing the waveform type: "sine", "square", "sawtooth", "triangle", "custom" * @param val the frequency value in Hz to play, or a PeriodicWave instance if type is "custom". * @returns a `Sound` instance * @example `Sound.generate( 'sine', 120 )` */ static generate( type:OscillatorType, val:number|PeriodicWave ):Sound { let s = new Sound("gen"); return s._gen( type, val ); } // Create the oscillator protected _gen( type:OscillatorType, val:number|PeriodicWave ):Sound { this._node = this._ctx.createOscillator(); let osc = (this._node as OscillatorNode); osc.type = type; if (type === 'custom') { osc.setPeriodicWave( val as PeriodicWave ); } else { osc.frequency.value = val as number; } return this; } /** * Create a `Sound` by streaming from an input device like microphone. Note that this function returns a Promise which resolves to a Sound instance. * @param constraint @param constraint Optional constraints which can be used to select a specific input device. For example, you may use [`enumerateDevices`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) to find a specific deviceId; * @returns a `Promise` which resolves to `Sound` instance * @example `Sound.input().then( s => sound = s );` */ static async input( constraint?:MediaStreamConstraints ):Promise<Sound> { try { let s = new Sound("input"); if (!s) return undefined; const c = constraint ? constraint : { audio: true, video: false }; s._stream = await navigator.mediaDevices.getUserMedia( c ); s._node = s._ctx.createMediaStreamSource( s._stream ); return s; } catch (e) { console.error( "Cannot get audio from input device."); return Promise.resolve( null ); } } /** * Get this Sound's AudioContext instance for advanced use-cases. */ get ctx():AudioContext { return this._ctx; } /** * Get this Sound's AudioNode subclass instance for advanced use-cases. */ get node():AudioNode { return this._node; } /** * Get this Sound's Output node AudioNode instance for advanced use-cases. */ get outputNode():AudioNode { return this._outputNode; } /** * Get this Sound's MediaStream (eg, from microphone, if in use) instance for advanced use-cases. See [`Sound.input`](#link) */ get stream():MediaStream { return this._stream; } /** * Get this Sound's Audio element (if used) instance for advanced use-cases. See [`Sound.load`](#link). */ get source():HTMLMediaElement { return this._source; } /** * Get this Sound's AudioBuffer (if any) instance for advanced use-cases. See [`Sound.loadAsBuffer`](#link). */ get buffer():AudioBuffer { return this._buffer; } set buffer( b:AudioBuffer ) { this._buffer = b; } /** * Get the type of input for this Sound instance. Either "file", "input", or "gen" */ get type():SoundType { return this._type; } /** * Indicate whether the sound is currently playing. */ get playing():boolean { return this._playing; } /** * A value between 0 to 1 to indicate playback progress. */ get progress():number { let dur = 0; let curr = 0; if (!!this._buffer) { dur = this._buffer.duration; curr = (this._timestamp) ? this._ctx.currentTime - this._timestamp : 0; } else { dur = this._source.duration; curr = this._source.currentTime; } return curr / dur; } /** * Indicate whether the sound is ready to play. When loading from a file, this corresponds to a ["canplaythrough"](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState) event. * You can also use `this.source.addEventListener( 'canplaythrough', ...)` if needed. See also [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event). */ get playable():boolean { return (this._type === "input") ? this._node !== undefined : (!!this._buffer || this._source.readyState === 4); } /** * If an analyzer is added (see [`analyze`](##unction_analyze) function), get the number of frequency bins in the analyzer. */ get binSize():number { return this.analyzer.size; } /** * Get the sample rate of the audio, for example, at 44100 hz. */ get sampleRate():number { return this._ctx.sampleRate; } /** * If the sound is generated, this sets and gets the frequency of the tone. */ get frequency():number { return (this._type === "gen") ? (this._node as OscillatorNode).frequency.value : 0; } set frequency( f:number ) { if (this._type === "gen") (this._node as OscillatorNode).frequency.value = f; } /** * Connect another AudioNode to this `Sound` instance's AudioNode. Using this function, you can extend the capabilities of this `Sound` instance for advanced use cases such as filtering. * @param node another AudioNode */ connect( node:AudioNode ):this { this._node.connect( node ); return this; } /** * Sets the 'output' node for this Sound * This would typically be used after Sound.connect, if you are adding nodes * in your chain for filtering purposes. * @param outputNode The AudioNode that should connect to the AudioContext */ setOutputNode(outputNode: AudioNode):this { this._outputNode = outputNode; return this; } /** * Removes the 'output' node added from setOuputNode * Note: if you start the Sound after calling this, it will play via the default node */ removeOutputNode():this { this._outputNode = null; return this; } /** * Add an analyzer to this `Sound`. Call this once only. * @param size the number of frequency bins * @param minDb Optional minimum decibels (corresponds to `AnalyserNode.minDecibels`) * @param maxDb Optional maximum decibels (corresponds to `AnalyserNode.maxDecibels`) * @param smooth Optional smoothing value (corresponds to `AnalyserNode.smoothingTimeConstant`) */ analyze( size:number=256, minDb:number=-100, maxDb:number=-30, smooth:number=0.8 ) { let a = this._ctx.createAnalyser(); a.fftSize = size * 2; a.minDecibels = minDb; a.maxDecibels = maxDb; a.smoothingTimeConstant = smooth; this.analyzer = { node: a, size: a.frequencyBinCount, data: new Uint8Array(a.frequencyBinCount) }; this._node.connect( this.analyzer.node ); return this; } // Get either time-domain or frequency domain protected _domain( time:boolean ):Uint8Array { if (this.analyzer) { if (time) { this.analyzer.node.getByteTimeDomainData( this.analyzer.data ); } else { this.analyzer.node.getByteFrequencyData( this.analyzer.data ); } return this.analyzer.data; } return new Uint8Array(0); } // Map domain data to another range protected _domainTo( time:boolean, size:PtLike, position:PtLike=[0,0], trim=[0,0] ):Group { let data = (time) ? this.timeDomain() : this.freqDomain() ; let g = new Group(); for (let i=trim[0], len=data.length-trim[1]; i<len; i++) { g.push( new Pt( position[0] + size[0] * i/len, position[1] + size[1] * data[i]/255 ) ); } return g; } /** * Get the raw time-domain data from analyzer as unsigned 8-bit integers. An analyzer must be added before calling this function (See [analyze](#function_analyze) function). */ timeDomain():Uint8Array { return this._domain( true ); } /** * Map the time-domain data from analyzer to a range. An analyzer must be added before calling this function (See [analyze](#function_analyze) function). * @param size map each data point `[index, value]` to `[width, height]` * @param position Optionally, set a starting `[x, y]` position. Default is `[0, 0]` * @param trim Optionally, trim the start and end values by `[startTrim, data.length-endTrim]` * @returns a Group containing the mapped values * @example form.point( s.timeDomainTo( space.size ) ) */ timeDomainTo( size:PtLike, position:PtLike=[0,0], trim=[0,0] ):Group { return this._domainTo( true, size, position, trim ); } /** * Get the raw frequency-domain data from analyzer as unsigned 8-bit integers. An analyzer must be added before calling this function (See [analyze](#function_analyze) function). */ freqDomain():Uint8Array { return this._domain( false ); } /** * Map the frequency-domain data from analyzer to a range. An analyzer must be added before calling this function (See [analyze](#function_analyze) function). * @param size map each data point `[index, value]` to `[width, height]` * @param position Optionally, set a starting `[x, y]` position. Default is `[0, 0]` * @param trim Optionally, trim the start and end values by `[startTrim, data.length-endTrim]` * @returns a Group containing the mapped values * @example `form.point( s.freqDomainTo( space.size ) )` */ freqDomainTo( size:PtLike, position:PtLike=[0,0], trim=[0,0] ):Group { return this._domainTo( false, size, position, trim ); } /** * Stop playing and disconnect the AudioNode. */ reset():this { this.stop(); this._node.disconnect(); return this; } /** * Start playing. Internally this connects the `AudioNode` to `AudioContext`'s destination. * @param timeAt optional parameter to play from a specific time */ start( timeAt:number=0 ):this { if (this._ctx.state === 'suspended') this._ctx.resume(); if (this._type === "file") { if (!!this._buffer) { (this._node as AudioBufferSourceNode).start(timeAt); this._timestamp = this._ctx.currentTime + timeAt; } else { this._source.play(); if (timeAt > 0) this._source.currentTime = timeAt; } } else if (this._type === "gen") { this._gen( (this._node as OscillatorNode).type, (this._node as OscillatorNode).frequency.value ); (this._node as OscillatorNode).start(); if (this.analyzer) this._node.connect( this.analyzer.node ); } (this._outputNode || this._node).connect( this._ctx.destination ); this._playing = true; return this; } /** * Stop playing. Internally this also disconnects the `AudioNode` from `AudioContext`'s destination. */ stop():this { if (this._playing) (this._outputNode || this._node).disconnect( this._ctx.destination ); if (this._type === "file") { if (!!this._buffer) { // Safari throws InvalidState error if stop() is called after finished playing if (this.progress < 1) (this._node as AudioBufferSourceNode).stop(); } else { this._source.pause(); } } else if (this._type === "gen") { (this._node as OscillatorNode).stop(); } else if (this._type === "input") { this._stream.getAudioTracks().forEach( track => track.stop() ); } this._playing = false; return this; } /** * Toggle between `start` and `stop`. This won't work if using [`Sound.loadAsBuffer`](#link), since `AudioBuffer` can only be played once. (See [`Sound.createBuffer`](#link) to reset buffer for replay). */ toggle():this { if (this._playing) { this.stop(); } else { this.start(); } return this; } }
the_stack
* Created by Dolkkok on 2017. 8. 14.. */ import {AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit} from '@angular/core'; import { AxisType, CHART_STRING_DELIMITER, ChartType, LineType, Position, SeriesType, ShelveFieldType, ShelveType, UIChartDataLabelDisplayType } from '../option/define/common'; import {OptionGenerator} from '../option/util/option-generator'; import {Series} from '../option/define/series'; import * as _ from 'lodash'; import {Pivot} from 'app/domain/workbook/configurations/pivot'; import {BaseChart, PivotTableInfo} from '../base-chart'; import {BaseOption} from '../option/base-option'; import {FormatOptionConverter} from '../option/converter/format-option-converter'; import {UIChartFormat} from '../option/ui-option/ui-format'; import {AxisOptionConverter} from '../option/converter/axis-option-converter'; import optGen = OptionGenerator; import {UIOption} from '@common/component/chart/option/ui-option'; declare let echarts: any; @Component({ selector: 'boxplot-chart', template: '<div class="chartCanvas" style="width: 100%; height: 100%; display: block;"></div>' }) export class BoxPlotChartComponent extends BaseChart<UIOption> implements OnInit, AfterViewInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ constructor( protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Getter & Setter |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { super.ngOnInit(); } // Destroy public ngOnDestroy() { super.ngOnDestroy(); } // After View Init public ngAfterViewInit(): void { super.ngAfterViewInit(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 선반정보를 기반으로 차트를 그릴수 있는지 여부를 체크 * * @param shelve */ public isValid(shelve: Pivot): boolean { return ((this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.DIMENSION) + this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.TIMESTAMP)) === 1) && ((this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.MEASURE) + this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.CALCULATED)) === 1) && ((this.getFieldTypeCount(shelve, ShelveType.COLUMNS, ShelveFieldType.DIMENSION) + this.getFieldTypeCount(shelve, ShelveType.COLUMNS, ShelveFieldType.TIMESTAMP)) > 0) && (this.getFieldTypeCount(shelve, ShelveType.COLUMNS, ShelveFieldType.MEASURE) === 0 && this.getFieldTypeCount(shelve, ShelveType.COLUMNS, ShelveFieldType.CALCULATED) === 0) && (this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.MEASURE) === 0 && this.getFieldTypeCount(shelve, ShelveType.ROWS, ShelveFieldType.CALCULATED) === 0) && (this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.DIMENSION) === 0 && this.getFieldTypeCount(shelve, ShelveType.AGGREGATIONS, ShelveFieldType.TIMESTAMP) === 0); } public draw(isKeepRange?: boolean): void { // pivot cols, rows 초기화 const cols: string[] = []; this.data.columns.map((column) => { cols.push(column.name); return column.value; }); this.pivotInfo = new PivotTableInfo(cols, [], this.fieldInfo.aggs); super.draw(isKeepRange); } /** * 시리즈 데이터 선택 - 차트별 재설정 * @param seriesData */ protected selectSeriesData(seriesData) { this.chartOption.series.forEach(seriesItem => { seriesItem.data.forEach(dataItem => { if (dataItem.name === seriesData.name) { dataItem.itemStyle.normal.opacity = 1; dataItem.selected = true; return true; } return false; }); }); } // function - selectSeriesData /** * 시리즈 데이터 선택 해제 - 차트별 재설정 * @param seriesData */ protected unselectSeriesData(seriesData) { this.chartOption.series.forEach(seriesItem => { seriesItem.data.forEach(dataItem => { if (dataItem.name === seriesData.name) { dataItem.itemStyle.normal.opacity = 0.2; dataItem.selected = false; return true; } return false; }); }); } // function - unselectSeriesData /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 차트의 기본 옵션을 생성한다. * - 각 차트에서 Override */ protected initOption(): BaseOption { return { type: ChartType.BOXPLOT, grid: [OptionGenerator.Grid.verticalMode(10, 0, 0, 10, false, true, false)], xAxis: [OptionGenerator.Axis.categoryAxis(Position.MIDDLE, null, false, true, true, true)], yAxis: [OptionGenerator.Axis.valueAxis(Position.MIDDLE, null, false, false, true, true, true)], dataZoom: [OptionGenerator.DataZoom.horizontalDataZoom(), OptionGenerator.DataZoom.horizontalInsideDataZoom()], tooltip: OptionGenerator.Tooltip.itemTooltip(), toolbox: OptionGenerator.Toolbox.hiddenToolbox(), series: [] }; } /** * 차트별 시리즈 추가정보 * - 반드시 각 차트에서 Override * @returns {BaseOption} */ protected convertSeriesData(): BaseOption { let boxItem: Series; let outlierItem: Series; const columns = this.data.columns; let boxPlotData = columns.map((column) => { return column.value; }); boxPlotData = echarts.dataTool.prepareBoxplotData(boxPlotData); // Box 데이터 구성 boxItem = { type: SeriesType.BOXPLOT, name: this.fieldInfo.aggs[0], data: boxPlotData.boxData.map((val, idx) => { return { name: columns[idx].name, value: val, selected: false, itemStyle: OptionGenerator.ItemStyle.opacity1() } }), originData: _.cloneDeep(boxPlotData.boxData), hoverAnimation: false, itemStyle: { normal: {borderWidth: 1, borderType: LineType.SOLID}, emphasis: {borderWidth: 1, borderType: LineType.SOLID} }, tooltip: { formatter: (params) => { return this.tooltipFormatter(params); } } }; // outlier 데이터 구성 outlierItem = { type: SeriesType.SCATTER, symbolSize: 8, itemStyle: optGen.ItemStyle.auto(), data: boxPlotData.outliers.map((val, _idx) => { return { name: columns[val[0]].name, value: val, selected: false, itemStyle: OptionGenerator.ItemStyle.opacity1() } }), originData: _.cloneDeep(boxPlotData.outliers), tooltip: { formatter: (param) => { return FormatOptionConverter.getFormatValue(param.value[1], this.uiOption.valueFormat.isAll ? this.uiOption.valueFormat : this.uiOption.valueFormat.each[0]); } } }; // 시리즈 설정 this.chartOption.series = [boxItem, outlierItem]; return this.chartOption; } /** * 박스플롯으로 series로 설정되는 부분 */ protected additionalSeries(): BaseOption { // outlier 색상은 빨간색으로 고정 this.chartOption.series[1].itemStyle.normal.color = '#ca4819'; return this.chartOption; } /** * 셀렉션 이벤트를 등록한다. * - 필요시 각 차트에서 Override */ protected selection(): void { this.addChartSelectEventListener(); } /** * 박스플롯으로 xAxis 설정되는 부분 */ protected additionalXAxis(): BaseOption { this.chartOption.xAxis[0].data = this.data.columns.map((column) => { return column.name; }); // 축 Label 최대길이 설정 this.chartOption = AxisOptionConverter.convertAxisLabelMaxLength(this.chartOption, this.uiOption, AxisType.X); return this.chartOption; } /** * 차트 선택 데이터 설정 * * @param params * @param colValues * @param _rowValues * @returns {any} */ protected setSelectData(params: any, colValues: string[], _rowValues: string[]): any { const returnDataList: any = []; // 선택정보 설정 let targetValues: string[] = []; _.forEach(this.pivot, (_value, key) => { // deep copy let deepCopyShelve = _.cloneDeep(this.pivot[key]); // dimension timestamp 데이터만 설정 deepCopyShelve = _.filter(deepCopyShelve, (obj) => { if (_.eq(obj.type, ShelveFieldType.DIMENSION) || _.eq(obj.type, ShelveFieldType.TIMESTAMP)) { return obj; } }); deepCopyShelve.map((obj, idx) => { // 선택한 데이터 정보가 있을 경우에만 차원값필드와 맵핑 if (!_.isNull(params)) { if (_.eq(key, ShelveType.ROWS)) return; targetValues = colValues; } // 해당 차원값에 선택 데이터 값을 맵핑, null값인경우 데이터가 들어가지 않게 설정 if (!_.isEmpty(targetValues) && targetValues[idx]) { // object 형식으로 returnData 설정 if (-1 === _.findIndex(returnDataList, {name: obj.name})) { returnDataList.push(obj); } returnDataList[returnDataList.length - 1].data = [targetValues[idx]]; } }); }); return returnDataList; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * tooltip formatter * * @param params * @returns {any} */ private tooltipFormatter(params): any { let format: UIChartFormat = this.uiOption.valueFormat; // 축의 포멧이 있는경우 축의 포멧으로 설정 const axisFormat = FormatOptionConverter.getlabelAxisScaleFormatTooltip(this.uiOption); if (axisFormat) format = axisFormat; let result: string[] = []; let valueList = params.data.length ? params.data : params.data.value; if (!this.uiOption.toolTip || !this.uiOption.toolTip.displayTypes) { const nameList = _.split(params.name, CHART_STRING_DELIMITER); result = FormatOptionConverter.getTooltipName(nameList, this.pivot.columns, result, true); result.push('High: ' + FormatOptionConverter.getFormatValue(valueList[0], format)); result.push('3Q: ' + FormatOptionConverter.getFormatValue(valueList[1], format)); result.push('Median: ' + FormatOptionConverter.getFormatValue(valueList[2], format)); result.push('1Q: ' + FormatOptionConverter.getFormatValue(valueList[3], format)); result.push('Low: ' + FormatOptionConverter.getFormatValue(valueList[4], format)); } else { if (-1 !== this.uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.CATEGORY_NAME)) { const nameList = _.split(params.name, CHART_STRING_DELIMITER); result = FormatOptionConverter.getTooltipName(nameList, this.pivot.columns, result, true); } if (-1 !== this.uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.HIGH_VALUE)) { result.push('High: ' + FormatOptionConverter.getFormatValue(valueList[0], format)); } if (-1 !== this.uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.THREE_Q_VALUE)) { result.push('3Q: ' + FormatOptionConverter.getFormatValue(valueList[3], format)); } if (-1 !== this.uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.MEDIAN_VALUE)) { result.push('Median: ' + FormatOptionConverter.getFormatValue(valueList[2], format)); } if (-1 !== this.uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.FIRST_Q_VALUE)) { result.push('1Q: ' + FormatOptionConverter.getFormatValue(valueList[1], format)); } if (-1 !== this.uiOption.toolTip.displayTypes.indexOf(UIChartDataLabelDisplayType.LOW_VALUE)) { result.push('Low: ' + FormatOptionConverter.getFormatValue(valueList[4], format)); } } return result.join('<br/>'); } }
the_stack
import { rest, stream, paginate, RequestOptions } from "../request"; import { AuthClient, TwitterResponse, TwitterBody, TwitterParams, TwitterPaginatedResponse, } from "../types"; import { OAuth2Bearer } from "../auth"; import { findUsersById, findUserById, findUsersByUsername, findMyUser, findUserByUsername, usersIdBlock, usersIdBlocking, usersIdUnblock, getUsersIdBookmarks, postUsersIdBookmarks, usersIdBookmarksDelete, usersIdUnmute, usersIdMute, usersIdMuting, usersIdFollowers, usersIdFollowing, usersIdFollow, usersIdUnfollow, userFollowedLists, listUserFollow, listUserUnfollow, getUserListMemberships, listUserOwnedLists, listUserPinnedLists, listUserPin, listUserUnpin, findTweetsById, createTweet, findTweetById, deleteTweetById, findTweetsThatQuoteATweet, hideReplyById, tweetsRecentSearch, tweetsFullarchiveSearch, searchStream, getRules, addOrDeleteRules, sampleStream, getOpenApiSpec, usersIdTimeline, usersIdTweets, usersIdMentions, usersIdLike, usersIdUnlike, usersIdLikedTweets, tweetsIdLikingUsers, tweetsIdRetweetingUsers, usersIdRetweets, usersIdUnretweets, tweetCountsRecentSearch, tweetCountsFullArchiveSearch, listBatchComplianceJobs, createBatchComplianceJob, getBatchComplianceJob, listIdCreate, listIdDelete, listIdUpdate, listIdGet, listGetFollowers, listAddMember, listGetMembers, listRemoveMember, listsIdTweets, findSpaceById, findSpacesByIds, findSpacesByCreatorIds, searchSpaces, spaceTweets, spaceBuyers, } from "./openapi-types"; /** * Twitter API TypeScript Client * * TypeScript SDK for use with the Twitter API * */ export class Client { #auth: AuthClient; #defaultRequestOptions?: Partial<RequestOptions>; constructor( auth: string | AuthClient, requestOptions?: Partial<RequestOptions> ) { this.#auth = typeof auth === "string" ? new OAuth2Bearer(auth) : auth; this.#defaultRequestOptions = requestOptions; } /** * Bookmarks * * Endpoints related to retrieving, managing bookmarks of a user * * Find out more * https://developer.twitter.com/en/docs/twitter-api/bookmarks */ public readonly bookmarks = { /** * Bookmarks by User * * Returns Tweet objects that have been bookmarked by the requesting user * @param id - The ID of the user for whom to return results * @param params - The params for getUsersIdBookmarks * @param request_options - Customize the options for this request */ getUsersIdBookmarks: ( id: string, params: TwitterParams<getUsersIdBookmarks> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<getUsersIdBookmarks>> => paginate<TwitterResponse<getUsersIdBookmarks>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/bookmarks`, params, method: "GET", }), /** * Add Tweet to Bookmarks * * Adds a Tweet (ID in the body) to the requesting user's (in the path) bookmarks * @param id - The ID of the user for whom to add bookmarks * @param request_body - The request_body for postUsersIdBookmarks * @param request_options - Customize the options for this request */ postUsersIdBookmarks: ( id: string, request_body: TwitterBody<postUsersIdBookmarks>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<postUsersIdBookmarks>> => rest<TwitterResponse<postUsersIdBookmarks>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/bookmarks`, request_body, method: "POST", }), /** * Remove a bookmarked Tweet * * Removes a Tweet from the requesting user's bookmarked Tweets. * @param id - The ID of the user whose bookmark is to be removed. * @param tweet_id - The ID of the tweet that the user is removing from bookmarks * @param request_options - Customize the options for this request */ usersIdBookmarksDelete: ( id: string, tweet_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdBookmarksDelete>> => rest<TwitterResponse<usersIdBookmarksDelete>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/bookmarks/${tweet_id}`, method: "DELETE", }), }; /** * Compliance * * Endpoints related to keeping Twitter data in your systems compliant * * Find out more * https://developer.twitter.com/en/docs/twitter-api/compliance/batch-tweet/introduction */ public readonly compliance = { /** * List compliance jobs * * Returns recent compliance jobs for a given job type and optional job status * @param params - The params for listBatchComplianceJobs * @param request_options - Customize the options for this request */ listBatchComplianceJobs: ( params: TwitterParams<listBatchComplianceJobs>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listBatchComplianceJobs>> => rest<TwitterResponse<listBatchComplianceJobs>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/compliance/jobs`, params, method: "GET", }), /** * Create compliance job * * Creates a compliance for the given job type * @param request_body - The request_body for createBatchComplianceJob * @param request_options - Customize the options for this request */ createBatchComplianceJob: ( request_body: TwitterBody<createBatchComplianceJob>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<createBatchComplianceJob>> => rest<TwitterResponse<createBatchComplianceJob>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/compliance/jobs`, request_body, method: "POST", }), /** * Get compliance job * * Returns a single compliance job by ID * @param id - ID of the compliance job to retrieve. * @param request_options - Customize the options for this request */ getBatchComplianceJob: ( id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<getBatchComplianceJob>> => rest<TwitterResponse<getBatchComplianceJob>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/compliance/jobs/${id}`, method: "GET", }), }; /** * General * * Miscellaneous endpoints for general API functionality * * Find out more * https://developer.twitter.com/en/docs/twitter-api */ public readonly general = { /** * Returns the open api spec document. * * Full open api spec in JSON format. (See https://github.com/OAI/OpenAPI-Specification/blob/master/README.md) * @param request_options - Customize the options for this request */ getOpenApiSpec: ( request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<getOpenApiSpec>> => rest<TwitterResponse<getOpenApiSpec>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/openapi.json`, method: "GET", }), }; /** * Lists * * Endpoints related to retrieving, managing Lists * * Find out more * https://developer.twitter.com/en/docs/twitter-api/lists */ public readonly lists = { /** * Get User's Followed Lists * * Returns a user's followed Lists. * @param id - The ID of the user for whom to return results * @param params - The params for userFollowedLists * @param request_options - Customize the options for this request */ userFollowedLists: ( id: string, params: TwitterParams<userFollowedLists> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<userFollowedLists>> => paginate<TwitterResponse<userFollowedLists>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/followed_lists`, params, method: "GET", }), /** * Follow a List * * Causes a user to follow a List. * @param id - The ID of the authenticated source user that will follow the List * @param request_body - The request_body for listUserFollow * @param request_options - Customize the options for this request */ listUserFollow: ( id: string, request_body: TwitterBody<listUserFollow>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listUserFollow>> => rest<TwitterResponse<listUserFollow>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/followed_lists`, request_body, method: "POST", }), /** * Unfollow a List * * Causes a user to unfollow a List. * @param id - The ID of the authenticated source user that will unfollow the List * @param list_id - The ID of the List to unfollow * @param request_options - Customize the options for this request */ listUserUnfollow: ( id: string, list_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listUserUnfollow>> => rest<TwitterResponse<listUserUnfollow>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/followed_lists/${list_id}`, method: "DELETE", }), /** * Get a User's List Memberships * * Get a User's List Memberships. * @param id - The ID of the user for whom to return results * @param params - The params for getUserListMemberships * @param request_options - Customize the options for this request */ getUserListMemberships: ( id: string, params: TwitterParams<getUserListMemberships> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<getUserListMemberships>> => paginate<TwitterResponse<getUserListMemberships>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/list_memberships`, params, method: "GET", }), /** * Get a User's Owned Lists * * Get a User's Owned Lists. * @param id - The ID of the user for whom to return results * @param params - The params for listUserOwnedLists * @param request_options - Customize the options for this request */ listUserOwnedLists: ( id: string, params: TwitterParams<listUserOwnedLists> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<listUserOwnedLists>> => paginate<TwitterResponse<listUserOwnedLists>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/owned_lists`, params, method: "GET", }), /** * Get a User's Pinned Lists * * Get a User's Pinned Lists. * @param id - The ID of the user for whom to return results * @param params - The params for listUserPinnedLists * @param request_options - Customize the options for this request */ listUserPinnedLists: ( id: string, params: TwitterParams<listUserPinnedLists> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listUserPinnedLists>> => rest<TwitterResponse<listUserPinnedLists>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/pinned_lists`, params, method: "GET", }), /** * Pin a List * * Causes a user to pin a List. * @param id - The ID of the authenticated source user that will pin the List * @param request_body - The request_body for listUserPin * @param request_options - Customize the options for this request */ listUserPin: ( id: string, request_body: TwitterBody<listUserPin>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listUserPin>> => rest<TwitterResponse<listUserPin>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/pinned_lists`, request_body, method: "POST", }), /** * Unpin a List * * Causes a user to remove a pinned List. * @param id - The ID of the authenticated source user that will remove the pinned List * @param list_id - The ID of the List to unpin * @param request_options - Customize the options for this request */ listUserUnpin: ( id: string, list_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listUserUnpin>> => rest<TwitterResponse<listUserUnpin>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/pinned_lists/${list_id}`, method: "DELETE", }), /** * Create List * * Creates a new List. * @param request_body - The request_body for listIdCreate * @param request_options - Customize the options for this request */ listIdCreate: ( request_body: TwitterBody<listIdCreate>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listIdCreate>> => rest<TwitterResponse<listIdCreate>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists`, request_body, method: "POST", }), /** * Delete List * * Delete a List that you own. * @param id - The ID of the List to delete * @param request_options - Customize the options for this request */ listIdDelete: ( id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listIdDelete>> => rest<TwitterResponse<listIdDelete>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}`, method: "DELETE", }), /** * Update List * * Update a List that you own. * @param id - The ID of the List to modify * @param request_body - The request_body for listIdUpdate * @param request_options - Customize the options for this request */ listIdUpdate: ( id: string, request_body: TwitterBody<listIdUpdate>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listIdUpdate>> => rest<TwitterResponse<listIdUpdate>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}`, request_body, method: "PUT", }), /** * List lookup by List ID * * Returns a List * @param id - The ID of the List to get * @param params - The params for listIdGet * @param request_options - Customize the options for this request */ listIdGet: ( id: string, params: TwitterParams<listIdGet> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listIdGet>> => rest<TwitterResponse<listIdGet>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}`, params, method: "GET", }), /** * Add a List member * * Causes a user to become a member of a List. * @param id - The ID of the List to add a member * @param request_body - The request_body for listAddMember * @param request_options - Customize the options for this request */ listAddMember: ( id: string, request_body: TwitterBody<listAddMember>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listAddMember>> => rest<TwitterResponse<listAddMember>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}/members`, request_body, method: "POST", }), /** * Remove a List member * * Causes a user to be removed from the members of a List. * @param id - The ID of the List to remove a member * @param user_id - The ID of user that will be removed from the List * @param request_options - Customize the options for this request */ listRemoveMember: ( id: string, user_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<listRemoveMember>> => rest<TwitterResponse<listRemoveMember>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}/members/${user_id}`, method: "DELETE", }), }; /** * Spaces * * Endpoints related to retrieving, managing Spaces * * Find out more * https://developer.twitter.com/en/docs/twitter-api/spaces */ public readonly spaces = { /** * Space lookup by Space ID * * Returns a variety of information about the Space specified by the requested ID * @param id - The space id to be retrieved * @param params - The params for findSpaceById * @param request_options - Customize the options for this request */ findSpaceById: ( id: string, params: TwitterParams<findSpaceById> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findSpaceById>> => rest<TwitterResponse<findSpaceById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/spaces/${id}`, params, method: "GET", }), /** * Space lookup up Space IDs * * Returns a variety of information about the Spaces specified by the requested IDs * @param params - The params for findSpacesByIds * @param request_options - Customize the options for this request */ findSpacesByIds: ( params: TwitterParams<findSpacesByIds>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findSpacesByIds>> => rest<TwitterResponse<findSpacesByIds>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/spaces`, params, method: "GET", }), /** * Space lookup by their creators * * Returns a variety of information about the Spaces created by the provided User IDs * @param params - The params for findSpacesByCreatorIds * @param request_options - Customize the options for this request */ findSpacesByCreatorIds: ( params: TwitterParams<findSpacesByCreatorIds>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findSpacesByCreatorIds>> => rest<TwitterResponse<findSpacesByCreatorIds>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/spaces/by/creator_ids`, params, method: "GET", }), /** * Search for Spaces * * Returns Spaces that match the provided query. * @param params - The params for searchSpaces * @param request_options - Customize the options for this request */ searchSpaces: ( params: TwitterParams<searchSpaces>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<searchSpaces>> => rest<TwitterResponse<searchSpaces>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/spaces/search`, params, method: "GET", }), /** * Retrieve tweets from a Space * * Retrieves tweets shared in the specified space * @param id - The space id from which tweets will be retrieved * @param params - The params for spaceTweets * @param request_options - Customize the options for this request */ spaceTweets: ( id: string, params: TwitterParams<spaceTweets> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<spaceTweets>> => rest<TwitterResponse<spaceTweets>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/spaces/${id}/tweets`, params, method: "GET", }), /** * Retrieve the list of users who purchased a ticket to the given space * * Retrieves the list of users who purchased a ticket to the given space * @param id - The space id from which tweets will be retrieved * @param params - The params for spaceBuyers * @param request_options - Customize the options for this request */ spaceBuyers: ( id: string, params: TwitterParams<spaceBuyers> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<spaceBuyers>> => rest<TwitterResponse<spaceBuyers>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/spaces/${id}/buyers`, params, method: "GET", }), }; /** * Tweets * * Endpoints related to retrieving, searching, and modifying Tweets * * Find out more * https://developer.twitter.com/en/docs/twitter-api/tweets/lookup */ public readonly tweets = { /** * Tweet lookup by Tweet IDs * * Returns a variety of information about the Tweet specified by the requested ID. * @param params - The params for findTweetsById * @param request_options - Customize the options for this request */ findTweetsById: ( params: TwitterParams<findTweetsById>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findTweetsById>> => rest<TwitterResponse<findTweetsById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets`, params, method: "GET", }), /** * Creation of a Tweet * * Causes the user to create a tweet under the authorized account. * @param request_body - The request_body for createTweet * @param request_options - Customize the options for this request */ createTweet: ( request_body: TwitterBody<createTweet>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<createTweet>> => rest<TwitterResponse<createTweet>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets`, request_body, method: "POST", }), /** * Tweet lookup by Tweet ID * * Returns a variety of information about the Tweet specified by the requested ID. * @param id - A single Tweet ID. * @param params - The params for findTweetById * @param request_options - Customize the options for this request */ findTweetById: ( id: string, params: TwitterParams<findTweetById> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findTweetById>> => rest<TwitterResponse<findTweetById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/${id}`, params, method: "GET", }), /** * Tweet delete by Tweet ID * * Delete specified Tweet (in the path) by ID. * @param id - The ID of the Tweet to be deleted. * @param request_options - Customize the options for this request */ deleteTweetById: ( id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<deleteTweetById>> => rest<TwitterResponse<deleteTweetById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/${id}`, method: "DELETE", }), /** * Retrieve tweets that quote a tweet. * * Returns a variety of information about each tweet that quotes the Tweet specified by the requested ID. * @param id - The ID of the Quoted Tweet. * @param params - The params for findTweetsThatQuoteATweet * @param request_options - Customize the options for this request */ findTweetsThatQuoteATweet: ( id: string, params: TwitterParams<findTweetsThatQuoteATweet> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findTweetsThatQuoteATweet>> => rest<TwitterResponse<findTweetsThatQuoteATweet>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/${id}/quote_tweets`, params, method: "GET", }), /** * Hide replies * * Hides or unhides a reply to an owned conversation. * @param id - The ID of the reply that you want to hide or unhide. * @param request_body - The request_body for hideReplyById * @param request_options - Customize the options for this request */ hideReplyById: ( id: string, request_body: TwitterBody<hideReplyById>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<hideReplyById>> => rest<TwitterResponse<hideReplyById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/${id}/hidden`, request_body, method: "PUT", }), /** * Recent search * * Returns Tweets from the last 7 days that match a search query. * @param params - The params for tweetsRecentSearch * @param request_options - Customize the options for this request */ tweetsRecentSearch: ( params: TwitterParams<tweetsRecentSearch>, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<tweetsRecentSearch>> => paginate<TwitterResponse<tweetsRecentSearch>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/search/recent`, params, method: "GET", }), /** * Full-archive search * * Returns Tweets that match a search query. * @param params - The params for tweetsFullarchiveSearch * @param request_options - Customize the options for this request */ tweetsFullarchiveSearch: ( params: TwitterParams<tweetsFullarchiveSearch>, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<tweetsFullarchiveSearch>> => paginate<TwitterResponse<tweetsFullarchiveSearch>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/search/all`, params, method: "GET", }), /** * Filtered stream * * Streams Tweets matching the stream's active rule set. * @param params - The params for searchStream * @param request_options - Customize the options for this request */ searchStream: ( params: TwitterParams<searchStream> = {}, request_options?: Partial<RequestOptions> ): AsyncGenerator<TwitterResponse<searchStream>> => stream<TwitterResponse<searchStream>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/search/stream`, params, method: "GET", }), /** * Rules lookup * * Returns rules from a user's active rule set. Users can fetch all of their rules or a subset, specified by the provided rule ids. * @param params - The params for getRules * @param request_options - Customize the options for this request */ getRules: ( params: TwitterParams<getRules> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<getRules>> => paginate<TwitterResponse<getRules>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/search/stream/rules`, params, method: "GET", }), /** * Add/Delete rules * * Add or delete rules from a user's active rule set. Users can provide unique, optionally tagged rules to add. Users can delete their entire rule set or a subset specified by rule ids or values. * @param params - The params for addOrDeleteRules * @param request_body - The request_body for addOrDeleteRules * @param request_options - Customize the options for this request */ addOrDeleteRules: ( request_body: TwitterBody<addOrDeleteRules>, params: TwitterParams<addOrDeleteRules> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<addOrDeleteRules>> => rest<TwitterResponse<addOrDeleteRules>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/search/stream/rules`, params, request_body, method: "POST", }), /** * Sample stream * * Streams a deterministic 1% of public Tweets. * @param params - The params for sampleStream * @param request_options - Customize the options for this request */ sampleStream: ( params: TwitterParams<sampleStream> = {}, request_options?: Partial<RequestOptions> ): AsyncGenerator<TwitterResponse<sampleStream>> => stream<TwitterResponse<sampleStream>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/sample/stream`, params, method: "GET", }), /** * User home timeline by User ID * * Returns Tweet objects that appears in the provided User ID's home timeline * @param id - The ID of the User to list Reverse Chronological Timeline Tweets of * @param params - The params for usersIdTimeline * @param request_options - Customize the options for this request */ usersIdTimeline: ( id: string, params: TwitterParams<usersIdTimeline> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdTimeline>> => paginate<TwitterResponse<usersIdTimeline>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/timelines/reverse_chronological`, params, method: "GET", }), /** * User Tweets timeline by User ID * * Returns a list of Tweets authored by the provided User ID * @param id - The ID of the User to list Tweets of * @param params - The params for usersIdTweets * @param request_options - Customize the options for this request */ usersIdTweets: ( id: string, params: TwitterParams<usersIdTweets> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdTweets>> => paginate<TwitterResponse<usersIdTweets>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/tweets`, params, method: "GET", }), /** * User mention timeline by User ID * * Returns Tweet objects that mention username associated to the provided User ID * @param id - The ID of the User to list mentions of * @param params - The params for usersIdMentions * @param request_options - Customize the options for this request */ usersIdMentions: ( id: string, params: TwitterParams<usersIdMentions> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdMentions>> => paginate<TwitterResponse<usersIdMentions>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/mentions`, params, method: "GET", }), /** * Causes the user (in the path) to like the specified tweet * * Causes the user (in the path) to like the specified tweet. The user in the path must match the user context authorizing the request. * @param id - The ID of the user that is requesting to like the tweet * @param request_body - The request_body for usersIdLike * @param request_options - Customize the options for this request */ usersIdLike: ( id: string, request_body: TwitterBody<usersIdLike>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdLike>> => rest<TwitterResponse<usersIdLike>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/likes`, request_body, method: "POST", }), /** * Causes the user (in the path) to unlike the specified tweet * * Causes the user (in the path) to unlike the specified tweet. The user must match the user context authorizing the request * @param id - The ID of the user that is requesting to unlike the tweet * @param tweet_id - The ID of the tweet that the user is requesting to unlike * @param request_options - Customize the options for this request */ usersIdUnlike: ( id: string, tweet_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdUnlike>> => rest<TwitterResponse<usersIdUnlike>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/likes/${tweet_id}`, method: "DELETE", }), /** * Returns Tweet objects liked by the provided User ID * * Returns a list of Tweets liked by the provided User ID * @param id - The ID of the User to list the liked Tweets of * @param params - The params for usersIdLikedTweets * @param request_options - Customize the options for this request */ usersIdLikedTweets: ( id: string, params: TwitterParams<usersIdLikedTweets> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdLikedTweets>> => paginate<TwitterResponse<usersIdLikedTweets>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/liked_tweets`, params, method: "GET", }), /** * Causes the user (in the path) to retweet the specified tweet * * Causes the user (in the path) to retweet the specified tweet. The user in the path must match the user context authorizing the request. * @param id - The ID of the user that is requesting to retweet the tweet * @param request_body - The request_body for usersIdRetweets * @param request_options - Customize the options for this request */ usersIdRetweets: ( id: string, request_body: TwitterBody<usersIdRetweets>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdRetweets>> => rest<TwitterResponse<usersIdRetweets>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/retweets`, request_body, method: "POST", }), /** * Causes the user (in the path) to unretweet the specified tweet * * Causes the user (in the path) to unretweet the specified tweet. The user must match the user context authorizing the request * @param id - The ID of the user that is requesting to unretweet the tweet * @param source_tweet_id - The ID of the tweet that the user is requesting to unretweet * @param request_options - Customize the options for this request */ usersIdUnretweets: ( id: string, source_tweet_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdUnretweets>> => rest<TwitterResponse<usersIdUnretweets>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/retweets/${source_tweet_id}`, method: "DELETE", }), /** * Recent search counts * * Returns Tweet Counts from the last 7 days that match a search query. * @param params - The params for tweetCountsRecentSearch * @param request_options - Customize the options for this request */ tweetCountsRecentSearch: ( params: TwitterParams<tweetCountsRecentSearch>, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<tweetCountsRecentSearch>> => paginate<TwitterResponse<tweetCountsRecentSearch>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/counts/recent`, params, method: "GET", }), /** * Full archive search counts * * Returns Tweet Counts that match a search query. * @param params - The params for tweetCountsFullArchiveSearch * @param request_options - Customize the options for this request */ tweetCountsFullArchiveSearch: ( params: TwitterParams<tweetCountsFullArchiveSearch>, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse< TwitterResponse<tweetCountsFullArchiveSearch> > => paginate<TwitterResponse<tweetCountsFullArchiveSearch>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/counts/all`, params, method: "GET", }), /** * List Tweets timeline by List ID * * Returns a list of Tweets associated with the provided List ID * @param id - The ID of the List to list Tweets of * @param params - The params for listsIdTweets * @param request_options - Customize the options for this request */ listsIdTweets: ( id: string, params: TwitterParams<listsIdTweets> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<listsIdTweets>> => paginate<TwitterResponse<listsIdTweets>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}/tweets`, params, method: "GET", }), }; /** * Users * * Endpoints related to retrieving, managing relationships of Users * * Find out more * https://developer.twitter.com/en/docs/twitter-api/users/lookup */ public readonly users = { /** * User lookup by IDs * * This endpoint returns information about users. Specify users by their ID. * @param params - The params for findUsersById * @param request_options - Customize the options for this request */ findUsersById: ( params: TwitterParams<findUsersById>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findUsersById>> => rest<TwitterResponse<findUsersById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users`, params, method: "GET", }), /** * User lookup by ID * * This endpoint returns information about a user. Specify user by ID. * @param id - Required. A User ID. * @param params - The params for findUserById * @param request_options - Customize the options for this request */ findUserById: ( id: string, params: TwitterParams<findUserById> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findUserById>> => rest<TwitterResponse<findUserById>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}`, params, method: "GET", }), /** * User lookup by usernames * * This endpoint returns information about users. Specify users by their username. * @param params - The params for findUsersByUsername * @param request_options - Customize the options for this request */ findUsersByUsername: ( params: TwitterParams<findUsersByUsername>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findUsersByUsername>> => rest<TwitterResponse<findUsersByUsername>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/by`, params, method: "GET", }), /** * User lookup me * * This endpoint returns information about the requesting user. * @param params - The params for findMyUser * @param request_options - Customize the options for this request */ findMyUser: ( params: TwitterParams<findMyUser> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findMyUser>> => rest<TwitterResponse<findMyUser>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/me`, params, method: "GET", }), /** * User lookup by username * * This endpoint returns information about a user. Specify user by username. * @param username - Required. A username. * @param params - The params for findUserByUsername * @param request_options - Customize the options for this request */ findUserByUsername: ( username: string, params: TwitterParams<findUserByUsername> = {}, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<findUserByUsername>> => rest<TwitterResponse<findUserByUsername>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/by/username/${username}`, params, method: "GET", }), /** * Block User by User ID * * Causes the user (in the path) to block the target user. The user (in the path) must match the user context authorizing the request * @param id - The ID of the user that is requesting to block the target user * @param request_body - The request_body for usersIdBlock * @param request_options - Customize the options for this request */ usersIdBlock: ( id: string, request_body: TwitterBody<usersIdBlock>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdBlock>> => rest<TwitterResponse<usersIdBlock>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/blocking`, request_body, method: "POST", }), /** * Returns user objects that are blocked by provided user ID * * Returns a list of users that are blocked by the provided user ID * @param id - The ID of the user for whom to return results * @param params - The params for usersIdBlocking * @param request_options - Customize the options for this request */ usersIdBlocking: ( id: string, params: TwitterParams<usersIdBlocking> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdBlocking>> => paginate<TwitterResponse<usersIdBlocking>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/blocking`, params, method: "GET", }), /** * Unblock User by User ID * * Causes the source user to unblock the target user. The source user must match the user context authorizing the request * @param source_user_id - The ID of the user that is requesting to unblock the target user * @param target_user_id - The ID of the user that the source user is requesting to unblock * @param request_options - Customize the options for this request */ usersIdUnblock: ( source_user_id: string, target_user_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdUnblock>> => rest<TwitterResponse<usersIdUnblock>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${source_user_id}/blocking/${target_user_id}`, method: "DELETE", }), /** * Unmute User by User ID * * Causes the source user to unmute the target user. The source user must match the user context authorizing the request * @param source_user_id - The ID of the user that is requesting to unmute the target user * @param target_user_id - The ID of the user that the source user is requesting to unmute * @param request_options - Customize the options for this request */ usersIdUnmute: ( source_user_id: string, target_user_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdUnmute>> => rest<TwitterResponse<usersIdUnmute>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${source_user_id}/muting/${target_user_id}`, method: "DELETE", }), /** * Mute User by User ID * * Causes the user (in the path) to mute the target user. The user (in the path) must match the user context authorizing the request * @param id - The ID of the user that is requesting to mute the target user * @param request_body - The request_body for usersIdMute * @param request_options - Customize the options for this request */ usersIdMute: ( id: string, request_body: TwitterBody<usersIdMute>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdMute>> => rest<TwitterResponse<usersIdMute>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/muting`, request_body, method: "POST", }), /** * Returns user objects that are muted by the provided user ID * * Returns a list of users that are muted by the provided user ID * @param id - The ID of the user for whom to return results * @param params - The params for usersIdMuting * @param request_options - Customize the options for this request */ usersIdMuting: ( id: string, params: TwitterParams<usersIdMuting> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdMuting>> => paginate<TwitterResponse<usersIdMuting>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/muting`, params, method: "GET", }), /** * Returns user objects that follow the provided user ID * * Returns a list of users that follow the provided user ID * @param id - The ID of the user for whom to return results * @param params - The params for usersIdFollowers * @param request_options - Customize the options for this request */ usersIdFollowers: ( id: string, params: TwitterParams<usersIdFollowers> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdFollowers>> => paginate<TwitterResponse<usersIdFollowers>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/followers`, params, method: "GET", }), /** * Following by User ID * * Returns a list of users that are being followed by the provided user ID * @param id - The ID of the user for whom to return results * @param params - The params for usersIdFollowing * @param request_options - Customize the options for this request */ usersIdFollowing: ( id: string, params: TwitterParams<usersIdFollowing> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<usersIdFollowing>> => paginate<TwitterResponse<usersIdFollowing>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/following`, params, method: "GET", }), /** * Follow User * * Causes the user(in the path) to follow, or “request to follow” for protected users, the target user. The user(in the path) must match the user context authorizing the request * @param id - The ID of the user that is requesting to follow the target user * @param request_body - The request_body for usersIdFollow * @param request_options - Customize the options for this request */ usersIdFollow: ( id: string, request_body: TwitterBody<usersIdFollow>, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdFollow>> => rest<TwitterResponse<usersIdFollow>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${id}/following`, request_body, method: "POST", }), /** * Unfollow User * * Causes the source user to unfollow the target user. The source user must match the user context authorizing the request * @param source_user_id - The ID of the user that is requesting to unfollow the target user * @param target_user_id - The ID of the user that the source user is requesting to unfollow * @param request_options - Customize the options for this request */ usersIdUnfollow: ( source_user_id: string, target_user_id: string, request_options?: Partial<RequestOptions> ): Promise<TwitterResponse<usersIdUnfollow>> => rest<TwitterResponse<usersIdUnfollow>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/users/${source_user_id}/following/${target_user_id}`, method: "DELETE", }), /** * Returns user objects that have liked the provided Tweet ID * * Returns a list of users that have liked the provided Tweet ID * @param id - The ID of the Tweet for which to return results * @param params - The params for tweetsIdLikingUsers * @param request_options - Customize the options for this request */ tweetsIdLikingUsers: ( id: string, params: TwitterParams<tweetsIdLikingUsers> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<tweetsIdLikingUsers>> => paginate<TwitterResponse<tweetsIdLikingUsers>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/${id}/liking_users`, params, method: "GET", }), /** * Returns user objects that have retweeted the provided Tweet ID * * Returns a list of users that have retweeted the provided Tweet ID * @param id - The ID of the Tweet for which to return results * @param params - The params for tweetsIdRetweetingUsers * @param request_options - Customize the options for this request */ tweetsIdRetweetingUsers: ( id: string, params: TwitterParams<tweetsIdRetweetingUsers> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<tweetsIdRetweetingUsers>> => paginate<TwitterResponse<tweetsIdRetweetingUsers>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/tweets/${id}/retweeted_by`, params, method: "GET", }), /** * Returns user objects that follow a List by the provided List ID * * Returns a list of users that follow a List by the provided List ID * @param id - The ID of the List for which to return followers * @param params - The params for listGetFollowers * @param request_options - Customize the options for this request */ listGetFollowers: ( id: string, params: TwitterParams<listGetFollowers> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<listGetFollowers>> => paginate<TwitterResponse<listGetFollowers>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}/followers`, params, method: "GET", }), /** * Returns user objects that are members of a List by the provided List ID * * Returns a list of users that are members of a List by the provided List ID * @param id - The ID of the List for which to return members * @param params - The params for listGetMembers * @param request_options - Customize the options for this request */ listGetMembers: ( id: string, params: TwitterParams<listGetMembers> = {}, request_options?: Partial<RequestOptions> ): TwitterPaginatedResponse<TwitterResponse<listGetMembers>> => paginate<TwitterResponse<listGetMembers>>({ auth: this.#auth, ...this.#defaultRequestOptions, ...request_options, endpoint: `/2/lists/${id}/members`, params, method: "GET", }), }; }
the_stack
// Migrator // ------- import _ from '../deps/lodash@4.17.15/index.js'; const differenceWith = _.differenceWith; const get = _.get; const isBoolean = _.isBoolean; const isEmpty = _.isEmpty; const isFunction = _.isFunction; const max = _.max; import inherits from '../deps/inherits@2.0.4/inherits.js'; import { getLockTableName, getLockTableNameWithSchema, getTable, getTableName, } from './table-resolver.js'; import { getSchemaBuilder } from './table-creator.js'; import migrationListResolver from './migration-list-resolver.js'; import MigrationGenerator from './MigrationGenerator.js'; import { getMergedConfig } from './configuration-merger.js'; function LockError(msg) { this.name = 'MigrationLocked'; this.message = msg; } inherits(LockError, Error); // The new migration we're performing, typically called from the `knex.migrate` // interface on the main `knex` object. Passes the `knex` instance performing // the migration. export class Migrator { constructor(knex) { // Clone knex instance and remove post-processing that is unnecessary for internal queries from a cloned config if (isFunction(knex)) { if (!knex.isTransaction) { this.knex = knex.withUserParams({ ...knex.userParams, }); } else { this.knex = knex; } } else { this.knex = Object.assign({}, knex); this.knex.userParams = this.knex.userParams || {}; } this.config = getMergedConfig(this.knex.client.config.migrations); this.generator = new MigrationGenerator(this.knex.client.config.migrations); this._activeMigration = { fileName: null, }; } // Migrators to the latest configuration. latest(config) { this._disableProcessing(); this.config = getMergedConfig(config, this.config); return migrationListResolver .listAllAndCompleted(this.config, this.knex) .then((value) => { if (!this.config.disableMigrationsListValidation) { validateMigrationList(this.config.migrationSource, value); } return value; }) .then(([all, completed]) => { const migrations = getNewMigrations( this.config.migrationSource, all, completed ); const transactionForAll = !this.config.disableTransactions && !migrations.some((migration) => { const migrationContents = this.config.migrationSource.getMigration( migration ); return !this._useTransaction(migrationContents); }); if (transactionForAll) { return this.knex.transaction((trx) => { return this._runBatch(migrations, 'up', trx); }); } else { return this._runBatch(migrations, 'up'); } }); } // Runs the next migration that has not yet been run up(config) { this._disableProcessing(); this.config = getMergedConfig(config, this.config); return migrationListResolver .listAllAndCompleted(this.config, this.knex) .then((value) => { if (!this.config.disableMigrationsListValidation) { validateMigrationList(this.config.migrationSource, value); } return value; }) .then(([all, completed]) => { const newMigrations = getNewMigrations( this.config.migrationSource, all, completed ); let migrationToRun; const name = this.config.name; if (name) { if (!completed.includes(name)) { migrationToRun = newMigrations.find((migration) => { return ( this.config.migrationSource.getMigrationName(migration) === name ); }); if (!migrationToRun) { throw new Error(`Migration "${name}" not found.`); } } } else { migrationToRun = newMigrations[0]; } const migrationsToRun = []; if (migrationToRun) { migrationsToRun.push(migrationToRun); } const transactionForAll = !this.config.disableTransactions && (!migrationToRun || this._useTransaction( this.config.migrationSource.getMigration(migrationToRun) )); if (transactionForAll) { return this.knex.transaction((trx) => { return this._runBatch(migrationsToRun, 'up', trx); }); } else { return this._runBatch(migrationsToRun, 'up'); } }); } // Rollback the last "batch", or all, of migrations that were run. rollback(config, all = false) { this._disableProcessing(); return new Promise((resolve, reject) => { try { this.config = getMergedConfig(config, this.config); } catch (e) { reject(e); } migrationListResolver .listAllAndCompleted(this.config, this.knex) .then((value) => { if (!this.config.disableMigrationsListValidation) { validateMigrationList(this.config.migrationSource, value); } return value; }) .then((val) => { const [allMigrations, completedMigrations] = val; return all ? allMigrations .filter((migration) => { return completedMigrations.includes(migration.file); }) .reverse() : this._getLastBatch(val); }) .then((migrations) => { return this._runBatch(migrations, 'down'); }) .then(resolve, reject); }); } down(config) { this._disableProcessing(); this.config = getMergedConfig(config, this.config); return migrationListResolver .listAllAndCompleted(this.config, this.knex) .then((value) => { if (!this.config.disableMigrationsListValidation) { validateMigrationList(this.config.migrationSource, value); } return value; }) .then(([all, completed]) => { const completedMigrations = all.filter((migration) => { return completed.includes( this.config.migrationSource.getMigrationName(migration) ); }); let migrationToRun; const name = this.config.name; if (name) { migrationToRun = completedMigrations.find((migration) => { return ( this.config.migrationSource.getMigrationName(migration) === name ); }); if (!migrationToRun) { throw new Error(`Migration "${name}" was not run.`); } } else { migrationToRun = completedMigrations[completedMigrations.length - 1]; } const migrationsToRun = []; if (migrationToRun) { migrationsToRun.push(migrationToRun); } return this._runBatch(migrationsToRun, 'down'); }); } status(config) { this._disableProcessing(); this.config = getMergedConfig(config, this.config); return Promise.all([ getTable(this.knex, this.config.tableName, this.config.schemaName).select( '*' ), migrationListResolver.listAll(this.config.migrationSource), ]).then(([db, code]) => db.length - code.length); } // Retrieves and returns the current migration version we're on, as a promise. // If no migrations have been run yet, return "none". currentVersion(config) { this._disableProcessing(); this.config = getMergedConfig(config, this.config); return migrationListResolver .listCompleted(this.config.tableName, this.config.schemaName, this.knex) .then((completed) => { const val = max(completed.map((value) => value.split('_')[0])); return val === undefined ? 'none' : val; }); } // list all migrations async list(config) { this._disableProcessing(); this.config = getMergedConfig(config, this.config); const [all, completed] = await migrationListResolver.listAllAndCompleted( this.config, this.knex ); if (!this.config.disableMigrationsListValidation) { validateMigrationList(this.config.migrationSource, [all, completed]); } const newMigrations = getNewMigrations( this.config.migrationSource, all, completed ); return [completed, newMigrations]; } forceFreeMigrationsLock(config) { this.config = getMergedConfig(config, this.config); const lockTable = getLockTableName(this.config.tableName); return getSchemaBuilder(this.knex, this.config.schemaName) .hasTable(lockTable) .then((exist) => exist && this._freeLock()); } // Creates a new migration, with a given name. make(name, config) { this.config = getMergedConfig(config, this.config); return this.generator.make(name, this.config); } _disableProcessing() { if (this.knex.disableProcessing) { this.knex.disableProcessing(); } } _lockMigrations(trx) { const tableName = getLockTableName(this.config.tableName); return getTable(this.knex, tableName, this.config.schemaName) .transacting(trx) .where('is_locked', '=', 0) .update({ is_locked: 1 }) .then((rowCount) => { if (rowCount != 1) { throw new Error('Migration table is already locked'); } }); } _getLock(trx) { const transact = trx ? (fn) => fn(trx) : (fn) => this.knex.transaction(fn); return transact((trx) => { return this._lockMigrations(trx); }).catch((err) => { throw new LockError(err.message); }); } _freeLock(trx = this.knex) { const tableName = getLockTableName(this.config.tableName); return getTable(trx, tableName, this.config.schemaName).update({ is_locked: 0, }); } // Run a batch of current migrations, in sequence. _runBatch(migrations, direction, trx) { return ( this._getLock(trx) // When there is a wrapping transaction, some migrations // could have been done while waiting for the lock: .then(() => trx ? migrationListResolver.listCompleted( this.config.tableName, this.config.schemaName, trx ) : [] ) .then( (completed) => (migrations = getNewMigrations( this.config.migrationSource, migrations, completed )) ) .then(() => Promise.all( migrations.map(this._validateMigrationStructure.bind(this)) ) ) .then(() => this._latestBatchNumber(trx)) .then((batchNo) => { if (direction === 'up') batchNo++; return batchNo; }) .then((batchNo) => { return this._waterfallBatch(batchNo, migrations, direction, trx); }) .then(async (res) => { await this._freeLock(trx); return res; }) .catch(async (error) => { let cleanupReady = Promise.resolve(); if (error instanceof LockError) { // If locking error do not free the lock. this.knex.client.logger.warn( `Can't take lock to run migrations: ${error.message}` ); this.knex.client.logger.warn( 'If you are sure migrations are not running you can release the ' + 'lock manually by deleting all the rows = require(migrations lock ' + 'table: ' + getLockTableNameWithSchema( this.config.tableName, this.config.schemaName ) ); } else { if (this._activeMigration.fileName) { this.knex.client.logger.warn( `migration file "${this._activeMigration.fileName}" failed` ); } this.knex.client.logger.warn( `migration failed with error: ${error.message}` ); // If the error was not due to a locking issue, then remove the lock. cleanupReady = this._freeLock(trx); } try { await cleanupReady; // eslint-disable-next-line no-empty } catch (e) {} throw error; }) ); } // Validates some migrations by requiring and checking for an `up` and `down` // function. _validateMigrationStructure(migration) { const migrationName = this.config.migrationSource.getMigrationName( migration ); const migrationContent = this.config.migrationSource.getMigration( migration ); if ( typeof migrationContent.up !== 'function' || typeof migrationContent.down !== 'function' ) { throw new Error( `Invalid migration: ${migrationName} must have both an up and down function` ); } return migration; } // Get the last batch of migrations, by name, ordered by insert id in reverse // order. _getLastBatch([allMigrations]) { const { tableName, schemaName } = this.config; return getTable(this.knex, tableName, schemaName) .where('batch', function (qb) { qb.max('batch').from(getTableName(tableName, schemaName)); }) .orderBy('id', 'desc') .then((migrations) => Promise.all( migrations.map((migration) => { return allMigrations.find((entry) => { return ( this.config.migrationSource.getMigrationName(entry) === migration.name ); }); }) ) ); } // Returns the latest batch number. _latestBatchNumber(trx = this.knex) { return trx .from(getTableName(this.config.tableName, this.config.schemaName)) .max('batch as max_batch') .then((obj) => obj[0].max_batch || 0); } // If transaction config for a single migration is defined, use that. // Otherwise, rely on the common config. This allows enabling/disabling // transaction for a single migration at will, regardless of the common // config. _useTransaction(migrationContent, allTransactionsDisabled) { const singleTransactionValue = get(migrationContent, 'config.transaction'); return isBoolean(singleTransactionValue) ? singleTransactionValue : !allTransactionsDisabled; } // Runs a batch of `migrations` in a specified `direction`, saving the // appropriate database information as the migrations are run. _waterfallBatch(batchNo, migrations, direction, trx) { const trxOrKnex = trx || this.knex; const { tableName, schemaName, disableTransactions } = this.config; let current = Promise.resolve(); const log = []; migrations.forEach((migration) => { const name = this.config.migrationSource.getMigrationName(migration); this._activeMigration.fileName = name; const migrationContent = this.config.migrationSource.getMigration( migration ); // We're going to run each of the migrations in the current "up". current = current .then(() => { this._activeMigration.fileName = name; if ( !trx && this._useTransaction(migrationContent, disableTransactions) ) { this.knex.enableProcessing(); return this._transaction( this.knex, migrationContent, direction, name ); } trxOrKnex.enableProcessing(); return checkPromise( this.knex.client.logger, migrationContent[direction](trxOrKnex), name ); }) .then(() => { trxOrKnex.disableProcessing(); this.knex.disableProcessing(); log.push(name); if (direction === 'up') { return trxOrKnex.into(getTableName(tableName, schemaName)).insert({ name, batch: batchNo, migration_time: new Date(), }); } if (direction === 'down') { return trxOrKnex .from(getTableName(tableName, schemaName)) .where({ name }) .del(); } }); }); return current.then(() => [batchNo, log]); } _transaction(knex, migrationContent, direction, name) { return knex.transaction((trx) => { return checkPromise( knex.client.logger, migrationContent[direction](trx), name, () => { trx.commit(); } ); }); } } // Validates that migrations are present in the appropriate directories. function validateMigrationList(migrationSource, migrations) { const all = migrations[0]; const completed = migrations[1]; const diff = getMissingMigrations(migrationSource, completed, all); if (!isEmpty(diff)) { throw new Error( `The migration directory is corrupt, the following files are missing: ${diff.join( ', ' )}` ); } } function getMissingMigrations(migrationSource, completed, all) { return differenceWith(completed, all, (completedMigration, allMigration) => { return ( completedMigration === migrationSource.getMigrationName(allMigration) ); }); } function getNewMigrations(migrationSource, all, completed) { return differenceWith(all, completed, (allMigration, completedMigration) => { return ( completedMigration === migrationSource.getMigrationName(allMigration) ); }); } function checkPromise(logger, migrationPromise, name, commitFn) { if (!migrationPromise || typeof migrationPromise.then !== 'function') { logger.warn(`migration ${name} did not return a promise`); if (commitFn) { commitFn(); } } return migrationPromise; } export default { Migrator, };
the_stack
'use strict'; import * as vscode from 'vscode'; import { TextEditor, Disposable } from 'vscode'; import * as vscodeTypes from 'vscode-languageserver-types'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import {decorations} from './Decorations'; import {Highlights} from './Highlights'; // import {CoqView, SimpleCoqView} from './SimpleCoqView'; // import {MDCoqView} from './MDCoqView'; import {HtmlCoqView} from './HtmlCoqView'; import {HtmlLtacProf} from './HtmlLtacProf'; import * as proto from './protocol'; import * as textUtil from './text-util'; import {extensionContext} from './extension'; import {CoqDocumentLanguageServer} from './CoqLanguageServer'; import {CoqView, adjacentPane} from './CoqView'; import {StatusBar} from './StatusBar'; import {CoqProject} from './CoqProject'; import * as psm from './prettify-symbols-mode'; namespace DisplayOptionPicks { type T = vscode.QuickPickItem & {displayItem: number}; export const ImplicitArguments : T = { label: "Implicit Arguments", description: "toggle display of *implicit arguments*", detail: "some detail", displayItem: proto.DisplayOption.ImplicitArguments }; export const Coercions : T = { label: "Coercions", description: "toggle display of *coercions*", displayItem: proto.DisplayOption.Coercions }; export const RawMatchingExpressions : T = { label: "Raw Matching Expressions", description: "toggle display of *raw matching expressions*", displayItem: proto.DisplayOption.RawMatchingExpressions }; export const Notations : T = { label: "Notations", description: "toggle display of notations", displayItem: proto.DisplayOption.Notations }; export const AllBasicLowLevelContents : T = { label: "All Basic Low Level Contents", description: "toggle display of ", displayItem: proto.DisplayOption.AllBasicLowLevelContents }; export const ExistentialVariableInstances : T = { label: "Existential Variable Instances", description: "toggle display of ", displayItem: proto.DisplayOption.ExistentialVariableInstances }; export const UniverseLevels : T = { label: "Universe Levels", description: "toggle display of ", displayItem: proto.DisplayOption.UniverseLevels }; export const AllLowLevelContents : T = { label: "All Low Level Contents", description: "toggle display of ", displayItem: proto.DisplayOption.AllLowLevelContents }; export const allPicks = [ImplicitArguments, Coercions, RawMatchingExpressions, Notations, AllBasicLowLevelContents, ExistentialVariableInstances, UniverseLevels, AllLowLevelContents]; } export class CoqDocument implements vscode.Disposable { /** A list of things to dispose */ private readonly queryRouteId = 2; private subscriptions : Disposable[] = [] private statusBar: StatusBar; public documentUri: string; public highlights = new Highlights(); private document: vscode.TextDocument; private langServer: CoqDocumentLanguageServer; private view : CoqView; /** Tracks which editors of this document have not had cursors positions changed since the last call to `rememberCursors()`. When stepping forward, the cursor is advanced for all editors whose cursors have not moved since the previous step. */ private cursorUnmovedSinceCommandInitiated = new Set<vscode.TextEditor>(); /** Coq STM focus */ private focus?: vscode.Position; private stateViewFocus?: vscode.Position; private project: CoqProject; private currentLtacProfView: HtmlLtacProf|null = null; //private coqtopRunning = false; constructor(document: vscode.TextDocument, project: CoqProject) { this.statusBar = new StatusBar(); this.document = document; this.project = project; // this.document = vscode.workspace.textDocuments.find((doc) => doc.uri === uri); this.documentUri = document.uri.toString(); try { this.langServer = new CoqDocumentLanguageServer(document.uri.toString()); } catch(err) { var x = this.langServer; x = x; } this.view = new HtmlCoqView(document.uri, extensionContext); // this.view = new SimpleCoqView(uri.toString()); // this.view = new MDCoqView(uri); if(this.project.settings.showProofViewOn === "open-script") { let viewCol = this.currentViewColumn(); if (viewCol) this.view.show(adjacentPane(viewCol)) else this.view.show(vscode.ViewColumn.One) }; this.langServer.onUpdateHighlights((p) => this.onDidUpdateHighlights(p)); this.langServer.onMessage((p) => this.onCoqMessage(p)); this.langServer.onReset((p) => this.onCoqReset()); this.langServer.onUpdateCoqStmFocus((p) => this.updateFocus(p.position)); this.langServer.onLtacProfResults((p) => this.onLtacProfResults(p)); this.langServer.onCoqtopStart(p => { //this.coqtopRunning = true; this.statusBar.setCoqtopStatus(true); }) this.langServer.onCoqtopStop(p => { //this.coqtopRunning = false; if(p.reason === proto.CoqtopStopReason.Anomaly || p.reason === proto.CoqtopStopReason.InternalError) vscode.window.showErrorMessage(p.message || "Coqtop quit for an unknown reason.") this.statusBar.setCoqtopStatus(false); }) this.view.resize(async (columns:number) => { try { await this.langServer.resizeView(Math.floor(columns)); await this.refreshGoal(); } catch(err) {} }); this.subscriptions.push(vscode.window.onDidChangeTextEditorSelection((e:vscode.TextEditorSelectionChangeEvent) => { if(this.project.settings.autoRevealProofStateAtCursor && e.textEditor.document === this.document && e.selections.length === 1) this.viewGoalAt(e.textEditor,e.selections[0].active); if(this.cursorUnmovedSinceCommandInitiated.has(e.textEditor)) this.cursorUnmovedSinceCommandInitiated.delete(e.textEditor); })); if(vscode.window.activeTextEditor) if(vscode.window.activeTextEditor.document.uri.toString() == this.documentUri) this.statusBar.focus(); this.statusBar.setStateReady(); } private async refreshGoal(e?: vscode.TextEditor) { if(!e) e = vscode.window.activeTextEditor; const value = await this.langServer.getGoal(); this.updateView(value, false); if (e) if(this.project.settings.autoRevealProofStateAtCursor && e.document === this.document && e.selections.length === 1) this.viewGoalAt(e,e.selections[0].active) } public getUri() { return this.documentUri; } public getDocument() { return this.document; } public dispose() { this.quitCoq(); this.langServer.dispose(); this.highlights.clearAll(this.allEditors()); this.statusBar.dispose(); if(this.view) this.view.dispose(); this.subscriptions.forEach((d) => d.dispose()); } private reset() { this.highlights.clearAll(this.allEditors()) } private rememberCursors() { this.cursorUnmovedSinceCommandInitiated.clear(); for(let editor of this.allEditors()) { this.cursorUnmovedSinceCommandInitiated.add(editor); } } private onDidUpdateHighlights(params: proto.Highlights) { this.highlights.set(this.allEditors(),params); } // private onUpdateComputingStatus(params: proto.NotifyComputingStatusParams) { // this.statusBar.setStateComputing(params.status); // } private onCoqMessage(params: proto.NotifyMessageParams) { if (params.routeId == this.queryRouteId) { this.project.queryOut.show(true); this.project.queryOut.appendLine(psm.prettyTextToString(params.message)); } else { switch (params.level) { case 'warning': this.project.infoOut.show(true); this.project.infoOut.appendLine(psm.prettyTextToString(params.message)); return; case 'info': this.project.infoOut.appendLine(psm.prettyTextToString(params.message)); return; case 'notice': this.project.noticeOut.show(true); this.project.noticeOut.append(psm.prettyTextToString(params.message)); this.project.noticeOut.append("\n"); return; case 'debug': this.project.debugOut.show(true); this.project.debugOut.appendLine(psm.prettyTextToString(params.message)); return; } } } public onDidChangeTextDocument(params: vscode.TextDocumentChangeEvent) { this.updateFocus(this.focus, false); } public async interruptCoq() { this.statusBar.setStateMessage('Killing CoqTop'); try { await this.langServer.interruptCoq(); } finally {} this.statusBar.setStateReady(); } public async quitCoq(editor?: TextEditor) { this.statusBar.setStateMessage('Killing CoqTop'); try { await this.langServer.quitCoq(); } finally {} this.reset(); this.statusBar.setStateReady(); } public async resetCoq(editor?: TextEditor) { this.statusBar.setStateMessage('Resetting Coq'); try { await this.langServer.resetCoq(); } finally {} this.reset(); this.statusBar.setStateReady(); } private findEditor() : vscode.TextEditor|undefined { return vscode.window.visibleTextEditors.find((editor,i,a) => editor.document.uri.toString() === this.documentUri); } public allEditors() : vscode.TextEditor[] { return vscode.window.visibleTextEditors.filter((editor,i,a) => editor.document.uri.toString() === this.documentUri) } private currentViewColumn() { let editor = this.findEditor(); if(editor) return editor.viewColumn; else if (vscode.window.activeTextEditor) return vscode.window.activeTextEditor.viewColumn; else return undefined; } private onCoqReset() { this.reset(); this.statusBar.setStateReady(); } /** Bring the focus into the editor's view, but only scroll rightward * if the focus is not at the end of a line * */ public setCursorToPosition(pos: vscode.Position|undefined, editor: vscode.TextEditor, scroll: boolean = true, scrollHorizontal = false) { if(!editor || !pos) return; editor.selections = [new vscode.Selection(pos, pos)] if(scroll) { if (scrollHorizontal || textUtil.positionIsBefore(pos, this.document.lineAt(pos.line).range.end)) editor.revealRange(new vscode.Range(pos, pos), vscode.TextEditorRevealType.Default) else editor.revealRange(new vscode.Range(pos.line, 0, pos.line + 1, 0), vscode.TextEditorRevealType.Default) } } private updateFocus(focus?: vscodeTypes.Position, moveCursor = false) { if(focus) { this.focus = new vscode.Position(focus.line,focus.character); if(moveCursor) { // adjust the cursor position for(let editor of this.cursorUnmovedSinceCommandInitiated) this.setCursorToPosition(this.focus, editor, editor === vscode.window.activeTextEditor); } // update the focus decoration this.showFocusDecorations(); } else { for(let editor of this.allEditors()) editor.setDecorations(decorations.focus, []); } } private async userSetCoqtopPath(global = false) { const current = vscode.workspace.getConfiguration("coqtop").get("binPath", ""); const coqtopExe = vscode.workspace.getConfiguration("coqtop").get("coqtopExe", ""); const newPath = await vscode.window.showInputBox({ignoreFocusOut: true, value: current, validateInput: (v:string):string => { try { const statDir = fs.statSync(v); if(!statDir.isDirectory()) return "not a directory"; } catch(err) { return "invalid path"; } let stat : fs.Stats|undefined = undefined; try { stat = fs.statSync(path.join(v, coqtopExe)); } catch { if (os.platform() === 'win32') { try { stat = fs.statSync(path.join(v, coqtopExe, '.exe')); } catch {} } } if (!stat) return "coqtop not found here" if (!stat.isFile()) return "coqtop found here, but is not an executable file"; return ""; } }); async function checkCoqtopExists(newPath: string) { if(!newPath) return false; try { return await fs.existsSync(path.join(newPath, coqtopExe)) || os.platform() === 'win32' && await fs.existsSync(path.join(newPath, coqtopExe, '.exe')) } catch(err) { return false; } } if (newPath) if(await checkCoqtopExists(newPath)) await vscode.workspace.getConfiguration("coqtop").update("binPath", newPath, global); } private handleResult(value: proto.CommandResult) { if(value.type === 'busy') return false; else if(value.type === 'failure' && value.range) { this.updateFocus(value.focus, false); if(this.project.settings.moveCursorToFocus) { for(let editor of this.cursorUnmovedSinceCommandInitiated) this.setCursorToPosition(new vscode.Position(value.range.start.line, value.range.start.character), editor, editor === vscode.window.activeTextEditor); } } else if(value.type === 'not-running') { this.updateFocus(undefined, false); if(value.reason === 'spawn-failed') { const getCoq = {title: "Get Coq", id: 0}; const setPathLocal = {title: "Set path for this project", id: 1}; const setPathGlobal = {title: "Set path globally", id: 2}; vscode.window.showErrorMessage(`Could not start coqtop ${value.coqtop ? ` (${value.coqtop})` : ""}`, getCoq, setPathLocal, setPathGlobal) .then(async act => { if(act && act.id === getCoq.id) { vscode.commands.executeCommand("vscode.open", vscode.Uri.parse('https://coq.inria.fr/download')) } else if(act && (act.id === setPathLocal.id || act.id === setPathGlobal.id)) { await this.userSetCoqtopPath(act.id === setPathGlobal.id); } }) } } else if(value.type === 'interrupted') this.statusBar.setStateComputing(proto.ComputingStatus.Interrupted) else this.updateFocus(value.focus, this.project.settings.moveCursorToFocus); return true; } private updateView(state: proto.CommandResult, interactive = false) { if(interactive && !this.view.isVisible() && this.project.settings.showProofViewOn === "first-interaction") { let viewCol = this.currentViewColumn(); if (viewCol) this.view.show(adjacentPane(viewCol), state) else this.view.show(vscode.ViewColumn.One, state) } else { this.view.update(state); } this.stateViewFocus = state.type==="proof-view" ? new vscode.Position(state.focus.line,state.focus.character) : undefined; this.showFocusDecorations(); } private showFocusDecorations() { if(!this.focus) return; const focusRange = new vscode.Range(this.focus.line,0,this.focus.line,1); if(this.focus.line === 0 && this.focus.character === 0) { for(let editor of this.allEditors()) { editor.setDecorations(decorations.focusBefore, [focusRange]); editor.setDecorations(decorations.focus, []); } } else { for(let editor of this.allEditors()) { editor.setDecorations(decorations.focusBefore, []); editor.setDecorations(decorations.focus, [focusRange]); } } if(this.stateViewFocus && this.stateViewFocus.line !== this.focus.line) { const focusRange = new vscode.Range(this.stateViewFocus.line,0,this.stateViewFocus.line,1); for(let editor of this.allEditors()) { editor.setDecorations(decorations.proofViewFocus, [focusRange]); } } else { for(let editor of this.allEditors()) { editor.setDecorations(decorations.proofViewFocus, []); } } } private async makePreviewOpenedFilePermanent(editor: TextEditor){ //Make sure that the file is really open instead of preview-open, to avoid accidentaly closing the file await vscode.commands.executeCommand("workbench.action.keepEditor",editor.document.uri); } public async stepForward(editor: TextEditor) { this.statusBar.setStateWorking('Stepping forward'); try { this.makePreviewOpenedFilePermanent(editor); this.rememberCursors(); const value = await this.langServer.stepForward(); this.updateView(value, true); this.handleResult(value); } catch (err) { } this.statusBar.setStateReady(); } public async stepBackward(editor: TextEditor) { this.statusBar.setStateWorking('Stepping backward'); try { this.makePreviewOpenedFilePermanent(editor); this.rememberCursors(); const value = await this.langServer.stepBackward(); this.updateView(value, true); if(this.handleResult(value)) this.statusBar.setStateReady(); // const range = new vscode.Range(editor.document.positionAt(value.commandStart), editor.document.positionAt(value.commandEnd)); // clearHighlight(editor, range); } catch (err) { } } public async finishComputations(editor: TextEditor) { this.statusBar.setStateWorking('Finishing computations'); try { await this.langServer.finishComputations(); this.statusBar.setStateReady(); } catch (err) { } } public async interpretToCursorPosition(editor: TextEditor, synchronous = false) { this.statusBar.setStateWorking('Interpreting to point'); try { if(!editor || editor.document.uri.toString() !== this.documentUri) return; this.makePreviewOpenedFilePermanent(editor); const value = await this.langServer.interpretToPoint(editor.selection.active, synchronous); this.updateView(value, true); this.handleResult(value); } catch (err) { console.warn("Interpret to point failed: " + err.toString()); if(err.stack) console.log("Stack: \n" + err.stack); } this.statusBar.setStateReady(); } public async interpretToEnd(editor: TextEditor, synchronous = false) { this.statusBar.setStateWorking('Interpreting to end'); try { this.makePreviewOpenedFilePermanent(editor); const value = await this.langServer.interpretToEnd(synchronous); this.updateView(value, true); this.handleResult(value); } catch (err) { } this.statusBar.setStateReady(); } public async query(query: proto.QueryFunction, term: string | undefined) { try { if (term) { this.project.queryOut.clear(); this.project.queryOut.show(true); this.langServer.query(query, term, this.queryRouteId); } } catch (err) { } finally { this.statusBar.setStateReady(); } } public async viewGoalState(editor: TextEditor) { try { if (editor.viewColumn) await this.view.show(adjacentPane(editor.viewColumn)) else await this.view.show(vscode.ViewColumn.One) } catch (err) {} } public async ltacProfGetResults(editor: TextEditor) { this.statusBar.setStateWorking('Running query'); try { if(!editor || editor.document.uri.toString() !== this.documentUri) return; const offset = editor.document.offsetAt(editor.selection.active); this.currentLtacProfView = new HtmlLtacProf({total_time: 0, tactics: []}); this.currentLtacProfView.show(true); await this.langServer.ltacProfGetResults(offset); // const view = new HtmlLtacProf(results); // const out = vscode.window.createOutputChannel("LtacProfiler"); // results.forEach((value,key) => { // out.appendLine("-----------------------------------"); // this.outputLtacProfTreeNode(out, "", key, value); // }); } catch (err) { } finally { this.statusBar.setStateReady(); } } private onLtacProfResults(results: proto.LtacProfResults) { if(!this.currentLtacProfView) this.currentLtacProfView = new HtmlLtacProf(results); else this.currentLtacProfView.update(results); } public async doOnLostFocus() { this.statusBar.unfocus(); } public async doOnFocus(editor: TextEditor) { this.showFocusDecorations(); this.highlights.refresh([editor]); this.statusBar.focus(); // await this.view.show(true); } // public async doOnSwitchActiveEditor(oldEditor: TextEditor, newEditor: TextEditor) { // this.showFocusDecorations(); // this.highlights.refresh([newEditor]); // this.statusBar.focus(); // } private async queryDisplayOptionChange() : Promise<proto.DisplayOption|null> { const result = await vscode.window.showQuickPick(DisplayOptionPicks.allPicks); if (result) return result.displayItem else return null; } public async setDisplayOption(item?: proto.DisplayOption, value?: proto.SetDisplayOption) { if(item===undefined) { item = await this.queryDisplayOptionChange() || undefined; if(!item) return; } value = value || proto.SetDisplayOption.Toggle; try { await this.langServer.setDisplayOptions([{item: item, value: value}]); await this.refreshGoal(); } catch(err) { } } public async viewGoalAt(editor: vscode.TextEditor, pos?: vscode.Position) { try { if(!pos) pos = editor.selection.active; const proofview = await this.langServer.getCachedGoal(pos, this.project.settings.revealProofStateAtCursorDirection); if(proofview.type === "proof-view") this.updateView(proofview, false); } catch(err) { } } public getCurrentFocus() { return this.focus; } }
the_stack
import { Resolvers } from '@apollo/client'; import { ClientType, getBlockTime, getLogs, ColonyClientV5, ColonyClientV6, getMultipleEvents, ColonyRole, ColonyVersion, } from '@colony/colony-js'; import { Log } from 'ethers/providers'; import { LogDescription } from 'ethers/utils'; import { AddressZero } from 'ethers/constants'; import { Context } from '~context/index'; import { RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables, RecoveryEventsForSessionDocument, ColonyMembersQuery, ColonyMembersQueryVariables, ColonyMembersDocument, RecoveryRolesUsersQuery, RecoveryRolesUsersQueryVariables, RecoveryRolesUsersDocument, getMinimalUser, UserQuery, GetRecoveryRequiredApprovalsQuery, GetRecoveryRequiredApprovalsQueryVariables, GetRecoveryRequiredApprovalsDocument, } from '~data/index'; import { ProcessedEvent } from './colonyActions'; import { ActionsPageFeedType, SystemMessage, SystemMessagesName, } from '~dashboard/ActionsPageFeed'; import { ensureHexPrefix } from '~utils/strings'; import { halfPlusOne } from '~utils/numbers'; import { ColonyAndExtensionsEvents } from '~types/index'; const getSessionRecoveryEvents = async ( colonyClient: ColonyClientV6, startBlock = 1, ) => { const blockFilter: { fromBlock: number; toBlock?: number; } = { fromBlock: startBlock, }; const recoveryModeLogs: Log[] = []; const [mostRecentExitRecovery] = await getLogs( colonyClient, colonyClient.filters.RecoveryModeExited(null), { fromBlock: startBlock, }, ); if (mostRecentExitRecovery) { blockFilter.toBlock = mostRecentExitRecovery?.blockNumber; recoveryModeLogs.push(mostRecentExitRecovery); } const storageSlotSetLogs = await getLogs( colonyClient, colonyClient.filters.RecoveryStorageSlotSet(null, null, null, null), blockFilter, ); const exitApprovedLogs = await getLogs( colonyClient, colonyClient.filters.RecoveryModeExitApproved(null), blockFilter, ); const parsedRecoveryEvents = await Promise.all( [...recoveryModeLogs, ...storageSlotSetLogs, ...exitApprovedLogs].map( async (log) => { const potentialParsedLog = colonyClient.interface.parseLog(log); const { address, blockHash, blockNumber, transactionHash } = log; const { name, values } = potentialParsedLog; return { type: ActionsPageFeedType.NetworkEvent, name, values, createdAt: blockHash ? await getBlockTime(colonyClient.provider, blockHash) : 0, emmitedBy: ClientType.ColonyClient, address, blockNumber, transactionHash, } as ProcessedEvent; }, ), ); /* * Mayyyybe? this can work if we just use reverse() -- going by the logic * that all events come in order from the chain? * * Unless the RPC provider screws us over that is... */ const sortedRecoveryEvents = parsedRecoveryEvents.sort( (firstEvent, secondEvent) => firstEvent.createdAt - secondEvent.createdAt, ); return sortedRecoveryEvents; }; const getUsersWithRecoveryRoles = (recoveryRoleSetEvents: LogDescription[]) => { const userAddresses: Record<string, boolean> = {}; recoveryRoleSetEvents.map(({ values: { user, setTo } }) => { if (setTo) { userAddresses[user] = true; } else { userAddresses[user] = false; } return null; }); return Object.keys(userAddresses).filter( (userAddress) => !!userAddresses[userAddress], ); }; const resetAllApprovalChecks = (users: Array<UserQuery['user']>) => users.map((user) => ({ ...user, approvedRecoveryExit: false })); export const recoveryModeResolvers = ({ colonyManager, colonyManager: { provider }, apolloClient, }: Required<Context>): Resolvers => ({ Query: { async recoveryEventsForSession(_, { blockNumber, colonyAddress }) { try { const colonyClient = (await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, )) as ColonyClientV6; return await getSessionRecoveryEvents(colonyClient, blockNumber); } catch (error) { console.error(error); return []; } }, async recoveryAllEnteredEvents(_, { colonyAddress }) { try { const colonyClient = (await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, )) as ColonyClientV6; const enterRecoveryLogs = await getLogs( colonyClient, colonyClient.filters.RecoveryModeEntered(null), ); return Promise.all( enterRecoveryLogs.map(async (log) => { const potentialParsedLog = colonyClient.interface.parseLog(log); const { address, blockHash, blockNumber, transactionHash } = log; const { name, values } = potentialParsedLog; return { type: ActionsPageFeedType.NetworkEvent, name, values, createdAt: blockHash ? await getBlockTime(colonyClient.provider, blockHash) : 0, emmitedBy: ClientType.ColonyClient, address, blockNumber, transactionHash, } as ProcessedEvent; }), ); } catch (error) { console.error(error); return []; } }, async recoverySystemMessagesForSession(_, { blockNumber, colonyAddress }) { try { /* * @NOTE Leveraging apollo's internal cache * * This might seem counter intuitive, fetching an apollo query here, * when we could just call `getSessionRecoveryEvents` directly, but * doing so, allows us to fetch the recovery events that are already * inside the cache, and not be forced to fetch them all over again. * * This cuts down on loading times, especially on pages with a lot * of events generated. */ const recoveryEvents = await apolloClient.query< RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables >({ query: RecoveryEventsForSessionDocument, variables: { colonyAddress, blockNumber, }, }); /* * @NOTE Leveraging apollo's internal cache * * This cuts down on loading times, especially on pages with a lot * of events generated. */ const requiredApprovals = await apolloClient.query< GetRecoveryRequiredApprovalsQuery, GetRecoveryRequiredApprovalsQueryVariables >({ query: GetRecoveryRequiredApprovalsDocument, variables: { colonyAddress, blockNumber, }, }); if ( recoveryEvents?.data?.recoveryEventsForSession?.length && requiredApprovals?.data?.getRecoveryRequiredApprovals ) { let exitApprovalsCounter = 0; const systemMessages: SystemMessage[] = []; const { data: { getRecoveryRequiredApprovals: thresholdExitApprovals }, } = requiredApprovals; await Promise.all( recoveryEvents.data.recoveryEventsForSession.map( async ({ createdAt, name }) => { switch (name) { case ColonyAndExtensionsEvents.RecoveryModeExitApproved: exitApprovalsCounter += 1; break; case ColonyAndExtensionsEvents.RecoveryStorageSlotSet: exitApprovalsCounter = 0; break; default: break; } if (exitApprovalsCounter >= thresholdExitApprovals) { systemMessages.push({ type: ActionsPageFeedType.SystemMessage, name: SystemMessagesName.EnoughExitRecoveryApprovals, createdAt, }); exitApprovalsCounter = 0; } }, ), ); return systemMessages; } return []; } catch (error) { console.error(error); return []; } }, async recoveryRolesUsers(_, { colonyAddress, endBlockNumber }) { try { const subscribedUsers = await apolloClient.query< ColonyMembersQuery, ColonyMembersQueryVariables >({ query: ColonyMembersDocument, variables: { colonyAddress, }, }); /* * @NOTE This part is **very** import here * * We need to check the RecoveryRoleSet events UP UNTIL the block where * we exit the recovery mode. * * This is because the "old" recovery mode pages (where the recovery * session finished), need the reflect the then-users and approvals * as the roles might change between sessions (eg: one user lost * the recovery role, another gained it) * * If we are in a recovery session curently, we just go up until the * curent block * * (then again, we could also check these against the bock up until the * recovery session start, as roles cannot be changed once the recovery * session starts) */ const filterOptions: { fromBlock: number; toBlock?: number } = { fromBlock: 0, }; if (endBlockNumber) { filterOptions.toBlock = endBlockNumber; } const colonyClient = (await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, )) as ColonyClientV6; const recoveryRolesSet = await getMultipleEvents( colonyClient, [colonyClient.filters.RecoveryRoleSet(null, null)], filterOptions, ); const allUsers = subscribedUsers?.data?.subscribedUsers || []; const userWithRecoveryRoles = getUsersWithRecoveryRoles( recoveryRolesSet, ); return userWithRecoveryRoles.map((userAddress) => { const userWithProfile = allUsers.find( ({ profile: { walletAddress } }) => walletAddress.toLowerCase() === userAddress.toLowerCase(), ); if (!userWithProfile) { return getMinimalUser(userAddress); } return userWithProfile; }); } catch (error) { console.error(error); return []; } }, async recoveryRolesAndApprovalsForSession( _, { blockNumber, colonyAddress }, ) { try { /* * @NOTE Leveraging apollo's internal cache * * This might seem counter intuitive, fetching an apollo query here, * when we could just call `getSessionRecoveryEvents` directly, but * doing so, allows us to fetch the recovery events that are already * inside the cache, and not be forced to fetch them all over again. * * This cuts down on loading times, especially on pages with a lot * of events generated. */ const recoveryEvents = await apolloClient.query< RecoveryEventsForSessionQuery, RecoveryEventsForSessionQueryVariables >({ query: RecoveryEventsForSessionDocument, variables: { colonyAddress, blockNumber, }, }); // eslint-disable-next-line max-len const potentialExitEvent = recoveryEvents?.data?.recoveryEventsForSession?.find( ({ name }) => name === ColonyAndExtensionsEvents.RecoveryModeExited, ); /* * @NOTE Leveraging apollo's internal cache yet again, so we don't * re-fetch and re-parse both the server user and the recovery role events */ const usersWithRecoveryRoles = await apolloClient.query< RecoveryRolesUsersQuery, RecoveryRolesUsersQueryVariables >({ query: RecoveryRolesUsersDocument, variables: { colonyAddress, endBlockNumber: potentialExitEvent?.blockNumber, }, }); if (usersWithRecoveryRoles?.data?.recoveryRolesUsers?.length) { let usersAndApprovals = resetAllApprovalChecks( usersWithRecoveryRoles.data.recoveryRolesUsers, ); recoveryEvents?.data?.recoveryEventsForSession.map((event) => { const { name, values } = event; const { user: userAddress } = (values as unknown) as { user: string; }; const userIndex = usersAndApprovals.findIndex( ({ id: walletAddress }) => walletAddress.toLowerCase() === userAddress.toLowerCase(), ); if ( name === ColonyAndExtensionsEvents.RecoveryModeExitApproved && userIndex >= 0 ) { usersAndApprovals[userIndex].approvedRecoveryExit = true; } /* * Storage Slot was set, reset everything */ if (name === ColonyAndExtensionsEvents.RecoveryStorageSlotSet) { usersAndApprovals = resetAllApprovalChecks(usersAndApprovals); } return null; }); return usersAndApprovals; } return []; } catch (error) { console.error(error); return []; } }, async getRecoveryStorageSlot(_, { colonyAddress, storageSlot }) { try { const storageSlotValue = await provider.getStorageAt( colonyAddress, storageSlot, ); return ensureHexPrefix( storageSlotValue.toLowerCase().slice(2).padStart(64, '0'), ); } catch (error) { console.error(error); return `0x${'0'.padStart(64, '0')}`; } }, async getRecoveryRequiredApprovals(_, { blockNumber, colonyAddress }) { try { /* * @NOTE Leveraging apollo's internal cache yet again, so we don't * re-fetch and re-parse both the server user and the recovery role events */ const usersWithRecoveryRoles = await apolloClient.query< RecoveryRolesUsersQuery, RecoveryRolesUsersQueryVariables >({ query: RecoveryRolesUsersDocument, variables: { colonyAddress, endBlockNumber: blockNumber, }, }); const colonyClient = (await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, )) as ColonyClientV6; /* * The deployment owner is "special" * * Normally it's not set, but might get set when the colony is in * recovery mode, so the next the colony is in recovery mode, we * need to count recovery roles + 1 */ const deploymentOwner = await colonyClient.owner(); /* * If we have an owner address, we need to actually check if that is * a different address from all the ones that have recovery roles assinged * to them. * * If it is, disregard it, as the number of required approvals is the same. * * But if it's not, then we need to add one to the count */ if (deploymentOwner !== AddressZero) { /* * Prettier is being stupid again */ // eslint-disable-next-line max-len const isOwnerAlreadyAssignedRole = usersWithRecoveryRoles?.data?.recoveryRolesUsers?.find( ({ id: walletAddress }) => walletAddress.toLowerCase() === deploymentOwner.toLowerCase(), ); if (!isOwnerAlreadyAssignedRole) { return halfPlusOne( usersWithRecoveryRoles?.data?.recoveryRolesUsers?.length ? usersWithRecoveryRoles?.data?.recoveryRolesUsers?.length + 1 : 1, ); } /* * If we could find the user in the recovery roles array it means that * even though it has the owner designation as well, it was also * assigned a recovery role, at which point we just default back * to our usual mode of calculating this. */ } /* * We don't have the owner address set, so we just take the total * number of recovery roles and apply the half + 1 logic */ return halfPlusOne( usersWithRecoveryRoles?.data?.recoveryRolesUsers?.length || 0, ); } catch (error) { console.error(error); return 0; } }, /* * Total number of recovery roles set to users by the colony * * We use this to detect the issue introduced in v5 network contracts * and prevent the colony upgrade if a colony has more than 1 recovery * roles set to users */ async legacyNumberOfRecoveryRoles(_, { colonyAddress }) { try { const colonyClient = (await colonyManager.getClient( ClientType.ColonyClient, colonyAddress, )) as ColonyClientV5; const colonyVersion = await colonyClient.version(); /* * @NOTE We don't care about colonies that are newer than v6 */ if (colonyVersion.toNumber() === ColonyVersion.LightweightSpaceship) { const allRolesSet = await getMultipleEvents(colonyClient, [ colonyClient.filters.ColonyRoleSet(null, null, null, null, null), ]); const filteredAllRoles = getUsersWithRecoveryRoles( allRolesSet?.filter( ({ values }) => values?.role === ColonyRole.Recovery, ) || [], ); const recoveryRolesSet = await getMultipleEvents(colonyClient, [ colonyClient.filters.RecoveryRoleSet(null, null), ]); const filteredRecoveryRoles = getUsersWithRecoveryRoles( recoveryRolesSet, ); return [...filteredAllRoles, ...filteredRecoveryRoles].length; } return 0; } catch (error) { console.error(error); return 0; } }, }, });
the_stack
import {ParsedUrlQuery} from 'querystring'; import * as React from 'react'; import {CSSProperties} from 'react'; import {Store} from 'redux'; import {UrlWithStringQuery} from 'url'; import {DataCustomer} from './core/DataCustomer/index'; import {DataProviderEvent} from './core/Events/dataProviderEvent'; import {Events} from './core/Events/index'; import moment from 'moment'; import {RCREFormState} from './core/Form/Form'; import {RCREFormItem} from './core/Form/FormItem'; import {gridPositionItems} from './core/Layout/Row/Row'; import {ContainerNode} from './core/Service/ContainerDepGraph'; import {TriggerEventItem} from './core/Trigger/Trigger'; export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export type Overwrite<T, U> = Omit<T, Extract<keyof T, keyof U>> & U; // 扩展原有的类型 export type ExtendType<T1, extendType> = { [P in keyof T1]: T1[P] | extendType; }; export enum CoreKind { container = 'container', text = 'text', row = 'row', div = 'div', form = 'form', formItem = 'formItem' } // export type COREConfig<T> = // ContainerConfig // | TextConfig // | RowConfig<T> // | DivConfig<T> // | FormConfig<T> // | FormItemConfig<T>; // export type ConfigFactory<Config, Extend> = BasicConfig & ExtendType<Overwrite<Config, Extend>, string> & Extend; // export type DriverPropsFactory<Config extends BasicConfig, Props, Collection extends BasicConfig, Extend = {}> = // BasicConfig & // Props & // Extend & // BasicConnectProps<BasicContainerPropsInterface, Collection>; export type runTimeType = RunTimeType; type $itemType = { $parentItem?: $itemType; $parentIndex?: number; [key: string]: any; }; export interface RunTimeType { $data: any; $query?: any; $value?: any; $name?: any; $global?: any; $item?: $itemType; $location: any; $trigger?: any; $index?: number; $now?: moment.Moment; $moment?: typeof moment; $args?: any; $output?: any; $iterator?: any; $parent?: any; $form?: any; $formItem?: { valid: boolean; errmsg: string; }; $prev?: any; } export interface PropsRunTimeType extends RunTimeType { $parent: any; } export interface TriggerRunTimeType extends RunTimeType { $trigger: any; } export interface InteratorRunTimeType extends RunTimeType { $item: any; $index: number; } export type ExpressionStringType = string; export class BasicConfig { /** * 组件类型 */ type: string; /** * 是否隐藏 */ hidden?: boolean | ExpressionStringType; /** * 字级数据Key */ name?: string; /** * 默认数据 */ defaultValue?: any; /** * 延迟同步数据 */ debounce?: number | ExpressionStringType; /** * 关闭组件数据自清空的功能 */ disabledAutoClear?: boolean; /** * 是否禁用 */ disabled?: boolean | ExpressionStringType; /** * 不作为表单提交侦测的表单元素 */ notFormItem?: boolean; /** * 停止使用name进行数据同步 */ disableSync?: boolean; /** * 如果设置了disableSync,直接使用value传值 */ value?: any; /** * 是否显示 */ show?: boolean | ExpressionStringType; /** * 组件从container传值和组件向组件传值中的过滤器 * @deprecated */ transform?: { in: string; out: string; }; /** * 父级属性映射 */ parentMapping?: Object; /** * CSS class */ className?: string; /** * HTML ID 属性 */ id?: string; /** * 内联CSS属性 */ style?: CSSProperties; /** * 事件触发 */ trigger?: TriggerEventItem[]; /** * 关闭当组件被销毁时,就自动清除在container中的值 */ disableClearWhenDestroy?: boolean; /** * 当组件被销毁是,清除container中的值 */ clearWhenDestroy?: boolean; /** * 只清除表单数据不清楚container中的数据 */ clearFormStatusOnlyWhenDestroy?: boolean; /** * 是否作为表单输入元素 */ formItem?: boolean; __TEST_NAME__?: string; } export type ContainerSetDataOption = { /** * 强制触发刷新 */ forceUpdate?: boolean; /** * 是否是分页 */ pagination?: { paginationQueryParams: string[]; }; /** * 自定义同步的Key值 */ name?: string; /** * 跳过debounce缓存,直接设置container的值 */ skipDebounce?: boolean; }; export type rawJSONType = string | number | null | boolean | Object; export type originJSONType = rawJSONType | rawJSONType[]; export type defaultData = { [s: string]: ESFunc | any; }; export type BindItem = { child: string; parent: string; transform?: string }; export interface ContainerNodeOptions { /** * 同步删除无状态数据到父级 */ syncDelete?: boolean; /** * 使用字符串的export属性,并强制清除当前container和父级container相关的Key */ forceSyncDelete?: boolean; /** * 当前container组件被销毁的时候,同步清除父级和当前container所有相关的key */ clearDataToParentsWhenDestroy?: boolean; /** * 不允许同步undefined或者null到父级的container上 */ noNilToParent?: boolean; } export type ESFunc = (runTime: runTimeType) => any; export class BasicContainerPropsInterface { // 调试模式 debug?: boolean; info: any; /** * 当前Container的数据模型对象 */ $data?: Object; /** * 父级Container组件的数据模型对象 */ $parent?: Object; /** * RCRE 渲染配置 */ options?: RCREOptions; /** * Trigger组件的数据模型对象 */ $trigger?: Object; /** * 通过表格组件, 渲染之后, 获取到的每一行的数据 */ $item?: Object; /** * 通过表格组件, 渲染之后, 获取到的第几行 */ $index?: number; /** * 表单状态变量 */ $form?: { layout?: string; name?: string; control?: any; }; /** * React组件Key */ key?: string | number; /** * 底层组件设置数据模型值使用 */ $setData?: (name: string, value: any, options?: ContainerSetDataOption) => void; /** * 底层组件获取数据模型值使用 */ $getData?: (name: string | number, props: BasicContainerPropsInterface, isTmp?: boolean) => any | null; /** * 底层组件清除某个字段的数据 */ $deleteData?: (name: string, isTmp?: boolean) => void; /** * 清除Form的数据 */ $deleteFormItem?: (name: string) => void; /** * 底层组件设置多组数据模型值 */ $setMultiData?: (items: { name: string, value: any, isTmp?: boolean }[]) => void; /** * Trigger注入的通用事件处理函数, 所有事件处理都走这里 */ eventHandle?: (eventName: string, args: Object, options?: object) => void; /** * 来自Container的数据消耗者实例 */ dataCustomer?: DataCustomer; /** * 父级的数据模型Key */ model?: string; /** * Trigger组件自动生成的回调函数 */ injectEvents: { [fc: string]: Function }; } export interface BasicProps { /** * 来自RCRE的context对象 */ rcreContext: RCREContextType; /** * 来自Foreach组件的context对象 */ iteratorContext: IteratorContextType; /** * 来自Form组件的context对象 */ formContext?: FormContextType; /** * 来自FormItem组件的context对象 */ formItemContext?: FormItemContextType; /** * 来自父级Container的context对象 */ containerContext: ContainerContextType; /** * 来自Trigger组件的context对象 */ triggerContext?: TriggerContextType; gridCount?: number; gridPosition?: gridPositionItems; gridPaddingLeft?: number; gridPaddingRight?: number; gridLeft?: number; gridTop?: number; gridWidth?: number | string; gridHeight?: number | string; } /** * Provider 对象数据源配置 */ export interface ProviderSourceConfig { /** * provider模式 */ mode: string; /** * Provider配置 */ config?: any; /** * 请求发起所依赖的参数 */ requiredParams?: string[] | string; /** * 不仅判断参数的key,同样如果每个参数的value转义之后都是true */ strictRequired?: boolean | string; /** * 使用ExpressionString来决定是否请起数据 */ condition?: string | boolean; /** * Provider命名空间 */ namespace: string; /** * Provider返回值映射[弃用] */ retMapping?: Object; /** * Provider返回值映射 */ responseRewrite?: Object; /** * 返回值检查Expression String */ retCheckPattern?: string; /** * 错误弹出的错误提示 */ retErrMsg?: string; /** * 自动触发 */ autoInterval?: number; /** * 调试默认 */ debug?: boolean; } export interface CustomerItem { /** * customer名称 */ name: string; /** * customer执行模式 */ mode?: string; /** * customer配置 */ config?: any; /** * customer 函数 */ func?: string; } export interface CustomerGroup { /** * 组合名称 */ name: string; /** * 执行顺序 */ steps: string[]; /** * 当发生错误的时候,继续执行 */ keepWhenError?: boolean; } export interface TaskConfig { /** * 单个customer配置 */ customers?: CustomerItem[]; tasks?: CustomerItem[]; /** * 业务组合 */ groups?: CustomerGroup[]; taskMap?: CustomerGroup[]; } export type RCREOptions = { /** * 启动0.15.0版本之前的container数据合并策略 */ oldNestContainerCompatible?: boolean; /** * 兼容Safari10的兼容代码 */ safari10Layout?: boolean; }; /** * 内部基础组件的context变量 */ export interface RCREContextType { $global: object; $location: UrlWithStringQuery; $query: ParsedUrlQuery; debug: boolean; loadMode: string; lang: string; events: Events; dataProviderEvent: DataProviderEvent; options?: RCREOptions; store: Store<any>; containerGraph: Map<string, ContainerNode>; mode: 'React' | 'json'; } /** * Container为底层组件提供的Context */ export interface ContainerContextType { model: string; $data: any; $parent?: any; dataCustomer: DataCustomer; $setData: (name: string, value: any, options?: ContainerSetDataOption) => void; $getData: (name: string) => any; $deleteData: (name: string) => void; $setMultiData: (items: { name: string, value: any}[]) => void; } type TriggerContextOptions = { index?: number, preventSubmit?: boolean }; export type ExecTaskOptions = { // 延迟一定时间触发 wait?: number; }; export interface TriggerContextType { $trigger: any; eventHandle: (eventName: string, args: Object, options?: TriggerContextOptions) => Promise<any>; execTask: (targetTask: string, args: any, options?: ExecTaskOptions) => Promise<any>; } export interface IteratorContextType { $item: any; $index: number; $parentIndex?: number; $parentItem?: any; } export interface FormItemState { valid: boolean; formItemName: string; rules?: any[]; status?: string; errorMsg?: string; $validate?: boolean; validating?: boolean; required?: boolean; } export interface FormContextType { $form: RCREFormState; isSubmitting?: boolean; $setFormItem: (payload: FormItemState) => void; $getFormItem: (formItemName: string) => FormItemState; $setFormItems: (payload: FormItemState[]) => void; $deleteFormItem: (itemName: string) => void; $registerFormItem: (name: string, component: RCREFormItem) => void; $runValidations: () => Promise<boolean>; $resetForm: () => void; $handleSubmit: (e: React.FormEvent<HTMLFormElement> | undefined) => Promise<void>; } export type ElementsInfo = { disabled?: boolean; type?: string; value: any; }; export interface FormItemContextType { $validateFormItem: (name: string, value: any) => void; $deleteFormItem: (name: string) => void; $setFormItem: (payload: FormItemState) => void; deleteControlElements: (name: string) => void; initControlElements: (name: string, info: ElementsInfo) => void; updateControlElements: (name: string, info: ElementsInfo) => void; $handleBlur: () => void; $formItem: { valid: boolean; errmsg: string; validating: boolean; }; isUnderFormItem: boolean; } export interface PageConfig<T extends BasicConfig> { title?: string; body: T[]; } export interface PageProps<T extends BasicConfig> extends PageConfig<T> { // 外部注入的全局对象 global?: Object; // 调试模式 debug?: boolean; // 报错的信息语言 lang?: string; loadMode?: string; options?: RCREOptions; events?: Events; store: Store<any>; containerGraph: Map<string, ContainerNode>; }
the_stack
import { expectSaga } from 'redux-saga-test-plan'; import { ExternalLibraryName } from '../../../commons/application/types/ExternalTypes'; import { actions } from '../../../commons/utils/ActionsHelper'; import { CHANGE_EXTERNAL_LIBRARY, CHAPTER_SELECT, UPDATE_EDITOR_VALUE } from '../../../commons/workspace/WorkspaceTypes'; import { PLAYGROUND_UPDATE_PERSISTENCE_FILE } from '../../../features/playground/PlaygroundTypes'; // mock away the store - the store can't be created in a test, it leads to // import cycles // this is before the import below because we need to ensure PersistenceSaga's // store import is mocked jest.mock('../../../pages/createStore'); // eslint-disable-next-line @typescript-eslint/no-var-requires const PersistenceSaga = require('../PersistenceSaga').default; const USER_EMAIL = 'test@email.com'; const FILE_ID = '123'; const FILE_NAME = 'file'; const FILE_DATA = '// Hello world'; const SOURCE_CHAPTER = 3; const SOURCE_VARIANT = 'lazy'; const SOURCE_LIBRARY = ExternalLibraryName.MACHINELEARNING; beforeAll(() => { const authInstance: gapi.auth2.GoogleAuth = { signOut: () => {}, isSignedIn: { get: () => true, listen: () => {} }, currentUser: { listen: () => {}, get: () => ({ isSignedIn: () => true, getBasicProfile: () => ({ getEmail: () => USER_EMAIL }) }) } } as any; window.gapi = { client: { request: () => {}, init: () => Promise.resolve(), drive: { files: { get: () => {} } } }, load: (apiName: string, callbackOrConfig: gapi.CallbackOrConfig) => typeof callbackOrConfig === 'function' ? callbackOrConfig() : callbackOrConfig.callback(), auth2: { getAuthInstance: () => authInstance } } as any; }); test('LOGOUT_GOOGLE causes logout', async () => { const signOut = jest.spyOn(window.gapi.auth2.getAuthInstance(), 'signOut'); await expectSaga(PersistenceSaga).dispatch(actions.logoutGoogle()).silentRun(); expect(signOut).toBeCalled(); }); describe('PERSISTENCE_OPEN_PICKER', () => { test('opens a file on success path', () => { return expectSaga(PersistenceSaga) .dispatch(actions.persistenceOpenPicker()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': return { id: FILE_ID, name: FILE_NAME, picked: true }; case 'showSimpleConfirmDialog': return true; case 'get': expect(effect.args[0].fileId).toEqual(FILE_ID); if (effect.args[0].alt === 'media') { return { body: FILE_DATA }; } else if (effect.args[0].fields.includes('appProperties')) { return { result: { appProperties: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT, external: SOURCE_LIBRARY } } }; } break; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .put.like({ action: actions.playgroundUpdatePersistenceFile({ id: FILE_ID, name: FILE_NAME }) }) .put(actions.updateEditorValue(FILE_DATA, 'playground')) .put(actions.chapterSelect(SOURCE_CHAPTER, SOURCE_VARIANT, 'playground')) .put(actions.externalLibrarySelect(SOURCE_LIBRARY, 'playground')) .silentRun(); }); test('does not open if picker cancelled', () => { return expectSaga(PersistenceSaga) .dispatch(actions.persistenceOpenPicker()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': return { id: '', name: '', picked: true }; case 'showSimpleConfirmDialog': return false; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .not.put.like({ action: { type: PLAYGROUND_UPDATE_PERSISTENCE_FILE } }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); }); test('does not open if confirm cancelled', () => { return expectSaga(PersistenceSaga) .dispatch(actions.persistenceOpenPicker()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': return { picked: false }; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .not.put.like({ action: { type: PLAYGROUND_UPDATE_PERSISTENCE_FILE } }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); }); }); test('PERSISTENCE_SAVE_FILE saves', () => { let updateFileCalled = false; return expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFile({ id: FILE_ID, name: FILE_NAME })) .provide({ call(effect, next) { switch (effect.fn.name) { case 'updateFile': expect(updateFileCalled).toBe(false); expect(effect.args).toEqual([ FILE_ID, FILE_NAME, 'text/plain', FILE_DATA, { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT, external: SOURCE_LIBRARY } ]); updateFileCalled = true; return; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .put.like({ action: actions.playgroundUpdatePersistenceFile({ id: FILE_ID, name: FILE_NAME }) }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); }); describe('PERSISTENCE_SAVE_FILE_AS', () => { const DIR = { id: '456', name: 'Directory', picked: true }; test('overwrites a file in root', async () => { let updateFileCalled = false; await expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFileAs()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': if (effect.args[1].pickFolders) { return { picked: false }; } expect(effect.args[1].rootFolder).toEqual('root'); return { id: FILE_ID, name: FILE_NAME, picked: true }; case 'updateFile': expect(updateFileCalled).toBe(false); expect(effect.args).toEqual([ FILE_ID, FILE_NAME, 'text/plain', FILE_DATA, { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT, external: SOURCE_LIBRARY } ]); updateFileCalled = true; return; case 'showSimpleConfirmDialog': return true; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .put.like({ action: actions.playgroundUpdatePersistenceFile({ id: FILE_ID, name: FILE_NAME }) }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); expect(updateFileCalled).toBe(true); }); test('overwrites a file in a directory', async () => { let updateFileCalled = false; await expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFileAs()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': if (effect.args[1].pickFolders) { return DIR; } expect(effect.args[1].rootFolder).toEqual(DIR.id); return { id: FILE_ID, name: FILE_NAME, picked: true }; case 'updateFile': expect(updateFileCalled).toBe(false); expect(effect.args).toEqual([ FILE_ID, FILE_NAME, 'text/plain', FILE_DATA, { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT, external: SOURCE_LIBRARY } ]); updateFileCalled = true; return; case 'showSimpleConfirmDialog': return true; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .put.like({ action: actions.playgroundUpdatePersistenceFile({ id: FILE_ID, name: FILE_NAME }) }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); expect(updateFileCalled).toBe(true); }); test('creates a new file in root', async () => { let createFileCalled = false; await expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFileAs()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': if (effect.args[1].pickFolders) { return { picked: false }; } expect(effect.args[1].rootFolder).toEqual('root'); return { picked: false }; case 'createFile': expect(createFileCalled).toBe(false); expect(effect.args).toEqual([ FILE_NAME, 'root', 'text/plain', FILE_DATA, { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT, external: SOURCE_LIBRARY } ]); createFileCalled = true; return { id: FILE_ID, name: FILE_NAME }; case 'showSimplePromptDialog': return { buttonResponse: true, value: FILE_NAME }; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; default: console.log(effect); } fail(`unexpected function called: ${effect.fn.name}`); } }) .put.like({ action: actions.playgroundUpdatePersistenceFile({ id: FILE_ID, name: FILE_NAME }) }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); expect(createFileCalled).toBe(true); }); test('creates a new file in a directory', async () => { let createFileCalled = false; await expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFileAs()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': if (effect.args[1].pickFolders) { return DIR; } expect(effect.args[1].rootFolder).toEqual(DIR.id); return { picked: false }; case 'createFile': expect(createFileCalled).toBe(false); expect(effect.args).toEqual([ FILE_NAME, DIR.id, 'text/plain', FILE_DATA, { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT, external: SOURCE_LIBRARY } ]); createFileCalled = true; return { id: FILE_ID, name: FILE_NAME }; case 'showSimplePromptDialog': return { buttonResponse: true, value: FILE_NAME }; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; default: console.log(effect); } fail(`unexpected function called: ${effect.fn.name}`); } }) .put.like({ action: actions.playgroundUpdatePersistenceFile({ id: FILE_ID, name: FILE_NAME }) }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun(); expect(createFileCalled).toBe(true); }); test('does not overwrite if cancelled', () => expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFileAs()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': if (effect.args[1].pickFolders) { return DIR; } expect(effect.args[1].rootFolder).toEqual(DIR.id); return { id: FILE_ID, name: FILE_NAME, picked: true }; case 'showSimpleConfirmDialog': return false; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; } fail(`unexpected function called: ${effect.fn.name}`); } }) .not.put.like({ action: { type: PLAYGROUND_UPDATE_PERSISTENCE_FILE } }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun()); test('does not create a new file if cancelled', () => expectSaga(PersistenceSaga) .withState({ workspaces: { playground: { editorValue: FILE_DATA, externalLibrary: SOURCE_LIBRARY, context: { chapter: SOURCE_CHAPTER, variant: SOURCE_VARIANT } } } }) .dispatch(actions.persistenceSaveFileAs()) .provide({ call(effect, next) { switch (effect.fn.name) { case 'pickFile': if (effect.args[1].pickFolders) { return DIR; } expect(effect.args[1].rootFolder).toEqual(DIR.id); return { picked: false }; case 'showSimplePromptDialog': return { buttonResponse: false, value: FILE_NAME }; case 'ensureInitialisedAndAuthorised': case 'ensureInitialised': case 'showMessage': case 'showSuccessMessage': return; default: console.log(effect); } fail(`unexpected function called: ${effect.fn.name}`); } }) .not.put.like({ action: { type: PLAYGROUND_UPDATE_PERSISTENCE_FILE } }) .not.put.like({ action: { type: UPDATE_EDITOR_VALUE } }) .not.put.like({ action: { type: CHAPTER_SELECT } }) .not.put.like({ action: { type: CHANGE_EXTERNAL_LIBRARY } }) .silentRun()); });
the_stack
import {isNull, isNullOrUndefined} from 'util'; import * as pixelWidth from 'string-pixel-width'; import { Component, ElementRef, EventEmitter, HostListener, Injector, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {CommonUtil} from '@common/util/common.util'; import {PopupService} from '@common/service/popup.service'; import {AbstractPopupComponent} from '@common/component/abstract-popup.component'; import {GridComponent} from '@common/component/grid/grid.component'; import {GridOption} from '@common/component/grid/grid.option'; import {Header, SlickGridHeader} from '@common/component/grid/grid.header'; import {FileFormat, PrDatasetFile, SheetInfo} from '@domain/data-preparation/pr-dataset'; import {PreparationCommonUtil} from '../../util/preparation-common.util'; import {DatasetService} from '../service/dataset.service'; @Component({ selector: 'app-create-dataset-selecturl', templateUrl: './create-dataset-selecturl.component.html', }) export class CreateDatasetSelecturlComponent extends AbstractPopupComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild(GridComponent) private gridComponent: GridComponent; private _isInit: boolean = true; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Output() public typeEmitter = new EventEmitter<string>(); @Input() public datasetFiles: any; public isCSV: boolean = false; public isEXCEL: boolean = false; public isJSON: boolean = false; public settingFoldFlag: boolean = false; // grid hide public clearGrid: boolean = true; public isNext: boolean = false; public isDelimiterRequired: boolean = false; public isColumnCountRequired: boolean = false; public currDelimiter: string = ''; public currSheetIndex: number = 0; public currDSIndex: number = 0; public currDetail: any; public currColumnCount: number; public previewErrorMessge: string; public storedUri: string = ''; public isValidCheck: boolean = false; public errorNum: number; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ constructor(private popupService: PopupService, private datasetService: DatasetService, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public ngOnInit() { super.ngOnInit(); this.currDSIndex = 0; this.currSheetIndex = 0; this.currDetail = {fileFormat: null, detailName: null, columns: null, rows: null}; this.previewErrorMessge = ''; // Check init by selected count this._checkNextBtn(); this.settingFoldFlag = false; this._isInit = (!this.datasetFiles[0]); if (this._isInit) { const datasetFile = new PrDatasetFile(); datasetFile.storedUri = ''; datasetFile.sheetInfo = []; this.datasetFiles.push(datasetFile); } else { this.storedUri = this.datasetFiles[0].storedUri; this.isValidCheck = true; this._updateGrid(this.datasetFiles[0].sheetInfo[0].data, this.datasetFiles[0].sheetInfo[0].fields); this.currDelimiter = (this.datasetFiles[0].fileFormat === FileFormat.CSV ? this.datasetFiles[0].delimiter : ''); this.currColumnCount = (this.datasetFiles[0].sheetInfo ? this.datasetFiles[0].sheetInfo[0].columnCount : 0); this._setFileFormat(this.datasetFiles[0].fileFormat); this._setDetailInfomation(0, 0); } } public ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Close */ public close() { super.close(); // Check if came from dataflow if (this.datasetService.dataflowId) { this.datasetService.dataflowId = undefined; } this.popupService.notiPopup({ name: 'close-create', data: null }); } /** * Previous step */ public prev() { super.close(); this.popupService.notiPopup({ name: 'close-create', data: null }); } /** * Move to next step */ public next() { // 이미 validation 했고 실패한 상태 if (!isNullOrUndefined(this.errorNum) || this.isColumnCountRequired || this.isDelimiterRequired) { return; } // File url can't be empty if (this.storedUri.trim() === '' || isNullOrUndefined(this.storedUri)) { this.errorNum = 0; this.isValidCheck = false; return; } if (!this.isValidCheck) { this.errorNum = 0; return; } // Find selected sheets this.datasetFiles.forEach((dsFile) => { if (dsFile.sheetInfo && dsFile.fileFormat === FileFormat.EXCEL) { dsFile.selectedSheets = []; dsFile.sheetInfo.forEach((sheet) => { if (sheet.selected) dsFile.selectedSheets.push(sheet.sheetName); }); } }); // Excel일 경우 Sheet가 하나 이상 선택되어있어야 한다 if (this.isEXCEL) { if (this.datasetFiles[0].selectedSheets.length === 0) { return; } } this.typeEmitter.emit('URL'); this.popupService.notiPopup({ name: 'create-dataset-name', data: null }); } /** * Check URL Validation */ public checkValidation() { if (this.storedUri.length < 1) { console.log('length error'); this.errorNum = 0; this.isValidCheck = false; return; } this.settingFoldFlag = false; // Why ? this._setFileFormat(); this.currDelimiter = ','; // this.storedUri ='file:///Development/project/metatron-app/dataprep/uploads/dfaa81a7-b702-478c-91f8-18d3b9f96a00.xlsx'; // this.storedUri ='hdfs://localhost:9000/user/hive/dataprep/uploads/967d9cb8-f03d-4476-9f5a-b0cf22ba7fed.xlsx'; // // this.storedUri = 'file:///Development/project/metatron-app/dataprep/uploads/7f680c39-7b94-44f1-ac3b-d9dc18a15367.json'; // this.storedUri = 'hdfs://localhost:9000/user/hive/dataprep/uploads/2e73f15f-2b26-4e1a-9305-3a94fc3b4948.json'; // // this.storedUri = 'file:///Development/project/metatron-app/dataprep/uploads/2579531b-2c5a-40a8-8b02-0c8bd732553f.csv'; // this.storedUri = 'hdfs://localhost:9000/user/hive/dataprep/uploads/b5192e9e-c67c-49a6-90ef-148860a0a2ea.csv'; this.currDetail = {fileFormat: null, detailName: null, columns: null, rows: null}; delete this.datasetFiles[0].error; this.datasetFiles[0].fileName = this.storedUri.slice(this.storedUri.lastIndexOf('/') + 1, this.storedUri.lastIndexOf('.')); this.datasetFiles[0].fileExtension = (this.storedUri.lastIndexOf('.') > 0 ? this.storedUri.slice(this.storedUri.lastIndexOf('.') + 1, this.storedUri.length) : ''); this.datasetFiles[0].filenameBeforeUpload = this.storedUri.slice(this.storedUri.lastIndexOf('/') + 1, this.storedUri.length); this.datasetFiles[0].storedUri = this.storedUri; // File format this.datasetFiles[0].fileFormat = PreparationCommonUtil.getFileFormat(this.datasetFiles[0].fileExtension); this.datasetFiles[0].delimiter = ','; this.datasetFiles[0].sheetIndex = null; this.datasetFiles[0].sheetName = ''; this.datasetFiles[0].selectedSheets = []; this.datasetFiles[0].selected = false; this.datasetFiles[0].sheetInfo = []; this._setFileFormat(this.datasetFiles[0].fileFormat); this._getGridInformation(0, this._getParamForGrid(this.datasetFiles[0]), 'draw'); } /** * Toggle advanced setting */ public toggleAdvancedSetting() { this.settingFoldFlag = !this.settingFoldFlag; return this.settingFoldFlag; } /** * When delimiter is changed(only CSV) */ public changeDelimiter() { this.isDelimiterRequired = ('' === this.currDelimiter && this.isCSV); // No change in grid when delimiter is empty if ('' === this.currDelimiter.trim() || isNullOrUndefined(this.currDelimiter) || !this.isCSV) { return; } // 현재 딜리미터와 입력된 딜리미터가 다르다면 새로운 딜리미터가 적용된 그리드를 불러온다 if (this.datasetFiles[this.currDSIndex].delimiter !== this.currDelimiter) { this.datasetFiles[this.currDSIndex].delimiter = this.currDelimiter; this.loadingShow(); this._getGridInformation(this.currDSIndex, this._getParamForGrid(this.datasetFiles[this.currDSIndex]), 'draw'); this.isColumnCountRequired = false; } } /** * Keydown event * @param event * @param type */ public keydownEvent(event, type: string) { // 13 is enter key if (event.keyCode === 13) { // Stop event bubbling event.stopPropagation(); event.preventDefault(); // Column count input if ('colCnt' === type) { this.changeColumnCount(); } // File url input if ('url' === type) { this.checkValidation(); } // File delimiter if ('delimiter' === type) { this.changeDelimiter(); } } else { // 단어가 지워지거나 추가된다면 if (this._isKeyPressedWithChar(event.keyCode)) { // Column count input if ('colCnt' === type) { this.isColumnCountRequired = true; } // Column count input if ('delimiter' === type) { this.isDelimiterRequired = true; } // File url input if ('url' === type) { this.errorNum = null; } this.isValidCheck = false; } } } /** * When columnCount is changed(CSV, EXCEL) */ public changeColumnCount() { this.isColumnCountRequired = ((isNullOrUndefined(this.currColumnCount) || 1 > this.currColumnCount) && this.datasetFiles[this.currDSIndex].fileFormat !== FileFormat.JSON); if (isNullOrUndefined(this.currColumnCount) || 1 > this.currColumnCount || this.datasetFiles[this.currDSIndex].fileFormat === FileFormat.JSON) { return; } if (this.datasetFiles[this.currDSIndex].sheetInfo && this.datasetFiles[this.currDSIndex].sheetInfo[this.currSheetIndex].columnCount !== this.currColumnCount) { this.datasetFiles[this.currDSIndex].sheetInfo[this.currSheetIndex].columnCount = this.currColumnCount; this.loadingShow(); this._getGridInformation(this.currDSIndex, this._getParamForGrid(this.datasetFiles[this.currDSIndex], this.currColumnCount), 'draw'); this.isValidCheck = true; } } /** * Returns grid style */ public getGridStyle() { return {top: '0px'}; } /** * When Datafile Checked * @param event * @param dsIdx */ public checkGroup(event: any, dsIdx: number) { // stop event bubbling event.stopPropagation(); event.preventDefault(); if (!this.datasetFiles[dsIdx].sheetInfo) return; this.datasetFiles[dsIdx].sheetInfo = this.datasetFiles[dsIdx].sheetInfo.map((obj) => { obj.selected = !this.datasetFiles[dsIdx].selected; // obj.selected = true or false return obj; }); this.datasetFiles[dsIdx].selected = !this.datasetFiles[dsIdx].selected; this._checkNextBtn(); } /** * When Sheet Checked * @param event * @param dsIdx * @param sheetIdx */ public checkSheet(event: any, dsIdx: number, sheetIdx: number) { // stop event bubbling event.stopPropagation(); event.preventDefault(); console.log('checkSheet', this.datasetFiles[dsIdx]); if (!this.datasetFiles[dsIdx].sheetInfo) return; this.datasetFiles[dsIdx].sheetInfo[sheetIdx].selected = !this.datasetFiles[dsIdx].sheetInfo[sheetIdx].selected; if (!this.datasetFiles[dsIdx].sheetInfo[sheetIdx].selected) this.datasetFiles[dsIdx].selected = false; let selectedCount: number = 0; this.datasetFiles[dsIdx].sheetInfo.forEach((sheet) => { if (sheet.selected) selectedCount++; }); if (selectedCount === this.datasetFiles[dsIdx].sheetInfo.length) this.datasetFiles[dsIdx].selected = true; this._checkNextBtn(); this.safelyDetectChanges(); } /** * Select datasetFile and show grid * @param event * @param dsIdx */ public selectFile(event: any, dsIdx: number) { // stop event bubbling event.stopPropagation(); event.preventDefault(); this.previewErrorMessge = (this.datasetFiles[dsIdx].error ? this.datasetFiles[dsIdx].error.details : ''); this.isDelimiterRequired = false; this.isColumnCountRequired = false; if (this.datasetFiles[dsIdx].fileFormat !== FileFormat.EXCEL) { this._setFileFormat(this.datasetFiles[dsIdx].fileFormat); this.currDSIndex = dsIdx; this.currSheetIndex = 0; this._setDetailInfomation(dsIdx, 0); this.currDelimiter = this.datasetFiles[dsIdx].delimiter; this.currColumnCount = (this.datasetFiles[dsIdx].sheetInfo ? this.datasetFiles[dsIdx].sheetInfo[0].columnCount : 0); if (!this.datasetFiles[dsIdx].sheetInfo) { this.clearGrid = true; return; } this.currSheetIndex = 0; this.datasetFiles[dsIdx].sheetIndex = 0; this.datasetFiles[dsIdx].sheetName = this.datasetFiles[dsIdx].sheetInfo[0].sheetName; // if grid info is valid show grid else clear grid if (!isNullOrUndefined(this.datasetFiles[dsIdx]) && this.datasetFiles[dsIdx].sheetInfo[0]) { this._updateGrid(this.datasetFiles[dsIdx].sheetInfo[0].data, this.datasetFiles[dsIdx].sheetInfo[0].fields); } else { this.clearGrid = true; } } } /** * Select sheet and show grid * @param event * @param dsIdx * @param sheetName * @param sheetIdx */ public selectSheet(event: any, dsIdx: number, sheetName: string, sheetIdx: number) { event.stopPropagation(); event.preventDefault(); this.isDelimiterRequired = false; this.currDelimiter = ''; this.isColumnCountRequired = false; this.currColumnCount = (this.datasetFiles[dsIdx].sheetInfo ? this.datasetFiles[dsIdx].sheetInfo[sheetIdx].columnCount : 0); this.currDSIndex = dsIdx; this._setFileFormat(this.datasetFiles[dsIdx].fileFormat); this.currSheetIndex = sheetIdx; if (!this.datasetFiles[dsIdx].sheetInfo) { this.clearGrid = true; return; } this._setDetailInfomation(dsIdx, sheetIdx); this.currSheetIndex = sheetIdx; this.datasetFiles[dsIdx].sheetIndex = sheetIdx; this.datasetFiles[dsIdx].sheetName = sheetName; // if grid info is valid show grid else clear grid if (!isNullOrUndefined(this.datasetFiles[dsIdx]) && this.datasetFiles[dsIdx].sheetInfo[sheetIdx]) { this._updateGrid(this.datasetFiles[dsIdx].sheetInfo[sheetIdx].data, this.datasetFiles[dsIdx].sheetInfo[sheetIdx].fields); } else { this.clearGrid = true; } } /** * Go to next stage with enter key * @param event Event */ @HostListener('document:keydown.enter', ['$event']) public onEnterKeydownHandler(event: KeyboardEvent) { if (event.keyCode === 13) { this.next(); } } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private _setFileFormat(fileFormat?: FileFormat) { if (fileFormat && fileFormat.toString().length > 0) { this.isCSV = (fileFormat === FileFormat.CSV) || (fileFormat === FileFormat.TXT); this.isJSON = (fileFormat === FileFormat.JSON); this.isEXCEL = (fileFormat === FileFormat.EXCEL); } else { this.isCSV = false; this.isJSON = false; this.isEXCEL = false; } } /** * Returns parameter required for grid fetching API * @returns result {fileKey: string, delimiter: string} * @private */ private _getParamForGrid(datasetFile: PrDatasetFile, manualColumnCount?: number) { const result = { storedUri: datasetFile.storedUri, }; if (this.isCSV) result['delimiter'] = datasetFile.delimiter; if (manualColumnCount && manualColumnCount > 0) result['manualColumnCount'] = manualColumnCount; return result; } private _getGridInformation(idx: number, param: any, option: string) { this.loadingShow(); this.datasetService.getFileGridInfo(param).then((result) => { if (result.gridResponses) { this.isValidCheck = true; if (option && option === 'draw') this.clearGrid = false; this._setSheetInformation(idx, result.gridResponses, result.sheetNames); // 첫번째 시트로 그리드를 그린다. const sheet = this.datasetFiles[idx].sheetInfo[this.currSheetIndex]; // Update grid if (option && option === 'draw') this._updateGrid(sheet.data, sheet.fields); if (result.sheetNames) { // Select first sheet in the list this.datasetFiles[idx].sheetName = sheet.sheetName ? sheet.sheetName : undefined; } this.errorNum = null; } else { // no result from server if (option && option === 'draw') this.clearGrid = true; this.errorNum = 1; this.isValidCheck = false; } this.loadingHide(); }).catch(() => { this.errorNum = 1; this.isValidCheck = false; this.datasetFiles[0] = new PrDatasetFile(); this.clearGrid = true; this.isEXCEL = false; this.gridComponent.destroy(); this.loadingHide(); }); } /** * Grid update * @param data * @param {Field[]} fields */ private _updateGrid(data: any, fields: Field[]) { if (data.length > 0 && fields.length > 0) { this.clearGrid = false; const headers: Header[] = this._getHeaders(fields); const rows: any[] = PreparationCommonUtil.getRows(data); this._drawGrid(headers, rows); } else { this.loadingHide(); this.clearGrid = true; } } /** * Draw grid * @param {any[]} headers * @param {any[]} rows */ private _drawGrid(headers: any[], rows: any[]) { this.safelyDetectChanges(); this.gridComponent.create(headers, rows, new GridOption() .SyncColumnCellResize(true) .MultiColumnSort(true) .RowHeight(32) .build() ); this.loadingHide(); } /** * Returns header information for grid * @param {Field[]} fields * @returns {header[]} */ private _getHeaders(fields: Field[]) { return fields.map( (field: Field) => { /* 70 는 CSS 상의 padding 수치의 합산임 */ const headerWidth: number = Math.floor(pixelWidth(field.name, {size: 12})) + 70; return new SlickGridHeader() .Id(field.name) .Name('<span style="padding-left:20px;"><em class="' + this.getFieldTypeIconClass(field.type) + '"></em>' + field.name + '</span>') .Field(field.name) .Behavior('select') .Selectable(false) .CssClass('cell-selection') .Width(headerWidth) .CannotTriggerInsert(true) .Resizable(true) .Unselectable(true) .Sortable(true) .ColumnType(field.type) .Formatter((_row, _cell, value, _columnDef) => { if (field.type === 'STRING') { value = (value) ? value.toString().replace(/</gi, '&lt;') : value; value = (value) ? value.toString().replace(/>/gi, '&gt;') : value; value = (value) ? value.toString().replace(/\n/gi, '&crarr;') : value; const tag = '<span style="color:#ff00ff; font-size: 9pt; letter-spacing: 0">&middot;</span>'; value = (value) ? value.toString().replace(/\s/gi, tag) : value; } if (isNull(value)) { return '<div style=\'position:absolute; top:0; left:0; right:0; bottom:0; line-height:30px; padding:0 10px; font-style: italic ; color:#b8bac2;\'>' + '(null)' + '</div>'; } else { return value; } }) .build(); } ); } /** * Set sheet information - name, grid etc * @param idx * @param gridInfo * @param sheetNames * @private */ private _setSheetInformation(idx: number, gridInfo: any, sheetNames: string[]) { if (gridInfo && gridInfo.length > 0) { this.datasetFiles[idx].sheetInfo = []; gridInfo.forEach((item, index) => { const gridData = this._getGridDataFromGridResponse(item); const info: SheetInfo = { selected: true, data: gridData.data, fields: gridData.fields, totalRows: 0, valid: true, columnCount: gridData.fields.length }; if (sheetNames) info.sheetName = sheetNames[index]; this.datasetFiles[idx].sheetInfo.push(info); if (this.currDSIndex === 0) this._setDetailInfomation(0, 0); }); // set current column count if (idx === this.currDSIndex) this.currColumnCount = (this.datasetFiles[this.currDSIndex].sheetInfo ? this.datasetFiles[this.currDSIndex].sheetInfo[this.currSheetIndex].columnCount : null); this.datasetFiles[idx].selected = true; this.isNext = true; } } /** * API 조회 결과를 바탕으로 그리드 데이터 구조를 얻는다. * @param gridResponse * @returns {GridData} * @private */ private _getGridDataFromGridResponse(gridResponse: any): GridData { const colCnt = gridResponse.colCnt; const colNames = gridResponse.colNames; const colTypes = gridResponse.colDescs; const gridData: GridData = new GridData(); for (let idx = 0; idx < colCnt; idx++) { gridData.fields.push({ name: colNames[idx], type: colTypes[idx].type, seq: idx, uuid: CommonUtil.getUUID() }); } gridResponse.rows.forEach((row) => { const obj = {}; for (let idx = 0; idx < colCnt; idx++) { obj[colNames[idx]] = row.objCols[idx]; } gridData.data.push(obj); }); return gridData; } // function - _getGridDataFromGridResponse /** * Detail Information of Selected Sheet * @private */ private _setDetailInfomation(dsIdx: number, sheetIdx?: number) { if (this.datasetFiles[dsIdx].fileFormat === FileFormat.EXCEL) { this.currDetail.detailName = this.datasetFiles[dsIdx].fileName; if (this.datasetFiles[dsIdx].sheetInfo) this.currDetail.detailName += '-' + this.datasetFiles[dsIdx].sheetInfo[sheetIdx].sheetName; } else { this.currDetail.detailName = this.datasetFiles[dsIdx].fileName; } this.currDetail.fileFormat = this.datasetFiles[dsIdx].fileFormat; this.currDetail.columns = ((this.datasetFiles[dsIdx].sheetInfo) ? this.datasetFiles[dsIdx].sheetInfo[sheetIdx].fields.length : null); this.currDetail.rows = ((this.datasetFiles[dsIdx].sheetInfo) ? this.datasetFiles[dsIdx].sheetInfo[sheetIdx].totalRows : null); } /** * Check Next Button */ private _checkNextBtn() { let selectedCount: number = 0; this.datasetFiles.forEach((dsFile) => { if (dsFile.sheetInfo) { dsFile.sheetInfo.forEach((sheet) => { if (sheet.selected) selectedCount++; }) } }); this.isNext = (selectedCount > 0); } /** * Returns true if something is typed on the keyboard * Returns false if shift, tab etc is pressed * 즉 직접 단어 자체가 지워지거나 입력된다면 true 를 반환한다. * @param keyCode */ private _isKeyPressedWithChar(keyCode: number): boolean { const exceptionList: number[] = [9, 13, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 92, 219, 220, 93, 144, 145]; return exceptionList.indexOf(keyCode) === -1 } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ } class Field { name: string; type: string; timestampStyle?: string; } class GridData { public data: any[]; public fields: any[]; constructor() { this.data = []; this.fields = []; } }
the_stack
import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; import * as ec2 from '@aws-cdk/aws-ec2'; import * as events from '@aws-cdk/aws-events'; import * as iam from '@aws-cdk/aws-iam'; import * as s3 from '@aws-cdk/aws-s3'; import * as core from '@aws-cdk/core'; import { Construct } from 'constructs'; // for files that are part of this package, we do import individual classes or functions import { exampleResourceArnComponents } from './private/example-resource-common'; /** * The interface that represents the ExampleResource resource. * We always use an interface, because each L2 resource type in the CDK can occur in two aspects: * * 1. It can be a resource that's created and managed by the CDK. * Those resources are represented by the class with the name identical to the resource - * {@link ExampleResource} in our case, which implements {@link IExampleResource}. * 2. It can be a resource that exists already, and is not managed by the CDK code, * but needs to be referenced in your infrastructure definition code. * Those kinds of instances are returned from static `fromXyz(Name/Arn/Attributes)` methods - * in our case, the {@link ExampleResource.fromExampleResourceName} method. * In general, those kinds of resources do not allow any sort of mutating operations to be performed on them * (the exception is when they can be changed by creating a different resource - * IAM Roles, which you can attach multiple IAM Policies to, * are the canonical example of this sort of resource), * as they are not part of the CloudFormation stack that is created by the CDK. * * So, an interface like {@link IExampleResource} represents a resource that *might* be mutable, * while the {@link ExampleResource} class represents a resource that definitely is mutable. * Whenever a type that represents this resource needs to referenced in other code, * you want to use {@link IExampleResource} as the type, not {@link ExampleResource}. * * The interface for the resource should have at least 2 (readonly) properties * that represent the ARN and the physical name of the resource - * in our example, those are {@link exampleResourceArn} and {@link exampleResourceName}. * * The interface defines the behaviors the resource exhibits. * Common behaviors are: * - {@link addToRolePolicy} for resources that are tied to an IAM Role * - grantXyz() methods (represented by {@link grantRead} in this example) * - onXyz() CloudWatch Events methods (represented by {@link onEvent} in this example) * - metricXyz() CloudWatch Metric methods (represented by {@link metricCount} in this example) * * Of course, other behaviors are possible - * it all depends on the capabilities of the underlying resource that is being modeled. * * This interface must always extend the IResource interface from the core module. * It can also extend some other common interfaces that add various default behaviors - * some examples are shown below. */ export interface IExampleResource extends // all L2 interfaces need to extend IResource core.IResource, // Only for resources that have an associated IAM Role. // Allows this resource to be the target in calls like bucket.grantRead(exampleResource). iam.IGrantable, // only for resources that are in a VPC and have SecurityGroups controlling their traffic ec2.IConnectable { /** * The ARN of example resource. * Equivalent to doing `{ 'Fn::GetAtt': ['LogicalId', 'Arn' ]}` * in CloudFormation if the underlying CloudFormation resource * surfaces the ARN as a return value - * if not, we usually construct the ARN "by hand" in the construct, * using the Fn::Join function. * * It needs to be annotated with '@attribute' if the underlying CloudFormation resource * surfaces the ARN as a return value. * * @attribute */ readonly exampleResourceArn: string; /** * The physical name of the example resource. * Often, equivalent to doing `{ 'Ref': 'LogicalId' }` * (but not always - depends on the particular resource modeled) * in CloudFormation. * Also needs to be annotated with '@attribute'. * * @attribute */ readonly exampleResourceName: string; /** * For resources that have an associated IAM Role, * surface that Role as a property, * so that other classes can add permissions to it. * Make it optional, * as resources imported with {@link ExampleResource.fromExampleResourceName} * will not have this set. */ readonly role?: iam.IRole; /** * For resources that have an associated IAM Role, * surface a method that allows you to conditionally * add a statement to that Role if it's known. * This is just a convenience, * so that clients of your interface don't have to check {@link role} for null. * Many such methods in the CDK return void; * you can also return a boolean indicating whether the permissions were in fact added * (so, when {@link role} is not null). */ addToRolePolicy(policyStatement: iam.PolicyStatement): boolean; /** * An example of a method that grants the given IAM identity * permissions to this resource * (in this case - read permissions). */ grantRead(identity: iam.IGrantable): iam.Grant; /** * Add a CloudWatch rule that will use this resource as the source of events. * Resources that emit events have a bunch of methods like these, * that allow different resources to be triggered on various events happening to this resource * (like item added, item updated, item deleted, ect.) - * exactly which methods you need depends on the resource you're modeling. */ onEvent(id: string, options?: events.OnEventOptions): events.Rule; /** * Standard method that allows you to capture metrics emitted by this resource, * and use them in dashboards and alarms. * The details of which metric methods you should have of course depends on the * resource that is being modeled. */ metricCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric; } /** * A common abstract superclass that implements the {@link IExampleResource} interface. * We often have these classes to share code between the {@link ExampleResource} * class and the {@link IExampleResource} instances returned from methods like * {@link ExampleResource.fromExampleResourceName}. * It has to extend the Resource class from the core module. * * Notice that the class is not exported - it's not part of the public API of this module! */ abstract class ExampleResourceBase extends core.Resource implements IExampleResource { // these stay abstract at this level public abstract readonly exampleResourceArn: string; public abstract readonly exampleResourceName: string; public abstract readonly role?: iam.IRole; // this property is needed for the iam.IGrantable interface public abstract readonly grantPrincipal: iam.IPrincipal; // This is needed for the ec2.IConnectable interface. // Allow subclasses to write this field. // JSII requires all member starting with an underscore to be annotated with '@internal'. /** @internal */ protected _connections: ec2.Connections | undefined; /** Implement the ec2.IConnectable interface, using the _connections field. */ public get connections(): ec2.Connections { if (!this._connections) { throw new Error('An imported ExampleResource cannot manage its security groups'); } return this._connections; } /** Implement the convenience {@link IExampleResource.addToRolePolicy} method. */ public addToRolePolicy(policyStatement: iam.PolicyStatement): boolean { if (this.role) { this.role.addToPrincipalPolicy(policyStatement); return true; } else { return false; } } /** Implement the {@link IExampleResource.grantRead} method. */ public grantRead(identity: iam.IGrantable): iam.Grant { // usually, we would grant some service-specific permissions here, // but since this is just an example, let's use S3 return iam.Grant.addToPrincipal({ grantee: identity, actions: ['s3:Get*'], // as many actions as you need resourceArns: [this.exampleResourceArn], }); } /** * Implement the {@link IExampleResource.onEvent} method. * Notice that we change 'options' from an optional argument to an argument with a default value - * that's a common trick in the CDK * (you're not allowed to have default values for arguments in interface methods in TypeScript), * as it simplifies the implementation code (less branching). */ public onEvent(id: string, options: events.OnEventOptions = {}): events.Rule { const rule = new events.Rule(this, id, options); rule.addTarget(options.target); rule.addEventPattern({ // obviously, you would put your resource-specific values here source: ['aws.cloudformation'], detail: { 'example-resource-name': [this.exampleResourceName], }, }); return rule; } /** Implement the {@link IExampleResource.metricCount} method. */ public metricCount(props?: cloudwatch.MetricOptions): cloudwatch.Metric { return new cloudwatch.Metric({ // of course, you would put your resource-specific values here namespace: 'AWS/ExampleResource', metricName: 'Count', dimensionsMap: { ExampleResource: this.exampleResourceName }, ...props, }).attachTo(this); } } /** * Construction properties for {@link ExampleResource}. * All constructs have the same construction pattern: * you provide a scope of type Construct, * a string identifier, and a third argument, * representing the properties specific to that resource. * That third type is represented in the CDK by an interface * with only readonly simple properties (no methods), * sometimes called, in JSII terminology, a 'struct'. * This is this struct for the {@link ExampleResource} class. * * This interface is always called '<ResourceName>Props'. */ export interface ExampleResourceProps { /** * The physical name of the resource. * If you don't provide one, CloudFormation will generate one for you. * Almost all resources, with only a few exceptions, * allow setting their physical name. * The name is a little silly, * because of the @resource annotation on the {@link ExampleResource} class * (CDK linters make sure those two names are aligned). * * @default - CloudFormation-generated name */ readonly waitConditionHandleName?: string; /** * Many resources require an IAM Role to function. * While a customer can provide one, * the CDK will always create a new one * (with the correct assumeRole service principal) if it wasn't provided. * * @default - a new Role will be created */ readonly role?: iam.IRole; /** * Many resources allow passing in an optional S3 Bucket. * Buckets can also have KMS Keys associated with them, * so any encryption settings in your resource should check * for the presence of that property on the passed Bucket. * * @default - no Bucket will be used */ readonly bucket?: s3.IBucket; /** * Many resources can be attached to a VPC. * If your resource cannot function without a VPC, * make this property required - * do NOT make it optional, and then create a VPC implicitly! * This is different than what we do for IAM Roles, for example. * * @default - no VPC will be used */ readonly vpc?: ec2.IVpc; /** * Whenever you have IVpc as a property, * like we have in {@link vpc}, * you need to provide an optional property of type ec2.SubnetSelection, * which can be used to specify which subnets of the VPC should the resource use. * The default is usually all private subnets, * however you can change that default in your resource if it makes sense * (for example, to all public subnets). * * @default - default subnet selection strategy, see the EC2 module for details */ readonly vpcSubnets?: ec2.SubnetSelection; /** * If your resource interface extends ec2.IConnectable, * that means it needs security groups to control traffic coming to and from it. * Allow the customer to specify these security groups. * If none were specified, we will create a new one implicitly, * similarly like we do for IAM Roles. * * **Note**: a few resources in the CDK only allow you to provide a single SecurityGroup. * This is generally considered a historical mistake, * and all new code should allow an array of security groups to be passed. * * @default - a new security group will be created */ readonly securityGroups?: ec2.ISecurityGroup[]; /** * What to do when this resource is deleted from a stack. * Some stateful resources cannot be deleted if they have any contents * (S3 Buckets are the canonical example), * so we set their deletion policy to RETAIN by default. * If your resource also behaves like that, * you need to allow your customers to override this behavior if they need to. * * @default RemovalPolicy.RETAIN */ readonly removalPolicy?: core.RemovalPolicy; } /** * The actual L2 class for the ExampleResource. * Extends ExampleResourceBase. * Represents a resource completely managed by the CDK, and thus mutable. * You can add additional methods to the public API of this class not present in {@link IExampleResource}, * although you should strive to minimize that as much as possible, * and have the entire API available in {@link IExampleResource} * (but perhaps some of it not having any effect, * like {@link IExampleResource.addToRolePolicy}). * * Usually, the CDK is able to figure out what's the equivalent CloudFormation resource for this L2, * but sometimes (like in this example), we need to specify it explicitly. * You do it with the '@resource' annotation: * * @resource AWS::CloudFormation::WaitConditionHandle */ export class ExampleResource extends ExampleResourceBase { /** * Reference an existing ExampleResource, * defined outside of the CDK code, by name. * * The class might contain more methods for referencing an existing resource, * like fromExampleResourceArn, * or fromExampleResourceAttributes * (the last one if you want the importing behavior to be more customizable). */ public static fromExampleResourceName(scope: Construct, id: string, exampleResourceName: string): IExampleResource { // Imports are almost always implemented as a module-private // inline class in the method itself. // We extend ExampleResourceBase to reuse all of the logic inside it. class Import extends ExampleResourceBase { // we don't have an associated Role in this case public readonly role = undefined; // for imported resources, you always use the UnknownPrincipal, // which ignores all modifications public readonly grantPrincipal = new iam.UnknownPrincipal({ resource: this }); public readonly exampleResourceName = exampleResourceName; // Since we have the name, we have to generate the ARN, // using the Stack.formatArn helper method from the core library. // We have to know the ARN components of ExampleResource in a few places, so, // to avoid duplication, extract that into a module-private function public readonly exampleResourceArn = core.Stack.of(scope) .formatArn(exampleResourceArnComponents(exampleResourceName)); } return new Import(scope, id); } // implement all fields that are abstract in ExampleResourceBase public readonly exampleResourceArn: string; public readonly exampleResourceName: string; // while we know 'role' will actually never be undefined in this class, // JSII does not allow changing the optionality of a field // when overriding it, so it has to be 'role?' public readonly role?: iam.IRole; public readonly grantPrincipal: iam.IPrincipal; /** * The constructor of a construct has always 3 arguments: * the parent Construct, the string identifier, * locally unique within the scope of the parent, * and a properties struct. * * If the props only have optional properties, like in our case, * make sure to add a default value of an empty object to the props argument. */ constructor(scope: Construct, id: string, props: ExampleResourceProps = {}) { // Call the constructor from Resource superclass, // which attaches this construct to the construct tree. super(scope, id, { // You need to let the Resource superclass know which of your properties // signifies the resource's physical name. // If your resource doesn't have a physical name, // don't set this property. // For more information on what exactly is a physical name, // see the CDK guide: https://docs.aws.amazon.com/cdk/latest/guide/resources.html#resources_physical_names physicalName: props.waitConditionHandleName, }); // We often add validations for properties, // so that customers receive feedback about incorrect properties // sooner than a CloudFormation deployment. // However, when validating string (and number!) properties, // it's important to remember that the value can be a CFN function // (think a { Ref: ParameterName } expression in CloudFormation), // and that sort of value would be also encoded as a string; // so, we need to use the Token.isUnresolved() method from the core library // to skip validation in that case. if (props.waitConditionHandleName !== undefined && !core.Token.isUnresolved(props.waitConditionHandleName) && !/^[_a-zA-Z]+$/.test(props.waitConditionHandleName)) { throw new Error('waitConditionHandleName must be non-empty and contain only letters and underscores, ' + `got: '${props.waitConditionHandleName}'`); } // Inside the implementation of the L2, // we very often use L1 classes (those whose names begin with 'Cfn'). // However, it's important we don't 'leak' that fact to the API of the L2 class - // so, we should never take L1 types as inputs in our props, // and we should not surface any L1 classes in public fields or methods of the class. // The 'Cfn*' class is purely an implementation detail. // If this was a real resource, we would use a specific L1 for that resource // (like a CfnBucket inside the Bucket class), // but since this is just an example, // we'll use CloudFormation wait conditions. // Remember to always, always, pass 'this' as the first argument // when creating any constructs inside your L2s! // This guarantees that they get scoped correctly, // and the CDK will make sure their locally-unique identifiers // are globally unique, which makes your L2 compose. const waitConditionHandle = new core.CfnWaitConditionHandle(this, 'WaitConditionHandle'); // The 'main' L1 you create should always have the logical ID 'Resource'. // This is important, so that the ConstructNode.defaultChild method works correctly. // The local variable representing the L1 is often called 'resource' as well. const resource = new core.CfnWaitCondition(this, 'Resource', { count: 0, handle: waitConditionHandle.ref, timeout: '10', }); // The resource's physical name and ARN are set using // some protected methods from the Resource superclass // that correctly resolve when your L2 is used in another resource // that is in a different AWS region or account than this one. this.exampleResourceName = this.getResourceNameAttribute( // A lot of the CloudFormation resources return their physical name // when the Ref function is used on them. // If your resource is like that, simply pass 'resource.ref' here. // However, if Ref for your resource returns something else, // it's often still possible to use CloudFormation functions to get out the physical name; // for example, if Ref for your resource returns the ARN, // and the ARN for your resource is of the form 'arn:aws:<service>:<region>:<account>:resource/physical-name', // which is quite common, // you can use Fn::Select and Fn::Split to take out the part after the '/' from the ARN: core.Fn.select(1, core.Fn.split('/', resource.ref)), ); this.exampleResourceArn = this.getResourceArnAttribute( // A lot of the L1 classes have an 'attrArn' property - // if yours does, use it here. // However, if it doesn't, // you can often formulate the ARN yourself, // using the Stack.formatArn helper function. // Here, we assume resource.ref returns the physical name of the resource. core.Stack.of(this).formatArn(exampleResourceArnComponents(resource.ref)), // always use the protected physicalName property for this second argument exampleResourceArnComponents(this.physicalName)); // if a role wasn't passed, create one const role = props.role || new iam.Role(this, 'Role', { // of course, fill your correct service principal here assumedBy: new iam.ServicePrincipal('cloudformation.amazonaws.com'), }); this.role = role; // we need this to correctly implement the iam.IGrantable interface this.grantPrincipal = role; // implement the ec2.IConnectable interface, // by writing to the _connections field in ExampleResourceBase, // if a VPC was passed in props if (props.vpc) { const securityGroups = (props.securityGroups ?? []).length === 0 // no security groups were provided - create one ? [new ec2.SecurityGroup(this, 'SecurityGroup', { vpc: props.vpc, })] : props.securityGroups; this._connections = new ec2.Connections({ securityGroups }); // this is how you would use the VPC inputs to fill a subnetIds property of an L1: new ec2.CfnVPCEndpoint(this, 'VpcEndpoint', { vpcId: props.vpc.vpcId, serviceName: 'ServiceName', subnetIds: props.vpc.selectSubnets(props.vpcSubnets).subnetIds, }); } // this is how you apply the removal policy resource.applyRemovalPolicy(props.removalPolicy, { // this is the default to apply if props.removalPolicy is undefined default: core.RemovalPolicy.RETAIN, }); } }
the_stack
export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** The `DateTime` scalar represents an ISO-8601 compliant date time type. */ DateTime: any; UUID: any; /** The `Long` scalar type represents non-fractional signed whole 64-bit numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ Long: any; }; export type Query = { __typename?: 'Query'; /** Returns a list of pastes and markdown docs beloning to the active user */ myDocs?: Maybe<MyDocsConnection>; /** Returns a doc(paste or markdown) by slug */ doc?: Maybe<VirtualFile>; file?: Maybe<PhysicalFile>; /** Paged list of the active users uploaded media, newest first. */ myFiles?: Maybe<MyFilesConnection>; /** Returns a list of this users permanently deleted files(no recovery, 30 days passed) */ deletedFiles?: Maybe<Array<Maybe<DeletedFile>>>; /** Returns a paged list of this users files awaiting removal(30 days after deleted) */ filesPendingRemoval?: Maybe<AllFilesResult>; /** Returns a paged list of physical and virtual files */ allFiles?: Maybe<AllFilesResult>; /** Returns a list of User Features enabled on the current users account */ userFeatures?: Maybe<Array<Maybe<UserFeature>>>; /** Returns a result outlining the total storage space used by physical files uploaded by this user(including files marked for deletion but not yet deleted) */ storageUsage?: Maybe<UserStorageUsageResult>; /** Returns paged list of signup codes */ signupCodes?: Maybe<SignupCodesConnection>; /** Returns the API key for the current user */ myApiKey?: Maybe<Scalars['String']>; }; export type QueryMyDocsArgs = { first?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['String']>; }; export type QueryDocArgs = { slug?: Maybe<Scalars['String']>; }; export type QueryFileArgs = { slug?: Maybe<Scalars['String']>; }; export type QueryMyFilesArgs = { first?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['String']>; }; export type QueryFilesPendingRemovalArgs = { page?: Scalars['Int']; perPage?: Scalars['Int']; }; export type QueryAllFilesArgs = { page?: Scalars['Int']; perPage?: Scalars['Int']; }; export type QuerySignupCodesArgs = { first?: Maybe<Scalars['Int']>; after?: Maybe<Scalars['String']>; last?: Maybe<Scalars['Int']>; before?: Maybe<Scalars['String']>; }; export type Mutation = { __typename?: 'Mutation'; /** Create a signup code for new users to use */ createSignupCode?: Maybe<SignupCode>; /** Removes an existing signup code */ removeSignupCode: Scalars['Boolean']; /** Creates a code paste */ createPaste?: Maybe<VirtualFile>; /** Create a markdown document */ createMarkdown?: Maybe<VirtualFile>; /** Marks a document(paste or MD) for removal */ removeDoc: Scalars['Boolean']; /** Permenantly deletes a file that is currently marked for removal */ forceFileDelete: Scalars['Boolean']; /** If a file belonging to the current user has been marked for deletion(IE deleted within the last30 days), this endpoint will undo it. */ undoFileDelete: Scalars['Boolean']; /** Marks a physical file for removal */ removeFile: Scalars['Boolean']; }; export type MutationCreateSignupCodeArgs = { input?: Maybe<CreateSignupCodeInput>; }; export type MutationRemoveSignupCodeArgs = { code?: Maybe<Scalars['String']>; }; export type MutationCreatePasteArgs = { input?: Maybe<CreatePasteInput>; }; export type MutationCreateMarkdownArgs = { input?: Maybe<CreateMarkdownInput>; }; export type MutationRemoveDocArgs = { slug?: Maybe<Scalars['String']>; }; export type MutationForceFileDeleteArgs = { input?: Maybe<UndoFileDeleteInput>; }; export type MutationUndoFileDeleteArgs = { input?: Maybe<UndoFileDeleteInput>; }; export type MutationRemoveFileArgs = { slug?: Maybe<Scalars['String']>; }; export type Subscription = { __typename?: 'Subscription'; notifyCompletedTUSUpload?: Maybe<UploadCompleteEventResult>; }; export enum ApplyPolicy { BeforeResolver = 'BEFORE_RESOLVER', AfterResolver = 'AFTER_RESOLVER' } /** A connection to a list of items. */ export type MyDocsConnection = { __typename?: 'MyDocsConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<MyDocsEdge>>; /** A flattened list of the nodes. */ nodes?: Maybe<Array<Maybe<VirtualFile>>>; }; /** A connection to a list of items. */ export type MyFilesConnection = { __typename?: 'MyFilesConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<MyFilesEdge>>; /** A flattened list of the nodes. */ nodes?: Maybe<Array<Maybe<PhysicalFile>>>; }; /** A connection to a list of items. */ export type SignupCodesConnection = { __typename?: 'SignupCodesConnection'; /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<SignupCodesEdge>>; /** A flattened list of the nodes. */ nodes?: Maybe<Array<Maybe<SignupCode>>>; }; /** Information about pagination in a connection. */ export type PageInfo = { __typename?: 'PageInfo'; /** Indicates whether more edges exist following the set defined by the clients arguments. */ hasNextPage: Scalars['Boolean']; /** Indicates whether more edges exist prior the set defined by the clients arguments. */ hasPreviousPage: Scalars['Boolean']; /** When paginating backwards, the cursor to continue. */ startCursor?: Maybe<Scalars['String']>; /** When paginating forwards, the cursor to continue. */ endCursor?: Maybe<Scalars['String']>; }; /** Represents a virtually stored file(code pastes, markdown docs, etc) */ export type VirtualFile = { __typename?: 'VirtualFile'; /** Slug identifier for this file */ slug?: Maybe<Scalars['String']>; id?: Maybe<Scalars['String']>; /** Title of this file */ name?: Maybe<Scalars['String']>; /** The content(text) of this document */ content?: Maybe<Scalars['String']>; /** If this is a code paste, the language that it was created with. */ language?: Maybe<Scalars['String']>; /** The user responsible for uploading this file */ uploader?: Maybe<AppUser>; /** The type of virtual file(code paste or markdown doc) */ fileKind: VirtualFileKind; /** If this document is a fork, this is the parent documen it was forked from. */ parentFile?: Maybe<VirtualFile>; /** Date and time this file was uploaded */ created: Scalars['DateTime']; /** Whether this file is marked as deleted */ markedForDeletion: Scalars['Boolean']; /** The date and time this file was marked as deleted */ deletedAt: Scalars['DateTime']; deletedBy?: Maybe<AppUser>; deletedFor?: Maybe<Scalars['String']>; /** Frontend preview URL for this file */ previewUrl?: Maybe<Scalars['String']>; }; /** An edge in a connection. */ export type MyDocsEdge = { __typename?: 'MyDocsEdge'; /** A cursor for use in pagination. */ cursor: Scalars['String']; /** The item at the end of the edge. */ node?: Maybe<VirtualFile>; }; /** Represents a physical stored file on S3(audio, video, images, etc) */ export type PhysicalFile = { __typename?: 'PhysicalFile'; /** Slug identifier for this file */ slug?: Maybe<Scalars['String']>; id?: Maybe<Scalars['String']>; /** S3 store ID for this file */ fileId: Scalars['UUID']; /** The name of the original uploaded file */ fileName?: Maybe<Scalars['String']>; /** The mimetype of the original uploaded file */ mimeType?: Maybe<Scalars['String']>; /** The size in bytes of the original uploaded file */ fileLength: Scalars['Long']; /** S3 file URL */ fileUrl?: Maybe<Scalars['String']>; /** The user responsible for uploading this file */ uploader?: Maybe<AppUser>; /** Frontend preview URL for this file */ previewUrl?: Maybe<Scalars['String']>; /** The kind of media this file represents */ fileKind: FileKind; /** Date and time this file was uploaded */ created: Scalars['DateTime']; /** Whether this file is marked as deleted */ markedForDeletion: Scalars['Boolean']; /** The date and time this file was marked as deleted */ deletedAt: Scalars['DateTime']; deletedBy?: Maybe<AppUser>; deletedFor?: Maybe<Scalars['String']>; uploadComplete: Scalars['Boolean']; }; /** An edge in a connection. */ export type MyFilesEdge = { __typename?: 'MyFilesEdge'; /** A cursor for use in pagination. */ cursor: Scalars['String']; /** The item at the end of the edge. */ node?: Maybe<PhysicalFile>; }; export type SignupCode = { __typename?: 'SignupCode'; code?: Maybe<Scalars['String']>; isAdmin: Scalars['Boolean']; creatorUser?: Maybe<AppUser>; creatorId?: Maybe<Scalars['String']>; user?: Maybe<AppUser>; used: Scalars['Boolean']; usedAt: Scalars['DateTime']; created: Scalars['DateTime']; }; /** An edge in a connection. */ export type SignupCodesEdge = { __typename?: 'SignupCodesEdge'; /** A cursor for use in pagination. */ cursor: Scalars['String']; /** The item at the end of the edge. */ node?: Maybe<SignupCode>; }; export type CreateSignupCodeInput = { isAdmin: Scalars['Boolean']; }; export type AppUser = { __typename?: 'AppUser'; id?: Maybe<Scalars['String']>; username?: Maybe<Scalars['String']>; email?: Maybe<Scalars['String']>; isAdmin: Scalars['Boolean']; isOwner: Scalars['Boolean']; maxStorageSize: Scalars['Float']; maxUploadSize: Scalars['Float']; apiKey?: Maybe<Scalars['String']>; /** Additional features provided to this user account */ features?: Maybe<Array<Maybe<AppliedUserFeature>>>; created: Scalars['DateTime']; updated: Scalars['DateTime']; }; export type UserStorageUsageResult = { __typename?: 'UserStorageUsageResult'; /** The total amount of storage space currently in use by this user(in gigabytes) */ gigabytes: Scalars['Float']; /** The total amount of storage space currently in use by this user(in megabytes) */ megabytes: Scalars['Float']; /** The total amount of storage space currently in use by this user(in kilobytes) */ kilobytes: Scalars['Float']; /** The amount of storage space in total available to this user(in gigabytes) */ userMaxSizeInGb: Scalars['Float']; /** The amount of storage space in total available to this user(in mgeabytes) */ userMaxSizeInMb: Scalars['Float']; /** The maximum size of file that can be uploaded by this user(in megabytes) */ userMaxUploadSizeInMb: Scalars['Float']; /** The maximum size of file that can be uploaded by this user(in bytes) */ userMaxUploadSizeInB: Scalars['Float']; userMaxUploadSizeString?: Maybe<Scalars['String']>; userMaxSizeString?: Maybe<Scalars['String']>; }; /** A feature that can be applied to a user account */ export type UserFeature = { __typename?: 'UserFeature'; featureName?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; }; export type AllFilesResult = { __typename?: 'AllFilesResult'; files?: Maybe<Array<Maybe<FileResult>>>; numPages: Scalars['Int']; hasNextPage: Scalars['Boolean']; curPage: Scalars['Int']; }; export type DeletedFile = { __typename?: 'DeletedFile'; id: Scalars['UUID']; fileId: Scalars['UUID']; fileSlug?: Maybe<Scalars['String']>; fileName?: Maybe<Scalars['String']>; uploader?: Maybe<AppUser>; deleter?: Maybe<AppUser>; deletedReason?: Maybe<Scalars['String']>; deletedAt: Scalars['DateTime']; deleteMarkedAt: Scalars['DateTime']; fileType: DeletedFileType; }; export enum VirtualFileKind { CodePaste = 'CODE_PASTE', Markdown = 'MARKDOWN' } export type AuthDirective = { __typename?: 'AuthDirective'; requireAdmin: Scalars['Boolean']; }; export type CreatePasteInput = { /** Optional document name */ name?: Maybe<Scalars['String']>; /** Paste content */ text: Scalars['String']; /** Code language for highlighting */ language: Scalars['String']; /** The slug of the parent paste if this is a fork. */ parentSlug?: Maybe<Scalars['String']>; /** A custom slug, if enabled on this account(between 5 and 75 characters in length). */ customSlug?: Maybe<Scalars['String']>; }; export type CreateMarkdownInput = { /** Optional document name */ name?: Maybe<Scalars['String']>; /** Markdown content */ text: Scalars['String']; /** The slug of the parent document if this is a fork. */ parentSlug?: Maybe<Scalars['String']>; /** A custom slug, if enabled on this account(between 5 and 75 characters in length). */ customSlug?: Maybe<Scalars['String']>; }; export type UndoFileDeleteInput = { /** The slug for the file */ slug?: Maybe<Scalars['String']>; /** The type of file('PHYSICAL' or 'VIRTUAL') */ type: UndoFileDeleteType; }; export type UploadCompleteEventResult = { __typename?: 'UploadCompleteEventResult'; uploadId?: Maybe<Scalars['String']>; file?: Maybe<PhysicalFile>; }; export enum FileKind { Video = 'VIDEO', Audio = 'AUDIO', Text = 'TEXT', Image = 'IMAGE', Paste = 'PASTE', Markdown = 'MARKDOWN', File = 'FILE' } export enum UndoFileDeleteType { Physical = 'PHYSICAL', Virtual = 'VIRTUAL' } export enum DeletedFileType { Physical = 'PHYSICAL', Virtual = 'VIRTUAL' } export type FileResult = { __typename?: 'FileResult'; id?: Maybe<Scalars['String']>; slug?: Maybe<Scalars['String']>; fileType: AllFilesResultType; name?: Maybe<Scalars['String']>; s3Url?: Maybe<Scalars['String']>; previewUrl?: Maybe<Scalars['String']>; virtual?: Maybe<VirtualFile>; physical?: Maybe<PhysicalFile>; physicalKind: FileKind; virtualKind: VirtualFileKind; created: Scalars['DateTime']; }; export type AppliedUserFeature = { __typename?: 'AppliedUserFeature'; id: Scalars['UUID']; feature?: Maybe<UserFeature>; }; export enum AllFilesResultType { Physical = 'PHYSICAL', Virtual = 'VIRTUAL' }
the_stack
import axios from "axios"; import fs from "fs"; import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate"; import { GasPrice, calculateFee, StdFee } from "@cosmjs/stargate"; import { DirectSecp256k1HdWallet, makeCosmoshubPath } from "@cosmjs/proto-signing"; import { Slip10RawIndex } from "@cosmjs/crypto"; import path from "path"; /* * This is a set of helpers meant for use with @cosmjs/cli * With these you can easily use the cw721 contract without worrying about forming messages and parsing queries. * * Usage: npx @cosmjs/cli@^0.26 --init https://raw.githubusercontent.com/CosmWasm/cosmwasm-plus/master/contracts/cw721-base/helpers.ts * * Create a client: * const [addr, client] = await useOptions(pebblenetOptions).setup('password'); * * Get the mnemonic: * await useOptions(pebblenetOptions).recoverMnemonic(password); * * Create contract: * const contract = CW721(client, pebblenetOptions.fees); * * Upload contract: * const codeId = await contract.upload(addr); * * Instantiate contract example: * const initMsg = { * name: "Potato Coin", * symbol: "TATER", * minter: addr * }; * const instance = await contract.instantiate(addr, codeId, initMsg, 'Potato Coin!'); * If you want to use this code inside an app, you will need several imports from https://github.com/CosmWasm/cosmjs */ interface Options { readonly httpUrl: string readonly networkId: string readonly feeToken: string readonly bech32prefix: string readonly hdPath: readonly Slip10RawIndex[] readonly faucetUrl?: string readonly defaultKeyFile: string, readonly fees: { upload: StdFee, init: StdFee, exec: StdFee } } const pebblenetGasPrice = GasPrice.fromString("0.01upebble"); const pebblenetOptions: Options = { httpUrl: 'https://rpc.pebblenet.cosmwasm.com', networkId: 'pebblenet-1', bech32prefix: 'wasm', feeToken: 'upebble', faucetUrl: 'https://faucet.pebblenet.cosmwasm.com/credit', hdPath: makeCosmoshubPath(0), defaultKeyFile: path.join(process.env.HOME, ".pebblenet.key"), fees: { upload: calculateFee(1500000, pebblenetGasPrice), init: calculateFee(500000, pebblenetGasPrice), exec: calculateFee(200000, pebblenetGasPrice), }, } interface Network { setup: (password: string, filename?: string) => Promise<[string, SigningCosmWasmClient]> recoverMnemonic: (password: string, filename?: string) => Promise<string> } const useOptions = (options: Options): Network => { const loadOrCreateWallet = async (options: Options, filename: string, password: string): Promise<DirectSecp256k1HdWallet> => { let encrypted: string; try { encrypted = fs.readFileSync(filename, 'utf8'); } catch (err) { // generate if no file exists const wallet = await DirectSecp256k1HdWallet.generate(12, {hdPaths: [options.hdPath], prefix: options.bech32prefix}); const encrypted = await wallet.serialize(password); fs.writeFileSync(filename, encrypted, 'utf8'); return wallet; } // otherwise, decrypt the file (we cannot put deserialize inside try or it will over-write on a bad password) const wallet = await DirectSecp256k1HdWallet.deserialize(encrypted, password); return wallet; }; const connect = async ( wallet: DirectSecp256k1HdWallet, options: Options ): Promise<SigningCosmWasmClient> => { const clientOptions = { prefix: options.bech32prefix } return await SigningCosmWasmClient.connectWithSigner(options.httpUrl, wallet, clientOptions) }; const hitFaucet = async ( faucetUrl: string, address: string, denom: string ): Promise<void> => { await axios.post(faucetUrl, { denom, address }); } const setup = async (password: string, filename?: string): Promise<[string, SigningCosmWasmClient]> => { const keyfile = filename || options.defaultKeyFile; const wallet = await loadOrCreateWallet(pebblenetOptions, keyfile, password); const client = await connect(wallet, pebblenetOptions); const [account] = await wallet.getAccounts(); // ensure we have some tokens if (options.faucetUrl) { const tokens = await client.getBalance(account.address, options.feeToken) if (tokens.amount === '0') { console.log(`Getting ${options.feeToken} from faucet`); await hitFaucet(options.faucetUrl, account.address, options.feeToken); } } return [account.address, client]; } const recoverMnemonic = async (password: string, filename?: string): Promise<string> => { const keyfile = filename || options.defaultKeyFile; const wallet = await loadOrCreateWallet(pebblenetOptions, keyfile, password); return wallet.mnemonic; } return { setup, recoverMnemonic }; } type TokenId = string interface Balances { readonly address: string readonly amount: string // decimal as string } interface MintInfo { readonly minter: string readonly cap?: string // decimal as string } interface ContractInfo { readonly name: string readonly symbol: string } interface NftInfo { readonly name: string, readonly description: string, readonly image: any } interface Access { readonly owner: string, readonly approvals: [] } interface AllNftInfo { readonly access: Access, readonly info: NftInfo } interface Operators { readonly operators: [] } interface Count { readonly count: number } interface InitMsg { readonly name: string readonly symbol: string readonly minter: string } // Better to use this interface? interface MintMsg { readonly token_id: TokenId readonly owner: string readonly name: string readonly description?: string readonly image?: string } type Expiration = { readonly at_height: number } | { readonly at_time: number } | { readonly never: {} }; interface AllowanceResponse { readonly allowance: string; // integer as string readonly expires: Expiration; } interface AllowanceInfo { readonly allowance: string; // integer as string readonly spender: string; // bech32 address readonly expires: Expiration; } interface AllAllowancesResponse { readonly allowances: readonly AllowanceInfo[]; } interface AllAccountsResponse { // list of bech32 address that have a balance readonly accounts: readonly string[]; } interface TokensResponse { readonly tokens: readonly string[]; } interface CW721Instance { readonly contractAddress: string // queries allowance: (owner: string, spender: string) => Promise<AllowanceResponse> allAllowances: (owner: string, startAfter?: string, limit?: number) => Promise<AllAllowancesResponse> allAccounts: (startAfter?: string, limit?: number) => Promise<readonly string[]> minter: () => Promise<MintInfo> contractInfo: () => Promise<ContractInfo> nftInfo: (tokenId: TokenId) => Promise<NftInfo> allNftInfo: (tokenId: TokenId) => Promise<AllNftInfo> ownerOf: (tokenId: TokenId) => Promise<Access> approvedForAll: (owner: string, include_expired?: boolean, start_after?: string, limit?: number) => Promise<Operators> numTokens: () => Promise<Count> tokens: (owner: string, startAfter?: string, limit?: number) => Promise<TokensResponse> allTokens: (startAfter?: string, limit?: number) => Promise<TokensResponse> // actions mint: (senderAddress: string, tokenId: TokenId, owner: string, name: string, level: number, description?: string, image?: string) => Promise<string> transferNft: (senderAddress: string, recipient: string, tokenId: TokenId) => Promise<string> sendNft: (senderAddress: string, contract: string, token_id: TokenId, msg?: BinaryType) => Promise<string> approve: (senderAddress: string, spender: string, tokenId: TokenId, expires?: Expiration) => Promise<string> approveAll: (senderAddress: string, operator: string, expires?: Expiration) => Promise<string> revoke: (senderAddress: string, spender: string, tokenId: TokenId) => Promise<string> revokeAll: (senderAddress: string, operator: string) => Promise<string> } interface CW721Contract { // upload a code blob and returns a codeId upload: (senderAddress: string) => Promise<number> // instantiates a cw721 contract // codeId must come from a previous deploy // label is the public name of the contract in listing // if you set admin, you can run migrations on this contract (likely client.senderAddress) instantiate: (senderAddress: string, codeId: number, initMsg: Record<string, unknown>, label: string, admin?: string) => Promise<CW721Instance> use: (contractAddress: string) => CW721Instance } export const CW721 = (client: SigningCosmWasmClient, fees: Options['fees']): CW721Contract => { const use = (contractAddress: string): CW721Instance => { const allowance = async (owner: string, spender: string): Promise<AllowanceResponse> => { return client.queryContractSmart(contractAddress, { allowance: { owner, spender } }); }; const allAllowances = async (owner: string, startAfter?: string, limit?: number): Promise<AllAllowancesResponse> => { return client.queryContractSmart(contractAddress, { all_allowances: { owner, start_after: startAfter, limit } }); }; const allAccounts = async (startAfter?: string, limit?: number): Promise<readonly string[]> => { const accounts: AllAccountsResponse = await client.queryContractSmart(contractAddress, { all_accounts: { start_after: startAfter, limit } }); return accounts.accounts; }; const minter = async (): Promise<MintInfo> => { return client.queryContractSmart(contractAddress, { minter: {} }); }; const contractInfo = async (): Promise<ContractInfo> => { return client.queryContractSmart(contractAddress, { contract_info: {} }); }; const nftInfo = async (token_id: TokenId): Promise<NftInfo> => { return client.queryContractSmart(contractAddress, { nft_info: { token_id } }); } const allNftInfo = async (token_id: TokenId): Promise<AllNftInfo> => { return client.queryContractSmart(contractAddress, { all_nft_info: { token_id } }); } const ownerOf = async (token_id: TokenId): Promise<Access> => { return await client.queryContractSmart(contractAddress, { owner_of: { token_id } }); } const approvedForAll = async (owner: string, include_expired?: boolean, start_after?: string, limit?: number): Promise<Operators> => { return await client.queryContractSmart(contractAddress, { approved_for_all: { owner, include_expired, start_after, limit } }) } // total number of tokens issued const numTokens = async (): Promise<Count> => { return client.queryContractSmart(contractAddress, { num_tokens: {} }); } // list all token_ids that belong to a given owner const tokens = async (owner: string, start_after?: string, limit?: number): Promise<TokensResponse> => { return client.queryContractSmart(contractAddress, { tokens: { owner, start_after, limit } }); } const allTokens = async (start_after?: string, limit?: number): Promise<TokensResponse> => { return client.queryContractSmart(contractAddress, { all_tokens: { start_after, limit } }); } // actions const mint = async (senderAddress: string, token_id: TokenId, owner: string, name: string, level: number, description?: string, image?: string): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { mint: { token_id, owner, name, level, description, image } }, fees.exec); return result.transactionHash; } // transfers ownership, returns transactionHash const transferNft = async (senderAddress: string, recipient: string, token_id: TokenId): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { transfer_nft: { recipient, token_id } }, fees.exec); return result.transactionHash; } // sends an nft token to another contract (TODO: msg type any needs to be revisited once receiveNft is implemented) const sendNft = async (senderAddress: string, contract: string, token_id: TokenId, msg?: any): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { send_nft: { contract, token_id, msg } }, fees.exec) return result.transactionHash; } const approve = async (senderAddress: string, spender: string, token_id: TokenId, expires?: Expiration): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { approve: { spender, token_id, expires } }, fees.exec); return result.transactionHash; } const approveAll = async (senderAddress: string, operator: string, expires?: Expiration): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { approve_all: { operator, expires } }, fees.exec) return result.transactionHash } const revoke = async (senderAddress: string, spender: string, token_id: TokenId): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { revoke: { spender, token_id } }, fees.exec); return result.transactionHash; } const revokeAll = async (senderAddress: string, operator: string): Promise<string> => { const result = await client.execute(senderAddress, contractAddress, { revoke_all: { operator } }, fees.exec) return result.transactionHash; } return { contractAddress, allowance, allAllowances, allAccounts, minter, contractInfo, nftInfo, allNftInfo, ownerOf, approvedForAll, numTokens, tokens, allTokens, mint, transferNft, sendNft, approve, approveAll, revoke, revokeAll }; } const downloadWasm = async (url: string): Promise<Uint8Array> => { const r = await axios.get(url, { responseType: 'arraybuffer' }) if (r.status !== 200) { throw new Error(`Download error: ${r.status}`) } return r.data } const upload = async (senderAddress: string): Promise<number> => { const sourceUrl = "https://github.com/CosmWasm/cosmwasm-plus/releases/download/v0.9.0/cw721_base.wasm"; const wasm = await downloadWasm(sourceUrl); const result = await client.upload(senderAddress, wasm, fees.upload); return result.codeId; } const instantiate = async (senderAddress: string, codeId: number, initMsg: Record<string, unknown>, label: string, admin?: string): Promise<CW721Instance> => { const result = await client.instantiate(senderAddress, codeId, initMsg, label, fees.init, { memo: `Init ${label}`, admin }); return use(result.contractAddress); } return { upload, instantiate, use }; }
the_stack
module es { /** * 多边形 */ export class Polygon extends Shape { /** * 组成多边形的点 * 保持顺时针与凸边形 */ public points: Vector2[]; public _areEdgeNormalsDirty = true; /** * 多边形的原始数据 */ public _originalPoints: Vector2[]; public _polygonCenter: Vector2; /** * 用于优化未旋转box碰撞 */ public isBox: boolean; public isUnrotated: boolean = true; /** * 从点构造一个多边形 * 多边形应该以顺时针方式指定 不能重复第一个/最后一个点,它们以0 0为中心 * @param points * @param isBox */ constructor(points: Vector2[], isBox?: boolean) { super(); this.setPoints(points); this.isBox = isBox; } public create(vertCount: number, radius: number) { Polygon.buildSymmetricalPolygon(vertCount, radius); } public _edgeNormals: Vector2[]; /** * 边缘法线用于SAT碰撞检测。缓存它们用于避免squareRoots * box只有两个边缘 因为其他两边是平行的 */ public get edgeNormals() { if (this._areEdgeNormalsDirty) this.buildEdgeNormals(); return this._edgeNormals; } /** * 重置点并重新计算中心和边缘法线 * @param points */ public setPoints(points: Vector2[]) { this.points = points; this.recalculateCenterAndEdgeNormals(); this._originalPoints = []; this.points.forEach(p => { this._originalPoints.push(p.clone()); }); } /** * 重新计算多边形中心 * 如果点数改变必须调用该方法 */ public recalculateCenterAndEdgeNormals() { this._polygonCenter = Polygon.findPolygonCenter(this.points); this._areEdgeNormalsDirty = true; } /** * 建立多边形边缘法线 * 它们仅由edgeNormals getter惰性创建和更新 */ public buildEdgeNormals() { // 对于box 我们只需要两条边,因为另外两条边是平行的 let totalEdges = this.isBox ? 2 : this.points.length; if (this._edgeNormals == undefined || this._edgeNormals.length != totalEdges) this._edgeNormals = new Array(totalEdges); let p2: Vector2; for (let i = 0; i < totalEdges; i++) { let p1 = this.points[i]; if (i + 1 >= this.points.length) p2 = this.points[0]; else p2 = this.points[i + 1]; let perp = Vector2Ext.perpendicular(p1, p2); Vector2Ext.normalize(perp); this._edgeNormals[i] = perp; } } /** * 建立一个对称的多边形(六边形,八角形,n角形)并返回点 * @param vertCount * @param radius */ public static buildSymmetricalPolygon(vertCount: number, radius: number) { const verts = new Array(vertCount); for (let i = 0; i < vertCount; i++) { const a = 2 * Math.PI * (i / vertCount); verts[i] = new Vector2(Math.cos(a) * radius, Math.sin(a) * radius); } return verts; } /** * 重定位多边形的点 * @param points */ public static recenterPolygonVerts(points: Vector2[]) { const center = this.findPolygonCenter(points); for (let i = 0; i < points.length; i++) points[i] = points[i].sub(center); } /** * 找到多边形的中心。注意,这对于正则多边形是准确的。不规则多边形没有中心。 * @param points */ public static findPolygonCenter(points: Vector2[]) { let x = 0, y = 0; for (let i = 0; i < points.length; i++) { x += points[i].x; y += points[i].y; } return new Vector2(x / points.length, y / points.length); } /** * 不知道辅助顶点,所以取每个顶点,如果你知道辅助顶点,执行climbing算法 * @param points * @param direction */ public static getFarthestPointInDirection(points: Vector2[], direction: Vector2): Vector2 { let index = 0; let maxDot = points[index].dot(direction); for (let i = 1; i < points.length; i++) { let dot = points[i].dot(direction); if (dot > maxDot) { maxDot = dot; index = i; } } return points[index]; } /** * 迭代多边形的所有边,并得到任意边上离点最近的点。 * 通过最近点的平方距离和它所在的边的法线返回。 * 点应该在多边形的空间中(点-多边形.位置) * @param points * @param point * @param distanceSquared * @param edgeNormal */ public static getClosestPointOnPolygonToPoint(points: Vector2[], point: Vector2): { distanceSquared: number; edgeNormal: Vector2; closestPoint: Vector2 } { const res = { distanceSquared: Number.MAX_VALUE, edgeNormal: Vector2.zero, closestPoint: Vector2.zero, }; let tempDistanceSquared = 0; for (let i = 0; i < points.length; i++) { let j = i + 1; if (j === points.length) j = 0; const closest = ShapeCollisionsCircle.closestPointOnLine(points[i], points[j], point); tempDistanceSquared = Vector2.sqrDistance(point, closest); if (tempDistanceSquared < res.distanceSquared) { res.distanceSquared = tempDistanceSquared; res.closestPoint = closest; // 求直线的法线 const line = points[j].sub(points[i]); res.edgeNormal.x = line.y; res.edgeNormal.y = -line.x; } } res.edgeNormal = res.edgeNormal.normalize(); return res; } /** * 旋转原始点并复制旋转的值到旋转的点 * @param radians * @param originalPoints * @param rotatedPoints */ public static rotatePolygonVerts(radians: number, originalPoints: Vector2[], rotatedPoints: Vector2[]) { let cos = Math.cos(radians); let sin = Math.sin(radians); for (let i = 0; i < originalPoints.length; i++) { let position = originalPoints[i]; rotatedPoints[i] = new Vector2(position.x * cos + position.y * -sin, position.x * sin + position.y * cos); } } public recalculateBounds(collider: Collider) { // 如果我们没有旋转或不关心TRS我们使用localOffset作为中心,我们会从那开始 this.center = collider.localOffset; if (collider.shouldColliderScaleAndRotateWithTransform) { let hasUnitScale = true; const tempMat: Matrix2D = new Matrix2D(); const combinedMatrix: Matrix2D = new Matrix2D(); Matrix2D.createTranslation( this._polygonCenter.x * -1, this._polygonCenter.y * -1, combinedMatrix ); if (!collider.entity.transform.scale.equals(Vector2.one)) { Matrix2D.createScale( collider.entity.scale.x, collider.entity.scale.y, tempMat ); Matrix2D.multiply(combinedMatrix, tempMat, combinedMatrix); hasUnitScale = false; // 缩放偏移量并将其设置为中心。如果我们有旋转,它会在下面重置 const scaledOffset = new Vector2( collider.localOffset.x * collider.entity.scale.x, collider.localOffset.y * collider.entity.scale.y ); this.center = scaledOffset; } if (collider.entity.transform.rotation != 0) { Matrix2D.createRotation( MathHelper.Deg2Rad * collider.entity.rotation, tempMat ); Matrix2D.multiply(combinedMatrix, tempMat, combinedMatrix); // 为了处理偏移原点的旋转我们只需要将圆心在(0,0)附近移动 // 我们的偏移使角度为0我们还需要处理这里的比例所以我们先对偏移进行缩放以得到合适的长度。 const offsetAngle = Math.atan2(collider.localOffset.y * collider.entity.transform.scale.y, collider.localOffset.x * collider.entity.transform.scale.x) * MathHelper.Rad2Deg; const offsetLength = hasUnitScale ? collider._localOffsetLength : collider.localOffset.multiply(collider.entity.transform.scale).magnitude(); this.center = MathHelper.pointOnCirlce(Vector2.zero, offsetLength, collider.entity.transform.rotationDegrees + offsetAngle); } Matrix2D.createTranslation( this._polygonCenter.x, this._polygonCenter.y, tempMat ); Matrix2D.multiply(combinedMatrix, tempMat, combinedMatrix); // 最后变换原始点 this.points = []; this._originalPoints.forEach(p => { this.points.push(p.transform(combinedMatrix)); }); this.isUnrotated = collider.entity.transform.rotation == 0; // 如果旋转的话,我们只需要重建边的法线 if (collider._isRotationDirty) this._areEdgeNormalsDirty = true; } this.position = collider.transform.position.add(this.center); this.bounds = Rectangle.rectEncompassingPoints(this.points); this.bounds.location = this.bounds.location.add(this.position); } public overlaps(other: Shape) { let result: CollisionResult = new CollisionResult(); if (other instanceof Polygon) return ShapeCollisionsPolygon.polygonToPolygon(this, other, result); if (other instanceof Circle) { if (ShapeCollisionsCircle.circleToPolygon(other, this, result)) { result.invertResult(); return true; } return false; } throw new Error(`overlaps of Pologon to ${other} are not supported`); } public collidesWithShape(other: Shape, result: CollisionResult): boolean { if (other instanceof Polygon) { return ShapeCollisionsPolygon.polygonToPolygon(this, other, result); } if (other instanceof Circle) { if (ShapeCollisionsCircle.circleToPolygon(other, this, result)) { result.invertResult(); return true; } return false; } throw new Error(`overlaps of Polygon to ${other} are not supported`); } public collidesWithLine(start: es.Vector2, end: es.Vector2, hit: es.RaycastHit): boolean { return ShapeCollisionsLine.lineToPoly(start, end, this, hit); } /** * 本质上,这个算法所做的就是从一个点发射一条射线。 * 如果它与奇数条多边形边相交,我们就知道它在多边形内部。 * @param point */ public containsPoint(point: Vector2) { // 将点归一化到多边形坐标空间中 point = point.sub(this.position); let isInside = false; for (let i = 0, j = this.points.length - 1; i < this.points.length; j = i++) { if (((this.points[i].y > point.y) !== (this.points[j].y > point.y)) && (point.x < (this.points[j].x - this.points[i].x) * (point.y - this.points[i].y) / (this.points[j].y - this.points[i].y) + this.points[i].x)) { isInside = !isInside; } } return isInside; } public pointCollidesWithShape(point: Vector2, result: CollisionResult): boolean { return ShapeCollisionsPoint.pointToPoly(point, this, result); } } }
the_stack
import { useEffect, useState } from 'react'; import { KeyWithTranslationsModel, LanguageModel } from '@tolgee/core'; import { ComponentDependencies } from './KeyDialog'; import { sleep } from '../tools/sleep'; import { createProvider } from '../tools/createProvider'; export interface ScreenshotInterface { id: number; filename: string; fileUrl: string; createdAt?: string; // is it screenshot or only uploaded image justUploaded: boolean; } type FormTranslations = { [key: string]: string; }; interface TranslationInterface { text?: string; } type DialogProps = { input: string; defaultValue: string; open: boolean; onClose: () => void; dependencies: ComponentDependencies; }; const responseToTranslationData = ( data: Record<string, TranslationInterface> | undefined ): FormTranslations => { const translations: Record<string, string> = {}; if (data) { Object.entries(data).forEach( ([language, translation]) => (translations[language] = translation.text) ); } return translations; }; type State = | { type: 'ON_INPUT_CHANGE'; payload: { key: string; value: string } } | { type: 'ON_SELECTED_LANGUAGES_CHANGE'; payload: { languages: Set<string> }; } | { type: 'LOAD_TRANSLATIONS'; payload: { reinitialize?: boolean; languages: Set<string> }; } | { type: 'HANDLE_UPLOAD_IMAGES'; payload: { files: File[] } } | { type: 'HANDLE_TAKE_SCREENSHOT' } | { type: 'HANDLE_REMOVE_SCREENSHOT'; payload: { id: number } } | { type: 'ON_SAVE' } | { type: 'ON_CLOSE' } | { type: 'SET_USE_BROWSER_WINDOW'; payload: boolean } | { type: 'SET_CONTAINER'; payload: Element }; export const [DialogProvider, useDialogDispatch, useDialogContext] = createProvider((props: DialogProps) => { const [loading, setLoading] = useState<boolean>(true); const [saving, setSaving] = useState<boolean>(false); const [success, setSuccess] = useState<boolean>(false); const [error, setError] = useState<string>(null); const [takingScreenshot, setTakingScreenshot] = useState<boolean>(false); const [translations, setTranslations] = useState<KeyWithTranslationsModel>(null); const [translationsForm, setTranslationsForm] = useState<FormTranslations>(null); const [translationsFormTouched, setTranslationsFormTouched] = useState(false); const coreService = props.dependencies.coreService; const properties = props.dependencies.properties; const linkToPlatform = properties.projectId !== undefined ? `${properties.config.apiUrl}/projects/${properties.projectId}/translations/single?key=${props.input}` : undefined; const translationService = props.dependencies.translationService; const screenshotService = props.dependencies.screenshotService; const [container, setContainer] = useState( undefined as Element | undefined ); const [useBrowserWindow, setUseBrowserWindow] = useState(false); const [screenshots, setScreenshots] = useState<ScreenshotInterface[]>([]); const [screenshotsUploading, setScreenshotsUploading] = useState(false); const dispatch = async (action: State) => { switch (action.type) { case 'ON_INPUT_CHANGE': setSuccess(false); setTranslationsFormTouched(true); setTranslationsForm({ ...translationsForm, [action.payload.key]: action.payload.value, }); break; case 'LOAD_TRANSLATIONS': { const { reinitialize = true, languages } = action.payload; translationService .getTranslationsOfKey(props.input, languages) .then(([result, languages]) => { setTranslations( result || { keyId: undefined, translations: {}, screenshots: [], keyName: props.input, keyTags: [], screenshotCount: 0, } ); if (!selectedLanguages?.size) { setSelectedLanguages(new Set(languages)); } const translationsData = responseToTranslationData( result?.translations ); if (!translationsForm || reinitialize) { // reset form setTranslationsForm(translationsData); setScreenshots( result?.screenshots?.map((sc) => ({ ...sc, justUploaded: false, })) || [] ); } else { // update form const result: FormTranslations = {}; languages.forEach((lng) => { result[lng] = translationsForm[lng] || translationsData[lng]; }); setTranslationsForm(result); } setLoading(false); }); break; } case 'HANDLE_UPLOAD_IMAGES': setScreenshotsUploading(true); await Promise.all(action.payload.files.map(uploadImage)); setScreenshotsUploading(false); break; case 'HANDLE_TAKE_SCREENSHOT': { setTakingScreenshot(true); const data = await props.dependencies.pluginManager.takeScreenshot({ key: props.input, translations: translationsForm, }); setTakingScreenshot(false); setScreenshotsUploading(true); const blob = await fetch(data).then((r) => r.blob()); await uploadImage(blob); setScreenshotsUploading(false); break; } case 'HANDLE_REMOVE_SCREENSHOT': { const { id } = action.payload; const screenshot = screenshots.find((sc) => sc.id === id); if (screenshot.justUploaded) { screenshotService.deleteImages([screenshot.id]); } setScreenshots(screenshots.filter((sc) => sc.id !== id)); break; } case 'ON_SAVE': { setSaving(true); try { if (translations.keyId === undefined) { await translationService.createKey({ name: props.input, translations: translationsForm, screenshotUploadedImageIds: screenshots.map((sc) => sc.id), }); } else { await translationService.updateKeyComplex(translations.keyId, { name: props.input, translations: translationsForm, screenshotIdsToDelete: getRemovedScreenshots(), screenshotUploadedImageIds: getJustUploadedScreenshots(), }); } setSuccess(true); await sleep(200); setError(null); props.onClose(); } catch (e) { setError('Unexpected error occurred :('); // eslint-disable-next-line no-console console.error(e); } finally { setSaving(false); } break; } case 'ON_CLOSE': { props.onClose(); setUseBrowserWindow(false); const uploadedScreenshots = getJustUploadedScreenshots(); if (uploadedScreenshots.length) { screenshotService.deleteImages(uploadedScreenshots); } setScreenshots([]); break; } case 'ON_SELECTED_LANGUAGES_CHANGE': { const { languages } = action.payload; if (languages.size) { setSelectedLanguages(languages); properties.preferredLanguages = languages; dispatch({ type: 'LOAD_TRANSLATIONS', payload: { languages, reinitialize: false }, }); } break; } case 'SET_CONTAINER': setContainer(action.payload); break; case 'SET_USE_BROWSER_WINDOW': setUseBrowserWindow(action.payload); break; } }; useEffect(() => { const onKeyDown = (e) => { if (e.key === 'Escape') { dispatch({ type: 'ON_CLOSE' }); } }; if (!useBrowserWindow) { window.addEventListener('keydown', onKeyDown); return () => { window.removeEventListener('keydown', onKeyDown); }; } }, [useBrowserWindow]); useEffect(() => { if (props.open) { setLoading(true); setSuccess(false); setError(null); setTranslationsFormTouched(false); dispatch({ type: 'LOAD_TRANSLATIONS', payload: { languages: properties.preferredLanguages }, }); if (availableLanguages === undefined) { coreService.getLanguagesFull().then((l) => { setAvailableLanguages(l); }); } } }, [props.open, useBrowserWindow, props.input]); const getJustUploadedScreenshots = () => { return screenshots.filter((sc) => sc.justUploaded).map((sc) => sc.id); }; const getRemovedScreenshots = () => { return translations.screenshots ?.map((sc) => sc.id) .filter((scId) => !screenshots.find((sc) => sc.id === scId)); }; const uploadImage = async (file: Blob) => { await screenshotService .uploadImage(file) .then((data) => setScreenshots((screenshots) => [ ...screenshots, { ...data, justUploaded: true }, ]) ) .catch((e) => { setError(e.code || e.message); }); }; const formDisabled = loading || (translations.keyId ? !coreService.isAuthorizedTo('translations.edit') : !coreService.isAuthorizedTo('keys.edit')); const [availableLanguages, setAvailableLanguages] = useState<LanguageModel[]>(undefined); const [selectedLanguages, setSelectedLanguages] = useState( properties.preferredLanguages || new Set([properties.currentLanguage]) ); // sets the default value for base language if is not stored already useEffect(() => { if ( props.defaultValue && availableLanguages && selectedLanguages && translationsForm ) { const baseLanguageDefinition = availableLanguages.find((l) => l.base); if ( baseLanguageDefinition && selectedLanguages.has(baseLanguageDefinition.tag) && !translationsFormTouched ) { const wasBaseTranslationProvided = translations.translations[baseLanguageDefinition.tag] !== undefined; if ( !translationsForm[baseLanguageDefinition.tag] && !wasBaseTranslationProvided ) { setTranslationsForm({ ...translationsForm, [baseLanguageDefinition.tag]: props.defaultValue, }); } } } }, [ availableLanguages, translationsForm, selectedLanguages, props.defaultValue, ]); const contextValue = { input: props.input, dependencies: props.dependencies, open: props.open, loading, saving, success, error, availableLanguages, selectedLanguages, formDisabled, translations, translationsForm, container, useBrowserWindow, pluginAvailable: props.dependencies.pluginManager.handshakeSucceed, takingScreenshot, screenshotsUploading, screenshots, linkToPlatform, }; return [contextValue, dispatch]; });
the_stack
import {Field, Form as FormikForm, Formik, FormikBag, FormikErrors, FormikProps, withFormik} from "formik"; import * as React from "react"; import { AccordionTitleProps, CheckboxProps, Form, Button, Divider, Icon, Label, Accordion, FormProps } from "semantic-ui-react"; import * as Yup from "yup"; import {DEPProfile, SkipSetupSteps} from "../../store/dep/types"; import {FormikCheckbox} from "../formik/FormikCheckbox"; // The major difference between the form values and the server-side model is that the skip values are boolean inverted // so that we can use the language "show" instead of hidden / unhide. export interface IDEPProfileFormValues { // show: not present on DEPProfile show: { [SkipSetupSteps: string]: boolean }; readonly id?: string; readonly uuid?: string; dep_account_id?: number; profile_name: string; url?: string; allow_pairing: boolean; is_supervised: boolean; is_multi_user: boolean; is_mandatory: boolean; await_device_configured: boolean; is_mdm_removable: boolean; support_phone_number: string; auto_advance_setup: boolean; support_email_address?: string; org_magic?: string; // inverted by the form // skip_setup_items: SkipSetupSteps[]; department?: string; } export interface IDEPProfileFormProps { data?: IDEPProfileFormValues; id?: string | number; loading: boolean; activeIndex: number; onSubmit: (values: IDEPProfileFormValues) => void; onClickAccordionTitle: (event: React.MouseEvent<any>, data: AccordionTitleProps) => void; } export interface IDEPProfileFormState { activeIndex: number; } export enum DEPProfilePairWithOptions { AnyComputer = "AnyComputer", Certificates = "Certificates", } const initialValues: IDEPProfileFormValues = { allow_pairing: true, auto_advance_setup: false, await_device_configured: false, department: "", is_mandatory: false, is_mdm_removable: true, is_multi_user: false, is_supervised: true, org_magic: "", profile_name: "", show: { [SkipSetupSteps.AppleID]: true, [SkipSetupSteps.Biometric]: true, [SkipSetupSteps.Diagnostics]: true, [SkipSetupSteps.DisplayTone]: true, [SkipSetupSteps.Location]: true, [SkipSetupSteps.Passcode]: true, [SkipSetupSteps.Payment]: true, [SkipSetupSteps.Privacy]: true, [SkipSetupSteps.Restore]: true, [SkipSetupSteps.SIMSetup]: true, [SkipSetupSteps.Siri]: true, [SkipSetupSteps.TOS]: true, [SkipSetupSteps.Zoom]: true, [SkipSetupSteps.Android]: true, [SkipSetupSteps.HomeButtonSensitivity]: true, [SkipSetupSteps.iMessageAndFaceTime]: true, [SkipSetupSteps.OnBoarding]: true, [SkipSetupSteps.ScreenTime]: true, [SkipSetupSteps.SoftwareUpdate]: true, [SkipSetupSteps.WatchMigration]: true, [SkipSetupSteps.Appearance]: true, [SkipSetupSteps.FileVault]: true, [SkipSetupSteps.iCloudDiagnostics]: true, [SkipSetupSteps.iCloudStorage]: true, [SkipSetupSteps.Registration]: true, [SkipSetupSteps.ScreenSaver]: true, [SkipSetupSteps.TapToSetup]: true, [SkipSetupSteps.TVHomeScreenSync]: true, [SkipSetupSteps.TVProviderSignIn]: true, [SkipSetupSteps.TVRoom]: true, }, support_email_address: "", support_phone_number: "", }; export interface IInnerFormProps { activeIndex: number | string; id?: number | string; onClickAccordionTitle: (event: React.MouseEvent<any>, data: AccordionTitleProps) => void; } const InnerForm = (props: IInnerFormProps & FormikProps<IDEPProfileFormValues>) => { const { touched, errors, isSubmitting, activeIndex, handleChange, handleBlur, values, id, handleSubmit, onClickAccordionTitle } = props; return ( <Form onSubmit={handleSubmit}> <Accordion fluid styled> <Accordion.Title active={activeIndex === 0} index={0} onClick={onClickAccordionTitle}> <Icon name="dropdown"/> General </Accordion.Title> <Accordion.Content active={activeIndex === 0}> <Form.Field required> <label>Profile Name</label> <input type="text" name="profile_name" onChange={handleChange} onBlur={handleBlur} value={values.profile_name}/> {errors.profile_name && touched.profile_name && <Label pointing>{errors.profile_name}</Label>} </Form.Field> <Form.Field> <label>Support Phone Number</label> <input type="tel" name="support_phone_number" onChange={handleChange} onBlur={handleBlur} value={values.support_phone_number}/> {errors.support_phone_number && touched.support_phone_number && errors.support_phone_number} </Form.Field> <Form.Field> <label>Support E-mail Address</label> <input type="email" name="support_email_address" onChange={handleChange} onBlur={handleBlur} value={values.support_email_address}/> {errors.support_email_address && touched.support_email_address && errors.support_email_address} </Form.Field> <Form.Field> <label>Department</label> <input type="text" name="department" onChange={handleChange} onBlur={handleBlur} value={values.department}/> {errors.department && touched.department && errors.department} </Form.Field> <FormikCheckbox toggle name="allow_pairing" label="Allow Pairing"/> <FormikCheckbox toggle name="is_supervised" label="Supervised (will be required in a future version of iOS)" defaultChecked/> <FormikCheckbox toggle name="is_multi_user" label="Shared iPad" /> <FormikCheckbox toggle name="is_mandatory" label="Mandatory. User cannot skip Remote Management" /> <FormikCheckbox toggle name="await_device_configured" label="Await Configured" /> <FormikCheckbox toggle name="is_mdm_removable" label="MDM Payload Removable" /> <FormikCheckbox toggle name="auto_advance_setup" label="Auto Advance (tvOS)" /> </Accordion.Content> <Accordion.Title active={activeIndex === 1} index={1} onClick={onClickAccordionTitle}> <Icon name="dropdown"/> Setup Assistant Steps (Common) </Accordion.Title> <Accordion.Content active={activeIndex === 1}> <FormikCheckbox toggle name={`show.${SkipSetupSteps.AppleID}`} label="Show Apple ID Setup" value={SkipSetupSteps.AppleID}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Biometric}`} label="Show Touch ID" value={SkipSetupSteps.Biometric}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Diagnostics}`} label="Show Diagnostics" value={SkipSetupSteps.Diagnostics}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.DisplayTone}`} label="Show DisplayTone" value={SkipSetupSteps.DisplayTone}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Location}`} label="Show Location Services" value={SkipSetupSteps.Location}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Passcode}`} label="Show Passcode Setup" value={SkipSetupSteps.Passcode}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Payment}`} label="Show Apple Pay" value={SkipSetupSteps.Payment}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Privacy}`} label="Show Privacy" value={SkipSetupSteps.Privacy}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Restore}`} label="Show Restore from Backup" value={SkipSetupSteps.Restore}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.SIMSetup}`} label="Show Add Cellular Plan" value={SkipSetupSteps.SIMSetup}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Siri}`} label="Show Siri" value={SkipSetupSteps.Siri}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.TOS}`} label="Show Terms and Conditions" value={SkipSetupSteps.TOS}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Zoom}`} label="Show Zoom" value={SkipSetupSteps.Zoom}/> </Accordion.Content> <Accordion.Title active={activeIndex === 2} index={2} onClick={onClickAccordionTitle}> <Icon name="dropdown" /> Setup Assistant Steps (iOS) </Accordion.Title> <Accordion.Content active={activeIndex === 2}> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Android}`} label="Show Restore from Android" value={SkipSetupSteps.Android} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.HomeButtonSensitivity}`} label="Show Home Button Sensitivity" value={SkipSetupSteps.HomeButtonSensitivity} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.iMessageAndFaceTime}`} label="Show iMessage and FaceTime" value={SkipSetupSteps.iMessageAndFaceTime} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.OnBoarding}`} label="Show On-Boarding" value={SkipSetupSteps.OnBoarding}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.ScreenTime}`} label="Show Screen Time" value={SkipSetupSteps.ScreenTime}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.SoftwareUpdate}`} label="Show Mandatory Software Update Screen" value={SkipSetupSteps.SoftwareUpdate}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.WatchMigration}`} label="Show Watch Migration" value={SkipSetupSteps.WatchMigration} /> </Accordion.Content> <Accordion.Title active={activeIndex === 3} index={3} onClick={onClickAccordionTitle}> <Icon name="dropdown" /> Setup Assistant Steps (macOS) </Accordion.Title> <Accordion.Content active={activeIndex === 3}> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Appearance}`} label="Show Choose your Look" value={SkipSetupSteps.Appearance} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.FileVault}`} label="Show FileVault on macOS" value={SkipSetupSteps.FileVault} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.iCloudDiagnostics}`} label="Show iCloud Analytics" value={SkipSetupSteps.iCloudDiagnostics} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.iCloudStorage}`} label="Show iCloud Desktop and Documents" value={SkipSetupSteps.iCloudStorage} /> <FormikCheckbox toggle name={`show.${SkipSetupSteps.Registration}`} label="Show Registration" value={SkipSetupSteps.Registration} /> </Accordion.Content> <Accordion.Title active={activeIndex === 4} index={4} onClick={onClickAccordionTitle}> <Icon name="dropdown" /> Setup Assistant Steps (tvOS) </Accordion.Title> <Accordion.Content active={activeIndex === 4}> <FormikCheckbox toggle name={`show.${SkipSetupSteps.ScreenSaver}`} label="Show Screen about using Aerial Screensavers in ATV" value={SkipSetupSteps.ScreenSaver}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.TapToSetup}`} label="Show Tap to Set Up option in ATV" value={SkipSetupSteps.TapToSetup}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.TVHomeScreenSync}`} label="Show home screen layout sync" value={SkipSetupSteps.TVHomeScreenSync}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.TVProviderSignIn}`} label="Show TV provider sign in" value={SkipSetupSteps.TVProviderSignIn}/> <FormikCheckbox toggle name={`show.${SkipSetupSteps.TVRoom}`} label='Show "Where is this Apple TV?" screen' value={SkipSetupSteps.TVRoom}/> </Accordion.Content> </Accordion> <Divider hidden/> <Button type="submit" disabled={isSubmitting} primary> {id ? "Update" : "Create"} </Button> </Form> ); }; export const DEPProfileForm = withFormik<IDEPProfileFormProps, IDEPProfileFormValues>({ mapPropsToValues: (props) => { return props.data || initialValues; }, validationSchema: Yup.object().shape({ profile_name: Yup.string().required("Required"), }), handleSubmit: (values, formikBag: FormikBag<IDEPProfileFormProps, IDEPProfileFormValues>) => { formikBag.props.onSubmit(values); formikBag.setSubmitting(false); }, enableReinitialize: true, displayName: 'DEPProfileForm', })(InnerForm);
the_stack
import { ReactElement } from 'react'; import { ComponentMetadata, NpmInfo, NodeData, NodeSchema, ComponentAction, TitleContent, TransformedComponentMetadata, NestingFilter, isTitleConfig, I18nData, LiveTextEditingConfig, FieldConfig, } from '@alilc/lowcode-types'; import { deprecate } from '@alilc/lowcode-utils'; import { computed, engineConfig } from '@alilc/lowcode-editor-core'; import EventEmitter from 'events'; import { componentDefaults, legacyIssues } from './transducers'; import { isNode, Node, ParentalNode } from './document'; import { Designer } from './designer'; import { intlNode } from './locale'; import { IconLock, IconUnlock, IconContainer, IconPage, IconComponent, IconRemove, IconClone, IconHidden, } from './icons'; function ensureAList(list?: string | string[]): string[] | null { if (!list) { return null; } if (!Array.isArray(list)) { if (typeof list !== 'string') { return null; } list = list.split(/ *[ ,|] */).filter(Boolean); } if (list.length < 1) { return null; } return list; } function isRegExp(obj: any): obj is RegExp { return obj && obj.test && obj.exec && obj.compile; } function buildFilter(rule?: string | string[] | RegExp | NestingFilter) { if (!rule) { return null; } if (typeof rule === 'function') { return rule; } if (isRegExp(rule)) { return (testNode: Node | NodeSchema) => rule.test(testNode.componentName); } const list = ensureAList(rule); if (!list) { return null; } return (testNode: Node | NodeSchema) => list.includes(testNode.componentName); } export class ComponentMeta { readonly isComponentMeta = true; private _npm?: NpmInfo; private emitter: EventEmitter = new EventEmitter(); get npm() { return this._npm; } set npm(_npm: any) { this.setNpm(_npm); } private _componentName?: string; get componentName(): string { return this._componentName!; } private _isContainer?: boolean; get isContainer(): boolean { return this._isContainer! || this.isRootComponent(); } get isMinimalRenderUnit(): boolean { return this._isMinimalRenderUnit || false; } private _isModal?: boolean; get isModal(): boolean { return this._isModal!; } private _descriptor?: string; get descriptor(): string | undefined { return this._descriptor; } private _rootSelector?: string; get rootSelector(): string | undefined { return this._rootSelector; } private _transformedMetadata?: TransformedComponentMetadata; get configure() { const config = this._transformedMetadata?.configure; return config?.combined || config?.props || []; } private _liveTextEditing?: LiveTextEditingConfig[]; get liveTextEditing() { return this._liveTextEditing; } private _isTopFixed?: boolean; get isTopFixed() { return this._isTopFixed; } private parentWhitelist?: NestingFilter | null; private childWhitelist?: NestingFilter | null; private _title?: TitleContent; private _isMinimalRenderUnit?: boolean; get title(): string | I18nData | ReactElement { // TODO: 标记下。这块需要康师傅加一下API,页面正常渲染。 // string | i18nData | ReactElement // TitleConfig title.label if (isTitleConfig(this._title)) { return (this._title.label as any) || this.componentName; } return this._title || this.componentName; } @computed get icon() { // give Slot default icon // if _title is TitleConfig get _title.icon return ( this._transformedMetadata?.icon || // eslint-disable-next-line (this.componentName === 'Page' ? IconPage : this.isContainer ? IconContainer : IconComponent) ); } private _acceptable?: boolean; get acceptable(): boolean { return this._acceptable!; } constructor(readonly designer: Designer, metadata: ComponentMetadata) { this.parseMetadata(metadata); } setNpm(info: NpmInfo) { if (!this._npm) { this._npm = info; } } private parseMetadata(metadata: ComponentMetadata) { const { componentName, npm } = metadata; this._npm = npm || this._npm; this._componentName = componentName; // 额外转换逻辑 this._transformedMetadata = this.transformMetadata(metadata); const { title } = this._transformedMetadata; if (title) { this._title = typeof title === 'string' ? { type: 'i18n', 'en-US': this.componentName, 'zh-CN': title, } : title; } const liveTextEditing = this._transformedMetadata.configure.advanced?.liveTextEditing || []; function collectLiveTextEditing(items: FieldConfig[]) { items.forEach((config) => { if (config?.items) { collectLiveTextEditing(config.items); } else { const liveConfig = config.liveTextEditing || config.extraProps?.liveTextEditing; if (liveConfig) { liveTextEditing.push({ propTarget: String(config.name), ...liveConfig, }); } } }); } collectLiveTextEditing(this.configure); this._liveTextEditing = liveTextEditing.length > 0 ? liveTextEditing : undefined; const isTopFiexd = this._transformedMetadata.configure.advanced?.isTopFixed; if (isTopFiexd) { this._isTopFixed = isTopFiexd; } const { configure = {} } = this._transformedMetadata; this._acceptable = false; const { component } = configure; if (component) { this._isContainer = !!component.isContainer; this._isModal = !!component.isModal; this._descriptor = component.descriptor; this._rootSelector = component.rootSelector; this._isMinimalRenderUnit = component.isMinimalRenderUnit; if (component.nestingRule) { const { parentWhitelist, childWhitelist } = component.nestingRule; this.parentWhitelist = buildFilter(parentWhitelist); this.childWhitelist = buildFilter(childWhitelist); } } else { this._isContainer = false; this._isModal = false; } this.emitter.emit('metadata_change'); } refreshMetadata() { this.parseMetadata(this.getMetadata()); } private transformMetadata(metadta: ComponentMetadata): TransformedComponentMetadata { const result = getRegisteredMetadataTransducers().reduce((prevMetadata, current) => { return current(prevMetadata); }, preprocessMetadata(metadta)); if (!result.configure) { result.configure = {}; } if (result.experimental && !result.configure.advanced) { deprecate(result.experimental, '.experimental', '.configure.advanced'); result.configure.advanced = result.experimental; } return result as any; } isRootComponent(includeBlock = true) { return ( this.componentName === 'Page' || this.componentName === 'Component' || (includeBlock && this.componentName === 'Block') ); } @computed get availableActions() { // eslint-disable-next-line prefer-const let { disableBehaviors, actions } = this._transformedMetadata?.configure.component || {}; const disabled = ensureAList(disableBehaviors) || (this.isRootComponent(false) ? ['copy', 'remove', 'lock', 'unlock'] : null); actions = builtinComponentActions.concat( this.designer.getGlobalComponentActions() || [], actions || [], ); if (disabled) { if (disabled.includes('*')) { return actions.filter((action) => action.condition === 'always'); } return actions.filter((action) => disabled.indexOf(action.name) < 0); } return actions; } setMetadata(metadata: ComponentMetadata) { this.parseMetadata(metadata); } getMetadata(): TransformedComponentMetadata { return this._transformedMetadata!; } checkNestingUp(my: Node | NodeData, parent: ParentalNode) { // 检查父子关系,直接约束型,在画布中拖拽直接掠过目标容器 if (this.parentWhitelist) { return this.parentWhitelist( parent.internalToShellNode(), isNode(my) ? my.internalToShellNode() : my, ); } return true; } checkNestingDown(my: Node, target: Node | NodeSchema | NodeSchema[]) { // 检查父子关系,直接约束型,在画布中拖拽直接掠过目标容器 if (this.childWhitelist) { const _target: any = !Array.isArray(target) ? [target] : target; return _target.every((item: Node | NodeSchema) => { const _item = !isNode(item) ? new Node(my.document, item) : item; return ( this.childWhitelist && this.childWhitelist(_item.internalToShellNode(), my.internalToShellNode()) ); }); } return true; } onMetadataChange(fn: (args: any) => void): () => void { this.emitter.on('metadata_change', fn); return () => { this.emitter.removeListener('metadata_change', fn); }; } // compatiable vision prototype?: any; } export function isComponentMeta(obj: any): obj is ComponentMeta { return obj && obj.isComponentMeta; } function preprocessMetadata(metadata: ComponentMetadata): TransformedComponentMetadata { if (metadata.configure) { if (Array.isArray(metadata.configure)) { return { ...metadata, configure: { props: metadata.configure, }, }; } return metadata as any; } return { ...metadata, configure: {}, }; } export interface MetadataTransducer { (prev: TransformedComponentMetadata): TransformedComponentMetadata; /** * 0 - 9 system * 10 - 99 builtin-plugin * 100 - app & plugin */ level?: number; /** * use to replace TODO */ id?: string; } const metadataTransducers: MetadataTransducer[] = []; export function registerMetadataTransducer( transducer: MetadataTransducer, level = 100, id?: string, ) { transducer.level = level; transducer.id = id; const i = metadataTransducers.findIndex((item) => item.level != null && item.level > level); if (i < 0) { metadataTransducers.push(transducer); } else { metadataTransducers.splice(i, 0, transducer); } } export function getRegisteredMetadataTransducers(): MetadataTransducer[] { return metadataTransducers; } const builtinComponentActions: ComponentAction[] = [ { name: 'remove', content: { icon: IconRemove, title: intlNode('remove'), action(node: Node) { node.remove(); }, }, important: true, }, { name: 'hide', content: { icon: IconHidden, title: intlNode('hide'), action(node: Node) { node.setVisible(false); }, }, condition: (node: Node) => { return node.componentMeta.isModal; }, important: true, }, { name: 'copy', content: { icon: IconClone, title: intlNode('copy'), action(node: Node) { // node.remove(); const { document: doc, parent, index } = node; if (parent) { const newNode = doc.insertNode(parent, node, index + 1, true); newNode.select(); const { isRGL, rglNode } = node.getRGL(); if (isRGL) { // 复制layout信息 let layout = rglNode.getPropValue('layout') || []; let curLayout = layout.filter((item) => item.i === node.getPropValue('fieldId')); if (curLayout && curLayout[0]) { layout.push({ ...curLayout[0], i: newNode.getPropValue('fieldId'), }); rglNode.setPropValue('layout', layout); // 如果是磁贴块复制,则需要滚动到影响位置 setTimeout(() => newNode.document.simulator?.scrollToNode(newNode), 10); } } } }, }, important: true, }, { name: 'lock', content: { icon: IconLock, // 锁定 icon title: intlNode('lock'), action(node: Node) { node.lock(); }, }, condition: (node: Node) => { return engineConfig.get('enableCanvasLock', false) && node.isContainer() && !node.isLocked; }, important: true, }, { name: 'unlock', content: { icon: IconUnlock, // 解锁 icon title: intlNode('unlock'), action(node: Node) { node.lock(false); }, }, condition: (node: Node) => { return engineConfig.get('enableCanvasLock', false) && node.isContainer() && node.isLocked; }, important: true, }, ]; export function removeBuiltinComponentAction(name: string) { const i = builtinComponentActions.findIndex((action) => action.name === name); if (i > -1) { builtinComponentActions.splice(i, 1); } } export function addBuiltinComponentAction(action: ComponentAction) { builtinComponentActions.push(action); } export function modifyBuiltinComponentAction( actionName: string, handle: (action: ComponentAction) => void, ) { const builtinAction = builtinComponentActions.find((action) => action.name === actionName); if (builtinAction) { handle(builtinAction); } } registerMetadataTransducer(legacyIssues, 2, 'legacy-issues'); // should use a high level priority, eg: 2 registerMetadataTransducer(componentDefaults, 100, 'component-defaults');
the_stack
import { TxData, TxDataPayable } from "../../types"; import * as promisify from "tiny-promisify"; import { classUtils } from "../../../utils/class_utils"; import { Web3Utils } from "../../../utils/web3_utils"; import { BigNumber } from "../../../utils/bignumber"; import { DummyToken as ContractArtifacts } from "@dharmaprotocol/contracts"; import * as Web3 from "web3"; import { BaseContract, CONTRACT_WRAPPER_ERRORS } from "./base_contract_wrapper"; export class DummyTokenContract extends BaseContract { public mintingFinished = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<boolean> { const self = this as DummyTokenContract; const result = await promisify<boolean>( self.web3ContractInstance.mintingFinished.call, self.web3ContractInstance, )(); return result; }, }; public name = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as DummyTokenContract; const result = await promisify<string>( self.web3ContractInstance.name.call, self.web3ContractInstance, )(); return result; }, }; public approve = { async sendTransactionAsync( _spender: string, _value: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.approve.estimateGasAsync.bind(self, _spender, _value), ); const txHash = await promisify<string>( self.web3ContractInstance.approve, self.web3ContractInstance, )(_spender, _value, txDataWithDefaults); return txHash; }, async estimateGasAsync( _spender: string, _value: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.approve.estimateGas, self.web3ContractInstance, )(_spender, _value, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( _spender: string, _value: BigNumber, txData: TxData = {}, ): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.approve.getData(); return abiEncodedTransactionData; }, }; public totalSupply = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as DummyTokenContract; const result = await promisify<BigNumber>( self.web3ContractInstance.totalSupply.call, self.web3ContractInstance, )(); return result; }, }; public transferFrom = { async sendTransactionAsync( _from: string, _to: string, _value: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.transferFrom.estimateGasAsync.bind(self, _from, _to, _value), ); const txHash = await promisify<string>( self.web3ContractInstance.transferFrom, self.web3ContractInstance, )(_from, _to, _value, txDataWithDefaults); return txHash; }, async estimateGasAsync( _from: string, _to: string, _value: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.transferFromAsync.estimateGas, self.web3ContractInstance, )(_from, _to, _value, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( _from: string, _to: string, _value: BigNumber, txData: TxData = {}, ): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.transferFromAsync.getData(); return abiEncodedTransactionData; }, }; public decimals = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as DummyTokenContract; const result = await promisify<BigNumber>( self.web3ContractInstance.decimals.call, self.web3ContractInstance, )(); return result; }, }; public mint = { async sendTransactionAsync( _to: string, _amount: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.mint.estimateGasAsync.bind(self, _to, _amount), ); const txHash = await promisify<string>( self.web3ContractInstance.mint, self.web3ContractInstance, )(_to, _amount, txDataWithDefaults); return txHash; }, async estimateGasAsync( _to: string, _amount: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.mint.estimateGas, self.web3ContractInstance, )(_to, _amount, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(_to: string, _amount: BigNumber, txData: TxData = {}): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.mint.getData(); return abiEncodedTransactionData; }, }; public decreaseApproval = { async sendTransactionAsync( _spender: string, _subtractedValue: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.decreaseApproval.estimateGasAsync.bind(self, _spender, _subtractedValue), ); const txHash = await promisify<string>( self.web3ContractInstance.decreaseApproval, self.web3ContractInstance, )(_spender, _subtractedValue, txDataWithDefaults); return txHash; }, async estimateGasAsync( _spender: string, _subtractedValue: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.decreaseApproval.estimateGas, self.web3ContractInstance, )(_spender, _subtractedValue, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( _spender: string, _subtractedValue: BigNumber, txData: TxData = {}, ): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.decreaseApproval.getData(); return abiEncodedTransactionData; }, }; public balanceOf = { async callAsync(_owner: string, defaultBlock?: Web3.BlockParam): Promise<BigNumber> { const self = this as DummyTokenContract; const result = await promisify<BigNumber>( self.web3ContractInstance.balanceOf.call, self.web3ContractInstance, )(_owner); return result; }, }; public finishMinting = { async sendTransactionAsync(txData: TxData = {}): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.finishMinting.estimateGasAsync.bind(self), ); const txHash = await promisify<string>( self.web3ContractInstance.finishMinting, self.web3ContractInstance, )(txDataWithDefaults); return txHash; }, async estimateGasAsync(txData: TxData = {}): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.finishMinting.estimateGas, self.web3ContractInstance, )(txDataWithDefaults); return gas; }, getABIEncodedTransactionData(txData: TxData = {}): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.finishMinting.getData(); return abiEncodedTransactionData; }, }; public owner = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as DummyTokenContract; const result = await promisify<string>( self.web3ContractInstance.owner.call, self.web3ContractInstance, )(); return result; }, }; public symbol = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as DummyTokenContract; const result = await promisify<string>( self.web3ContractInstance.symbol.call, self.web3ContractInstance, )(); return result; }, }; public transfer = { async sendTransactionAsync( _to: string, _value: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.transfer.estimateGasAsync.bind(self, _to, _value), ); const txHash = await promisify<string>( self.web3ContractInstance.transfer, self.web3ContractInstance, )(_to, _value, txDataWithDefaults); return txHash; }, async estimateGasAsync( _to: string, _value: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.transferAsync.estimateGas, self.web3ContractInstance, )(_to, _value, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(_to: string, _value: BigNumber, txData: TxData = {}): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.transferAsync.getData(); return abiEncodedTransactionData; }, }; public increaseApproval = { async sendTransactionAsync( _spender: string, _addedValue: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.increaseApproval.estimateGasAsync.bind(self, _spender, _addedValue), ); const txHash = await promisify<string>( self.web3ContractInstance.increaseApproval, self.web3ContractInstance, )(_spender, _addedValue, txDataWithDefaults); return txHash; }, async estimateGasAsync( _spender: string, _addedValue: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.increaseApproval.estimateGas, self.web3ContractInstance, )(_spender, _addedValue, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( _spender: string, _addedValue: BigNumber, txData: TxData = {}, ): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.increaseApproval.getData(); return abiEncodedTransactionData; }, }; public allowance = { async callAsync( _owner: string, _spender: string, defaultBlock?: Web3.BlockParam, ): Promise<BigNumber> { const self = this as DummyTokenContract; const result = await promisify<BigNumber>( self.web3ContractInstance.allowance.call, self.web3ContractInstance, )(_owner, _spender); return result; }, }; public setBalance = { async sendTransactionAsync( _target: string, _value: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.setBalance.estimateGasAsync.bind(self, _target, _value), ); const txHash = await promisify<string>( self.web3ContractInstance.setBalance, self.web3ContractInstance, )(_target, _value, txDataWithDefaults); return txHash; }, async estimateGasAsync( _target: string, _value: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.setBalance.estimateGas, self.web3ContractInstance, )(_target, _value, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( _target: string, _value: BigNumber, txData: TxData = {}, ): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.setBalance.getData(); return abiEncodedTransactionData; }, }; public transferOwnership = { async sendTransactionAsync(newOwner: string, txData: TxData = {}): Promise<string> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.transferOwnership.estimateGasAsync.bind(self, newOwner), ); const txHash = await promisify<string>( self.web3ContractInstance.transferOwnership, self.web3ContractInstance, )(newOwner, txDataWithDefaults); return txHash; }, async estimateGasAsync(newOwner: string, txData: TxData = {}): Promise<number> { const self = this as DummyTokenContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.transferOwnership.estimateGas, self.web3ContractInstance, )(newOwner, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(newOwner: string, txData: TxData = {}): string { const self = this as DummyTokenContract; const abiEncodedTransactionData = self.web3ContractInstance.transferOwnership.getData(); return abiEncodedTransactionData; }, }; constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { super(web3ContractInstance, defaults); classUtils.bindAll(this, ["web3ContractInstance", "defaults"]); } public static async at( address: string, web3: Web3, defaults: Partial<TxData>, ): Promise<DummyTokenContract> { const web3Utils = new Web3Utils(web3); const { abi }: { abi: any } = ContractArtifacts; const contractExists = await web3Utils.doesContractExistAtAddressAsync(address); const currentNetwork = await web3Utils.getNetworkIdAsync(); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(address); return new DummyTokenContract(web3ContractInstance, defaults); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK("DummyToken", currentNetwork), ); } } } // tslint:disable:max-file-line-count
the_stack
import * as Fs from 'fs-extra'; import * as Path from 'path'; import * as ReadlineSync from 'readline-sync'; import * as semver from 'semver'; import * as Tmp from 'tmp'; import { Git } from './git'; import { Paths } from './paths'; import { Release } from './release'; import { Submodule } from './submodule'; import { Utils } from './utils'; const defaultDumpFileName = 'tutorial.json'; const headEnd = '[//]: # (head-end)\n'; const footStart = '[//]: # (foot-start)\n'; // Dumps tutorial into a JSON file // Output path defaults to cwd function dumpProject(out: any = Utils.cwd(), options: any = {}) { if (out instanceof Object && !(out instanceof String)) { options = out; out = Utils.cwd(); } options = { filter: options.filter, reject: options.reject, ...options}; // Output path is relative to cwd out = Path.resolve(Utils.cwd(), out); // If provided output path is a dir assume the dump file should be created inside of it if (Utils.exists(out, 'dir')) { out = Path.join(out, defaultDumpFileName); } if (Utils.exists(out, 'file')) { options.override = options.override || ReadlineSync.keyInYN([ 'Output path already exists.', 'Would you like to override it and continue?', ].join('\n')); if (!options.override) { return; } } console.log(); console.log(`Dumping into ${out}...`); console.log(); // Ensure submodules are updated // Note that we don't necessarily have to init tortilla, which is useful if we wanna reset // the submodules url before we proceed any further Submodule.list().forEach((submodule) => { Submodule.update(submodule); }); // Will recursively ensure dirs as well Fs.ensureFileSync(out); // Run command once const tags = Git([ 'log', '--tags', '--simplify-by-decoration', '--pretty=format:%ci %d' ]).split('\n') .filter(Boolean) .map((line) => line.match(/^([^(]+) \(.*tag: ([^@]+@\d+\.\d+\.\d+).*\)$/) || line.match(/^([^(]+) \(.*tag: ([^@]+@next).*\)$/) ) .filter(Boolean) .map(([str, date, name]) => ({ date, name, })) .sort((a, b) => new Date(a.date) > new Date(b.date) ? -1 : 1 ) let branchNames = tags .map((tag) => { return tag.name.split('@')[0]; }) .reduce((prev, branchName) => { if (!prev.includes(branchName)) { prev.push(branchName); } return prev; }, []); if (options.filter) { branchNames = branchNames.filter((branchName) => { return options.filter.includes(branchName); }); } if (options.reject) { branchNames = branchNames.filter((branchName) => { return !options.reject.includes(branchName); }); } const pack = Fs.readJsonSync(Paths.npm.package) // TODO: Update test data // Will be defined per branch for compatibility reasons const repoUrl = ( typeof pack.repository === 'string' ? pack.repository : typeof pack.repository === 'object' ? pack.repository.url : '' ).replace(/\.git$/, '') const dump = branchNames.map((branchName) => { const historyBranchName = `${branchName}-history`; // Check if branch exists try { Git(['rev-parse', historyBranchName]); // If not, create it } catch (e) { Git.print(['branch', '--track', historyBranchName, `remotes/origin/${historyBranchName}`]); } // Run command once const releaseTags = tags .filter((tag) => tag.name.match(branchName) ) .map((tag) => ({ date: tag.date, version: tag.name.split('@').pop(), })) const releases = releaseTags.map((releaseTag, releaseIndex) => { const prevReleaseTag = releaseTags[releaseIndex + 1] || {}; const tagName = `${branchName}@${releaseTag.version}`; const tagRevision = Git(['rev-parse', tagName]); const historyRevision = Git([ 'log', historyBranchName, `--grep=^${tagName}:`, '--format=%H', ]).split('\n') .filter(Boolean) .pop(); // Instead of printing diff to stdout we will receive it as a buffer const changesDiff = Release.diff(prevReleaseTag.version, releaseTag.version, null, { branch: branchName, pipe: true }); const manuals = Fs .readdirSync(Paths.manuals.views) // There might also be transformed manuals inside nested dirs. If we will take // these dirs into an account there will be additional unexpected manuals in the // formed dump file .filter(fileName => /\.md$/.test(fileName)) .sort(Utils.naturalSort) .map((manualName, stepIndex) => { const format = '%H %s'; let stepLog; let manualPath; // Step if (stepIndex) { manualPath = Path.resolve(Paths.manuals.views, manualName); stepLog = Git([ 'log', tagRevision, `--grep=^Step ${stepIndex}:`, `--format=${format}`, ]); } else { manualPath = Paths.readme; stepLog = Git([ 'log', Git.rootHash(tagRevision), `--format=${format}`, ]); } manualPath = Path.relative(Utils.cwd(), manualPath); stepLog = stepLog.split(' '); const stepRevision = stepLog.shift(); const manualTitle = stepLog.join(' '); const stepPack = JSON.parse(Git(['show', `${stepRevision}:package.json`])); const keywords = stepPack.keywords || []; // Removing header and footer, since the view should be used externally on a // different host which will make sure to show these two let manualView = Git(['show', `${stepRevision}:${manualPath}`]); if (manualView.includes(headEnd)) { manualView = manualView .split(headEnd) .slice(1) .join(headEnd); } if (manualView.includes(footStart)) { manualView = manualView .split(footStart) .slice(0, -1) .join(footStart); } manualView = manualView.trim(); return { manualTitle, stepRevision, manualView, keywords }; }); return { releaseVersion: releaseTag.version, releaseDate: releaseTag.date, tagName, tagRevision, historyRevision, changesDiff, manuals, }; }); return { repoUrl, branchName, historyBranchName, releases, }; }); Fs.writeJsonSync(out, dump, { spaces: 2 }); console.log(); console.log('Dump finished.'); console.log(); } // TODO: Make client calculate the diff on a service worker // or serve the created HTML file (using SSR) function diffReleases(dump: string|object, srcTag: string, dstTag: string) { let [srcBranchName, srcReleaseVersion] = srcTag.split('@'); let [dstBranchName, dstReleaseVersion] = dstTag.split('@'); if (!srcReleaseVersion && !dstReleaseVersion) { srcReleaseVersion = srcBranchName; dstReleaseVersion = dstBranchName; srcBranchName = null; dstBranchName = null; } if (semverEq(srcReleaseVersion, dstReleaseVersion)) { return ''; } // Test result will be used later on const reversed = semverGt(srcReleaseVersion, dstReleaseVersion) if (reversed) { let temp; temp = srcReleaseVersion; srcReleaseVersion = dstReleaseVersion; dstReleaseVersion = temp; temp = srcBranchName; srcBranchName = dstBranchName; dstBranchName = temp; } // If an FS path was provided if (typeof dump === 'string' || dump instanceof String) { // Resolving path relative to cwd // Note that this is the process cwd and not the project cwd dump = Path.resolve(process.cwd(), dump as string); // Parsing JSON dump = Fs.readJSONSync(dump); } const srcDir = buildRelease(dump, srcReleaseVersion, srcBranchName); const dstDir = buildRelease(dump, dstReleaseVersion, dstBranchName); Fs.removeSync(`${srcDir.name}/.git`); Fs.copySync(`${dstDir.name}/.git`, `${srcDir.name}/.git`); const diff = Utils.scopeEnv(() => { Git(['add', '.']); try { Git(['commit', '-m', dstReleaseVersion]); // No changes were made between releases // Probably due to missing versions of submodules } catch (e) { return ''; } return reversed ? Git(['diff', 'HEAD^', 'HEAD']) : Git(['diff', 'HEAD', 'HEAD^']); }, { TORTILLA_CWD: srcDir.name }); srcDir.removeCallback(); dstDir.removeCallback(); return postTransformDiff(diff); } function buildRelease(dump: any, releaseVersion: string, branchName?: string) { // If no branch was provided, assuming this is a chunk const chunk = branchName ? dump.find(c => c.branchName === branchName) : dump; const releaseIndex = chunk.releases.findIndex(r => r.releaseVersion === releaseVersion); // Most recent release would come LAST const releases = chunk.releases.slice(releaseIndex - chunk.releases.length).reverse(); const diffs = releases.map(r => r.changesDiff).filter(Boolean).map(preTransformDiff); const dir = Tmp.dirSync({ unsafeCleanup: true }); Utils.scopeEnv(() => { Git(['init']); diffs.forEach((diff) => { try { Git(['apply'], { input: diff }); } catch (e) { e.message += ` (version ${releaseVersion})` throw e } }); Git(['add', '.']); Git(['commit', '-m', releaseVersion]); }, { TORTILLA_CWD: dir.name }); return dir; } // TODO: Add tests // Turns binary files into placeholders so diff can be applied function preTransformDiff(diff) { return diff .replace(/Binary files \/dev\/null and b\/([^ ]+) differ/g, [ '--- /dev/null', '+++ b/$1', '@@ -0,0 +1 @@', '+__tortilla_bin__', ].join('\n')) .replace(/Binary files a\/([^ ]+) and \/dev\/null differ/g, [ '--- a/$1', '+++ /dev/null', '@@ -1 +0,0 @@', '-__tortilla_bin__', ].join('\n')) .replace(/Binary files a\/([^ ]+) and b\/([^ ]+) differ/g, [ '--- a/$1', '+++ b/$2', '@@ -1 +1 @@', '-__tortilla_bin__', '+__tortilla_bin__', ].join('\n')) } // Turns placeholders into binary files so diff can be loyal function postTransformDiff(diff) { return diff .replace( /--- \/dev\/null\n\+\+\+ b\/(.+)\n@@ -0,0 \+1 @@\n\+__tortilla_bin__/g, 'Binary files /dev/null and b/$1 differ' ) .replace( /--- a\/(.+)\n\+\+\+ \/dev\/null\n@@ -1 \+0,0 @@\n-__tortilla_bin__/g, 'Binary files a/$1 and /dev/null differ' ) .replace( /--- a\/(.+)\n\+\+\+ b\/(.+)\n@@ -1 \+1 @@\n-__tortilla_bin__\n\+__tortilla_bin__/g, 'Binary files a/$1 and b/$2 differ' ) } // Add vNext to semver.eq() function semverEq(src, dst) { if (src === 'next' && dst === 'next') { return true } if (src === 'next') { return false } if (dst === 'next') { return false } return semver.eq(src, dst) } // Add vNext to semver.gt() function semverGt(src, dst) { if (src === 'next' && dst === 'next') { return false } if (src === 'next') { return true } if (dst === 'next') { return false } return semver.gt(src, dst) } export const Dump = { create: dumpProject, diffReleases };
the_stack
import { BoundingBox, Browser, ElementHandle, launch, Page } from 'puppeteer' import * as path from 'path' import { CollectionViewDelegate, GridLayoutParameters, Size as ImportedSize, CollectionView, GridLayout } from '../dist' jest.setTimeout(10000) let page: Page let browser: Browser const width = 1024 const height = 1024 beforeAll(async () => { if (process.env.CI === 'true') { browser = await launch({ headless: true, slowMo: 200, args: [ `--window-size=${width},${height}`, '--no-sandbox', '--disable-setuid-sandbox' ] }); } else { browser = await launch({ headless: false, slowMo: 300, args: [ `--window-size=${width},${height}`, ] }) } }) afterAll(async () => { await browser.close() }) const collectTraces = false let testIndex = 0 beforeEach(async () => { page = await browser.newPage() await page.setViewport({ width, height }) page.once('pageerror', fail) const envURL = 'file://' + path.resolve(__dirname, 'env', 'index.html') await page.goto(envURL, {"waitUntil" : "networkidle0"}) if (collectTraces) { await page.tracing.start({path: `trace-${testIndex++}.json`}) } }) afterEach(async () => { if (collectTraces) { await page.tracing.stop() } }) // only used to help TypeScript in evaluate calls. see env/src/index.js declare const delegate: CollectionViewDelegate declare const collectionView: CollectionView declare const wrapperElement: HTMLDivElement declare const newGridLayout: (params: GridLayoutParameters) => GridLayout declare const Size: typeof ImportedSize async function getElements(): Promise<ElementHandle[]> { return await page.$$('#scroll div') } async function getBoundingBoxesAndContents(elements: ElementHandle[]): Promise<[BoundingBox, string][]> { const unsorted: [BoundingBox, string][] = await Promise.all(elements.map(element => { return Promise.all([ element.boundingBox() as Promise<BoundingBox>, page.evaluate(element => element.innerText, element) ]) })) return unsorted .sort((a, b) => { const boxA = a[0] const boxB = b[0] if (boxA.y < boxB.y) return -1 if (boxA.y > boxB.y) return 1 if (boxA.x < boxB.x) return -1 if (boxA.x > boxB.x) return 1 return 0 }) } async function expectElements(expected: [number, number, string][], size: [number, number]) { const elements = await getElements() const actualBoundingBoxesAndContents = await getBoundingBoxesAndContents(elements) // console.debug(actualBoundingBoxesAndContents.map(([box, content]) => box && [box.x, box.y, content])) const expectedBoundingBoxesAndContents = expected.map(([x, y, content]): [BoundingBox, string] => [{x, y, width: size[0], height: size[1]}, content]) expect(actualBoundingBoxesAndContents) .toEqual(expectedBoundingBoxesAndContents) } function wait(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); } describe("Collection View with default Grid Layout", () => { test("add elements and scroll", async () => { // add elements await page.evaluate(() => { const items = Array.from(Array(100).keys()) delegate.items = items const addedIndices = items.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // check first set of elements were loaded await expectElements( [ [ 80, 10, '0'], [ 300, 10, '1' ], [ 520, 10 , '2'], [ 80, 230 , '3'], [ 300, 230 , '4'], [ 520, 230 , '5'], [ 80, 450 , '6'], [ 300, 450, '7' ], [ 520, 450, '8' ] ], [200, 200] ) // scroll down a bit await page.evaluate(() => { wrapperElement.scrollBy(0,140) }) // check more elements are loaded await expectElements( [ [ 80, -130, '0'], [ 300, -130, '1' ], [ 520, -130, '2' ], [ 80, 90, '3' ], [ 300, 90, '4' ], [ 520, 90, '5' ], [ 80, 310, '6' ], [ 300, 310, '7' ], [ 520, 310, '8' ], [ 80, 530, '9'], [ 300, 530, '10' ], [ 520, 530, '11' ] ], [200, 200] ) // scroll down a bit more await page.evaluate(() => { wrapperElement.scrollBy(0,200) }) // check more elements are loaded, and elements are reused await expectElements( [ [ 80, -110, '3' ], [ 300, -110, '4' ], [ 520, -110, '5' ], [ 80, 110, '6' ], [ 300, 110, '7' ], [ 520, 110, '8' ], [ 80, 330, '9' ], [ 300, 330, '10' ], [ 520, 330, '11' ], [ 80, 550, '12' ], [ 300, 550, '13' ], [ 520, 550, '14' ], ], [200, 200] ) }); test("change elements", async () => { // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // change elements await page.evaluate(() => { delegate.items = [ 1, 15, 16, 3, 6, 8, 4, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([ 1, 4, 6, 8 ], [ 1, 2 ], new Map([[3, 6]])) }) // check the elements were changed properly await expectElements( [ [ 80, 10, '1' ], [ 300, 10, '15' ], [ 520, 10, '16' ], [ 80, 230, '3' ], [ 300, 230, '6' ], [ 520, 230, '8' ], [ 80, 450, '4' ], [ 300, 450, '10' ], [ 520, 450, '11' ] ], [ 200, 200 ] ) // change the elements back to the initial state await page.evaluate(() => { delegate.items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([1, 2], [1, 4, 6, 8], new Map([[6, 3]])) }) // check the elements were changed properly await expectElements( [ [ 80, 10, '1' ], [ 300, 10, '2' ], [ 520, 10, '3' ], [ 80, 230, '4' ], [ 300, 230, '5' ], [ 520, 230, '6' ], [ 80, 450, '7' ], [ 300, 450, '8' ], [ 520, 450, '9' ] ], [ 200, 200 ] ) }); test("change elements at bottom", async () => { // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // scroll to bottom await page.evaluate(() => { wrapperElement.scrollTo(0, wrapperElement.scrollHeight) }) // change elements await page.evaluate(() => { delegate.items = [ 1, 15, 16, 3, 6, 8, 4, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([ 1, 4, 6, 8 ], [ 1, 2 ], new Map([[3, 6]])) }) // check the elements were changed properly await expectElements( [ [ 80, -70, '3' ], [ 300, -70, '6' ], [ 520, -70, '8' ], [ 80, 150, '4' ], [ 300, 150, '10' ], [ 520, 150, '11' ], [ 80, 370, '12' ], [ 300, 370, '13' ], [ 520, 370, '14' ] ], [ 200, 200 ] ) // change the elements back to the initial state await page.evaluate(() => { delegate.items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([1, 2], [1, 4, 6, 8], new Map([[6, 3]])) }) // check the elements were changed properly await expectElements( [ [ 80, -70, '4' ], [ 300, -70, '5' ], [ 520, -70, '6' ], [ 80, 150, '7' ], [ 300, 150, '8' ], [ 520, 150, '9' ], [ 80, 370, '10' ], [ 300, 370, '11' ], [ 520, 370, '12' ], [ 80, 590, '13' ], [ 300, 590, '14' ] ], [ 200, 200 ] ) }); test("change elements, one interruption", async () => { const animationDuration = await page.evaluate(() => collectionView.animationDuration) // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // change elements // NOTE: not waiting, this promise is checked later const firstUpdate = page.evaluate(() => { delegate.items = [ 1, 15, 16, 3, 6, 8, 4, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([ 1, 4, 6, 8 ], [ 1, 2 ], new Map([[3, 6]])) // recover cancellation as promise resolution which can be checked .catch(() => Promise.resolve('update failed')) }) // wait for half of the first update to complete await wait(animationDuration * 0.5) // change the elements back to the initial state await page.evaluate(() => { delegate.items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([1, 2], [1, 4, 6, 8], new Map([[6, 3]])) }) // check the elements were changed back properly await expectElements( [ [ 80, 10, '1' ], [ 300, 10, '2' ], [ 520, 10, '3' ], [ 80, 230, '4' ], [ 300, 230, '5' ], [ 520, 230, '6' ], [ 80, 450, '7' ], [ 300, 450, '8' ], [ 520, 450, '9' ] ], [ 200, 200 ] ) // the first update should have failed expect(await firstUpdate).toEqual('update failed') }); test("change elements, multiple interruptions", async () => { const animationDuration = await page.evaluate(() => collectionView.animationDuration) // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // change elements; will not complete successfully, // as it will be interrupted by a following change // NOTE: not waiting, this promise is checked later const firstUpdate = page.evaluate(() => { delegate.items = [ 1, 15, 16, 3, 6, 8, 4, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([ 1, 4, 6, 8 ], [ 1, 2 ], new Map([[3, 6]])) // recover cancellation as promise resolution which can be checked .catch(() => Promise.resolve('first update failed')) }) // wait for half of the first update to complete await wait(animationDuration * 0.5) // change the elements back to the initial state; // will not complete successfully either, // as it will also be interrupted by a following change // NOTE: not waiting, this promise is checked later const secondUpdate = page.evaluate(() => { delegate.items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([1, 2], [1, 4, 6, 8], new Map([[6, 3]])) // recover cancellation as promise resolution which can be checked .catch(() => Promise.resolve('second update failed')) }) // wait for half of the second update to complete await wait(animationDuration * 0.5) // change elements again; will complete successfully // NOTE: waiting, this promise should succeed await page.evaluate(() => { delegate.items = [ 1, 15, 16, 3, 6, 8, 4, 10, 11, 12, 13, 14 ] return collectionView.changeIndices([ 1, 4, 6, 8 ], [ 1, 2 ], new Map([ [ 3, 6 ] ])) }); // check the elements were changed properly await expectElements( [ [ 80, 10, '1' ], [ 300, 10, '15' ], [ 520, 10, '16' ], [ 80, 230, '3' ], [ 300, 230, '6' ], [ 520, 230, '8' ], [ 80, 450, '4' ], [ 300, 450, '10' ], [ 520, 450, '11' ] ], [ 200, 200 ] ) // the first update should have failed expect(await firstUpdate).toEqual('first update failed') // the second update should have also failed expect(await secondUpdate).toEqual('second update failed') }); test("update layout", async () => { // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // update layout await page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(300, 300)})) }) // check the elements were changed properly await expectElements( [ [ 90, 10, '1'], [ 410, 10, '2'], [ 90, 330, '3'], [ 410, 330, '4'] ], [ 300, 300 ] ) // update the layout back to the initial state await page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(200, 200)})) }) // check the elements were changed properly await expectElements( [ [ 80, 10, '1' ], [ 300, 10, '2' ], [ 520, 10, '3' ], [ 80, 230, '4' ], [ 300, 230, '5' ], [ 520, 230, '6' ], [ 80, 450, '7' ], [ 300, 450, '8' ], [ 520, 450, '9' ] ], [ 200, 200 ] ) }); test("update layout at bottom", async () => { // update layout await page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(260, 260)})) }) // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // scroll to bottom await page.evaluate(() => { wrapperElement.scrollTo(0, wrapperElement.scrollHeight) }) // update layout await page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(180, 180)})) }) // check the elements were changed properly await expectElements( [ [ 10, -10, '5' ], [ 210, -10, '6' ], [ 410, -10, '7' ], [ 610, -10, '8' ], [ 10, 190, '9' ], [ 210, 190, '10' ], [ 410, 190, '11' ], [ 610, 190, '12' ], [ 10, 390, '13' ], [ 210, 390, '14' ] ], [ 180, 180 ] ) }) test("update layout, one interruption", async () => { const animationDuration = await page.evaluate(() => collectionView.animationDuration) // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // update layout // NOTE: not waiting, this promise is checked later const firstUpdate = page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(300, 300)})) // recover cancellation as promise resolution which can be checked .catch(() => Promise.resolve('update failed')) }) // wait for half of the first update to complete await wait(animationDuration * 0.5) // update the layout back to the initial state await page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(200, 200)})) }) // check the elements were changed properly await expectElements( [ [ 80, 10, '1' ], [ 300, 10, '2' ], [ 520, 10, '3' ], [ 80, 230, '4' ], [ 300, 230, '5' ], [ 520, 230, '6' ], [ 80, 450, '7' ], [ 300, 450, '8' ], [ 520, 450, '9' ] ], [ 200, 200 ] ) // the first update should have failed expect(await firstUpdate).toEqual('update failed') }); test("update layout, multiple interruptions", async () => { const animationDuration = await page.evaluate(() => collectionView.animationDuration) // add initial elements await page.evaluate(() => { const initialElements = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] delegate.items = initialElements.slice() const addedIndices = initialElements.map((_, index) => index) return collectionView.changeIndices([], addedIndices, new Map()) }) // update layout; will not complete successfully, // as it will be interrupted by a following update // NOTE: not waiting, this promise is checked later const firstUpdate = page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(300, 300)})) // recover cancellation as promise resolution which can be checked .catch(() => Promise.resolve('first update failed')) }) await wait(animationDuration * 0.5) // update the layout back to the initial state; // will not complete successfully either, // as it will also be interrupted by a following update // NOTE: not waiting, this promise is checked later const secondUpdate = page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(200, 200)})) // recover cancellation as promise resolution which can be checked .catch(() => Promise.resolve('second update failed')) }) // wait for half of the first update to complete await wait(animationDuration * 0.5) // update layout again; will complete successfully // NOTE: waiting, this promise should succeed await page.evaluate(() => { return collectionView.updateLayout(newGridLayout({itemSize: new Size(300, 300)})) }) // check the elements were changed properly await expectElements( [ [ 90, 10, '1'], [ 410, 10, '2'], [ 90, 330, '3'], [ 410, 330, '4'] ], [ 300, 300 ] ) // the first update should have failed expect(await firstUpdate).toEqual('first update failed') // the second update should have also failed expect(await secondUpdate).toEqual('second update failed') }); })
the_stack
import { } from '@dapplets/dapplet-extension'; import WHITE_ICON from './icons/money-twiter-light.svg'; import DARK_ICON from './icons/money-twiter-dark.svg'; import NEAR_BIG_ICON from './icons/near-big.svg'; import NEAR_SMALL_ICON from './icons/near-small.svg'; import NEAR_LINK_BLACK_ICON from './icons/near-link-black.svg'; import NEAR_LINK_WHITE_ICON from './icons/near-link-white.svg'; import { TippingContractService } from './services/TippingContractService'; import { IdentityService } from './services/IdentityService'; import { debounce } from 'lodash'; import { equals, getMilliseconds, lte, sum } from './helpers'; import { NearNetwork } from './interfaces'; const { parseNearAmount, formatNearAmount } = Core.near.utils.format; @Injectable export default class TwitterFeature { @Inject('twitter-adapter.dapplet-base.eth') public adapter: any; private tippingService: TippingContractService; private identityService: IdentityService; private _stepYocto: string; private _network: NearNetwork; private _debounceDelay: number; private _maxAmountPerItem = '10000000000000000000000000'; // 10 NEAR private _maxAmountPerTip = '1000000000000000000000000'; // 1 NEAR refreshProfileButtonClaim: () => void | null = null; // private _overlay = Core.overlay({ name: 'overlay', title: 'Tipping Near' }).listen({ // getAllUserStat: () => // this.tippingService // .getAllUserStat() // .then((x) => this._overlay.send('getAllUserStat_done', x)) // .catch((e) => this._overlay.send('getAllUserStat_undone', e)), // donateToUser: (_: any, { type, message }: any) => // this.tippingService // .donateToUser(message.nearAccountId, message.donateAmount) // .then(() => this._overlay.send('donateToUser_done')) // .catch((e) => this._overlay.send('donateToUser_undone', e)), // }); // Core.onAction(() => this._overlay.send('')); async activate(): Promise<void> { const step = await Core.storage.get('step'); const delay = await Core.storage.get('delay'); this._network = await Core.storage.get('network'); if (step <= 0) { throw new Error('A donation step must be more than zero. Change the step parameter in the dapplet settings.'); } if (delay <= 0) { throw new Error('A delay must be greater than zero. Change the delay parameter in the dapplet settings.'); } if (!(this._network === 'mainnet' || this._network === 'testnet')) { throw new Error( 'Only "mainnet" and "testnet" networks are supported. Change the network parameter in the dapplet settings.', ); } this._stepYocto = parseNearAmount(step.toString()); this._debounceDelay = getMilliseconds(delay); this.identityService = new IdentityService(this._network); this.tippingService = new TippingContractService(this._network); const { button, avatarBadge } = this.adapter.exports; this.adapter.attachConfig({ PROFILE: () => [ button({ DEFAULT: { hidden: true, img: { DARK: WHITE_ICON, LIGHT: DARK_ICON }, tooltip: 'Claim tokens', init: this.onProfileButtonClaimInit, exec: this.onProfileButtonClaimExec, }, }), button({ DEFAULT: { hidden: true, img: { DARK: NEAR_LINK_WHITE_ICON, LIGHT: NEAR_LINK_BLACK_ICON }, init: this.onProfileButtonLinkInit, exec: this.onProfileButtonLinkExec, }, }), avatarBadge({ DEFAULT: { img: NEAR_BIG_ICON, horizontal: 'right', vertical: 'bottom', hidden: true, init: this.onProfileAvatarBadgeInit, exec: this.onProfileAvatarBadgeExec, }, }), ], POST: () => [ button({ DEFAULT: { img: { DARK: WHITE_ICON, LIGHT: DARK_ICON }, label: 'Tip', tooltip: 'Send donation', amount: '0', donationsAmount: '0', nearAccount: '', debouncedDonate: debounce(this.onDebounceDonate, this._debounceDelay), init: this.onPostButtonInit, exec: this.onPostButtonExec, }, }), avatarBadge({ DEFAULT: { img: NEAR_SMALL_ICON, basic: true, horizontal: 'right', vertical: 'bottom', hidden: true, init: this.onPostAvatarBadgeInit, exec: this.onPostAvatarBadgeExec, }, }), ], }); } onProfileButtonClaimInit = async (profile, me) => { this.refreshProfileButtonClaim = () => this.onProfileButtonClaimInit(profile, me); const username = await this.getCurrentUserAsync(); const isMyProfile = profile.id?.toLowerCase() === username?.toLowerCase(); if (isMyProfile) { const tokens = await this.tippingService.getAvailableTipsByExternalAccount('twitter/' + profile.id); const availableTokens = this.formatNear(tokens); if (Number(availableTokens) !== 0) { me.label = `Claim ${availableTokens} Ⓝ`; me.hidden = false; } else { me.hidden = true; } } else { me.hidden = true; } }; onProfileButtonClaimExec = async (profile, me) => { const nearAccount = await this.identityService.getNearAccount('twitter/' + profile.id); if (!nearAccount) return alert('You must link NEAR account before continue.'); // if (!isParticipant(nearAccount) && this._network === NearNetwork.MAINNET) { // return alert( // 'As part of the closed testing, the withdrawal of tokens is available for ' + // 'the first testers of the dapplet who have sent at least one transaction ' + // 'on the testnet and feedback to Learn NEAR Club before November 25, 2021. ' + // 'We will make it available to everyone soon. Stay tuned!', // ); // } try { me.disabled = true; me.loading = true; me.label = 'Waiting...'; await this.tippingService.claimTokens(); } catch (e) { console.error(e); } finally { me.disabled = false; me.loading = false; this.onProfileButtonClaimInit(profile, me); } }; onProfileButtonLinkInit = async (profile, me) => { const username = await this.getCurrentUserAsync(); const isMyProfile = profile.id.toLowerCase() === username?.toLowerCase(); const parsingNearAccount = this.parseNearId(profile.authorFullname, this._network); if (isMyProfile) { const nearAccount = await this.identityService.getNearAccount('twitter/' + profile.id, true); if (!nearAccount) { me.label = 'Link'; me.tooltip = `Link ${parsingNearAccount ? parsingNearAccount + ' ' : ''}account with NEAR wallet`; } else { me.label = 'Unlink'; me.tooltip = `Unlink ${nearAccount} account from NEAR wallet`; } me.hidden = false; } else { me.hidden = true; } }; onProfileButtonLinkExec = async (profile, me) => { const nearAccount = this.parseNearId(profile.authorFullname, this._network); try { me.disabled = true; me.loading = true; const linkedAccount = await this.identityService.getNearAccount('twitter/' + profile.id); me.label = 'Waiting...'; if (linkedAccount) { // unlink if (nearAccount) { alert('Remove NEAR Account ID from your profile name before continue.'); } else { await this.identityService.requestVerification( `twitter/${profile.id}`, true, 'https://twitter.com/' + profile.id, ); } } else { // link if (!nearAccount) { const exampleWallet = this._network === NearNetwork.TESTNET ? 'yourwallet.testnet' : 'yourwallet.near'; alert( 'Add your NEAR account ID to your profile name in Twitter before continuing. ' + 'This is necessary for Oracle so that it can make sure that you own this Twitter account. ' + 'After linking you can remove it back.\n' + `For example: "${profile.authorFullname} (${exampleWallet})"\n`, ); } else { await this.identityService.requestVerification( `twitter/${profile.id}`, false, 'https://twitter.com/' + profile.id, ); } } } catch (e) { console.error(e); } finally { me.disabled = false; me.loading = false; this.onProfileButtonLinkInit(profile, me); } }; onProfileAvatarBadgeInit = async (ctx, me) => { const nearAccount = await this.identityService.getNearAccount('twitter/' + ctx.id); if (nearAccount) { me.hidden = false; me.tooltip = nearAccount; me.nearAccount = nearAccount; } }; onProfileAvatarBadgeExec = (_, me) => { if (this._network === NearNetwork.TESTNET) { window.open(`https://explorer.testnet.near.org/accounts/${me.nearAccount}`, '_blank'); } else if (this._network === NearNetwork.MAINNET) { window.open(`https://explorer.near.org/accounts/${me.nearAccount}`, '_blank'); } else { throw new Error('Unsupported network'); } }; onPostButtonInit = async (tweet, me) => { if (tweet.id && tweet.authorUsername) { me.hidden = false; me.donationsAmount = await this.tippingService.getTotalDonationByItem('tweet/' + tweet.id); if (equals(me.donationsAmount, '0')) return (me.label = 'Tip'); if (Number(this.formatNear(me.donationsAmount)) === 10) me.disabled = true; me.label = this.formatNear(me.donationsAmount) + ' NEAR'; } else { me.hidden = true; } }; onDebounceDonate = async (me: any, externalAccount: string, tweetId: string, amount: string) => { try { me.loading = true; me.disabled = true; const fee = await this.tippingService.calculateFee(amount); const total = sum(amount, fee); const [domain, account] = externalAccount.split('/'); if ( confirm( `You're tipping ${Core.near.utils.format.formatNearAmount(amount)} Ⓝ to "@${account}" at "${domain}".\n` + `A tiny fee of ${Core.near.utils.format.formatNearAmount(fee)} Ⓝ for project development will be added.\n` + `Thank you for your support!` ) ) { const txHash = await this.tippingService.donateByTweet(externalAccount, 'tweet/' + tweetId, total); const explorerUrl = this._network === 'mainnet' ? 'https://explorer.near.org' : 'https://explorer.testnet.near.org'; alert( `Tipped ${Core.near.utils.format.formatNearAmount(amount)} $NEAR with @tippingdapplet. ` + `Tx link: ${explorerUrl}/transactions/${txHash}` ); } } catch (e) { console.error(e); } finally { me.donationsAmount = await this.tippingService.getTotalDonationByItem('tweet/' + tweetId); me.loading = false; me.disabled = false; me.amount = '0'; me.label = equals(me.donationsAmount, '0') ? 'Tip' : this.formatNear(me.donationsAmount) + ' NEAR'; await this.refreshProfileButtonClaim?.(); } }; onPostButtonExec = async (tweet, me) => { const donationsAmount = Number(this.formatNear(me.donationsAmount)); const donation = Number(this.formatNear(me.amount)); const stepYocto = Number(this.formatNear(this._stepYocto)); const result = Number((donationsAmount + donation + stepYocto).toFixed(2)); if (result > 10) return (me.disabled = true); if ( lte(sum(me.donationsAmount, me.amount, this._stepYocto), this._maxAmountPerItem) && lte(sum(me.amount, this._stepYocto), this._maxAmountPerTip) ) { me.amount = sum(me.amount, this._stepYocto); me.label = this.formatNear(sum(me.donationsAmount, me.amount)) + ' NEAR'; } const externalAccount = 'twitter/' + tweet.authorUsername; await me.debouncedDonate(me, externalAccount, tweet.id, me.amount); }; onPostAvatarBadgeInit = async (ctx, me) => { const nearAccount = await this.identityService.getNearAccount('twitter/' + ctx.authorUsername); if (nearAccount) { me.hidden = false; me.tooltip = nearAccount; me.nearAccount = nearAccount; } }; onPostAvatarBadgeExec = (ctx, me) => { if (this._network === NearNetwork.TESTNET) { window.open(`https://explorer.testnet.near.org/accounts/${me.nearAccount}`, '_blank'); } else if (this._network === NearNetwork.MAINNET) { window.open(`https://explorer.near.org/accounts/${me.nearAccount}`, '_blank'); } else { throw new Error('Unsupported network'); } }; parseNearId(fullname: string, network: string): string | null { const regExpMainnet = /(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+\.near/; const regExpTestnet = /(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+\.testnet/; const nearId = fullname.toLowerCase().match(network === NearNetwork.TESTNET ? regExpTestnet : regExpMainnet); return nearId && nearId[0]; } formatNear(amount: string): string { return Number(formatNearAmount(amount, 4)).toFixed(2); } async getCurrentUserAsync(): Promise<string | null> { let i = 0; while (i < 10) { i++; try { const user = this.adapter.getCurrentUser(); return user ? user.username : null; } catch (e) { console.error(e); } await new Promise((res) => setTimeout(res, 1000)); } return null; } }
the_stack
import { Regl, Framebuffer2D, DrawCommand } from "regl" import * as k from "./kernels/simulation" import { DrawInfo, DrawShape } from "./drawing" export type MaterialType = "permittivity" | "permeability" | "conductivity" function clamp(min: number, max: number, value: number) { return Math.max(min, Math.min(max, value)) } function snapToGrid(relativePoint: [number, number], gridSize: [number, number]) { const relativeCellSize = [1 / gridSize[0], 1 / gridSize[1]] const residual = [relativePoint[0] % relativeCellSize[0], relativePoint[1] % relativeCellSize[1]] const gridPoint = [ relativePoint[0] - residual[0] + 0.5 * relativeCellSize[0], relativePoint[1] - residual[1] + 0.5 * relativeCellSize[1] ] return gridPoint } export function combineMaterialMaps(permittivity: number[][], permeability: number[][], conductivity: number[][]): number[][][] { const material: number[][][] = []; const width = permittivity[0].length; const height = permittivity.length; // TODO: Verify same dims for (let y = 0; y < height; y++) { const row: number[][] = [] for (let x = 0; x < width; x++) { row.push([ clamp(0, 255, 128 + 4 * permittivity[y][x]), clamp(0, 255, 128 + 4 * permeability[y][x]), clamp(0, 255, 128 + 4 * conductivity[y][x]), ]) } material.push(row) } return material } class DoubleFramebuffer2D { current: Framebuffer2D previous: Framebuffer2D constructor(current: Framebuffer2D, previous: Framebuffer2D) { this.current = current this.previous = previous } swap() { const oldCurrent = this.current this.current = this.previous this.previous = oldCurrent } } export type SimulationData = { time: number electricField: DoubleFramebuffer2D magneticField: DoubleFramebuffer2D material: DoubleFramebuffer2D alphaBetaField: Framebuffer2D electricSourceField: DoubleFramebuffer2D } /** * Simulates the electromagnetic field with materials. */ export interface Simulator { /** * Performs the update step for the electric field. * @param dt Time step size */ stepElectric: (dt: number) => void /** * Performs the update step for the magnetic field. * @param dt Time step size */ stepMagnetic: (dt: number) => void /** * Resets the electric, magnetic and source fields * and sets the time back to `0`. */ resetFields: () => void /** * Resets the materials to their default values of * `1` for permittivity and permeability and `0` for * conductivity. */ resetMaterials: () => void /** * Injects a value into the electric source field. * @param drawInfo Draw info that specifies where and * what values to inject. * @param dt Time step size */ injectSignal: (drawInfo: DrawInfo, dt: number) => void /** * Returns the simulation data containing the frame-buffers * for the fields and materials. */ getData: () => SimulationData /** * Returns the size of a cell. */ getCellSize: () => number /** * Sets the size of a cell. * @param cellSize Size of a cell */ setCellSize: (cellSize: number) => void /** * Returns the width and height of the grid in * number of cells. */ getGridSize: () => [number, number] /** * Sets the width and height of the grid in * number of cells. * @param reflectiveBoundary Width and height of the grid in * number of cells. */ setGridSize: (gridSize: [number, number]) => void /** * Returns whether the grid boundary is reflective. */ getReflectiveBoundary: () => boolean /** * Sets whether the grid boundary is reflective. * @param reflectiveBoundary Whether the grid boundary is reflective */ setReflectiveBoundary: (reflectiveBoundary: boolean) => void /** * Draws values onto a material. * @param materialType Material to draw onto * @param drawInfo Draw info that specifies where and * what values to draw. */ drawMaterial: (materialType: MaterialType, drawInfo: DrawInfo) => void /** * Loads a material from a 3D array. * @param material Material of shape `[height, width, 3]`. * * Channel 0: Permittivity * * Channel 1: Permeability * * Channel 2: Conductivity */ loadMaterial: (material: number[][][]) => void /** * Loads a material from arrays. * @param permittivity Array of shape `[height, width]` * specifying the permittivity at every cell. * @param permeability Array of shape `[height, width]` * specifying the permeability at every cell. * @param conductivity Array of shape `[height, width]` * specifying the conductivity at every cell. */ loadMaterialFromComponents: (permittivity: number[][], permeability: number[][], conductivity: number[][]) => void /** * Returns the material as a 3D array. * @param material Material of shape `[height, width, 3]`. * * Channel 0: Permittivity * * Channel 1: Permeability * * Channel 2: Conductivity */ getMaterial: () => number[][][] } export class FDTDSimulator implements Simulator { private data: SimulationData private updateMagnetic: DrawCommand private updateElectric: DrawCommand private updateAlphaBeta: DrawCommand private injectSource: DrawCommand private decaySource: DrawCommand private drawOnTexture: { [shape: string]: DrawCommand } private copyUint8ToFloat16: DrawCommand private copyFloat16ToUint8: DrawCommand private frameBuffers: Framebuffer2D[] private alphaBetaDt: number // dt that the alpha beta values were calculated for constructor(readonly regl: Regl, private gridSize: [number, number], private cellSize: number, public reflectiveBoundary: boolean, private dt: number) { this.alphaBetaDt = dt this.frameBuffers = [] const makeFrameBuffer = () => { // Create half-precision texture at grid size const fbo = regl.framebuffer({ color: regl.texture({ width: gridSize[0], height: gridSize[1], wrap: "clamp", type: "float16", format: "rgba", min: "nearest", mag: "nearest", }), depthStencil: false }) // Keep track of all fbos so we can resize them // together if the grid size changes. this.frameBuffers.push(fbo) return fbo } const makeField = () => { return new DoubleFramebuffer2D( makeFrameBuffer(), makeFrameBuffer() ) } this.data = { time: 0, electricField: makeField(), magneticField: makeField(), electricSourceField: makeField(), material: makeField(), alphaBetaField: makeFrameBuffer() } const makeFragFn = <T>(frag: string, fbos: { current: Framebuffer2D }, uniforms: T) => { return regl({ frag: frag, framebuffer: () => fbos.current, uniforms: uniforms, attributes: { position: [ [1, -1], [1, 1], [-1, -1], [-1, 1] ] }, vert: k.vert, count: 4, primitive: "triangle strip", depth: { enable: false } }) } const makeFragWithFboPropFn = (frag: string, uniforms: any) => { return regl({ frag: frag, framebuffer: (_: any, prop: any) => prop.fbo, uniforms: uniforms, attributes: { position: [ [1, -1], [1, 1], [-1, -1], [-1, 1] ] }, vert: k.vert, count: 4, primitive: "triangle strip", depth: { enable: false } }) } this.updateAlphaBeta = makeFragFn(k.updateAlphaBeta, { current: this.data.alphaBetaField }, { dt: (_: any, props: any) => props.dt, cellSize: (_: any, props: any) => props.cellSize, material: (_: any, props: any) => props.material, }) this.updateElectric = makeFragFn(k.updateElectric, this.data.electricField, { electricField: (_: any, props: any) => props.electricField, magneticField: (_: any, props: any) => props.magneticField, alphaBetaField: (_: any, props: any) => props.alphaBetaField, relativeCellSize: (_: any, props: any) => props.relativeCellSize, reflectiveBoundary: (_: any, props: any) => props.reflectiveBoundary, }) this.updateMagnetic = makeFragFn(k.updateMagnetic, this.data.magneticField, { electricField: (_: any, props: any) => props.electricField, magneticField: (_: any, props: any) => props.magneticField, alphaBetaField: (_: any, props: any) => props.alphaBetaField, relativeCellSize: (_: any, props: any) => props.relativeCellSize, reflectiveBoundary: (_: any, props: any) => props.reflectiveBoundary, }) this.injectSource = makeFragFn(k.injectSource, this.data.electricField, { sourceField: (_: any, props: any) => props.sourceField, field: (_: any, props: any) => props.field, dt: (_: any, props: any) => props.dt, }) this.decaySource = makeFragFn(k.decaySource, this.data.electricSourceField, { sourceField: (_: any, props: any) => props.sourceField, dt: (_: any, props: any) => props.dt, }) this.drawOnTexture = { [DrawShape.Ellipse]: makeFragWithFboPropFn(k.drawEllipse, { texture: (_: any, props: any) => props.texture, pos: (_: any, props: any) => props.pos, value: (_: any, props: any) => props.value, radius: (_: any, props: any) => props.radius, keep: (_: any, props: any) => props.keep, }), [DrawShape.Square]: makeFragWithFboPropFn(k.drawSquare, { texture: (_: any, props: any) => props.texture, pos: (_: any, props: any) => props.pos, value: (_: any, props: any) => props.value, size: (_: any, props: any) => props.size, keep: (_: any, props: any) => props.keep, }), } this.copyUint8ToFloat16 = makeFragFn(k.copyUint8ToFloat16, this.data.material, { texture: (_: any, props: any) => props.texture }) this.copyFloat16ToUint8 = makeFragWithFboPropFn(k.copyFloat16ToUint8, { texture: (_: any, props: any) => props.texture }) this.resetFields() this.resetMaterials() } updateAlphaBetaFromMaterial(dt: number) { this.alphaBetaDt = dt this.updateAlphaBeta({ material: this.data.material.current, dt: dt, cellSize: this.cellSize }) } getGridSize = () => this.gridSize; setGridSize = (gridSize: [number, number]) => { this.gridSize = gridSize this.frameBuffers.forEach(frameBuffer => frameBuffer.resize(gridSize[0], gridSize[1])) // TODO: Copy old data ? this.resetFields() } getCellSize = () => this.cellSize; setCellSize = (cellSize: number) => { this.cellSize = cellSize this.resetFields() } getReflectiveBoundary = () => this.reflectiveBoundary; setReflectiveBoundary = (reflectiveBoundary: boolean) => { this.reflectiveBoundary = reflectiveBoundary } stepElectric = (dt: number) => { if (this.alphaBetaDt !== dt) { this.updateAlphaBetaFromMaterial(dt) } this.data.electricField.swap() this.data.electricSourceField.swap() // Writes to E current this.injectSource({ sourceField: this.data.electricSourceField.previous, field: this.data.electricField.previous, dt: dt }) this.data.electricField.swap() // Writes to S current this.decaySource({ sourceField: this.data.electricSourceField.previous, dt: dt }) // Writes to E current this.updateElectric({ electricField: this.data.electricField.previous, magneticField: this.data.magneticField.current, alphaBetaField: this.data.alphaBetaField, relativeCellSize: [1 / this.gridSize[0], 1 / this.gridSize[1]], reflectiveBoundary: this.reflectiveBoundary, }) this.data.time += dt / 2 } stepMagnetic = (dt: number) => { if (this.alphaBetaDt !== dt) { this.updateAlphaBetaFromMaterial(dt) } this.data.magneticField.swap() this.updateMagnetic({ electricField: this.data.electricField.current, magneticField: this.data.magneticField.previous, alphaBetaField: this.data.alphaBetaField, relativeCellSize: [1 / this.gridSize[0], 1 / this.gridSize[1]], reflectiveBoundary: this.reflectiveBoundary, }) this.data.time += dt / 2 } resetFields = () => { this.data.time = 0 this.regl.clear({ color: [0, 0, 0, 0], framebuffer: this.data.electricField.current }) this.regl.clear({ color: [0, 0, 0, 0], framebuffer: this.data.magneticField.current }) this.regl.clear({ color: [0, 0, 0, 0], framebuffer: this.data.electricSourceField.current }) } resetMaterials = () => { this.regl.clear({ color: [1, 1, 0, 0], framebuffer: this.data.material.current }) this.updateAlphaBetaFromMaterial(this.alphaBetaDt) } drawMaterial = (materialType: MaterialType, drawInfo: DrawInfo) => { this.data.material.swap() const value = [0, 0, 0, 0] const keep = [1, 1, 1, 1] if (materialType === "permittivity") { value[0] = drawInfo.value keep[0] = 0 } else if (materialType === "permeability") { value[1] = drawInfo.value keep[1] = 0 } else if (materialType === "conductivity") { value[2] = drawInfo.value keep[2] = 0 } const uniforms: any = { pos: snapToGrid(drawInfo.center, this.gridSize), value: value, keep: keep, texture: this.data.material.previous, fbo: this.data.material.current } if (drawInfo.drawShape === DrawShape.Ellipse) { uniforms.radius = drawInfo.radius } else if (drawInfo.drawShape === DrawShape.Square) { uniforms.size = drawInfo.halfSize } this.drawOnTexture[drawInfo.drawShape](uniforms) this.updateAlphaBetaFromMaterial(this.alphaBetaDt) } injectSignal = (drawInfo: DrawInfo, dt: number) => { this.data.electricSourceField.swap() const uniforms: any = { pos: snapToGrid(drawInfo.center, this.gridSize), value: [0, 0, drawInfo.value * dt, 0], keep: [1, 1, 1, 1], texture: this.data.electricSourceField.previous, fbo: this.data.electricSourceField.current } if (drawInfo.drawShape === DrawShape.Ellipse) { uniforms.radius = drawInfo.radius } else if (drawInfo.drawShape === DrawShape.Square) { uniforms.size = drawInfo.halfSize } this.drawOnTexture[drawInfo.drawShape](uniforms) } loadMaterial = (material: number[][][]) => { const materialTexture = this.regl.texture({ data: material, format: "rgb", type: "uint8", min: "nearest", mag: "nearest", }) this.copyUint8ToFloat16({ texture: materialTexture }) materialTexture.destroy() this.updateAlphaBetaFromMaterial(this.alphaBetaDt) } loadMaterialFromComponents = (permittivity: number[][], permeability: number[][], conductivity: number[][]) => { this.loadMaterial( combineMaterialMaps(permittivity, permeability, conductivity) ) } getData = () => this.data getMaterial = () => { const fbo = this.regl.framebuffer({ color: this.regl.texture({ width: this.gridSize[0], height: this.gridSize[1], wrap: "clamp", type: "uint8", format: "rgba", min: "nearest", mag: "nearest", }), depthStencil: false }) this.copyFloat16ToUint8({ fbo: fbo, texture: this.data.material.current }) const materialData = this.regl.read({ framebuffer: fbo }) fbo.destroy() // Uint8 to float with correct scaling const materialFloats: number[][][] = [] for (let y = 0; y < this.gridSize[1]; y++) { const row: number[][] = [] for (let x = 0; x < this.gridSize[0]; x++) { row.push([ (materialData[y * this.gridSize[0] * 4 + x * 4 + 0] - 127) / 4, (materialData[y * this.gridSize[0] * 4 + x * 4 + 1] - 127) / 4, (materialData[y * this.gridSize[0] * 4 + x * 4 + 2] - 127) / 4, // +3 is unused ]) } materialFloats.push(row) } return materialFloats } }
the_stack
import { parserInput } from 'fruitsconfits/modules/lib/types'; import { formatErrorMessage } from 'fruitsconfits/modules/lib/parser'; import { SxToken, SxSymbol, SxParserConfig } from 'liyad/modules/s-exp/types'; import installCore from 'liyad/modules/s-exp/operators/core'; import { SExpression } from 'liyad/modules/s-exp/interpreters'; import { defaultConfig } from 'liyad/modules/s-exp/defaults'; import { TypeAssertion, PrimitiveTypeAssertion, ErrorMessages, TypeAssertionSetValue, TypeAssertionMap } from './types'; import * as operators from './operators'; import { resolveMemberNames, resolveSchema } from './lib/resolver'; import { dummyTargetObject, isUnsafeVarNames } from './lib/protection'; import { externalTypeDef, program } from './lib/compiler'; function parseExternalDirective(s: string) { const z = externalTypeDef(parserInput(s, {/* TODO: set initial state to the context */})); if (! z.succeeded) { throw new Error('Invalid external directive.'); } return z.tokens; } export function parse(s: string) { const z = program(parserInput(s, {/* TODO: set initial state to the context */})); if (! z.succeeded) { throw new Error(formatErrorMessage(z)); } return z.tokens; } const lisp = (() => { let config: SxParserConfig = Object.assign({}, defaultConfig); config.reservedNames = Object.assign({}, config.reservedNames, { Template: '$concat', }); config = installCore(config); config.stripComments = true; return SExpression(config); })(); // tslint:disable: object-literal-key-quotes export function compile(s: string) { const mapTyToTySet = new Map<TypeAssertion, TypeAssertionSetValue>(); const schema: TypeAssertionMap = new Map<string, TypeAssertionSetValue>(); let gensymCount = 0; const def = (name: SxSymbol | string, ty: TypeAssertion): TypeAssertion => { let ret = ty; const sym = typeof name === 'string' ? name : name.symbol; if (isUnsafeVarNames(dummyTargetObject, sym)) { throw new Error(`Unsafe symbol name is appeared: ${sym}`); } if (! mapTyToTySet.has(ret)) { const originalTypeName = ret.typeName; ret = operators.withName(operators.withTypeName( originalTypeName ? operators.withOriginalTypeName(ret, originalTypeName) : ret, sym), sym); } const tySet = mapTyToTySet.has(ret) ? mapTyToTySet.get(ret) as TypeAssertionSetValue : {ty: ret, exported: false, isDeclare: false, resolved: false}; schema.set(sym, tySet); if (! mapTyToTySet.has(ret)) { // TODO: aliases are not exported correctly mapTyToTySet.set(ret, tySet); } return ret; }; const ref = (name: SxSymbol | string, ...memberNames: (SxSymbol | string)[]): TypeAssertion => { const sym = typeof name === 'string' ? name : name.symbol; if (isUnsafeVarNames(dummyTargetObject, sym)) { throw new Error(`Unsafe symbol name is appeared: ${sym}`); } const memberTreeSymbols = memberNames.map(x => { const ms = typeof x === 'string' ? x : x.symbol; if (isUnsafeVarNames(dummyTargetObject, ms)) { throw new Error(`Unsafe symbol name is appeared: ${ms}`); } return ms; }); if (! schema.has(sym)) { return ({ ...{ kind: 'symlink', symlinkTargetName: sym, name: sym, typeName: sym, }, ...(0 < memberTreeSymbols.length ? { memberTree: memberTreeSymbols, } : {}), }); } let ty = resolveMemberNames( (schema.get(sym) as TypeAssertionSetValue).ty, sym, memberTreeSymbols, 0, ); if (ty.noOutput) { ty = {...ty}; delete ty.noOutput; } return ty; }; const redef = (original: TypeAssertion, ty: TypeAssertion) => { if (original === ty) { return ty; } // NOTE: 'ty' should already be registered to 'mapTyToTySet' and 'schema' const tySet = mapTyToTySet.has(original) ? mapTyToTySet.get(original) as TypeAssertionSetValue : {ty: original, exported: false, isDeclare: false, resolved: false}; tySet.ty = ty; mapTyToTySet.set(tySet.ty, tySet); if (ty.name) { schema.set(ty.name, tySet); } return tySet.ty; }; const exported = (ty: TypeAssertion) => { if (ty.kind === 'never' && typeof ty.passThruCodeBlock === 'string') { ty.passThruCodeBlock = `export ${ty.passThruCodeBlock}`; return ty; } else { // NOTE: 'ty' should already be registered to 'mapTyToTySet' and 'schema' const tySet = mapTyToTySet.has(ty) ? mapTyToTySet.get(ty) as TypeAssertionSetValue : {ty, exported: false, isDeclare: false, resolved: false}; tySet.exported = true; return ty; } }; const external = (...names: (string | [string, TypeAssertion?])[]) => { for (const name of names) { let ty: TypeAssertion = null as any; if (typeof name === 'string') { ty = def(name, operators.primitive('any')); } else { ty = def(name[0], name[1] ? name[1] : operators.primitive('any')); } ty.noOutput = true; } }; const asConst = (ty: TypeAssertion) => { switch (ty.kind) { case 'enum': // NOTE: `ty` may already `def`ed. ty.isConst = true; break; default: throw new Error(`It cannot set to const: ${ty.kind} ${ty.typeName || '(unnamed)'}`); } return ty; }; const asDeclare = (ty: TypeAssertion) => { // NOTE: 'ty' should already be registered to 'mapTyToTySet' and 'schema' const tySet = mapTyToTySet.has(ty) ? mapTyToTySet.get(ty) as TypeAssertionSetValue : {ty, exported: false, isDeclare: false, resolved: false}; tySet.isDeclare = true; return ty; }; const passthru = (str: string, docCommentText?: string) => { const ty: TypeAssertion = { kind: 'never', passThruCodeBlock: str || '', }; if (docCommentText) { ty.docComment = docCommentText; } schema.set(`__$$$gensym_${gensymCount++}$$$__`, {ty, exported: false, isDeclare: false, resolved: false}); return ty; }; const directive = (name: string, body: string) => { switch (name) { case '@tynder-external': lisp.evaluateAST(parseExternalDirective(`external ${body} ;`) as SxToken[]); break; case '@tynder-pass-through': passthru(body); break; default: throw new Error(`Unknown directive is appeared: ${name}`); } return []; }; lisp.setGlobals({ picked: operators.picked, omit: operators.omit, partial: operators.partial, intersect: operators.intersect, oneOf: operators.oneOf, subtract: operators.subtract, primitive: operators.primitive, primitiveValue: operators.primitiveValue, optional: operators.optional, repeated: operators.repeated, sequenceOf: operators.sequenceOf, spread: operators.spread, enumType: operators.enumType, objectType: operators.objectType, derived: operators.derived, def, ref, redef, export: exported, external, asConst, asDeclare, passthru, directive, docComment: operators.withDocComment, '@range': (minValue: number | string, maxValue: number | string) => (ty: PrimitiveTypeAssertion) => operators.withRange(minValue, maxValue)(ty), '@minValue': (minValue: number | string) => (ty: PrimitiveTypeAssertion) => operators.withMinValue(minValue)(ty), '@maxValue': (maxValue: number | string) => (ty: PrimitiveTypeAssertion) => operators.withMaxValue(maxValue)(ty), '@greaterThan': (greaterThan: number | string) => (ty: PrimitiveTypeAssertion) => operators.withGreaterThan(greaterThan)(ty), '@lessThan': (lessThan: number | string) => (ty: PrimitiveTypeAssertion) => operators.withLessThan(lessThan)(ty), '@minLength': (minLength: number) => (ty: PrimitiveTypeAssertion) => operators.withMinLength(minLength)(ty), '@maxLength': (maxLength: number) => (ty: PrimitiveTypeAssertion) => operators.withMaxLength(maxLength)(ty), '@match': (pattern: RegExp) => (ty: PrimitiveTypeAssertion) => operators.withMatch(pattern)(ty), '@stereotype': (stereotype: string) => (ty: TypeAssertion) => operators.withStereotype(stereotype)(ty), '@constraint': (name: string, args?: any) => (ty: TypeAssertion) => operators.withConstraint(name, args)(ty), '@forceCast': () => (ty: TypeAssertion) => operators.withForceCast()(ty), '@recordType': () => (ty: TypeAssertion) => operators.withRecordType()(ty), '@meta': (meta: any) => (ty: TypeAssertion) => operators.withMeta(meta)(ty), '@msg': (messages: string | ErrorMessages) => (ty: TypeAssertion) => operators.withMsg(messages)(ty), '@msgId': (messageId: string) => (ty: TypeAssertion) => operators.withMsgId(messageId)(ty), }); const z = parse(s); lisp.evaluateAST(z as SxToken[]); return resolveSchema(schema); } // tslint:enable: object-literal-key-quotes
the_stack
import * as csstips from 'csstips'; import * as typestyle from 'typestyle'; import * as React from "react"; /** * Defaults used in layout */ export let defaultValues = { verticalSpacing: 24, horizontalSpacing: 24, breakpoints: { phone: 480, } } export function setDefaults(defaults: typeof defaultValues) { defaultValues = defaults; } declare global { interface Function { displayName?: string; } } /******** * * Primitives * ********/ /** * For that time you just need a visual vertical seperation */ export const SmallVerticalSpace = (props: { space?: number }) => { return <div style={{ height: props.space || defaultValues.verticalSpacing }}></div>; } SmallVerticalSpace.displayName = "SmallVerticalSpace"; /** * For that time you just need a visual horizontal seperation */ export const SmallHorizontalSpace = (props: { space?: number }) => { return <div style={{ width: props.space || defaultValues.horizontalSpacing, display: 'inline-block' }}></div>; } SmallVerticalSpace.displayName = "SmallHorizontalSpace"; export interface PrimitiveProps extends React.HTMLProps<HTMLDivElement> { }; namespace ClassNames { export const content = typestyle.style(csstips.content); export const flex = typestyle.style(csstips.pass, csstips.flex); export const flexScrollY = typestyle.style(csstips.pass, csstips.flex, csstips.vertical, { overflowY: 'auto' }); export const pass = typestyle.style(csstips.pass); export const contentVertical = typestyle.style(csstips.content, csstips.vertical); export const contentVerticalCentered = typestyle.style(csstips.content, csstips.vertical, csstips.center); export const flexVerticalCentered = typestyle.style(csstips.flex, csstips.vertical, csstips.center); export const contentHorizontal = typestyle.style(csstips.content, csstips.horizontal); export const contentHorizontalCentered = typestyle.style(csstips.content, csstips.horizontal, csstips.center); export const flexHorizontalCentered = typestyle.style(csstips.flex, csstips.horizontal, csstips.center); export const flexVertical = typestyle.style(csstips.flex, csstips.vertical, { maxWidth: '100%' /*normalizing browser bugs*/ }); export const flexHorizontal = typestyle.style(csstips.flex, csstips.horizontal); } /** * Generally prefer an inline block (as that will wrap). * Use this for critical `content` driven *vertical* height * * Takes as much space as it needs, no more, no less */ export const Content = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.content, props.className); return ( <div data-comment="Content" {...props} className={className} /> ); }; Content.displayName = "Content"; /** * Takes as much space as it needs, no more, no less */ export const InlineBlock = (props: PrimitiveProps) => { const className = typestyle.classes(typestyle.style({ display: 'inline-block' }), props.className); return ( <div data-comment="InlineBlock" {...props} className={className} /> ); }; InlineBlock.displayName = "InlineBlock"; /** * Takes up all the parent space, no more, no less */ export const Flex = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.flex, props.className); return ( <div data-comment="Flex" {...props} className={className} /> ); }; Flex.displayName = "Flex"; /** * Takes up all the parent space, no more, no less and scrolls the children in Y if needed */ export const FlexScrollY = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.flexScrollY, props.className); return ( <div data-comment="FlexScrollY" {...props} className={className} /> ); }; FlexScrollY.displayName = "FlexScrollY"; /** * When you need a general purpose container. Use this instead of a `div` */ export const Pass = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.pass, props.className); return ( <div data-comment="Pass" {...props} className={className} /> ); }; Pass.displayName = "Pass"; /** * Provides a Vertical Container. For the parent it behaves like content. */ export const ContentVertical = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.contentVertical, props.className); return ( <div data-comment="ContentVertical" {...props} className={className} /> ); }; ContentVertical.displayName = "ContentVertical"; /** * Quite commonly need horizontally centered text */ export const ContentVerticalCentered = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.contentVerticalCentered, props.className); return ( <div data-comment="ContentVerticalCentered" {...props} className={className} /> ); } ContentVerticalCentered.displayName = "ContentVerticalCentered"; /** * Quite commonly need horizontally centered text */ export const FlexVerticalCentered = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.flexVerticalCentered, props.className); return ( <div data-comment="FlexVerticalCentered" {...props} className={className} /> ); } FlexVerticalCentered.displayName = "FlexVerticalCentered"; /** * Provides a Horizontal Container. For the parent it behaves like content. */ export const ContentHorizontal = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.contentHorizontal, props.className); return ( <div data-comment="ContentHorizontal" {...props} className={className} /> ); }; ContentHorizontal.displayName = "ContentHorizontal"; /** * Provides a Horizontal Container and centers its children in the cross dimension */ export const ContentHorizontalCentered = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.contentHorizontalCentered, props.className); return ( <div data-comment="ContentHorizontalCentered" {...props} className={className} /> ); }; ContentHorizontalCentered.displayName = "ContentHorizontalCentered"; /** * Provides a Vertical Container. For the parent it behaves like flex. */ export const FlexVertical = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.flexVertical, props.className); return ( <div data-comment="FlexVertical" {...props} className={className} /> ); }; FlexVertical.displayName = "FlexVertical"; /** * Provides a Horizontal Container. For the parent it behaves like flex. */ export const FlexHorizontal = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.flexHorizontal, props.className); return ( <div data-comment="FlexHorizontal" {...props} className={className} /> ); }; FlexHorizontal.displayName = "FlexHorizontal"; /** * Provides a Horizontal Container and centers its children in the cross dimension */ export const FlexHorizontalCentered = (props: PrimitiveProps) => { const className = typestyle.classes(ClassNames.flexHorizontalCentered, props.className); return ( <div data-comment="FlexHorizontalCentered" {...props} className={className} /> ); }; ContentHorizontalCentered.displayName = "FlexHorizontalCentered"; /******** * * Grid System * ********/ export interface MarginedProps extends PrimitiveProps { margin?: number; } export const ContentHorizontalMarginedCentered = (props: MarginedProps) => { const { margin, ...otherProps } = props; const spacing = (margin == null ? defaultValues.horizontalSpacing : margin); const className = typestyle.classes(props.className, typestyle.style(csstips.center, csstips.horizontallySpaced(spacing))); return ( <ContentHorizontal {...otherProps} className={className} data-comment="ContentHorizontalMarginedCentered" /> ); } ContentHorizontalMarginedCentered.displayName = "ContentHorizontalMarginedCentered"; /** * Lays out the children horizontally with * - Parent: gets to chose the Width * - ThisComponent: gets the overall Height (by max) of the children * - Children: get the Width : equally distributed from the parent Width * - Children: get the Height : sized by content * - ThisComponent: Puts a horizontal margin between each item */ export const FlexHorizontalMargined = (props: MarginedProps) => { const { margin, ...otherProps } = props; const spacing = (margin == null ? defaultValues.horizontalSpacing : margin); const className = typestyle.classes(props.className, typestyle.style(csstips.horizontallySpaced(spacing))); return ( <FlexHorizontal {...otherProps} className={className} data-comment="FlexHorizontalMargined" /> ); } FlexHorizontalMargined.displayName = "FlexHorizontalMargined"; export const FlexVerticalMargined = (props: MarginedProps) => { const { margin, ...otherProps } = props; const spacing = (margin == null ? defaultValues.verticalSpacing : margin); const className = typestyle.classes(props.className, typestyle.style(csstips.verticallySpaced(spacing))); return ( <FlexVertical {...otherProps} className={className} data-comment="FlexVerticalMargined" /> ); } FlexHorizontalMargined.displayName = "FlexVerticalMargined"; /** * Just a display:block with vertical spacing between each child */ export const VerticalMargined = (props: MarginedProps) => { const { margin, ...otherProps } = props; const spacing = (margin == null ? defaultValues.verticalSpacing : margin); const className = typestyle.classes(props.className, typestyle.style(csstips.verticallySpaced(spacing))); return ( <div {...otherProps} className={className} data-comment="VerticalMargined" /> ); } VerticalMargined.displayName = "VerticalMargined"; /** * If you want a constrained max width layout */ export const MaxWidth = ({ maxWidth, children }: { maxWidth: number, children?: React.ReactNode }) => { return <div style={{ maxWidth: maxWidth + 'px' }} children={children} /> } ////////////////////// // AP core page layout components ////////////////////// export type VerticalProps = MarginedProps & { maxWidth?: number, horizontalAlign?: 'left' /** default */ | 'center', }; /** * Could be ContentVerticalMargined but also wraps each child in Content to auto fix IE vertical layout issues */ export const Vertical = (props: VerticalProps) => { const { margin, children, maxWidth, horizontalAlign, ...otherProps } = props; const spacing = (margin == null ? defaultValues.verticalSpacing : margin); const className = typestyle.classes( props.className, typestyle.style(csstips.verticallySpaced(spacing)), maxWidth != null && typestyle.style({ maxWidth: maxWidth + 'px' }), horizontalAlign == 'center' && typestyle.style(csstips.center), ); return ( <ContentVertical {...otherProps} className={className} data-comment="Vertical"> { React.Children.toArray(children).filter(c => !!c).map((child, i) => <Content key={(child as any).key || i}>{child}</Content>) } </ContentVertical> ); } Vertical.displayName = "Vertical"; /** * Lays out the children horizontally with * - ThisComponent: gets the overall Height (by max) of the children * - Children: get the Width : equally distributed from the parent Width * - Children: get the Height : sized by content * - ThisComponent: Puts a horizontal margin between each item */ export const Horizontal = (props: MarginedProps & { horizontalAlign?: 'left' /** default */ | 'right', verticalAlign?: 'top' /** default */ | 'center' }) => { const { margin, horizontalAlign, verticalAlign, ...otherProps } = props; const spacing = (margin == null ? defaultValues.horizontalSpacing : margin); const className = typestyle.classes(props.className, typestyle.style(csstips.horizontallySpaced(spacing)), horizontalAlign == 'right' && typestyle.style(csstips.endJustified), verticalAlign == 'center' && typestyle.style(csstips.center), ); return ( <ContentHorizontal {...otherProps} className={className} data-comment="Horizontal" /> ); } Horizontal.displayName = "Horizontal"; /** * Responsive Container */ export interface ResponsiveGridParentProps extends PrimitiveProps { /** Margins in vertical mode */ verticalMargin?: number; /** Margins in horizontal mode */ horizontalMargin?: number; breakpoint?: number; /** Alignment in horizontal mode */ horizontalAlign?: 'top' /** Default */ | 'center'; } export const Responsive = (props: ResponsiveGridParentProps) => { const { verticalMargin, horizontalMargin, breakpoint, horizontalAlign, ...otherProps } = props; const spacingVertical = (verticalMargin == null ? defaultValues.verticalSpacing : verticalMargin); const spacingHorizontal = (horizontalMargin == null ? defaultValues.horizontalSpacing : horizontalMargin); const breakpointNum = (breakpoint || defaultValues.breakpoints.phone) const children = React.Children.toArray(props.children).filter(c => !!c); const alignment = horizontalAlign === 'center' ? [csstips.flexRoot, csstips.center] : [csstips.flexRoot, csstips.start]; const parentClassName = typestyle.classes( props.className, typestyle.style( csstips.layerParent, /** Lower than breakpoint: Vertical Margined */ typestyle.media({ minWidth: 0, maxWidth: breakpointNum }, csstips.verticallySpaced(spacingVertical)), /** Bigger than breakpoint: Horizontal Margined */ typestyle.media({ minWidth: breakpointNum + 1 }, csstips.horizontallySpaced(spacingHorizontal), ...alignment), ) ); const childClassName = (className: string) => typestyle.classes( className, typestyle.style( csstips.inlineBlock, /** Lower than breakpoint: full sized */ typestyle.media({ minWidth: 0, maxWidth: breakpointNum }, { width: '100%' }), /** Bigger than breakpoint: percent sized */ typestyle.media({ minWidth: breakpointNum + 1 }, { width: `calc(${(1 / children.length) * 100}% - ${spacingHorizontal - spacingHorizontal / children.length}px)` }), ) ); return ( <div {...otherProps} className={parentClassName} data-comment="Responsive"> { children.map((child, i) => <div data-comment="ResponsiveChild" key={(child as any).key || i} className={childClassName((child as any).className)}>{child}</div>) } </div> ); } Responsive.displayName = "Responsive";
the_stack
import fix from './fix'; type SkipToken<T> = { data: symbol, next: ChainedPromise<T> }; /** * An extended promise for recurring promises with multiple compositions. * * ```javascript * var chained = ChainedPromise.from(promise); * chained.flatMap(a).flatMap(b).flatMap(c).forEach(fn).catch(onRejected); * ``` * * is equivalent to: * * ```javascript * promise.then(a).then(b).then(c).then(fn).then((v) => v.next) * .then(a).then(b).then(c).then(fn).then((v) => v.next) * .then(a).then(b).then(c).then(fn).then((v) => v.next) * ... * .catch(onRejected); * ``` * * `(v) => v.next` function is the default {@link ChainedPromise#next} value * picker. We can supply custom value picker to the {@link * ChainedPromise#constructor} and {@link ChainedPromise#from}. */ class ChainedPromise<T> extends Promise<T> { private flatMapChain: Array<(v: any) => Promise<any>>; /** * Function to construct promise to next item in chain. */ public next: (t: T) => Promise<T>; /** * Initializes fields common to both {@link ChainedPromise#constructor} * and {@link ChainedPromise#from} code path. */ private initialize() { this.flatMapChain = []; } /** * Constructs next {@link ChainedPromise} that carries over settings and * composition properties of the current one. */ private nextPromise<U>(v: T|SkipToken<T>): ChainedPromise<U> { let nextPromise; if ((v as SkipToken<T>).data && (v as SkipToken<T>).data === ChainedPromise.SKIP) { nextPromise = ChainedPromise.from((v as SkipToken<T>).next, this.next); } else { nextPromise = ChainedPromise.from(this.next(v as T), this.next); } nextPromise.flatMapChain = this.flatMapChain; return ((nextPromise as any) as ChainedPromise<U>); } /** * @param executor Promise executor * @param next */ constructor(executor, next = ChainedPromise.nextFieldPicker<T>('next')) { super(executor); this.next = next; this.initialize(); } /** * Creates a ChainedPromise that extends given Promise. */ static from<T>( innerPromise: Promise<T>, next = ChainedPromise.nextFieldPicker<T>('next')): ChainedPromise<T> { return new ChainedPromise((res, rej) => innerPromise.then(res, rej), next); } /** * Returns a function to pick the given attribute. * @param {string} attr Name of the attribute (that will contain the next promise). * @returns {function(T) : Promise.<T>} * @template T */ static nextFieldPicker<T>(attr: string): (v: T) => Promise<T> { return (x) => x[attr]; } /** * Creates `[ChainedPromise, callback, error]` array. * * Calling callback with a value `v` will cause the promise to be resolved * into * `{data: v, next: nextPromise}`, `nextPromise` being another {@link * ChainedPromise} who gets resolved next time `callback` is called. * * Calling `error` function will cause the promise to be rejected. * @returns {Array} * @template T */ static createPromiseCallbackPair<U, T = {data: U, next: ChainedPromise<T>}>(): [ChainedPromise<T>, (v: U) => void, (error: any) => void] { let resolver; let rejecter; const callback = (v) => { const oldResolver = resolver; const nextPromise = new ChainedPromise((resolve, reject) => { resolver = resolve; rejecter = reject; }); oldResolver({data: v, next: nextPromise}); }; const error = (err) => { rejecter(err); }; const promise = new ChainedPromise<T>((resolve, reject) => { resolver = resolve; rejecter = reject; }); return [promise, callback, error]; } /** * Applies the given function on all values in the chain, until the {@link * ChainedPromise#next} value returns an object with {@link * ChainedPromise.DONE} symbol. */ forEach<V>(fn: (v: T) => void): Promise<V> { return fix<T, V>((v: T|SkipToken<T>, complete) => { let nextPromise; if ((v as SkipToken<T>).data && (v as SkipToken<T>).data === ChainedPromise.SKIP) { nextPromise = (v as SkipToken<T>).next; } else { fn(v as T); nextPromise = this.next(v as T); } if (nextPromise[ChainedPromise.DONE] !== undefined) { return complete(nextPromise[ChainedPromise.DONE]); } else { return this.nextPromise(v as T); } })(this); } /** * Stacks up flat map operation to be performed in this promise. See {@link * ChainedPromise} for examples. */ flatMap<U>(fn: (v: T) => Promise<U>): ChainedPromise<U> { this.flatMapChain.push(fn); return ((this as any) as ChainedPromise<U>); } /** * Non-async equivalent of {@link ChainedPromise#flatMap}. */ map<U>(fn: (T) => U): ChainedPromise<U> { this.flatMap((v) => new ChainedPromise((res) => res(fn(v)))); return ((this as any) as ChainedPromise<U>); } /** * Overrides Promise.then to compose with extra functions. See {@link * ChainedPromise} for the specifics of available compositions. */ then<TResult1 = T | SkipToken<T>, TResult2 = never>( onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>)|null| undefined, onRejected?: (result: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1|TResult2> { if (!onFulfilled) { // Skip processing in case of Promise.catch call. // TODO: fix type. return super.then(onFulfilled as any, onRejected as any) as any; } // Branch out no-op special case, since "super" in ES6 is not a first-class // citizen. if (this.flatMapChain.length === 0) { // TODO: fix type. return super.then(onFulfilled as any, onRejected as any) as any; } else { const firstFlatMapped = super.then(this.flatMapChain[0]); let flatMapped = this.flatMapChain.slice(1).reduce((x, y) => { return x.then((res) => { if (res.data && res.data === ChainedPromise.SKIP) { return res; } return y(res); }); }, firstFlatMapped); return flatMapped.then(onFulfilled, onRejected); } } /** * Flat-maps current promise chain to resolve into successive accumulation of * values, from given accumulator. Accumulator should pass on next promise to * the accumulated value. * @param fn Accumulator that takes previous accumulation and current value, * and calculate next accumulation. * @param initial Initial accumulated value to start with. */ accumulate<U>(fn: (U, T) => Promise<U>, initial: U): ChainedPromise<U> { let accumulated = initial; this.flatMap((v) => fn(accumulated, v)).map((acc) => { accumulated = acc; return acc; }); return ((this as any) as ChainedPromise<U>); } /** * Takes a join spec and flatMaps current ChainedPromise accordingly. A join * spec is recursively defined as follows: * * * If the spec is a function taking a value and returning a promise, then * the join operation evaluates the function with current value and replaces * the value with the resulting promise. * * * If the spec is an array of a spec, then the current value is assumed to * be an array, and each element in the current value is mapped to the inner * spec. * * * If the spec is an object with keys to specs, then the field of the * current value with each key is replaced with the result of each join * operations with the inner spec. * @param {(function(T): (Promise.<U>) | Array | Object)} spec * @returns {ChainedPromise.<V>} * @template T * @template U * @template V */ join<V>(spec: ((t: T) => Promise<{}>)|Array<Object>| Object): ChainedPromise<V> { this.flatMap((v) => { function pickAndJoin(curSpec, curValue) { if (typeof curSpec === 'function') { return curSpec(curValue); } if (curSpec instanceof Array) { // TODO(yiinho): more thorough error handling. return Promise.all(curValue.map((x) => pickAndJoin(curSpec[0], x))); } if (curSpec instanceof Object) { return Promise .all(Object.keys(curSpec).map( (key) => pickAndJoin(curSpec[key], curValue[key]) .then((joinResult) => { const result = {}; result[key] = joinResult; return result; }))) .then((joinedValues) => { joinedValues.forEach((join) => Object.assign(curValue, join)); return curValue; }); } throw new TypeError( 'Specification not recognized: ' + JSON.stringify(spec)); } return pickAndJoin(spec, v); }); return this as any as ChainedPromise<V>; } /** * Collects results (including the final "done" value) into an array. * @param fn Mapper function to be applied to each data points (except * the final "done" value) before collecting into the result array. */ collect<U, V>(fn: (t: T) => (U | V) = (x) => (x as any as U)) { const collected: Array<U|V> = []; return this .forEach<V>((v) => { collected.push(fn(v)); }) .then((done) => { collected.push(done); return collected; }); } /** * Filters for values that evaluates to `true`. */ filter(fn: (t: T) => boolean): ChainedPromise<T|SkipToken<T>> { return this.map<T|SkipToken<T>>((v) => { if (!fn(v)) { return {data: ChainedPromise.SKIP, next: this.next(v)}; } return v; }); } /** * Symbol to indicate the end of promise chains. Having * `{[ChainedPromise.DONE]: <some value>}` as a next value will indicate the * end of the chain, and will cause fixed promises such as * {@link ChainedPromise#forEach} to resolve to the given value. */ static DONE = Symbol('ChainedPromise.DONE'); private static SKIP = Symbol('ChainedPromise.SKIP'); } export default ChainedPromise;
the_stack
import * as d3 from 'd3'; import { annotation, annotationBadge, annotationLabel, annotationCallout, annotationCalloutElbow, annotationCalloutCurve, annotationCalloutCircle, annotationCalloutRect, annotationXYThreshold } from '../../node_modules/d3-svg-annotation/indexRollupNext.js'; import { visaColorToHex } from './colors'; import { hideNode } from './accessibilityUtils'; import { select } from 'd3-selection'; import { roundTo } from './formatStats'; import { resolveLabelCollision } from './collisionDetection'; import { getTextWidth } from './textHelpers'; interface DatumObject { [key: string]: any; } const types = { annotationLabel: annotationLabel, annotationCallout: annotationCallout, annotationCalloutElbow: annotationCalloutElbow, annotationCalloutCurve: annotationCalloutCurve, annotationCalloutCircle: annotationCalloutCircle, annotationCalloutRect: annotationCalloutRect, annotationXYThreshold: annotationXYThreshold, annotationBadge: annotationBadge }; export function annotate({ source, data, xScale, xAccessor, yScale, yAccessor, ignoreScales, width, height, padding, margin, bitmaps }: { source?: any; data?: any; xScale?: any; xAccessor?: any; yScale?: any; yAccessor?: any; ignoreScales?: boolean; width?; any; height?: any; padding?: any; margin?: any; bitmaps?: any; }) { d3.select(source) .selectAll('.vcl-annotation-group') .remove(); const annotations = d3 .select(source) .append('g') .attr('class', 'vcl-annotation-group') .attr('data-testid', 'annotation-group'); hideNode(annotations.node()); const editable = d3 .select(source) .append('g') .attr('class', 'editable vcl-annotation-group') .attr('data-testid', 'editable-annotation-group'); hideNode(editable.node()); if (data && data.length) { const percentX = d3 .scaleLinear() .range(xScale ? xScale.range() : [0, 100]) .domain([0, 100]); const yRange = yScale ? yScale.range() : [0, 100]; const y0 = yRange[0] >= yRange[1] ? 100 : 0; const y1 = 100 - y0; const percentY = d3 .scaleLinear() .range(yRange) .domain([y0, y1]); let invertedY = d => { const height = yRange[0] >= yRange[1] ? yRange[0] : yRange[1]; return yScale(d) - height; }; const annotationData = []; const annotationEditableData = []; data.forEach((datum, i) => { const d: DatumObject = {}; const dKeys = Object.keys(datum); dKeys.forEach(key => { if (key !== 'data' && key !== 'subject' && key !== 'connector' && key !== 'note') { if (datum[key] instanceof Array) { d[key] = [...datum[key]]; } else { d[key] = datum[key]; } } else { d[key] = {}; const innerKeys = Object.keys(datum[key]); innerKeys.forEach(innerKey => { if (datum[key][innerKey] instanceof Array) { if (innerKey === 'points') { // [ // datum[key][innerKey] // [ // point // 40, // 50 // ], // [ // 200, // 100 // ] // ] // or // [ // datum[key][innerKey] // [ // point // [val,val], // [val] // ], // [ // [val], // [val] // ] // ] d[key][innerKey] = []; datum[key][innerKey].forEach(point => { const clonedPoint = []; if (point[0] instanceof Array && point[1] instanceof Array) { clonedPoint.push([...point[0]]); clonedPoint.push([...point[1]]); } else { clonedPoint.push(point[0]); clonedPoint.push(point[1]); } d[key][innerKey].push(clonedPoint); }); } else { d[key][innerKey] = [...datum[key][innerKey]]; } } else { d[key][innerKey] = datum[key][innerKey]; } }); } }); const yToDate = d.parseAsDates && (d.parseAsDates.includes('y') || d.parseAsDates.includes(yAccessor)); const xToDate = d.parseAsDates && (d.parseAsDates.includes('x') || d.parseAsDates.includes(xAccessor)); let diff = 0; if (d.data) { const keys = Object.keys(d.data); let i = 0; if (yToDate || xToDate) { for (i = 0; i < keys.length; i++) { if (keys[i] === 'x' || keys[i] === xAccessor) { d.data[keys[i]] = checkDate(d.data[keys[i]], xToDate); } else if (keys[i] === yAccessor || keys[i] === 'y') { d.data[keys[i]] = checkDate(d.data[keys[i]], yToDate); } } } } if (d.x) { d.x = resolveValue(d.x, xScale, percentX, xToDate); } if (d.y) { d.y = resolveValue(d.y, yScale, percentY, yToDate); } if (d.dx) { if (d.dx instanceof Array) { diff = d.data && d.data[xAccessor] !== undefined ? xScale(d.data[xAccessor]) : d.x ? d.x : 0; } d.dx = resolveValue(d.dx, xScale, percentX, xToDate) - diff; } if (d.dy) { diff = 0; if (d.dy instanceof Array) { diff = d.data && d.data[yAccessor] !== undefined ? yScale(d.data[yAccessor]) : d.y ? d.y : 0; } d.dy = resolveValue(d.dy, yScale, percentY, yToDate) - diff; } if (d.subject) { if (d.subject.x1) { d.subject.x1 = resolveValue(d.subject.x1, xScale, percentX, xToDate); } if (d.subject.y1) { d.subject.y1 = resolveValue(d.subject.y1, yScale, percentY, yToDate); } if (d.subject.x2) { d.subject.x2 = resolveValue(d.subject.x2, xScale, percentX, xToDate); } if (d.subject.y2) { d.subject.y2 = resolveValue(d.subject.y2, yScale, percentY, yToDate); } if (d.subject.width) { d.subject.width = resolveValue(d.subject.width, xScale, percentX, xToDate); } if (d.subject.height) { d.subject.height = resolveValue(d.subject.height, invertedY, percentY, yToDate); } } if (d.connector) { if (typeof d.connector.curve === 'string') { d.connector.curve = d3[d.connector.curve]; } if (d.connector.points instanceof Array) { d.connector.points.forEach(point => { point[0] = resolveValue(point[0], xScale, percentX, xToDate); point[1] = resolveValue(point[1], yScale, percentY, yToDate); }); } } if (d.type && typeof d.type === 'string') { d.type = types[d.type]; } if (!d.editMode) { annotationData.push(d); } else { annotationEditableData.push(d); } if (d.color) { d.color = visaColorToHex(d.color) || d.color; } if (d.collisionHideOnly) { if (d.className) { d.className = d.className + ' annotation-detect-collision'; } else { d.className = 'annotation-detect-collision'; } } }); let makeAnnotations = annotation().annotations(annotationData); let makeEditableAnnotations = annotation() .editMode(true) .annotations(annotationEditableData); if (!ignoreScales) { makeAnnotations = annotation() .accessors({ x: function(d) { return xScale(d[xAccessor]); }, y: function(d) { return yScale(d[yAccessor]); } }) .annotations(annotationData); makeEditableAnnotations = annotation() .editMode(true) .accessors({ x: function(d) { return xScale(d[xAccessor]); }, y: function(d) { return yScale(d[yAccessor]); } }) .annotations(annotationEditableData); } annotations.call(makeAnnotations); editable.call(makeEditableAnnotations); // checking if avoidCollision is set in any annotation object that user passed if (annotationData && annotationData.some(e => e.collisionHideOnly === true)) { hideOverlappingAnnotations(source, width, height, padding, margin, bitmaps); } if (annotationEditableData && annotationEditableData.some(e => e.collisionHideOnly === true)) { hideOverlappingAnnotations(source, width, height, padding, margin, bitmaps); } } // addStrokeUnder( // d3 // .select(source) // .selectAll('.vcl-annotation-group') // .selectAll('text'), // 'white' // ); } function resolveValue(d, scale, percentScale, shouldBeDate) { if (d) { if (d instanceof Array) { if (d.length === 1) { return checkZero(scale(checkDate(d[0], shouldBeDate))); } else if (d.length === 2) { return checkZero(scale(checkDate(d[0], shouldBeDate)) - scale(checkDate(d[1], shouldBeDate))); } } else if (typeof d === 'string' && d.substring(d.length - 1, d.length) === '%') { return checkZero(percentScale(+d.substring(0, d.length - 1))); } } return checkZero(d); } function checkZero(v) { if (v === 0) { return 0.000000001; } return v; } function checkDate(d, shouldCheck) { if (shouldCheck) { if (typeof d === 'object' && typeof d.getMonth === 'function') { return d; } return new Date(d); } return d; } function hideOverlappingAnnotations(source, width, height, padding, margin, bitmaps) { // now that we have annotated we can use existing bitmap to check for collisions // all annotation shapes are drawn as paths // circle.handle is used for edit mode, which we currently don't support // annotation-connector // path.connector // annotation-subject // path.subject // annotation-note // path.note-line // annotation-note-content // text.annotation-note-label // text.annotation-note-title // rect.annotation-note-bg const annotationsG = select(source) .select('.vcl-annotation-group') .select('.annotations'); annotationsG.selectAll('.annotation').style('visibility', null); annotationsG.selectAll('.annotation-detect-collision').each((_, i, n) => { // annotationsG.selectAll('.annotation').each((_, i, n) => { const me = n[i]; const annotationTransform = parseTransformSimple(select(me).attr('transform')); const annotationTranslate = (annotationTransform && annotationTransform['translate']) || [0, 0]; // we will need to address transforms on: // 1. g.annotation // 2. g.annotation-note // 3. g.annotation-note-content // 4. g.connector path.connector-end.connector-dot const annotationNoteTransform = select(me) .select('.annotation-note') .attr('transform') && parseTransformSimple( select(me) .select('.annotation-note') .attr('transform') ); const annotationNoteTranslate = (annotationNoteTransform && annotationNoteTransform['translate']) || [0, 0]; const annotationNoteContentTransform = select(me) .select('.annotation-note') .select('.annotation-note-content') .attr('transform') && parseTransformSimple( select(me) .select('.annotation-note') .select('.annotation-note-content') .attr('transform') ); const annotationNoteContentTranslate = (annotationNoteContentTransform && annotationNoteContentTransform['translate']) || [0, 0]; // first thing we can do is add data-d paths to draw all the annotation stuff to bitmap // paths will also need to handle the various transforms select(me) .selectAll('path') .each((_, i, n) => { const pathMe = select(n[i]); let translateX = annotationTranslate[0] + padding.left + margin.left; let translateY = annotationTranslate[1] + padding.top + margin.top; if (pathMe.classed('note-line')) { translateX += annotationNoteTranslate[0]; translateY += annotationNoteTranslate[1]; } pathMe .attr('data-d', pathMe.attr('d')) .attr('data-translate-x', translateX) .attr('data-translate-y', translateY); }); // next we need to try and handle our texts for the annotations // this assumes all text is in the note arena let maxDataWidth = 0; select(me) .selectAll('text') .each((_, i, n) => { const textElement = n[i]; const style = getComputedStyle(textElement); const fontSize = parseFloat(style.fontSize); const textHeight = Math.max(fontSize - 1, 1); // clone.getBBox().height; const textWidth = getTextWidth(textElement.textContent, fontSize, true, style.fontFamily); const textMe = select(textElement); const translateX = annotationTranslate[0] + annotationNoteTranslate[0] + annotationNoteContentTranslate[0] + padding.left + margin.left; const translateY = annotationTranslate[1] + annotationNoteTranslate[1] + annotationNoteContentTranslate[1] + padding.top + margin.top; maxDataWidth = Math.max(textWidth, maxDataWidth); textMe .attr('data-x', +textMe.attr('x') || 0) .attr('data-y', textHeight / 2 + +textMe.attr('y') || 0) .attr('data-ignore', textWidth === 0) .attr('data-width', textWidth) .attr('data-height', textHeight) .attr('data-translate-x', translateX) .attr('data-translate-y', translateY) .attr('data-no-text-anchor', true); }); // if we have no text we set this flag for visibility check later if (maxDataWidth === 0) { select(me).attr('data-no-text', true); } }); bitmaps = resolveLabelCollision({ bitmaps: bitmaps, labelSelection: select('.nothing-exists-here'), avoidMarks: [annotationsG.selectAll('.annotation-detect-collision').selectAll('path')], validPositions: ['middle'], offsets: [1], // offsets: [2, 2, 4, 2, 1, 1, 1, 1], accessors: ['cidx'], size: [roundTo(width, 0), roundTo(height, 0)] // we need the whole width for series labels }); bitmaps = resolveLabelCollision({ bitmaps: bitmaps, labelSelection: annotationsG.selectAll('.annotation-detect-collision text'), //.filter((_, i, n) => +select(n[i]).attr('data-width') > 0), avoidMarks: [], validPositions: ['middle'], offsets: [1], accessors: ['cidx'], size: [roundTo(width, 0), roundTo(height, 0)] // we need the whole width for series labels }); // now that we have hidden text, we need to hide the rest of the annotation annotationsG.selectAll('.annotation-detect-collision').each((_, i, n) => { const me = n[i]; let textShownIndicator = false; select(me) .selectAll('text') .each((_, i, n) => { const textElement = n[i]; const elementIndicator = select(textElement).attr('data-label-hidden') === 'false' && select(textElement).attr('data-ignore') === 'false'; textShownIndicator = textShownIndicator || elementIndicator; // if we already have a true, we need to keep it }); // this will flip visibility on the full element if we don't find any visible text if (textShownIndicator || select(me).attr('data-no-text') === 'true') { select(me).style('visibility', null); } else { select(me).style('visibility', 'hidden'); } }); } function parseTransformSimple(transform) { const result = {}; transform .trim() .replace(', ', ',') .split(' ') .forEach(transformation => { const step1 = transformation.split(')')[0].split(','); const step2 = step1[0].split('('); result[step2[0]] = []; result[step2[0]].push(+step2[1], +step1[1]); }); return result; }
the_stack
import { Component } from 'react' import { FormattedMessage } from 'react-intl' import { connect } from 'redaction' import { BigNumber } from 'bignumber.js' import erc20Like from 'common/erc20Like' import { feedback, externalConfig, constants, transactions, cacheStorageGet, cacheStorageSet, metamask, } from 'helpers' import actions from 'redux/actions' import Link from 'local_modules/sw-valuelink' import ModalForm from './ModalForm' type ComponentProps = { name: string allCurrencies: IUniversalObj[] tokensWallets: IUniversalObj[] } type ComponentState = { network: IUniversalObj currencies: IUniversalObj[] takerList: IUniversalObj[] makerWallet: IUniversalObj takerWallet: IUniversalObj makerAsset: IUniversalObj takerAsset: IUniversalObj makerAmount: string takerAmount: string wrongNetwork: boolean isPending: boolean needMakerApprove: boolean enoughSwapCurrencies: boolean } const noCurrenciesTemplate = [{ blockchain: '-', fullTitle: '-', name: '-', notExist: true, }] class LimitOrder extends Component<ComponentProps, ComponentState> { constructor(props) { super(props) const { allCurrencies } = props let { currencies, wrongNetwork } = actions.oneinch.filterCurrencies({ currencies: allCurrencies, onlyTokens: true, }) let enoughSwapCurrencies = true if (wrongNetwork || !currencies.length) { currencies = noCurrenciesTemplate if (!currencies.length) enoughSwapCurrencies = false } const makerAsset = currencies[0] const makerWallet = actions.core.getWallet({ currency: makerAsset.value }) const network = externalConfig.evmNetworks[makerAsset.blockchain || makerAsset.value.toUpperCase()] let takerList = this.returnTakerList(currencies, makerAsset) if (!takerList.length) { takerList = noCurrenciesTemplate enoughSwapCurrencies = false } const takerAsset = takerList[0] const takerWallet = actions.core.getWallet({ currency: takerAsset.value }) this.state = { network, wrongNetwork, currencies, takerList, makerWallet, takerWallet, makerAsset, takerAsset, makerAmount: '', needMakerApprove: false, takerAmount: '', isPending: false, enoughSwapCurrencies, } } componentDidUpdate(prevProps, prevState) { const { allCurrencies, tokensWallets } = this.props const { wrongNetwork: prevWrongNetwork, currencies: prevCurrencies } = prevState const { makerAsset } = this.state const isCurrentNetworkAvailable = metamask.isAvailableNetwork() const isMakerAssetNetworkAvailable = metamask.isAvailableNetworkByCurrency(makerAsset.value) const needUpdate = metamask.isConnected() && ( (prevWrongNetwork && (isMakerAssetNetworkAvailable || isCurrentNetworkAvailable)) || (!prevWrongNetwork && !isMakerAssetNetworkAvailable) ) if (needUpdate) { let { currencies, wrongNetwork } = actions.oneinch.filterCurrencies({ currencies: allCurrencies, tokensWallets, }) if (wrongNetwork) { currencies = prevCurrencies } let makerAsset = currencies[0] let takerList = this.returnTakerList(currencies, makerAsset) let takerAsset = takerList[0] this.setState(() => ({ wrongNetwork, currencies, makerAsset, takerList, takerAsset, network: externalConfig.evmNetworks[makerAsset.blockchain || makerAsset.value.toUpperCase()] })) } } reportError = (error) => { console.group('%c Create limit order', 'color: red;') console.error(error) console.groupEnd() actions.notifications.show(constants.notifications.ErrorNotification, { error: error.message, }) feedback.oneinch.failed(error.message) } updateNetwork = () => { const { makerAsset } = this.state this.setState(() => ({ network: externalConfig.evmNetworks[makerAsset.blockchain || makerAsset.value.toUpperCase()], })) } returnTakerList = (currencies, makerAsset) => { return currencies.filter( (item) => item.blockchain === makerAsset.blockchain && item.value !== makerAsset.value ) } updateTakerList = () => { const { allCurrencies } = this.props const { makerAsset, currencies } = this.state const takerList = this.returnTakerList(currencies, makerAsset) if (!takerList.length) { this.setState(() => ({ takerList: allCurrencies, enoughSwapCurrencies: false, })) } else { this.setState(() => ({ takerList, takerAsset: takerList[0], takerAmount: '0', takerWallet: actions.core.getWallet({ currency: takerList[0].value }), enoughSwapCurrencies: true, })) } } approve = async (wallet, amount) => { this.setState(() => ({ isPending: true, })) try { const hash = await actions[wallet.standard].approve({ to: externalConfig.limitOrder[wallet.baseCurrency.toLowerCase()], name: wallet.tokenKey, amount, }) actions.notifications.show(constants.notifications.Transaction, { link: transactions.getLink(wallet.baseCurrency.toLowerCase(), hash), completed: true, }) cacheStorageSet('limitOrderAllowance', wallet.tokenKey, amount, Infinity) this.checkMakerAllowance() this.checkTakerAllowance() } catch (error) { this.reportError(error) } finally { this.setState(() => ({ isPending: false, })) } } createLimitOrder = async () => { const { name } = this.props const { network, makerWallet, takerWallet, makerAmount, takerAmount } = this.state this.setState(() => ({ isPending: true, })) try { const response: any = await actions.oneinch.createLimitOrder({ chainId: network.networkVersion, baseCurrency: makerWallet.baseCurrency.toLowerCase(), makerAddress: makerWallet.address, makerAssetAddress: makerWallet.contractAddress, makerAssetDecimals: makerWallet.decimals, takerAssetAddress: takerWallet.contractAddress, takerAssetDecimals: takerWallet.decimals, makerAmount, takerAmount, }) this.decreaseAllowance(makerWallet, makerAmount) this.decreaseAllowance(takerWallet, takerAmount) if (response && response.success) { await actions.oneinch.fetchLatestLimitOrder({ chainId: network.networkVersion, owner: makerWallet.address, }) actions.modals.close(name) actions.notifications.show(constants.notifications.Message, { message: ( <FormattedMessage id="limitOrderCreated" defaultMessage="You have successfully created the order" /> ), }) } else { actions.notifications.show(constants.notifications.Message, { message: ( <FormattedMessage id="limitOrderIsNotCreated" defaultMessage="Something went wrong. Try again later" /> ), }) } } catch (error) { this.reportError(error) } finally { this.setState(() => ({ isPending: false, })) } } selectMakerAsset = async (value) => { const makerWallet = actions.core.getWallet({ currency: value.value }) this.setState( () => ({ makerAsset: value, makerWallet, }), () => { this.checkMakerAllowance() this.updateNetwork() this.updateTakerList() } ) } selectTakerAsset = (value) => { const takerWallet = actions.core.getWallet({ currency: value.value }) this.setState( () => ({ takerAsset: value, takerWallet, }), () => { this.checkTakerAllowance() } ) } decreaseAllowance = (wallet, amount) => { const oldAllowance: any = cacheStorageSet( 'limitOrderAllowance', wallet.tokenKey, amount, Infinity ) cacheStorageSet( 'limitOrderAllowance', wallet.tokenKey, new BigNumber(oldAllowance).minus(amount), Infinity ) } checkMakerAllowance = async () => { const { makerWallet, makerAmount } = this.state let allowance = cacheStorageGet('limitOrderAllowance', makerWallet.tokenKey) if (!allowance) { allowance = await this.fetchTokenAllowance(makerWallet) } this.setState(() => ({ needMakerApprove: new BigNumber(allowance).isLessThan(makerAmount), })) } checkTakerAllowance = async () => { const { takerWallet, takerAmount } = this.state let allowance = cacheStorageGet('limitOrderAllowance', takerWallet.tokenKey) if (!allowance) { allowance = await this.fetchTokenAllowance(takerWallet) } } fetchTokenAllowance = async (wallet) => { return await erc20Like[wallet.standard].checkAllowance({ owner: wallet.address, spender: externalConfig.limitOrder[wallet.baseCurrency.toLowerCase()], contract: wallet.contractAddress, decimals: wallet.decimals, }) } areWrongOrderParams = () => { const { makerAmount, takerAmount, makerWallet } = this.state const isWrongAmount = (amount) => { return new BigNumber(amount).isNaN() || new BigNumber(amount).isEqualTo(0) } return ( isWrongAmount(makerAmount) || isWrongAmount(takerAmount) || new BigNumber(makerWallet.balance).isLessThan(makerAmount) ) } render() { const { name } = this.props const { currencies, takerList, makerAsset, takerAsset, makerWallet, takerWallet, isPending, needMakerApprove, enoughSwapCurrencies, wrongNetwork, } = this.state const linked = Link.all(this, 'makerAmount', 'takerAmount') const blockCreation = this.areWrongOrderParams() || !enoughSwapCurrencies || isPending // TODO: how to calculate the tx cost for token approvement ? // FIXME: don't let an user to start approvement without balance const blockApprove = blockCreation // || new BigNumber(makerWallet.balance).isLessThan(0) return ( <ModalForm wrongNetwork={wrongNetwork} enoughSwapCurrencies={enoughSwapCurrencies} modalName={name} stateReference={linked} availableCurrencies={currencies} takerList={takerList} makerAsset={makerAsset} makerWallet={makerWallet} takerAsset={takerAsset} takerWallet={takerWallet} blockApprove={blockApprove} blockCreation={blockCreation} isPending={isPending} selectMakerAsset={this.selectMakerAsset} checkMakerAllowance={this.checkMakerAllowance} checkTakerAllowance={this.checkTakerAllowance} needMakerApprove={needMakerApprove} selectTakerAsset={this.selectTakerAsset} approve={this.approve} createOrder={this.createLimitOrder} /> ) } } export default connect(({ currencies, user }) => ({ allCurrencies: currencies.items, activeFiat: user.activeFiat, }))(LimitOrder)
the_stack
import * as aws from "@pulumi/aws"; import * as lambda from "@pulumi/aws/lambda"; import * as awsx from "@pulumi/awsx"; import * as cloud from "@pulumi/cloud"; import * as pulumi from "@pulumi/pulumi"; import { RunError } from "@pulumi/pulumi/errors"; import { createCallbackFunction } from "./function"; import { Endpoint } from "./service"; import { sha1hash } from "./utils"; // StaticRoute is a registered static file route, backed by an S3 bucket. export interface StaticRoute { path: string; localPath: string; options: cloud.ServeStaticOptions; } // ProxyRoute is a registered proxy route, proxying to either a URL or cloud.Endpoint. export interface ProxyRoute { path: string; target: string | pulumi.Output<cloud.Endpoint>; } // Route is a registered dynamic route, backed by a serverless Lambda. export interface Route { method: string; path: string; handlers: cloud.RouteHandler[]; } // AWSDomain represents a domain with an SSL/TLS certificate available in AWS. // The certificate must be in the us-east-1 region. export interface AWSDomain { domainName: string; certificateArn: pulumi.Input<string>; } // Domain represents a hosted domain and associated SSL/TLS certificates. export type Domain = cloud.Domain | AWSDomain; // Helper to test whether the Domain is a cloud.Domain or an AWS-specific Domain. function isCloudDomain(domain: Domain): domain is cloud.Domain { return (domain as cloud.Domain).certificateBody !== undefined; } export class API implements cloud.API { private readonly name: string; private readonly staticRoutes: StaticRoute[]; private readonly proxyRoutes: ProxyRoute[]; private readonly routes: Route[]; private readonly customDomains: Domain[]; public deployment?: HttpDeployment; constructor(name: string) { this.name = name; this.staticRoutes = []; this.proxyRoutes = []; this.routes = []; this.customDomains = []; } public static(path: string, localPath: string, options?: cloud.ServeStaticOptions) { if (!path.startsWith("/")) { path = "/" + path; } this.staticRoutes.push({ path, localPath, options: options || {} }); } public proxy(path: string, target: string | pulumi.Output<cloud.Endpoint>) { if (!path.startsWith("/")) { path = "/" + path; } this.proxyRoutes.push({ path, target }); } public route(method: string, path: string, ...handlers: cloud.RouteHandler[]) { if (!path.startsWith("/")) { path = "/" + path; } this.routes.push({ method: method, path: path, handlers: handlers }); } public get(path: string, ...handlers: cloud.RouteHandler[]) { this.route("GET", path, ...handlers); } public put(path: string, ...handlers: cloud.RouteHandler[]) { this.route("PUT", path, ...handlers); } public post(path: string, ...handlers: cloud.RouteHandler[]) { this.route("POST", path, ...handlers); } public delete(path: string, ...handlers: cloud.RouteHandler[]) { this.route("DELETE", path, ...handlers); } public options(path: string, ...handlers: cloud.RouteHandler[]) { this.route("OPTIONS", path, ...handlers); } public all(path: string, ...handlers: cloud.RouteHandler[]) { this.route("ANY", path, ...handlers); } public attachCustomDomain(domain: Domain): void { this.customDomains.push(domain); } public publish(): HttpDeployment { if (this.deployment) { throw new RunError("This endpoint is already published and cannot be re-published."); } // Create a unique name prefix that includes the name plus all the registered routes. this.deployment = new HttpDeployment( this.name, this.staticRoutes, this.proxyRoutes, this.routes, this.customDomains); return this.deployment; } } // HttpDeployment actually performs a deployment of a set of HTTP API Gateway resources. export class HttpDeployment extends pulumi.ComponentResource implements cloud.HttpDeployment { public readonly staticRoutes: StaticRoute[]; public readonly proxyRoutes: ProxyRoute[]; public readonly routes: Route[]; public /*out*/ readonly api: awsx.apigateway.API; public /*out*/ readonly url: pulumi.Output<string>; // the URL for this deployment. public /*out*/ readonly customDomainNames: pulumi.Output<string>[]; // any custom domain names. public /*out*/ readonly customDomains: aws.apigateway.DomainName[]; // AWS DomainName objects for custom domains. private static registerCustomDomains(parent: pulumi.Resource, apiName: string, api: aws.apigateway.RestApi, domains: Domain[]): aws.apigateway.DomainName[] { const awsDomains: aws.apigateway.DomainName[] = []; for (const domain of domains) { // Ensure this pair of api-domain name doesn't conflict with anything else. i.e. there // may be another http endpoint that registers a custom domain with a different data. // We don't want to collide with that. hash the name to ensure this urn doesn't get too // long. const domainNameHash = sha1hash(domain.domainName); const apiNameAndHash = `${apiName}-${domainNameHash}`; let domainArgs: aws.apigateway.DomainNameArgs; if (isCloudDomain(domain)) { domainArgs = { domainName: domain.domainName, certificateName: domain.domainName, certificateBody: domain.certificateBody, certificatePrivateKey: domain.certificatePrivateKey, certificateChain: domain.certificateChain, }; } else { domainArgs = { domainName: domain.domainName, certificateArn: domain.certificateArn, }; } const awsDomain = new aws.apigateway.DomainName(apiNameAndHash, domainArgs, {parent}); const basePathMapping = new aws.apigateway.BasePathMapping(apiNameAndHash, { restApi: api, stageName: stageName, domainName: awsDomain.domainName, }, {parent}); awsDomains.push(awsDomain); } return awsDomains; } constructor(name: string, staticRoutes: StaticRoute[], proxyRoutes: ProxyRoute[], routes: Route[], customDomains: Domain[], opts?: pulumi.ResourceOptions) { super("cloud:http:API", name, { }, opts); this.staticRoutes = staticRoutes; this.proxyRoutes = proxyRoutes; this.routes = routes; this.api = new awsx.apigateway.API(name, { routes: [ ...staticRoutes.map(convertStaticRoute), ...proxyRoutes.map(r => convertProxyRoute(name, this, r)), ...routes.map(r => convertRoute(name, r, { parent: this })), ], }, { parent: this }); // If there are any custom domains, attach them now. const awsDomains: aws.apigateway.DomainName[] = HttpDeployment.registerCustomDomains(this, name, this.api.restAPI, customDomains); // Finally, manufacture a URL and set it as an output property. this.url = this.api.url; this.customDomainNames = awsDomains.map(awsDomain => awsDomain.cloudfrontDomainName); this.customDomains = awsDomains; this.registerOutputs({ api: this.api, url: this.url, staticRoutes: staticRoutes, proxyRoutes: proxyRoutes, routes: routes, customDomainNames: this.customDomainNames, customDomains: this.customDomainNames, }); } } function convertStaticRoute(route: StaticRoute): awsx.apigateway.StaticRoute { const options = route.options || {}; return { path: route.path, localPath: route.localPath, contentType: options.contentType, index: options.index, }; } function convertProxyRoute(name: string, api: HttpDeployment, route: ProxyRoute): awsx.apigateway.IntegrationRoute { return { path: route.path, target: convertProxyRouteTarget(name, api, route), }; } function convertProxyRouteTarget(name: string, api: HttpDeployment, route: ProxyRoute): pulumi.Input<awsx.apigateway.IntegrationTarget> { const target = route.target; if (typeof target === "string") { let result = target; // ensure there is a trailing `/` if (!result.endsWith("/")) { result += "/"; } return { uri: result, type: "http_proxy", connectionId: undefined, connectionType: undefined }; } const targetArn = target.apply(ep => { const endpoint = ep as Endpoint; if (!endpoint.loadBalancer) { throw new pulumi.ResourceError("AWS endpoint proxy requires an AWS Endpoint", api); } return endpoint.loadBalancer.loadBalancerType.apply(loadBalancerType => { if (loadBalancerType === "application") { // We can only support proxying to an Endpoint if it is backed by an // NLB, which will only be the case for cloud.Service ports exposed as // type "tcp". throw new pulumi.ResourceError( "AWS endpoint proxy requires an Endpoint on a service port of type 'tcp'", api); } return endpoint.loadBalancer.arn; }); }); const vpcLink = new aws.apigateway.VpcLink(name + sha1hash(route.path), { targetArn: targetArn, }, { parent: api }); return { uri: pulumi.interpolate`http://${target.hostname}:${target.port}/`, type: "http_proxy", connectionType: "VPC_LINK", connectionId: vpcLink.id, }; } function convertRoute(name: string, route: Route, opts: pulumi.ResourceOptions): awsx.apigateway.Route { return { method: <awsx.apigateway.Method>route.method, path: route.path, eventHandler: convertHandlers(name, route, opts), }; } function convertHandlers(name: string, route: Route, opts: pulumi.ResourceOptions): lambda.Function { const handlers = route.handlers; const callback: lambda.Callback<awsx.apigateway.Request, awsx.apigateway.Response> = (ev, ctx, cb) => { let body: Buffer; if (ev.body !== null) { if (ev.isBase64Encoded) { body = Buffer.from(ev.body, "base64"); } else { body = Buffer.from(ev.body, "utf8"); } } else { body = Buffer.from([]); } ctx.callbackWaitsForEmptyEventLoop = false; const [req, res] = apiGatewayToRequestResponse(ev, body, cb); let i = 0; const next = () => { const nextHandler = handlers[i++]; if (nextHandler !== undefined) { nextHandler(req, res, next); } }; next(); }; const routeName = name + sha1hash(route.method + ":" + route.path); // Create the CallbackFunction in the cloud layer as opposed to just passing 'callback' as-is to // apigateway.x.API to do it. This ensures that the right configuration values are used that // will appropriately respect user settings around things like codepaths/policies etc. const callbackFunction = createCallbackFunction( routeName, callback, /*isFactoryFunction:*/ false, opts); return callbackFunction; } const stageName = "stage"; function apiGatewayToRequestResponse( ev: awsx.apigateway.Request, body: Buffer, cb: (err: any, result: awsx.apigateway.Response) => void): [cloud.Request, cloud.Response] { const response = { statusCode: 200, headers: <{[header: string]: string}>{}, body: Buffer.from([]), }; const headers: { [name: string]: string; } = {}; const rawHeaders: string[] = []; // Lowercase all header names to align with Node.js HTTP request behaviour, // and create the `rawHeaders` array to maintain access to raw header data. if (ev.headers) { for (const [name, header] of Object.entries(ev.headers)) { if (header) { headers[name.toLowerCase()] = header; rawHeaders.push(name); rawHeaders.push(header); } } } const params: { [param: string]: string } = {}; if (ev.pathParameters) { for (const [name, param] of Object.entries(ev.pathParameters)) { if (param) { params[name] = param; } } } const query: { [query: string]: string } = {}; if (ev.queryStringParameters) { for (const [name, param] of Object.entries(ev.queryStringParameters)) { if (param) { query[name] = param; } } } // Always add `content-length` header, as this is stripped by API Gateway headers["content-length"] = body.length.toString(); const req: cloud.Request = { headers: headers, rawHeaders: rawHeaders, body: body, method: ev.httpMethod, params: params, query: query, path: ev.path, baseUrl: "/" + stageName, hostname: headers["host"], protocol: headers["x-forwarded-proto"], }; const res: cloud.Response = { locals: {}, status: (code: number) => { response.statusCode = code; return res; }, getHeader: (name: string) => { return response.headers![name]; }, setHeader: (name: string, value: string) => { response.headers![name] = value; return res; }, write: (data: string | Buffer, encoding?: string) => { if (encoding === undefined) { encoding = "utf8"; } if (typeof data === "string") { data = Buffer.from(data, encoding); } response.body = Buffer.concat([response.body, data]); return res; }, end: (data?: string | Buffer, encoding?: string) => { if (data !== undefined) { res.write(data, encoding); } cb(null, { statusCode: response.statusCode, headers: response.headers, isBase64Encoded: true, body: response.body.toString("base64"), }); }, json: (obj: any) => { res.setHeader("content-type", "application/json"); const seen = new WeakSet(); res.end(JSON.stringify(obj, (_, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; })); }, redirect: (arg1: string | number, arg2?: string) => { // Support two overloads: // - redirect(url: string): void; // - redirect(status: number, url: string): void; let code: number; let url: string; if (typeof arg1 === "string") { code = 302; url = arg1; } else { code = arg1; url = arg2!; } res.status(code); res.setHeader("Location", url); res.end(); }, }; return [req, res]; } /** * @deprecated HttpEndpoint has been renamed to API */ export type HttpEndpoint = API; /** * @deprecated HttpEndpoint has been renamed to API */ export let HttpEndpoint = API; // tslint:disable-line
the_stack
import { mXparserConstants } from '../mXparserConstants'; import { java } from 'j4ts/j4ts'; import { javaemul } from 'j4ts/j4ts'; import { SpecialFunctions } from './SpecialFunctions'; import { MathConstants } from './MathConstants'; import { MathFunctions } from './MathFunctions'; /** * ProbabilityDistributions - random number generators, PDF - Probability Distribution Functions, * CDF - Cumulative Distribution Functions, QNT - Quantile Functions (Inverse Cumulative Distribution * Functions). * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * * @version 4.3.0 * @class */ export class ProbabilityDistributions { /** * java.util.Random number generator */ public static randomGenerator: java.util.Random; public static randomGenerator_$LI$(): java.util.Random { if (ProbabilityDistributions.randomGenerator == null) { ProbabilityDistributions.randomGenerator = new java.util.Random(); } return ProbabilityDistributions.randomGenerator; } public static rndUniformContinuous$double$double$java_util_Random(a: number, b: number, rnd: java.util.Random): number { if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN; if (b < a)return javaemul.internal.DoubleHelper.NaN; if (a === b)return a; const r: number = a + rnd.nextDouble() * (b - a); return r; } /** * java.util.Random number from Uniform Continuous distribution over interval [a, b). * * @param {number} a Interval limit - left / lower. * @param {number} b Interval limit - right / upper. * @param {Random} rnd java.util.Random number generator. * @return {number} Double.NaN if a or b is null, or b is lower than a - * otherwise returns random number. */ public static rndUniformContinuous(a?: any, b?: any, rnd?: any): any { if (((typeof a === 'number') || a === null) && ((typeof b === 'number') || b === null) && ((rnd != null && rnd instanceof <any>java.util.Random) || rnd === null)) { return <any>ProbabilityDistributions.rndUniformContinuous$double$double$java_util_Random(a, b, rnd); } else if (((typeof a === 'number') || a === null) && ((typeof b === 'number') || b === null) && rnd === undefined) { return <any>ProbabilityDistributions.rndUniformContinuous$double$double(a, b); } else if (((a != null && a instanceof <any>java.util.Random) || a === null) && b === undefined && rnd === undefined) { return <any>ProbabilityDistributions.rndUniformContinuous$java_util_Random(a); } else throw new Error('invalid overload'); } public static rndUniformContinuous$double$double(a: number, b: number): number { return ProbabilityDistributions.rndUniformContinuous$double$double$java_util_Random(a, b, ProbabilityDistributions.randomGenerator_$LI$()); } public static rndUniformContinuous$java_util_Random(rnd: java.util.Random): number { return rnd.nextDouble(); } /** * java.util.Random number from Uniform Continuous distribution over interval [0, 1). * * @return {number} java.util.Random number. */ public static randomUniformContinuous(): number { return ProbabilityDistributions.rndUniformContinuous$java_util_Random(ProbabilityDistributions.randomGenerator_$LI$()); } /** * PDF - Probability Distribution Function - Uniform Continuous distribution * over interval [a, b). * * @param {number} x Point to evaluate pdf function. * @param {number} a Interval limit - left / lower. * @param {number} b Interval limit - right / upper. * @return {number} Double.NaN if a or b is null, or b is lower than a - * otherwise function value. */ public static pdfUniformContinuous(x: number, a: number, b: number): number { if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN; if (b < a)return javaemul.internal.DoubleHelper.NaN; if (a === b){ if (x === a)return 1; else return 0; } if ((x < a) || (x > b))return 0; if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return 0.0; if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 0.0; return 1.0 / (b - a); } /** * CDF - Cumulative Distribution Function - Uniform Continuous distribution * over interval [a, b). * * @param {number} x Point to evaluate cdf function. * @param {number} a Interval limit - left / lower. * @param {number} b Interval limit - right / upper. * @return {number} Double.NaN if a or b is null, or b is lower than a - * otherwise function value. */ public static cdfUniformContinuous(x: number, a: number, b: number): number { if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN; if (b < a)return javaemul.internal.DoubleHelper.NaN; if (a === b){ if (x < a)return 0.0; else return 1.0; } if (x < a)return 0.0; if (x >= b)return 1.0; if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return 0.0; if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 1.0; return (x - a) / (b - a); } /** * QNT - Quantile Function - Uniform Continuous distribution over interval [a, b). * (Inverse of Cumulative Distribution Function). * * @param {number} q Quantile. * @param {number} a Interval limit - left / lower. * @param {number} b Interval limit - right / upper. * @return {number} Double.NaN if a or b is null, or b is lower than a * or q is lower than 0 or q is greater than 1 - * otherwise function value. */ public static qntUniformContinuous(q: number, a: number, b: number): number { if (/* isNaN */isNaN(q))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN; if ((q < 0.0) || (q > 1.0))return javaemul.internal.DoubleHelper.NaN; if (b < a)return javaemul.internal.DoubleHelper.NaN; if (a === b){ if (q === 1.0)return b; else return javaemul.internal.DoubleHelper.NaN; } if (q === 0.0)return a; if (q === 1.0)return b; return a + q * (b - a); } public static rndInteger$int$int$java_util_Random(a: number, b: number, rnd: java.util.Random): number { if (/* isNaN */isNaN(a))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(b))return javaemul.internal.DoubleHelper.NaN; if (b < a)return javaemul.internal.DoubleHelper.NaN; if (a === b)return a; const n: number = (b - a) + 1; const r: number = a + rnd.nextInt(n); return r; } /** * java.util.Random number from Uniform Discrete distribution. * over set interval (a, a+1, ..., b-1, b). * * @param {number} a Interval limit - left / lower. * @param {number} b Interval limit - right / upper. * @param {Random} rnd java.util.Random number generator. * @return {number} Double.NaN if a or b is null, or b is lower than a - * otherwise returns random number. */ public static rndInteger(a?: any, b?: any, rnd?: any): any { if (((typeof a === 'number') || a === null) && ((typeof b === 'number') || b === null) && ((rnd != null && rnd instanceof <any>java.util.Random) || rnd === null)) { return <any>ProbabilityDistributions.rndInteger$int$int$java_util_Random(a, b, rnd); } else if (((typeof a === 'number') || a === null) && ((typeof b === 'number') || b === null) && rnd === undefined) { return <any>ProbabilityDistributions.rndInteger$int$int(a, b); } else if (((a != null && a instanceof <any>java.util.Random) || a === null) && b === undefined && rnd === undefined) { return <any>ProbabilityDistributions.rndInteger$java_util_Random(a); } else if (a === undefined && b === undefined && rnd === undefined) { return <any>ProbabilityDistributions.rndInteger$(); } else throw new Error('invalid overload'); } public static rndInteger$int$int(a: number, b: number): number { return ProbabilityDistributions.rndInteger$int$int$java_util_Random(a, b, ProbabilityDistributions.randomGenerator_$LI$()); } public static rndInteger$java_util_Random(rnd: java.util.Random): number { return rnd.nextInt(); } public static rndIndex$int$java_util_Random(n: number, rnd: java.util.Random): number { if (n < 0)return -1; return rnd.nextInt(n); } /** * java.util.Random index from 0 to n-1, * * @param {number} n Bound. * @param {Random} rnd java.util.Random number generator. * @return {number} if n &lt; 0 returns -1, otherwise random index. */ public static rndIndex(n?: any, rnd?: any): any { if (((typeof n === 'number') || n === null) && ((rnd != null && rnd instanceof <any>java.util.Random) || rnd === null)) { return <any>ProbabilityDistributions.rndIndex$int$java_util_Random(n, rnd); } else if (((typeof n === 'number') || n === null) && rnd === undefined) { return <any>ProbabilityDistributions.rndIndex$int(n); } else throw new Error('invalid overload'); } public static rndIndex$int(n: number): number { if (n < 0)return -1; return ProbabilityDistributions.randomGenerator_$LI$().nextInt(n); } public static rndInteger$(): number { return ProbabilityDistributions.rndInteger$java_util_Random(ProbabilityDistributions.randomGenerator_$LI$()); } public static rndNormal$double$double$java_util_Random(mean: number, stddev: number, rnd: java.util.Random): number { if (/* isNaN */isNaN(mean))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(stddev))return javaemul.internal.DoubleHelper.NaN; if (rnd == null)return javaemul.internal.DoubleHelper.NaN; if (stddev < 0)return javaemul.internal.DoubleHelper.NaN; if (stddev === 0)return mean; let x: number; let a: number; let v1: number; let b: number; let v2: number; let r: number; let fac: number; let polarTransform: boolean; do {{ if (mXparserConstants.isCurrentCalculationCancelled())return javaemul.internal.DoubleHelper.NaN; a = rnd.nextDouble(); b = rnd.nextDouble(); v1 = 2.0 * a - 1.0; v2 = 2.0 * b - 1.0; r = (v1 * v1) + (v2 * v2); if (r >= 1.0 || r === 0.0){ x = 0.0; polarTransform = false; } else { fac = MathFunctions.sqrt(-2.0 * MathFunctions.ln(r) / r); x = v1 * fac; polarTransform = true; } }} while((!polarTransform)); return mean + (stddev * x); } /** * java.util.Random number from normal distribution N(mean, stddev). * * @param {number} mean Mean value. * @param {number} stddev Standard deviation. * @param {Random} rnd java.util.Random number generator. * @return {number} Double.NaN if mean or stddev or rnd is null or stddev is lower than 0 - * otherwise random number. */ public static rndNormal(mean?: any, stddev?: any, rnd?: any): any { if (((typeof mean === 'number') || mean === null) && ((typeof stddev === 'number') || stddev === null) && ((rnd != null && rnd instanceof <any>java.util.Random) || rnd === null)) { return <any>ProbabilityDistributions.rndNormal$double$double$java_util_Random(mean, stddev, rnd); } else if (((typeof mean === 'number') || mean === null) && ((typeof stddev === 'number') || stddev === null) && rnd === undefined) { return <any>ProbabilityDistributions.rndNormal$double$double(mean, stddev); } else throw new Error('invalid overload'); } public static rndNormal$double$double(mean: number, stddev: number): number { return ProbabilityDistributions.rndNormal$double$double$java_util_Random(mean, stddev, ProbabilityDistributions.randomGenerator_$LI$()); } /** * PDF - Probability Distribution Function - Normal distribution N(mean, stddev). * * @param {number} x Point to evaluate pdf function. * @param {number} mean Mean value. * @param {number} stddev Standard deviation. * @return {number} Double.NaN if mean or stddev is null or stddev is lower than 0 - * otherwise function value. */ public static pdfNormal(x: number, mean: number, stddev: number): number { if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(mean))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(stddev))return javaemul.internal.DoubleHelper.NaN; if (stddev < 0)return javaemul.internal.DoubleHelper.NaN; if (stddev === 0){ if (x === mean)return 1.0; else return 0; } if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return 0.0; if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 0.0; const d: number = (x - mean) / stddev; return MathFunctions.exp(-0.5 * d * d) / (MathConstants.SQRT2Pi * stddev); } /** * CDF - Cumulative Distribution Function - Normal distribution N(mean, stddev). * * @param {number} x Point to evaluate pdf function. * @param {number} mean Mean value. * @param {number} stddev Standard deviation. * @return {number} Double.NaN if mean or stddev is null or stddev is lower than 0 - * otherwise function value. */ public static cdfNormal(x: number, mean: number, stddev: number): number { if (/* isNaN */isNaN(x))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(mean))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(stddev))return javaemul.internal.DoubleHelper.NaN; if (stddev < 0)return javaemul.internal.DoubleHelper.NaN; if (stddev === 0){ if (x < mean)return 0.0; else return 1.0; } if (x === javaemul.internal.DoubleHelper.NEGATIVE_INFINITY)return 0.0; if (x === javaemul.internal.DoubleHelper.POSITIVE_INFINITY)return 1.0; return 0.5 * SpecialFunctions.erfc((mean - x) / (stddev * MathConstants.SQRT2_$LI$())); } /** * QNT - Quantile Function - Normal distribution N(mean, stddev). * (Inverse of Cumulative Distribution Function). * * @param {number} q Quantile. * @param {number} mean Mean value. * @param {number} stddev Standard deviation. * @return {number} Double.NaN if mean or stddev is null or stddev is lower than 0 * or q is lower than 0 or q is greater than 1 - * otherwise function value. */ public static qntNormal(q: number, mean: number, stddev: number): number { if (/* isNaN */isNaN(q))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(mean))return javaemul.internal.DoubleHelper.NaN; if (/* isNaN */isNaN(stddev))return javaemul.internal.DoubleHelper.NaN; if ((q < 0.0) || (q > 1.0))return javaemul.internal.DoubleHelper.NaN; if (stddev < 0)return javaemul.internal.DoubleHelper.NaN; if (stddev === 0){ if (q === 1.0)return mean; else return javaemul.internal.DoubleHelper.NaN; } if (q === 0.0)return javaemul.internal.DoubleHelper.NEGATIVE_INFINITY; if (q === 1.0)return javaemul.internal.DoubleHelper.POSITIVE_INFINITY; return mean - (stddev * MathConstants.SQRT2_$LI$() * SpecialFunctions.erfcInv(2.0 * q)); } } ProbabilityDistributions["__class"] = "org.mariuszgromada.math.mxparser.mathcollection.ProbabilityDistributions";
the_stack
import { Component, HostBinding } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { slideInUpAnimation } from '../../../../app.animations'; import { copyToClipboard, formatJSON, convertObjectsToCSV, convertCSVToJSON, downloadCSV, downloadJSON, downloadObjectsToCSV, downloadObjectsToJSON, downloadFile, readFile, } from '../../../../../platform/core/common'; @Component({ selector: 'td-functions', templateUrl: './functions.component.html', styleUrls: ['./functions.component.scss'], animations: [slideInUpAnimation], }) export class FunctionsDemoComponent { @HostBinding('@routeAnimation') routeAnimation: boolean = true; @HostBinding('class.td-route-animation') classAnimation: boolean = true; copyText: string = 'Lorem Ipsum'; objects: object[] = [ { name: 'user1', id: 123 }, { name: 'user2', id: 234 }, ]; objectsString: string; csvOutput: string = ''; csv: string = 'name,id\r\nuser1,123\r\nuser2,234\r\n'; jsonOutput: string = ''; json: string = '[{"name":"user1","id":"123"},{"name":"user2","id":"234"}]'; fileName: string = 'sample.txt'; fileContent: string = 'Lorem Ipsum'; mimeType: string = 'text/plain'; readFileContent: string = ''; clipboardCodeHtml: string = ` <form> <div layout="row"> <mat-form-field flex> <textarea matInput [(ngModel)]="copyText" placeholder="Text to be copied" rows="1" name="copyTextinput"></textarea> </mat-form-field> </div> </form> <button mat-raised-button color="none" (click)="doCopyToClipboard()" class="text-upper"> Copy To Clipboard </button> `; clipboardCodeTypescript: string = ` import { copyToClipboard } from '@covalent/core/common' export class FunctionsDemoComponent { copyText: string = 'Lorem Ipsum'; constructor(private _snackBar: MatSnackBar) {} doCopyToClipboard(): void { // Invoke utility function to copy input text to clipboard copyToClipboard(this.copyText); // Show snackbar to indicate task complete this._snackBar.open('Text copied!', undefined, { duration: 2000, }); } } `; convertCodeHtml: string = ` <h4>Input CSV:</h4> <td-highlight [content]="csv"></td-highlight> <button mat-raised-button color="none" (click)="doConvertCSVToJSON()" class="text-upper push-top-sm"> Convert CSV </button> <h4>Output JSON:</h4> <td-highlight [content]="jsonOutput"></td-highlight> <h4>Input Objects:</h4> <td-highlight [content]="objectsString"></td-highlight> <button mat-raised-button color="none" (click)="doConvertObjectsToCSV()" class="text-upper push-top-sm"> Convert Objects </button> <h4>Output CSV:</h4> <td-highlight[content]="csvOutput"></td-highlight> `; convertCodeTypescript: string = ` import { convertCSVToJSON, convertObjectsToCSV } from '@covalent/core/common' export class FunctionsDemoComponent { csv: string = 'name,id\r\nuser1,123\r\nuser2,234\r\n'; jsonOutput: string = ''; objects: object[] = [ { 'name': 'user1', 'id': 123 }, { 'name': 'user2', 'id': 234 } ]; objectsString: string; csvOutput: string = ''; constructor(private _snackBar: MatSnackBar) { this.objectsString = JSON.stringify(this.objects, undefined, 2); } doConvertCSVToJSON(): void { // Invoke utility function to CSV value using // comma as the key separator and carriage return line feed // as the line separator into JSON format. Use two space // indent to prettify output JSON. this.jsonOutput = convertCSVToJSON(this.csv,',','\r\n',2); // Show snackbar to indicate task complete this._snackBar.open('Objects converted!', undefined, { duration: 2000, }); } doConvertObjectsToCSV(): void { // Invoke utility function to convert objects array using // comma as the key separator and carriage return line feed // as the line separator. this.csvOutput = convertObjectsToCSV(this.objects,',','\r\n'); // Show snackbar to indicate task complete this._snackBar.open('Objects converted!', undefined, { duration: 2000, }); } } `; downloadCodeHtml: string = ` <h4>CSV:</h4> <td-highlight [content]="csv"></td-highlight> <button mat-raised-button color="none" (click)="doDownloadCSV()" class="text-upper push-top-sm"> Download CSV </button> <h4>JSON:</h4> <td-highlight [content]="json"></td-highlight> <button mat-raised-button color="none" (click)="doDownloadJSON()" class="text-upper push-top-sm"> Download JSON </button> <h4>Objects:</h4> <td-highlight [content]="objectsString"></td-highlight> <button mat-raied-button color="none" (click)="doDownloadObjectsToCSV()" class="text-upper push-top-sm"> Download To CSV </button> <h4>Objects:</h4> <td-highlight [content]="objectsString"></td-highlight> <button mat-raised-button color="none" (click)="doDownloadObjectsToJSON()" class="text-upper push-top-sm"> Download To JSON </button> <form> <div layout="column"> <mat-form-field flex> <input matInput [(ngModel)]="fileName" placeholder="File name" rows="1" name="fileNameInput"> </mat-form-field> <mat-form-field flex> <textarea matInput [(ngModel)]="fileContent" placeholder="File content" rows="1" name="fileContentInput"></textarea> </mat-form-field> <mat-form-field flex> <input matInput [(ngModel)]="mimeType" placeholder="Mime type" rows="1" name="mimeTypeInput"> </mat-form-field> </div> </form> <button mat-raised-button color="none" (click)="doDownloadFile()" class="text-upper"> Download </button> `; downloadCodeTypescript: string = ` import { downloadCSV, downloadJSON, downloadObjectsToCSV, downloadObjectsToJSON, downloadFile } from '@covalent/core/common'; export class FunctionsDemoComponent { csv: string = 'name,id\r\nuser1,123\r\nuser2,234\r\n'; json: string = '[ {"name":"user1","id":"123"}, {"name":"user2","id":"234"}, ]'; objects: object[] = [ { 'name': 'user1', 'id': 123 }, { 'name': 'user2', 'id': 234 } ]; objectsString: string; fileName: string = 'sample.txt'; fileContent: string = 'Lorem Ipsum'; mimeType: string = 'text/plain'; constructor(private _snackBar: MatSnackBar) { this.objectsString = JSON.stringify(this.objects, undefined, 2); } doDownloadCSV(): void { // Invoke utility function to download CSV value into file // with 'text/csv' mime type and '.csv' extension. downloadCSV('csvsampledata', this.csv); // Show snackbar to indicate task complete this._snackBar.open('CSV downloaded!', undefined, { duration: 2000, }); } doDownloadJSON(): void { // Invoke utility function to download JSON into file // with 'application/json' mime type and '.json' extension. // Request JSON to be prettied. downloadJSON('jsonsampledata', this.json, true, 2); // Show snackbar to indicate task complete this._snackBar.open('JSON downloaded!', undefined, { duration: 2000, }); } doDownloadObjectsToCSV(): void { // Invoke utility function to convert objects to CSV value // and download into file with 'text/csv' mime type and // '.csv' extension. downloadObjectsToCSV('objtocsvsampledata', this.objects); // Show snackbar to indicate task complete this._snackBar.open('JSON converted to CSV and downloaded!', undefined, { duration: 2000, }); } doDownloadObjectsToJSON(): void { // Invoke utility function to convert objects to JSON // and download into file with 'application/json' mime type and // '.json' extension. downloadObjectsToJSON('objtojsonsampledata', this.objects); // Show snackbar to indicate task complete this._snackBar.open('Objects converted to JSON and downloaded!', undefined, { duration: 2000, }); } doDownloadFile(): void { // Invoke utility function to write contents to specified // file with desired mime type. downloadFile(this.fileName, this.fileContent, this.mimeType); // Show snackbar to indicate task complete this._snackBar.open('Content downloaded!', undefined, { duration: 2000, }); } } `; fileCodeHtml: string = ` <button mat-raised-button class="text-upper" color="primary" (click)="fileInput.click()"> Choose File <input #fileInput type="file" (change)="doReadFile($event)" style="display:none"/> </button> <h4>File Content:</h4> <td-highlight [content]="readFileContent"></td-highlight> `; fileCodeTypescript: string = ` import { readFile } from '@covalent/core/common' export class FunctionsDemoComponent { readFileContent: string = ''; async doReadFile(event: any): Promise<void> { let file: File = event.srcElement.files[0]; this.readFileContent = await readFile(file); } } `; constructor(private _snackBar: MatSnackBar) { this.objectsString = formatJSON(this.objects, 2); } doCopyToClipboard(): void { // Invoke utility function to copy input text to clipboard copyToClipboard(this.copyText); // Show snackbar to indicate task complete this._snackBar.open('Text copied!', undefined, { duration: 2000, }); } doConvertObjectsToCSV(): void { // Invoke utility function to convert objects array using // comma as the key separator and carriage return line feed // as the line separator. this.csvOutput = convertObjectsToCSV(this.objects, ',', '\r\n'); // Show snackbar to indicate task complete this._snackBar.open('Objects converted!', undefined, { duration: 2000, }); } doConvertCSVToJSON(): void { // Invoke utility function to convert CSV value using // comma as the key separator and carriage return line feed // as the line separator into JSON format. Use two space // indent to pretty output JSON. this.jsonOutput = convertCSVToJSON(this.csv, ',', '\r\n', 2); // Show snackbar to indicate task complete this._snackBar.open('CSV converted!', undefined, { duration: 2000, }); } doDownloadCSV(): void { // Invoke utility function to download CSV value into file // with 'text/csv' mime type and '.csv' extension. downloadCSV('csvsampledata', this.csv); // Show snackbar to indicate task complete this._snackBar.open('CSV downloaded!', undefined, { duration: 2000, }); } doDownloadJSON(): void { // Invoke utility function to download JSON into file // with 'application/json' mime type and '.json' extension. // Request JSON to be prettied. downloadJSON('jsonsampledata', this.json, true, 2); // Show snackbar to indicate task complete this._snackBar.open('JSON downloaded!', undefined, { duration: 2000, }); } doDownloadObjectsToCSV(): void { // Invoke utility function to convert objects to CSV value // and download into file with 'text/csv' mime type and // '.csv' extension. downloadObjectsToCSV('objtocsvsampledata', this.objects); // Show snackbar to indicate task complete this._snackBar.open('Objects converted to CSV and downloaded!', undefined, { duration: 2000, }); } doDownloadObjectsToJSON(): void { // Invoke utility function to convert objects to JSON // and download into file with 'application/json' mime type and // '.json' extension. downloadObjectsToJSON('objtojsonsampledata', this.objects); // Show snackbar to indicate task complete this._snackBar.open('Objects converted to JSON and downloaded!', undefined, { duration: 2000, }); } doDownloadFile(): void { // Invoke utility function to write contents to specified // file with desired mime type. downloadFile(this.fileName, this.fileContent, this.mimeType); // Show snackbar to indicate task complete this._snackBar.open('Content downloaded!', undefined, { duration: 2000, }); } async doReadFile(event: any): Promise<void> { const file: File = event.srcElement.files[0]; this.readFileContent = await readFile(file); } }
the_stack
import { expect } from 'chai'; import * as sinon from 'sinon'; import { Source, StackFrame } from 'vscode-debugadapter'; import { DebugProtocol } from 'vscode-debugprotocol'; import { EXTENT_TRIGGER_PREFIX } from '../../../src'; import { ApexDebugStackFrameInfo, ApexReplayDebug, ApexVariable, ApexVariableContainer, LaunchRequestArguments, VariableContainer } from '../../../src/adapter/apexReplayDebug'; import { ApexExecutionOverlayResultCommandSuccess } from '../../../src/commands/apexExecutionOverlayResultCommand'; import { ApexHeapDump, LogContext } from '../../../src/core'; import { Handles } from '../../../src/core/handles'; import { HeapDumpService } from '../../../src/core/heapDumpService'; import { MockApexReplayDebug } from './apexReplayDebug.test'; import { createHeapDumpResultForTriggers, createHeapDumpWithCircularRefs, createHeapDumpWithNestedRefs, createHeapDumpWithNoStringTypes, createHeapDumpWithStrings } from './heapDumpTestUtil'; // tslint:disable:no-unused-expression describe('Replay debugger adapter variable handling - unit', () => { let adapter: MockApexReplayDebug; let sendResponseSpy: sinon.SinonSpy; const logFileName = 'foo.log'; const logFilePath = `path/${logFileName}`; const projectPath = undefined; const launchRequestArgs: LaunchRequestArguments = { logFile: logFilePath, trace: true, projectPath }; describe('Scopes request', () => { let hasHeapDumpForTopFrameStub: sinon.SinonStub; let getFrameHandlerStub: sinon.SinonStub; let copyStateForHeapDumpStub: sinon.SinonStub; let replaceVariablesWithHeapDumpStub: sinon.SinonStub; let resetLastSeenHeapDumpLogLineStub: sinon.SinonStub; let response: DebugProtocol.ScopesResponse; let args: DebugProtocol.ScopesArguments; let frameHandler: Handles<ApexDebugStackFrameInfo>; beforeEach(() => { adapter = new MockApexReplayDebug(); adapter.setLogFile(launchRequestArgs); response = Object.assign(adapter.getDefaultResponse(), { body: {} }); args = { frameId: 0 }; frameHandler = new Handles<ApexDebugStackFrameInfo>(); sendResponseSpy = sinon.spy(ApexReplayDebug.prototype, 'sendResponse'); getFrameHandlerStub = sinon .stub(LogContext.prototype, 'getFrameHandler') .returns(frameHandler); }); afterEach(() => { sendResponseSpy.restore(); hasHeapDumpForTopFrameStub.restore(); getFrameHandlerStub.restore(); if (copyStateForHeapDumpStub) { copyStateForHeapDumpStub.restore(); } if (replaceVariablesWithHeapDumpStub) { replaceVariablesWithHeapDumpStub.restore(); } if (resetLastSeenHeapDumpLogLineStub) { resetLastSeenHeapDumpLogLineStub.restore(); } }); it('Should return no scopes for unknown frame', async () => { hasHeapDumpForTopFrameStub = sinon .stub(LogContext.prototype, 'hasHeapDumpForTopFrame') .returns(false); await adapter.scopesRequest(response, args); expect(sendResponseSpy.calledOnce).to.be.true; const actualResponse: DebugProtocol.ScopesResponse = sendResponseSpy.getCall( 0 ).args[0]; expect(actualResponse.success).to.be.true; expect(actualResponse.body.scopes.length).to.equal(0); }); it('Should return local, static, and global scopes', async () => { hasHeapDumpForTopFrameStub = sinon .stub(LogContext.prototype, 'hasHeapDumpForTopFrame') .returns(false); const id = frameHandler.create(new ApexDebugStackFrameInfo(0, 'foo')); args.frameId = id; await adapter.scopesRequest(response, args); const actualResponse: DebugProtocol.ScopesResponse = sendResponseSpy.getCall( 0 ).args[0]; expect(actualResponse.success).to.be.true; expect(actualResponse.body.scopes.length).to.equal(3); expect(actualResponse.body.scopes[0].name).to.equal('Local'); expect(actualResponse.body.scopes[1].name).to.equal('Static'); expect(actualResponse.body.scopes[2].name).to.equal('Global'); }); it('Should replace with heapdump variables', async () => { hasHeapDumpForTopFrameStub = sinon .stub(LogContext.prototype, 'hasHeapDumpForTopFrame') .returns(true); copyStateForHeapDumpStub = sinon.stub( LogContext.prototype, 'copyStateForHeapDump' ); replaceVariablesWithHeapDumpStub = sinon.stub( HeapDumpService.prototype, 'replaceVariablesWithHeapDump' ); resetLastSeenHeapDumpLogLineStub = sinon.stub( LogContext.prototype, 'resetLastSeenHeapDumpLogLine' ); await adapter.scopesRequest(response, args); expect(copyStateForHeapDumpStub.calledOnce).to.be.true; expect(replaceVariablesWithHeapDumpStub.calledOnce).to.be.true; expect(resetLastSeenHeapDumpLogLineStub.calledOnce).to.be.true; }); }); describe('Variables request', () => { let getVariableHandlerStub: sinon.SinonStub; let getAllVariablesStub: sinon.SinonStub; let response: DebugProtocol.VariablesResponse; let args: DebugProtocol.VariablesArguments; let variableHandler: Handles<VariableContainer>; beforeEach(() => { adapter = new MockApexReplayDebug(); adapter.setLogFile(launchRequestArgs); response = Object.assign(adapter.getDefaultResponse(), { body: {} }); args = { variablesReference: 0 }; variableHandler = new Handles<VariableContainer>(); sendResponseSpy = sinon.spy(ApexReplayDebug.prototype, 'sendResponse'); }); afterEach(() => { sendResponseSpy.restore(); if (getVariableHandlerStub) { getVariableHandlerStub.restore(); } if (getAllVariablesStub) { getAllVariablesStub.restore(); } }); it('Should return no variables for unknown scope', async () => { await adapter.variablesRequest(response, args); const actualResponse: DebugProtocol.VariablesResponse = sendResponseSpy.getCall( 0 ).args[0]; expect(actualResponse.success).to.be.true; expect(actualResponse.body.variables.length).to.equal(0); }); it('Should collect variables from scope container', async () => { getVariableHandlerStub = sinon .stub(LogContext.prototype, 'getVariableHandler') .returns(variableHandler); getAllVariablesStub = sinon .stub(VariableContainer.prototype, 'getAllVariables') .returns([new ApexVariable('foo', 'bar', 'String')]); const id = variableHandler.create( new ApexVariableContainer('foo', 'bar', 'String') ); args.variablesReference = id; await adapter.variablesRequest(response, args); const actualResponse: DebugProtocol.VariablesResponse = sendResponseSpy.getCall( 0 ).args[0]; expect(actualResponse.success).to.be.true; expect(actualResponse.body.variables.length).to.equal(1); const apexVariable = actualResponse.body.variables[0]; expect(apexVariable.name).to.equal('foo'); expect(apexVariable.value).to.equal('bar'); expect(apexVariable.evaluateName).to.equal(apexVariable.value); expect(apexVariable.type).to.equal('String'); }); }); describe('Heapdump', () => { let heapDumpService: HeapDumpService; before(() => { adapter = new MockApexReplayDebug(); const logContext = new LogContext(launchRequestArgs, adapter); heapDumpService = new HeapDumpService(logContext); }); describe('replaceVariablesWithHeapDump', () => { let getTopFrameStub: sinon.SinonStub; let getHeapDumpForThisLocationStub: sinon.SinonStub; let createStringRefsFromHeapdumpSpy: sinon.SinonSpy; let updateLeafReferenceContainerSpy: sinon.SinonSpy; let createVariableFromReferenceSpy: sinon.SinonSpy; let getFrameHandlerStub: sinon.SinonStub; let getRefsMapStub: sinon.SinonStub; let getStaticVariablesClassMapStub: sinon.SinonStub; const topFrame: StackFrame = { id: 0, name: 'Foo.cls', line: 10, column: 0, source: new Source('Foo.cls', '/path/Foo.cls') }; let frameHandler: Handles<ApexDebugStackFrameInfo>; let refsMap: Map<string, ApexVariableContainer>; let staticVariablesClassMap: Map<string, Map<string, VariableContainer>>; beforeEach(() => { adapter = new MockApexReplayDebug(); adapter.setLogFile(launchRequestArgs); frameHandler = new Handles<ApexDebugStackFrameInfo>(); refsMap = new Map<string, ApexVariableContainer>(); staticVariablesClassMap = new Map< string, Map<string, ApexVariableContainer> >(); getTopFrameStub = sinon .stub(LogContext.prototype, 'getTopFrame') .returns(topFrame); createStringRefsFromHeapdumpSpy = sinon.spy( HeapDumpService.prototype, 'createStringRefsFromHeapdump' ); updateLeafReferenceContainerSpy = sinon.spy( HeapDumpService.prototype, 'updateLeafReferenceContainer' ); createVariableFromReferenceSpy = sinon.spy( HeapDumpService.prototype, 'createVariableFromReference' ); getFrameHandlerStub = sinon .stub(LogContext.prototype, 'getFrameHandler') .returns(frameHandler); getRefsMapStub = sinon .stub(LogContext.prototype, 'getRefsMap') .returns(refsMap); getStaticVariablesClassMapStub = sinon .stub(LogContext.prototype, 'getStaticVariablesClassMap') .returns(staticVariablesClassMap); }); afterEach(() => { getTopFrameStub.restore(); getHeapDumpForThisLocationStub.restore(); createStringRefsFromHeapdumpSpy.restore(); updateLeafReferenceContainerSpy.restore(); createVariableFromReferenceSpy.restore(); getFrameHandlerStub.restore(); getRefsMapStub.restore(); getStaticVariablesClassMapStub.restore(); }); it('Should not switch variables without a heapdump for current location', () => { getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(undefined); heapDumpService.replaceVariablesWithHeapDump(); expect(createStringRefsFromHeapdumpSpy.called).to.be.false; expect(updateLeafReferenceContainerSpy.called).to.be.false; expect(createVariableFromReferenceSpy.called).to.be.false; }); it('Should not switch variables without a successful heapdump for current location', () => { const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); heapDumpService.replaceVariablesWithHeapDump(); expect(createStringRefsFromHeapdumpSpy.called).to.be.false; expect(updateLeafReferenceContainerSpy.called).to.be.false; expect(createVariableFromReferenceSpy.called).to.be.false; }); it('Should not create string refs if there are not any in the heapdump', () => { const heapdump = createHeapDumpWithNoStringTypes(); heapDumpService.createStringRefsFromHeapdump( heapdump.getOverlaySuccessResult()! ); expect(refsMap.size).to.be.eq(0); }); it('Should only create string refs if there are not any in the heapdump', () => { const heapdump = createHeapDumpWithNoStringTypes(); heapDumpService.createStringRefsFromHeapdump( heapdump.getOverlaySuccessResult()! ); expect(refsMap.size).to.be.eq(0); }); it('Should create string refs if there are any in the heapdump', () => { const heapdump = createHeapDumpWithStrings(); heapDumpService.createStringRefsFromHeapdump( heapdump.getOverlaySuccessResult()! ); expect(refsMap.size).to.be.eq(2); let tempStringVar = refsMap.get('0x47a32f5b') as ApexVariableContainer; expect(tempStringVar.value).to.be.eq( "'This is a longer string that will certainly get truncated until we hit a checkpoint and inspect it_extra'" ); tempStringVar = refsMap.get('0x6cda5efc') as ApexVariableContainer; expect(tempStringVar.value).to.be.eq("'9/13/2018'"); }); it('Should not follow reference chain when creating leaf variables except strings', () => { const heapdump = createHeapDumpWithNestedRefs(); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; heapDumpService.replaceVariablesWithHeapDump(); expect(createStringRefsFromHeapdumpSpy.called).to.be.true; expect(updateLeafReferenceContainerSpy.called).to.be.true; expect(createVariableFromReferenceSpy.called).to.be.false; expect(refsMap.size).to.be.eq(4); // NonStaticClassWithVariablesToInspect has an inner class of the same type. // Get the one that's the top level one and verify that it's innerVariable does not // have children and that all of the other values have been set including the string // value let tempApexVar = refsMap.get('0x3557adc7') as ApexVariableContainer; expect(tempApexVar.variables.size).to.be.eq(7); expect( (tempApexVar.variables.get('MyBoolean') as ApexVariableContainer) .value ).to.be.eq('false'); expect( (tempApexVar.variables.get('MyDate') as ApexVariableContainer).value ).to.be.eq('Thu Sep 13 00:00:00 GMT 2018'); expect( (tempApexVar.variables.get('MyDouble') as ApexVariableContainer).value ).to.be.eq('4.37559'); expect( (tempApexVar.variables.get('MyInteger') as ApexVariableContainer) .value ).to.be.eq('10'); expect( (tempApexVar.variables.get('MyLong') as ApexVariableContainer).value ).to.be.eq('4271993'); expect( (tempApexVar.variables.get('MyString') as ApexVariableContainer).value ).to.be.eq( "'This is a longer string that will certainly get truncated until we hit a checkpoint and inspect it_extra'" ); const innerApexRefVar = tempApexVar.variables.get( 'innerVariable' ) as ApexVariableContainer; expect(innerApexRefVar.ref).to.be.eq('0x55260a7a'); expect(innerApexRefVar.variables.size).to.be.eq(0); tempApexVar = refsMap.get('0x55260a7a') as ApexVariableContainer; expect(tempApexVar.variables.size).to.be.eq(7); expect( (tempApexVar.variables.get('MyBoolean') as ApexVariableContainer) .value ).to.be.eq('true'); expect( (tempApexVar.variables.get('MyDate') as ApexVariableContainer).value ).to.be.eq('Thu Sep 13 00:00:00 GMT 2018'); expect( (tempApexVar.variables.get('MyDouble') as ApexVariableContainer).value ).to.be.eq('3.14159'); expect( (tempApexVar.variables.get('MyInteger') as ApexVariableContainer) .value ).to.be.eq('5'); expect( (tempApexVar.variables.get('MyLong') as ApexVariableContainer).value ).to.be.eq('4271990'); expect( (tempApexVar.variables.get('MyString') as ApexVariableContainer).value ).to.be.eq("'9/13/2018'"); expect( (tempApexVar.variables.get('innerVariable') as ApexVariableContainer) .value ).to.be.eq('null'); }); it('Should follow reference chain when creating instance variables from references', () => { const heapdump = createHeapDumpWithNestedRefs(); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); const localRefVariable = new ApexVariableContainer( 'foo', '', 'NonStaticClassWithVariablesToInspect' ); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; frameInfo.locals.set(localRefVariable.name, localRefVariable); heapDumpService.replaceVariablesWithHeapDump(); const updatedLocRefVariable = frameInfo.locals.get( localRefVariable.name ) as ApexVariableContainer; expect(updatedLocRefVariable.variables.size).to.be.eq(7); expect( (updatedLocRefVariable.variables.get( 'MyBoolean' ) as ApexVariableContainer).value ).to.be.eq('false'); expect( (updatedLocRefVariable.variables.get( 'MyDate' ) as ApexVariableContainer).value ).to.be.eq('Thu Sep 13 00:00:00 GMT 2018'); expect( (updatedLocRefVariable.variables.get( 'MyDouble' ) as ApexVariableContainer).value ).to.be.eq('4.37559'); expect( (updatedLocRefVariable.variables.get( 'MyInteger' ) as ApexVariableContainer).value ).to.be.eq('10'); expect( (updatedLocRefVariable.variables.get( 'MyLong' ) as ApexVariableContainer).value ).to.be.eq('4271993'); expect( (updatedLocRefVariable.variables.get( 'MyString' ) as ApexVariableContainer).value ).to.be.eq( "'This is a longer string that will certainly get truncated until we hit a checkpoint and inspect it_extra'" ); const innerApexRefVar = updatedLocRefVariable.variables.get( 'innerVariable' ) as ApexVariableContainer; expect(innerApexRefVar.ref).to.be.eq('0x55260a7a'); expect(innerApexRefVar.variables.size).to.be.eq(7); expect( (innerApexRefVar.variables.get('MyBoolean') as ApexVariableContainer) .value ).to.be.eq('true'); expect( (innerApexRefVar.variables.get('MyDate') as ApexVariableContainer) .value ).to.be.eq('Thu Sep 13 00:00:00 GMT 2018'); expect( (innerApexRefVar.variables.get('MyDouble') as ApexVariableContainer) .value ).to.be.eq('3.14159'); expect( (innerApexRefVar.variables.get('MyInteger') as ApexVariableContainer) .value ).to.be.eq('5'); expect( (innerApexRefVar.variables.get('MyLong') as ApexVariableContainer) .value ).to.be.eq('4271990'); expect( (innerApexRefVar.variables.get('MyString') as ApexVariableContainer) .value ).to.be.eq("'9/13/2018'"); expect( (innerApexRefVar.variables.get( 'innerVariable' ) as ApexVariableContainer).value ).to.be.eq('null'); }); it('Should update a non-reference variable', () => { const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10); heapdump.setOverlaySuccessResult({ HeapDump: { extents: [ { collectionType: null, typeName: 'Integer', definition: [ { name: 'value', type: 'Double' } ], extent: [ { address: '0xfoo', isStatic: false, symbols: ['theInt'], value: { value: 5 } } ] } ] } } as ApexExecutionOverlayResultCommandSuccess); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); const nonRefVariable = new ApexVariableContainer( 'theInt', '2', 'Double' ); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; frameInfo.locals.set(nonRefVariable.name, nonRefVariable); heapDumpService.replaceVariablesWithHeapDump(); expect(createStringRefsFromHeapdumpSpy.calledOnce).to.be.true; expect(updateLeafReferenceContainerSpy.calledOnce).to.be.false; expect(createVariableFromReferenceSpy.calledOnce).to.be.false; const updatedNonRefVariable = frameInfo.locals.get( nonRefVariable.name ) as ApexVariableContainer; expect(updatedNonRefVariable.value).to.be.eq('5'); }); it('Should update a non-reference static variable', () => { const heapdump = new ApexHeapDump('some ID', 'Foo', '', 10); heapdump.setOverlaySuccessResult({ HeapDump: { extents: [ { collectionType: null, typeName: 'Integer', definition: [ { name: 'value', type: 'Double' } ], extent: [ { address: '0xfoo', isStatic: false, symbols: ['Foo.theInt'], value: { value: 5 } } ] } ] } } as ApexExecutionOverlayResultCommandSuccess); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); const nonRefVariable = new ApexVariableContainer( 'theInt', '2', 'Double' ); staticVariablesClassMap.set( 'Foo', new Map([['theInt', nonRefVariable]]) ); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; frameInfo.statics.set(nonRefVariable.name, nonRefVariable); heapDumpService.replaceVariablesWithHeapDump(); expect(createStringRefsFromHeapdumpSpy.calledOnce).to.be.true; expect(updateLeafReferenceContainerSpy.calledOnce).to.be.false; expect(createVariableFromReferenceSpy.calledOnce).to.be.false; const updatedNonRefVariable = frameInfo.statics.get( nonRefVariable.name ) as ApexVariableContainer; expect(updatedNonRefVariable.value).to.be.eq('5'); }); it('Should correctly deal with circular references and variable values', () => { const heapdump = createHeapDumpWithCircularRefs(); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); const localRefVariable = new ApexVariableContainer( 'cf1', '', 'CircularReference', '0x717304ef' ); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; frameInfo.locals.set(localRefVariable.name, localRefVariable); heapDumpService.replaceVariablesWithHeapDump(); // Verify the variable was updated and that there is a cicular reference that // was set up correctly. The local variable cf1, of type CircularReference contains // a field that's a List<CircularReference>. After creating cf1 we add cf1 to its own // list. const expectedVariableValue = 'CircularReference:{(already output), someInt=5}'; const expectedListVarValue = '(CircularReference:{already output, someInt=5})'; const updatedLocRefVariable = frameInfo.locals.get( localRefVariable.name ) as ApexVariableContainer; expect(updatedLocRefVariable.value).to.be.eq(expectedVariableValue); expect(updatedLocRefVariable.variables.size).to.be.eq(2); expect( (updatedLocRefVariable.variables.get( 'someInt' ) as ApexVariableContainer).value ).to.be.eq('5'); const listChildVar = updatedLocRefVariable.variables.get( 'cfList' ) as ApexVariableContainer; expect(listChildVar.value).to.be.eq(expectedListVarValue); expect(listChildVar.variables.size).to.be.eq(1); const listElementVar = listChildVar.variables.get( '0' ) as ApexVariableContainer; expect(listElementVar.value).to.be.eq(expectedVariableValue); expect( (listElementVar.variables.get('cfList') as ApexVariableContainer) .value ).to.be.eq(expectedListVarValue); }); }); // Describe replaceVariablesWithHeapDump describe('heapDumpTriggerContextVariables', () => { let getTopFrameStub: sinon.SinonStub; let getHeapDumpForThisLocationStub: sinon.SinonStub; let getFrameHandlerStub: sinon.SinonStub; let getRefsMapStub: sinon.SinonStub; let getStaticVariablesClassMapStub: sinon.SinonStub; let isRunningApexTriggerStub: sinon.SinonStub; let getVariableHandlerStub: sinon.SinonStub; let variableHandler: Handles<VariableContainer>; const topFrame: StackFrame = { id: 0, name: 'Foo.cls', line: 10, column: 0, source: new Source('Foo.trigger', '/path/Foo.trigger') }; let frameHandler: Handles<ApexDebugStackFrameInfo>; let refsMap: Map<string, ApexVariableContainer>; let staticVariablesClassMap: Map<string, Map<string, VariableContainer>>; beforeEach(() => { adapter = new MockApexReplayDebug(); adapter.setLogFile(launchRequestArgs); frameHandler = new Handles<ApexDebugStackFrameInfo>(); refsMap = new Map<string, ApexVariableContainer>(); staticVariablesClassMap = new Map< string, Map<string, ApexVariableContainer> >(); getTopFrameStub = sinon .stub(LogContext.prototype, 'getTopFrame') .returns(topFrame); getFrameHandlerStub = sinon .stub(LogContext.prototype, 'getFrameHandler') .returns(frameHandler); getRefsMapStub = sinon .stub(LogContext.prototype, 'getRefsMap') .returns(refsMap); getStaticVariablesClassMapStub = sinon .stub(LogContext.prototype, 'getStaticVariablesClassMap') .returns(staticVariablesClassMap); variableHandler = new Handles<VariableContainer>(); isRunningApexTriggerStub = sinon.stub( LogContext.prototype, 'isRunningApexTrigger' ); }); afterEach(() => { getTopFrameStub.restore(); getHeapDumpForThisLocationStub.restore(); getFrameHandlerStub.restore(); getRefsMapStub.restore(); getStaticVariablesClassMapStub.restore(); if (isRunningApexTriggerStub) { isRunningApexTriggerStub.restore(); } if (getVariableHandlerStub) { getVariableHandlerStub.restore(); } }); it('Should not create global trigger variables if not processing a trigger heapdump', () => { const heapdump = createHeapDumpResultForTriggers(); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); getVariableHandlerStub = sinon .stub(LogContext.prototype, 'getVariableHandler') .returns(variableHandler); isRunningApexTriggerStub.returns(false); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; expect(frameInfo.globals.size).to.eq(0); heapDumpService.replaceVariablesWithHeapDump(); expect(frameInfo.globals.size).to.eq(0); }); it('Should create trigger variables if processing a trigger heapdump', () => { const heapdump = createHeapDumpResultForTriggers(); getHeapDumpForThisLocationStub = sinon .stub(LogContext.prototype, 'getHeapDumpForThisLocation') .returns(heapdump); getVariableHandlerStub = sinon .stub(LogContext.prototype, 'getVariableHandler') .returns(variableHandler); isRunningApexTriggerStub.returns(true); const frameInfo = new ApexDebugStackFrameInfo(0, 'Foo'); const id = frameHandler.create(frameInfo); topFrame.id = id; expect(frameInfo.globals.size).to.eq(0); heapDumpService.replaceVariablesWithHeapDump(); expect(frameInfo.globals.size).to.eq(8); expect( (frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'isbefore' ) as ApexVariableContainer).value ).to.eq('false'); expect( (frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'isdelete' ) as ApexVariableContainer).value ).to.eq('false'); expect( (frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'isundelete' ) as ApexVariableContainer).value ).to.eq('false'); expect( (frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'isupdate' ) as ApexVariableContainer).value ).to.eq('false'); expect( (frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'isafter' ) as ApexVariableContainer).value ).to.eq('true'); expect( (frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'isinsert' ) as ApexVariableContainer).value ).to.eq('true'); const triggerNew = frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'new' ) as ApexVariableContainer; expect(triggerNew.type).to.be.eq('List<Account>'); expect(triggerNew.variablesRef).to.be.greaterThan(0); expect(triggerNew.variables.size).to.be.eq(3); expect( (triggerNew.variables.get('0') as ApexVariableContainer).ref ).to.eq('0x5f163c72'); expect( (triggerNew.variables.get('1') as ApexVariableContainer).ref ).to.eq('0xf1fabe'); expect( (triggerNew.variables.get('2') as ApexVariableContainer).ref ).to.eq('0x76e9852b'); const triggerNewmap = frameInfo.globals.get( EXTENT_TRIGGER_PREFIX + 'newmap' ) as ApexVariableContainer; expect(triggerNewmap.type).to.be.eq('Map<Id,Account>'); expect(triggerNewmap.variablesRef).to.be.greaterThan(0); expect(triggerNewmap.variables.size).to.be.eq(3); let tempKeyValPairApexVar = triggerNewmap.variables.get( 'key0_value0' ) as ApexVariableContainer; expect(tempKeyValPairApexVar.name).to.be.eq("'001xx000003Dv3YAAS'"); let keyApexVar = tempKeyValPairApexVar.variables.get( 'key' ) as ApexVariableContainer; expect(keyApexVar.type).to.eq('Id'); expect(keyApexVar.value).to.eq(tempKeyValPairApexVar.name); let valueApexVar = tempKeyValPairApexVar.variables.get( 'value' ) as ApexVariableContainer; expect(valueApexVar.type).to.be.eq('Account'); expect(valueApexVar.ref).to.be.eq('0x5f163c72'); tempKeyValPairApexVar = triggerNewmap.variables.get( 'key1_value1' ) as ApexVariableContainer; expect(tempKeyValPairApexVar.name).to.be.eq("'001xx000003Dv3ZAAS'"); keyApexVar = tempKeyValPairApexVar.variables.get( 'key' ) as ApexVariableContainer; expect(keyApexVar.type).to.eq('Id'); expect(keyApexVar.value).to.eq(tempKeyValPairApexVar.name); valueApexVar = tempKeyValPairApexVar.variables.get( 'value' ) as ApexVariableContainer; expect(valueApexVar.type).to.be.eq('Account'); expect(valueApexVar.ref).to.be.eq('0xf1fabe'); tempKeyValPairApexVar = triggerNewmap.variables.get( 'key2_value2' ) as ApexVariableContainer; expect(tempKeyValPairApexVar.name).to.be.eq("'001xx000003Dv3aAAC'"); keyApexVar = tempKeyValPairApexVar.variables.get( 'key' ) as ApexVariableContainer; expect(keyApexVar.type).to.eq('Id'); expect(keyApexVar.value).to.eq(tempKeyValPairApexVar.name); valueApexVar = tempKeyValPairApexVar.variables.get( 'value' ) as ApexVariableContainer; expect(valueApexVar.type).to.be.eq('Account'); expect(valueApexVar.ref).to.be.eq('0x76e9852b'); }); }); }); });
the_stack
import * as FunctionNames from "./FunctionNames"; import * as babylon from "@babel/parser"; import operations, { shouldSkipIdentifier, initForBabel } from "./operations"; import { ignoreNode, ignoredArrayExpression, ignoredStringLiteral, ignoredIdentifier, ignoredCallExpression, ignoredNumericLiteral, createOperation, getLastOperationTrackingResultCall, runIfIdentifierExists, isInNodeType, isInIdOfVariableDeclarator, isInLeftPartOfAssignmentExpression, getTrackingVarName, addLoc, skipPath, getTrackingIdentifier, getLocObjectASTNode } from "./babelPluginHelpers"; import helperCodeLoaded from "../helperFunctions"; import * as t from "@babel/types"; import { VERIFY } from "./config"; initForBabel(t, babylon); var helperCode = ` (function(){ var global = Function("return this")(); if (!global.__fromJSConfig) { global.__fromJSConfig = { VERIFY: ${VERIFY} } } })(); `; helperCode += helperCodeLoaded.toString(); helperCode += "/* HELPER_FUNCTIONS_END */ "; // I got some babel-generator "cannot read property 'type' of undefined" errors // when prepending the code itself, so just prepend a single eval call expression helperCode = ` if (typeof __fromJSMaybeMapInitialPageHTML !== "undefined") { __fromJSMaybeMapInitialPageHTML() } var global = Function("return this")(); if (!global.__didInitializeDataFlowTracking) {` + "eval(`" + helperCode .replace(/\\/g, "\\\\") .replace(/`/g, "\\`") .replace(/\$/g, "\\$") + "\n//# sourceURL=/helperFns.js`)" + "}"; helperCode += "// aaaaa"; // this seems to help with debugging/evaling the code... not sure why...just take it out if the tests dont break // helperCode = "" function plugin(babel) { const { types: t } = babel; function handleFunction(path) { const declarators: any[] = []; path.node.params.forEach((param, i) => { if (param.type === "ObjectPattern") { // do nothing for now, logic is in objectpattern visitor // for (var n = 0; n < param.properties.length; n++) { // const prop = param.properties[n]; // declarators.push( // t.variableDeclarator( // addLoc( // getTrackingIdentifier( // prop.value ? prop.value.name : prop.key.name // ), // prop.loc // ), // t.nullLiteral() // ) // ); // } } else if (param.type === "ArrayPattern") { param.elements.forEach(elem => { let varName; if (!elem) { // e.g. [,,c] } else if (elem.type === "Identifier") { varName = elem.name; } else if (elem.type === "AssignmentPattern") { varName = elem.left.name; } else if (elem.type === "RestParameter") { varName = elem.argument.name; } else if (elem.type === "ObjectPattern") { // will be processed in ObjectPattern visitor } else { throw Error( "aaa unknown array pattern elem type " + elem.type + " " + JSON.stringify(path.node.loc) ); } if (elem && varName) { declarators.push( t.variableDeclarator( addLoc(getTrackingIdentifier(varName), param.loc), ignoredCallExpression(FunctionNames.getEmptyTrackingInfo, [ ignoredStringLiteral("arrayPatternInFunction"), getLocObjectASTNode(elem.loc), ignoredIdentifier(varName) ]) ) ); } }); } else if (param.type === "AssignmentPattern") { let varName = param.left.name; declarators.push( t.variableDeclarator( addLoc(getTrackingIdentifier(varName), param.loc), ignoredCallExpression(FunctionNames.getEmptyTrackingInfo, [ ignoredStringLiteral("assignmentPatternInFunction"), getLocObjectASTNode(param.loc), ignoredIdentifier(varName) ]) ) ); } else if (param.type === "RestElement") { let varName = param.argument.name; declarators.push( t.variableDeclarator( addLoc(getTrackingIdentifier(varName), param.loc), ignoredCallExpression(FunctionNames.getEmptyTrackingInfo, [ ignoredStringLiteral("restElement"), getLocObjectASTNode(param.loc) ]) ) ); } else { declarators.push( t.variableDeclarator( addLoc(getTrackingIdentifier(param.name), param.loc), t.callExpression( t.identifier(FunctionNames.getFunctionArgTrackingInfo), [t.numericLiteral(i)] ) ) ); } }); // keep whole list in case the function uses `arguments` object // We can't just access the arg tracking values when `arguments` is used (instead of doing it // at the top of the function) // That's because when we return the argTrackingValues are not reset to the parent function's declarators.push( t.variableDeclarator( ignoredIdentifier("__allArgTV"), ignoredCallExpression(FunctionNames.getFunctionArgTrackingInfo, []) ) ); const d = t.variableDeclaration("var", declarators); skipPath(d); if (path.node.body.type !== "BlockStatement") { // arrow function path.node.body = ignoreNode( t.blockStatement([t.returnStatement(path.node.body)]) ); } path.node.body.body.unshift(d); path.node.ignore = true; // I'm not sure why it would re-enter the functiondecl/expr, but it has happened before if (path.node.type === "FunctionExpression") { path.replaceWith(createOperation("fn", [path.node], null, path.node.loc)); } } const visitors = { FunctionDeclaration(path) { handleFunction(path); }, FunctionExpression(path) { handleFunction(path); }, ArrowFunctionExpression(path) { handleFunction(path); }, ClassMethod(path) { handleFunction(path); }, ObjectPattern(path) { // debugger; const newProperties: any[] = []; path.node.properties.forEach(prop => { let varName; if (prop.value && prop.value.type === "Identifier") { varName = prop.value.name; } else if (prop.value && prop.value.type === "AssignmentPattern") { varName = prop.value.left.name; } else if (prop.type === "RestElement") { varName = prop.argument.name; } else { varName = prop.key.name; } // tracking values need to be at the top level, otherwise we'd have to modify the // return value of provideObjectPatternTrackingValues which could // mean the program ends up with a modified value let topLevelObjectPattern = path.node; let currentPath = path.parentPath; while (currentPath) { if (currentPath.node.type === "ObjectPattern") { topLevelObjectPattern = currentPath.node; } currentPath = currentPath.parentPath; } let topLevelObjectPatternProperties = topLevelObjectPattern === path.node ? newProperties : topLevelObjectPattern.properties; let trackingVarPath = skipPath( t.ObjectProperty( ignoreNode(getTrackingIdentifier(varName)), t.assignmentPattern( getTrackingIdentifier(varName), ignoredCallExpression(FunctionNames.getEmptyTrackingInfo, [ ignoredStringLiteral("objectPattern"), getLocObjectASTNode(prop.loc) ]) ) ) ); const lastTopLevelObjectProperty = topLevelObjectPatternProperties[ topLevelObjectPatternProperties.length - 1 ]; const topLevelHasRestElement = lastTopLevelObjectProperty && lastTopLevelObjectProperty.type === "RestElement"; if (!topLevelHasRestElement) { topLevelObjectPatternProperties.push(trackingVarPath); } else { topLevelObjectPatternProperties.splice( topLevelObjectPatternProperties.length - 2, 0, trackingVarPath ); } newProperties.push(prop); }); path.node.properties = newProperties; }, ForOfStatement(path) { if (path.node.left.type === "VariableDeclaration") { const variableDeclarator = path.node.left.declarations[0]; let varKind = "let"; if (path.node.left.kind === "var") { // should leak into parent scope varKind = "var"; } if (variableDeclarator.id.type === "Identifier") { if (!path.node.body.body) { path.node.body = ignoreNode( babel.types.blockStatement([path.node.body]) ); } path.node.body.body.unshift( skipPath( t.variableDeclaration(varKind, [ t.variableDeclarator( ignoredIdentifier( getTrackingVarName(variableDeclarator.id.name) ), ignoredCallExpression(FunctionNames.getEmptyTrackingInfo, [ ignoredStringLiteral("forOfVariable"), getLocObjectASTNode(variableDeclarator.loc) ]) ) ]) ) ); } } }, VariableDeclaration(path) { if (["ForInStatement", "ForOfStatement"].includes(path.parent.type)) { return; } var originalDeclarations = path.node.declarations; var newDeclarations: any[] = []; originalDeclarations.forEach(function(decl) { newDeclarations.push(decl); if (!decl.init) { decl.init = addLoc(ignoredIdentifier("undefined"), decl.loc); } if (decl.id.type === "ArrayPattern") { // declaration are inserted into pattern already } else if (decl.id.type === "ObjectPattern") { // declarations are inserted into object pattern already // but we need to make sure they are provided function getProps(propsArr, pathPrefix = "") { let properties: { name: string; path: string; isRest?: boolean; }[] = []; for (const prop of propsArr) { if (prop.type === "RestElement") { // for now just ignore and don't add tracking values properties.push({ name: prop.argument.name, path: pathPrefix + prop.argument.name, isRest: true }); } else if (prop.value.type === "ObjectPattern") { properties = [ ...properties, ...getProps( prop.value.properties, pathPrefix + prop.key.name + "." ) ]; } else if (prop.value.type === "AssignmentPattern") { // for now just ignore and don't add tracking values } else { properties.push({ name: prop.value.name, path: pathPrefix + prop.key.name }); } } return properties; } let properties = getProps(decl.id.properties); decl.init = ignoredCallExpression( FunctionNames.provideObjectPatternTrackingValues, [ decl.init, ignoredArrayExpression( properties.map(prop => { let arrItems = [ ignoredStringLiteral(prop.name), ignoredStringLiteral(prop.path) ]; if (prop.isRest) { arrItems.push(ignoredStringLiteral("isRest")); } return ignoredArrayExpression(arrItems); }) ) ] ); } else { newDeclarations.push( t.variableDeclarator( addLoc(getTrackingIdentifier(decl.id.name), decl.id.loc), skipPath( t.callExpression( t.identifier(FunctionNames.getLastOperationTrackingResult), [] ) ) ) ); } }); path.node.declarations = newDeclarations; }, WithStatement(path) { function i(node) { if (node.name === null) { debugger; } node.ignoreInWithStatementVisitor = true; return node; } // not an ideal way to track things and might not work for nested // with statements, but with statement use should be rare. // Underscore uses them for templates though. let obj = path.node.object; path.get("object").traverse({ Identifier(path) { path.replaceWith(i(path.node)); } }); path.traverse({ Identifier(path) { if (path.node.ignoreInWithStatementVisitor) { return; } if (shouldSkipIdentifier(path)) { return; } if ( ["WithStatement", "FunctionExpression"].includes(path.parent.type) ) { return; } if (path.parent.type === "MemberExpression") { if ((path.parent.property = path.node)) { console.log("ignoreing"); return; } } path.node.ignoreInWithStatementVisitor = true; const identifierName = path.node.name; path.replaceWith( ignoreNode( t.conditionalExpression( ignoreNode( t.binaryExpression( "in", addLoc(t.stringLiteral(identifierName), path.node.loc), obj ) ), addLoc( t.memberExpression( obj, addLoc(t.stringLiteral(identifierName), path.node.loc), true ), path.node.loc ), i(addLoc(t.identifier(identifierName), path.node.loc)) ) ) ); } }); }, CatchClause(path) { const errName = path.node.param.name; // We don't track anything, but this var has to exist to avoid "err___tv is undeclared" errors const trackingVarDec = skipPath( t.variableDeclaration("let", [ t.variableDeclarator(t.identifier(getTrackingVarName(errName))) ]) ); path.node.body.body.unshift(trackingVarDec); }, ArrayPattern(path) { const isForOfStatementWithVarDeclaration = path.parentPath.node.type === "VariableDeclarator" && path.parentPath.parentPath.parentPath.node.type === "ForOfStatement"; const isForOfStatementWithoutVarDeclaration = path.parentPath.node.type === "ForOfStatement"; if ( [ "FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression" ].includes(path.parentPath.node.type) ) { // don't transform, it would break how the values are passed return; } const specificParamCount = path.node.elements.filter(el => { // !el if e.g. [,a,b] with an empty item at the start return !el || el.type !== "RestElement"; }).length; if ( isForOfStatementWithVarDeclaration || isForOfStatementWithoutVarDeclaration ) { let forOfStatement; if (isForOfStatementWithVarDeclaration) { forOfStatement = path.parentPath.parentPath.parentPath.node; } else if (isForOfStatementWithoutVarDeclaration) { forOfStatement = path.parentPath.node; } forOfStatement.right = ignoredCallExpression( FunctionNames.expandArrayForArrayPattern, [ forOfStatement.right, getLocObjectASTNode(forOfStatement.loc), ignoredStringLiteral("forOf"), ignoredNumericLiteral(specificParamCount) ] ); } else if ( path.parentPath.parentPath.node.type === "VariableDeclaration" ) { const declarator = path.parentPath.node; declarator.init = ignoredCallExpression( FunctionNames.expandArrayForArrayPattern, [ declarator.init, getLocObjectASTNode(declarator.loc), ignoredStringLiteral("variableDeclarationInit"), ignoredNumericLiteral(specificParamCount) ] ); } else if (path.parentPath.node.type === "AssignmentExpression") { const assignmentExpression = path.parentPath.node; assignmentExpression.right = ignoredCallExpression( FunctionNames.expandArrayForArrayPattern, [ assignmentExpression.right, getLocObjectASTNode(assignmentExpression.loc), ignoredStringLiteral("assignmentExpressionRight"), ignoredNumericLiteral(specificParamCount) ] ); } const arrayPattern = path.node; const newElements: any[] = []; arrayPattern.elements.forEach(elem => { let varName; if (!elem) { } else if (elem.type === "Identifier") { varName = elem.name; } else if (elem.type === "AssignmentPattern") { varName = elem.left.name; } else if (elem.type === "RestElement") { varName = elem.argument.name; } else if (elem.type === "ObjectPattern") { // will be processed in ObjectPattern visitor } else { throw Error("array pattern elem type " + elem.type); } if (!elem) { newElements.push(elem); newElements.push(elem); } else if (elem.type !== "RestElement") { newElements.push(elem); newElements.push(addLoc(getTrackingIdentifier(varName), elem.loc)); } else { // Rest element must be last element newElements.push(addLoc(getTrackingIdentifier(varName), elem.loc)); newElements.push(elem.argument); } // newDeclarations.push( // t.variableDeclarator( // , // skipPath( // ignoredCallExpression(FunctionNames.getEmptyTrackingInfo, [ // ignoredStringLiteral("arrayPatternInVarDeclaration"), // getLocObjectASTNode(elem.loc) // ]) // ) // ) // ); }); arrayPattern.elements = newElements; }, ForInStatement(path) { let varName; let isNewVariable; let varKind = "let"; if (path.node.left.type === "VariableDeclaration") { const variableDeclaration = path.node.left; varName = variableDeclaration.declarations[0].id.name; if (variableDeclaration.kind === "var") { // should leak into outer scope varKind = "var"; } isNewVariable = true; } else if (path.node.left.type === "Identifier") { varName = path.node.left.name; isNewVariable = false; } else { throw Error("not sure what this is"); } if (path.node.body.type !== "BlockStatement") { // Technically it might not be safe to make this conversion // because it affects scoping for let/const inside the body // ...although that's not usually what you do inside a for in body path.node.body = ignoreNode( babel.types.blockStatement([path.node.body]) ); } const body = path.node.body.body; let forInRightValueIdentifier = ignoreNode( path.scope.generateUidIdentifier("__forInRightVal") ); // insertBefore causes this ForInStatement to be visited again // if a block body is introduced for the parent (e.g. if the parent // was a single-statement if statement before) // Prevent processing this ForInStatement twice path.node.ignore = true; path.insertBefore( ignoreNode( t.variableDeclaration("let", [ t.variableDeclarator(forInRightValueIdentifier, path.node.right) ]) ) ); path.node.right = forInRightValueIdentifier; var assignment = ignoreNode( t.expressionStatement( ignoreNode( t.assignmentExpression( "=", ignoredIdentifier(getTrackingVarName(varName)), ignoredCallExpression( FunctionNames.getObjectPropertyNameTrackingValue, [forInRightValueIdentifier, ignoredIdentifier(varName)] ) ) ) ) ); body.unshift(assignment); if (isNewVariable) { var declaration = ignoreNode( // Note: this needs to be let or else there could be conflict with // a var from parent scope t.variableDeclaration(varKind, [ t.variableDeclarator(ignoredIdentifier(getTrackingVarName(varName))) ]) ); body.unshift(declaration); } } }; Object.keys(operations).forEach(key => { var operation = operations[key]; key = key[0].toUpperCase() + key.slice(1); if (operation.visitor) { if (visitors[key]) { throw Error("duplicate visitor " + key); } visitors[key] = path => { var ret = operation.visitor.call(operation, path); if (ret) { if (!ret.loc) { // debugger; } try { path.replaceWith(ret); } catch (err) { console.log("Error for path at loc", JSON.stringify(path.node.loc)); // for easier debugging, allow step in again debugger; operation.visitor.call(operation, path); throw err; } } }; } }); // var enter = 0; // var enterNotIgnored = 0; Object.keys(visitors).forEach(key => { var originalVisitor = visitors[key]; visitors[key] = function(path) { // enter++; if (path.node.skipPath) { path.skip(); return; } if (path.node.skipKeys) { path.skipKeys = path.node.skipKeys; return; } if (path.node.ignore) { return; } // enterNotIgnored++; return originalVisitor.apply(this, arguments); }; }); visitors["Program"] = { // Run on exit so injected code isn't processed by other babel plugins exit: function(path) { const babelPluginOptions = plugin["babelPluginOptions"]; let usableHelperCode; if (babelPluginOptions) { const { accessToken, backendPort, backendOriginWithoutPort } = babelPluginOptions; usableHelperCode = helperCode; usableHelperCode = usableHelperCode.replace( /ACCESS_TOKEN_PLACEHOLDER/g, accessToken ); usableHelperCode = usableHelperCode.replace( /BACKEND_PORT_PLACEHOLDER/g, backendPort ); usableHelperCode = usableHelperCode.replace( /BACKEND_ORIGIN_WITHOUT_PORT_PLACEHOLDER/g, backendOriginWithoutPort ); } else { usableHelperCode = helperCode; } // console.log({ enter, enterNotIgnored }); var initCodeAstNodes = babylon .parse(usableHelperCode) .program.body.reverse(); initCodeAstNodes.forEach(node => { path.node.body.unshift(node); }); } }; return { name: "fromjs-babel-plugin", visitor: visitors }; } export default plugin;
the_stack
class Main extends egret.DisplayObjectContainer { public static menu: Menu; private static _that: egret.DisplayObjectContainer; private rewardedVideo: any; public constructor() { super(); this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); } private onAddToStage(event: egret.Event) { //初始化Facebook SDK,在回调方法里获取相关信息 egretfb.EgretFBInstant.initializeAsync().then(function () { egret.log("player.getID", egretfb.EgretFBInstant.player.getID()); try { egretfb.EgretFBInstant.player.getSignedPlayerInfoAsync('egret').then((result) => { try { egret.log('result.playerID', result.getPlayerID()) egret.log('result.getSignature.length', result.getSignature().length) } catch (err) { egret.log('SignedPlayerInfoAsync.err2', err) } }) } catch (err) { egret.log('SignedPlayerInfoAsync.err1', err) } egret.log("player.getID", egretfb.EgretFBInstant.player.getID()); egret.log("player.getName", egretfb.EgretFBInstant.player.getName()); egret.log("player.getPhoto.length", egretfb.EgretFBInstant.player.getPhoto().length); egret.log("getLocale:", egretfb.EgretFBInstant.getLocale()); egret.log("getPlatform:", egretfb.EgretFBInstant.getPlatform()); egret.log("getSDKVersion", egretfb.EgretFBInstant.getSDKVersion()); egret.log("num getSupportedAPIs", egretfb.EgretFBInstant.getSupportedAPIs().length); egret.log('getEntryPointData', egretfb.EgretFBInstant.getEntryPointData()) }) this.createScence(); setTimeout(() => { egretfb.EgretFBInstant.setLoadingProgress(100); egretfb.EgretFBInstant.startGameAsync().then(() => { this.showScence(); }) }, 1000) } private createScence() { Main._that = this; Context.init(this.stage); Main.menu = new Menu("Egret Facebook SDK Test") this.addChild(Main.menu); Main.menu.addTestFunc("context", this.contextInfo, this); Main.menu.addTestFunc("setDataAsync", this.setDataAsync, this); Main.menu.addTestFunc("getDataAsync", this.getDataAsync, this); Main.menu.addTestFunc("flushDataAsync", this.flushDataAsync, this); Main.menu.addTestFunc("setStatsAsync", this.setStatsAsync, this); Main.menu.addTestFunc("getStatsAsync", this.getStatsAsync, this); Main.menu.addTestFunc("incrementStatsAsync", this.incrementStatsAsync, this); Main.menu.addTestFunc("getInterstitialAdAsync", this.getInterstitialAdAsync, this); Main.menu.addTestFunc("显示视频广告", this.playRewardedVideo, this); Main.menu.addTestFunc("getConnectedPlayersAsync", this.getConnectedPlayersAsync, this); Main.menu.addTestFunc("switchAsync", this.switchAsync, this); Main.menu.addTestFunc("chooseAsync", this.chooseAsync, this); Main.menu.addTestFunc("createAsync", this.createAsync, this); Main.menu.addTestFunc("getPlayersAsync", this.getPlayersAsync, this); Main.menu.addTestFunc("setSessionData", this.setSessionData, this); Main.menu.addTestFunc("shareAsync", this.shareAsync, this); Main.menu.addTestFunc("updateAsync", this.updateAsync, this); Main.menu.addTestFunc("logEvent", this.logEvent, this); Main.menu.addTestFunc("quit", this.quit, this); } public static backMenu(): void { Main._that.removeChildren(); Main._that.addChild(Main.menu); } private showScence() { egret.log('showScence') this.loadRewardedVideo(); egretfb.EgretFBInstant.onPause(() => { egret.log('onPause'); }); } private loadRewardedVideo() { egretfb.EgretFBInstant.getRewardedVideoAsync('380072779038584_503394323373095') .then((rewardedVideo) => { this.rewardedVideo = rewardedVideo; egret.log('开始加载视频广告,翻墙网络慢,请稍等..', JSON.stringify(rewardedVideo)) return this.rewardedVideo.loadAsync(); }).then(() => { egret.log('视频广告加载结束,可以播放 ') }, (err) => { egret.log('视频广告加载错误', JSON.stringify(err)); }) } async playRewardedVideo() { await this.rewardedVideo.showAsync(); this.loadRewardedVideo(); } private contextInfo() { egret.log('context.getID', egretfb.EgretFBInstant.context.getID()); egret.log('context.getType', egretfb.EgretFBInstant.context.getType()); egret.log('context.isSizeBetween0-10', JSON.stringify(egretfb.EgretFBInstant.context.isSizeBetween(0, 10))); } private setDataAsync() { var saveData = { score: 123, value: Math.floor(Math.random() * 100) } egretfb.EgretFBInstant.player.setDataAsync(saveData).then(() => { egret.log('data is set'); }) egret.log('setDataAsync', JSON.stringify(saveData)); } private getDataAsync() { egretfb.EgretFBInstant.player.getDataAsync(['score', 'value']).then((data) => { egret.log('getDataAsync', data['score'], data['value']) }) } private flushDataAsync() { var saveData = { score: 778, value: Math.floor(Math.random() * 100) } egret.log('flushDataAsync', JSON.stringify(saveData)); egretfb.EgretFBInstant.player.setDataAsync(saveData) .then(egretfb.EgretFBInstant.player.flushDataAsync) .then(() => { egret.log('flushDataAsync succ'); }) } private setStatsAsync() { var saveState = { level: 68, money: Math.floor(Math.random() * 100) } egretfb.EgretFBInstant.player .setStatsAsync(saveState) .then(function () { egret.log('data is set'); }); } private getStatsAsync() { egretfb.EgretFBInstant.player .getStatsAsync(['level', 'money']) .then(function (stats) { egret.log('getStatsAsync', JSON.stringify(stats)) }); } private incrementStatsAsync() { var saveState = { level: 15, money: 1276, life: 9 } egretfb.EgretFBInstant.player .incrementStatsAsync(saveState) .then(function (stats) { egret.log('incrementStatsAsync', JSON.stringify(stats)); }); } private getInterstitialAdAsync() { var ad = null; egretfb.EgretFBInstant.getInterstitialAdAsync('380072779038584_502979883414539') .then((interstitial) => { ad = interstitial; egret.log('interstitial', JSON.stringify(interstitial)) egret.log('getPlacementID', ad.getPlacementID()) return ad.loadAsync(); }).then(() => { egret.log('ad loaded'); // return ad.showAsync(); }, (err) => { egret.log('err', JSON.stringify(err)); }).then(() => { egret.log('watch ad'); }); } private getConnectedPlayersAsync() { egretfb.EgretFBInstant.player.getConnectedPlayersAsync().then((players) => { egret.log('getConnectedPlayersAsync.length', players.length) players.map((player) => {//好友很多的话,请注释此方法 egret.log('id', player.getID()); egret.log('name', player.getName()); }) }) } private switchAsync() { egret.log('context.id now:', egretfb.EgretFBInstant.context.getID()) egretfb.EgretFBInstant.context.switchAsync('12345678').then(() => { egret.log('context.id switch:', egretfb.EgretFBInstant.context.getID()) }, (err) => { egret.log('switchAsync error', JSON.stringify(err)); }) } private chooseAsync() { egret.log('context.id now:', egretfb.EgretFBInstant.context.getID()) egretfb.EgretFBInstant.context.chooseAsync().then(() => { egret.log('context.id chooseAsync:', egretfb.EgretFBInstant.context.getID()) }, (err) => { egret.log('chooseAsync error', JSON.stringify(err)); }) } private createAsync() { egretfb.EgretFBInstant.context.createAsync('123456').then(() => { egret.log('context.id chooseAsync:', egretfb.EgretFBInstant.context.getID()) }, (err) => { egret.log('chooseAsync error', JSON.stringify(err)); }) } private getPlayersAsync() { egretfb.EgretFBInstant.context.getPlayersAsync().then((players) => { egret.log('getPlayersAsync:', JSON.stringify(players)); }, (err) => { egret.log('getPlayersAsync error', JSON.stringify(err)); }) } private setSessionData() { egretfb.EgretFBInstant.setSessionData({ coinsEarned: 10, eventsSeen: ['start', 'zhangyu'] }) } private shareAsync() { var shareObj:egretfb.EgretSharePayload = { intent: 'REQUEST', image: '', text: 'zhangyu is asking for your help!', data: { myReplayData: '...' } }; egretfb.EgretFBInstant.shareAsync(shareObj).then(function () { egret.log('share end! continue game') }); } private updateAsync() { egretfb.EgretFBInstant.updateAsync({ action: 'CUSTOM', cta: 'Join The Fight', template: 'join_fight', image: '', text: 'zhangyu just invaded Y\'s village!', data: { myReplayData: 'good' }, strategy: 'IMMEDIATE', notification: 'NO_PUSH', }).then(function () { //当消息发送后,关闭游戏 egretfb.EgretFBInstant.quit(); }); } private logEvent() { var logged = egretfb.EgretFBInstant.logEvent( 'my_custom_event', 42, { custom_property: 'custom_value' }, ); egret.log('logEvent', logged); } private quit() { egretfb.EgretFBInstant.quit(); } }
the_stack
import '../../../test/common-test-setup-karma'; import './gr-permission'; import {GrPermission} from './gr-permission'; import {stubRestApi} from '../../../test/test-utils'; import {GitRef, GroupId, GroupName} from '../../../types/common'; import {PermissionAction} from '../../../constants/constants'; import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions'; import { AutocompleteCommitEventDetail, GrAutocomplete, } from '../../shared/gr-autocomplete/gr-autocomplete'; import {queryAndAssert} from '../../../test/test-utils'; import {GrRuleEditor} from '../gr-rule-editor/gr-rule-editor'; import {GrButton} from '../../shared/gr-button/gr-button'; const basicFixture = fixtureFromElement('gr-permission'); suite('gr-permission tests', () => { let element: GrPermission; setup(() => { element = basicFixture.instantiate(); stubRestApi('getSuggestedGroups').returns( Promise.resolve({ Administrators: { id: '4c97682e6ce61b7247f3381b6f1789356666de7f' as GroupId, }, 'Anonymous Users': { id: 'global%3AAnonymous-Users' as GroupId, }, }) ); }); suite('unit tests', () => { test('_sortPermission', () => { const permission = { id: 'submit' as GitRef, value: { rules: { 'global:Project-Owners': { action: PermissionAction.ALLOW, force: false, }, '4c97682e6ce6b7247f3381b6f1789356666de7f': { action: PermissionAction.ALLOW, force: false, }, }, }, }; const expectedRules = [ { id: '4c97682e6ce6b7247f3381b6f1789356666de7f' as GitRef, value: {action: PermissionAction.ALLOW, force: false}, }, { id: 'global:Project-Owners' as GitRef, value: {action: PermissionAction.ALLOW, force: false}, }, ]; element._sortPermission(permission); assert.deepEqual(element._rules, expectedRules); }); test('_computeLabel and _computeLabelValues', () => { const labels = { 'Code-Review': { default_value: 0, values: { ' 0': 'No score', '-1': 'I would prefer this is not merged as is', '-2': 'This shall not be merged', '+1': 'Looks good to me, but someone else must approve', '+2': 'Looks good to me, approved', }, }, }; let permission = { id: 'label-Code-Review' as GitRef, value: { label: 'Code-Review', rules: { 'global:Project-Owners': { action: PermissionAction.ALLOW, force: false, min: -2, max: 2, }, '4c97682e6ce6b7247f3381b6f1789356666de7f': { action: PermissionAction.ALLOW, force: false, min: -2, max: 2, }, }, }, }; const expectedLabelValues = [ {value: -2, text: 'This shall not be merged'}, {value: -1, text: 'I would prefer this is not merged as is'}, {value: 0, text: 'No score'}, {value: 1, text: 'Looks good to me, but someone else must approve'}, {value: 2, text: 'Looks good to me, approved'}, ]; const expectedLabel = { name: 'Code-Review', values: expectedLabelValues, }; assert.deepEqual( element._computeLabelValues(labels['Code-Review'].values), expectedLabelValues ); assert.deepEqual( element._computeLabel(permission, labels), expectedLabel ); permission = { id: 'label-reviewDB' as GitRef, value: { label: 'reviewDB', rules: { 'global:Project-Owners': { action: PermissionAction.ALLOW, force: false, min: 0, max: 0, }, '4c97682e6ce6b7247f3381b6f1789356666de7f': { action: PermissionAction.ALLOW, force: false, min: 0, max: 0, }, }, }, }; assert.isNotOk(element._computeLabel(permission, labels)); }); test('_computeSectionClass', () => { let deleted = true; let editing = false; assert.equal(element._computeSectionClass(editing, deleted), 'deleted'); deleted = false; assert.equal(element._computeSectionClass(editing, deleted), ''); editing = true; assert.equal(element._computeSectionClass(editing, deleted), 'editing'); deleted = true; assert.equal( element._computeSectionClass(editing, deleted), 'editing deleted' ); }); test('_computeGroupName', () => { const groups = { abc123: {id: '1' as GroupId, name: 'test group' as GroupName}, bcd234: {id: '1' as GroupId}, }; assert.equal( element._computeGroupName(groups, 'abc123' as GroupId), 'test group' as GroupName ); assert.equal( element._computeGroupName(groups, 'bcd234' as GroupId), 'bcd234' as GroupName ); }); test('_computeGroupsWithRules', () => { const rules = [ { id: '4c97682e6ce6b7247f3381b6f1789356666de7f' as GitRef, value: {action: PermissionAction.ALLOW, force: false}, }, { id: 'global:Project-Owners' as GitRef, value: {action: PermissionAction.ALLOW, force: false}, }, ]; const groupsWithRules = { '4c97682e6ce6b7247f3381b6f1789356666de7f': true, 'global:Project-Owners': true, }; assert.deepEqual(element._computeGroupsWithRules(rules), groupsWithRules); }); test('_getGroupSuggestions without existing rules', async () => { element._groupsWithRules = {}; const groups = await element._getGroupSuggestions(); assert.deepEqual(groups, [ { name: 'Administrators', value: '4c97682e6ce61b7247f3381b6f1789356666de7f', }, { name: 'Anonymous Users', value: 'global%3AAnonymous-Users', }, ]); }); test('_getGroupSuggestions with existing rules filters them', async () => { element._groupsWithRules = { '4c97682e6ce61b7247f3381b6f1789356666de7f': true, }; const groups = await element._getGroupSuggestions(); assert.deepEqual(groups, [ { name: 'Anonymous Users', value: 'global%3AAnonymous-Users', }, ]); }); test('_handleRemovePermission', () => { element.editing = true; element.permission = {id: 'test' as GitRef, value: {rules: {}}}; element._handleRemovePermission(); assert.isTrue(element._deleted); assert.isTrue(element.permission.value.deleted); element.editing = false; assert.isFalse(element._deleted); assert.isNotOk(element.permission.value.deleted); }); test('_handleUndoRemove', () => { element.permission = { id: 'test' as GitRef, value: {deleted: true, rules: {}}, }; element._handleUndoRemove(); assert.isFalse(element._deleted); assert.isNotOk(element.permission.value.deleted); }); test('_computeHasRange', () => { assert.isTrue(element._computeHasRange('Query Limit')); assert.isTrue(element._computeHasRange('Batch Changes Limit')); assert.isFalse(element._computeHasRange('test')); }); }); suite('interactions', () => { setup(() => { sinon.spy(element, '_computeLabel'); element.name = 'Priority'; element.section = 'refs/*' as GitRef; element.labels = { 'Code-Review': { values: { ' 0': 'No score', '-1': 'I would prefer this is not merged as is', '-2': 'This shall not be merged', '+1': 'Looks good to me, but someone else must approve', '+2': 'Looks good to me, approved', }, default_value: 0, }, }; element.permission = { id: 'label-Code-Review' as GitRef, value: { label: 'Code-Review', rules: { 'global:Project-Owners': { action: PermissionAction.ALLOW, force: false, min: -2, max: 2, }, '4c97682e6ce6b7247f3381b6f1789356666de7f': { action: PermissionAction.ALLOW, force: false, min: -2, max: 2, }, }, }, }; element._setupValues(); flush(); }); test('adding a rule', () => { element.name = 'Priority'; element.section = 'refs/*' as GitRef; element.groups = {}; queryAndAssert<GrAutocomplete>(element, '#groupAutocomplete').text = 'ldap/tests te.st'; const e = { detail: { value: 'ldap:CN=test+te.st', }, } as CustomEvent<AutocompleteCommitEventDetail>; element.editing = true; assert.equal(element._rules!.length, 2); assert.equal(Object.keys(element._groupsWithRules!).length, 2); element._handleAddRuleItem(e); flush(); assert.deepEqual(element.groups, { 'ldap:CN=test te.st': { name: 'ldap/tests te.st', }, }); assert.equal(element._rules!.length, 3); assert.equal(Object.keys(element._groupsWithRules!).length, 3); assert.deepEqual(element.permission!.value.rules['ldap:CN=test te.st'], { action: PermissionAction.ALLOW, min: -2, max: 2, added: true, }); assert.equal( queryAndAssert<GrAutocomplete>(element, '#groupAutocomplete').text, '' ); // New rule should be removed if cancel from editing. element.editing = false; assert.equal(element._rules!.length, 2); assert.equal(Object.keys(element.permission!.value.rules).length, 2); }); test('removing an added rule', async () => { element.name = 'Priority'; element.section = 'refs/*' as GitRef; element.groups = {}; queryAndAssert<GrAutocomplete>(element, '#groupAutocomplete').text = 'new group name'; assert.equal(element._rules!.length, 2); queryAndAssert<GrRuleEditor>(element, 'gr-rule-editor').dispatchEvent( new CustomEvent('added-rule-removed', { composed: true, bubbles: true, }) ); await flush(); assert.equal(element._rules!.length, 1); }); test('removing an added permission', () => { const removeStub = sinon.stub(); element.addEventListener('added-permission-removed', removeStub); element.editing = true; element.name = 'Priority'; element.section = 'refs/*' as GitRef; element.permission!.value.added = true; MockInteractions.tap(queryAndAssert<GrButton>(element, '#removeBtn')); assert.isTrue(removeStub.called); }); test('removing the permission', () => { element.editing = true; element.name = 'Priority'; element.section = 'refs/*' as GitRef; const removeStub = sinon.stub(); element.addEventListener('added-permission-removed', removeStub); assert.isFalse( queryAndAssert(element, '#permission').classList.contains('deleted') ); assert.isFalse(element._deleted); MockInteractions.tap(queryAndAssert<GrButton>(element, '#removeBtn')); assert.isTrue( queryAndAssert(element, '#permission').classList.contains('deleted') ); assert.isTrue(element._deleted); MockInteractions.tap(queryAndAssert<GrButton>(element, '#undoRemoveBtn')); assert.isFalse( queryAndAssert(element, '#permission').classList.contains('deleted') ); assert.isFalse(element._deleted); assert.isFalse(removeStub.called); }); test('modify a permission', () => { element.editing = true; element.name = 'Priority'; element.section = 'refs/*' as GitRef; assert.isFalse(element._originalExclusiveValue); assert.isNotOk(element.permission!.value.modified); queryAndAssert(element, '#exclusiveToggle'); MockInteractions.tap(queryAndAssert(element, '#exclusiveToggle')); flush(); assert.isTrue(element.permission!.value.exclusive); assert.isTrue(element.permission!.value.modified); assert.isFalse(element._originalExclusiveValue); element.editing = false; assert.isFalse(element.permission!.value.exclusive); }); test('_handleValueChange', () => { const modifiedHandler = sinon.stub(); element.permission = {id: '0' as GitRef, value: {rules: {}}}; element.addEventListener('access-modified', modifiedHandler); assert.isNotOk(element.permission.value.modified); element._handleValueChange(); assert.isTrue(element.permission.value.modified); assert.isTrue(modifiedHandler.called); }); test('Exclusive hidden for owner permission', () => { queryAndAssert(element, '#exclusiveToggle'); assert.equal( getComputedStyle(queryAndAssert(element, '#exclusiveToggle')).display, 'flex' ); element.set(['permission', 'id'], 'owner'); flush(); assert.equal( getComputedStyle(queryAndAssert(element, '#exclusiveToggle')).display, 'none' ); }); test('Exclusive hidden for any global permissions', () => { assert.equal( getComputedStyle(queryAndAssert(element, '#exclusiveToggle')).display, 'flex' ); element.section = 'GLOBAL_CAPABILITIES' as GitRef; flush(); assert.equal( getComputedStyle(queryAndAssert(element, '#exclusiveToggle')).display, 'none' ); }); }); });
the_stack
import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core'; import { MatSort, MatTableDataSource, MatPaginator, PageEvent } from '@angular/material'; import { GlobalService } from '../../global.service'; import { Router, ActivatedRoute, NavigationEnd } from '@angular/router'; import { isNullOrUndefined } from 'util'; import { animate, state, style, transition, trigger } from '@angular/animations'; import { FileService } from 'src/app/Services/file.service'; import { DatePipe } from '@angular/common'; import * as moment from 'moment'; import { ErrorService } from 'src/app/Services/error.service'; import { RouterExtService } from 'src/app/Services/router-ext.service'; @Component({ selector: 'app-commit-details', templateUrl: './commit-details.component.html', styleUrls: ['./commit-details.component.css'], animations: [ trigger('detailExpand', [ state('collapsed', style({ 'height': '0px', 'minHeight': '0', 'display': 'none' })), state('expanded', style({ 'height': '*' })), transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')), ]), ], }) export class CommitDetailsComponent implements OnInit { dataSource: any; displayedColumns: string[] = ['commitId', 'timestamp', 'file_name', 'confidenceScore', 'prediction', 'commitDetails']; expandabledisplayedColumns: string[] = ['timestamp', 'fileName', 'confidenceScore', 'prediction', 'commitDetails']; data: any; expandedElement: any; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; positionOptions: any; position: any; fetchingData = false; pageEvent: PageEvent; pageSize: number = 10; pageIndex: number = 0; sortType: string = "timestamp"; sortBy: string = "desc"; totalLength: any; PIvar: number = 0; Dashboardview = false; constructor(public _globalService: GlobalService, public _fileService: FileService, public _errorService: ErrorService, private datePipe: DatePipe, private router: Router, private route: ActivatedRoute, private routerService: RouterExtService) { this.dataSource = null; this._globalService.loading = true; if (isNullOrUndefined(this._globalService.selectedProject)) { this.fetchingData = true; this.route.queryParams.subscribe(params => { if (params.length < 0) { if (isNullOrUndefined(this._globalService.selectedProject)) { this.router.navigate(['../ProjectDashboard'], { relativeTo: this.route }); } } this._globalService.getProjects().subscribe(data => { let result = data let projects = result["result"].projectList; this._globalService.projects = data["result"].projectList; this._globalService.selectedProject = projects[params["projectId"] - 1]; this.getCommitList(this._globalService.selectedProject.Id, this.pageIndex + 1, this.pageSize, this.sortType, this.sortBy); }, err => { if (err.status != null) { this._errorService.ErrorNumber = err.status; this._errorService.ErrorStatus = err.statusText; this._errorService.ErrorMessage = err.message; this.router.navigate(['../Error']); } } ); }); } else { if (!isNullOrUndefined(this._globalService.commitDetails) && !isNullOrUndefined(this._globalService.tableDataProjectName) && (this._globalService.viewChange) && this._globalService.tableDataProjectName == this._globalService.selectedProject.ProjectName) { console.log(this.routerService.getCurrentUrl()) this._globalService.viewChange = false; } else { this.getCommitList(this._globalService.selectedProject.Id, this.pageIndex + 1, this.pageSize, this.sortType, this.sortBy); } } } ngOnInit() { if (!this.fetchingData && !isNullOrUndefined(this._globalService.commitTableData) && !isNullOrUndefined(this._globalService.tableDataProjectName) && this._globalService.tableDataProjectName == this._globalService.selectedProject.ProjectName) { this.dataSource = this._globalService.commitTableData; } } ngAfterViewInit() { if (!this.fetchingData && !isNullOrUndefined(this._globalService.commitTableData) && !isNullOrUndefined(this._globalService.tableDataProjectName) && this._globalService.tableDataProjectName == this._globalService.selectedProject.ProjectName) { console.log(this._globalService.commitTableData.sort); console.log(this._globalService.commitTableData.paginator); this.pageSize = this._globalService.retainPageSize; this.pageIndex = this._globalService.retainPageIndex; this.totalLength = this._globalService.totalLength; //Retain Paginator // this.paginator.pageIndex=this._globalService.commitTableData.paginator.pageIndex; // this.paginator.pageSize=this._globalService.commitTableData.paginator.pageSize; // this.paginator.showFirstLastButtons=true; // this.paginator.hidePageSize=false; // this.paginator.disabled=false; // this.paginator.length=this._globalService.commitTableData.paginator.length; // this.dataSource.paginator = this.paginator; //Retain Sort // this.sort.direction = this._globalService.commitTableData.sort.direction; // this.sort.active = this._globalService.commitTableData.sort.active; //this.sort.sortables=this._globalService.commitTableData.sort.sortables; //this.sort.disabled=this._globalService.commitTableData.sort.disabled; // this.sort.initialized = this._globalService.commitTableData.sort.initialized; // this.dataSource.sort = this.sort; this._globalService.loading = false; } } getCommitList(Id: any, pageIndex: any, pageSize: any, sortType: any, sortBy: any) { this._globalService.resetGitHubUrl(); this._globalService.getCommitDetails(Id, pageIndex, pageSize, sortType, sortBy).subscribe(data => { console.log(data); let result = data["result"]; this._globalService.tableDataProjectName = this._globalService.selectedProject.ProjectName; this._globalService.commitDetails = result; this._globalService.projects = data["result"].projectList; this._globalService.gitbaseurl = this._globalService.gitbaseurl.replace('{project_name}', result.project_name); this.data = result.predictionListing; this.dataSource = new MatTableDataSource(this.data); console.log(result); this._globalService.commitTableData = this.dataSource; this.PIvar = 0; this.totalLength = result.total_commit_count; this._globalService.totalLength = result.total_commit_count; this._globalService.loading = false; }, err => { if (err.status != null) { this._errorService.ErrorNumber = err.status; this._errorService.ErrorStatus = err.statusText; this._errorService.ErrorMessage = err.message; this.router.navigate(['../Error']); } }); } expandedElementfn(row: any) { if (this._globalService.expandedElement == row) { this._globalService.expandedElement = null; } else { this._globalService.expandedElement = row; } } viewAllFiles(row: any) { this._fileService.selectedCommit = row.preds; this._fileService.commitId = row.commitId; this._globalService.viewChange = true; this.router.navigate(['../committedFiles'], { queryParams: { projectId: this._globalService.selectedProject.Id, commitId: this._fileService.commitId }, relativeTo: this.route }); } //Open file in GIT viewFile(url: any) { window.open(url, "_blank"); } loadBugRiskPrediction(row: any) { // console.log(Object.keys(row).length); if (isNullOrUndefined(row.total_count)) { this._fileService.selectedCommit = this._globalService.expandedElement.preds; this._fileService.commitId = this._globalService.expandedElement.commitId; this._fileService.selectedFile = row; } else { this._fileService.selectedCommit = row.preds; this._fileService.commitId = row.commitId; this._fileService.selectedFile = row.preds[0]; } // if (Object.keys(row).length > 4) { // this._fileService.selectedCommit = this._globalService.expandedElement.preds; // this._fileService.commitId = this._globalService.expandedElement.commitId; // this._fileService.selectedFile = row; // } // else { // this._fileService.selectedCommit = row.preds; // this._fileService.commitId = row.commitId; // this._fileService.selectedFile = row.preds[0]; // } this._globalService.viewChange = true; this.router.navigate(['../bugPrediction'], { queryParams: { projectId: this._globalService.selectedProject.Id, commitId: this._fileService.commitId, fileName: this._fileService.selectedFile.file_name }, relativeTo: this.route }); } viewFileByCommitId(base: any, commitId: any) { window.open(base + commitId, "_blank"); } getBuggyCount(row: any) { return row.preds.filter(x => x.prediction == 1).length; } getDate(timestamp: any) { var momentDate = moment(timestamp); if (!momentDate.isValid()) return timestamp; return momentDate.format("YYYY-MM-DD"); } getTime(timestamp: any) { var momentDate = moment(timestamp); if (!momentDate.isValid()) return timestamp; return momentDate.format("hh:mm:ss"); } getAMPM(timestamp: any) { var momentDate = moment(timestamp); if (!momentDate.isValid()) return timestamp; return momentDate.format("A"); } getFileName(fileName: any) { let a = fileName.split('/'); let fname = String(a[a.length - 1]); if (fname.length < 60) { return fname; } return "..." + fname.slice(fname.length - 50, fname.length); } getFilepath(file: any) { } getDataSource(predictions: any) { if (predictions.length > 5) { return predictions.slice(0, 5); } return predictions; } padZero(n: any) { return (n < 10) ? ("0" + String(n)) : String(n); } public getServerData(event?: PageEvent) { this._globalService.loading = true; console.log(event.pageIndex); this.PIvar = 1; this._globalService.retainPageSize = event.pageSize; this._globalService.retainPageIndex = event.pageIndex; this.getCommitList(this._globalService.selectedProject.Id, event.pageIndex + 1, this._globalService.retainPageSize, this.sortType, this.sortBy); } public sortData(event) { this._globalService.loading = true; console.log(event); this.sortType = event.active; this.sortBy = event.direction; // if (event.direction == "") { // event.direction = this.sortBy; // } console.log(this._globalService.retainPageSize); console.log(this._globalService.retainPageIndex); this.getCommitList(this._globalService.selectedProject.Id, this._globalService.retainPageIndex + 1, this._globalService.retainPageSize, this.sortType, event.direction); } }
the_stack
import * as AsyncLock from 'async-lock' import { getLogger, hexStrToBuf, hexBufToStr, logError, SignatureVerifier, DefaultSignatureVerifier, serializeObject, serializeObjectAsHexString, SignatureProvider, } from '@pigi/core-utils' import { DB, EthereumListener, EthereumEvent } from '@pigi/core-db' /* Internal Imports */ import { UnipigAggregator } from '../types/unipig-aggregator' import { Address, isFaucetTransaction, isSwapTransaction, NotSyncedError, RollupBlock, RollupBlockSubmitter, RollupStateMachine, RollupTransaction, RollupTransition, Signature, SignedStateReceipt, SignedTransaction, StateReceipt, StateSnapshot, StateUpdate, SwapTransition, Transfer, TransferTransition, } from '../types' import { abiEncodeStateReceipt, abiEncodeTransaction, abiEncodeTransition, parseTransitionFromABI, } from '../common/serialization' import { EMPTY_AGGREGATOR_SIGNATURE, generateTransferTx, PIGI_TOKEN_TYPE, UNI_TOKEN_TYPE, UNISWAP_ADDRESS, } from '../common' const log = getLogger('rollup-aggregator') /* * An aggregator implementation which allows for transfers, swaps, * balance queries, & faucet requests. */ export class RollupAggregator implements EthereumListener<EthereumEvent>, UnipigAggregator { public static readonly PENDING_BLOCK_KEY: Buffer = Buffer.from( 'pending_block_number' ) public static readonly LAST_TRANSITION_KEY: Buffer = Buffer.from( 'last_transition' ) public static readonly TRANSACTION_COUNT_KEY: Buffer = Buffer.from('tx_count') public static readonly TX_COUNT_STORAGE_THRESHOLD: number = 7 private static readonly lockKey: string = 'lock' private readonly lock: AsyncLock private synced: boolean private transactionCount: number private pendingBlock: RollupBlock private lastBlockSubmission: Date public static async create( db: DB, rollupStateMachine: RollupStateMachine, rollupBlockSubmitter: RollupBlockSubmitter, signatureProvider: SignatureProvider, signatureVerifier: SignatureVerifier = DefaultSignatureVerifier.instance(), blockSubmissionTransitionCount: number = 100, blockSubmissionIntervalMillis: number = 300_000, authorizedFaucetAddress?: Address ): Promise<RollupAggregator> { const aggregator = new RollupAggregator( db, rollupStateMachine, rollupBlockSubmitter, signatureProvider, signatureVerifier, blockSubmissionTransitionCount, blockSubmissionIntervalMillis, authorizedFaucetAddress ) await aggregator.init() return aggregator } private constructor( private readonly db: DB, private readonly rollupStateMachine: RollupStateMachine, private readonly rollupBlockSubmitter: RollupBlockSubmitter, private readonly signatureProvider: SignatureProvider, private readonly signatureVerifier: SignatureVerifier = DefaultSignatureVerifier.instance(), private readonly blockSubmissionTransitionCount: number = 100, private readonly blockSubmissionIntervalMillis: number = 300_000, private readonly authorizedFaucetAddress?: Address ) { this.pendingBlock = { blockNumber: 1, transitions: [], } this.lock = new AsyncLock() this.synced = false } /** * Initialize method, required for the Aggregator to load existing state before * it can handle requests. */ private async init(): Promise<void> { try { const [ pendingBlockNumberBuffer, lastTransitionBuffer, txCountBuffer, ] = await Promise.all([ this.db.get(RollupAggregator.PENDING_BLOCK_KEY), this.db.get(RollupAggregator.LAST_TRANSITION_KEY), this.db.get(RollupAggregator.TRANSACTION_COUNT_KEY), ]) // Fresh start -- nothing in the DB if (!lastTransitionBuffer) { log.info(`Init returning -- no stored last transition.`) this.transactionCount = 0 this.lastBlockSubmission = new Date() return } this.transactionCount = txCountBuffer ? parseInt(txCountBuffer.toString(), 10) : 0 const pendingBlock: number = pendingBlockNumberBuffer ? parseInt(pendingBlockNumberBuffer.toString(), 10) : 1 const lastTransition: number = parseInt( lastTransitionBuffer.toString(), 10 ) const promises: Array<Promise<Buffer>> = [] for (let i = 1; i <= lastTransition; i++) { promises.push(this.db.get(RollupAggregator.getTransitionKey(i))) } const transitionBuffers: Buffer[] = await Promise.all(promises) const transitions: RollupTransition[] = transitionBuffers.map((x) => parseTransitionFromABI(hexBufToStr(x)) ) this.pendingBlock = { blockNumber: pendingBlock, transitions, } log.info( `Initialized aggregator with pending block: ${JSON.stringify( this.pendingBlock )}` ) this.lastBlockSubmission = new Date() this.setBlockSubmissionTimeout() } catch (e) { logError(log, 'Error initializing aggregator', e) throw e } } public async onSyncCompleted(syncIdentifier?: string): Promise<void> { this.synced = true } public async handle(event: EthereumEvent): Promise<void> { log.debug(`Aggregator received event: ${JSON.stringify(event)}`) if (!!event && !!event.values && 'blockNumber' in event.values) { await this.rollupBlockSubmitter.handleNewRollupBlock( (event.values['blockNumber'] as any).toNumber() ) } } public async getTransactionCount(): Promise<number> { return this.transactionCount } public async getState(address: string): Promise<SignedStateReceipt> { if (!this.synced) { throw new NotSyncedError() } try { const stateReceipt: StateReceipt = await this.lock.acquire( RollupAggregator.lockKey, async () => { const snapshot: StateSnapshot = await this.rollupStateMachine.getState( address ) return { blockNumber: this.pendingBlock.blockNumber, transitionIndex: this.pendingBlock.transitions.length, ...snapshot, } } ) let signature: Signature if (!!stateReceipt.state) { signature = await this.signatureProvider.sign( abiEncodeStateReceipt(stateReceipt) ) } else { signature = EMPTY_AGGREGATOR_SIGNATURE } return { stateReceipt, signature, } } catch (e) { log.error( `Error getting state for address [${address}]! ${e.message}, ${e.stack}` ) throw e } } public async applyTransaction( signedTransaction: SignedTransaction ): Promise<SignedStateReceipt[]> { if (!this.synced) { throw new NotSyncedError() } try { const [ stateUpdate, blockNumber, transitionIndex, ] = await this.lock.acquire(RollupAggregator.lockKey, async () => { const update: StateUpdate = await this.rollupStateMachine.applyTransaction( signedTransaction ) await this.addToPendingBlock([update], signedTransaction) return [ update, this.pendingBlock.blockNumber, this.pendingBlock.transitions.length, ] }) if ( this.pendingBlock.transitions.length >= this.blockSubmissionTransitionCount ) { this.submitBlock() } await this.incrementTxCount() return this.respond(stateUpdate, blockNumber, transitionIndex) } catch (e) { log.error( `Error applying transaction [${serializeObject(signedTransaction)}]! ${ e.message }, ${e.stack}` ) throw e } } public async requestFaucetFunds( signedTransaction: SignedTransaction ): Promise<SignedStateReceipt> { if (!this.synced) { throw new NotSyncedError() } try { if (!isFaucetTransaction(signedTransaction.transaction)) { throw Error('Cannot handle non-Faucet Request in faucet endpoint') } const messageSigner: Address = this.signatureVerifier.verifyMessage( serializeObjectAsHexString(signedTransaction.transaction), signedTransaction.signature ) const requiredSigner = !!this.authorizedFaucetAddress ? this.authorizedFaucetAddress : signedTransaction.transaction.sender if (messageSigner !== requiredSigner) { throw Error( `Faucet requests must be signed by the authorized faucet requester address. Signer address: ${messageSigner}, required address: ${requiredSigner}` ) } // TODO: Probably need to check amount before blindly giving them this amount const { sender, amount } = signedTransaction.transaction // Generate the faucet txs (one sending uni the other pigi) const faucetTxs = await this.generateFaucetTxs( sender, // original tx sender... is actually faucet fund recipient amount ) const [ stateUpdate, blockNumber, transitionIndex, ] = await this.lock.acquire(RollupAggregator.lockKey, async () => { // Apply the two txs const updates: StateUpdate[] = await this.rollupStateMachine.applyTransactions( faucetTxs ) await this.addToPendingBlock(updates, signedTransaction) return [ updates[updates.length - 1], this.pendingBlock.blockNumber, this.pendingBlock.transitions.length, ] }) if ( this.pendingBlock.transitions.length >= this.blockSubmissionTransitionCount ) { this.submitBlock() } await this.incrementTxCount() return (await this.respond(stateUpdate, blockNumber, transitionIndex))[1] } catch (e) { log.error( `Error handling faucet request [${serializeObject( signedTransaction )}]! ${e.message}, ${e.stack}` ) throw e } } /** * Responds to the provided RollupTransaction according to the provided resulting state * update and rollup transition. * * @param stateUpdate The state update that resulted from this transaction * @param blockNumber The block number of this update * @param transitionIndex The transition index of this update * @returns The signed state receipt objects for the */ private async respond( stateUpdate: StateUpdate, blockNumber: number, transitionIndex: number ): Promise<SignedStateReceipt[]> { const receipts: SignedStateReceipt[] = [] const senderReceipt: StateReceipt = { slotIndex: stateUpdate.senderSlotIndex, stateRoot: stateUpdate.stateRoot, state: stateUpdate.senderState, inclusionProof: stateUpdate.senderStateInclusionProof, blockNumber, transitionIndex, } const senderSignature: string = await this.signatureProvider.sign( abiEncodeStateReceipt(senderReceipt) ) receipts.push({ signature: senderSignature, stateReceipt: senderReceipt, }) if (stateUpdate.receiverState.pubkey !== UNISWAP_ADDRESS) { const recipientReceipt: StateReceipt = { slotIndex: stateUpdate.receiverSlotIndex, stateRoot: stateUpdate.stateRoot, state: stateUpdate.receiverState, inclusionProof: stateUpdate.receiverStateInclusionProof, blockNumber, transitionIndex, } const recipientSignature: string = await this.signatureProvider.sign( abiEncodeStateReceipt(recipientReceipt) ) receipts.push({ signature: recipientSignature, stateReceipt: recipientReceipt, }) } log.debug(`Returning receipts: ${serializeObject(receipts)}`) return receipts } /** * Adds and returns the pending transition(s) resulting from * the provided StateUpdate(s). * * @param updates The state updates in question * @param transaction The signed transaction received as input * @returns The rollup transition */ private async addToPendingBlock( updates: StateUpdate[], transaction: SignedTransaction ): Promise<RollupTransition[]> { const transitions: RollupTransition[] = [] if (isSwapTransaction(transaction.transaction)) { const update: StateUpdate = updates[0] const transition: SwapTransition = { stateRoot: update.stateRoot, senderSlotIndex: update.senderSlotIndex, uniswapSlotIndex: update.receiverSlotIndex, tokenType: transaction.transaction.tokenType, inputAmount: transaction.transaction.inputAmount, minOutputAmount: transaction.transaction.minOutputAmount, timeout: transaction.transaction.timeout, signature: transaction.signature, } this.pendingBlock.transitions.push(transition) await this.db.put( RollupAggregator.getTransitionKey(this.pendingBlock.transitions.length), hexStrToBuf(abiEncodeTransition(transition)) ) } else { // It's a transfer -- either faucet or p2p for (const u of updates) { const transition: TransferTransition = this.getTransferTransitionFromStateUpdate( u ) this.pendingBlock.transitions.push(transition) await this.db.put( RollupAggregator.getTransitionKey( this.pendingBlock.transitions.length ), hexStrToBuf(abiEncodeTransition(transition)) ) } } await this.db.put( RollupAggregator.LAST_TRANSITION_KEY, Buffer.from(this.pendingBlock.transitions.length.toString(10)) ) return transitions } /** * Creates a TransferTransition from the provided StateUpdate for a Transfer. * @param update The state update * @returns the TransferTransition */ private getTransferTransitionFromStateUpdate( update: StateUpdate ): TransferTransition { const transfer = update.transaction.transaction as Transfer const transition = { stateRoot: update.stateRoot, senderSlotIndex: update.senderSlotIndex, recipientSlotIndex: update.receiverSlotIndex, tokenType: transfer.tokenType, amount: transfer.amount, signature: update.transaction.signature, } if (update.receiverCreated) { transition['createdAccountPubkey'] = update.receiverState.pubkey } return transition } /** * Submits a block to the main chain, creating a new pending block for future * transitions. */ private async submitBlock(): Promise<void> { return this.lock.acquire(RollupAggregator.lockKey, async () => { if ( this.pendingBlock.transitions.length < this.blockSubmissionTransitionCount ) { const millisSinceLastSubmission: number = new Date().getTime() - this.lastBlockSubmission.getTime() if (millisSinceLastSubmission < this.blockSubmissionIntervalMillis) { this.setBlockSubmissionTimeout( this.blockSubmissionIntervalMillis - millisSinceLastSubmission ) return } else if (this.pendingBlock.transitions.length === 0) { this.setBlockSubmissionTimeout(this.blockSubmissionIntervalMillis) return } } const toSubmit = this.pendingBlock await this.rollupBlockSubmitter.submitBlock(toSubmit) this.pendingBlock = { blockNumber: toSubmit.blockNumber + 1, transitions: [], } await this.db.put(RollupAggregator.LAST_TRANSITION_KEY, Buffer.from('0')) await this.db.put( RollupAggregator.PENDING_BLOCK_KEY, Buffer.from(this.pendingBlock.blockNumber.toString(10)) ) this.lastBlockSubmission = new Date() this.setBlockSubmissionTimeout() }) } private setBlockSubmissionTimeout(timeoutMillis?: number): void { setTimeout(async () => { await this.submitBlock() }, timeoutMillis || this.blockSubmissionIntervalMillis) } public static getTransitionKey(transIndex: number): Buffer { return Buffer.from(`TRANS_${transIndex}`) } /** * Generates two transactions which together send the user some UNI * & some PIGI. * * @param recipient The address to receive the faucet tokens * @param amount The amount to receive * @returns The signed faucet transactions */ private async generateFaucetTxs( recipient: Address, amount: number ): Promise<SignedTransaction[]> { const address: string = await this.signatureProvider.getAddress() const txOne: RollupTransaction = generateTransferTx( address, recipient, UNI_TOKEN_TYPE, amount ) const txTwo: RollupTransaction = generateTransferTx( address, recipient, PIGI_TOKEN_TYPE, amount ) return [ { signature: await this.signatureProvider.sign( abiEncodeTransaction(txOne) ), transaction: txOne, }, { signature: await this.signatureProvider.sign( abiEncodeTransaction(txTwo) ), transaction: txTwo, }, ] } /** * Increments the total transaction count that this aggregator has processed, * saving periodically */ private async incrementTxCount(): Promise<void> { if ( ++this.transactionCount % RollupAggregator.TX_COUNT_STORAGE_THRESHOLD === 0 ) { try { await this.db.put( RollupAggregator.TRANSACTION_COUNT_KEY, Buffer.from(this.transactionCount.toString(10)) ) } catch (e) { logError(log, 'Error saving transaction count!', e) } } } /*********** * GETTERS * ***********/ public getPendingBlockNumber(): number { return this.pendingBlock.blockNumber } public getNextTransitionIndex(): number { return this.pendingBlock.transitions.length } }
the_stack
import type * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as TimelineModel from '../../models/timeline_model/timeline_model.js'; import * as Components from '../../ui/legacy/components/utils/utils.js'; import * as UI from '../../ui/legacy/legacy.js'; import {EventsTimelineTreeView} from './EventsTimelineTreeView.js'; import type {PerformanceModel} from './PerformanceModel.js'; import {Events} from './PerformanceModel.js'; import {TimelineLayersView} from './TimelineLayersView.js'; import {TimelinePaintProfilerView} from './TimelinePaintProfilerView.js'; import type {TimelineModeViewDelegate} from './TimelinePanel.js'; import {TimelineSelection} from './TimelinePanel.js'; import type {TimelineTreeView} from './TimelineTreeView.js'; import {BottomUpTimelineTreeView, CallTreeTimelineTreeView} from './TimelineTreeView.js'; import {TimelineDetailsContentHelper, TimelineUIUtils} from './TimelineUIUtils.js'; const UIStrings = { /** *@description Text for the summary view */ summary: 'Summary', /** *@description Text in Timeline Details View of the Performance panel */ bottomup: 'Bottom-Up', /** *@description Text in Timeline Details View of the Performance panel */ callTree: 'Call Tree', /** *@description Text in Timeline Details View of the Performance panel */ eventLog: 'Event Log', /** *@description The label for estimated total blocking time in the performance panel */ estimated: 'estimated', /** *@description Label for the total blocking time in the Performance Panel *@example {320.23} PH1 *@example {(estimated)} PH2 */ totalBlockingTimeSmss: 'Total blocking time: {PH1}ms{PH2}', /** *@description Text that is usually a hyperlink to more documentation */ learnMore: 'Learn more', /** *@description Title of the Layers tool */ layers: 'Layers', /** *@description Title of the paint profiler, old name of the performance pane */ paintProfiler: 'Paint Profiler', /** *@description Text in Timeline Details View of the Performance panel *@example {1ms} PH1 *@example {10ms} PH2 */ rangeSS: 'Range: {PH1} – {PH2}', }; const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineDetailsView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineDetailsView extends UI.Widget.VBox { private readonly detailsLinkifier: Components.Linkifier.Linkifier; private tabbedPane: UI.TabbedPane.TabbedPane; private readonly defaultDetailsWidget: UI.Widget.VBox; private readonly defaultDetailsContentElement: HTMLElement; private rangeDetailViews: Map<string, TimelineTreeView>; private readonly additionalMetricsToolbar: UI.Toolbar.Toolbar; private model!: PerformanceModel; private track?: TimelineModel.TimelineModel.Track|null; private lazyPaintProfilerView?: TimelinePaintProfilerView|null; private lazyLayersView?: TimelineLayersView|null; private preferredTabId?: string; private selection?: TimelineSelection|null; constructor(delegate: TimelineModeViewDelegate) { super(); this.element.classList.add('timeline-details'); this.detailsLinkifier = new Components.Linkifier.Linkifier(); this.tabbedPane = new UI.TabbedPane.TabbedPane(); this.tabbedPane.show(this.element); this.defaultDetailsWidget = new UI.Widget.VBox(); this.defaultDetailsWidget.element.classList.add('timeline-details-view'); this.defaultDetailsContentElement = this.defaultDetailsWidget.element.createChild('div', 'timeline-details-view-body vbox'); this.appendTab(Tab.Details, i18nString(UIStrings.summary), this.defaultDetailsWidget); this.setPreferredTab(Tab.Details); this.rangeDetailViews = new Map(); const bottomUpView = new BottomUpTimelineTreeView(); this.appendTab(Tab.BottomUp, i18nString(UIStrings.bottomup), bottomUpView); this.rangeDetailViews.set(Tab.BottomUp, bottomUpView); const callTreeView = new CallTreeTimelineTreeView(); this.appendTab(Tab.CallTree, i18nString(UIStrings.callTree), callTreeView); this.rangeDetailViews.set(Tab.CallTree, callTreeView); const eventsView = new EventsTimelineTreeView(delegate); this.appendTab(Tab.EventLog, i18nString(UIStrings.eventLog), eventsView); this.rangeDetailViews.set(Tab.EventLog, eventsView); this.additionalMetricsToolbar = new UI.Toolbar.Toolbar('timeline-additional-metrics'); this.element.appendChild(this.additionalMetricsToolbar.element); this.tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected, this.tabSelected, this); } setModel(model: PerformanceModel|null, track: TimelineModel.TimelineModel.Track|null): void { if (this.model !== model) { if (this.model) { this.model.removeEventListener(Events.WindowChanged, this.onWindowChanged, this); } this.model = (model as PerformanceModel); if (this.model) { this.model.addEventListener(Events.WindowChanged, this.onWindowChanged, this); } } this.track = track; this.tabbedPane.closeTabs([Tab.PaintProfiler, Tab.LayerViewer], false); for (const view of this.rangeDetailViews.values()) { view.setModel(model, track); } this.lazyPaintProfilerView = null; this.lazyLayersView = null; this.setSelection(null); // Add TBT info to the footer. this.additionalMetricsToolbar.removeToolbarItems(); if (model && model.timelineModel()) { const {estimated, time} = model.timelineModel().totalBlockingTime(); const isEstimate = estimated ? ` (${i18nString(UIStrings.estimated)})` : ''; const message = i18nString(UIStrings.totalBlockingTimeSmss, {PH1: time.toFixed(2), PH2: isEstimate}); const warning = document.createElement('span'); const clsLink = UI.XLink.XLink.create('https://web.dev/tbt/', i18nString(UIStrings.learnMore)); // crbug.com/1103188: In dark mode the focus ring is hidden by the surrounding // container of this link. For some additional spacing on the right to make // sure the ring is fully visible. clsLink.style.marginRight = '2px'; warning.appendChild(clsLink); this.additionalMetricsToolbar.appendText(message); this.additionalMetricsToolbar.appendToolbarItem(new UI.Toolbar.ToolbarItem(warning)); } } private setContent(node: Node): void { const allTabs = this.tabbedPane.otherTabs(Tab.Details); for (let i = 0; i < allTabs.length; ++i) { if (!this.rangeDetailViews.has(allTabs[i])) { this.tabbedPane.closeTab(allTabs[i]); } } this.defaultDetailsContentElement.removeChildren(); this.defaultDetailsContentElement.appendChild(node); } private updateContents(): void { const view = this.rangeDetailViews.get(this.tabbedPane.selectedTabId || ''); if (view) { const window = this.model.window(); view.updateContents(this.selection || TimelineSelection.fromRange(window.left, window.right)); } } private appendTab(id: string, tabTitle: string, view: UI.Widget.Widget, isCloseable?: boolean): void { this.tabbedPane.appendTab(id, tabTitle, view, undefined, undefined, isCloseable); if (this.preferredTabId !== this.tabbedPane.selectedTabId) { this.tabbedPane.selectTab(id); } } headerElement(): Element { return this.tabbedPane.headerElement(); } setPreferredTab(tabId: string): void { this.preferredTabId = tabId; } private onWindowChanged(): void { if (!this.selection) { this.updateContentsFromWindow(); } } private updateContentsFromWindow(): void { if (!this.model) { this.setContent(UI.Fragment.html`<div/>`); return; } const window = this.model.window(); this.updateSelectedRangeStats(window.left, window.right); this.updateContents(); } setSelection(selection: TimelineSelection|null): void { this.detailsLinkifier.reset(); this.selection = selection; if (!this.selection) { this.updateContentsFromWindow(); return; } switch (this.selection.type()) { case TimelineSelection.Type.TraceEvent: { const event = (this.selection.object() as SDK.TracingModel.Event); TimelineUIUtils.buildTraceEventDetails(event, this.model.timelineModel(), this.detailsLinkifier, true) .then(fragment => this.appendDetailsTabsForTraceEventAndShowDetails(event, fragment)); break; } case TimelineSelection.Type.Frame: { const frame = (this.selection.object() as TimelineModel.TimelineFrameModel.TimelineFrame); const filmStripFrame = this.model.filmStripModelFrame(frame); this.setContent(TimelineUIUtils.generateDetailsContentForFrame(frame, filmStripFrame)); if (frame.layerTree) { const layersView = this.layersView(); layersView.showLayerTree(frame.layerTree); if (!this.tabbedPane.hasTab(Tab.LayerViewer)) { this.appendTab(Tab.LayerViewer, i18nString(UIStrings.layers), layersView); } } break; } case TimelineSelection.Type.NetworkRequest: { const request = (this.selection.object() as TimelineModel.TimelineModel.NetworkRequest); TimelineUIUtils.buildNetworkRequestDetails(request, this.model.timelineModel(), this.detailsLinkifier) .then(this.setContent.bind(this)); break; } case TimelineSelection.Type.Range: { this.updateSelectedRangeStats(this.selection.startTime(), this.selection.endTime()); break; } } this.updateContents(); } private tabSelected(event: Common.EventTarget.EventTargetEvent<UI.TabbedPane.EventData>): void { if (!event.data.isUserGesture) { return; } this.setPreferredTab(event.data.tabId); this.updateContents(); } private layersView(): TimelineLayersView { if (this.lazyLayersView) { return this.lazyLayersView; } this.lazyLayersView = new TimelineLayersView(this.model.timelineModel(), this.showSnapshotInPaintProfiler.bind(this)); return this.lazyLayersView; } private paintProfilerView(): TimelinePaintProfilerView { if (this.lazyPaintProfilerView) { return this.lazyPaintProfilerView; } this.lazyPaintProfilerView = new TimelinePaintProfilerView(this.model.frameModel()); return this.lazyPaintProfilerView; } private showSnapshotInPaintProfiler(snapshot: SDK.PaintProfiler.PaintProfilerSnapshot): void { const paintProfilerView = this.paintProfilerView(); paintProfilerView.setSnapshot(snapshot); if (!this.tabbedPane.hasTab(Tab.PaintProfiler)) { this.appendTab(Tab.PaintProfiler, i18nString(UIStrings.paintProfiler), paintProfilerView, true); } this.tabbedPane.selectTab(Tab.PaintProfiler, true); } private appendDetailsTabsForTraceEventAndShowDetails(event: SDK.TracingModel.Event, content: Node): void { this.setContent(content); if (event.name === TimelineModel.TimelineModel.RecordType.Paint || event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { this.showEventInPaintProfiler(event); } } private showEventInPaintProfiler(event: SDK.TracingModel.Event): void { const paintProfilerModel = SDK.TargetManager.TargetManager.instance().models(SDK.PaintProfiler.PaintProfilerModel)[0]; if (!paintProfilerModel) { return; } const paintProfilerView = this.paintProfilerView(); const hasProfileData = paintProfilerView.setEvent(paintProfilerModel, event); if (!hasProfileData) { return; } if (this.tabbedPane.hasTab(Tab.PaintProfiler)) { return; } this.appendTab(Tab.PaintProfiler, i18nString(UIStrings.paintProfiler), paintProfilerView); } private updateSelectedRangeStats(startTime: number, endTime: number): void { if (!this.model || !this.track) { return; } const aggregatedStats = TimelineUIUtils.statsForTimeRange(this.track.syncEvents(), startTime, endTime); const startOffset = startTime - this.model.timelineModel().minimumRecordTime(); const endOffset = endTime - this.model.timelineModel().minimumRecordTime(); const contentHelper = new TimelineDetailsContentHelper(null, null); contentHelper.addSection(i18nString( UIStrings.rangeSS, {PH1: i18n.TimeUtilities.millisToString(startOffset), PH2: i18n.TimeUtilities.millisToString(endOffset)})); const pieChart = TimelineUIUtils.generatePieChart(aggregatedStats); contentHelper.appendElementRow('', pieChart); this.setContent(contentHelper.fragment); } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum Tab { Details = 'Details', EventLog = 'EventLog', CallTree = 'CallTree', BottomUp = 'BottomUp', PaintProfiler = 'PaintProfiler', LayerViewer = 'LayerViewer', }
the_stack
module Inknote { var keysDown: number[] = []; if (typeof document != "undefined" && typeof window != "undefined") { document.onkeydown = function (e) { if (e.target == document.getElementById("file-search") && e.keyCode != 27) { return; } if (e.target == document.getElementById("smart-search-text") && e.keyCode != 27) { return; } keysDown.push(e.keyCode); if (CONFIRM_IS_OPEN) { return; } if (Modal.isModalOpen === true) { return; } // ctrl if (anyItemIs(keysDown, function (item: number) { return item == 17; })) { // c // copy if (e.keyCode == 67) { ClipboardService.Instance.copy(); } // v // paste if (e.keyCode == 86) { ClipboardService.Instance.paste(); } // x // cut if (e.keyCode == 88) { ClipboardService.Instance.cut(); } // z // undo if (e.keyCode == 90) { UndoService.Instance.undo(); } // s // save if (e.keyCode == 83) { Action(ActionType.SaveProject); e.preventDefault(); } // p // print if (e.keyCode == 80) { PrintService.Instance.print(); e.preventDefault(); } // f // find if (e.keyCode == 70) { FrontEnd.SmartSearch.openSearch(); e.preventDefault(); } } if (e.keyCode == 8) { e.preventDefault(); } } window.onkeyup = function (ev: KeyboardEvent) { if (ev.target == document.getElementById("file-search") && ev.keyCode != 27) { return; } if (ev.target == document.getElementById("smart-search-text") && ev.keyCode != 27) { return; } keysDown = getItemsWhere(keysDown, function (item: number) { return item != ev.keyCode; }); if (anyItemIs(keysDown, function (item: number) { return item == 17; })) { return; } if (CONFIRM_IS_OPEN) { return; } if (Modal.isModalOpen === true && ev.keyCode != 27) { return; } switch (Managers.PageManager.Current.page) { case Managers.Page.File: fileType(ev); break; case Managers.Page.Score: scoreType(ev); break; default: break; } } } function scoreType(e: KeyboardEvent) { var inst = Managers.ProjectManager.Instance; var proj = inst.currentProject; // name is selected var noteVal: Model.NoteValue = null; if (!ProjectConverter.name.select) { switch (e.keyCode) { // esc case 27: Action(ActionType.ToPage, Managers.Page.File); Modal.cancelReport(); Modal.hideAllModals(); FrontEnd.SmartSearch.closeSearch(); break; // a case 65: noteVal = Model.NoteValue.C; break; // w case 87: noteVal = Model.NoteValue.Db; break; // s case 83: noteVal = Model.NoteValue.D; break; // e case 69: noteVal = Model.NoteValue.Eb; break; // d case 68: noteVal = Model.NoteValue.E; break; // f case 70: noteVal = Model.NoteValue.F; break; // t case 84: noteVal = Model.NoteValue.Gb; break; // g case 71: noteVal = Model.NoteValue.G; break; // y case 89: noteVal = Model.NoteValue.Ab; break; // h case 72: noteVal = Model.NoteValue.A; break; // u case 85: noteVal = Model.NoteValue.Bb; break; // j case 74: noteVal = Model.NoteValue.B; break; // left case 37: ScoringService.Instance.cursorLeft(); break; // right case 39: ScoringService.Instance.cursorRight(); break; // up case 38: NoteControlService.Instance.noteValueUp(); break; // down case 40: NoteControlService.Instance.noteValueDown(); break; // delete case 8: case 46: NoteControlService.Instance.deleteSelected(); break; // SPACE case 32: Audio.AudioService.Instance.toggle(); break; // < case 188: // [ case 219: NoteControlService.Instance.piano.octave--; break; // > case 190: // ] case 221: NoteControlService.Instance.piano.octave++; break; // + case 107: NoteControlService.Instance.show(); break; // - case 109: NoteControlService.Instance.hide(); break; default: log("key pressed: " + e.keyCode); } } if (noteVal != null) { if (ScoringService.Instance.selectID == null || ScoringService.Instance.SelectedItem instanceof Drawing.Bar) { NoteControlService.Instance.addNote( new Model.Note( noteVal, NoteControlService.Instance.piano.octave, NoteControlService.Instance.lengthControl.selectedLength)); } else { NoteControlService.Instance.editNoteValueAndOctave(noteVal, NoteControlService.Instance.piano.octave); } } if (ScoringService.Instance.SelectedItem instanceof Drawing.Clef) { switch (e.keyCode) { // up case 38: NoteControlService.Instance.editCurrentClef(true); break; // down case 40: NoteControlService.Instance.editCurrentClef(false); break; } } if (inst.selectID == proj.ID) { if (e.keyCode == 13) { // enter inst.selectID = null; } else if (countWhere([16, 17, 18, 20], function (item: number) { return item == e.keyCode }) > 0) { // alt, ctrl shift, etc } else if (e.keyCode == 8) { // backspace proj.name = proj.name.substr(0, proj.name.length - 1); } else if (e.keyCode == 46) { // delete proj.name = ""; } else { proj.name = pascalCase(proj.name + String.fromCharCode(e.keyCode)); } e.preventDefault(); return; } e.preventDefault(); switch (e.keyCode) { // m case 77: Menu.toggle(); return; case 78: Inknote.Action(ActionType.NewProject, Managers.Page.Score); return; } } function fileType(e: KeyboardEvent) { var inst = Managers.ProjectManager.Instance; var proj = inst.currentProject; if (e.keyCode == 13) { // enter inst.openSelectedProject(); } else if (e.keyCode == 38) { // up ScrollService.Instance.up(); } else if (e.keyCode == 40) { // down ScrollService.Instance.down(); } else if (e.keyCode == 37) { // left inst.previous(); } else if (e.keyCode == 39) { // right inst.next(); } else if (e.keyCode == 46) { // delete inst.deleteSelectedProject(); } switch (e.keyCode) { // esc case 27: Menu.closeAllSubMenus(); if (Menu.isMenuOpen) { Menu.toggle(); } Modal.cancelReport(); Modal.hideAllModals(); RightClickMenuService.Instance.visible = false; FrontEnd.hideElement(document.getElementById("search-bar")); FrontEnd.SmartSearch.closeSearch(); return; // SPACE case 32: FrontEnd.showElement(document.getElementById("search-bar")); return; // m case 77: Menu.toggle(); return; // n case 78: Inknote.Action(ActionType.NewProject, Managers.Page.Score); return; } } }
the_stack
import MapOverlay from '../effects/MapOverlay'; import GameState from '../states/GameState'; import { IKeymap } from '../data/Keymap'; import Constants from '../data/Constants'; import Hud from '../gui/Hud'; import Dialog from '../gui/Dialog'; import Entity from '../entities/Entity'; export default class Level extends GameState { // key for the level data levelKey: string = ''; // the reference to the tiled map tiledmap: Phaser.Plugin.Tiled.Tilemap = null; // layer and zone tracking activeZone: Phaser.Plugin.Tiled.ITiledObject = null; oldZone: Phaser.Plugin.Tiled.ITiledObject = null; oldLayer: Phaser.Plugin.Tiled.Objectlayer = null; oldLayerOverlay: Phaser.Plugin.Tiled.Objectlayer = null; activeLayer: Phaser.Plugin.Tiled.Objectlayer = null; activeLayerOverlay: Phaser.Plugin.Tiled.Objectlayer = null; // ambient music music: Phaser.Sound = null; // misc sprites used for map effects overlay: MapOverlay = null; dialog: Dialog = null; hud: Hud = null; keymap: IKeymap = { keyboard: { up: Phaser.Keyboard.W, down: Phaser.Keyboard.S, left: Phaser.Keyboard.A, right: Phaser.Keyboard.D, use: Phaser.Keyboard.E, useItem: Phaser.Keyboard.V, attack: Phaser.Keyboard.SPACEBAR, menuSave: Phaser.Keyboard.B, menuMap: Phaser.Keyboard.M, menuInv: Phaser.Keyboard.I, }, gamepad: { up: Phaser.Gamepad.XBOX360_DPAD_UP, down: Phaser.Gamepad.XBOX360_DPAD_DOWN, left: Phaser.Gamepad.XBOX360_DPAD_LEFT, right: Phaser.Gamepad.XBOX360_DPAD_RIGHT, use: Phaser.Gamepad.XBOX360_A, useItem: Phaser.Gamepad.XBOX360_Y, attack: Phaser.Gamepad.XBOX360_B, menuSave: Phaser.Gamepad.XBOX360_BACK, menuMap: Phaser.Gamepad.XBOX360_X, menuInv: Phaser.Gamepad.XBOX360_START, }, }; // flag whether the zone load private _firstZone: boolean = true; // the data loaded for this level in its pack private _packData: any = null; private _tempVector: Phaser.Point = new Phaser.Point(); // private _bgtx: Phaser.RenderTexture = null; // private _bgspr: Phaser.Sprite = null; private _cameraBounds: Phaser.Rectangle; private _paused: boolean = false; preload() { super.preload(); // should be loaded by the preloader state this._packData = this.cache.getJSON(Constants.ASSET_TILEMAP_PACKS_KEY); this.load.pack(this.levelKey, null, this._packData); } create() { super.create(); this.overlay = this.add.existing(new MapOverlay(this.game)); this._cameraBounds = new Phaser.Rectangle(0, 0, 0, 0); this.dialog = this.add.existing(new Dialog(this.game, null, true, false)); this.dialog.fixedToCamera = true; this.dialog.cameraOffset.set(34, 146); this.hud = this.add.existing(new Hud(this.game)); this.hud.fixedToCamera = true; this.hud.cameraOffset.set(0, 0); // this._bgtx = this.game.add.renderTexture(this.game.width, this.game.height); // this._bgspr = this.game.add.sprite(0, 0, this._bgtx); // this._bgspr.fixedToCamera = true; // this._bgspr.name = '_bgSprite'; // this._bgspr.visible = false; // These <any> casts are because typescript doesn't have a method for extending existing classes // defined in external .d.ts files. This means phaser-tiled can't properly extend the type defs // for the classes it added methods to. I promise these exist :) // More info: // https://github.com/Microsoft/TypeScript/issues/9 // https://github.com/Microsoft/TypeScript/issues/819 this.tiledmap = (<any>this.add).tiledmap(this.levelKey); (<any>this.physics.p2).convertTiledCollisionObjects(this.tiledmap, 'collisions'); (<any>this.physics.p2).convertTiledCollisionObjects(this.tiledmap, 'exits'); (<any>this.physics.p2).convertTiledCollisionObjects(this.tiledmap, 'zones'); if (Constants.DEBUG) { // this._enableDebugBodies(this.tiledmap.getObjectlayer('collisions')); this._enableDebugBodies(this.tiledmap.getObjectlayer('exits')); // this._enableDebugBodies(this.tiledmap.getObjectlayer('zones')); } // setup the player for a new level const exit = this.game.loadedSave.lastUsedExit; this.game.player.reset(exit.properties.loc[0], exit.properties.loc[1]); this.game.player.setup(this); this.game.player.onReadSign.add((sign: Entity) => { this.showDialog(sign.properties.text); }, this); this.game.player.onInventoryChange.add(() => { this.hud.updateValues(this.game.player); }, this); this.hud.updateValues(this.game.player); this.tiledmap.getObjectlayer('player').add(this.game.player); // ensure gravity is off this.game.physics.p2.world.gravity[0] = 0; this.game.physics.p2.world.gravity[1] = 0; // setup camera to follow the player this.game.camera.follow(this.game.player, Phaser.Camera.FOLLOW_LOCKON); // setup handlers for player sensor collisions this.game.physics.p2.onBeginContact.add(this.onBeginContact, this); this.game.physics.p2.onEndContact.add(this.onEndContact, this); this._firstZone = true; // this.lastExit = exit; // set link position // this.game.player.position.set( // exit.properties.loc[0], // exit.properties.loc[1] // ); this.world.bringToTop(this.overlay); this.world.bringToTop(this.dialog); this.world.bringToTop(this.hud); } shutdown() { super.shutdown(); // lose reference to player in camera this.game.camera.unfollow(); // transitioning to a new state will destroy the world, including the player so remove it. this.game.player.parent.removeChild(this.game.player); this.game.player.onReadSign.removeAll(this); this.game.player.onInventoryChange.removeAll(this); // remove the listeners or they will keep firing this.game.physics.p2.onBeginContact.removeAll(this); this.game.physics.p2.onEndContact.removeAll(this); this.activeZone = null; this.oldZone = null; this.oldLayer = null; this.oldLayerOverlay = null; this.activeLayer = null; this.activeLayerOverlay = null; this.overlay.destroy(true); this.overlay = null; this.dialog.destroy(true); this.dialog = null; } showDialog(text: (string|string[])) { this.pause(); this.dialog.show(text); } pause() { // // render the current world onto a texture // this.hud.visible = false; // this._bgtx.render(this.world); // this._bgspr.visible = true; // // turn the camera back on // this.hud.visible = true; // // hides and stop updates to the world // this.world.visible = false; this._paused = true; // stop physics updates this.physics.p2.pause(); } resume() { // this._bgspr.visible = false; // this.world.visible = true; this._paused = false; // restart physics simulation this.physics.p2.resume(); } onBeginContact(bodyA: p2.IBodyEx, bodyB: p2.IBodyEx, shapeA: p2.Shape, shapeB: p2.Shape, contactEquations: any) { this._checkContact(true, bodyA, bodyB, shapeA, shapeB, contactEquations); } onEndContact(bodyA: p2.IBodyEx, bodyB: p2.IBodyEx, shapeA: p2.Shape, shapeB: p2.Shape, contactEquations: any) { this._checkContact(false, bodyA, bodyB, shapeA, shapeB, contactEquations); } /** * Input Handling */ onKeyboardDown(event: KeyboardEvent) { super.onKeyboardDown(event); this.handleKeyboard(event.keyCode, true); } onKeyboardUp(event: KeyboardEvent) { super.onKeyboardUp(event); this.handleKeyboard(event.keyCode, false); } onGamepadDown(button: number, value: number) { super.onGamepadDown(button, value); this.handleGamepadButton(button, value, true); } onGamepadUp(button: number, value: number) { super.onGamepadUp(button, value); this.handleGamepadButton(button, value, false); } onGamepadAxis(pad: Phaser.SinglePad, index: number, value: number) { super.onGamepadAxis(pad, index, value); this.handleGamepadAxis(index, value, true); } handleGamepadAxis(index: number, value: number, active: boolean) { // TODO: stick handling // switch(index) { // // AXIS UP/DOWN // case Phaser.Gamepad.XBOX360_STICK_LEFT_Y: // this.game.player.lookUp(value > 0 ? active : false); // this.game.player.duck(value < 0 ? active : false); // GarageServerIO.addInput({ name: 'lookUp', active: value > 0 ? active : false, value: value }); // GarageServerIO.addInput({ name: 'duck', active: value < 0 ? active : false, value: value }); // break; // // AXIS LEFT/RIGHT // case Phaser.Gamepad.XBOX360_STICK_LEFT_X: // this.game.player.move(Phaser.RIGHT, value, value > 0 ? active : false); // this.game.player.move(Phaser.LEFT, -value, value < 0 ? active : false); // GarageServerIO.addInput({ name: 'forward', active: value > 0 ? active : false, value: value }); // GarageServerIO.addInput({ name: 'backward', active: value < 0 ? active : false, value: -value }); // break; // } } handleKeyboard(key: number, active: boolean) { if (key === this.keymap.keyboard.use && this.dialog.visible) { if (this.dialog.typing || this.dialog.queue.length) { this.dialog.advance(); } else { this.dialog.hide(); this.resume(); } return; } if (this._paused) { return; } switch (key) { // use case this.keymap.keyboard.use: this.game.player.use(active); break; // use item case this.keymap.keyboard.useItem: this.game.player.useItem(active); break; // attack case this.keymap.keyboard.attack: this.game.player.attack(active); break; // UP case this.keymap.keyboard.up: this.game.player.move(Phaser.UP, 1, active); break; // DOWN case this.keymap.keyboard.down: this.game.player.move(Phaser.DOWN, 1, active); break; // LEFT case this.keymap.keyboard.left: this.game.player.move(Phaser.LEFT, 1, active); break; // RIGHT case this.keymap.keyboard.right: this.game.player.move(Phaser.RIGHT, 1, active); break; } } handleGamepadButton(button: number, value: number, active: boolean) { switch (button) { // UP case this.keymap.gamepad.up: this.game.player.move(Phaser.UP, value, active); break; // DOWN case this.keymap.gamepad.down: this.game.player.move(Phaser.DOWN, value, active); break; // LEFT case this.keymap.gamepad.left: this.game.player.move(Phaser.LEFT, value, active); break; // RIGHT case this.keymap.gamepad.right: this.game.player.move(Phaser.RIGHT, value, active); break; } } private _enableDebugBodies(layer: Phaser.Plugin.Tiled.Objectlayer) { if (!layer) { return; } for (let i = 0; i < layer.bodies.length; ++i) { let body: Phaser.Physics.P2.Body = layer.bodies[i]; body.debug = true; } } private _checkContact(begin: boolean, bodyA: p2.IBodyEx, bodyB: p2.IBodyEx, shapeA: p2.Shape, shapeB: p2.Shape, contactEquations: any) { if (!bodyA.parent || !bodyB.parent) { return; } if (bodyA.parent.sprite !== this.game.player && bodyB.parent.sprite !== this.game.player) { return; } const playerIsA = bodyA.parent.sprite === this.game.player; // const playerBody = playerIsA ? bodyA.parent : bodyB.parent; const playerShape = playerIsA ? shapeA : shapeB; const objBody = playerIsA ? bodyB.parent : bodyA.parent; const objShape = playerIsA ? shapeB : shapeA; const obj = objBody.sprite || (<any>objBody).tiledObject; // the tiledObject property is added by phaser-tiled if (!obj) { return; } if (begin && contactEquations.length && playerShape === this.game.player.bodyShape) { this._tempVector.set(-contactEquations[0].normalA[0], -contactEquations[0].normalA[1]); // colliding with a new zone if (obj.type === 'zone') { return this._zone(obj, this._tempVector); } // collide with an exit else if (obj.type === 'exit') { return this._exit(obj, this._tempVector); } } if (begin) { this.game.player.onBeginContact(obj, objShape, playerShape); } else { this.game.player.onEndContact(obj, objShape, playerShape); } } private _exit(exit: Phaser.Plugin.Tiled.ITiledObject, vec: TPoint) { if (!exit.properties.animation) { this._mapTransition(exit, vec); } else { this.game.player.events.onAnimationComplete.addOnce(function() { this._doMapTransition(exit, vec); this.game.player.unlock(); }, this); this.game.player.lock(); this.game.player.animations.play(exit.properties.animation); return; } } private _mapTransition(exit: Phaser.Plugin.Tiled.ITiledObject, vec: TPoint) { switch (exit.properties.transition) { case 'none': this._gotoLevel(exit, vec); break; case 'close': // make this work again... // this.camera.close('ellipse', animTime, this.link.position, function() { // self._dogotoMap(exit, vec); // }); /* falls through, for now */ case 'fade': /* falls through */ default: this.game.effects.fadeScreen(Constants.COLORS.BLACK, Constants.EFFECT_MAP_TRANSITION_TIME) .onComplete.addOnce(function () { this._gotoLevel(exit, vec); }, this); break; } } private _gotoLevel(exit: Phaser.Plugin.Tiled.ITiledObject, vec: TPoint) { this.game.save(exit); this.game.state.start('level_' + exit.name); } private _zone(zone: Phaser.Plugin.Tiled.ITiledObject, vec: TPoint) { // done repeat zoning if (zone === this.activeZone) { return; } // save old actives this.oldZone = this.activeZone; this.oldLayer = this.activeLayer; this.oldLayerOverlay = this.activeLayerOverlay; // assign new actives this.activeZone = zone; this.activeLayer = this.tiledmap.getObjectlayer(zone.name); this.activeLayerOverlay = this.tiledmap.getObjectlayer(zone.name + '_overlay'); // spawn layer objects this.activeLayer.spawn(Phaser.Physics.P2JS); this._setupOverlay(); this._setupZone(vec); } private _setupOverlay() { this.overlay.deactivate(); if (this.oldLayerOverlay) { this.oldLayerOverlay.despawn(); } // show overlay for layer or map if (this.activeLayerOverlay) { this.activeLayerOverlay.spawn(Phaser.Physics.P2JS); } else if (this.tiledmap.properties.overlay) { this.overlay.activate(this.tiledmap.properties.overlay); } } private _setupZone(vec: TPoint) { // const mapData = this.game.loadedSave.mapData[this.tiledmap.name]; // const zoneData = mapData ? mapData[this.activeLayer.name] : null; this.camera.unfollow(); this.camera.bounds = null; if (!this._firstZone) { this._zoneTransition(vec); } else { this._zoneReady(); } } private _zoneTransition(vec: TPoint) { const vel = vec.x ? vec.x : vec.y; const cameraEnd: TTable<number> = {}; this.game.player.lock(); switch (this.activeZone.properties.transition) { case 'fade': this.game.effects.fadeScreen(Constants.COLORS.BLACK, Constants.EFFECT_ZONE_TRANSITION_TIME) .onComplete.addOnce(function () { // pan camera this.camera.x += this.camera.width * vec.x; this.camera.y += this.camera.height * vec.y; this._transitionPlayer(!!vec.x, vel); // zone ready this._zoneReady(); }, this); break; case 'none': // pan camera this.camera.x += this.camera.width * vec.x; this.camera.y += this.camera.height * vec.y; this._transitionPlayer(!!vec.x, vel); // zone ready this._zoneReady(); break; case 'slide': /* falls through */ default: if (vec.x) { cameraEnd['x'] = this.camera.x + this.camera.width * vel; } else { cameraEnd['y'] = this.camera.y + this.camera.height * vel; } this.game.add.tween(this.camera) .to(cameraEnd, Constants.EFFECT_ZONE_TRANSITION_TIME) .start() .onComplete.addOnce(this._zoneReady, this); this._transitionPlayer(!!vec.x, vel, true); break; } } private _transitionPlayer(horizontal: boolean, vector: number, ease: boolean = true) { if (ease) { const playerEnd: TTable<number> = { x: this.game.player.body.x, y: this.game.player.body.y, }; playerEnd[horizontal ? 'x' : 'y'] += Constants.EFFECT_ZONE_TRANSITION_SPACE * vector; this.game.add.tween(this.game.player.body) .to(playerEnd, Constants.EFFECT_ZONE_TRANSITION_TIME) .start(); } else { if (horizontal) { this.game.player.body.x += Constants.EFFECT_ZONE_TRANSITION_SPACE * vector; } else { this.game.player.body.y += Constants.EFFECT_ZONE_TRANSITION_SPACE * vector; } } } private _zoneReady() { if (this.oldLayer) { this.game.save(null, this.oldLayer); this.oldLayer.despawn(); } const zone = this.activeZone; this._firstZone = false; this._cameraBounds.copyFrom(zone); this.camera.bounds = this._cameraBounds; this.camera.follow(this.game.player, Phaser.Camera.FOLLOW_LOCKON); // play zone music, or the map music if there is no zone music this._setupMusic(zone.properties.music || this.tiledmap.properties.music); this.game.player.unlock(); } private _setupMusic(key?: string) { // no key or already playing if (!key || (this.music && this.music.key === key)) { return; } // destroy current music object if (this.music) { this.music.destroy(); } this.music = this.add.audio(key, Constants.AUDIO_MUSIC_VOLUME, true); this.music.play(); } }
the_stack
import { Migrator as AppMigrator, getMigratorPlugins as getAppMigratorPlugins, MigrationAllOptions as AppMigrationAllOptions, } from '@nodepack/app-migrator' import { Migrator as EnvMigrator } from '@nodepack/env-migrator' import { Migrator as DbMigrator } from '@nodepack/db-migrator' import { getPlugins } from '@nodepack/plugins-resolution' import { readPkg, commitOnGit, shouldUseGit, hasGitChanges, installDeps, loadGlobalOptions, getPkgCommand, Preset, } from '@nodepack/utils' import { Hookable, ConfigHooks } from '@nodepack/hookable' import { loadFragment } from '@nodepack/fragment' import inquirer from 'inquirer' import execa from 'execa' import chalk from 'chalk' import consola from 'consola' const FRAGMENTS = [ 'config', 'context', 'runtime', ] const ENV_MIGRATION_FOLDER = 'migration/env' const DB_MIGRATION_FOLDER = 'migration/db' export interface MaintenanceHookAPI { cwd: string isTestOrDebug: boolean packageManager: string pkg: any plugins: string[] results: MaintenanceResults shouldCommitState: typeof Maintenance.prototype.shouldCommitState installDeps: typeof Maintenance.prototype.installDeps } export type MaintenanceHook = (api: MaintenanceHookAPI) => Promise<void> | void export interface MaintenanceHooks extends ConfigHooks { before?: MaintenanceHook afterAppMigrations?: MaintenanceHook afterEnvMigrations?: MaintenanceHook after?: MaintenanceHook } export interface MaintenanceOptions { /** Working directory */ cwd: string /** CLI options if any */ cliOptions?: any /** Project preset (used for project creation) */ preset?: Preset | null /** Don't try to commit with git */ skipCommit?: boolean /** Don't run install package at the begining of the maintenance */ skipPreInstall?: boolean /** Don't build app fragments like config */ skipBuild?: boolean /** Hooks */ hooks?: MaintenanceHooks | null } export interface MaintenanceResults { appMigrationAllOptions: AppMigrationAllOptions | null appMigrationCount: number envMigrationCount: number dbMigrationCount: number } /** * A Maintenance is a special system that should be run on user project * on most occasions (for example: project create, plugin add/update/remove...). * It will automatically execute maintenance operations like app and env migrations if needed. * It also has useful helpers for those occasions to reduce code duplication. */ export class Maintenance { cwd: string cliOptions: any preset: Preset | null skipCommit: boolean skipPreInstall: boolean skipBuild: boolean hooks: Hookable isTestOrDebug: boolean pkg: any plugins: string[] packageManager: string results: MaintenanceResults = { appMigrationAllOptions: null, appMigrationCount: 0, envMigrationCount: 0, dbMigrationCount: 0, } completeCbs: Function[] = [] context: any = null fragmentsBuilt = false constructor ({ cwd, cliOptions = {}, preset = null, skipCommit = false, skipPreInstall = false, skipBuild = false, hooks = null, }: MaintenanceOptions) { this.cwd = cwd this.cliOptions = cliOptions this.preset = preset this.skipCommit = skipCommit this.skipPreInstall = skipPreInstall this.skipBuild = skipBuild this.hooks = new Hookable() if (hooks) this.hooks.addHooks(hooks) // Are one of those vars non-empty? this.isTestOrDebug = !!(process.env.NODEPACK_TEST || process.env.NODEPACK_DEBUG) this.pkg = readPkg(this.cwd) this.plugins = getPlugins(this.pkg) this.packageManager = this.cliOptions.packageManager || loadGlobalOptions().packageManager || getPkgCommand(this.cwd) } async preInstall () { await this.installDeps(`📦 Checking dependencies installation...`) } async run () { await this.callHook('before') // pre-run install to be sure everything is up-to-date if (!this.skipPreInstall) { await this.preInstall() } // App Migrations await this.runAppMigrations() await this.callHook('afterAppMigrations') // Prepare context await this.createContext() // Env Migrations await this.runEnvMigrations() await this.callHook('afterEnvMigrations') // Database Migrations await this.runDbMigrations() await this.callHook('afterDbMigrations') consola.log(`🔧 Maintenance complete!`) await this.callHook('after') await this.callCompleteCbs() } async runAppMigrations () { const { cwd, plugins } = this const migratorPlugins = await getAppMigratorPlugins(cwd, plugins) const migrator = new AppMigrator(cwd, { plugins: migratorPlugins, }) const { migrations } = await migrator.prepareUp() if (migrations.length) { await this.shouldCommitState(`[nodepack] before app migration`) consola.log(`🚀 Migrating app code...`) const { migrationCount, allOptions } = await migrator.up(this.preset) consola.log(`📝 ${migrationCount} app migration${migrationCount > 1 ? 's' : ''} applied!`) this.results.appMigrationCount = migrationCount this.results.appMigrationAllOptions = allOptions // install additional deps (injected by migrations) await this.installDeps(`📦 Installing additional dependencies...`) await this.shouldCommitState(`[nodepack] after app migration`) } this.completeCbs.push(() => { migrator.displayNotices() }) } async runEnvMigrations () { const { cwd, context } = this const migrator = new EnvMigrator(cwd, { migrationsFolder: ENV_MIGRATION_FOLDER, }) const { files } = await migrator.prepareUp({ context, }) if (files.length) { // Migrate await this.shouldCommitState(`[nodepack] before env migration`) consola.log(`🚀 Migrating env...`) const { migrationCount } = await migrator.up({ context, }) consola.log(`💻️ ${migrationCount} env migration${migrationCount > 1 ? 's' : ''} applied!`) this.results.envMigrationCount = migrationCount // install additional deps (injected by migrations) await this.installDeps(`📦 Installing additional dependencies...`) await this.shouldCommitState(`[nodepack] after env migration`) } } async runDbMigrations () { const { cwd, context } = this if (!context.readDbMigrationRecords) return const migrator = new DbMigrator(cwd, { migrationsFolder: DB_MIGRATION_FOLDER, }) const { files } = await migrator.prepareUp({ context, }) if (files.length) { // Migrate await this.shouldCommitState(`[nodepack] before db migration`) consola.log(`🚀 Migrating db...`) const { migrationCount } = await migrator.up({ context, }) consola.log(`🗄️ ${migrationCount} db migration${migrationCount > 1 ? 's' : ''} applied!`) this.results.dbMigrationCount = migrationCount await this.shouldCommitState(`[nodepack] after db migration`) } } /** * @param {string} id */ async callHook (id) { // Hook API await this.hooks.callHook(id, { cwd: this.cwd, isTestOrDebug: this.isTestOrDebug, pkg: this.pkg, plugins: this.plugins, packageManager: this.packageManager, results: this.results, shouldCommitState: this.shouldCommitState.bind(this), installDeps: this.installDeps.bind(this), }) } async callCompleteCbs () { for (const cb of this.completeCbs) { await cb() } } /** * Should be called each time the project is about to be modified. * @param {string} defaultMessage * @param {boolean} force */ async shouldCommitState (defaultMessage, force = false) { if (this.skipCommit && !force) return // Commit app code before installing a new plugin // in case it modify files const shouldCommit = await shouldUseGit(this.cwd, this.cliOptions) && await hasGitChanges(this.cwd, false) if (shouldCommit) { const { success, message, error: e } = await commitOnGit(this.cwd, this.cliOptions, this.isTestOrDebug, defaultMessage) if (success) { consola.log(chalk.grey(`commit ${message}`), 'git') } else { consola.error(`Could not commit state`, e.stack || e) // Commit failed confirmation const answers = await inquirer.prompt<{ continue: boolean }>([ { name: 'continue', type: 'confirm', message: `Git commit "${defaultMessage}" failed, the current app code wasn't saved. Continue anyway?`, default: false, }, ]) if (!answers.continue) { process.exit() } } } } /** * @param {string?} message */ async installDeps (message = null) { if (!this.isTestOrDebug) { if (message) consola.log(message) await installDeps(this.cwd, this.packageManager, this.cliOptions.registry) } } /** * Build app fragments * @param {string[]} entryNames */ async buildFragments (entryNames) { if (this.fragmentsBuilt || this.skipBuild) return consola.log(`🔨️ Building fragments ${chalk.blue(entryNames.join(', '))}...`) try { const io = process.env.NODEPACK_DEBUG === 'true' ? 'inherit' : 'ignore' const result = await execa('nodepack-service', [ 'build', '--silent', '--no-autoNodeEnv', '--no-preInstall', ], { cwd: this.cwd, env: { NODEPACK_ENTRIES: entryNames.join(','), NODEPACK_NO_MAINTENANCE: 'true', NODEPACK_OUTPUT: '.nodepack/temp/fragments/', NODEPACK_RAW_STATS: 'true', NODEPACK_MAINTENANCE_FRAGMENTS: 'true', }, stdio: [io, io, 'inherit'], preferLocal: true, }) this.fragmentsBuilt = true if (result.failed) { console.log(result.all) throw new Error(`Fragment build failed`) } } catch (e) { if (e.failed) { console.log(e.all) } throw e } } async createContext () { if (this.context != null) return await this.buildFragments(FRAGMENTS) try { const { createContext } = loadFragment('context', this.cwd) this.context = await createContext() } catch (e) { consola.error('Failed loading context fragment') throw e } } }
the_stack
import { FeatureStateUpdate, StrategyAttributeDeviceName, RoleType, StrategyAttributeWellKnownNames, SSEResultState, FeatureState, StrategyAttributeCountryName, RolloutStrategyAttribute, RolloutStrategy, Environment, FeatureValueType, StrategyAttributePlatformName, RolloutStrategyAttributeConditional, RolloutStrategyFieldType } from './'; export class EnvironmentTypeTransformer { public static toJson(__val: Environment): any { const __data: any = {}; if (__val.id !== null && __val.id !== undefined) { __data['id'] = __val.id; } if (__val.features !== null && __val.features !== undefined) { __data['features'] = ObjectSerializer.serialize(__val.features, 'Array<FeatureState>'); } return __data; } // expect this to be a decoded value public static fromJson(__val: any): Environment { const __init: any = { id: __val['id'], features: ObjectSerializer.deserialize(__val['features'], 'Array<FeatureState>'), }; return new Environment(__init); } } export class FeatureStateTypeTransformer { public static toJson(__val: FeatureState): any { const __data: any = {}; if (__val.id !== null && __val.id !== undefined) { __data['id'] = __val.id; } if (__val.key !== null && __val.key !== undefined) { __data['key'] = __val.key; } if (__val.l !== null && __val.l !== undefined) { __data['l'] = __val.l; } if (__val.version !== null && __val.version !== undefined) { __data['version'] = __val.version; } if (__val.type !== null && __val.type !== undefined) { __data['type'] = ObjectSerializer.serialize(__val.type, 'FeatureValueType'); } if (__val.value !== null && __val.value !== undefined) { __data['value'] = __val.value; } if (__val.environmentId !== null && __val.environmentId !== undefined) { __data['environmentId'] = __val.environmentId; } if (__val.strategies !== null && __val.strategies !== undefined) { __data['strategies'] = ObjectSerializer.serialize(__val.strategies, 'Array<RolloutStrategy>'); } return __data; } // expect this to be a decoded value public static fromJson(__val: any): FeatureState { const __init: any = { id: __val['id'], key: __val['key'], l: __val['l'], version: __val['version'], type: ObjectSerializer.deserialize(__val['type'], 'FeatureValueType'), value: __val['value'], environmentId: __val['environmentId'], strategies: ObjectSerializer.deserialize(__val['strategies'], 'Array<RolloutStrategy>'), }; return new FeatureState(__init); } } export class FeatureStateUpdateTypeTransformer { public static toJson(__val: FeatureStateUpdate): any { const __data: any = {}; if (__val.value !== null && __val.value !== undefined) { __data['value'] = __val.value; } if (__val.updateValue !== null && __val.updateValue !== undefined) { __data['updateValue'] = __val.updateValue; } if (__val.lock !== null && __val.lock !== undefined) { __data['lock'] = __val.lock; } return __data; } // expect this to be a decoded value public static fromJson(__val: any): FeatureStateUpdate { const __init: any = { value: __val['value'], updateValue: __val['updateValue'], lock: __val['lock'], }; return new FeatureStateUpdate(__init); } } export class FeatureValueTypeTypeTransformer { public static toJson(__val: FeatureValueType): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): FeatureValueType { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'BOOLEAN': return FeatureValueType.Boolean; case 'STRING': return FeatureValueType.String; case 'NUMBER': return FeatureValueType.Number; case 'JSON': return FeatureValueType.Json; } return undefined; } } export class RoleTypeTypeTransformer { public static toJson(__val: RoleType): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): RoleType { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'READ': return RoleType.Read; case 'LOCK': return RoleType.Lock; case 'UNLOCK': return RoleType.Unlock; case 'CHANGE_VALUE': return RoleType.ChangeValue; } return undefined; } } export class RolloutStrategyTypeTransformer { public static toJson(__val: RolloutStrategy): any { const __data: any = {}; if (__val.id !== null && __val.id !== undefined) { __data['id'] = __val.id; } if (__val.name !== null && __val.name !== undefined) { __data['name'] = __val.name; } if (__val.percentage !== null && __val.percentage !== undefined) { __data['percentage'] = __val.percentage; } if (__val.percentageAttributes !== null && __val.percentageAttributes !== undefined) { __data['percentageAttributes'] = __val.percentageAttributes; } if (__val.colouring !== null && __val.colouring !== undefined) { __data['colouring'] = __val.colouring; } if (__val.avatar !== null && __val.avatar !== undefined) { __data['avatar'] = __val.avatar; } if (__val.value !== null && __val.value !== undefined) { __data['value'] = __val.value; } if (__val.attributes !== null && __val.attributes !== undefined) { __data['attributes'] = ObjectSerializer.serialize(__val.attributes, 'Array<RolloutStrategyAttribute>'); } return __data; } // expect this to be a decoded value public static fromJson(__val: any): RolloutStrategy { const __init: any = { id: __val['id'], name: __val['name'], percentage: __val['percentage'], percentageAttributes: __val['percentageAttributes'], colouring: __val['colouring'], avatar: __val['avatar'], value: __val['value'], attributes: ObjectSerializer.deserialize(__val['attributes'], 'Array<RolloutStrategyAttribute>'), }; return new RolloutStrategy(__init); } } export class RolloutStrategyAttributeTypeTransformer { public static toJson(__val: RolloutStrategyAttribute): any { const __data: any = {}; if (__val.id !== null && __val.id !== undefined) { __data['id'] = __val.id; } if (__val.conditional !== null && __val.conditional !== undefined) { __data['conditional'] = ObjectSerializer.serialize(__val.conditional, 'RolloutStrategyAttributeConditional'); } if (__val.fieldName !== null && __val.fieldName !== undefined) { __data['fieldName'] = __val.fieldName; } if (__val.values !== null && __val.values !== undefined) { __data['values'] = __val.values; } if (__val.type !== null && __val.type !== undefined) { __data['type'] = ObjectSerializer.serialize(__val.type, 'RolloutStrategyFieldType'); } return __data; } // expect this to be a decoded value public static fromJson(__val: any): RolloutStrategyAttribute { const __init: any = { id: __val['id'], conditional: ObjectSerializer.deserialize(__val['conditional'], 'RolloutStrategyAttributeConditional'), fieldName: __val['fieldName'], values: __val['values'], type: ObjectSerializer.deserialize(__val['type'], 'RolloutStrategyFieldType'), }; return new RolloutStrategyAttribute(__init); } } export class RolloutStrategyAttributeConditionalTypeTransformer { public static toJson(__val: RolloutStrategyAttributeConditional): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): RolloutStrategyAttributeConditional { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'EQUALS': return RolloutStrategyAttributeConditional.Equals; case 'ENDS_WITH': return RolloutStrategyAttributeConditional.EndsWith; case 'STARTS_WITH': return RolloutStrategyAttributeConditional.StartsWith; case 'GREATER': return RolloutStrategyAttributeConditional.Greater; case 'GREATER_EQUALS': return RolloutStrategyAttributeConditional.GreaterEquals; case 'LESS': return RolloutStrategyAttributeConditional.Less; case 'LESS_EQUALS': return RolloutStrategyAttributeConditional.LessEquals; case 'NOT_EQUALS': return RolloutStrategyAttributeConditional.NotEquals; case 'INCLUDES': return RolloutStrategyAttributeConditional.Includes; case 'EXCLUDES': return RolloutStrategyAttributeConditional.Excludes; case 'REGEX': return RolloutStrategyAttributeConditional.Regex; } return undefined; } } export class RolloutStrategyFieldTypeTypeTransformer { public static toJson(__val: RolloutStrategyFieldType): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): RolloutStrategyFieldType { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'STRING': return RolloutStrategyFieldType.String; case 'SEMANTIC_VERSION': return RolloutStrategyFieldType.SemanticVersion; case 'NUMBER': return RolloutStrategyFieldType.Number; case 'DATE': return RolloutStrategyFieldType.Date; case 'DATETIME': return RolloutStrategyFieldType.Datetime; case 'BOOLEAN': return RolloutStrategyFieldType.Boolean; case 'IP_ADDRESS': return RolloutStrategyFieldType.IpAddress; } return undefined; } } export class SSEResultStateTypeTransformer { public static toJson(__val: SSEResultState): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): SSEResultState { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'ack': return SSEResultState.Ack; case 'bye': return SSEResultState.Bye; case 'failure': return SSEResultState.Failure; case 'features': return SSEResultState.Features; case 'feature': return SSEResultState.Feature; case 'delete_feature': return SSEResultState.DeleteFeature; } return undefined; } } export class StrategyAttributeCountryNameTypeTransformer { public static toJson(__val: StrategyAttributeCountryName): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): StrategyAttributeCountryName { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'afghanistan': return StrategyAttributeCountryName.Afghanistan; case 'albania': return StrategyAttributeCountryName.Albania; case 'algeria': return StrategyAttributeCountryName.Algeria; case 'andorra': return StrategyAttributeCountryName.Andorra; case 'angola': return StrategyAttributeCountryName.Angola; case 'antigua_and_barbuda': return StrategyAttributeCountryName.AntiguaAndBarbuda; case 'argentina': return StrategyAttributeCountryName.Argentina; case 'armenia': return StrategyAttributeCountryName.Armenia; case 'australia': return StrategyAttributeCountryName.Australia; case 'austria': return StrategyAttributeCountryName.Austria; case 'azerbaijan': return StrategyAttributeCountryName.Azerbaijan; case 'the_bahamas': return StrategyAttributeCountryName.TheBahamas; case 'bahrain': return StrategyAttributeCountryName.Bahrain; case 'bangladesh': return StrategyAttributeCountryName.Bangladesh; case 'barbados': return StrategyAttributeCountryName.Barbados; case 'belarus': return StrategyAttributeCountryName.Belarus; case 'belgium': return StrategyAttributeCountryName.Belgium; case 'belize': return StrategyAttributeCountryName.Belize; case 'benin': return StrategyAttributeCountryName.Benin; case 'bhutan': return StrategyAttributeCountryName.Bhutan; case 'bolivia': return StrategyAttributeCountryName.Bolivia; case 'bosnia_and_herzegovina': return StrategyAttributeCountryName.BosniaAndHerzegovina; case 'botswana': return StrategyAttributeCountryName.Botswana; case 'brazil': return StrategyAttributeCountryName.Brazil; case 'brunei': return StrategyAttributeCountryName.Brunei; case 'bulgaria': return StrategyAttributeCountryName.Bulgaria; case 'burkina_faso': return StrategyAttributeCountryName.BurkinaFaso; case 'burundi': return StrategyAttributeCountryName.Burundi; case 'cabo_verde': return StrategyAttributeCountryName.CaboVerde; case 'cambodia': return StrategyAttributeCountryName.Cambodia; case 'cameroon': return StrategyAttributeCountryName.Cameroon; case 'canada': return StrategyAttributeCountryName.Canada; case 'central_african_republic': return StrategyAttributeCountryName.CentralAfricanRepublic; case 'chad': return StrategyAttributeCountryName.Chad; case 'chile': return StrategyAttributeCountryName.Chile; case 'china': return StrategyAttributeCountryName.China; case 'colombia': return StrategyAttributeCountryName.Colombia; case 'comoros': return StrategyAttributeCountryName.Comoros; case 'congo_democratic_republic_of_the': return StrategyAttributeCountryName.CongoDemocraticRepublicOfThe; case 'congo_republic_of_the': return StrategyAttributeCountryName.CongoRepublicOfThe; case 'costa_rica': return StrategyAttributeCountryName.CostaRica; case 'cote_divoire': return StrategyAttributeCountryName.CoteDivoire; case 'croatia': return StrategyAttributeCountryName.Croatia; case 'cuba': return StrategyAttributeCountryName.Cuba; case 'cyprus': return StrategyAttributeCountryName.Cyprus; case 'czech_republic': return StrategyAttributeCountryName.CzechRepublic; case 'denmark': return StrategyAttributeCountryName.Denmark; case 'djibouti': return StrategyAttributeCountryName.Djibouti; case 'dominica': return StrategyAttributeCountryName.Dominica; case 'dominican_republic': return StrategyAttributeCountryName.DominicanRepublic; case 'east_timor': return StrategyAttributeCountryName.EastTimor; case 'ecuador': return StrategyAttributeCountryName.Ecuador; case 'egypt': return StrategyAttributeCountryName.Egypt; case 'el_salvador': return StrategyAttributeCountryName.ElSalvador; case 'equatorial_guinea': return StrategyAttributeCountryName.EquatorialGuinea; case 'eritrea': return StrategyAttributeCountryName.Eritrea; case 'estonia': return StrategyAttributeCountryName.Estonia; case 'eswatini': return StrategyAttributeCountryName.Eswatini; case 'ethiopia': return StrategyAttributeCountryName.Ethiopia; case 'fiji': return StrategyAttributeCountryName.Fiji; case 'finland': return StrategyAttributeCountryName.Finland; case 'france': return StrategyAttributeCountryName.France; case 'gabon': return StrategyAttributeCountryName.Gabon; case 'the_gambia': return StrategyAttributeCountryName.TheGambia; case 'georgia': return StrategyAttributeCountryName.Georgia; case 'germany': return StrategyAttributeCountryName.Germany; case 'ghana': return StrategyAttributeCountryName.Ghana; case 'greece': return StrategyAttributeCountryName.Greece; case 'grenada': return StrategyAttributeCountryName.Grenada; case 'guatemala': return StrategyAttributeCountryName.Guatemala; case 'guinea': return StrategyAttributeCountryName.Guinea; case 'guinea_bissau': return StrategyAttributeCountryName.GuineaBissau; case 'guyana': return StrategyAttributeCountryName.Guyana; case 'haiti': return StrategyAttributeCountryName.Haiti; case 'honduras': return StrategyAttributeCountryName.Honduras; case 'hungary': return StrategyAttributeCountryName.Hungary; case 'iceland': return StrategyAttributeCountryName.Iceland; case 'india': return StrategyAttributeCountryName.India; case 'indonesia': return StrategyAttributeCountryName.Indonesia; case 'iran': return StrategyAttributeCountryName.Iran; case 'iraq': return StrategyAttributeCountryName.Iraq; case 'ireland': return StrategyAttributeCountryName.Ireland; case 'israel': return StrategyAttributeCountryName.Israel; case 'italy': return StrategyAttributeCountryName.Italy; case 'jamaica': return StrategyAttributeCountryName.Jamaica; case 'japan': return StrategyAttributeCountryName.Japan; case 'jordan': return StrategyAttributeCountryName.Jordan; case 'kazakhstan': return StrategyAttributeCountryName.Kazakhstan; case 'kenya': return StrategyAttributeCountryName.Kenya; case 'kiribati': return StrategyAttributeCountryName.Kiribati; case 'korea_north': return StrategyAttributeCountryName.KoreaNorth; case 'korea_south': return StrategyAttributeCountryName.KoreaSouth; case 'kosovo': return StrategyAttributeCountryName.Kosovo; case 'kuwait': return StrategyAttributeCountryName.Kuwait; case 'kyrgyzstan': return StrategyAttributeCountryName.Kyrgyzstan; case 'laos': return StrategyAttributeCountryName.Laos; case 'latvia': return StrategyAttributeCountryName.Latvia; case 'lebanon': return StrategyAttributeCountryName.Lebanon; case 'lesotho': return StrategyAttributeCountryName.Lesotho; case 'liberia': return StrategyAttributeCountryName.Liberia; case 'libya': return StrategyAttributeCountryName.Libya; case 'liechtenstein': return StrategyAttributeCountryName.Liechtenstein; case 'lithuania': return StrategyAttributeCountryName.Lithuania; case 'luxembourg': return StrategyAttributeCountryName.Luxembourg; case 'madagascar': return StrategyAttributeCountryName.Madagascar; case 'malawi': return StrategyAttributeCountryName.Malawi; case 'malaysia': return StrategyAttributeCountryName.Malaysia; case 'maldives': return StrategyAttributeCountryName.Maldives; case 'mali': return StrategyAttributeCountryName.Mali; case 'malta': return StrategyAttributeCountryName.Malta; case 'marshall_islands': return StrategyAttributeCountryName.MarshallIslands; case 'mauritania': return StrategyAttributeCountryName.Mauritania; case 'mauritius': return StrategyAttributeCountryName.Mauritius; case 'mexico': return StrategyAttributeCountryName.Mexico; case 'micronesia_federated_states_of': return StrategyAttributeCountryName.MicronesiaFederatedStatesOf; case 'moldova': return StrategyAttributeCountryName.Moldova; case 'monaco': return StrategyAttributeCountryName.Monaco; case 'mongolia': return StrategyAttributeCountryName.Mongolia; case 'montenegro': return StrategyAttributeCountryName.Montenegro; case 'morocco': return StrategyAttributeCountryName.Morocco; case 'mozambique': return StrategyAttributeCountryName.Mozambique; case 'myanmar': return StrategyAttributeCountryName.Myanmar; case 'namibia': return StrategyAttributeCountryName.Namibia; case 'nauru': return StrategyAttributeCountryName.Nauru; case 'nepal': return StrategyAttributeCountryName.Nepal; case 'netherlands': return StrategyAttributeCountryName.Netherlands; case 'new_zealand': return StrategyAttributeCountryName.NewZealand; case 'nicaragua': return StrategyAttributeCountryName.Nicaragua; case 'niger': return StrategyAttributeCountryName.Niger; case 'nigeria': return StrategyAttributeCountryName.Nigeria; case 'north_macedonia': return StrategyAttributeCountryName.NorthMacedonia; case 'norway': return StrategyAttributeCountryName.Norway; case 'oman': return StrategyAttributeCountryName.Oman; case 'pakistan': return StrategyAttributeCountryName.Pakistan; case 'palau': return StrategyAttributeCountryName.Palau; case 'panama': return StrategyAttributeCountryName.Panama; case 'papua_new_guinea': return StrategyAttributeCountryName.PapuaNewGuinea; case 'paraguay': return StrategyAttributeCountryName.Paraguay; case 'peru': return StrategyAttributeCountryName.Peru; case 'philippines': return StrategyAttributeCountryName.Philippines; case 'poland': return StrategyAttributeCountryName.Poland; case 'portugal': return StrategyAttributeCountryName.Portugal; case 'qatar': return StrategyAttributeCountryName.Qatar; case 'romania': return StrategyAttributeCountryName.Romania; case 'russia': return StrategyAttributeCountryName.Russia; case 'rwanda': return StrategyAttributeCountryName.Rwanda; case 'saint_kitts_and_nevis': return StrategyAttributeCountryName.SaintKittsAndNevis; case 'saint_lucia': return StrategyAttributeCountryName.SaintLucia; case 'saint_vincent_and_the_grenadines': return StrategyAttributeCountryName.SaintVincentAndTheGrenadines; case 'samoa': return StrategyAttributeCountryName.Samoa; case 'san_marino': return StrategyAttributeCountryName.SanMarino; case 'sao_tome_and_principe': return StrategyAttributeCountryName.SaoTomeAndPrincipe; case 'saudi_arabia': return StrategyAttributeCountryName.SaudiArabia; case 'senegal': return StrategyAttributeCountryName.Senegal; case 'serbia': return StrategyAttributeCountryName.Serbia; case 'seychelles': return StrategyAttributeCountryName.Seychelles; case 'sierra_leone': return StrategyAttributeCountryName.SierraLeone; case 'singapore': return StrategyAttributeCountryName.Singapore; case 'slovakia': return StrategyAttributeCountryName.Slovakia; case 'slovenia': return StrategyAttributeCountryName.Slovenia; case 'solomon_islands': return StrategyAttributeCountryName.SolomonIslands; case 'somalia': return StrategyAttributeCountryName.Somalia; case 'south_africa': return StrategyAttributeCountryName.SouthAfrica; case 'spain': return StrategyAttributeCountryName.Spain; case 'sri_lanka': return StrategyAttributeCountryName.SriLanka; case 'sudan': return StrategyAttributeCountryName.Sudan; case 'sudan_south': return StrategyAttributeCountryName.SudanSouth; case 'suriname': return StrategyAttributeCountryName.Suriname; case 'sweden': return StrategyAttributeCountryName.Sweden; case 'switzerland': return StrategyAttributeCountryName.Switzerland; case 'syria': return StrategyAttributeCountryName.Syria; case 'taiwan': return StrategyAttributeCountryName.Taiwan; case 'tajikistan': return StrategyAttributeCountryName.Tajikistan; case 'tanzania': return StrategyAttributeCountryName.Tanzania; case 'thailand': return StrategyAttributeCountryName.Thailand; case 'togo': return StrategyAttributeCountryName.Togo; case 'tonga': return StrategyAttributeCountryName.Tonga; case 'trinidad_and_tobago': return StrategyAttributeCountryName.TrinidadAndTobago; case 'tunisia': return StrategyAttributeCountryName.Tunisia; case 'turkey': return StrategyAttributeCountryName.Turkey; case 'turkmenistan': return StrategyAttributeCountryName.Turkmenistan; case 'tuvalu': return StrategyAttributeCountryName.Tuvalu; case 'uganda': return StrategyAttributeCountryName.Uganda; case 'ukraine': return StrategyAttributeCountryName.Ukraine; case 'united_arab_emirates': return StrategyAttributeCountryName.UnitedArabEmirates; case 'united_kingdom': return StrategyAttributeCountryName.UnitedKingdom; case 'united_states': return StrategyAttributeCountryName.UnitedStates; case 'uruguay': return StrategyAttributeCountryName.Uruguay; case 'uzbekistan': return StrategyAttributeCountryName.Uzbekistan; case 'vanuatu': return StrategyAttributeCountryName.Vanuatu; case 'vatican_city': return StrategyAttributeCountryName.VaticanCity; case 'venezuela': return StrategyAttributeCountryName.Venezuela; case 'vietnam': return StrategyAttributeCountryName.Vietnam; case 'yemen': return StrategyAttributeCountryName.Yemen; case 'zambia': return StrategyAttributeCountryName.Zambia; case 'zimbabwe': return StrategyAttributeCountryName.Zimbabwe; } return undefined; } } export class StrategyAttributeDeviceNameTypeTransformer { public static toJson(__val: StrategyAttributeDeviceName): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): StrategyAttributeDeviceName { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'browser': return StrategyAttributeDeviceName.Browser; case 'mobile': return StrategyAttributeDeviceName.Mobile; case 'desktop': return StrategyAttributeDeviceName.Desktop; case 'server': return StrategyAttributeDeviceName.Server; case 'watch': return StrategyAttributeDeviceName.Watch; case 'embedded': return StrategyAttributeDeviceName.Embedded; } return undefined; } } export class StrategyAttributePlatformNameTypeTransformer { public static toJson(__val: StrategyAttributePlatformName): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): StrategyAttributePlatformName { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'linux': return StrategyAttributePlatformName.Linux; case 'windows': return StrategyAttributePlatformName.Windows; case 'macos': return StrategyAttributePlatformName.Macos; case 'android': return StrategyAttributePlatformName.Android; case 'ios': return StrategyAttributePlatformName.Ios; } return undefined; } } export class StrategyAttributeWellKnownNamesTypeTransformer { public static toJson(__val: StrategyAttributeWellKnownNames): any { return __val?.toString(); } // expect this to be a decoded value public static fromJson(__val: any): StrategyAttributeWellKnownNames { if (__val === null || __val === undefined) return undefined; switch (__val.toString()) { case 'device': return StrategyAttributeWellKnownNames.Device; case 'country': return StrategyAttributeWellKnownNames.Country; case 'platform': return StrategyAttributeWellKnownNames.Platform; case 'userkey': return StrategyAttributeWellKnownNames.Userkey; case 'session': return StrategyAttributeWellKnownNames.Session; case 'version': return StrategyAttributeWellKnownNames.Version; } return undefined; } } const _regList = new RegExp('^Array\\<(.*)\\>$'); const _regSet = new RegExp('^Set\\<(.*)\\>$'); const _regRecord = new RegExp('^Record\\<string,(.*)\\>$'); const _regMap = new RegExp('^Map\\<string,(.*)\\>$'); const _baseEncoder = (type: string, value: any) => value; const _dateEncoder = (type: string, value: any) => { const val = value as Date; return `${val.getFullYear()}-${val.getMonth()}-${val.getDay()}`; }; export declare type EncoderFunc = (type: string, value: any) => any; export const serializers: Record<string, EncoderFunc> = { 'string': _baseEncoder, 'String': _baseEncoder, 'email': _baseEncoder, 'uuid': _baseEncoder, 'int': _baseEncoder, 'num': _baseEncoder, 'number': _baseEncoder, 'double': _baseEncoder, 'float': _baseEncoder, 'boolean': _baseEncoder, 'object': _baseEncoder, 'any': _baseEncoder, 'Array<string>': _baseEncoder, 'Array<String>': _baseEncoder, 'Array<email>': _baseEncoder, 'Array<int>': _baseEncoder, 'Array<num>': _baseEncoder, 'Array<number>': _baseEncoder, 'Array<double>': _baseEncoder, 'Array<float>': _baseEncoder, 'Array<boolean>': _baseEncoder, 'Array<object>': _baseEncoder, 'Array<any>': _baseEncoder, 'Date': _dateEncoder, 'DateTime': (t, value) => (value as Date).toISOString(), 'Environment': (t, value) => EnvironmentTypeTransformer.toJson(value), 'FeatureState': (t, value) => FeatureStateTypeTransformer.toJson(value), 'FeatureStateUpdate': (t, value) => FeatureStateUpdateTypeTransformer.toJson(value), 'FeatureValueType': (t, value) => FeatureValueTypeTypeTransformer.toJson(value), 'RoleType': (t, value) => RoleTypeTypeTransformer.toJson(value), 'RolloutStrategy': (t, value) => RolloutStrategyTypeTransformer.toJson(value), 'RolloutStrategyAttribute': (t, value) => RolloutStrategyAttributeTypeTransformer.toJson(value), 'RolloutStrategyAttributeConditional': (t, value) => RolloutStrategyAttributeConditionalTypeTransformer.toJson(value), 'RolloutStrategyFieldType': (t, value) => RolloutStrategyFieldTypeTypeTransformer.toJson(value), 'SSEResultState': (t, value) => SSEResultStateTypeTransformer.toJson(value), 'StrategyAttributeCountryName': (t, value) => StrategyAttributeCountryNameTypeTransformer.toJson(value), 'StrategyAttributeDeviceName': (t, value) => StrategyAttributeDeviceNameTypeTransformer.toJson(value), 'StrategyAttributePlatformName': (t, value) => StrategyAttributePlatformNameTypeTransformer.toJson(value), 'StrategyAttributeWellKnownNames': (t, value) => StrategyAttributeWellKnownNamesTypeTransformer.toJson(value), }; const _stringDecoder = (type: string, value: any) => value.toString(); const _passthroughDecoder = (type: string, value: any) => value; const _intDecoder = (type: string, value: any) => (value instanceof Number) ? value.toFixed() : parseInt(value.toString()); const _numDecoder = (type: string, value: any) => (value instanceof Number) ? value : parseFloat(value.toString()); const _dateDecoder = (type: string, value: any) => new Date(`${value}T00:00:00Z`); const _dateTimeDecoder = (type: string, value: any) => new Date(value.toString()); export const deserializers: Record<string, EncoderFunc> = { 'string': _stringDecoder, 'String': _stringDecoder, 'email': _stringDecoder, 'uuid': _stringDecoder, 'int': _intDecoder, 'num': _numDecoder, 'number': _numDecoder, 'double': _numDecoder, 'float': _numDecoder, 'boolean': _passthroughDecoder, 'object': _passthroughDecoder, 'any': _passthroughDecoder, 'Date': _dateDecoder, 'DateTime': _dateTimeDecoder, 'Environment': (t, value) => EnvironmentTypeTransformer.fromJson(value), 'FeatureState': (t, value) => FeatureStateTypeTransformer.fromJson(value), 'FeatureStateUpdate': (t, value) => FeatureStateUpdateTypeTransformer.fromJson(value), 'FeatureValueType': (t, value) => FeatureValueTypeTypeTransformer.fromJson(value), 'RoleType': (t, value) => RoleTypeTypeTransformer.fromJson(value), 'RolloutStrategy': (t, value) => RolloutStrategyTypeTransformer.fromJson(value), 'RolloutStrategyAttribute': (t, value) => RolloutStrategyAttributeTypeTransformer.fromJson(value), 'RolloutStrategyAttributeConditional': (t, value) => RolloutStrategyAttributeConditionalTypeTransformer.fromJson(value), 'RolloutStrategyFieldType': (t, value) => RolloutStrategyFieldTypeTypeTransformer.fromJson(value), 'SSEResultState': (t, value) => SSEResultStateTypeTransformer.fromJson(value), 'StrategyAttributeCountryName': (t, value) => StrategyAttributeCountryNameTypeTransformer.fromJson(value), 'StrategyAttributeDeviceName': (t, value) => StrategyAttributeDeviceNameTypeTransformer.fromJson(value), 'StrategyAttributePlatformName': (t, value) => StrategyAttributePlatformNameTypeTransformer.fromJson(value), 'StrategyAttributeWellKnownNames': (t, value) => StrategyAttributeWellKnownNamesTypeTransformer.fromJson(value), }; export class ObjectSerializer { public static deserializeOwn(value: any, innerType: string): any { const result: any = {}; for (let __prop in value) { if (value.hasOwnProperty(__prop)) { result[__prop] = ObjectSerializer.deserialize(value[__prop], innerType); } } return result; } public static serializeOwn(value: any, innerType: string): any { const result: any = {}; for (let __prop in value) { if (value.hasOwnProperty(__prop)) { result[__prop] = ObjectSerializer.serialize(value[__prop], innerType); } } return result; } public static serialize(value: any, targetType: string): any { if (value === null || value === undefined) { return undefined; } const encoder = serializers[targetType]; if (encoder) { return encoder(targetType, value); } var match: any; if (((match = targetType.match(_regRecord)) !== null) && match.length === 2) { return ObjectSerializer.serializeOwn(value, match[1].trim()); } else if ((value instanceof Array) && ((match = targetType.match(_regList)) !== null) && match.length === 2) { return value.map((v) => ObjectSerializer.serialize(v, match[1])); } else if ((value instanceof Array) && ((match = targetType.match(_regSet)) !== null) && match.length === 2) { return new Set(value.map((v) => ObjectSerializer.serialize(v, match[1]))); } else if ((value instanceof Set) && ((match = targetType.match(_regSet)) !== null) && match.length === 2) { return Array.from(value).map((v) => ObjectSerializer.serialize(v, match[1])); } else if (value instanceof Map && ((match = targetType.match(_regMap)) !== null) && match.length === 2) { return new Map(Array.from(value, ([k, v]) => [k, ObjectSerializer.serialize(v, match[1])])); } return undefined; } public static deserialize(value: any, targetType: string): any { if (value === null || value === undefined) return null; // 204 if (targetType === null || targetType === undefined) return value.toString(); // best guess const decoder = deserializers[targetType]; if (decoder) { return decoder(targetType, value); } var match: any; if (((match = targetType.match(_regRecord)) !== null) && match.length === 2) { // is an array we want an array return ObjectSerializer.deserializeOwn(value, match[1].trim()); } else if ((value instanceof Array) && ((match = targetType.match(_regList)) !== null) && match.length === 2) { return value.map((v) => ObjectSerializer.deserialize(v, match[1])); } else if ((value instanceof Array) && // is a array we want a set ((match = targetType.match(_regSet)) !== null) && match.length === 2) { return value.map((v) => ObjectSerializer.deserialize(v, match[1])); } else if ((value instanceof Set) && // is a set we want a set ((match = targetType.match(_regSet)) !== null) && match.length === 2) { return new Set(Array.from(value).map((v) => ObjectSerializer.deserialize(v, match[1]))); } else if (value instanceof Map && ((match = targetType.match(_regMap)[1]) !== null) && match.length === 2) { return new Map(Array.from(value, ([k, v]) => [k, ObjectSerializer.deserialize(v, match[1])])); } return value; } // deserialize } // end of serializer
the_stack
'use strict'; import { DomainInfo, FileInfo, parser, PddlLanguage, ProblemInfo } from 'pddl-workspace'; import {TextDocument, CancellationToken, DocumentFormattingEditProvider, FormattingOptions, TextEdit, DocumentRangeFormattingEditProvider, Range, Position, EndOfLine } from 'vscode'; import { nodeToRange } from '../utils'; import { CodePddlWorkspace } from '../workspace/CodePddlWorkspace'; import { PddlOnTypeFormatter } from './PddlOnTypeFormatter'; export class PddlFormatProvider implements DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider { constructor(private pddlWorkspace?: CodePddlWorkspace) { } async provideDocumentRangeFormattingEdits(document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): Promise<TextEdit[] | undefined> { const fileInfo = await this.pddlWorkspace?.upsertAndParseFile(document); if (token.isCancellationRequested) { return undefined; } if (fileInfo && (fileInfo.getLanguage() !== PddlLanguage.PDDL)) { return undefined; } const tree: parser.PddlSyntaxTree = this.getSyntaxTree(fileInfo, document); return new PddlFormatter(document, range, options, token).format(tree.getRootNode()); } async provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): Promise<TextEdit[] | undefined> { const fileInfo = await this.pddlWorkspace?.upsertAndParseFile(document); if (token.isCancellationRequested) { return undefined; } if (fileInfo && (fileInfo.getLanguage() !== PddlLanguage.PDDL)) { return undefined; } const tree: parser.PddlSyntaxTree = this.getSyntaxTree(fileInfo, document); const fullRange = document.validateRange(new Range(new Position(0, 0), new Position(document.lineCount, Number.MAX_VALUE))); return new PddlFormatter(document, fullRange, options, token).format(tree.getRootNode()); } private getSyntaxTree(fileInfo: FileInfo | undefined, document: TextDocument): parser.PddlSyntaxTree { let tree: parser.PddlSyntaxTree; if (fileInfo && (fileInfo instanceof DomainInfo)) { tree = (fileInfo as DomainInfo).syntaxTree; } else if (fileInfo && (fileInfo instanceof ProblemInfo)) { tree = (fileInfo as ProblemInfo).syntaxTree; } else { tree = new parser.PddlSyntaxTreeBuilder(document.getText()).getTree(); } return tree; } } class PddlFormatter { private readonly edits: TextEdit[] = []; private readonly firstOffset: number; private readonly lastOffset: number; constructor(private readonly document: TextDocument, range: Range, private readonly options: FormattingOptions, private token: CancellationToken) { this.firstOffset = document.offsetAt(range.start); this.lastOffset = document.offsetAt(range.end); } getLastChild(node: parser.PddlSyntaxNode): parser.PddlSyntaxNode | undefined { let children = node?.getChildren(); while (children && (children.length > 0)) { node = children[children.length - 1]; children = node?.getChildren(); } return node; } format(node: parser.PddlSyntaxNode): TextEdit[] { if (node.getStart() > this.lastOffset || this.token.isCancellationRequested) { return this.edits; } const nextSibling = node.getFollowingSibling() ?? node.getParent()?.getFollowingSibling(undefined, node); const precedingSibling = node.getPrecedingSibling(); const precedingNode = precedingSibling && this.getLastChild(precedingSibling); if (node.getStart() >= this.firstOffset || node.includesIndex(this.firstOffset)) { if (node.isType(parser.PddlTokenType.OpenBracketOperator)) { if (precedingNode?.isNotType(parser.PddlTokenType.Whitespace)) { this.breakAndIndent(node); } } else if (node.getToken().type === parser.PddlTokenType.CloseBracket) { if (precedingNode?.isNotType(parser.PddlTokenType.Whitespace)) { const openBracketToken = node.getParent()?.getToken().tokenText ?? ''; if (['(:requirements', '(:domain'].includes(openBracketToken)) { // do nothing } else if (openBracketToken.startsWith('(:') || ['(define'].includes(openBracketToken)) { this.breakAndIndent(node, -1); } } } else if (node.isType(parser.PddlTokenType.Whitespace)) { if (node.getParent() && ['(increase', '(decrease', '(assign'].includes(node.getParent()!.getToken().tokenText)) { if ((node.getParent()?.length ?? 0) > 50) { this.breakAndIndent(node); } else { this.replace(node, ' '); } } else if (nextSibling?.isType(parser.PddlTokenType.Comment)) { if (node.getText().includes('\n')) { this.breakAndIndent(node); } else { this.replace(node, ' '); } } else if (node.getParent() && ['(:types', '(:objects', '(:constants'].includes(node.getParent()!.getToken().tokenText)) { if (nextSibling?.isType(parser.PddlTokenType.Dash) || precedingSibling?.isType(parser.PddlTokenType.Dash)) { this.replace(node, ' '); } else if (precedingSibling?.isType(parser.PddlTokenType.Comment)) { this.breakAndIndent(node); } else if (nextSibling?.isType(parser.PddlTokenType.CloseBracket)) { this.breakAndIndent(node, -1); } else { const precedingNodes = node.getPrecedingSiblings() .filter(n => n.isNoneOf([parser.PddlTokenType.Comment, parser.PddlTokenType.Whitespace])); if (precedingNodes.length === 0) { this.breakAndIndent(node); } else if (precedingNodes.length > 2 && this.areTypes(precedingNodes.slice(-2), [parser.PddlTokenType.Dash, parser.PddlTokenType.Other])) { this.breakAndIndent(node); } else { this.replace(node, ' '); } } } else if (nextSibling === undefined) { this.replace(node, ''); } else if (nextSibling.isType(parser.PddlTokenType.CloseBracket)) { if (node.getText().includes('\n')) { this.breakAndIndent(node, -1); } else { this.replace(node, ''); } } else if (nextSibling.isAnyOf([parser.PddlTokenType.Dash, parser.PddlTokenType.Other, parser.PddlTokenType.Parameter])) { this.replace(node, ' '); } else if (nextSibling.isAnyOf([parser.PddlTokenType.OpenBracket, parser.PddlTokenType.OpenBracketOperator, parser.PddlTokenType.Keyword])) { if (nextSibling.isType(parser.PddlTokenType.Keyword)) { const requirementsAncestor = node.findAncestor(parser.PddlTokenType.OpenBracketOperator, /:requirements/); if (requirementsAncestor) { this.replace(node, ' '); } else { this.breakAndIndent(node); } } else if (node.getParent()?.isNumericExpression() || node.getParent()?.isLogicalExpression() || node.getParent()?.isTemporalExpression()) { if (node.getText().includes('\n')) { this.breakAndIndent(node); } else { this.replace(node, ' '); } } else if (['(domain', '(problem'].includes(nextSibling.getToken().tokenText)) { this.replace(node, ' '); } else { if (node.getParent() && [':parameters', ':duration', ':precondition', ':condition', ':effect'].includes(node.getParent()!.getToken().tokenText)) { this.replace(node, ' '); } else { this.breakAndIndent(node); } } } } } node.getChildren().forEach(child => this.format(child)); return this.edits; } areTypes(nodes: parser.PddlSyntaxNode[], expectedTypes: parser.PddlTokenType[]): boolean { if (nodes.length !== expectedTypes.length) { throw new Error(`argument lengths are not matching`); } const actualTypes = nodes.map(n => n.getToken().type); for (let i = 0; i < actualTypes.length; i++) { if (actualTypes[i] !== expectedTypes[i]) { return false; } } return true; } breakAndIndent(node: parser.PddlSyntaxNode, offset = 0): void { const level = node.getAncestors([parser.PddlTokenType.OpenBracket, parser.PddlTokenType.OpenBracketOperator]).length; if (node.isType(parser.PddlTokenType.Whitespace)) { this.replace(node, this.ends(node.getText(), { min: 1, max: 2 }) + PddlOnTypeFormatter.createIndent('', level + offset, this.options)); } else { const newText = this.eol() + PddlOnTypeFormatter.createIndent('', level + offset, this.options); this.edits.push(TextEdit.insert(this.document.positionAt(node.getStart()), newText)); } } replace(node: parser.PddlSyntaxNode, newText: string): void { this.edits.push(TextEdit.replace(nodeToRange(this.document, node), newText)); } /** @returns the endline characters only, but at least the `min` count */ ends(text: string, options: { min: number; max?: number }): string { // strip off all other characters than the bare `\n` let endls = text.replace(/[^\n]/g, ''); let endlCount = (endls.match(/\n/g) || []).length; // remove excess line breaks while (endlCount > (options.max ?? Number.MAX_VALUE)) { endls = endls.replace('\n', ''); endlCount--; } // replace all `\n` by the actual document's eol sequence endls = endls.split('\n').join(this.eol()); if (endlCount < options.min) { return endls + this.eol().repeat(options.min - endlCount); } else { return endls; } } eol(): string { switch (this.document.eol) { case EndOfLine.LF: return '\n'; case EndOfLine.CRLF: return '\r\n'; } } }
the_stack
import { encodeXml, IFormat } from '../utils'; import { IHeadersMap, HeaderNames } from './Parser'; /** * ESLevent * * @see https://freeswitch.org/confluence/display/FREESWITCH/Event+Socket+Library#EventSocketLibrary-ESLeventObject */ export class Event { private _headers: IHeadersMap = {}; private _type: string; private _subclass: string; private _body: string; private _headerIndex = -1; constructor(headers: IHeadersMap, body?: string); constructor(type: string, subclass?: string); constructor(typeOrHeaders: IHeadersMap | string, subclassOrBody?: string) { if (typeof typeOrHeaders === 'string') { this._type = typeOrHeaders; this._subclass = subclassOrBody || ''; this._body = ''; this.addHeader(HeaderNames.EventName, this._type); if (this._subclass) this.addHeader(HeaderNames.EventSubclass, this._subclass); } else { this._type = typeOrHeaders[HeaderNames.EventName] || ''; this._subclass = typeOrHeaders[HeaderNames.EventSubclass] || ''; this._body = subclassOrBody || typeOrHeaders._body || ''; this._headers = typeOrHeaders; delete this._headers._body; } this.delHeader('Content-Length'); } get type() { return this._type; } get body() { return this._body; } get headers(): Readonly<IHeadersMap> { return this._headers; } /** * Turns an event into colon-separated 'name: value' * pairs similar to a sip/email packet * (the way it looks on '/events plain all'). */ serialize(format: IFormat = 'json'): string { switch (format) { /* { "Event-Name": "CUSTOM", "Core-UUID": "8b192020-7368-4498-9b11-cbe10f48a784", "FreeSWITCH-Hostname": "smsdev", "FreeSWITCH-Switchname": "smsdev", "FreeSWITCH-IPv4": "10.1.12.115", "FreeSWITCH-IPv6": "::1", "Event-Date-Local": "2012-09-25 14:22:37", "Event-Date-GMT": "Tue, 25 Sep 2012 18:22:37 GMT", "Event-Date-Timestamp": "1348597357036551", "Event-Calling-File": "switch_cpp.cpp", "Event-Calling-Function": "Event", "Event-Calling-Line-Number": "262", "Event-Sequence": "11027", "Event-Subclass": "SMS::SEND_MESSAGE", "proto": "sip", "dest_proto": "sip", "from": "9515529832", "from_full": "9515529832", "to": "internal/8507585138@sms-proxy-01.bandwidthclec.com", "subject": "PATLive Testing", "type": "text/plain", "hint": "the hint", "replying": "true", "Content-Length": "23", "_body": "Hello from Chad Engler!" } */ case 'json': { const obj = Object.assign({}, this._headers); if (this._body) { obj[HeaderNames.ContentLength] = Buffer.byteLength(this._body, 'utf8').toString(); obj._body = this._body; } else { delete obj[HeaderNames.ContentLength]; } return JSON.stringify(obj, null, 4); } /* Event-Name: CUSTOM Core-UUID: 8b192020-7368-4498-9b11-cbe10f48a784 FreeSWITCH-Hostname: smsdev FreeSWITCH-Switchname: smsdev FreeSWITCH-IPv4: 10.1.12.115 FreeSWITCH-IPv6: %3A%3A1 Event-Date-Local: 2012-09-25%2014%3A21%3A56 Event-Date-GMT: Tue,%2025%20Sep%202012%2018%3A21%3A56%20GMT Event-Date-Timestamp: 1348597316736546 Event-Calling-File: switch_cpp.cpp Event-Calling-Function: Event Event-Calling-Line-Number: 262 Event-Sequence: 11021 Event-Subclass: SMS%3A%3ASEND_MESSAGE proto: sip dest_proto: sip from: 9515529832 from_full: 9515529832 to: internal/8507585138%40sms-proxy-01.bandwidthclec.com subject: PATLive%20Testing type: text/plain hint: the%20hint replying: true Content-Length: 23 */ case 'plain': { let output = ''; const keys = Object.keys(this._headers); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (key === 'Content-Length') continue; const value = this._headers[key]; output += `${key}: ${value}\n`; } if (this._body) { const bodyLen = Buffer.byteLength(this._body, 'utf8'); output += `${HeaderNames.ContentLength}: ${bodyLen}\n\n`; output += this._body; } return output; } /* <event> <headers> <Event-Name>CUSTOM</Event-Name> <Core-UUID>8b192020-7368-4498-9b11-cbe10f48a784</Core-UUID> <FreeSWITCH-Hostname>smsdev</FreeSWITCH-Hostname> <FreeSWITCH-Switchname>smsdev</FreeSWITCH-Switchname> <FreeSWITCH-IPv4>10.1.12.115</FreeSWITCH-IPv4> <FreeSWITCH-IPv6>%3A%3A1</FreeSWITCH-IPv6> <Event-Date-Local>2012-09-25%2014%3A26%3A17</Event-Date-Local> <Event-Date-GMT>Tue,%2025%20Sep%202012%2018%3A26%3A17%20GMT</Event-Date-GMT> <Event-Date-Timestamp>1348597577616542</Event-Date-Timestamp> <Event-Calling-File>switch_cpp.cpp</Event-Calling-File> <Event-Calling-Function>Event</Event-Calling-Function> <Event-Calling-Line-Number>262</Event-Calling-Line-Number> <Event-Sequence>11057</Event-Sequence> <Event-Subclass>SMS%3A%3ASEND_MESSAGE</Event-Subclass> <proto>sip</proto> <dest_proto>sip</dest_proto> <from>9515529832</from> <from_full>9515529832</from_full> <to>internal/8507585138%40sms-proxy-01.bandwidthclec.com</to> <subject>PATLive%20Testing</subject> <type>text/plain</type> <hint>the%20hint</hint> <replying>true</replying> </headers> <Content-Length>23</Content-Length> <body>Hello from Chad Engler!</body> </event> */ case 'xml': { let output = ''; const keys = Object.keys(this._headers); output += '<event>\n'; output += ' <headers>\n'; for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (key === 'Content-Length') continue; const value = this._headers[key]; const encodedValue = typeof value === 'string' ? encodeXml(value) : value; output += ` <${key}>${encodedValue}</${key}>\n`; } if (this._body) { const xmlEncodedBody = encodeXml(this._body); const key = HeaderNames.ContentLength; const value = Buffer.byteLength(xmlEncodedBody, 'utf8'); output += ` <${key}>${value}</${key}>\n`; output += ' </headers>\n'; output += ` <body>${xmlEncodedBody}</body>\n`; } else { output += ' </headers>\n'; } output += '</event>'; return output; } } return ''; } /** * Sets the priority of an event to `priority` in case it's fired. */ setPriority(priority: number): void { this.addHeader('priority', priority.toString()); } /** * Gets the header with the key of `name` from the event object. */ getHeader(name: string): string | null { return this._headers[name] || null; } /** * Gets the body of the event object. */ getBody(): string { return this._body; } /** * Gets the event type of the event object. */ getType(): string { return this._type; } /** * Add `value` to the body of the event object. * This can be called multiple times for the same event object. * * @returns the new body after appending `value`. */ addBody(value: string): string { return this._body += value; } /** * Add a header with `name` and `value` to the event object. * This can be called multiple times * for the same event object. */ addHeader(name: string, value: string): void { this._headers[name] = value; } /** * Delete the header with key `name` from the event object. */ delHeader(name: string): void { delete this._headers[name]; } /** * Sets the pointer to the first header in the event object, * and returns it's key name. This must be called before nextHeader is called. * * If there are no headers, then it will return `null`. */ firstHeader(): string | null { this._headerIndex = 0; const keys = Object.keys(this._headers); if (keys.length === 0) return null; return keys[0]; } /** * Moves the pointer to the next header in the event object, * and returns it's key name. `firstHeader` must be called * before this method to set the pointer. If you're already * on the last header when this method is called, then it will return `null`. */ nextHeader(): string | null { // if no firstHeader called yet if (this._headerIndex === -1) return null; const keys = Object.keys(this._headers); // if reached end if (this._headerIndex === (keys.length - 1)) { this._headerIndex = -1; return null; } ++this._headerIndex; return keys[this._headerIndex]; } }
the_stack
/// <reference path="../metricsPlugin.ts"/> /// <reference path="../services/alertsManager.ts"/> /// <reference path="../services/errorsManager.ts"/> module HawkularMetrics { export class AppServerPlatformDetailsController implements IRefreshable { public static USED_COLOR = '#1884c7'; /// blue public static MAXIMUM_COLOR = '#f57f20'; /// orange public static MINIMUM_AVAIL_MEM = 100 * 1024 * 1024; public math = Math; private autoRefreshPromise: ng.IPromise<number>; public alertList: any[] = []; public fileStoreList; public processorList; public processorListNames; public chartCpuData: IChartDataPoint[] = []; public chartCpuDataMulti: IChartDataPoint[][] = []; public chartFileSystemData = {}; public startTimeStamp: TimestampInMillis; public endTimeStamp: TimestampInMillis; public chartMemoryUsageData: IChartDataPoint[]; // will contain in the format: 'metric name' : true | false public skipChartData = {}; public feedId: FeedId; private memoryResourceId: ResourceId; public resolvedChartFileSystemData = {}; public resolvedMemoryData: boolean = false; public resolvedCPUData: boolean = false; constructor(private $scope: any, private $rootScope: IHawkularRootScope, private $interval: ng.IIntervalService, private $log: ng.ILogService, private $routeParams: any, private HawkularNav: any, private HawkularInventory: any, private HawkularMetric: any, private HawkularAlertRouterManager: IHawkularAlertRouterManager, private $q: ng.IQService) { $scope.os = this; this.feedId = this.$routeParams.feedId; this.memoryResourceId = AppServerPlatformDetailsController.getMemoryResourceId(this.feedId); this.initTimeStamps(); this.HawkularAlertRouterManager.registerForAlerts( this.feedId, 'platform', _.bind(this.filterAlerts, this) ); if ($rootScope.currentPersona) { this.$log.log('We have have a persona'); this.setup(); } else { // currentPersona hasn't been injected to the rootScope yet, wait for it.. $rootScope.$watch('currentPersona', (currentPersona) => currentPersona && this.setup()); } // handle drag ranges on charts to change the time range this.$scope.$on('ChartTimeRangeChanged', (event, data: Date[]) => { this.startTimeStamp = data[0].getTime(); this.endTimeStamp = data[1].getTime(); this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp); this.refresh(); }); this.getAlerts(); this.autoRefresh(20); } private initTimeStamps() { this.endTimeStamp = this.$routeParams.endTime || +moment(); this.startTimeStamp = this.endTimeStamp - (this.$routeParams.timeOffset || 3600000); } private filterAlerts(alertData: IHawkularAlertQueryResult): IAlert[] { let alertList = alertData.alertList; _.remove(alertList, (item: IAlert) => { switch (item.context.alertType) { case 'CPU_USAGE_EXCEED': item.alertType = item.context.alertType; return false; case 'AVAILABLE_MEMORY': item.alertType = item.context.alertType; return false; default: return true; } }); this.alertList = alertList; return alertList; } private setup() { this.getProcessors(); this.getFileSystems(); this.getPlatformData(); this.$rootScope.lastUpdateTimestamp = new Date(); } public refresh(): void { this.initTimeStamps(); this.getAlerts(); this.getPlatformData(); this.getCPUChartData(); this.getMemoryChartData(); this.getFSChartData(); this.getCpuChartDetailData(); this.$rootScope.lastUpdateTimestamp = new Date(); } private getAlerts(): void { this.HawkularAlertRouterManager.getAlertsForResourceId( this.feedId, this.startTimeStamp, this.endTimeStamp ); } public getFileSystems(): any { this.HawkularInventory.ResourceOfTypeUnderFeed.query({ environmentId: globalEnvironmentId, feedId: this.feedId, resourceTypeId: 'File Store' }).$promise.then((aResourceList) => { this.fileStoreList = aResourceList; this.fileStoreList.$resolved = true; this.getFSChartData(); return aResourceList; }, () => { // error if (!this.fileStoreList) { this.fileStoreList = []; this.fileStoreList.$resolved = true; } }); } // retrieve the list of CPUs public getProcessors(): any { this.HawkularInventory.ResourceOfTypeUnderFeed.query({ environmentId: globalEnvironmentId, feedId: this.feedId, resourceTypeId: 'Processor' }).$promise.then((aResourceList) => { this.processorList = []; // aResourceList; this.processorListNames = []; // Generate metric key from resource id _.forEach(aResourceList, (item) => { const metricId: string = MetricsService.getMetricId('M', this.feedId, item['id'], 'CPU Usage'); this.processorList.push(metricId); this.processorListNames[metricId] = item['name']; }); this.processorList = _.sortBy(this.processorList); this.getCpuUsage(); this.getCPUChartData(); this.getCpuChartDetailData(); return aResourceList; }, () => { // error if (!this.processorList) { this.processorList = []; } }); } public getPlatformData(): void { this.HawkularMetric.GaugeMetricData(this.$rootScope.currentPersona.id).queryMetrics({ gaugeId: MetricsService.getMetricId('M', this.feedId, this.memoryResourceId, 'Available Memory'), start: this.startTimeStamp, end: this.endTimeStamp, buckets: 1 }).$promise.then((resource) => { if (resource.length) { this['memoryAvail'] = resource[0]; this.getMemoryChartData(); return resource[0]; } }); } private getCpuUsage() { if (this.processorList) { this.HawkularMetric.GaugeMetricMultipleStats(this.$rootScope.currentPersona.id).get({ metrics: this.processorList, start: this.startTimeStamp, end: this.endTimeStamp, buckets: 1 }).$promise.then((resource) => { if (resource.length) { this['cpuUsage'] = resource[0]; return resource[0]; } }); } } public getFSChartData(): void { let availPromises = []; angular.forEach(this.fileStoreList, function(res) { //Free Space if (!this.skipChartData[res.id + '_Free']) { availPromises.push( this.HawkularMetric.GaugeMetricData(this.$rootScope.currentPersona.id).queryMetrics({ gaugeId: MetricsService.getMetricId('M', this.feedId, res.id, 'Usable Space'), start: this.startTimeStamp, end: this.endTimeStamp, buckets: 60 }).$promise.then((data) => { return { fileStoreId: res.id, key: 'Usable Space', color: AppServerPlatformDetailsController.USED_COLOR, values: MetricsService.formatBucketedChartOutput(data, 1 / (1024 * 1024)) }; }) ); } //Total space if (!this.skipChartData[res.id + '_Total']) { availPromises.push( this.HawkularMetric.GaugeMetricData(this.$rootScope.currentPersona.id).queryMetrics({ gaugeId: MetricsService.getMetricId('M', this.feedId, res.id, 'Total Space'), start: this.startTimeStamp, end: this.endTimeStamp, buckets: 60 }).$promise.then((data) => { return { fileStoreId: res.id, key: 'Total Space', color: AppServerPlatformDetailsController.MAXIMUM_COLOR, values: MetricsService.formatBucketedChartOutput(data, 1 / (1024 * 1024)) }; }) ); } }, this); this.$q.all(availPromises).then((data) => { let tmpChartFileSystemData = {}; _.forEach(data, (item: any) => { if (!tmpChartFileSystemData[item.fileStoreId]) { tmpChartFileSystemData[item.fileStoreId] = []; } tmpChartFileSystemData[item.fileStoreId].push(item); this.resolvedChartFileSystemData[item.fileStoreId] = true; }); this.chartFileSystemData = tmpChartFileSystemData; }); } public getCPUChartData(): void { if (this.processorList) { this.HawkularMetric.GaugeMetricMultipleStats(this.$rootScope.currentPersona.id).get({ metrics: this.processorList, start: this.startTimeStamp, end: this.endTimeStamp, buckets: 60, stacked: true }).$promise.then((resource) => { if (resource.length) { this.chartCpuData = MetricsService.formatBucketedChartOutput(resource, 100); this.resolvedCPUData = true; } return resource; }); } } public getCpuChartDetailData(): void { if (this.processorList) { _.forEach(this.processorList, (res: string) => { this.HawkularMetric.GaugeMetricData(this.$rootScope.currentPersona.id).queryMetrics({ gaugeId: res, start: this.startTimeStamp, end: this.endTimeStamp, buckets: 60 }).$promise.then((data) => { this.chartCpuDataMulti[res] = MetricsService.formatBucketedChartOutput(data, 100); return data; }); }); } } public getMemoryChartData(): void { this.HawkularMetric.GaugeMetricData(this.$rootScope.currentPersona.id).queryMetrics({ gaugeId: MetricsService.getMetricId('M', this.feedId, this.memoryResourceId, 'Available Memory'), start: this.startTimeStamp, end: this.endTimeStamp, buckets: 60 }).$promise.then((resource) => { if (resource.length) { this.chartMemoryUsageData = MetricsService.formatBucketedChartOutput(resource, 1 / (1024 * 1024)); this.resolvedMemoryData = true; } return resource; }); } public toggleChartData(name): void { this.skipChartData[name] = !this.skipChartData[name]; this.getFSChartData(); } public static getMemoryResourceId(feedId): string { return 'platform~/OPERATING_SYSTEM=' + feedId + '_OperatingSystem/MEMORY=Memory'; } private autoRefresh(intervalInSeconds: number): void { this.autoRefreshPromise = this.$interval(() => { this.refresh(); }, intervalInSeconds * 1000); this.$scope.$on('$destroy', () => { this.$interval.cancel(this.autoRefreshPromise); }); } } _module.controller('AppServerPlatformDetailsController', AppServerPlatformDetailsController); }
the_stack
import { Nes } from "./nes"; import { BitHelper } from "./bithelper"; import { VideoScreen } from "./video"; import { Mirroring } from "./cartridge"; export class PPU { nes: Nes; palette: Color[] = []; vram: Uint8Array; scanline = -1; //y coordinate of scanline tick = 0; //x coordinate of scanline frame_complete = false; //control register 0x2000 nametable_x = 0; //which nametable gets drawn first nametable_y = 0; //which nametable gets drawn first increment_mode = 0; //ppu to increment address by 1 or 32 pattern_sprite = 0; //tells you whether to read sprite tiles from chr page 1 or 2 pattern_background = 0; //tells you whether to read background tiles from chr page 1 or 2 sprite_size = 0; slave_mode = 0; // unused enable_nmi = 0; //mask register 0x2001 greyscale = 0; show_background_leftmost = 0; show_sprites_leftmost = 0; show_background = 0; show_sprites = 0; emphasize_red = 0; emphasize_green = 0; emphasize_blue = 0; //status register 0x2002 sprite_overflow = 0; sprite_zero_hit = 0; vertical_blank = 0; //period when tv laser is off screen //oam register 0x2003 and 0x2004 oam:Uint8Array; oamAddress = 0; //scroll register 0x2005 scroll_x = 0; //ScrollX offset scroll_y = 0; //scrollY offset scroll_last = 0; //for address latch alternation //specific timing of scroll_x and nametable_x //for spritehit0 in mario bros and other games marioHack = false; //the scanline at which to do rendering renderScanline = 120; //used during rendering sprite_color = new Color(0,0,0); //used for IRQ in MMC3 Mapper isMMC3 = false; //for cpu reading/writing to the vram ppu_data:number = 0; ppu_data_delay:number = 0; //reading from the ppu by the cpu is delayed by one cycle ppu_address:number = 0; constructor(nes: Nes) { this.nes = nes; this.initPalette(); //16 kb addressable range (0x4000 = 16*1024) //though most of this array is unnecessary //as the first 8kb is on the cartridge rom this.vram = new Uint8Array(0x4000); //is this correct as an initial state? //will need to check for (let i = 0; i < this.vram.length; i++) this.vram[i] = 0x00; this.oam = new Uint8Array(256); for (let i = 0; i < this.oam.length; i++) this.oam[i] = 0x00; } clock() { //for performance, can skip most of this function if tick!=3 if (this.tick!=3) { this.incrementTickAndScanline(); return; } if (this.scanline==-1) { //reset vblank this.vertical_blank = 0; } //sprite hit 0 hack if (this.scanline==this.oam[0]) { // if (this.tick==sprite_0_x) this.sprite_zero_hit = 1; } //scanline counter for MMC3 Mapper once a frame //without this double dragon 2 doesn't play music //during the first stage, also double dragon 3 //won't get past the title screen //also bucky ohare just crashes at title if (this.isMMC3){ if (this.scanline<241){ this.nes.memory.clockScanlineCounter(); } } //when to start rendering //current default is 120 //unless overridden via hack if (this.scanline==this.renderScanline) { this.nes.render(); } if (this.scanline==241) { //vblank this.vertical_blank = 1; //nmi if (this.enable_nmi) this.nes.cpu.nmiRequest(); } this.incrementTickAndScanline(); } incrementTickAndScanline(){ this.tick+=3; if (this.tick == 342) { this.tick = 0; this.scanline++; //this is a hack to get it cycle accurate to what //i had before i switched it to running the //ppu clock function 1 time instead of 3 in main loop if (this.scanline==259) { this.tick = -81; } if (this.scanline > 259) { this.scanline = -1; this.frame_complete = true; } } } // PPU MEMORY MAP // Address range Size Description // $0000-$0FFF $1000 Pattern table 0 // $1000-$1FFF $1000 Pattern table 1 // $2000-$23FF $0400 Nametable 0 // $2400-$27FF $0400 Nametable 1 // $2800-$2BFF $0400 Nametable 2 // $2C00-$2FFF $0400 Nametable 3 // $3000-$3EFF $0F00 Mirrors of $2000-$2EFF // $3F00-$3F1F $0020 Palette RAM indexes // $3F20-$3FFF $00E0 Mirrors of $3F00-$3F1F //i am currently storing the ppu registers in //regular cpu ram out of convenience though //that's not really where they should live //I should move this to a different structure readRegister(address: number) { switch (address) { case 0x2000: // Control this.assembleControlRegister(); break; case 0x2001: // Mask this.assembleMaskRegister(); break; case 0x2002: // Status this.assembleStatusRegister(); this.vertical_blank = 0; //reading from the status register clears vertical blank this.ppu_address_lo_high = 0; //same for lo/hi counter this.sprite_zero_hit = 0; break; case 0x2003: // OAM Address break; case 0x2004: // OAM Data break; case 0x2005: // Scroll break; case 0x2006: // PPU Address break; case 0x2007: // PPU Data //reading from ppu is delayed by 1 cycle this.ppu_data = this.ppu_data_delay; this.ppu_data_delay = this.readVRAM(this.ppu_address); //special case for palette's - they don't need to be delayed if (address > 0x3f00) { this.ppu_data = this.readVRAM(this.ppu_address); } //it auto increments the address on every read/write if (this.increment_mode==0) this.ppu_address++; else this.ppu_address+=32; return this.ppu_data; break; } return this.nes.memory.ram[address]; } //writing to the ppu address takes 2 writes //first you write the hi byte then the lo byte //so each write alternates this variable between 0/1 ppu_address_lo_high = 0; writeRegister(address: number, value: number) { switch (address) { case 0x2000: // Control this.parseControlRegister(value); break; case 0x2001: // Mask this.parseMaskRegister(value); break; case 0x2002: // Status this.parseStatusRegister(value); break; case 0x2003: // OAM Address this.oamAddress = value; break; case 0x2004: // OAM Data this.writeOAM(value); break; case 0x2005: // Scroll if (this.scroll_last==0) { if (this.marioHack){ //mario hack if (this.scanline<200) this.scroll_x = value; } else this.scroll_x = value; this.scroll_last = 1; } //then the lo byte else { this.scroll_y = value; this.scroll_last = 0; } break; case 0x2006: // PPU Address //first the hi byte if (this.ppu_address_lo_high==0) { this.ppu_address = (this.ppu_address & 0x00FF) | (value<<8); this.ppu_address_lo_high = 1; } //then the lo byte else { this.ppu_address_lo_high = 0; this.ppu_address = (this.ppu_address & 0xFF00) | value; } break; case 0x2007: // PPU Data this.writeVRAM(this.ppu_address,value); //it auto increments the address on every read/write if (this.increment_mode==0) this.ppu_address++; else this.ppu_address+=32; break; } this.nes.memory.ram[address] = value; } readVRAM(address: number) { //cartridge if (address >= 0x0000 && address <= 0x1FFF) { return this.nes.cartridge.chrData[address]; } //nametable else if (address >= 0x2000 && address <= 0x3EFF) { //TODO mirroring of $2000-$27FF to $2800-$2BFF (NameTable 0,1 mirrored to 2,3) //TODO mirroring $2000-$2EFF to $3000-$3EFF if (this.nes.cartridge.mirroring==Mirroring.VERTICAL) { if (address >= 0x2800) address -= 0x800; } else if (this.nes.cartridge.mirroring==Mirroring.HORIZONTAL) { if (address>=0x2400 && address<0x2800) { address -= 0x400; } if (address>=0x2C00) { address -= 0x400; } } return this.vram[address]; } //palette else if (address >= 0x3F00 && address <= 0x3FFF) { //mirroring $3F00-$3F1F to $3F20-$3FFF let mirrored_address = (address &= 0x001F) + 0x3F00; if (mirrored_address==0x3F10) mirrored_address = 0x3F00; if (mirrored_address==0x3F14) mirrored_address = 0x3F04; if (mirrored_address==0x3F18) mirrored_address = 0x3F08; if (mirrored_address==0x3F1C) mirrored_address = 0x3F0C; return this.vram[mirrored_address]; } } writeVRAM(address: number, value: number) { //cartridge if (address >= 0x0000 && address <= 0x1FFF) { //can we write to the cartridge? //apparently we can - used to populate chr in zelda //since cartridge reports 0 chr banks this.nes.cartridge.chrData[address] = value; } //nametable else if (address >= 0x2000 && address <= 0x3EFF) { if (this.nes.cartridge.mirroring==Mirroring.VERTICAL) { if (address >= 0x2800) address -= 0x800; } else if (this.nes.cartridge.mirroring==Mirroring.HORIZONTAL) { if (address>=0x2400 && address<0x2800) { address -= 0x400; } if (address>=0x2C00) { address -= 0x400; } } this.vram[address] = value; } //palette else if (address >= 0x3F00 && address <= 0x3FFF) { let mirrored_address = (address &= 0x001F) + 0x3F00; if (mirrored_address==0x3F10) mirrored_address = 0x3F00; if (mirrored_address==0x3F14) mirrored_address = 0x3F04; if (mirrored_address==0x3F18) mirrored_address = 0x3F08; if (mirrored_address==0x3F1C) mirrored_address = 0x3F0C; this.vram[mirrored_address] = value; } } getPaletteColor(index:number):Color{ //background color is mirrored if (index%4==0) index=0; let pallete_number = this.readVRAM(0x3F00+index); pallete_number = pallete_number % 64; return this.palette[pallete_number]; } //REGISTER WRAPPERS parseControlRegister(value:number){ if (this.marioHack){ //mario hack if (this.scanline<200) this.nametable_x = BitHelper.getBit(value,0); } else this.nametable_x = BitHelper.getBit(value,0); this.nametable_y = BitHelper.getBit(value,1); this.increment_mode = BitHelper.getBit(value,2); this.pattern_sprite = BitHelper.getBit(value,3); this.pattern_background = BitHelper.getBit(value,4); this.sprite_size = BitHelper.getBit(value,5); this.slave_mode = BitHelper.getBit(value,6); this.enable_nmi = BitHelper.getBit(value,7); // console.log('Scanline) ' + this.scanline + ' Sprites) ' + this.pattern_sprite); } parseMaskRegister(value:number){ this.greyscale = BitHelper.getBit(value,0); this.show_background_leftmost = BitHelper.getBit(value,1); this.show_sprites_leftmost = BitHelper.getBit(value,2); this.show_background = BitHelper.getBit(value,3); this.show_sprites = BitHelper.getBit(value,4); this.emphasize_red = BitHelper.getBit(value,5); this.emphasize_green = BitHelper.getBit(value,6); this.emphasize_blue = BitHelper.getBit(value,7); } parseStatusRegister(value:number){ this.sprite_overflow = BitHelper.getBit(value,5); this.sprite_zero_hit = BitHelper.getBit(value,6); this.vertical_blank = BitHelper.getBit(value,7); } assembleControlRegister(){ this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],0,this.nametable_x); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],1,this.nametable_y); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],2,this.increment_mode); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],3,this.pattern_sprite); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],4,this.pattern_background); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],5,this.sprite_size); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],6,this.slave_mode); this.nes.memory.ram[0x2000] = BitHelper.setBit(this.nes.memory.ram[0x2000],7,this.enable_nmi); } assembleMaskRegister(){ this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],0,this.greyscale); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],1,this.show_background_leftmost); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],2,this.show_sprites_leftmost); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],3,this.show_background); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],4,this.show_sprites); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],5,this.emphasize_red); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],6,this.emphasize_green); this.nes.memory.ram[0x2001] = BitHelper.setBit(this.nes.memory.ram[0x2001],7,this.emphasize_blue); } assembleStatusRegister(){ this.nes.memory.ram[0x2002] = BitHelper.setBit(this.nes.memory.ram[0x2002],5,this.sprite_overflow); this.nes.memory.ram[0x2002] = BitHelper.setBit(this.nes.memory.ram[0x2002],6,this.sprite_zero_hit); this.nes.memory.ram[0x2002] = BitHelper.setBit(this.nes.memory.ram[0x2002],7,this.vertical_blank); } //used for visualizing current chr data //with available palettes testUsePallete = false; testCurrentPalette = -1; testCurrentColor0:Color; testCurrentColor1:Color; testCurrentColor2:Color; testCurrentColor3:Color; paletteSwapTest(){ this.testUsePallete = true; this.testCurrentPalette++; if (this.testCurrentPalette>7) this.testCurrentPalette = 0; this.testCurrentColor0 = this.nes.ppu.getPaletteColor( (this.testCurrentPalette*4) + 0); this.testCurrentColor1 = this.nes.ppu.getPaletteColor( (this.testCurrentPalette*4) + 1); this.testCurrentColor2 = this.nes.ppu.getPaletteColor( (this.testCurrentPalette*4) + 2); this.testCurrentColor3 = this.nes.ppu.getPaletteColor( (this.testCurrentPalette*4) + 3); } renderTile(address:number,x_screen:number,y_screen:number, screen:VideoScreen,scrolladjust_x:number,scrolladjust_y:number, nameTableIndex?:number,nameTableGrid?:number,spriteAttributes?:number) { let realPalColor0:Color = null; let realPalColor1:Color = null; let realPalColor2:Color = null; let realPalColor3:Color = null; let transparent = false; let flip_horizontal = false; let flip_vertical = false; if (nameTableIndex!=null) { //determine megatile //divide by 32 and do math_floor to determine the Y coordinate //mod by 32 to determine the X coordinate // scrolling test // let temp_x_screen = x_screen; // let temp_y_screen = y_screen; // if (nameTableGrid==1) //currently assuming horizontal mirroring // { // temp_y_screen-=240; // } // let x_tile = (temp_x_screen/8); // let y_tile = (temp_y_screen/8); let x_tile = (x_screen/8); let y_tile = (y_screen/8); let x_large = Math.floor(x_tile/4); //1 let y_large = Math.floor(y_tile/4); //0 let attribute_offset = (y_large*8)+x_large; //second nametable if (nameTableGrid==1) { if (this.nes.cartridge.mirroring==Mirroring.VERTICAL) attribute_offset +=0x400; else attribute_offset +=0x800; } let attribute_byte = this.nes.ppu.readVRAM(0x2000+960+attribute_offset); let quadrant_position = 0; if (x_tile%4>1) quadrant_position+=1; if (y_tile%4>1) quadrant_position+=2; attribute_byte = attribute_byte >> (quadrant_position*2) let bit0 = BitHelper.getBit(attribute_byte,0); let bit1 = BitHelper.getBit(attribute_byte,1); let pal_index = bit0 + (bit1*2); let pallete_number = (pal_index*4); realPalColor0 = this.nes.ppu.getPaletteColor(pallete_number + 0); realPalColor1 = this.nes.ppu.getPaletteColor(pallete_number + 1); realPalColor2 = this.nes.ppu.getPaletteColor(pallete_number + 2); realPalColor3 = this.nes.ppu.getPaletteColor(pallete_number + 3); } else if (spriteAttributes!=null){ let bit0 = BitHelper.getBit(spriteAttributes,0); let bit1 = BitHelper.getBit(spriteAttributes,1); let pal_index = bit0 + (bit1*2) + 4; let pallete_number = (pal_index*4); realPalColor0 = this.nes.ppu.getPaletteColor(pallete_number + 0); realPalColor1 = this.nes.ppu.getPaletteColor(pallete_number + 1); realPalColor2 = this.nes.ppu.getPaletteColor(pallete_number + 2); realPalColor3 = this.nes.ppu.getPaletteColor(pallete_number + 3); let flip_h = BitHelper.getBit(spriteAttributes,6); if (flip_h) flip_horizontal = true; let flip_v = BitHelper.getBit(spriteAttributes,7); if (flip_v) flip_vertical = true; } let val1 = 0; let val2 = 0; let color = 0; let palColor:Color; let byte1 = 0; let byte2 = 0; x_screen += scrolladjust_x; y_screen += scrolladjust_y; //code below will be called 61,000 times a frame //so keep it super efficient for (let y = 0; y < 8; y++) { byte1 = this.nes.cartridge.chrData[y+address]; byte2 = this.nes.cartridge.chrData[y+address+8]; for (let x = 0; x < 8; x++) { val1 = byte1 & 128; val2 = byte2 & 128; color = (val1 >> 7) + (val2 >> 6); // if (val1) color = 1; // if (val2) color += 2; //make nametable2 grayscale for debugging purposes // if (nameTableGrid==1) // realPalColor0 = null; if (realPalColor0!=null) { if (color==0) palColor = realPalColor0; else if (color==1) palColor = realPalColor1; else if (color==2) palColor = realPalColor2; else palColor = realPalColor3; this.sprite_color.red = palColor.red; this.sprite_color.green = palColor.green; this.sprite_color.blue = palColor.blue; if (spriteAttributes!=null && color==0) transparent = true; else transparent = false; } //used for visualizing the chr data //using available palettes else if (this.testUsePallete) { let palColor:Color; if (color==0) palColor = this.testCurrentColor0; if (color==1) palColor = this.testCurrentColor1; if (color==2) palColor = this.testCurrentColor2; if (color==3) palColor = this.testCurrentColor3; this.sprite_color.red = palColor.red; this.sprite_color.green = palColor.green; this.sprite_color.blue = palColor.blue; } else { color *= 70; this.sprite_color.red = color; this.sprite_color.green = color; this.sprite_color.blue = color } byte1 = byte1 << 1; byte2 = byte2 << 1; //scrolling calculation - MOVED OUT FOR PERFORMANCE if (flip_horizontal==false && flip_vertical==false) screen.setPixel(x_screen+x,y_screen+y,this.sprite_color,transparent); else if (flip_horizontal==true && flip_vertical == false) screen.setPixel(x_screen+(7-x),y_screen+y,this.sprite_color,transparent); else if (flip_horizontal==false && flip_vertical == true) screen.setPixel(x_screen+x,y_screen+(7-y),this.sprite_color,transparent); else screen.setPixel(x_screen+(7-x),y_screen+(7-y),this.sprite_color,transparent); } } } OAM_DMA_Copy(page:number){ //TODO Secondary OAM - what does it do? //I think it's just used for sprites on the current scanline - more than 8 flickering bug let address = 256*page; for(let i = 0;i<256;i++){ this.oam[i] = this.nes.memory.ram[address]; address++; } } writeOAM( value ) { if ( this.vertical_blank ) { this.oam[ this.oamAddress ] = value; this.oamAddress++; //increment oam } } initPalette() { for (let i = 0; i < 64; i++) { this.palette.push(new Color(0, 0, 0)); } this.palette[0x00] = new Color(84, 84, 84); this.palette[0x01] = new Color(0, 30, 116); this.palette[0x02] = new Color(8, 16, 144); this.palette[0x03] = new Color(48, 0, 136); this.palette[0x04] = new Color(68, 0, 100); this.palette[0x05] = new Color(92, 0, 48); this.palette[0x06] = new Color(84, 4, 0); this.palette[0x07] = new Color(60, 24, 0); this.palette[0x08] = new Color(32, 42, 0); this.palette[0x09] = new Color(8, 58, 0); this.palette[0x0A] = new Color(0, 64, 0); this.palette[0x0B] = new Color(0, 60, 0); this.palette[0x0C] = new Color(0, 50, 60); this.palette[0x0D] = new Color(0, 0, 0); this.palette[0x0E] = new Color(0, 0, 0); this.palette[0x0F] = new Color(0, 0, 0); this.palette[0x10] = new Color(152, 150, 152); this.palette[0x11] = new Color(8, 76, 196); this.palette[0x12] = new Color(48, 50, 236); this.palette[0x13] = new Color(92, 30, 228); this.palette[0x14] = new Color(136, 20, 176); this.palette[0x15] = new Color(160, 20, 100); this.palette[0x16] = new Color(152, 34, 32); this.palette[0x17] = new Color(120, 60, 0); this.palette[0x18] = new Color(84, 90, 0); this.palette[0x19] = new Color(40, 114, 0); this.palette[0x1A] = new Color(8, 124, 0); this.palette[0x1B] = new Color(0, 118, 40); this.palette[0x1C] = new Color(0, 102, 120); this.palette[0x1D] = new Color(0, 0, 0); this.palette[0x1E] = new Color(0, 0, 0); this.palette[0x1F] = new Color(0, 0, 0); this.palette[0x20] = new Color(236, 238, 236); this.palette[0x21] = new Color(76, 154, 236); this.palette[0x22] = new Color(120, 124, 236); this.palette[0x23] = new Color(176, 98, 236); this.palette[0x24] = new Color(228, 84, 236); this.palette[0x25] = new Color(236, 88, 180); this.palette[0x26] = new Color(236, 106, 100); this.palette[0x27] = new Color(212, 136, 32); this.palette[0x28] = new Color(160, 170, 0); this.palette[0x29] = new Color(116, 196, 0); this.palette[0x2A] = new Color(76, 208, 32); this.palette[0x2B] = new Color(56, 204, 108); this.palette[0x2C] = new Color(56, 180, 204); this.palette[0x2D] = new Color(60, 60, 60); this.palette[0x2E] = new Color(0, 0, 0); this.palette[0x2F] = new Color(0, 0, 0); this.palette[0x30] = new Color(236, 238, 236); this.palette[0x31] = new Color(168, 204, 236); this.palette[0x32] = new Color(188, 188, 236); this.palette[0x33] = new Color(212, 178, 236); this.palette[0x34] = new Color(236, 174, 236); this.palette[0x35] = new Color(236, 174, 212); this.palette[0x36] = new Color(236, 180, 176); this.palette[0x37] = new Color(228, 196, 144); this.palette[0x38] = new Color(204, 210, 120); this.palette[0x39] = new Color(180, 222, 120); this.palette[0x3A] = new Color(168, 226, 144); this.palette[0x3B] = new Color(152, 226, 180); this.palette[0x3C] = new Color(160, 214, 228); this.palette[0x3D] = new Color(160, 162, 160); this.palette[0x3E] = new Color(0, 0, 0); this.palette[0x3F] = new Color(0, 0, 0); } } export class Color { red: number = 0; green: number = 0; blue: number = 0; alpha: number = 255; constructor(red: number, green: number, blue: number) { this.red = red; this.green = green; this.blue = blue; } }
the_stack
import { expect } from 'chai'; import { Title } from '@phosphor/widgets'; const owner = { name: 'Bob' }; describe('@phosphor/widgets', () => { describe('Title', () => { describe('#constructor()', () => { it('should accept title options', () => { let title = new Title({ owner }); expect(title).to.be.an.instanceof(Title); }); }); describe('#changed', () => { it('should be emitted when the title state changes', () => { let called = false; let title = new Title({ owner }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.label = 'baz'; expect(called).to.equal(true); }); }); describe('#owner', () => { it('should be the title owner', () => { let title = new Title({ owner }); expect(title.owner).to.equal(owner); }); }); describe('#label', () => { it('should default to an empty string', () => { let title = new Title({ owner }); expect(title.label).to.equal(''); }); it('should initialize from the options', () => { let title = new Title({ owner, label: 'foo' }); expect(title.label).to.equal('foo'); }); it('should be writable', () => { let title = new Title({ owner, label: 'foo' }); title.label = 'bar'; expect(title.label).to.equal('bar'); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, label: 'foo' }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.label = 'baz'; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let title = new Title({ owner, label: 'foo' }); title.changed.connect((sender, arg) => { called = true; }); title.label = 'foo'; expect(called).to.equal(false); }); }); describe('#mnemonic', () => { it('should default to `-1', () => { let title = new Title({ owner }); expect(title.mnemonic).to.equal(-1); }); it('should initialize from the options', () => { let title = new Title({ owner, mnemonic: 1 }); expect(title.mnemonic).to.equal(1); }); it('should be writable', () => { let title = new Title({ owner, mnemonic: 1 }); title.mnemonic = 2; expect(title.mnemonic).to.equal(2); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, mnemonic: 1 }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.mnemonic = 0; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let title = new Title({ owner, mnemonic: 1 }); title.changed.connect((sender, arg) => { called = true; }); title.mnemonic = 1; expect(called).to.equal(false); }); }); describe('#icon', () => { it('should default to an empty string', () => { let title = new Title({ owner }); expect(title.icon).to.equal(''); }); it('should initialize from the options', () => { let title = new Title({ owner, icon: 'foo' }); expect(title.icon).to.equal('foo'); }); it('should be writable', () => { let title = new Title({ owner, icon: 'foo' }); title.icon = 'bar'; expect(title.icon).to.equal('bar'); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, icon: 'foo' }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.icon = 'baz'; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let title = new Title({ owner, icon: 'foo' }); title.changed.connect((sender, arg) => { called = true; }); title.icon = 'foo'; expect(called).to.equal(false); }); }); describe('#caption', () => { it('should default to an empty string', () => { let title = new Title({ owner }); expect(title.caption).to.equal(''); }); it('should initialize from the options', () => { let title = new Title({ owner, caption: 'foo' }); expect(title.caption).to.equal('foo'); }); it('should be writable', () => { let title = new Title({ owner, caption: 'foo' }); title.caption = 'bar'; expect(title.caption).to.equal('bar'); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, caption: 'foo' }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.caption = 'baz'; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let title = new Title({ owner, caption: 'foo' }); title.changed.connect((sender, arg) => { called = true; }); title.caption = 'foo'; expect(called).to.equal(false); }); }); describe('#className', () => { it('should default to an empty string', () => { let title = new Title({ owner }); expect(title.className).to.equal(''); }); it('should initialize from the options', () => { let title = new Title({ owner, className: 'foo' }); expect(title.className).to.equal('foo'); }); it('should be writable', () => { let title = new Title({ owner, className: 'foo' }); title.className = 'bar'; expect(title.className).to.equal('bar'); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, className: 'foo' }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.className = 'baz'; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let title = new Title({ owner, className: 'foo' }); title.changed.connect((sender, arg) => { called = true; }); title.className = 'foo'; expect(called).to.equal(false); }); }); describe('#closable', () => { it('should default to `false`', () => { let title = new Title({ owner }); expect(title.closable).to.equal(false); }); it('should initialize from the options', () => { let title = new Title({ owner, closable: true }); expect(title.closable).to.equal(true); }); it('should be writable', () => { let title = new Title({ owner, closable: true }); title.closable = false; expect(title.closable).to.equal(false); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, closable: false }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.closable = true; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let title = new Title({ owner, closable: false }); title.changed.connect((sender, arg) => { called = true; }); title.closable = false; expect(called).to.equal(false); }); }); describe('#dataset', () => { it('should default to `{}`', () => { let title = new Title({ owner }); expect(title.dataset).to.deep.equal({}); }); it('should initialize from the options', () => { let title = new Title({ owner, dataset: { foo: '12' } }); expect(title.dataset).to.deep.equal({ foo: '12' }); }); it('should be writable', () => { let title = new Title({ owner, dataset: { foo: '12' } }); title.dataset = { bar: '42' }; expect(title.dataset).to.deep.equal({ bar: '42' }); }); it('should emit the changed signal when the value changes', () => { let called = false; let title = new Title({ owner, dataset: { foo: '12' } }); title.changed.connect((sender, arg) => { expect(sender).to.equal(title); expect(arg).to.equal(undefined); called = true; }); title.dataset = { bar: '42' }; expect(called).to.equal(true); }); it('should not emit the changed signal when the value does not change', () => { let called = false; let dataset = { foo: '12' }; let title = new Title({ owner, dataset }); title.changed.connect((sender, arg) => { called = true; }); title.dataset = dataset; expect(called).to.equal(false); }); }); }); });
the_stack
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; import { AfterViewInit, Component, ChangeDetectionStrategy, ChangeDetectorRef, ContentChild, ElementRef, EventEmitter, Inject, Input, NgZone, OnDestroy, Optional, Output, ViewEncapsulation, ViewChild, Attribute, } from '@angular/core'; import {DOCUMENT} from '@angular/common'; import { CanColor, CanDisable, CanDisableRipple, HasTabIndex, MatRipple, MAT_RIPPLE_GLOBAL_OPTIONS, mixinColor, mixinDisableRipple, mixinTabIndex, mixinDisabled, RippleGlobalOptions, } from '@angular/material-experimental/mdc-core'; import {FocusMonitor} from '@angular/cdk/a11y'; import {Subject} from 'rxjs'; import {take} from 'rxjs/operators'; import {MatChipAvatar, MatChipTrailingIcon, MatChipRemove} from './chip-icons'; import {MatChipAction} from './chip-action'; import {BACKSPACE, DELETE} from '@angular/cdk/keycodes'; import {MAT_CHIP, MAT_CHIP_AVATAR, MAT_CHIP_REMOVE, MAT_CHIP_TRAILING_ICON} from './tokens'; let uid = 0; /** Represents an event fired on an individual `mat-chip`. */ export interface MatChipEvent { /** The chip the event was fired on. */ chip: MatChip; } /** * Boilerplate for applying mixins to MatChip. * @docs-private */ const _MatChipMixinBase = mixinTabIndex( mixinColor( mixinDisableRipple( mixinDisabled( class { constructor(public _elementRef: ElementRef<HTMLElement>) {} }, ), ), 'primary', ), -1, ); /** * Material design styled Chip base component. Used inside the MatChipSet component. * * Extended by MatChipOption and MatChipRow for different interaction patterns. */ @Component({ selector: 'mat-basic-chip, mat-chip', inputs: ['color', 'disabled', 'disableRipple', 'tabIndex'], exportAs: 'matChip', templateUrl: 'chip.html', styleUrls: ['chip.css'], host: { 'class': 'mat-mdc-chip', '[class.mdc-evolution-chip]': '!_isBasicChip', '[class.mdc-evolution-chip--disabled]': 'disabled', '[class.mdc-evolution-chip--with-trailing-action]': '_hasTrailingIcon()', '[class.mdc-evolution-chip--with-primary-graphic]': 'leadingIcon', '[class.mdc-evolution-chip--with-primary-icon]': 'leadingIcon', '[class.mdc-evolution-chip--with-avatar]': 'leadingIcon', '[class.mat-mdc-chip-with-avatar]': 'leadingIcon', '[class.mat-mdc-chip-highlighted]': 'highlighted', '[class.mat-mdc-chip-disabled]': 'disabled', '[class.mat-mdc-basic-chip]': '_isBasicChip', '[class.mat-mdc-standard-chip]': '!_isBasicChip', '[class.mat-mdc-chip-with-trailing-icon]': '_hasTrailingIcon()', '[class._mat-animation-noopable]': '_animationsDisabled', '[id]': 'id', '[attr.role]': 'role', '[attr.tabindex]': 'role ? tabIndex : null', '[attr.aria-label]': 'ariaLabel', '(keydown)': '_handleKeydown($event)', }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [{provide: MAT_CHIP, useExisting: MatChip}], }) export class MatChip extends _MatChipMixinBase implements AfterViewInit, CanColor, CanDisableRipple, CanDisable, HasTabIndex, OnDestroy { protected _document: Document; /** Whether the ripple is centered on the chip. */ readonly _isRippleCentered = false; /** Emits when the chip is focused. */ readonly _onFocus = new Subject<MatChipEvent>(); /** Emits when the chip is blurred. */ readonly _onBlur = new Subject<MatChipEvent>(); /** Whether this chip is a basic (unstyled) chip. */ readonly _isBasicChip: boolean; /** Role for the root of the chip. */ @Input() role: string | null = null; /** Whether the chip has focus. */ private _hasFocusInternal = false; /** Whether moving focus into the chip is pending. */ private _pendingFocus: boolean; /** Whether animations for the chip are enabled. */ _animationsDisabled: boolean; _hasFocus() { return this._hasFocusInternal; } /** A unique id for the chip. If none is supplied, it will be auto-generated. */ @Input() id: string = `mat-mdc-chip-${uid++}`; /** ARIA label for the content of the chip. */ @Input('aria-label') ariaLabel: string | null = null; private _textElement!: HTMLElement; /** * The value of the chip. Defaults to the content inside * the `mat-mdc-chip-action-label` element. */ @Input() get value(): any { return this._value !== undefined ? this._value : this._textElement.textContent!.trim(); } set value(value: any) { this._value = value; } protected _value: any; /** * Determines whether or not the chip displays the remove styling and emits (removed) events. */ @Input() get removable(): boolean { return this._removable; } set removable(value: BooleanInput) { this._removable = coerceBooleanProperty(value); } protected _removable: boolean = true; /** * Colors the chip for emphasis as if it were selected. */ @Input() get highlighted(): boolean { return this._highlighted; } set highlighted(value: BooleanInput) { this._highlighted = coerceBooleanProperty(value); } protected _highlighted: boolean = false; /** Emitted when a chip is to be removed. */ @Output() readonly removed: EventEmitter<MatChipEvent> = new EventEmitter<MatChipEvent>(); /** Emitted when the chip is destroyed. */ @Output() readonly destroyed: EventEmitter<MatChipEvent> = new EventEmitter<MatChipEvent>(); /** The unstyled chip selector for this component. */ protected basicChipAttrName = 'mat-basic-chip'; /** The chip's leading icon. */ @ContentChild(MAT_CHIP_AVATAR) leadingIcon: MatChipAvatar; /** The chip's trailing icon. */ @ContentChild(MAT_CHIP_TRAILING_ICON) trailingIcon: MatChipTrailingIcon; /** The chip's trailing remove icon. */ @ContentChild(MAT_CHIP_REMOVE) removeIcon: MatChipRemove; /** Reference to the MatRipple instance of the chip. */ @ViewChild(MatRipple) ripple: MatRipple; /** Action receiving the primary set of user interactions. */ @ViewChild(MatChipAction) primaryAction: MatChipAction; constructor( public _changeDetectorRef: ChangeDetectorRef, elementRef: ElementRef<HTMLElement>, protected _ngZone: NgZone, private _focusMonitor: FocusMonitor, @Inject(DOCUMENT) _document: any, @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string, @Optional() @Inject(MAT_RIPPLE_GLOBAL_OPTIONS) private _globalRippleOptions?: RippleGlobalOptions, @Attribute('tabindex') tabIndex?: string, ) { super(elementRef); const element = elementRef.nativeElement; this._document = _document; this._animationsDisabled = animationMode === 'NoopAnimations'; this._isBasicChip = element.hasAttribute(this.basicChipAttrName) || element.tagName.toLowerCase() === this.basicChipAttrName; if (tabIndex != null) { this.tabIndex = parseInt(tabIndex) ?? this.defaultTabIndex; } this._monitorFocus(); } ngAfterViewInit() { this._textElement = this._elementRef.nativeElement.querySelector('.mat-mdc-chip-action-label')!; if (this._pendingFocus) { this._pendingFocus = false; this.focus(); } } ngOnDestroy() { this._focusMonitor.stopMonitoring(this._elementRef); this.destroyed.emit({chip: this}); this.destroyed.complete(); } /** * Allows for programmatic removal of the chip. * * Informs any listeners of the removal request. Does not remove the chip from the DOM. */ remove(): void { if (this.removable) { this.removed.emit({chip: this}); } } /** Whether or not the ripple should be disabled. */ _isRippleDisabled(): boolean { return ( this.disabled || this.disableRipple || this._animationsDisabled || this._isBasicChip || !!this._globalRippleOptions?.disabled ); } /** Returns whether the chip has a trailing icon. */ _hasTrailingIcon() { return !!(this.trailingIcon || this.removeIcon); } /** Handles keyboard events on the chip. */ _handleKeydown(event: KeyboardEvent) { if (event.keyCode === BACKSPACE || event.keyCode === DELETE) { event.preventDefault(); this.remove(); } } /** Allows for programmatic focusing of the chip. */ focus(): void { if (!this.disabled) { // If `focus` is called before `ngAfterViewInit`, we won't have access to the primary action. // This can happen if the consumer tries to focus a chip immediately after it is added. // Queue the method to be called again on init. if (this.primaryAction) { this.primaryAction.focus(); } else { this._pendingFocus = true; } } } /** Gets the action that contains a specific target node. */ _getSourceAction(target: Node): MatChipAction | undefined { return this._getActions().find(action => { const element = action._elementRef.nativeElement; return element === target || element.contains(target); }); } /** Gets all of the actions within the chip. */ _getActions(): MatChipAction[] { const result: MatChipAction[] = []; if (this.primaryAction) { result.push(this.primaryAction); } if (this.removeIcon) { result.push(this.removeIcon); } if (this.trailingIcon) { result.push(this.trailingIcon); } return result; } /** Handles interactions with the primary action of the chip. */ _handlePrimaryActionInteraction() { // Empty here, but is overwritten in child classes. } /** Starts the focus monitoring process on the chip. */ private _monitorFocus() { this._focusMonitor.monitor(this._elementRef, true).subscribe(origin => { const hasFocus = origin !== null; if (hasFocus !== this._hasFocusInternal) { this._hasFocusInternal = hasFocus; if (hasFocus) { this._onFocus.next({chip: this}); } else { // When animations are enabled, Angular may end up removing the chip from the DOM a little // earlier than usual, causing it to be blurred and throwing off the logic in the chip list // that moves focus not the next item. To work around the issue, we defer marking the chip // as not focused until the next time the zone stabilizes. this._ngZone.onStable .pipe(take(1)) .subscribe(() => this._ngZone.run(() => this._onBlur.next({chip: this}))); } } }); } }
the_stack