text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import type { ElementHandle, JSHandle } from 'puppeteer'; import type { AsyncHookTracker } from './async-hooks'; import { activeAsyncHookTrackers } from './async-hooks'; import { createClientRuntimeServer } from './module-server/client-runtime-server'; import { deserialize, serialize } from './serialize'; import { isElementHandle, isPromise, jsHandleToArray, printColorsInErrorMessages, removeFuncFromStackTrace, } from './utils'; const methods = [ 'toBeInTheDocument', 'toBeEmptyDOMElement', 'toContainElement', 'toContainHTML', 'toHaveAccessibleDescription', 'toHaveAccessibleName', 'toHaveTextContent', 'toHaveAttribute', 'toHaveClass', 'toHaveStyle', 'toHaveFocus', 'toHaveFormValues', 'toBeVisible', 'toBeDisabled', 'toBeEnabled', 'toBeRequired', 'toBeInvalid', 'toBeValid', 'toHaveValue', 'toHaveDisplayValue', 'toBeChecked', 'toBePartiallyChecked', 'toHaveErrorMessage', ] as const; const isJSHandle = (input: unknown): input is JSHandle => { if (typeof input !== 'object' || !input) return false; // @ts-expect-error checking for properties that don't necessarily exist return input.asElement && input.dispose && input.evaluate; }; const matchers: jest.ExpectExtendMap = Object.fromEntries( methods.map((methodName) => { const matcher = async function ( this: jest.MatcherUtils, elementHandle: ElementHandle | null, ...matcherArgs: unknown[] ): Promise<jest.CustomMatcherResult> { const serverPromise = createClientRuntimeServer(); if (!isElementHandle(elementHandle)) { // Special case: expect(null).not.toBeInTheDocument() should pass if (methodName === 'toBeInTheDocument' && this.isNot) { // This is actually passing but since it is isNot it has to return false return { pass: false, message: () => '' }; } const message = [ this.utils.matcherHint( `${this.isNot ? '.not' : ''}.${methodName}`, 'received', '', ), '', `${this.utils.RECEIVED_COLOR( 'received', )} value must be an HTMLElement or an SVGElement.`, isPromise(elementHandle) ? `Received a ${this.utils.RECEIVED_COLOR( 'Promise', )}. Did you forget to await?` : this.utils.printWithType( 'Received', elementHandle, this.utils.printReceived, ), ].join('\n'); throw removeFuncFromStackTrace(new Error(message), matcher); } for (const arg of matcherArgs) { if ( typeof arg === 'object' && typeof (arg as any)?.asymmetricMatch === 'function' ) { const error = new Error( `Pleasantest does not support using asymmetric matchers in browser-based matchers Received ${this.utils.printReceived(arg)}`, ); throw removeFuncFromStackTrace(error, matcher); } } const { port } = await serverPromise; const ctxString = JSON.stringify(this); // Contains stuff like isNot and promise const result = await elementHandle.evaluateHandle( // Using new Function to avoid babel transpiling the import // @ts-expect-error pptr's types don't like new Function new Function( 'element', '...matcherArgs', `return import("http://localhost:${port}/@pleasantest/jest-dom") .then(({ jestContext, deserialize, ...jestDom }) => { const context = { ...(${ctxString}), ...jestContext } try { const deserialized = matcherArgs .slice(1) .map(a => typeof a === 'string' ? deserialize(a) : a) return jestDom.${methodName}.call(context, element, ...deserialized) } catch (error) { return { thrown: true, error } } })`, ), elementHandle, ...matcherArgs.map((arg) => (isJSHandle(arg) ? arg : serialize(arg))), ); // Whether the matcher threw (this is different from the matcher failing) // The matcher failing means that it returned a result for Jest to throw // But a matcher throwing means that the input was invalid or something const thrownError = await result.evaluate((result) => result.thrown); // We have to evaluate the message right away // because Jest does not accept a promise from the returned message property const message = await result.evaluate( thrownError ? (matcherResult) => matcherResult.error.message : (matcherResult) => matcherResult.message(), ); const deserializedMessage = runJestUtilsInNode(message, this as any); const { messageWithElementsRevived, messageWithElementsStringified } = await elementHandle .evaluateHandle( // @ts-expect-error pptr's types don't like new Function new Function( 'el', 'message', `return import("http://localhost:${port}/@pleasantest/jest-dom") .then(({ reviveElementsInString, printElement }) => { const messageWithElementsRevived = reviveElementsInString(message) const messageWithElementsStringified = messageWithElementsRevived .map(el => { if (el instanceof Element) return printElement(el, ${printColorsInErrorMessages}) return el }) .join('') return { messageWithElementsRevived, messageWithElementsStringified } })`, ), deserializedMessage, ) .then(async (returnHandle) => { const { messageWithElementsRevived, messageWithElementsStringified, } = Object.fromEntries(await returnHandle.getProperties()); return { messageWithElementsStringified: await messageWithElementsStringified.jsonValue(), messageWithElementsRevived: await jsHandleToArray( messageWithElementsRevived, ), }; }); if (thrownError) { const error = new Error(messageWithElementsStringified as any); // @ts-expect-error messageForBrowser is a property we added to Error error.messageForBrowser = messageWithElementsRevived; throw removeFuncFromStackTrace(error, matcher); } return { ...((await result.jsonValue()) as any), message: () => messageWithElementsStringified, messageForBrowser: messageWithElementsRevived, }; }; const matcherWrapper = async function ( this: jest.MatcherUtils, elementHandle: ElementHandle | null, ...matcherArgs: unknown[] ): Promise<jest.CustomMatcherResult> { const asyncHookTracker: AsyncHookTracker | false = activeAsyncHookTrackers.size === 1 && activeAsyncHookTrackers[Symbol.iterator]().next().value; if (asyncHookTracker) { const res = await asyncHookTracker.addHook( () => matcher.call(this, elementHandle, ...matcherArgs), matchers[methodName], ); // AddHook resolves to undefined if the function throws after the async hook tracker closes // Because it needs to not trigger an unhandled promise rejection if (res === undefined) return { pass: !this.isNot, message: () => '' }; return res; } return matcher.call(this, elementHandle, ...matcherArgs); }; return [methodName, matcherWrapper]; }), ); const runJestUtilsInNode = (message: string, context: jest.MatcherContext) => { // Handling nested JEST_UTILS calls here is the complexity // The while loop goes through them in reverse // so inner (nested) calls are evaluated before outer calls const jestUtilsCalls = [ ...message.matchAll(/\$JEST_UTILS\.([$A-Z_a-z]*)\$/g), ]; const closeRegex = /\$END_JEST_UTILS\$/g; let jestUtilsCall; while ((jestUtilsCall = jestUtilsCalls.pop())) { const start = jestUtilsCall.index!; const methodName = jestUtilsCall[1]; closeRegex.lastIndex = start; const closeIndex = closeRegex.exec(message)?.index; if (closeIndex !== undefined) { const argsString = message.slice( start + jestUtilsCall[0].length, closeIndex, ); const parsedArgs = deserialize(argsString); // @ts-expect-error TS doesn't know about the properties const res: string = context.utils[methodName](...parsedArgs); // Const escaped = res.replace(/"/g, '\\"').replace(/\u001b/g, '\\u001b'); const escaped = JSON.stringify(res).replace(/^"/, '').replace(/"$/, ''); message = message.slice(0, start) + escaped + message.slice(closeIndex + '$END_JEST_UTILS$'.length); } } return message .replace(/\\u[\dA-Fa-f]{4}/g, (match) => JSON.parse(`"${match}"`)) .replace(/\\./g, (match) => JSON.parse(`"${match}"`)); }; expect.extend(matchers); // These type definitions are incomplete, only including methods we've tested // More can be added from https://unpkg.com/@types/testing-library__jest-dom/index.d.ts // You can copy-paste and change the return types to promises declare global { // eslint-disable-next-line @cloudfour/typescript-eslint/no-namespace namespace jest { interface Matchers<R> { /** * Check whether an element is disabled from the user's perspective. * https://github.com/testing-library/jest-dom#tobedisabled */ toBeDisabled(): Promise<R>; /** * Check whether an element is not disabled from the user's perspective. * https://github.com/testing-library/jest-dom#tobeenabled * Same as .not.toBeDisabled() */ toBeEnabled(): Promise<R>; /** * Assert whether an element has content or not. * https://github.com/testing-library/jest-dom#tobeemptydomelement */ toBeEmptyDOMElement(): Promise<R>; /** * Assert whether an element is present in the document or not. * https://github.com/testing-library/jest-dom#tobeinthedocument */ toBeInTheDocument(): Promise<R>; /** * Check if the value of an element is currently invalid. * Uses [HTML5 Constraint Validation](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation) and checks for `aria-invalid`. * https://github.com/testing-library/jest-dom#tobeinvalid */ toBeInvalid(): Promise<R>; /** * Check if a form element is currently required. * https://github.com/testing-library/jest-dom#toberequired */ toBeRequired(): Promise<R>; /** * Check if the value of an element is currently valid. * Uses [HTML5 Constraint Validation](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation) and checks for `aria-invalid`. * https://github.com/testing-library/jest-dom#tobevalid */ toBeValid(): Promise<R>; /** * Check if an element is currently visible to the user. * https://github.com/testing-library/jest-dom#tobevisible */ toBeVisible(): Promise<R>; /** * Check if an element contains another element as a descendant. * https://github.com/testing-library/jest-dom#tocontainelement */ toContainElement( element: ElementHandle<HTMLElement | SVGElement> | null, ): Promise<R>; /** * Check whether a string representing a HTML element is contained in another element. * https://github.com/testing-library/jest-dom#tocontainhtml */ toContainHTML(html: string): Promise<R>; /** * Assert that an element has the expected [accessible description](https://www.w3.org/TR/accname-1.1/#dfn-accessible-description). * You can pass the exact string, or you can make a partial match passing a regular expression * https://github.com/testing-library/jest-dom#tohaveaccessibledescription */ toHaveAccessibleDescription(text?: string | RegExp): Promise<R>; /** * Assert that an element has the expected [accessible description](https://www.w3.org/TR/accname-1.1/#dfn-accessible-name). * It is useful, for instance, to assert that form elements and buttons are properly labelled. * You can pass the exact string, or you can make a partial match passing a regular expression * https://github.com/testing-library/jest-dom#tohaveaccessibledescription */ toHaveAccessibleName(text?: string | RegExp): Promise<R>; /** * Check whether the given element has an attribute or not. * You can also optionally check that the attribute has a specific expected value * https://github.com/testing-library/jest-dom#tohaveattribute */ toHaveAttribute(attr: string, value?: string): Promise<R>; /** * Check whether the given element has certain classes within its class attribute. * You must provide at least one class, unless you are asserting that an element does not have any classes. * https://github.com/testing-library/jest-dom#tohaveclass */ toHaveClass(...classNames: string[]): Promise<R>; toHaveClass(classNames: string, options?: { exact: boolean }): Promise<R>; /** * Check whether an element has focus * https://github.com/testing-library/jest-dom#tohavefocus */ toHaveFocus(): Promise<R>; /** * Check if a form or fieldset contains form controls for each given name, and value. * https://github.com/testing-library/jest-dom#tohaveformvalues */ toHaveFormValues(expectedValues: Record<string, unknown>): Promise<R>; /** * Check if an element has specific css properties applied * Unlike jest-dom, pleasantest does not support specifying expected styles as strings, they must be specified as an object. * https://github.com/testing-library/jest-dom#tohavestyle */ toHaveStyle(css: Record<string, unknown>): Promise<R>; /** * Check whether the given element has a text content * https://github.com/testing-library/jest-dom#tohavetextcontent */ toHaveTextContent( text: string | RegExp, options?: { normalizeWhitespace: boolean }, ): Promise<R>; /** * Check whether the given form element has the specified value. * It accepts <input>, <select> and <textarea> elements with the exception of <input type="checkbox"> and <input type="radio">, which should be matched using toBeChecked or toHaveFormValues. * https://github.com/testing-library/jest-dom#tohavevalue */ toHaveValue(value?: string | string[] | number | null): Promise<R>; /** * Check whether the given form element has the specified displayed value (the one the end user will see). * It accepts <input>, <select> and <textarea> elements with the exception of <input type="checkbox"> and <input type="radio">, which should be matched using toBeChecked or toHaveFormValues. * https://github.com/testing-library/jest-dom#tohavedisplayvalue */ toHaveDisplayValue( value: string | RegExp | (string | RegExp)[], ): Promise<R>; /** * Check whether the given element is checked. * Accepts an `input` of type `checkbox` or `radio` * and elements with a `role` of `checkbox`, `radio` or `switch` * with a valid `aria-checked` attribute of "true" or "false". * https://github.com/testing-library/jest-dom#tobechecked */ toBeChecked(): Promise<R>; /** * Check whether the given element is partially checked. * It accepts an `input` of type `checkbox` and elements with a `role` of `checkbox` with `aria-checked="mixed"`, or input of type `checkbox` with `indeterminate` set to `true` * https://github.com/testing-library/jest-dom#tobepartiallychecked */ toBePartiallyChecked(): Promise<R>; /** * Check whether the given element has an ARIA error message (via aria-errormessage) * https://github.com/testing-library/jest-dom#tohaveerrormessage */ toHaveErrorMessage(text: string | RegExp): Promise<R>; } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Linked Service (connection) between a Kusto Cluster and Azure Data Factory. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleFactory = new azure.datafactory.Factory("exampleFactory", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * identity: { * type: "SystemAssigned", * }, * }); * const exampleCluster = new azure.kusto.Cluster("exampleCluster", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * sku: { * name: "Standard_D13_v2", * capacity: 2, * }, * }); * const exampleDatabase = new azure.kusto.Database("exampleDatabase", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * clusterName: exampleCluster.name, * }); * const exampleLinkedServiceKusto = new azure.datafactory.LinkedServiceKusto("exampleLinkedServiceKusto", { * dataFactoryId: exampleFactory.id, * kustoEndpoint: exampleCluster.uri, * kustoDatabaseName: exampleDatabase.name, * useManagedIdentity: true, * }); * const exampleDatabasePrincipalAssignment = new azure.kusto.DatabasePrincipalAssignment("exampleDatabasePrincipalAssignment", { * resourceGroupName: exampleResourceGroup.name, * clusterName: exampleCluster.name, * databaseName: exampleDatabase.name, * tenantId: exampleFactory.identity.apply(identity => identity.tenantId), * principalId: exampleFactory.identity.apply(identity => identity.principalId), * principalType: "App", * role: "Viewer", * }); * ``` * * ## Import * * Data Factory Linked Service's can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:datafactory/linkedServiceKusto:LinkedServiceKusto example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/linkedservices/example * ``` */ export class LinkedServiceKusto extends pulumi.CustomResource { /** * Get an existing LinkedServiceKusto resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: LinkedServiceKustoState, opts?: pulumi.CustomResourceOptions): LinkedServiceKusto { return new LinkedServiceKusto(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:datafactory/linkedServiceKusto:LinkedServiceKusto'; /** * Returns true if the given object is an instance of LinkedServiceKusto. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is LinkedServiceKusto { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LinkedServiceKusto.__pulumiType; } /** * A map of additional properties to associate with the Data Factory Linked Service. */ public readonly additionalProperties!: pulumi.Output<{[key: string]: string} | undefined>; /** * List of tags that can be used for describing the Data Factory Linked Service. */ public readonly annotations!: pulumi.Output<string[] | undefined>; /** * The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource. */ public readonly dataFactoryId!: pulumi.Output<string>; /** * The description for the Data Factory Linked Service. */ public readonly description!: pulumi.Output<string | undefined>; /** * The integration runtime reference to associate with the Data Factory Linked Service. */ public readonly integrationRuntimeName!: pulumi.Output<string | undefined>; /** * The Kusto Database Name. */ public readonly kustoDatabaseName!: pulumi.Output<string>; /** * The URI of the Kusto Cluster endpoint. */ public readonly kustoEndpoint!: pulumi.Output<string>; /** * Specifies the name of the Data Factory Linked Service. Changing this forces a new resource to be created. Must be unique within a data * factory. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions. */ public readonly name!: pulumi.Output<string>; /** * A map of parameters to associate with the Data Factory Linked Service. */ public readonly parameters!: pulumi.Output<{[key: string]: string} | undefined>; /** * The service principal id in which to authenticate against the Kusto Database. */ public readonly servicePrincipalId!: pulumi.Output<string | undefined>; /** * The service principal key in which to authenticate against the Kusto Database. */ public readonly servicePrincipalKey!: pulumi.Output<string | undefined>; /** * The service principal tenant id or name in which to authenticate against the Kusto Database. */ public readonly tenant!: pulumi.Output<string | undefined>; /** * Whether to use the Data Factory's managed identity to authenticate against the Kusto Database. */ public readonly useManagedIdentity!: pulumi.Output<boolean | undefined>; /** * Create a LinkedServiceKusto resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: LinkedServiceKustoArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: LinkedServiceKustoArgs | LinkedServiceKustoState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as LinkedServiceKustoState | undefined; inputs["additionalProperties"] = state ? state.additionalProperties : undefined; inputs["annotations"] = state ? state.annotations : undefined; inputs["dataFactoryId"] = state ? state.dataFactoryId : undefined; inputs["description"] = state ? state.description : undefined; inputs["integrationRuntimeName"] = state ? state.integrationRuntimeName : undefined; inputs["kustoDatabaseName"] = state ? state.kustoDatabaseName : undefined; inputs["kustoEndpoint"] = state ? state.kustoEndpoint : undefined; inputs["name"] = state ? state.name : undefined; inputs["parameters"] = state ? state.parameters : undefined; inputs["servicePrincipalId"] = state ? state.servicePrincipalId : undefined; inputs["servicePrincipalKey"] = state ? state.servicePrincipalKey : undefined; inputs["tenant"] = state ? state.tenant : undefined; inputs["useManagedIdentity"] = state ? state.useManagedIdentity : undefined; } else { const args = argsOrState as LinkedServiceKustoArgs | undefined; if ((!args || args.dataFactoryId === undefined) && !opts.urn) { throw new Error("Missing required property 'dataFactoryId'"); } if ((!args || args.kustoDatabaseName === undefined) && !opts.urn) { throw new Error("Missing required property 'kustoDatabaseName'"); } if ((!args || args.kustoEndpoint === undefined) && !opts.urn) { throw new Error("Missing required property 'kustoEndpoint'"); } inputs["additionalProperties"] = args ? args.additionalProperties : undefined; inputs["annotations"] = args ? args.annotations : undefined; inputs["dataFactoryId"] = args ? args.dataFactoryId : undefined; inputs["description"] = args ? args.description : undefined; inputs["integrationRuntimeName"] = args ? args.integrationRuntimeName : undefined; inputs["kustoDatabaseName"] = args ? args.kustoDatabaseName : undefined; inputs["kustoEndpoint"] = args ? args.kustoEndpoint : undefined; inputs["name"] = args ? args.name : undefined; inputs["parameters"] = args ? args.parameters : undefined; inputs["servicePrincipalId"] = args ? args.servicePrincipalId : undefined; inputs["servicePrincipalKey"] = args ? args.servicePrincipalKey : undefined; inputs["tenant"] = args ? args.tenant : undefined; inputs["useManagedIdentity"] = args ? args.useManagedIdentity : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(LinkedServiceKusto.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering LinkedServiceKusto resources. */ export interface LinkedServiceKustoState { /** * A map of additional properties to associate with the Data Factory Linked Service. */ additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * List of tags that can be used for describing the Data Factory Linked Service. */ annotations?: pulumi.Input<pulumi.Input<string>[]>; /** * The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource. */ dataFactoryId?: pulumi.Input<string>; /** * The description for the Data Factory Linked Service. */ description?: pulumi.Input<string>; /** * The integration runtime reference to associate with the Data Factory Linked Service. */ integrationRuntimeName?: pulumi.Input<string>; /** * The Kusto Database Name. */ kustoDatabaseName?: pulumi.Input<string>; /** * The URI of the Kusto Cluster endpoint. */ kustoEndpoint?: pulumi.Input<string>; /** * Specifies the name of the Data Factory Linked Service. Changing this forces a new resource to be created. Must be unique within a data * factory. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions. */ name?: pulumi.Input<string>; /** * A map of parameters to associate with the Data Factory Linked Service. */ parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The service principal id in which to authenticate against the Kusto Database. */ servicePrincipalId?: pulumi.Input<string>; /** * The service principal key in which to authenticate against the Kusto Database. */ servicePrincipalKey?: pulumi.Input<string>; /** * The service principal tenant id or name in which to authenticate against the Kusto Database. */ tenant?: pulumi.Input<string>; /** * Whether to use the Data Factory's managed identity to authenticate against the Kusto Database. */ useManagedIdentity?: pulumi.Input<boolean>; } /** * The set of arguments for constructing a LinkedServiceKusto resource. */ export interface LinkedServiceKustoArgs { /** * A map of additional properties to associate with the Data Factory Linked Service. */ additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * List of tags that can be used for describing the Data Factory Linked Service. */ annotations?: pulumi.Input<pulumi.Input<string>[]>; /** * The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource. */ dataFactoryId: pulumi.Input<string>; /** * The description for the Data Factory Linked Service. */ description?: pulumi.Input<string>; /** * The integration runtime reference to associate with the Data Factory Linked Service. */ integrationRuntimeName?: pulumi.Input<string>; /** * The Kusto Database Name. */ kustoDatabaseName: pulumi.Input<string>; /** * The URI of the Kusto Cluster endpoint. */ kustoEndpoint: pulumi.Input<string>; /** * Specifies the name of the Data Factory Linked Service. Changing this forces a new resource to be created. Must be unique within a data * factory. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions. */ name?: pulumi.Input<string>; /** * A map of parameters to associate with the Data Factory Linked Service. */ parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The service principal id in which to authenticate against the Kusto Database. */ servicePrincipalId?: pulumi.Input<string>; /** * The service principal key in which to authenticate against the Kusto Database. */ servicePrincipalKey?: pulumi.Input<string>; /** * The service principal tenant id or name in which to authenticate against the Kusto Database. */ tenant?: pulumi.Input<string>; /** * Whether to use the Data Factory's managed identity to authenticate against the Kusto Database. */ useManagedIdentity?: pulumi.Input<boolean>; }
the_stack
import { ActionTree } from 'vuex'; import { StateInterface } from '../index'; import { AuthStateInterface } from './state'; import { apiNoAuth as $httpNoAuth } from '../../boot/httpNoAuth'; import { api as $http } from '../../boot/http'; import { Notify } from 'quasar'; import { LoginHttpResponse, HttpError, HttpResponse } from '../types'; const actions: ActionTree<AuthStateInterface, StateInterface> = { REGISTER_USER({ commit }, form) { return new Promise(async (resolve, reject) => { await $httpNoAuth .post('/auth/register', form) .then((res: LoginHttpResponse & HttpResponse) => { const data = res.data; const token = data.token; const userData = data.data; commit('SET_TOKEN', token); commit('SET_USER_DATA', userData); resolve(res.data); }) .catch((error: HttpError) => { reject(error); }); }); }, LOGIN_USER({ commit }, form) { return new Promise(async (resolve, reject) => { await $httpNoAuth .post('/auth/login', form) .then((res: LoginHttpResponse & HttpResponse) => { const data = res.data; const token = data.token; const userData = data.data; commit('SET_TOKEN', token); commit('SET_USER_DATA', userData); Notify.create({ message: data?.message, type: 'positive', position: 'top', progress: true, timeout: 2000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); resolve(res.data); }) .catch((error: HttpError) => { reject(error); }); }); }, LOGOUT_USER({ commit }) { return new Promise(async (resolve, reject) => { await $http .post('/auth/logout') .then((res: LoginHttpResponse) => { Notify.create({ message: 'You have been logged out!', type: 'positive', position: 'top', progress: true, timeout: 2000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); commit('LOGOUT_USER'); return resolve(res.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, FETCH_AUTH_PROFILE({ commit }) { return new Promise(async (resolve, reject) => { await $http .get('/auth/profile') .then((res: LoginHttpResponse) => { commit('SET_USER_DATA', res.data.data); resolve(res.data); }) .catch((error: HttpError) => { reject(error); }); }); }, REQUEST_PASSWORD_RESET(_, form: { email: string }) { return new Promise(async (resolve, reject) => { await $httpNoAuth .post('/auth/request-password-reset', { ...form }) .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: 'Password-reset email was sent', type: 'positive', position: 'top', progress: true, timeout: 2000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, VERIFY_PASSWORD_RESET(_, key: string) { return new Promise(async (resolve, reject) => { console.log(key); await $httpNoAuth .post('/auth/verify-password-reset', { key }) .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: 'Verified. Please reset your password!', type: 'positive', position: 'top', progress: true, timeout: 5000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, RESET_PASSWORD( { commit }, form: { email: string; newPassword: string; confirmNewPassword: string } ) { return new Promise(async (resolve, reject) => { console.log(form); await $httpNoAuth .post('/auth/reset-password', { ...form }) .then((res: LoginHttpResponse & HttpResponse) => { const data = res.data; const token = data.token; const userData = data.data; commit('SET_TOKEN', token); commit('SET_USER_DATA', userData); Notify.create({ message: data?.message, type: 'positive', position: 'top', progress: true, timeout: 2000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, CONFIRM_CURRENT_PASSWORD_FOR_PASSWORD_CHANGE( _, { currentPassword }: { currentPassword: string } ) { return new Promise(async (resolve, reject) => { await $http .post('/auth/confirm-current-password', { currentPassword, }) .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: res.data.message, type: 'positive', position: 'top', progress: true, timeout: 5000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, CONFIRM_CODE_FOR_PASSWORD_CHANGE( _, { code, secret }: { code: number; secret: string } ) { return new Promise(async (resolve, reject) => { await $http .post('/auth/confirm-password-change-code', { code, secret, }) .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: res.data.message, type: 'positive', position: 'top', progress: true, timeout: 5000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, SUBMIT_NEW_PASSWORD( _, { newPassword, confirmNewPassword, secret, }: { newPassword: string; confirmNewPassword: string; secret: string } ) { return new Promise(async (resolve, reject) => { await $http .post('/auth/submit-new-password', { newPassword, confirmNewPassword, secret, }) .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: res.data.message, type: 'positive', position: 'top', progress: true, timeout: 5000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, NEW_ACCOUNT_EMAIL_VERIFICATION(_, key: string) { return new Promise(async (resolve, reject) => { console.log(key); await $httpNoAuth .post('/auth/new-account-email-verification', { key }) .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: res.data.message, type: 'positive', position: 'top', progress: true, timeout: 5000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.message); }) .catch((error: HttpError) => { Notify.create({ message: error?.response?.data?.message ?? '', type: 'negative', position: 'top', progress: true, timeout: 5000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return reject(error?.response?.data?.message ?? ''); }); }); }, REQUEST_EMAIL_VERIFICATION() { return new Promise(async (resolve, reject) => { await $http .post('/auth/request-email-verification') .then((res: LoginHttpResponse & HttpResponse) => { Notify.create({ message: res.data.message, type: 'positive', position: 'top', progress: true, timeout: 10000, actions: [ { label: 'Dismiss', color: 'white', }, ], }); return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, FETCH_DEMO_LOGIN_CREDENTIALS() { return new Promise(async (resolve, reject) => { await $httpNoAuth .get('/auth/demo-login-credentials') .then((res: LoginHttpResponse & HttpResponse) => { return resolve(res.data.data); }) .catch((error: HttpError) => { return reject(error); }); }); }, }; export default actions;
the_stack
import React from 'react'; import client from "js/slycat-web-client"; /** * this class sets up and tests a remote session to an agent */ export default class SmbAuthentication extends React.Component<any,any> { /** *Creates an instance of SlycatRemoteControls. * @param {callBack, ConnectButton} props, * callback: function * where hostname, username, password, and session exist are return to the callee * every time the hostname is changed. session exist should always be checked before * moving on in in your logic structure. * connectButton: bool tells UI to include connect * @memberof SmbAuthentication */ constructor(props) { super(props); const display = this.populateDisplay(); this.state = { remote_hosts: [], hostname: display.hostname?display.hostname:null, username: display.username?display.username:null, session_exists: null, password: "", share: display.share?display.share:null, hostnames : [], loadingData: this.props.loadingData, initialLoad: false, smb_info: this.props.smb_info }; } private poll; /** * function used to test if we have an ssh connection to the hostname * @param {hostname} * @memberof SmbAuthentication */ checkRemoteStatus = async (hostname) => { return client.get_remotes_fetch(hostname) .then((json) => { this.setState({ session_exists:json.status && (json.share===this.state.share), initialLoad:true, loadingData:false }, () => { this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); }); }).catch(response => { this.setState({ session_exists: false, initialLoad:true, loadingData:false }, () => { this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); }); }); }; /** * takes a string value and encodes it to b64 * @param str string to be encode * @returns encoded result */ b64EncodeUnicode = (str) => { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); })); }; /** * gets a list of all the known remote hosts that we can connect to * via ssh * * @memberof SmbAuthentication */ getRemoteHosts = async () => { return client.get_configuration_smb_remote_hosts_fetch() .then((json)=>{ console.log(json.hostnames); this.setState({hostnames:json.hostnames}); }) }; async componentDidMount(){ await this.checkRemoteStatus(this.state.hostname); await this.getRemoteHosts(); if(this.poll){ clearInterval(this.poll); } this.poll = setInterval( async () => await this.checkRemoteStatus(this.state.hostname), 5000 ); } /** * checks local browser storage for the last used hostname and username * * @memberof SmbAuthentication */ populateDisplay = ():any => { const display:any = {}; if(!this.props.hover) { if(localStorage.getItem("slycat-smb-remote-controls-hostname")){ display.hostname = localStorage.getItem("slycat-smb-remote-controls-hostname") ? localStorage.getItem("slycat-smb-remote-controls-hostname"):null; } if(localStorage.getItem("slycat-smb-remote-controls-username")){ display.username = localStorage.getItem("slycat-smb-remote-controls-username") ? localStorage.getItem("slycat-smb-remote-controls-username"):null; } if(localStorage.getItem("slycat-smb-remote-controls-share")){ display.share = localStorage.getItem("slycat-smb-remote-controls-share") ? localStorage.getItem("slycat-smb-remote-controls-share"):null; } } else { display.hostname = this.props.smb_info["hostname"]; display.share = this.props.smb_info["collab"]; } return display; }; /** * updates local storage and react state depending on which input * is being typed in * * @memberof SmbAuthentication */ onValueChange = (value, type) => { switch(type) { case "share": localStorage.setItem("slycat-smb-remote-controls-share", value); this.setState({share: value},() => { this.checkRemoteStatus(this.state.hostname); this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); }); break; case "username": localStorage.setItem("slycat-smb-remote-controls-username", value); this.setState({username: value},() => { this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); }); break; case "hostname": localStorage.setItem("slycat-smb-remote-controls-hostname", value); this.checkRemoteStatus(value); this.setState({hostname: value},() => { this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); }); break; case "password": this.setState({password: value},() => { this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); }); break; default: throw new Error("bad Case"); } }; /** * cleanup state on unmounting */ cleanup() { clearInterval(this.poll); const display = this.populateDisplay(); const state = { remote_hosts: [], enable: true, hostname: display.hostname?display.hostname:null, username: display.username?display.username:null, session_exists: false, password: null, initialLoad: false }; this.setState(state); } /** * cleanup for when the component is unmounted * * @memberof SmbAuthentication */ componentWillUnmount() { this.cleanup(); window.removeEventListener('beforeunload', this.cleanup); } /** * if the 'enter key' is pressed try and connect to * the input hostname * * @memberof SmbAuthentication */ handleKeyDown = (e) => { if (e.key === 'Enter') { this.props.callBack(this.state.hostname, this.b64EncodeUnicode(this.state.username), this.b64EncodeUnicode(this.state.password), this.state.share, this.state.session_exists); } } /** * creates JSX form input if a session does not already exist for the given hostname * * @memberof SmbAuthentication */ getFormInputsJSX = () => { return ( <div> <div className='form-group row mb-3'> <label className='col-sm-2 col-form-label'>Share Name</label> <div className='col-sm-9'> <input disabled={this.props.loadingData} className='form-control' type='text' value={this.state.share?this.state.share:""} onChange={(e)=>this.onValueChange(e.target.value, "share")} /> </div> </div> <div className='form-group row mb-3'> <label className='col-sm-2 col-form-label'>Username</label> <div className='col-sm-9'> <input disabled={this.props.loadingData} className='form-control' type='text' value={this.state.username?this.state.username:""} onChange={(e)=>this.onValueChange(e.target.value, "username")} /> </div> </div> {!this.state.session_exists&&(<div className='form-group row mb-3'> <label className='col-sm-2 col-form-label'>Password</label> <div className='col-sm-9'> <input disabled={this.props.loadingData} className='form-control' type='password' onKeyDown={this.handleKeyDown} onChange={(e)=>this.onValueChange(e.target.value, "password")} /> </div> </div>)} </div> ); } /** * maps the hostnames as dropdowns items JSX * * @memberof SmbAuthentication */ getHostnamesJSX = () => { const hostnamesJSX = this.state.hostnames.map((hostname, i) => { return ( <li key={i}> <a className='dropdown-item' onClick={(e:any)=>this.onValueChange(e.target.text, "hostname")}> {hostname} </a> </li> ) }); return hostnamesJSX; } /** * JSX for SlycatRemoteControls * * @returns JSX for rendering the component * @memberof SmbAuthentication */ render() { //make sure our data is loaded before we render if(!this.state.initialLoad){ return (<div />) } return ( <form> <div className='form-group row mb-3'> <label className='col-sm-2 col-form-label'>Hostname</label> <div className='col-sm-9'> <div className='input-group'> <div className='input-group-prepend'> <button className='btn btn-secondary dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false' /> <ul className='dropdown-menu' aria-labelledby='dropdownMenuButton'> {this.getHostnamesJSX()} </ul> </div> <input className='form-control' value={this.state.hostname?this.state.hostname:""} type='text' onChange={(e)=>this.onValueChange(e.target.value, "hostname")} /> </div> </div> </div> {this.getFormInputsJSX()} </form> ); } }
the_stack
declare module '*.json' { const content: Record<string, unknown> export default content } interface IPoint { x: number y: number } /** Namespace for blueprint string interfaces */ declare namespace BPS { interface IColor { r: number g: number b: number a: number } type SignalType = 'item' | 'virtual' | 'fluid' interface ISignal { name: string type: SignalType } interface ICondition { comparator?: '<' | '>' | '≤' | '≥' | '=' | '≠' constant?: number first_signal?: ISignal second_signal?: ISignal } interface IFilter { index: number name: string } interface IWireColor { /** Entity number */ entity_id: number /** Entity side (1 or 2) for red or green wires */ circuit_id?: number /** Entity side (0 or 1) for copper wires */ wire_id?: number } interface IConnSide extends Record<string, IWireColor[]> { red?: IWireColor[] green?: IWireColor[] copper?: IWireColor[] } interface IConnection extends Record<string, IConnSide | IWireColor[]> { 1?: IConnSide 2?: IConnSide Cu0?: IWireColor[] Cu1?: IWireColor[] } interface IConstantCombinatorFilter { index: number count: number signal: ISignal } interface IDeciderCondition { comparator?: string constant?: number copy_count_from_input?: boolean first_signal?: ISignal second_signal?: ISignal output_signal?: ISignal } interface IArithmeticCondition { operation?: '+' | '-' | '*' | '/' | '%' | '^' | '<<' | '>>' | 'AND' | 'OR' | 'XOR' constant?: number first_constant?: number second_constant?: number first_signal?: ISignal second_signal?: ISignal output_signal?: ISignal } interface IEntity { entity_number: number name: string position: IPoint /** direction, can be ommited if 0 */ direction?: number // 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 /** direction type, only present if entity is of type underground-belt */ type?: 'input' | 'output' /** recipe name, only present if entity is of type assembling-machine or has fixed_recipe */ recipe?: string /** inventory size limitation, only present if entity has inventory_size */ bar?: number /** * keys are item names and value nr of items, only present if entity is locomotive or has module_specification * for the locomotive it represents fuel and for an eintity with module_specification it represents modules */ items?: Record<string, number> /** splitter input priority, only present if entity is of type splitter */ input_priority?: 'left' | 'right' /** splitter input priority, only present if entity is of type splitter */ output_priority?: 'left' | 'right' /** splitter filter for output priority, only present if entity is of type splitter */ filter?: string /** train stop station name, only present if entity is train-stop */ station?: string /** trains limit, only present if entity is train-stop */ manual_trains_limit?: number /** only present if entity is locomotive or train-stop */ color?: IColor /** only present if entity is locomotive, cargo_wagon or fluid_wagon */ orientation?: number /** only present if entity is cargo_wagon */ inventory?: { filters: IFilter[] } /** only present if entity is power-switch */ switch_state?: boolean /** auto launch, only present if entity is rocket-silo */ auto_launch?: boolean /** override stack size, only present if entity is of type inserter */ override_stack_size?: number /** only present if entity is logistic-chest-requester */ request_from_buffers?: boolean /** only present if entity is filter-inserter or stack-filter-inserter */ filter_mode?: 'blacklist' /** only present if entity is filter-inserter, stack-filter-inserter or of type loader */ filters?: IFilter[] /** only present if entity is logistic-chest-storage, logistic-chest-buffer or logistic-chest-requester */ request_filters?: { index: number name: string count?: number }[] /** only present if entity is programmable-speaker */ alert_parameters?: { alert_message?: string icon_signal_id?: ISignal show_alert?: boolean show_on_map?: boolean } /** only present if entity is programmable-speaker */ parameters?: { playback_volume?: number playback_globally?: boolean allow_polyphony?: boolean } /** only present if entity is electric_energy_interface */ buffer_size?: number /** only present if entity is electric_energy_interface */ power_production?: number /** only present if entity is electric_energy_interface */ power_usage?: number /** only present if entity is heat_interface */ mode?: 'at_least' | 'at_most' | 'exactly' /** only present if entity is heat_interface */ temperature?: number /** only present if entity is infinity_chest or infinity_pipe */ infinity_settings?: { /** only present if entity is infinity_pipe */ name?: string /** only present if entity is infinity_pipe */ mode?: 'at_least' | 'at_most' | 'exactly' /** only present if entity is infinity_pipe */ percentage?: number /** only present if entity is infinity_pipe */ temperature?: number /** only present if entity is infinity_chest */ filters?: { name: string mode: 'at_least' | 'at_most' | 'exactly' index: number count: number }[] /** only present if entity is infinity_chest */ remove_unfiltered_items?: boolean } /** power pole wire connections */ neighbours?: number[] /** wire connections */ connections?: IConnection control_behavior?: { /** only present if entity is constant-combinator */ is_on?: boolean /** only present if entity is constant-combinator */ filters?: IConstantCombinatorFilter[] /** only present if entity is small-lamp */ use_colors?: boolean /** only present if entity is of type mining-drill or transport-belt or train-stop */ circuit_enable_disable?: boolean /** only present if entity is of type inserter or transport-belt */ circuit_read_hand_contents?: boolean /** 0 = pulse, 1 = hold, only present if entity is of type inserter and circuit_read_hand_contents is true */ circuit_hand_read_mode?: 0 | 1 /** only present if entity is of type inserter and override_stack_size is not set */ circuit_set_stack_size?: boolean stack_control_input_signal?: ISignal /** 0 = pulse, 1 = hold, only present if entity is of type transport-belt and circuit_read_hand_contents is true */ circuit_contents_read_mode?: 0 | 1 /** only present if entity is roboport or logistic-chest-buffer or logistic-chest-requester or of type inserter(3)???????????????? */ circuit_mode_of_operation?: number available_logistic_output_signal?: ISignal total_logistic_output_signal?: ISignal available_construction_output_signal?: ISignal total_construction_output_signal?: ISignal /** only present if entity is of type mining-drill */ circuit_read_resources?: boolean /** only present if entity is burner-mining-drill or electric-mining-drill and circuit_read_resources is true */ circuit_resource_read_mode?: 0 | 1 /** only present if entity is stone-wall */ circuit_open_gate?: boolean /** only present if entity is stone-wall */ circuit_read_sensor?: boolean /** only present if entity is train-stop */ send_to_train?: boolean /** only present if entity is train-stop */ read_from_train?: boolean /** only present if entity is train-stop */ read_stopped_train?: boolean /** only present if entity is train-stop */ train_stopped_signal?: ISignal /** only present if entity is train-stop */ set_trains_limit?: boolean /** only present if entity is train-stop */ trains_limit_signal?: ISignal /** only present if entity is train-stop */ read_trains_count?: boolean /** only present if entity is train-stop */ trains_count_signal?: ISignal /** only present if entity is rail-signal */ circuit_close_signal?: boolean /** only present if entity is rail-signal, for chain signals: you have the same signals */ circuit_read_signal?: boolean red_output_signal?: ISignal orange_output_signal?: ISignal green_output_signal?: ISignal blue_output_signal?: ISignal /** only present if entity is stone-wall or accumulator */ output_signal?: ISignal /** only present if entity is programmable-speaker */ circuit_parameters?: { instrument_id?: number note_id?: number signal_value_is_pitch?: boolean } /** only present if entity is decider-combinator */ decider_conditions?: IDeciderCondition /** only present if entity is arithmetic-combinator */ arithmetic_conditions?: IArithmeticCondition /** * only present if entity is pump, offshore-pump, rail-signal, train-stop, small-lamp, * power-switch, stone-wall, programmable-speaker or of type: inserter, transport-belt or mining-drill */ circuit_condition?: ICondition /** * only present if entity is pump, offshore-pump, train-stop, small-lamp, power-switch * or of type: inserter, transport-belt or mining-drill */ connect_to_logistic_network?: boolean /** * only present if entity is pump, offshore-pump, train-stop, small-lamp, power-switch * or of type: inserter, transport-belt or mining-drill */ logistic_condition?: ICondition } } interface ITile { name: string position: IPoint } interface ISchedule { locomotives: number[] schedule: { station: string wait_conditions: { compare_type: 'and' | 'or' type: | 'time' | 'inactivity' | 'full' | 'empty' | 'item_count' | 'fluid_count' | 'circuit' | 'passenger_present' | 'passenger_not_present' ticks?: number condition?: ICondition }[] }[] } interface IIcon { index: 1 | 2 | 3 | 4 signal: ISignal } interface IBlueprint { version: number item: 'blueprint' icons: IIcon[] label?: string description?: string entities?: IEntity[] tiles?: ITile[] schedules?: ISchedule[] absolute_snapping?: boolean snap_to_grid?: IPoint position_relative_to_grid?: IPoint } interface IBlueprintBookEntry { index: number blueprint?: IBlueprint blueprint_book?: IBlueprintBook upgrade_planner?: Record<string, unknown> deconstruction_planner?: Record<string, unknown> } interface IBlueprintBook { version: number item: 'blueprint_book' active_index: number blueprints?: IBlueprintBookEntry[] label?: string description?: string icons?: IIcon[] } }
the_stack
var glValidEnumContexts = { // Generic setters and getters enable: {1: {0: true}}, disable: {1: {0: true}}, getParameter: {1: {0: true}}, // Rendering drawArrays: {3: {0: true}}, drawElements: {4: {0: true, 2: true}}, // Shaders createShader: {1: {0: true}}, getShaderParameter: {2: {1: true}}, getProgramParameter: {2: {1: true}}, getShaderPrecisionFormat: {2: {0: true, 1: true}}, // Vertex attributes getVertexAttrib: {2: {1: true}}, vertexAttribPointer: {6: {2: true}}, // Textures bindTexture: {2: {0: true}}, activeTexture: {1: {0: true}}, getTexParameter: {2: {0: true, 1: true}}, texParameterf: {3: {0: true, 1: true}}, texParameteri: {3: {0: true, 1: true, 2: true}}, // texImage2D and texSubImage2D are defined below with WebGL 2 entrypoints copyTexImage2D: {8: {0: true, 2: true}}, copyTexSubImage2D: {8: {0: true}}, generateMipmap: {1: {0: true}}, // compressedTexImage2D and compressedTexSubImage2D are defined below with WebGL 2 entrypoints // Buffer objects bindBuffer: {2: {0: true}}, // bufferData and bufferSubData are defined below with WebGL 2 entrypoints getBufferParameter: {2: {0: true, 1: true}}, // Renderbuffers and framebuffers pixelStorei: {2: {0: true, 1: true}}, // readPixels is defined below with WebGL 2 entrypoints bindRenderbuffer: {2: {0: true}}, bindFramebuffer: {2: {0: true}}, checkFramebufferStatus: {1: {0: true}}, framebufferRenderbuffer: {4: {0: true, 1: true, 2: true}}, framebufferTexture2D: {5: {0: true, 1: true, 2: true}}, getFramebufferAttachmentParameter: {3: {0: true, 1: true, 2: true}}, getRenderbufferParameter: {2: {0: true, 1: true}}, renderbufferStorage: {4: {0: true, 1: true}}, // Frame buffer operations (clear, blend, depth test, stencil) clear: {1: {0: {enumBitwiseOr: ['COLOR_BUFFER_BIT', 'DEPTH_BUFFER_BIT', 'STENCIL_BUFFER_BIT']}}}, depthFunc: {1: {0: true}}, blendFunc: {2: {0: true, 1: true}}, blendFuncSeparate: {4: {0: true, 1: true, 2: true, 3: true}}, blendEquation: {1: {0: true}}, blendEquationSeparate: {2: {0: true, 1: true}}, stencilFunc: {3: {0: true}}, stencilFuncSeparate: {4: {0: true, 1: true}}, stencilMaskSeparate: {2: {0: true}}, stencilOp: {3: {0: true, 1: true, 2: true}}, stencilOpSeparate: {4: {0: true, 1: true, 2: true, 3: true}}, // Culling cullFace: {1: {0: true}}, frontFace: {1: {0: true}}, // ANGLE_instanced_arrays extension drawArraysInstancedANGLE: {4: {0: true}}, drawElementsInstancedANGLE: {5: {0: true, 2: true}}, // EXT_blend_minmax extension blendEquationEXT: {1: {0: true}}, // WebGL 2 Buffer objects bufferData: { 3: {0: true, 2: true}, // WebGL 1 4: {0: true, 2: true}, // WebGL 2 5: {0: true, 2: true} // WebGL 2 }, bufferSubData: { 3: {0: true}, // WebGL 1 4: {0: true}, // WebGL 2 5: {0: true} // WebGL 2 }, copyBufferSubData: {5: {0: true, 1: true}}, getBufferSubData: {3: {0: true}, 4: {0: true}, 5: {0: true}}, // WebGL 2 Framebuffer objects blitFramebuffer: { 10: { 8: {enumBitwiseOr: ['COLOR_BUFFER_BIT', 'DEPTH_BUFFER_BIT', 'STENCIL_BUFFER_BIT']}, 9: true } }, framebufferTextureLayer: {5: {0: true, 1: true}}, invalidateFramebuffer: {2: {0: true}}, invalidateSubFramebuffer: {6: {0: true}}, readBuffer: {1: {0: true}}, // WebGL 2 Renderbuffer objects getInternalformatParameter: {3: {0: true, 1: true, 2: true}}, renderbufferStorageMultisample: {5: {0: true, 2: true}}, // WebGL 2 Texture objects texStorage2D: {5: {0: true, 2: true}}, texStorage3D: {6: {0: true, 2: true}}, texImage2D: { 9: {0: true, 2: true, 6: true, 7: true}, // WebGL 1 & 2 6: {0: true, 2: true, 3: true, 4: true}, // WebGL 1 10: {0: true, 2: true, 6: true, 7: true} // WebGL 2 }, texImage3D: { 10: {0: true, 2: true, 7: true, 8: true}, 11: {0: true, 2: true, 7: true, 8: true} }, texSubImage2D: { 9: {0: true, 6: true, 7: true}, // WebGL 1 & 2 7: {0: true, 4: true, 5: true}, // WebGL 1 10: {0: true, 6: true, 7: true} // WebGL 2 }, texSubImage3D: { 11: {0: true, 8: true, 9: true}, 12: {0: true, 8: true, 9: true} }, copyTexSubImage3D: {9: {0: true}}, compressedTexImage2D: { 7: {0: true, 2: true}, // WebGL 1 & 2 8: {0: true, 2: true}, // WebGL 2 9: {0: true, 2: true} // WebGL 2 }, compressedTexImage3D: { 8: {0: true, 2: true}, 9: {0: true, 2: true}, 10: {0: true, 2: true} }, compressedTexSubImage2D: { 8: {0: true, 6: true}, // WebGL 1 & 2 9: {0: true, 6: true}, // WebGL 2 10: {0: true, 6: true} // WebGL 2 }, compressedTexSubImage3D: { 10: {0: true, 8: true}, 11: {0: true, 8: true}, 12: {0: true, 8: true} }, // WebGL 2 Vertex attribs vertexAttribIPointer: {5: {2: true}}, // WebGL 2 Writing to the drawing buffer drawArraysInstanced: {4: {0: true}}, drawElementsInstanced: {5: {0: true, 2: true}}, drawRangeElements: {6: {0: true, 4: true}}, // WebGL 2 Reading back pixels readPixels: { 7: {4: true, 5: true}, // WebGL 1 & 2 8: {4: true, 5: true} // WebGL 2 }, // WebGL 2 Multiple Render Targets clearBufferfv: {3: {0: true}, 4: {0: true}}, clearBufferiv: {3: {0: true}, 4: {0: true}}, clearBufferuiv: {3: {0: true}, 4: {0: true}}, clearBufferfi: {4: {0: true}}, // WebGL 2 Query objects beginQuery: {2: {0: true}}, endQuery: {1: {0: true}}, getQuery: {2: {0: true, 1: true}}, getQueryParameter: {2: {1: true}}, // WebGL 2 Sampler objects samplerParameteri: {3: {1: true, 2: true}}, samplerParameterf: {3: {1: true}}, getSamplerParameter: {2: {1: true}}, // WebGL 2 Sync objects fenceSync: {2: {0: true, 1: {enumBitwiseOr: []}}}, clientWaitSync: {3: {1: {enumBitwiseOr: ['SYNC_FLUSH_COMMANDS_BIT']}}}, waitSync: {3: {1: {enumBitwiseOr: []}}}, getSyncParameter: {2: {1: true}}, // WebGL 2 Transform Feedback bindTransformFeedback: {2: {0: true}}, beginTransformFeedback: {1: {0: true}}, transformFeedbackVaryings: {3: {2: true}}, // WebGL2 Uniform Buffer Objects and Transform Feedback Buffers bindBufferBase: {3: {0: true}}, bindBufferRange: {5: {0: true}}, getIndexedParameter: {2: {0: true}}, getActiveUniforms: {3: {2: true}}, getActiveUniformBlockParameter: {3: {2: true}} }; /** Map of numbers to names. */ var glEnums: Record<number, string> = null; /** Map of names to numbers. */ var enumStringToValue: Record<string, number> = null; /** * Initializes this module. Safe to call more than once. * @param ctx A WebGL context. If * you have more than one context it doesn't matter which one * you pass in, it is only used to pull out constants. */ export function init(ctx: WebGLRenderingContext): void { if (glEnums == null) { glEnums = {}; enumStringToValue = {}; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'number') { glEnums[ctx[propertyName]] = propertyName; enumStringToValue[propertyName] = ctx[propertyName]; } } } } /** * Checks the utils have been initialized. */ function checkInit() { if (glEnums == null) { throw 'WebGLDebugUtils.init(ctx) not called'; } } /** * Returns true or false if value matches any WebGL enum * @param value Value to check if it might be an enum. * @return True if value matches one of the WebGL defined enums */ export function mightBeEnum(value: any): boolean { checkInit(); return glEnums[value] !== undefined; } /** * Gets an string version of an WebGL enum. * * @example * WebGLDebugUtil.init(ctx); * var str = WebGLDebugUtil.glEnumToString(ctx.getError()); * * @param value Value to return an enum for * @return The string version of the enum. */ export function glEnumToString(value: number): string { checkInit(); var name = glEnums[value]; return name !== undefined ? 'gl.' + name : '/*UNKNOWN WebGL ENUM*/ 0x' + value.toString(16) + ''; } /** * Converts the argument of a WebGL function to a string. * Attempts to convert enum arguments to strings. * * @example * WebGLDebugUtil.init(ctx); * var str = WebGLDebugUtil.glFunctionArgToString('bindTexture', 2, 0, gl.TEXTURE_2D); * * would return 'TEXTURE_2D' * * @param functionName the name of the WebGL function. * @param numArgs the number of arguments passed to the function. * @param argumentIndx the index of the argument. * @param value The value of the argument. * @return The value as a string. */ export function glFunctionArgToString( functionName: string, numArgs: number, argumentIndex: number, value: any ): string { var funcInfo = glValidEnumContexts[functionName]; if (funcInfo !== undefined) { var funcInfo = funcInfo[numArgs]; if (funcInfo !== undefined) { if (funcInfo[argumentIndex]) { if ( typeof funcInfo[argumentIndex] === 'object' && funcInfo[argumentIndex]['enumBitwiseOr'] !== undefined ) { var enums = funcInfo[argumentIndex]['enumBitwiseOr']; var orResult = 0; var orEnums = []; for (var i = 0; i < enums.length; ++i) { var enumValue = enumStringToValue[enums[i]]; if ((value & enumValue) !== 0) { orResult |= enumValue; orEnums.push(glEnumToString(enumValue)); } } if (orResult === value) { return orEnums.join(' | '); } else { return glEnumToString(value); } } else { return glEnumToString(value); } } } } if (value === null) { return 'null'; } else if (value === undefined) { return 'undefined'; } else { return value.toString(); } } /** * Converts the arguments of a WebGL function to a string. * Attempts to convert enum arguments to strings. * * @param functionName the name of the WebGL function. * @param args The arguments. * @return The arguments as a string. */ export function glFunctionArgsToString(functionName: string, args): string { // apparently we can't do args.join(","); var argStr = ''; var numArgs = args.length; for (var ii = 0; ii < numArgs; ++ii) { argStr += (ii == 0 ? '' : ', ') + glFunctionArgToString(functionName, numArgs, ii, args[ii]); } return argStr; } // Internal export for context-loss export function makePropertyWrapper(wrapper, original, propertyName) { //log("wrap prop: " + propertyName); wrapper.__defineGetter__(propertyName, function () { return original[propertyName]; }); // TODO(gmane): this needs to handle properties that take more than // one value? wrapper.__defineSetter__(propertyName, function (value) { //log("set: " + propertyName); original[propertyName] = value; }); } // Makes a function that calls a function on another object. function makeFunctionWrapper(original, functionName) { //log("wrap fn: " + functionName); var f = original[functionName]; return function () { //log("call: " + functionName); var result = f.apply(original, arguments); return result; }; } /** * Given a WebGL context returns a wrapped context that calls * gl.getError after every command and calls a function if the * result is not NO_ERROR. * * You can supply your own function if you want. For example, if you'd like * an exception thrown on any GL error you could do this * * @example * * function throwOnGLError(err, funcName, args) { * throw WebGLDebugUtils.glEnumToString(err) + * " was caused by call to " + funcName; * }; * * ctx = WebGLDebugUtils.makeDebugContext( * canvas.getContext("webgl"), throwOnGLError); * * @param {!WebGLRenderingContext} ctx The webgl context to wrap. * @param {!function(err, funcName, args): void} opt_onErrorFunc * The function to call when gl.getError returns an * error. If not specified the default function calls * console.log with a message. * @param {!function(funcName, args): void} opt_onFunc The * function to call when each webgl function is called. * You can use this to log all calls for example. * @param {!WebGLRenderingContext} opt_err_ctx The webgl context * to call getError on if different than ctx. */ export function makeDebugContext(ctx, opt_onErrorFunc, opt_onFunc, opt_err_ctx) { opt_err_ctx = opt_err_ctx || ctx; init(ctx); opt_onErrorFunc = opt_onErrorFunc || function (err, functionName, args) { // apparently we can't do args.join(","); var argStr = ''; var numArgs = args.length; for (var ii = 0; ii < numArgs; ++ii) { argStr += (ii == 0 ? '' : ', ') + glFunctionArgToString(functionName, numArgs, ii, args[ii]); } // error err('WebGL error ' + glEnumToString(err) + ' in ' + functionName + '(' + argStr + ')'); }; // Holds booleans for each GL error so after we get the error ourselves // we can still return it to the client app. var glErrorShadow = {}; // Makes a function that calls a WebGL function and then calls getError. function makeErrorWrapper(ctx, functionName) { return function () { if (opt_onFunc) { opt_onFunc(functionName, arguments); } var result = ctx[functionName].apply(ctx, arguments); var err = opt_err_ctx.getError(); if (err != 0) { glErrorShadow[err] = true; opt_onErrorFunc(err, functionName, arguments); } return result; }; } // Make a an object that has a copy of every property of the WebGL context // but wraps all functions. var wrapper = {}; for (var propertyName in ctx) { if (typeof ctx[propertyName] == 'function') { if (propertyName != 'getExtension') { wrapper[propertyName] = makeErrorWrapper(ctx, propertyName); } else { var wrapped = makeErrorWrapper(ctx, propertyName); wrapper[propertyName] = function () { var result = wrapped.apply(ctx, arguments); if (!result) { return null; } return makeDebugContext(result, opt_onErrorFunc, opt_onFunc, opt_err_ctx); }; } } else { makePropertyWrapper(wrapper, ctx, propertyName); } } // @ts-expect-error Override the getError function with one that returns our saved results. wrapper.getError = function () { for (var err in glErrorShadow) { if (glErrorShadow.hasOwnProperty(err)) { if (glErrorShadow[err]) { glErrorShadow[err] = false; return err; } } } return ctx.NO_ERROR; }; return wrapper; }
the_stack
import { RequestParameters } from "@azure-rest/core-client"; export type PathsGetBooleanTrueParameters = RequestParameters; export type PathsGetBooleanFalseParameters = RequestParameters; export type PathsGetIntOneMillionParameters = RequestParameters; export type PathsGetIntNegativeOneMillionParameters = RequestParameters; export type PathsGetTenBillionParameters = RequestParameters; export type PathsGetNegativeTenBillionParameters = RequestParameters; export type PathsFloatScientificPositiveParameters = RequestParameters; export type PathsFloatScientificNegativeParameters = RequestParameters; export type PathsDoubleDecimalPositiveParameters = RequestParameters; export type PathsDoubleDecimalNegativeParameters = RequestParameters; export type PathsStringUnicodeParameters = RequestParameters; export type PathsStringUrlEncodedParameters = RequestParameters; export type PathsStringUrlNonEncodedParameters = RequestParameters; export type PathsStringEmptyParameters = RequestParameters; export type PathsStringNullParameters = RequestParameters; export type PathsEnumValidParameters = RequestParameters; export type PathsEnumNullParameters = RequestParameters; export type PathsByteMultiByteParameters = RequestParameters; export type PathsByteEmptyParameters = RequestParameters; export type PathsByteNullParameters = RequestParameters; export type PathsDateValidParameters = RequestParameters; export type PathsDateNullParameters = RequestParameters; export type PathsDateTimeValidParameters = RequestParameters; export type PathsDateTimeNullParameters = RequestParameters; export type PathsBase64UrlParameters = RequestParameters; export type PathsArrayCsvInPathParameters = RequestParameters; export type PathsUnixTimeUrlParameters = RequestParameters; export interface QueriesGetBooleanTrueQueryParamProperties { /** true boolean value */ boolQuery: true; } export interface QueriesGetBooleanTrueQueryParam { queryParameters: QueriesGetBooleanTrueQueryParamProperties; } export type QueriesGetBooleanTrueParameters = QueriesGetBooleanTrueQueryParam & RequestParameters; export interface QueriesGetBooleanFalseQueryParamProperties { /** false boolean value */ boolQuery: false; } export interface QueriesGetBooleanFalseQueryParam { queryParameters: QueriesGetBooleanFalseQueryParamProperties; } export type QueriesGetBooleanFalseParameters = QueriesGetBooleanFalseQueryParam & RequestParameters; export interface QueriesGetBooleanNullQueryParamProperties { /** null boolean value */ boolQuery?: boolean; } export interface QueriesGetBooleanNullQueryParam { queryParameters?: QueriesGetBooleanNullQueryParamProperties; } export type QueriesGetBooleanNullParameters = QueriesGetBooleanNullQueryParam & RequestParameters; export interface QueriesGetIntOneMillionQueryParamProperties { /** '1000000' integer value */ intQuery: 1000000; } export interface QueriesGetIntOneMillionQueryParam { queryParameters: QueriesGetIntOneMillionQueryParamProperties; } export type QueriesGetIntOneMillionParameters = QueriesGetIntOneMillionQueryParam & RequestParameters; export interface QueriesGetIntNegativeOneMillionQueryParamProperties { /** '-1000000' integer value */ intQuery: -1000000; } export interface QueriesGetIntNegativeOneMillionQueryParam { queryParameters: QueriesGetIntNegativeOneMillionQueryParamProperties; } export type QueriesGetIntNegativeOneMillionParameters = QueriesGetIntNegativeOneMillionQueryParam & RequestParameters; export interface QueriesGetIntNullQueryParamProperties { /** null integer value */ intQuery?: number; } export interface QueriesGetIntNullQueryParam { queryParameters?: QueriesGetIntNullQueryParamProperties; } export type QueriesGetIntNullParameters = QueriesGetIntNullQueryParam & RequestParameters; export interface QueriesGetTenBillionQueryParamProperties { /** '10000000000' 64 bit integer value */ longQuery: 10000000000; } export interface QueriesGetTenBillionQueryParam { queryParameters: QueriesGetTenBillionQueryParamProperties; } export type QueriesGetTenBillionParameters = QueriesGetTenBillionQueryParam & RequestParameters; export interface QueriesGetNegativeTenBillionQueryParamProperties { /** '-10000000000' 64 bit integer value */ longQuery: -10000000000; } export interface QueriesGetNegativeTenBillionQueryParam { queryParameters: QueriesGetNegativeTenBillionQueryParamProperties; } export type QueriesGetNegativeTenBillionParameters = QueriesGetNegativeTenBillionQueryParam & RequestParameters; export interface QueriesGetLongNullQueryParamProperties { /** null 64 bit integer value */ longQuery?: number; } export interface QueriesGetLongNullQueryParam { queryParameters?: QueriesGetLongNullQueryParamProperties; } export type QueriesGetLongNullParameters = QueriesGetLongNullQueryParam & RequestParameters; export interface QueriesFloatScientificPositiveQueryParamProperties { /** '1.034E+20'numeric value */ floatQuery: 103400000000000000000; } export interface QueriesFloatScientificPositiveQueryParam { queryParameters: QueriesFloatScientificPositiveQueryParamProperties; } export type QueriesFloatScientificPositiveParameters = QueriesFloatScientificPositiveQueryParam & RequestParameters; export interface QueriesFloatScientificNegativeQueryParamProperties { /** '-1.034E-20'numeric value */ floatQuery: -1.034e-20; } export interface QueriesFloatScientificNegativeQueryParam { queryParameters: QueriesFloatScientificNegativeQueryParamProperties; } export type QueriesFloatScientificNegativeParameters = QueriesFloatScientificNegativeQueryParam & RequestParameters; export interface QueriesFloatNullQueryParamProperties { /** null numeric value */ floatQuery?: number; } export interface QueriesFloatNullQueryParam { queryParameters?: QueriesFloatNullQueryParamProperties; } export type QueriesFloatNullParameters = QueriesFloatNullQueryParam & RequestParameters; export interface QueriesDoubleDecimalPositiveQueryParamProperties { /** '9999999.999'numeric value */ doubleQuery: 9999999.999; } export interface QueriesDoubleDecimalPositiveQueryParam { queryParameters: QueriesDoubleDecimalPositiveQueryParamProperties; } export type QueriesDoubleDecimalPositiveParameters = QueriesDoubleDecimalPositiveQueryParam & RequestParameters; export interface QueriesDoubleDecimalNegativeQueryParamProperties { /** '-9999999.999'numeric value */ doubleQuery: -9999999.999; } export interface QueriesDoubleDecimalNegativeQueryParam { queryParameters: QueriesDoubleDecimalNegativeQueryParamProperties; } export type QueriesDoubleDecimalNegativeParameters = QueriesDoubleDecimalNegativeQueryParam & RequestParameters; export interface QueriesDoubleNullQueryParamProperties { /** null numeric value */ doubleQuery?: number; } export interface QueriesDoubleNullQueryParam { queryParameters?: QueriesDoubleNullQueryParamProperties; } export type QueriesDoubleNullParameters = QueriesDoubleNullQueryParam & RequestParameters; export interface QueriesStringUnicodeQueryParamProperties { /** '啊齄丂狛狜隣郎隣兀﨩'multi-byte string value */ stringQuery: "啊齄丂狛狜隣郎隣兀﨩"; } export interface QueriesStringUnicodeQueryParam { queryParameters: QueriesStringUnicodeQueryParamProperties; } export type QueriesStringUnicodeParameters = QueriesStringUnicodeQueryParam & RequestParameters; export interface QueriesStringUrlEncodedQueryParamProperties { /** 'begin!*'();:@ &=+$,/?#[]end' url encoded string value */ stringQuery: "begin!*'();:@ &=+$,/?#[]end"; } export interface QueriesStringUrlEncodedQueryParam { queryParameters: QueriesStringUrlEncodedQueryParamProperties; } export type QueriesStringUrlEncodedParameters = QueriesStringUrlEncodedQueryParam & RequestParameters; export interface QueriesStringEmptyQueryParamProperties { /** '' string value */ stringQuery: ""; } export interface QueriesStringEmptyQueryParam { queryParameters: QueriesStringEmptyQueryParamProperties; } export type QueriesStringEmptyParameters = QueriesStringEmptyQueryParam & RequestParameters; export interface QueriesStringNullQueryParamProperties { /** null string value */ stringQuery?: string; } export interface QueriesStringNullQueryParam { queryParameters?: QueriesStringNullQueryParamProperties; } export type QueriesStringNullParameters = QueriesStringNullQueryParam & RequestParameters; export interface QueriesEnumValidQueryParamProperties { /** 'green color' enum value */ enumQuery?: "red color" | "green color" | "blue color"; } export interface QueriesEnumValidQueryParam { queryParameters?: QueriesEnumValidQueryParamProperties; } export type QueriesEnumValidParameters = QueriesEnumValidQueryParam & RequestParameters; export interface QueriesEnumNullQueryParamProperties { /** null string value */ enumQuery?: "red color" | "green color" | "blue color"; } export interface QueriesEnumNullQueryParam { queryParameters?: QueriesEnumNullQueryParamProperties; } export type QueriesEnumNullParameters = QueriesEnumNullQueryParam & RequestParameters; export interface QueriesByteMultiByteQueryParamProperties { /** * '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array * * Value may contain base64 encoded characters */ byteQuery?: string; } export interface QueriesByteMultiByteQueryParam { queryParameters?: QueriesByteMultiByteQueryParamProperties; } export type QueriesByteMultiByteParameters = QueriesByteMultiByteQueryParam & RequestParameters; export interface QueriesByteEmptyQueryParamProperties { /** '' as byte array */ byteQuery: ""; } export interface QueriesByteEmptyQueryParam { queryParameters: QueriesByteEmptyQueryParamProperties; } export type QueriesByteEmptyParameters = QueriesByteEmptyQueryParam & RequestParameters; export interface QueriesByteNullQueryParamProperties { /** * null as byte array (no query parameters in uri) * * Value may contain base64 encoded characters */ byteQuery?: string; } export interface QueriesByteNullQueryParam { queryParameters?: QueriesByteNullQueryParamProperties; } export type QueriesByteNullParameters = QueriesByteNullQueryParam & RequestParameters; export interface QueriesDateValidQueryParamProperties { /** '2012-01-01' as date */ dateQuery: "2012-01-01"; } export interface QueriesDateValidQueryParam { queryParameters: QueriesDateValidQueryParamProperties; } export type QueriesDateValidParameters = QueriesDateValidQueryParam & RequestParameters; export interface QueriesDateNullQueryParamProperties { /** null as date (no query parameters in uri) */ dateQuery?: Date | string; } export interface QueriesDateNullQueryParam { queryParameters?: QueriesDateNullQueryParamProperties; } export type QueriesDateNullParameters = QueriesDateNullQueryParam & RequestParameters; export interface QueriesDateTimeValidQueryParamProperties { /** '2012-01-01T01:01:01Z' as date-time */ dateTimeQuery: "2012-01-01T01:01:01Z"; } export interface QueriesDateTimeValidQueryParam { queryParameters: QueriesDateTimeValidQueryParamProperties; } export type QueriesDateTimeValidParameters = QueriesDateTimeValidQueryParam & RequestParameters; export interface QueriesDateTimeNullQueryParamProperties { /** null as date-time (no query parameters) */ dateTimeQuery?: Date | string; } export interface QueriesDateTimeNullQueryParam { queryParameters?: QueriesDateTimeNullQueryParamProperties; } export type QueriesDateTimeNullParameters = QueriesDateTimeNullQueryParam & RequestParameters; export interface QueriesArrayStringCsvValidQueryParamProperties { /** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format */ arrayQuery?: Array<string>; } export interface QueriesArrayStringCsvValidQueryParam { queryParameters?: QueriesArrayStringCsvValidQueryParamProperties; } export type QueriesArrayStringCsvValidParameters = QueriesArrayStringCsvValidQueryParam & RequestParameters; export interface QueriesArrayStringCsvNullQueryParamProperties { /** a null array of string using the csv-array format */ arrayQuery?: Array<string>; } export interface QueriesArrayStringCsvNullQueryParam { queryParameters?: QueriesArrayStringCsvNullQueryParamProperties; } export type QueriesArrayStringCsvNullParameters = QueriesArrayStringCsvNullQueryParam & RequestParameters; export interface QueriesArrayStringCsvEmptyQueryParamProperties { /** an empty array [] of string using the csv-array format */ arrayQuery?: Array<string>; } export interface QueriesArrayStringCsvEmptyQueryParam { queryParameters?: QueriesArrayStringCsvEmptyQueryParamProperties; } export type QueriesArrayStringCsvEmptyParameters = QueriesArrayStringCsvEmptyQueryParam & RequestParameters; export interface QueriesArrayStringNoCollectionFormatEmptyQueryParamProperties { /** Array-typed query parameter. Pass in ['hello', 'nihao', 'bonjour']. */ arrayQuery?: Array<string>; } export interface QueriesArrayStringNoCollectionFormatEmptyQueryParam { queryParameters?: QueriesArrayStringNoCollectionFormatEmptyQueryParamProperties; } export type QueriesArrayStringNoCollectionFormatEmptyParameters = QueriesArrayStringNoCollectionFormatEmptyQueryParam & RequestParameters; export interface QueriesArrayStringSsvValidQueryParamProperties { /** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the ssv-array format */ arrayQuery?: Array<string>; } export interface QueriesArrayStringSsvValidQueryParam { queryParameters?: QueriesArrayStringSsvValidQueryParamProperties; } export type QueriesArrayStringSsvValidParameters = QueriesArrayStringSsvValidQueryParam & RequestParameters; export interface QueriesArrayStringTsvValidQueryParamProperties { /** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the tsv-array format */ arrayQuery?: Array<string>; } export interface QueriesArrayStringTsvValidQueryParam { queryParameters?: QueriesArrayStringTsvValidQueryParamProperties; } export type QueriesArrayStringTsvValidParameters = QueriesArrayStringTsvValidQueryParam & RequestParameters; export interface QueriesArrayStringPipesValidQueryParamProperties { /** an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the pipes-array format */ arrayQuery?: Array<string>; } export interface QueriesArrayStringPipesValidQueryParam { queryParameters?: QueriesArrayStringPipesValidQueryParamProperties; } export type QueriesArrayStringPipesValidParameters = QueriesArrayStringPipesValidQueryParam & RequestParameters; export interface PathItemsGetAllWithValuesQueryParamProperties { /** A string value 'pathItemStringQuery' that appears as a query parameter */ pathItemStringQuery?: string; /** should contain value 'localStringQuery' */ localStringQuery?: string; } export interface PathItemsGetAllWithValuesQueryParam { queryParameters?: PathItemsGetAllWithValuesQueryParamProperties; } export type PathItemsGetAllWithValuesParameters = PathItemsGetAllWithValuesQueryParam & RequestParameters; export interface PathItemsGetGlobalQueryNullQueryParamProperties { /** A string value 'pathItemStringQuery' that appears as a query parameter */ pathItemStringQuery?: string; /** should contain value 'localStringQuery' */ localStringQuery?: string; } export interface PathItemsGetGlobalQueryNullQueryParam { queryParameters?: PathItemsGetGlobalQueryNullQueryParamProperties; } export type PathItemsGetGlobalQueryNullParameters = PathItemsGetGlobalQueryNullQueryParam & RequestParameters; export interface PathItemsGetGlobalAndLocalQueryNullQueryParamProperties { /** A string value 'pathItemStringQuery' that appears as a query parameter */ pathItemStringQuery?: string; /** should contain null value */ localStringQuery?: string; } export interface PathItemsGetGlobalAndLocalQueryNullQueryParam { queryParameters?: PathItemsGetGlobalAndLocalQueryNullQueryParamProperties; } export type PathItemsGetGlobalAndLocalQueryNullParameters = PathItemsGetGlobalAndLocalQueryNullQueryParam & RequestParameters; export interface PathItemsGetLocalPathItemQueryNullQueryParamProperties { /** should contain value null */ pathItemStringQuery?: string; /** should contain value null */ localStringQuery?: string; } export interface PathItemsGetLocalPathItemQueryNullQueryParam { queryParameters?: PathItemsGetLocalPathItemQueryNullQueryParamProperties; } export type PathItemsGetLocalPathItemQueryNullParameters = PathItemsGetLocalPathItemQueryNullQueryParam & RequestParameters;
the_stack
export default { en: { // debug test_I18N: 'Test I18N', switch_theme: 'Switch theme', switch_device_status: 'Switch device status', switch_network_status: 'Switch network status', switch_bluetooth: 'Switch Bluetooth', switch_wifi: 'Switch Wifi', show_toolbox: 'Show toolbox', hide_toolbox: 'Hide toolbox', test_theme: 'Test theme configuration', // common text_title: 'Title', text_subTitle: 'Sub Title', text_confirm: 'Confirm', text_cancel: 'Cancel', text_basic: 'Basic Usage', style_basic: 'Basic Style', text_hour: 'hour', text_minute: 'minute', text_single: 'single selection', text_mul: 'multiple selection', power: 'power', // basic // battery battery: 'Battery', battery_power: 'Power {0}%', battery_power_cus: 'Power {0}%(custom theme)', battery_power_cus2: 'custom theme', battery_power_mod: 'Power {0}% (modify the electricity color distribution rules)', battery_power_mod2: 'Modify the power color assignment rule', // button button: 'Button', button_text: 'button', pure_text_button: 'Plain text button', pure_icon_button: 'Plain text button', with_text_icon_button: 'Text button with icon', text: 'text', click_me_once: 'Point me', // brick-button brick_button: 'BrickButton', brick_button_text: 'Text block button', brick_button_bg: 'Gradient background button', // icon-font iconfont: 'IconFont', iconfont_basic_use: 'Basic Usage', iconfont_color: 'Icon color', iconfont_size: 'Icon Size', // motion motion: 'Motion', motion_fade: 'fade in and fade out', motion_pullup: 'Pull up and down', motion_scalefadein: 'Zoom in and fade in/out', motion_scalefadeout: 'Zoom in and fade in/down to fade out', motion_pushdown: 'Pull-down push', motion_toast: 'No operation zoom in/out', // slider-progress slider_progress: 'SliderProgress', slider_progress_uni: 'Unilateral progress bar', slider_progress_bil: 'Bilateral progress bar', // tytext tytext: 'TYText', tytext_basic_style: 'Basic style', tytext_size_type: 'Use with size and type', unittext: 'UnitText', unittext_style: 'Basic style', unittext_size: 'Custom size', unittext_color: 'Customize the color of each value of UnitText', // data-entry // checkbox checkbox: 'Checkbox', checkbox_label: 'Checkbox', checkbox_basic: 'Basic Usage', checkbox_disable: 'Disable status', checkbox_color: 'Custom color and size', checkbox_position: 'Flip icon and child element position', // date-picker datepicker: 'DatePicker', datepicker_control: 'Controlled date picker', datepicker_uncontrol: 'Uncontrolled date picker', // picker-view pickerview: 'PickerView', pickerview_basic: 'Basic Usage', pickerview_mul: 'Multiple column selector', // slider slider: 'Slider', slider_basic: 'Horizontal slider - basic style', silder_horizontal_parcel: 'Horizontal parcel type slider', silder_horizontal_parcel_custom: 'Horizontal parcel custom thumb Slider', silder_horizontal_parcel_number: 'Horizontal package with graduated slider', silder_horizontal_number: 'Horizontal graduated slider', slider_custom: 'Horizontal slider - custom button', silder_vertical: 'Vertical slider', // slider_with_line slider_with_line: 'SliderWithLine', slider_with_line_horizontal: 'Slide the selector horizontally', slider_with_line_vertical: 'Slide the selector vertically', // stepper stepper: 'Stepper', stepper_style1: 'Style 1', stepper_style1_def: 'Default usage', stepper_style1_disable: 'Disable style', stepper_style1_point: 'Decimal point style', stepper_style1_input: 'Input state', stepper_style2: 'Style 2', stepper_style2_def: 'Default usage', stepper_style2_disable: 'Disable style', stepper_style2_point: 'Decimal point style', stepper_style2_input: 'Input state', // switch-button switchbutton: 'SwitchButton', switchbutton_style1: 'Basic style 1', switchbutton_style2: 'Basic style 2', switchbutton_style_basic_text: 'Basic text style', switchbutton_style_icon: 'Icon style', switchbutton_style_thumb: 'Slider animation style', switchbutton_style_gradient: 'Gradient style', switchbutton_style_gradient_text: 'Gradient text style', switchbutton_style_uncontrol: 'Uncontrolled switch', // time-picker timepicker: 'TimerPicker', timepicker_basic: 'Basic use of time period selector', timepicker_prefix: 'Time period selector with prefix position', // feedback // dialog dialog: 'Dialog', dialog_alert: 'Alert Dialog', dialog_confirm: 'Confirm Dialog', dialog_prompt: 'Prompt Dialog(UnControlled)', dialog_prompt_control: 'Controlled Prompt(Controlled)', dialog_single: 'Single Selection Checkbox', dialog_multi: 'Multi Selection Checkbox', dialog_list: 'List Dialog', dialog_custom: 'Custom Dialog', dialog_text_sensor: 'Sensor selection', dialog_text_room: 'Room sensor calibration', dialog_text_floor: 'Floor sensor calibration', dialog_text_adap: 'Floor sensor calibration', dialog_text_frost: 'Floor sensor calibration', dialog_text_test: 'Floor sensor calibration', dialog_text_click_close: 'Click for Close', dialog_text_option: 'option{0}', dialog_text_cus_content: 'Custom Content', // globaltoast globaltoast: 'GlobalToast', globaltoast_load: 'Loading Usage', globaltoast_max: 'Suggestions for suggestive copywriting display up to 16 characters', globaltoast_set: 'Set successfully', // modal modal: 'Modal', modal_count: 'Countdown popup layer', modal_date: 'Date selection popup', modal_list_single: 'List selection pop-up layer (single selection)', modal_list_mul: 'List selection pop-up layer (multiple selection)', modal_list_pick: 'Picker select pop-up layer', modal_content_iam: 'I am Modal', modal_content_count_title: 'Countdown', modal_content_date_title: 'Birthday', // notification notification: 'Notification', notification_label: 'Click me show Notification', notification_tip: 'Warning Notification', // notification-legacy notificationlegacy: 'NotificationLegacy', notificationlegacy_content: 'I am Notification', // popup popup: 'Popup', popup_count: 'Countdown popup layer', popup_date: 'Date selection popup', popup_time: 'Time period selection pop-up layer', popup_time_title: 'Time period selection', popup_number: 'Number selection pop-up layer', popup_number_title: 'Temperature adjustment (℃)', popup_list: 'List selection pop-up layer (single selection)', popup_listmore: 'List selection pop-up layer (multiple selection)', popup_picker: 'Picker select pop-up layer (single choice)', popup_pickermore: 'Picker select pop-up layer (multiple choice)', popup_cus: 'Costom Popup', popup_toast: 'Toast Popup', // swipeout swipeout: 'Swipeout', swipeout_left: 'Slide left', swipeout_left_content: 'Try sliding left', swipeout_right: 'Slide right', swipeout_right_content: 'Try sliding right', swipeout_disable: 'Disable sideslip', // tips tips: 'Tips', tips_top_left: 'Bubble - top left', tips_top_mid: 'Bubble - top center', tips_top_right: 'Bubble - top right', tips_bottom_left: 'Bubble -bottom left', tips_bottom_mid: 'Bubble -bottom center', tips_bottom_right: 'Bubble -bottom right', // toast-view toastview: 'ToastView', toastview_hasicon: 'With icon style', toastview_hasicon_success: 'Success tips', toastview_hasicon_success_text: 'Success Text', toastview_hasicon_warn: 'Warning tips', toastview_hasicon_warn_text: 'Warning Text', toastview_hasicon_error: 'Error tips', toastview_hasicon_error_text: 'Error Text', toastview_hasicon_loading: 'Loading tips', toastview_noicon: 'Without icon style', toastview_light: 'Light prompt', toastview_light_text: 'I am toastView!!!', // navigation // controllerbar controllerbar: 'ControllerBar', controllerbar_basic: 'Basic Bottom Bar', controllerbar_base: 'ControllerBar.Group base version', controllerbar_swiper: 'ControllerBar.Group Swiper version', controllerbar_divide: 'ControllerBar divide version', // tab tab: 'Tab', tab_text: 'Tab{0}', tab_content_1: 'The prime year does not come again', tab_content_2: 'A day is hard to come in the morning', tab_content_3: 'Time to encourage yourself', tab_content_4: 'Time treats no one', // tabbar tabbar: 'TabBar', tabbar_basic: 'Basic usage', tabbar_radio: 'Radio type', tabbar_radioCircle: 'RadioCircle type', // tabs tabs: 'Tabs', tabs_basic: 'Basic Tabs', tabs_basic_1: 'Detector', tabs_basic_2: 'Remote control', tabs_basic_3: 'Emulator', tabs_basic_4: 'Limited detector', tabs_screen: 'Multi-screen Tabs', tabs_screen_1: 'Name', tabs_screen_2: 'Age', tabs_screen_3: 'Home address', tabs_screen_4: 'Home', tabs_screen_5: 'Community', tabs_screen_6: 'Unit', tabs_screen_7: 'Graduated school', tabs_screen_8: 'Domicile', tabs_basic_stateless: 'Basic Tabs(Stateless component)', tabs_tabcontentsin: 'Use TabContent alone-swipe left and right', tabs_tabcontentsin_page_sin: 'The {0} Page', tabs_tabcontenttab: 'Tabs with TabContent', tabs_tabcontenttab_1: 'Practice_{0}', tabs_tabcontenttab_2: 'Test_{0}', tabs_tabcontenttab_3: 'School building_{0}', tabs_tabcontenttab_4: 'Stencil_{0}', tabs_screen2: 'Tabs with content on multiple screens', tabs_nested: 'Nested Tabs', // topbar topbar: 'TopBar', topbar_title: 'TopBar', topbar_back: 'Back', topbar_basic_split: 'Basic usage - split version', topbar_basic_pack: 'Basic use - package version', topbar_rad_pack: 'Radial Gradient - package version', topbar_line_split: 'Linear gradient - split version', topbar_mul_split: 'Multi toolbar - split version', topbar_mul_pack: 'Multi toolbar change - package version', topbar_timing: 'timing', // presentation // carousel carousel: 'Carousel', // circle-view circleview: 'CircleView', circleview_basic: 'Basic Usage', circleview_border: 'CircleView with border', circleview_embedded: 'CircleView with embedded custom content', // collapsible collapsible: 'Collapsible', collapsible_content: 'Respond to ever-changing things with no change, no tricks.', collapsible_label: 'Click expand', // divider divider: 'Divider', divider_basic: 'Basic form', divider_block: 'Block form display', // linear-gradient lineargradient: 'LinearGradient', lineargradient_two: 'Two vertical gradients', lineargradient_obl: 'Oblique three-stage gradient', // progress progress: 'Progress', progress_space: 'Spacing form', progress_dou: 'Double drag form', progress_comb: 'Combination form', // radial-gradient radialgradient: 'RadialGradient', radialgradient_y2b: 'Radial gradient from yellow to blue outwards', radialgradient_ryp: 'Radial gradient from red-yellow-pink outward', radialgradient_add: 'Add a radial gradient effect to the panel background in the business', // rotation-view rotationview: 'RotationView', rotationview_round: 'Round the edge', rotationview_circle: 'Circle around the center', // tyflat-list tyflatlist: 'TYFlatList', tyflatlist_0_title: 'Basic list', tyflatlist_0_value: 'details', tyflatlist_1_title: 'Here is the title', tyflatlist_1_subTitle: 'Here is the subtitle', tyflatlist_2_title: 'The situation where the title of the list is too long --- ', tyflatlist_3_title: 'Combination of list subtitle and theme', tyflatlist_3_subTitle: 'Warning message', tyflatlist_4_title: 'List title 1', tyflatlist_4_value: 'The content of this list item is a bit long', tyflatlist_5_title: 'List custom content', tyflatlist_6_title: 'List custom Action', tyflatlist_7_title: 'List custom rendering item', tyflatlist_7_action: 'Cleaned successfully', tyflatlist_7_subTitle: 'Cleaning 0 square meters | work 5 minutes', // tylist-item tylistitem: 'TYListItem', tylistitem_basic: 'Basic list', tylistitem_long: 'Long copy adaptation', tylistitem_long_title: 'When the main heading exceeds the specified width of one line, it wraps itself', tylistitem_ada: 'Adapt Icon', tylistitem_ada_title: 'This is a title', // tysection-list tysectionlist: 'TYSectionList', tysectionlist_basic: 'Basic list item', tysectionlist_basic_title: 'List title', tysectionlist_basic_subTitle: 'List subtitle', tysectionlist_select: 'Select box list item', tysectionlist_select_action: 'Cleaned successfully', tysectionlist_select_title: 'April 11th, 23:15', tysectionlist_select_subTitle: 'Cleaning 0 square meters | work 5 minutes', tysectionlist_slider: 'Slider list item', tysectionlist_input: 'Input box list item', tysectionlist_input_title: 'Name', tysectionlist_input_place: 'Enter name', tysectionlist_switch: 'Switch list item adaptation', tysectionlist_switch_title: 'The situation where the title of the list is too long --- ', tysectionlist_switch_subTitle: 'This is the case where the detailed information content of this list is too long', // diffusion diffusion: 'Diffusion', diffusion_basic: 'Basic style', diffusion_children: 'Custom children', // drawer drawer: 'Drawer', drawer_left: 'Click to open the left drawer', drawer_top: 'Click to open the top drawer', drawer_right: 'Click to open the right drawer', drawer_bottom: 'Click to open the bottom drawer', drawer_withMask: 'I have a mask', drawer_withoutMask: "I don't have a mask", // wave wave: 'Wave', wave_basic: 'Basic pattern of water ripples', wave_custom: 'Custom water ripple style', }, zh: { // debug test_I18N: '测试I18N', switch_theme: '切换主题', switch_device_status: '切换设备状态', switch_network_status: '切换网络状态', switch_bluetooth: '切换蓝牙', switch_wifi: '切换WIFI', show_toolbox: '显示工具箱', hide_toolbox: '隐藏工具箱', test_theme: '测试主题配置', // common text_title: '标题', text_subTitle: '副标题', text_confirm: '确认', text_cancel: '取消', text_basic: '基础使用', style_basic: '基础样式', text_hour: '小时', text_minute: '分钟', text_single: '单选', text_mul: '多选', power: '开关', // basic // battery battery: 'Battery 电池', battery_power: '电量 {0}%', battery_power_cus: '电量 {0}%(本地主题)', battery_power_cus2: '本地主题色', battery_power_mod: '电量 {0}% (修改电量颜色分配规则)', battery_power_mod2: '修改电量颜色分配规则', // button button: 'Button 按钮', button_text: '按钮', pure_text_button: '纯文本按钮', pure_icon_button: '纯icon按钮', with_text_icon_button: '带icon的文字按钮', text: '文字', click_me_once: '点我一下', // brick-button brick_button: 'BrickButton 块状按钮', brick_button_text: '文字块状按钮', brick_button_bg: '渐变背景按钮', // icon-font iconfont: 'IconFont 图标', iconfont_basic_use: '基础用法', iconfont_color: '图标颜色', iconfont_size: '图标大小', // motion motion: 'Motion 动效', motion_fade: '淡入淡出', motion_pullup: '淡入淡出', motion_scalefadein: '放大淡入/缩小淡出', motion_scalefadeout: '放大淡入/下滑淡出', motion_pushdown: '下拉上推', motion_toast: '无操作放大淡入/缩小淡出', // slider-progress slider_progress: 'SliderProgress 滑动进度条', slider_progress_uni: '单边进度条', slider_progress_bil: '双边进度条', // tytext tytext: 'TYText 文字', tytext_basic_style: '基本样式', tytext_size_type: '搭配 size 和 type 使用', unittext: 'UnitText 字体单位', unittext_style: '基本样式', unittext_size: '自定义大小', unittext_color: '自定义 UnitText 每个值的颜色', // data-entry // checkbox checkbox: 'Checkbox 选择框', checkbox_label: '单选框', checkbox_basic: '基础使用', checkbox_disable: '禁用状态', checkbox_color: '自定义颜色和大小', checkbox_position: '翻转图标和子元素位置', // date-picker datepicker: 'DatePicker 日期选择器', datepicker_control: '受控日期选择器', datepicker_uncontrol: '非受控日期选择器', // picker-view pickerview: 'PickerView 选择器', pickerview_basic: '基础选择器', pickerview_mul: '多列选择器', // slider slider: 'Slider 滑动选择器', silder_horizontal_parcel: '水平包裹类型滑动条', silder_horizontal_parcel_custom: '水平包裹自定义滑块滑动条', silder_horizontal_parcel_number: '水平包裹带有刻度滑块', silder_horizontal_number: '水平有刻度滑动条', slider_basic: '水平滑动条 - 基础样式', slider_custom: '水平滑动条 - 自定义按钮', silder_vertical: '竖直滑动条', // slider_with_line slider_with_line: 'SliderWithLine 滑动选择器', slider_with_line_horizontal: '水平滑动选择器', slider_with_line_vertical: '竖直滑动选择器', // stepper stepper: 'Stepper 步进器', stepper_style1: '风格一', stepper_style1_def: '默认用法', stepper_style1_disable: '禁用样式', stepper_style1_point: '小数点样式', stepper_style1_input: '可输入状态', stepper_style2: '风格二', stepper_style2_def: '默认用法', stepper_style2_disable: '禁用样式', stepper_style2_point: '小数点样式', stepper_style2_input: '可输入状态', // switch-button switchbutton: 'SwitchButton 开关', switchbutton_style1: '基础样式一', switchbutton_style2: '基础样式二', switchbutton_style_basic_text: '基础文本样式', switchbutton_style_icon: 'icon 样式', switchbutton_style_thumb: '滑块动画样式', switchbutton_style_gradient: '渐变样式', switchbutton_style_gradient_text: '渐变文本样式', switchbutton_style_uncontrol: '非受控开关', // time-picker timepicker: 'TimerPicker 时间段选择器', timepicker_basic: '时间段选择器基础使用', timepicker_prefix: '时间段选择器配合前缀位置', // feedback // dialog dialog: 'Dialog 对话框', dialog_alert: '警告框', dialog_confirm: '提示框', dialog_prompt: '输入对话框(非受控)', dialog_prompt_control: '输入对话框(受控)', dialog_single: '单选对话框', dialog_multi: '多选对话框', dialog_list: '列表对话框', dialog_custom: '自定义对话框', dialog_text_sensor: '传感器选择', dialog_text_room: '房间传感器校准', dialog_text_floor: '地板传感器校准', dialog_text_adap: '自适应功能', dialog_text_frost: '防冻保护功能', dialog_text_test: '测试滚动功能', dialog_text_click_close: '点我关闭', dialog_text_option: '选项{0}', dialog_text_cus_content: '自定义内容', // globaltoast globaltoast: 'GlobalToast 全局吐司', globaltoast_load: '加载使用', globaltoast_max: '提示性文案建议最多展示十六个字符', globaltoast_set: '设置成功', // modal modal: 'Modal 遮罩', modal_count: '倒计时弹出层', modal_date: '日期选择弹出层', modal_list_single: '列表选择弹出层(单选)', modal_list_mul: '列表选择弹出层(多选)', modal_list_pick: 'Picker 选择弹出层', modal_content_iam: '我是遮罩', modal_content_count_title: '倒计时', modal_content_date_title: '生日', // notification notification: 'Notification 全局通知', notification_label: '点我显示通知栏', notification_tip: '警告提示框', // notification-legacy notificationlegacy: 'NotificationLegacy 通知栏', notificationlegacy_content: 'I am Notification', // popup popup: 'Popup 弹出层', popup_count: '倒计时弹出层', popup_date: '日期选择弹出层', popup_time: '时间段选择弹出层', popup_time_title: '时间段选择', popup_number: '数值选择弹出层', popup_number_title: '温度调节 (℃)', popup_list: '列表选择弹出层(单选)', popup_listmore: '列表选择弹出层(多选)', popup_picker: 'Picker 选择弹出层(单选)', popup_pickermore: 'Picker 选择弹出层(多选)', popup_cus: '自定义弹出层', popup_toast: 'Toast 弹出层', // swipeout swipeout: 'Swipeout 侧滑', swipeout_left: '左侧滑', swipeout_left_content: '请尝试左侧滑', swipeout_right: '右侧滑', swipeout_right_content: '请尝试右侧滑', swipeout_disable: '禁用侧滑', // tips tips: 'Tips 气泡', tips_top_left: '气泡 - 上左', tips_top_mid: '气泡 - 上中', tips_top_right: '气泡 - 上右', tips_bottom_left: '气泡 - 下左', tips_bottom_mid: '气泡 - 下中', tips_bottom_right: '气泡 - 下右', // toast-view toastview: 'ToastView 吐司', toastview_hasicon: '带icon样式', toastview_hasicon_success: '成功提示', toastview_hasicon_success_text: '成功文案', toastview_hasicon_warn: '警示提示', toastview_hasicon_warn_text: '警示文案', toastview_hasicon_error: '错误提示', toastview_hasicon_error_text: '错误文案', toastview_hasicon_loading: '加载提示', toastview_noicon: '不带icon样式', toastview_light: '轻提示', toastview_light_text: 'I am toastView!!!', // navigation // controllerbar controllerbar: 'ControllerBar 底部栏', controllerbar_basic: '基础底部栏', controllerbar_base: 'ControllerBar.Group base 版', controllerbar_swiper: 'ControllerBar.Group Swiper 版', controllerbar_divide: 'ControllerBar divide 版', // tab tab: 'Tab 标签栏', tab_text: '标签{0}', tab_content_1: '盛年不重来', tab_content_2: '一日难再晨', tab_content_3: '及时宜自勉', tab_content_4: '岁月不待人', // tabbar tabbar: 'TabBar 标签栏拆分版', tabbar_basic: '基础类型', tabbar_radio: 'Radio 类型', tabbar_radioCircle: 'RadioCircle 类型', // tabs tabs: 'Tabs 纯手势标签栏', tabs_basic: '基础 Tabs', tabs_basic_1: '探测器', tabs_basic_2: '遥控器', tabs_basic_3: '模拟器', tabs_basic_4: '有限探测器', tabs_screen: '多屏 Tabs', tabs_screen_1: '姓名', tabs_screen_2: '年龄', tabs_screen_3: '家庭住址', tabs_screen_4: '房间', tabs_screen_5: '小区', tabs_screen_6: '单元', tabs_screen_7: '毕业院校', tabs_screen_8: '户籍', tabs_basic_stateless: '基础 Tabs(无状态组件)', tabs_tabcontentsin: '单独使用 TabContent - 左右滑动', tabs_tabcontentsin_page_sin: '第{0}页', tabs_tabcontenttab: '标签页配合 TabContent', tabs_tabcontenttab_1: '测试_{0}', tabs_tabcontenttab_2: 'Test_{0}', tabs_tabcontenttab_3: '校舍_{0}', tabs_tabcontenttab_4: '模版_{0}', tabs_screen2: '多屏存在内容的 Tabs', tabs_nested: '嵌套的 Tabs', // topbar topbar: 'TopBar 头部栏', topbar_title: '头部栏', topbar_back: '返回', topbar_basic_split: '基础使用 - 拆分版', topbar_basic_pack: '基础使用 - 封装版', topbar_rad_pack: '径向渐变 - 封装版', topbar_line_split: '线性渐变 - 拆分版', topbar_mul_split: '多工具栏 - 拆分版', topbar_mul_pack: '多工具栏 - 封装版', topbar_timing: '定时', // presentation // carousel carousel: 'Carousel 轮播', // circle-view circleview: 'CircleView 圆形视图', circleview_basic: '基础展示', circleview_border: '带边框的圆形视图', circleview_embedded: '内嵌自定义内容的圆形视图', // collapsible collapsible: 'Collapsible 折叠', collapsible_content: '以不变应万变,无招胜有招。', collapsible_label: '点击展开', // divider divider: 'Divider 分割线', divider_basic: '基础形式', divider_block: '块状形式展示', // linear-gradient lineargradient: 'LinearGradient 线性渐变', lineargradient_two: '垂直两段渐变', lineargradient_obl: '斜向三段渐变', // progress progress: 'Progress 进度条', progress_space: '间距形式', progress_dou: '双边拖动形式', progress_comb: '组合形式', // radial-gradient radialgradient: 'RadialGradient 径向渐变', radialgradient_y2b: '向外进行由黄色-蓝色的径向渐变', radialgradient_ryp: '向外进行由红色-黄色-粉色的径向渐变', radialgradient_add: '业务中给面板背景添加径向渐变效果', // rotation-view rotationview: 'RotationView 旋转视图', rotationview_round: '绕边缘转圈形式', rotationview_circle: '绕中心转圈', // tyflat-list tyflatlist: 'TYFlatList 列表', tyflatlist_0_title: '基础列表', tyflatlist_0_value: '详细信息', tyflatlist_1_title: '这里是正标题', tyflatlist_1_subTitle: '这里是副标题', tyflatlist_2_title: '列表标题过长的情况列表标题过长的情况列表标题过长的情况', tyflatlist_3_title: '列表副标题和theme的结合', tyflatlist_3_subTitle: '警告信息', tyflatlist_4_title: '列表标题1', tyflatlist_4_value: '这个列表项的内容有点长哦', tyflatlist_5_title: '列表自定义内容', tyflatlist_6_title: '列表自定义Action', tyflatlist_7_title: '列表自定义渲染item', tyflatlist_7_action: '清扫成功', tyflatlist_7_subTitle: '清扫 0平方米 | 工作 5分钟', // tylist-item tylistitem: 'TYListItem 列表项', tylistitem_basic: '基础列表', tylistitem_long: '文案过长适配', tylistitem_long_title: '主标题超过一行规定的宽度时,文案将自行换行', tylistitem_ada: '适配 Icon 样式', tylistitem_ada_title: '这是一个标题', // tysection-list tysectionlist: 'TYSectionList 分组列表', tysectionlist_basic: '基础列表项', tysectionlist_basic_title: '列表标题', tysectionlist_basic_subTitle: '列表副标题', tysectionlist_select: '选择框列表项', tysectionlist_select_action: '清扫成功', tysectionlist_select_title: '04月11日 23:15', tysectionlist_select_subTitle: '清扫 0平方米 | 工作 5分钟', tysectionlist_slider: '滑动条列表项', tysectionlist_input: '输入框列表项', tysectionlist_input_title: '名字', tysectionlist_input_place: '输入名字', tysectionlist_switch: '开关列表项适配', tysectionlist_switch_title: '列表标题过长的情况列表标题过长的情况列表标题过长的情况', tysectionlist_switch_subTitle: '这是这个列表的详细信息内容过长的情况这是这个列表的详细信息内容过长的情况', // diffusion diffusion: 'Diffusion 水波纹', diffusion_basic: '基础样式', diffusion_children: '自定义子组件', // drawer drawer: 'Drawer 抽屉动画', drawer_left: '点击打开左边抽屉', drawer_top: '点击打开上边抽屉', drawer_right: '点击打开右边抽屉', drawer_bottom: '点击打开下边抽屉', drawer_withMask: '我有遮罩', drawer_withoutMask: '我没有遮罩', // wave wave: 'Wave 波浪动画', wave_basic: '波浪基本样式', wave_custom: '自定义波浪样式', }, } as const;
the_stack
import { Promise } from 'bluebird'; import { calculateFilenameExt } from './calculateFilenameExt'; import { createFeatureHierarchySubExtension } from './createFeatureHierarchySubExtension'; import { Gltf, GltfType, GLenumName } from './gltfType'; import { FeatureHierarchyClass } from './featureHierarchyClass'; import { Material } from './Material'; import { Mesh } from './Mesh'; import { Cartesian3, defaultValue, defined, Math as CesiumMath, Matrix4, Quaternion } from 'cesium'; const gltfPipeline = require('gltf-pipeline'); var gltfToGlb = gltfPipeline.gltfToGlb; var fsExtra = require('fs-extra'); var path = require('path'); var gltfConversionOptions = { resourceDirectory: path.join(__dirname, '../') }; import createGltf = require('./createGltf'); import { createTilesetJsonSingle } from './createTilesetJsonSingle'; import { createFeatureMetadataExtension } from './createFeatureMetadataExtension'; import { Extensions } from './Extensions'; var typeConversion = require('./typeConversion'); var getMinMax = require('./getMinMax'); var createB3dm = require('./createB3dm'); var createGlb = require('./createGlb'); var getBufferPadded = require('./getBufferPadded'); var saveBinary = require('./saveBinary'); var saveJson = require('./saveJson'); var sizeOfFloat = 4; var sizeOfUint16 = 2; var whiteOpaqueMaterial = new Material([1.0, 1.0, 1.0, 1.0]); /** * Create a tileset that uses a batch table hierarchy, * by default using the 3DTILES_batch_table_hierarchy extension. * * @param {Object} options An object with the following properties: * @param {String} options.directory Directory in which to save the tileset. * @param {Boolean} [options.batchTableBinary=false] Create a batch table binary for the b3dm tile. * @param {Boolean} [options.noParents=false] Don't set any instance parents. * @param {Boolean} [options.multipleParents=false] Set multiple parents to some instances. * @param {Boolean} [options.legacy=false] Generate the batch table hierarchy as part of the base Batch Table, now deprecated. * @param {Matrix4} [options.transform=Matrix4.IDENTITY] The tile transform. * @param {Boolean} [options.gzip=false] Gzip the saved tile. * @param {Boolean} [options.prettyJson=true] Whether to prettify the JSON. * @param {Boolean} [options.use3dTilesNext=false] Whether to use 3dTilesNext (gltf) * @param {Boolean} [options.useGlb=false] Whether to use glb with 3dTilesNexxt * @returns {Promise} A promise that resolves when the tileset is saved. */ export function createBatchTableHierarchy(options) { var use3dTilesNext = defaultValue(options.use3dTilesNext, false); var useGlb = defaultValue(options.useGlb, false); var gzip = defaultValue(options.gzip, false); var useBatchTableBinary = defaultValue(options.batchTableBinary, false); var noParents = defaultValue(options.noParents, false); var multipleParents = defaultValue(options.multipleParents, false); var transform = defaultValue(options.transform, Matrix4.IDENTITY); var instances = createInstances(noParents, multipleParents); var batchTableJson = createBatchTableJson(instances, options); var batchTableBinary; if (useBatchTableBinary) { batchTableBinary = createBatchTableBinary(batchTableJson, options); // Modifies the json in place } // Mesh urls listed in the same order as features in the classIds arrays var urls = [ 'data/house/doorknob0.gltf', 'data/house/doorknob1.gltf', 'data/house/doorknob2.gltf', 'data/house/doorknob3.gltf', 'data/house/door0.gltf', 'data/house/door1.gltf', 'data/house/door2.gltf', 'data/house/door3.gltf', 'data/house/roof.gltf', 'data/house/wall.gltf' ]; var buildingPositions = [ new Cartesian3(40, 40, 0), new Cartesian3(-30, -20, 0), new Cartesian3(0, 0, 0) ]; // glTF models are initially y-up, transform to z-up var yUpToZUp = Quaternion.fromAxisAngle( Cartesian3.UNIT_X, CesiumMath.PI_OVER_TWO ); var scale = new Cartesian3(5.0, 5.0, 5.0); // Scale the models up a bit // Local transforms of the buildings within the tile var buildingTransforms = [ Matrix4.fromTranslationQuaternionRotationScale( buildingPositions[0], yUpToZUp, scale ), Matrix4.fromTranslationQuaternionRotationScale( buildingPositions[1], yUpToZUp, scale ), Matrix4.fromTranslationQuaternionRotationScale( buildingPositions[2], yUpToZUp, scale ) ]; var contentUri = 'tile' + calculateFilenameExt(use3dTilesNext, useGlb, '.b3dm'); var directory = options.directory; var tilePath = path.join(directory, contentUri); var tilesetJsonPath = path.join(directory, 'tileset.json'); var buildingsLength = 3; var meshesLength = urls.length; var batchLength = buildingsLength * meshesLength; var geometricError = 70.0; var box = [0, 0, 10, 50, 0, 0, 0, 50, 0, 0, 0, 10]; var opts: any = { contentUri: contentUri, geometricError: geometricError, box: box, transform: transform }; if (use3dTilesNext) { opts.versionNumber = '1.1'; } var tilesetJson = createTilesetJsonSingle(opts); if (!use3dTilesNext && !options.legacy) { Extensions.addExtensionsUsed( tilesetJson, '3DTILES_batch_table_hierarchy' ); Extensions.addExtensionsRequired( tilesetJson, '3DTILES_batch_table_hierarchy' ); } var featureTableJson = { BATCH_LENGTH: batchLength }; return Promise.map(urls, function (url) { return fsExtra.readJson(url).then(function (gltf) { return Mesh.fromGltf(gltf); }); }) .then(function (meshes) { var meshesLength = meshes.length; var clonedMeshes = []; for (var i = 0; i < buildingsLength; ++i) { for (var j = 0; j < meshesLength; ++j) { var mesh = Mesh.clone(meshes[j]); mesh.material = whiteOpaqueMaterial; mesh.transform(buildingTransforms[i]); clonedMeshes.push(mesh); } } var batchedMesh = Mesh.batch(clonedMeshes); if (use3dTilesNext) { return createGltf({ mesh: batchedMesh, use3dTilesNext: use3dTilesNext }); } return createGlb({ mesh: batchedMesh }); }) .then(function (result) { if (use3dTilesNext) { if (defined(batchTableJson)) { // add human readable batch table data if ( defined(batchTableJson) && Object.keys(batchTableJson).length > 0 ) { var batchTableJsonPruned = { area: batchTableJson.area, height: batchTableJson.height }; result = createFeatureMetadataExtension( result, batchTableJsonPruned, batchTableBinary ) as Gltf; const hierarchy = batchTableJson.tilesNextHierarchy; if (defined(hierarchy)) { addHierarchyToGltf( hierarchy, result, batchTableBinary ); } } } if (!useGlb) { return Promise.all([ saveJson(tilePath, result, options.prettyJson, gzip), saveJson( tilesetJsonPath, tilesetJson, options.prettyJson, gzip ) ]); } else { return Promise.all([ gltfToGlb(result, gltfConversionOptions).then(function ( out ) { return saveBinary(tilePath, out.glb, gzip); }), saveJson( tilesetJsonPath, tilesetJson, options.prettyJson, gzip ) ]); } } var b3dm = createB3dm({ glb: result, featureTableJson: featureTableJson, batchTableJson: batchTableJson, batchTableBinary: batchTableBinary }); // legacy b3dm return Promise.all([ saveJson( tilesetJsonPath, tilesetJson, options.prettyJson, gzip ), saveBinary(tilePath, b3dm, gzip) ]); }); } function createFloatBuffer(values) { var buffer = Buffer.alloc(values.length * sizeOfFloat); var length = values.length; for (var i = 0; i < length; ++i) { buffer.writeFloatLE(values[i], i * sizeOfFloat); } return buffer; } function createUInt16Buffer(values) { var buffer = Buffer.alloc(values.length * sizeOfUint16); var length = values.length; for (var i = 0; i < length; ++i) { buffer.writeUInt16LE(values[i], i * sizeOfUint16); } return buffer; } function createBatchTableBinary(batchTable, options) { var byteOffset = 0; var buffers = []; var use3dTilesNext = defaultValue(options.use3dTilesNext, false); function createBinaryProperty(values, componentType, type?, name?: string) { var buffer; if (componentType === 'FLOAT') { buffer = createFloatBuffer(values); } else if (componentType === 'UNSIGNED_SHORT') { buffer = createUInt16Buffer(values); } buffer = getBufferPadded(buffer); buffers.push(buffer); var binaryReference: any = { byteOffset: byteOffset, componentType: componentType, type: type }; // Create a composite object containing all of the necessary // information to split into a GltfAccessor / GltfBufferView if (use3dTilesNext) { // buffer view binaryReference.name = name; binaryReference.byteLength = buffer.length; binaryReference.target = GLenumName.ARRAY_BUFFER; // accessor binaryReference.componentType = typeConversion.componentTypeStringToInteger( componentType ); binaryReference.count = values.length; const minMax = getMinMax(values, 1); binaryReference.max = minMax.max; binaryReference.min = minMax.min; binaryReference.type = GltfType.SCALAR; } byteOffset += buffer.length; return binaryReference; } // Convert regular batch table properties to binary var propertyName; for (propertyName in batchTable) { if ( batchTable.hasOwnProperty(propertyName) && propertyName !== 'HIERARCHY' && propertyName !== 'extensions' && propertyName !== 'extras' ) { if (typeof batchTable[propertyName][0] === 'number') { batchTable[propertyName] = createBinaryProperty( batchTable[propertyName], 'FLOAT', 'SCALAR', propertyName ); } } } // Convert instance properties to binary var hierarchy = options.legacy ? batchTable.HIERARCHY : batchTable.extensions['3DTILES_batch_table_hierarchy']; var classes = hierarchy.classes; var classesLength = classes.length; for (var i = 0; i < classesLength; ++i) { var instances = classes[i].instances; for (propertyName in instances) { if (instances.hasOwnProperty(propertyName)) { if (typeof instances[propertyName][0] === 'number') { instances[propertyName] = createBinaryProperty( instances[propertyName], 'FLOAT', 'SCALAR', propertyName ); } } } } // Convert classIds to binary hierarchy.classIds = createBinaryProperty( hierarchy.classIds, 'UNSIGNED_SHORT' ); // Convert parentCounts to binary (if they exist) if (defined(hierarchy.parentCounts)) { hierarchy.parentCounts = createBinaryProperty( hierarchy.parentCounts, 'UNSIGNED_SHORT' ); } // Convert parentIds to binary (if they exist) if (defined(hierarchy.parentIds)) { hierarchy.parentIds = createBinaryProperty( hierarchy.parentIds, 'UNSIGNED_SHORT' ); } return Buffer.concat(buffers); } function createBatchTableJson(instances, options) { // Create batch table from the instances' regular properties var batchTable: any = {}; var instancesLength = instances.length; for (var i = 0; i < instancesLength; ++i) { var instance = instances[i]; var properties = instance.properties; if (defined(properties)) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { if (!defined(batchTable[propertyName])) { batchTable[propertyName] = []; } batchTable[propertyName].push(properties[propertyName]); } } } } var hierarchy = createHierarchy(instances); if (options.use3dTilesNext) { batchTable.tilesNextHierarchy = hierarchy; } if (options.legacy) { // Add HIERARCHY object batchTable.HIERARCHY = hierarchy; } else { Extensions.addExtension( batchTable, '3DTILES_batch_table_hierarchy', hierarchy ); } return batchTable; } function createHierarchy(instances) { var i; var j; var classes = []; var classIds = []; var parentCounts = []; var parentIds = []; var instancesLength = instances.length; var classId; var classData; for (i = 0; i < instancesLength; ++i) { var instance = instances[i].instance; var className = instance.className; var properties = instance.properties; var parents = defaultValue(instance.parents, []); var parentsLength = parents.length; // Get class id classId = undefined; classData = undefined; var classesLength = classes.length; for (j = 0; j < classesLength; ++j) { if (classes[j].name === className) { classId = j; classData = classes[j]; break; } } // Create class if it doesn't already exist if (!defined(classId)) { classData = { name: className, length: 0, instances: {} }; classId = classes.length; classes.push(classData); var propertyNames = Object.keys(properties); var propertyNamesLength = propertyNames.length; for (j = 0; j < propertyNamesLength; ++j) { classData.instances[propertyNames[j]] = []; } } // Add properties to class for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { classData!.instances[propertyName].push( properties[propertyName] ); } } // Increment class instances length classData!.length++; // Add to classIds classIds.push(classId); // Add to parentCounts parentCounts.push(parentsLength); // Add to parent ids for (j = 0; j < parentsLength; ++j) { var parent = parents[j]; var parentId = instances.indexOf(parent); parentIds.push(parentId); } } // Check if any of the instances have multiple parents, or if none of the instances have parents var singleParents = true; var noParents = true; for (i = 0; i < instancesLength; ++i) { if (parentCounts[i] > 0) { noParents = false; } if (parentCounts[i] > 1) { singleParents = false; } } if (noParents) { // Unlink parentCounts and parentIds parentCounts = undefined; parentIds = undefined; } else if (singleParents) { // Unlink parentCounts and add missing parentIds that point to themselves for (i = 0; i < instancesLength; ++i) { if (parentCounts[i] === 0) { parentIds.splice(i, 0, i); } } parentCounts = undefined; } return { instancesLength: instancesLength, classes: classes, classIds: classIds, parentIds: parentIds, parentCounts: parentCounts }; } function addHierarchyToGltf(hierarchy: any, gltf: Gltf, binary: Buffer) { const classes = hierarchy.classes.map( (item) => new FeatureHierarchyClass(item.name, item.length, item.instances) ); const classIds = hierarchy.classIds; const parentCounts = hierarchy.parentCounts; const parentIds = hierarchy.parentIds; const instancesLength = hierarchy.instancesLength; return createFeatureHierarchySubExtension( gltf, classes, classIds, instancesLength, parentIds, parentCounts, binary ); } function createInstances(noParents, multipleParents) { var door0: any = { instance: { className: 'door', properties: { door_name: 'door0', door_width: 1.2, door_mass: 10 } }, properties: { height: 5.0, area: 10.0 } }; var door1: any = { instance: { className: 'door', properties: { door_name: 'door1', door_width: 1.3, door_mass: 11 } }, properties: { height: 5.0, area: 10.0 } }; var door2: any = { instance: { className: 'door', properties: { door_name: 'door2', door_width: 1.21, door_mass: 14 } }, properties: { height: 5.0, area: 10.0 } }; var door3: any = { instance: { className: 'door', properties: { door_name: 'door3', door_width: 1.5, door_mass: 7 } }, properties: { height: 5.0, area: 10.0 } }; var door4: any = { instance: { className: 'door', properties: { door_name: 'door4', door_width: 1.1, door_mass: 8 } }, properties: { height: 5.0, area: 10.0 } }; var door5: any = { instance: { className: 'door', properties: { door_name: 'door5', door_width: 1.15, door_mass: 12 } }, properties: { height: 5.0, area: 10.0 } }; var door6: any = { instance: { className: 'door', properties: { door_name: 'door6', door_width: 1.32, door_mass: 3 } }, properties: { height: 5.0, area: 10.0 } }; var door7: any = { instance: { className: 'door', properties: { door_name: 'door7', door_width: 1.54, door_mass: 6 } }, properties: { height: 5.0, area: 10.0 } }; var door8: any = { instance: { className: 'door', properties: { door_name: 'door8', door_width: 1.8, door_mass: 3 } }, properties: { height: 5.0, area: 10.0 } }; var door9: any = { instance: { className: 'door', properties: { door_name: 'door9', door_width: 2.0, door_mass: 5 } }, properties: { height: 5.0, area: 10.0 } }; var door10: any = { instance: { className: 'door', properties: { door_name: 'door10', door_width: 2.1, door_mass: 9 } }, properties: { height: 5.0, area: 10.0 } }; var door11: any = { instance: { className: 'door', properties: { door_name: 'door11', door_width: 1.3, door_mass: 10 } }, properties: { height: 5.0, area: 10.0 } }; var doorknob0: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob0', doorknob_size: 0.3 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob1: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob1', doorknob_size: 0.43 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob2: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob2', doorknob_size: 0.32 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob3: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob3', doorknob_size: 0.2 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob4: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob4', doorknob_size: 0.21 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob5: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob5', doorknob_size: 0.35 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob6: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob6', doorknob_size: 0.3 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob7: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob7', doorknob_size: 0.23 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob8: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob8', doorknob_size: 0.43 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob9: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob9', doorknob_size: 0.32 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob10: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob10', doorknob_size: 0.41 } }, properties: { height: 0.1, area: 0.2 } }; var doorknob11: any = { instance: { className: 'doorknob', properties: { doorknob_name: 'doorknob11', doorknob_size: 0.33 } }, properties: { height: 0.1, area: 0.2 } }; var roof0: any = { instance: { className: 'roof', properties: { roof_name: 'roof0', roof_paint: 'red' } }, properties: { height: 6.0, area: 12.0 } }; var roof1: any = { instance: { className: 'roof', properties: { roof_name: 'roof1', roof_paint: 'blue' } }, properties: { height: 6.0, area: 12.0 } }; var roof2: any = { instance: { className: 'roof', properties: { roof_name: 'roof2', roof_paint: 'yellow' } }, properties: { height: 6.0, area: 12.0 } }; var wall0: any = { instance: { className: 'wall', properties: { wall_name: 'wall0', wall_paint: 'pink', wall_windows: 1 } }, properties: { height: 10.0, area: 20.0 } }; var wall1: any = { instance: { className: 'wall', properties: { wall_name: 'wall1', wall_paint: 'orange', wall_windows: 2 } }, properties: { height: 10.0, area: 20.0 } }; var wall2: any = { instance: { className: 'wall', properties: { wall_name: 'wall2', wall_paint: 'blue', wall_windows: 4 } }, properties: { height: 10.0, area: 20.0 } }; var building0: any = { instance: { className: 'building', properties: { building_name: 'building0', building_area: 20.0 } } }; var building1: any = { instance: { className: 'building', properties: { building_name: 'building1', building_area: 21.98 } } }; var building2: any = { instance: { className: 'building', properties: { building_name: 'building2', building_area: 39.3 } } }; var zone0: any = { instance: { className: 'zone', properties: { zone_name: 'zone0', zone_buildings: 3 } } }; var classifierNew: any = { instance: { className: 'classifier_new', properties: { year: 2000, color: 'red', name: 'project', architect: 'architect' } } }; var classifierOld: any = { instance: { className: 'classifier_old', properties: { description: 'built in 1980', inspection: 2009 } } }; if (noParents) { return [ doorknob0, doorknob1, doorknob2, doorknob3, door0, door1, door2, door3, roof0, wall0, doorknob4, doorknob5, doorknob6, doorknob7, door4, door5, door6, door7, roof1, wall1, doorknob8, doorknob9, doorknob10, doorknob11, door8, door9, door10, door11, roof2, wall2 ]; } door0.instance.parents = [building0]; door1.instance.parents = [building0]; door2.instance.parents = [building0]; door3.instance.parents = [building0]; door4.instance.parents = [building1]; door5.instance.parents = [building1]; door6.instance.parents = [building1]; door7.instance.parents = [building1]; door8.instance.parents = [building2]; door9.instance.parents = [building2]; door10.instance.parents = [building2]; door11.instance.parents = [building2]; doorknob0.instance.parents = [door0]; doorknob1.instance.parents = [door1]; doorknob2.instance.parents = [door2]; doorknob3.instance.parents = [door3]; doorknob4.instance.parents = [door4]; doorknob5.instance.parents = [door5]; doorknob6.instance.parents = [door6]; doorknob7.instance.parents = [door7]; doorknob8.instance.parents = [door8]; doorknob9.instance.parents = [door9]; doorknob10.instance.parents = [door10]; doorknob11.instance.parents = [door11]; roof0.instance.parents = [building0]; roof1.instance.parents = [building1]; roof2.instance.parents = [building2]; wall0.instance.parents = [building0]; wall1.instance.parents = [building1]; wall2.instance.parents = [building2]; building0.instance.parents = [zone0]; building1.instance.parents = [zone0]; building2.instance.parents = [zone0]; if (multipleParents) { door0.instance.parents.push(classifierOld); building0.instance.parents.push(classifierNew); building1.instance.parents.push(classifierOld); building2.instance.parents.push(classifierNew, classifierOld); return [ doorknob0, doorknob1, doorknob2, doorknob3, door0, door1, door2, door3, roof0, wall0, doorknob4, doorknob5, doorknob6, doorknob7, door4, door5, door6, door7, roof1, wall1, doorknob8, doorknob9, doorknob10, doorknob11, door8, door9, door10, door11, roof2, wall2, building0, building1, building2, zone0, classifierNew, classifierOld ]; } return [ doorknob0, doorknob1, doorknob2, doorknob3, door0, door1, door2, door3, roof0, wall0, doorknob4, doorknob5, doorknob6, doorknob7, door4, door5, door6, door7, roof1, wall1, doorknob8, doorknob9, doorknob10, doorknob11, door8, door9, door10, door11, roof2, wall2, building0, building1, building2, zone0 ]; }
the_stack
import { ethers } from 'ethers' import linker from 'solc/linker' import { POOL_INIT_CODE_HASH_OPTIMISM, POOL_INIT_CODE_HASH_OPTIMISM_KOVAN, } from '@uniswap/v3-sdk' import { sleep, add0x, remove0x, clone } from '@eth-optimism/core-utils' import { OLD_ETH_ADDRESS, WETH_TRANSFER_ADDRESSES, UNISWAP_V3_KOVAN_MULTICALL, } from './constants' import { findAccount, hexStringIncludes, transferStorageSlot, getMappingKey, getUniswapV3Factory, replaceWETH, } from './utils' import { compile } from './solc' import { Account, AccountType, SurgeryDataSources, ImmutableReference, } from './types' export const handlers: { [key in AccountType]: ( account: Account, data: SurgeryDataSources ) => Account | Promise<Account> } = { [AccountType.ONEINCH_DEPLOYER]: (account, data) => { return { ...handlers[AccountType.EOA](account, data), nonce: 0, } }, [AccountType.DELETE]: () => { return undefined // delete the account }, [AccountType.EOA]: (account) => { return { address: account.address, nonce: account.nonce, balance: account.balance, } }, [AccountType.PRECOMPILE]: (account) => { return account }, [AccountType.PREDEPLOY_NEW_NOT_ETH]: (account) => { return account }, [AccountType.PREDEPLOY_WIPE]: (account, data) => { const genesisAccount = findAccount(data.genesisDump, account.address) return { ...account, code: genesisAccount.code, storage: genesisAccount.storage, } }, [AccountType.PREDEPLOY_NO_WIPE]: (account, data) => { const genesisAccount = findAccount(data.genesisDump, account.address) return { ...account, code: genesisAccount.code, storage: { ...account.storage, ...genesisAccount.storage, }, } }, [AccountType.PREDEPLOY_ETH]: (account, data) => { // Get a copy of the old account so we don't modify the one in dump by accident. const oldAccount = clone(findAccount(data.dump, OLD_ETH_ADDRESS)) // Special handling for moving certain balances over to the WETH predeploy. // We need to trasnfer all statically defined addresses AND all uni pools. const addressesToXfer = WETH_TRANSFER_ADDRESSES.concat( data.pools.map((pool) => { return pool.oldAddress }) ) // For each of the listed addresses, check if it has an ETH balance. If so, we remove the ETH // balance and give WETH a balance instead. let wethBalance = ethers.BigNumber.from(0) for (const address of addressesToXfer) { const balanceKey = getMappingKey([address], 0) if (oldAccount.storage[balanceKey] !== undefined) { wethBalance = wethBalance.add(add0x(oldAccount.storage[balanceKey])) // Remove this balance from the old account storage. delete oldAccount.storage[balanceKey] } } const wethBalanceKey = getMappingKey([OLD_ETH_ADDRESS], 0) return { ...account, storage: { ...oldAccount.storage, ...account.storage, [wethBalanceKey]: wethBalance.toHexString(), }, } }, [AccountType.PREDEPLOY_WETH]: async (account, data) => { // Treat it like a wipe of the old ETH account. account = await handlers[AccountType.PREDEPLOY_WIPE](account, data) // Get a copy of the old ETH account so we don't modify the one in dump by accident. const ethAccount = clone(findAccount(data.dump, OLD_ETH_ADDRESS)) // Special handling for moving certain balances over from the old account. for (const address of WETH_TRANSFER_ADDRESSES) { const balanceKey = getMappingKey([address], 0) if (ethAccount.storage[balanceKey] !== undefined) { // Give this account a balance inside of WETH. const newBalanceKey = getMappingKey([address], 3) account.storage[newBalanceKey] = ethAccount.storage[balanceKey] } } // Need to handle pools in a special manner because we want to get the balance for the old pool // address but we need to transfer the balance to the new pool address. for (const pool of data.pools) { const balanceKey = getMappingKey([pool.oldAddress], 0) if (ethAccount.storage[balanceKey] !== undefined) { // Give this account a balance inside of WETH. const newBalanceKey = getMappingKey([pool.newAddress], 3) account.storage[newBalanceKey] = ethAccount.storage[balanceKey] } } return account }, [AccountType.UNISWAP_V3_FACTORY]: async (account, data) => { // Transfer the owner slot transferStorageSlot({ account, oldSlot: 0, newSlot: 3, }) // Transfer the feeAmountTickSpacing slot for (const fee of [500, 3000, 10000]) { transferStorageSlot({ account, oldSlot: getMappingKey([fee], 1), newSlot: getMappingKey([fee], 4), }) } // Transfer the getPool slot for (const pool of data.pools) { // Fix the token0 => token1 => fee mapping transferStorageSlot({ account, oldSlot: getMappingKey([pool.token0, pool.token1, pool.fee], 2), newSlot: getMappingKey([pool.token0, pool.token1, pool.fee], 5), newValue: pool.newAddress, }) // Fix the token1 => token0 => fee mapping transferStorageSlot({ account, oldSlot: getMappingKey([pool.token1, pool.token0, pool.fee], 2), newSlot: getMappingKey([pool.token1, pool.token0, pool.fee], 5), newValue: pool.newAddress, }) } return handlers[AccountType.UNISWAP_V3_OTHER](account, data) }, [AccountType.UNISWAP_V3_NFPM]: async (account, data) => { for (const pool of data.pools) { try { transferStorageSlot({ account, oldSlot: getMappingKey([pool.oldAddress], 10), newSlot: getMappingKey([pool.newAddress], 10), }) } catch (err) { if (err.message.includes('old slot not found in state dump')) { // It's OK for this to happen because some pools may not have any position NFTs. console.log( `pool not found in NonfungiblePositionManager _poolIds mapping: ${pool.oldAddress}` ) } else { throw err } } } return handlers[AccountType.UNISWAP_V3_OTHER](account, data) }, [AccountType.UNISWAP_V3_POOL]: async (account, data) => { // Find the pool by its old address const pool = data.pools.find((poolData) => { return poolData.oldAddress === account.address }) // Get the pool's code. let poolCode = await data.ropstenProvider.getCode(pool.newAddress) if (poolCode === '0x') { console.log('Could not find pool code, deploying to testnet...') const UniswapV3Factory = getUniswapV3Factory(data.ropstenWallet) await UniswapV3Factory.createPool(pool.token0, pool.token1, pool.fee) // Repeatedly try to get the remote pool code from the testnet. let retries = 0 while (poolCode === '0x') { retries++ if (retries > 50) { throw new Error(`unable to create pool with data: ${pool}`) } poolCode = await data.ropstenProvider.getCode(pool.newAddress) await sleep(5000) } } return { ...account, address: pool.newAddress, code: poolCode, } }, [AccountType.UNISWAP_V3_MAINNET_MULTICALL]: async (account, data) => { // When upgrading mainnet, we want to get rid of the old multicall contract and introduce a new // multicall contract at the OP Kovan address (also the ETH mainnet address). By changing the // address here and piping into the UNISWAP_V3_OTHER handler, we: // (1) Get the state of the old multicall but with the new address // (2) Query the code using the new address (required) return handlers[AccountType.UNISWAP_V3_OTHER]( { ...account, address: UNISWAP_V3_KOVAN_MULTICALL, }, data ) }, [AccountType.UNISWAP_V3_OTHER]: async (account, data) => { let code = await data.ethProvider.getCode(account.address) if (code === '0x') { throw new Error(`account code is empty: ${account.address}`) } // Replace references to L1 WETH address with the L2 WETH address. code = replaceWETH(code) return { ...account, code, } }, [AccountType.UNVERIFIED]: () => { return undefined // delete the account }, [AccountType.VERIFIED]: (account: Account, data: SurgeryDataSources) => { // Find the account in the etherscan dump const contract = data.etherscanDump.find((acc) => { return acc.contractAddress === account.address }) // The contract must exist if (!contract) { throw new Error(`Unable to find ${account.address} in etherscan dump`) } const evmOutput = compile({ contract, ovm: false, }) // Pull out the bytecode, exact handling depends on the Solidity version let bytecode = evmOutput.evm.deployedBytecode if (typeof bytecode === 'object') { bytecode = bytecode.object } // Make sure the bytecode is 0x-prefixed. bytecode = add0x(bytecode) // Handle external library references. if (contract.library) { const linkReferences = linker.findLinkReferences(bytecode) const libStrings = contract.library.split(';') const libraries = {} for (const [i, libStr] of libStrings.entries()) { const [name, address] = libStr.split(':') let key: string if (Object.keys(linkReferences).length > i) { key = Object.keys(linkReferences)[i] } else { key = name } libraries[key] = add0x(address) } // Inject the libraries at the required locations bytecode = linker.linkBytecode(bytecode, libraries) // There should no longer be any link references if linking was done correctly if (Object.keys(linker.findLinkReferences(bytecode)).length !== 0) { throw new Error( `Library linking did not happen correctly: ${contract.contractAddress}` ) } } // Make sure the bytecode is (still) 0x-prefixed. bytecode = add0x(bytecode) // If the contract has immutables in it, then the contracts // need to be compiled with the ovm compiler so that the offsets // can be found. The immutables must be pulled out of the old code // and inserted into the new code const immutableRefs: ImmutableReference = evmOutput.evm.deployedBytecode.immutableReferences if (immutableRefs && Object.keys(immutableRefs).length !== 0) { // Compile using the ovm compiler to find the location of the // immutableRefs in the ovm contract so they can be migrated // to the new contract const ovmOutput = compile({ contract, ovm: true, }) const ovmImmutableRefs: ImmutableReference = ovmOutput.evm.deployedBytecode.immutableReferences // Iterate over the immutableRefs and slice them into the new code // to carry over their values. The keys are the AST IDs for (const [key, value] of Object.entries(immutableRefs)) { const ovmValue = ovmImmutableRefs[key] if (!ovmValue) { throw new Error(`cannot find ast in ovm compiler output`) } // Each value is an array of {length, start} for (const [i, ref] of value.entries()) { const ovmRef = ovmValue[i] if (ref.length !== ovmRef.length) { throw new Error(`length mismatch`) } // Get the value from the contract code const immutable = ethers.utils.hexDataSlice( add0x(account.code), ovmRef.start, ovmRef.start + ovmRef.length ) const pre = ethers.utils.hexDataSlice(bytecode, 0, ref.start) const post = ethers.utils.hexDataSlice( bytecode, ref.start + ref.length ) // Make a note of the original bytecode length so we can confirm it doesn't change const bytecodeLength = bytecode.length // Assign to the global bytecode variable bytecode = ethers.utils.hexConcat([pre, immutable, post]) if (bytecode.length !== bytecodeLength) { throw new Error( `mismatch in size: ${bytecode.length} vs ${bytecodeLength}` ) } } } } // Handle migrating storage slots if (account.storage) { for (const [key, value] of Object.entries(account.storage)) { for (const pool of data.pools) { // Turn into hex string or hexStringIncludes will throw const val = add0x(value) if (hexStringIncludes(val, pool.oldAddress)) { console.log( `found unexpected reference to pool address ${val} in ${account.address}` ) const regex = new RegExp( remove0x(pool.oldAddress).toLowerCase(), 'g' ) account.storage[key] = value.replace( regex, remove0x(pool.newAddress).toLowerCase() ) console.log(`updated to ${account.storage[key]}`) } if (hexStringIncludes(val, POOL_INIT_CODE_HASH_OPTIMISM)) { throw new Error( `found unexpected reference to mainnet pool init code hash` ) } if (hexStringIncludes(val, POOL_INIT_CODE_HASH_OPTIMISM_KOVAN)) { throw new Error( `found unexpected reference to kovan pool init code hash` ) } } if (data.poolHashCache[key]) { const cached = data.poolHashCache[key] console.log( `fixing single-level mapping in contract`, `address=${account.address}`, `pool=${cached.pool.oldAddress}`, `slot=${key}` ) transferStorageSlot({ account, oldSlot: key, newSlot: getMappingKey([cached.pool.newAddress], cached.index), }) } } } return { ...account, code: bytecode, } }, [AccountType.ERC20]: async (account) => { throw new Error( `Unexpected ERC20 classification, this should never happen: ${account.address}` ) }, }
the_stack
import { ANTLRInputStream, CommonTokenStream } from 'antlr4ts'; import * as Lexer from './TomLexer'; import * as Parser from './TomParser'; import * as _ from 'lodash'; export class XDoc { private parser: Parser.TomParser constructor(source: string) { this.parser = new Parser.TomParser(new CommonTokenStream( new Lexer.TomLexer( new ANTLRInputStream(source) ) )); } parse() { return this.parser.documentation(); } static toJSON(ast: Parser.DocumentationContext) { return parseDocumentation(ast); } } export default (source: string) => { // Get the input stream return new XDoc(source).parse(); } /*! Documentation */ /* Parses the Documentation production. # API ``` @function parseDocumentation @param node: Parser.DocumentationContext - The documentation context node. @return Parser.BodyContext[] - The body context nodes. ``` # Remark Documentation is the root node. A documentation node has a body as its child. */ function parseDocumentation(node: Parser.DocumentationContext) { if (node.body()) { return parseBody(node.body()); } } /* Parses the Body production. # API ``` @function parseBody @param node: Parser.BodyContext - The body context node. @return Parser.Annotations[] - The body context nodes. ``` # Remark A body node has an array of annotation nodes. */ function parseBody(node: Parser.BodyContext) { if (node.annotations()) { return parseAnnotations(node.annotations()); } } /* Parses the Annotations production. # API ``` @function parseAnnotations @param node: Parser.AnnotationsContext - The annotation context node. @return Parser.TagContext[] - The tag context nodes. ``` # Remark An annotation node has an array of tag nodes. */ function parseAnnotations(node: Parser.AnnotationsContext) { return node.tag() .map(parseTag) .filter(x => x !== undefined); } /* Parses the Tag production. # API ``` @function parseTag @param node: Parser.TagContext - The annotation context node. @return: { name?: string, id?: {}, value?: {}, type?: {}, description?: {} } | undefined - The tag object or undefined if no leaf exists. ``` # Remark A TagContext node may have a tag name, tag id, value, type, and description. */ function parseTag(node: Parser.TagContext) { let tag = {}; if (node.tagName()) { _.assign(tag, { name: node.tagName().identifier().ID().text }); } if (node.type()) { _.assign(tag, { type: parseType(node.type()) }); } if (node.tagID()) { _.assign(tag, { identifier: parseTagID(node.tagID()) }) } if (node.value()) { _.assign(tag, { value: parseValue(node.value()) }) } if (node.description()) { _.assign(tag, { description: parseDescription(node.description()) }); } return _.isEqual(tag, {}) ? undefined : tag; } /* Parses the TagID production. # API ``` @function parseTagID @param node: Parser.TagIDContext - The tagID context node. @return: { id?: {}, optional: boolean, property?: {} } - The tagID object or undefined if no leaf exists. ``` # Remark A TagId node is an object. */ function parseTagID(node: Parser.TagIDContext) { let tag = { id: undefined, optional: false, property: [] }; if (node.identifier()) { tag.id = node.identifier().ID().text; } if (node.optionalTagID()) { tag.id = node.optionalTagID().identifier().ID().text; tag.optional = true; } if (node.propertyTagID()) { return parsePropertyTagID(node.propertyTagID()); } return tag; } /* Parses the PropertyTagID production. # API ``` @function parsePropertyTagID @param node: Parser.PropertyTagIDContext - The annotation context node. @return: { id: any, optional: any, property: any } - The PropertyTagId object . ``` # Remark A propertyTagID is an object with an 'id', 'property', and 'optional' key. */ function parsePropertyTagID(node: Parser.PropertyTagIDContext) { let tag: any = {}; if (node.identifier()) { _.assign(tag, { id: node.identifier().ID().text }); } if (node.optionalTagID()) { _.assign(tag, { id: node.identifier().ID().text, optional: true }); } if (node.optionalTagOrIdentifier()) { let property = node.optionalTagOrIdentifier() .map(parseOptionalTagOrIdentifier); property.unshift({ id: tag.id, optional: tag.optional }); property = property.filter(p => p.id !== undefined && p !== undefined); _.assign(tag, { property }); } return tag; } /* Parses the OptionalOrIdentifier production. # API ``` @function parseOptionalTagOrIdentifier @param node: Parser.OptionalTagOrIdentifierContext - The OptionalTagOrIdentifier context node. @return: { id?: string, optional?: boolean } - The OptionalTagOrIdentifierContext object. ``` # Remark An OptionalTagOrIdentifer is an object with an 'id' and 'optional' key. */ function parseOptionalTagOrIdentifier(node: Parser.OptionalTagOrIdentifierContext) { let id, optional = false; if (node.identifier()) { id = node.identifier().ID().text; } if (node.optionalTagID()) { id = node.optionalTagID().identifier().ID().text; optional = true; } return { id, optional }; } /*! Type */ /* Parses the Type production. # API ``` @function parseType @param node: Parse.TypeContext - The Type context node. @return: { intersect?: {}, union?: {}, lambda?: {}, tuple?: {}, primary?: {} } - The type object. # Remark A type is an object with 'intersection', 'union', 'lambda', 'tuple', or primary. ``` */ function parseType(node: Parser.TypeContext) { if (node.PIPE()) { // Intersections return { intersect: { left: parseType(node.type(0)), right: parseType(node.type(1)) } }; } if (node.AMP()) { // Unions return { union: { left: parseType(node.type(0)), right: parseType(node.type(1)) } }; } if (node.lambdaType()) { // Lambda functions i.e. (id) => type return { lambda: parseLambdaType(node.lambdaType()) }; } if (node.tupleType()) { // id<type, type> return { tuple: parseTuple(node.tupleType()) } } if (node.primaryType()) { // Primary return { primary: parsePrimaryType(node.primaryType()) }; } if (node.parenthesizedType()) { // (expression) return { parenthesized: parseParenthesizedType(node.parenthesizedType()) } } if (node.unaryType()) { return { unary: parseUnaryType(node.unaryType()) } } if (node.objectType()) { // { ... } return { object: parseObjectType(node.objectType()) } } if (node.arrayType()) { // [ ... ] return { array: parseArrayType(node.arrayType()) } } if (node.propertyType()) { return { property: parsePropertyType(node.propertyType()) } } } /*! Lambda */ function parseLambdaType(node: Parser.LambdaTypeContext) { let obj = { parameter: [] }; if (node.formalParameterSequence()) { _.assign(obj, { parameter: parseLambdaFormalParameterSequence(node.formalParameterSequence()) }) } else if (node.parameter()) { _.assign(obj, { parameter: [parseParameter(node.parameter())] }) } if (node.type()) { _.assign(obj, { type: parseType(node.type()) }) } return obj; } function parseLambdaFormalParameterSequence(node: Parser.FormalParameterSequenceContext) { return parseParameters(node.parameter()) } function parseParameters(nodes: Parser.ParameterContext[]) { return nodes.map(node => { return parseParameter(node); }) } function parseParameter(node: Parser.ParameterContext) { let id = node.identifier().ID().text; if (node.type()) { return { id, type: parseType(node.type()) } } return { id }; } function parseTuple(node: Parser.TupleTypeContext) { let type = {}; if (node.identifier()) { _.assign(type, { id: node.identifier().ID().text }); } if (node.tupleTypeList()) { _.assign(type, { types: parseTupleTypeList(node.tupleTypeList()) }) } return type; } function parseTupleTypeList(node: Parser.TupleTypeListContext) { return node.type() ? node.type().map(type => parseType(type)) : []; } function parsePrimaryType(node: Parser.PrimaryTypeContext) { if (node.optionalType()) { return { id: node.optionalType().identifier().ID().text, optional: true } } if (node.identifierOrKeyword()) { return { id: parseIdentifierOrKeyword(node.identifierOrKeyword()), optional: false } } } function parseParenthesizedType(node: Parser.ParenthesizedTypeContext) { if (node.type()) { return parseType(node.type()); } } function parseObjectType(node: Parser.ObjectTypeContext) { return node.objectPairTypeList() ? parseObjectPairTypeList(node.objectPairTypeList()) : [] } function parseObjectPairTypeList(node: Parser.ObjectPairTypeListContext) { return (node.objectPairType() || []).map(pair => { return { key: parseType(pair.type(0)), value: parseType(pair.type(1)) } }); } function parseArrayType(node: Parser.ArrayTypeContext) { if (node.type()) { return { type: node.type().map(type => parseType(type)) } } if (node.identifier()) { return { identifer: node.identifier().ID().text + '[]' } } } /* Parses the PropertyTagID production. # API ``` @function parsePropertyTagID @param node: Parser.PropertyTagIDContext - The annotation context node. @return { id: any, optional: any, property: any } - The PropertyTagId object . ``` # Remark A propertyTagID is an object with an 'id', 'property', and 'optional' keys. */ function parsePropertyType(node: Parser.PropertyTypeContext) { let tag: any = {}; if (node.identifier()) { _.assign(tag, { id: node.identifier().ID().text }); } if (node.optionalType()) { _.assign(tag, { id: node.identifier().ID().text }); _.assign(tag, { optional: true }); } if (node.optionalTypeOrIdentifer()) { _.assign(tag, { property: node.optionalTypeOrIdentifer() .map(parseOptionalTypeOrIdentifer) }); tag.property.unshift({ id: tag.id, optional: tag.optional }); tag.property = tag.property.filter(x => x.id !== undefined && x !== undefined); tag.id = tag.optional = undefined; } return tag; } /* Parses the parseOptionalTypeOrIdentifer production. # API ``` @function OptionalTypeOrIdentiferContext @param node: Parser.OptionalTypeOrIdentiferContext - The OptionalTypeOrIdentifer context node. @return { id?: string, optional?: boolean } - The OptionalTypeOrIdentiferContext object. ``` # Remark An propertyType is an object with an 'id', 'property', and 'optional' keys. */ function parseOptionalTypeOrIdentifer(node: Parser.OptionalTypeOrIdentiferContext) { let id: string, optional: boolean = false; if (node.identifier()) { id = node.identifier().ID().text; } if (node.optionalType()) { id = node.optionalType().identifier().ID().text; optional = true; } return { id, optional }; } function parseIdentifierOrKeyword(node: Parser.IdentifierOrKeywordContext) { if (node.identifier()) { return node.identifier().ID().text; } if (node.NullLiteral()) { return node.NullLiteral().text; } } function parseUnaryType(node: Parser.UnaryTypeContext) { return { left: (node.AMP() || node.STAR()).text, right: { primary: parsePrimaryType(node.primaryType())} } } /*! Value */ /* Parses the Value production. # API ``` @function parseValue @param node: Parser.ValueContext @return Parser.ValueContext - See {@link #parseExpression(node: Parser.ExpressionContext) }. ``` # Remark A value is an expression. */ function parseValue(node: Parser.ValueContext) { if (node.expression()) { return parseExpression(node.expression()); } } /*! Expression */ /* Parses the Expression production. # API ``` @function parseExpression @param node: Parser.ExpressionContext @return { unary?: {}, binary?: {}, array?: {}, object?: {}, literal?: {}, parenthesized?: {} } ``` */ function parseExpression(node: Parser.ExpressionContext) { if (node.unaryExpression()) { return { unary: parseUnaryExpression(node.unaryExpression()) } } if (node.expression()) { if (node.PLUS() || node.MINUS()) { return { binary: parseAdditionExpression(node) }; } if (node.STAR() || node.FORWARD_SLASH()) { return { binary: parseMultiplicationExpression(node) }; } } if (node.arrayExpression()) { return { array: parseArrayExpression(node.arrayExpression()) } } if (node.objectExpression()) { return { object: parseObjectExpression(node.objectExpression()) } } if (node.lambdaExpression()) { return { lambda: parseLambdaExpression(node.lambdaExpression()) } } if (node.literal()) { return { literal: parseLiteralExpression(node.literal()) } } if (node.parenthesizedExpression()) { return { parenthesized: parseParenthesizedExpression(node.parenthesizedExpression()) } } return {} } /* */ function parseUnaryExpression(node: Parser.UnaryExpressionContext) { return { left: (node.PLUS() || node.MINUS()).text, right: parseExpression(node.expression()) }; } function parseAdditionExpression(node: Parser.ExpressionContext) { if (node.PLUS()) { return { plus: { left: parseExpression(node.expression(0)), right: parseExpression(node.expression(1)) } } } if (node.MINUS()) { return { minus: { left: parseExpression(node.expression(0)), right: parseExpression(node.expression(1)) } } } } function parseMultiplicationExpression(node: Parser.ExpressionContext) { if (node.STAR()) { return { times: { left: parseExpression(node.expression(0)), right: parseExpression(node.expression(1)) } } } if (node.FORWARD_SLASH()) { return { divide: { left: parseExpression(node.expression(0)), right: parseExpression(node.expression(1)) } } } } function parseArrayExpression(node: Parser.ArrayExpressionContext) { if (node.expression()) { return node.expression().map(expression => { return parseExpression(expression) }); } return [] } function parseObjectExpression(node: Parser.ObjectExpressionContext) { return node.objectPairExpressionList() ? parseObjectPairExpressionList(node.objectPairExpressionList()) : []; } function parseObjectPairExpressionList(node: Parser.ObjectPairExpressionListContext) { return node.objectPairExpression().map(pair => { return { key: parseLiteralExpression(pair.literal(0)), value: pair.objectExpression() ? parseObjectExpression(pair.objectExpression()) : parseLiteralExpression(pair.literal(1)) } }); } function parseLambdaExpression(node: Parser.LambdaExpressionContext) { let result: any = parseLambdaType(node); _.assign(result.type, { optional: !!node.QUESTION() }) return result; } function parseParenthesizedExpression(node: Parser.ParenthesizedExpressionContext) { return parseExpression(node.expression()); } function parseLiteralExpression(node: Parser.LiteralContext) { if (node.IntegerLiteral() || node.FloatingPointLiteral()) { return { number: (node.IntegerLiteral() || node.FloatingPointLiteral()).text } } if (node.BooleanLiteral()) { return { boolean: node.BooleanLiteral().text } } if (node.CharacterLiteral()) { return { character: node.CharacterLiteral().text } } if (node.StringLiteral()) { return { string: node.StringLiteral().text } } if (node.StringLiteral()) { return { null: node.StringLiteral().text } } } /*! Description */ function parseDescription(node: Parser.DescriptionContext) { return { text: node.text, inlines: parseDescriptionLine(node.descriptionLine()) } } function parseDescriptionLine(node: Parser.DescriptionLineContext) { return parseDescriptionLineElement(node.descriptionLineElement()); } function parseDescriptionLineElement(node: Parser.DescriptionLineElementContext[]) { return node.map(element => { return element.inlineTag() ? parseInlineTag(element.inlineTag()) : undefined }).filter(element => element !== undefined); } function parseInlineTag(node: Parser.InlineTagContext) { return { id: node.inlineTagName().identifier().ID().text, body: parseInlineTagBody(node.inlineTagBody()) } } function parseInlineTagBody(node: Parser.InlineTagBodyContext) { return node.braceBody().map(body => body.text).join(''); }
the_stack
import { Buffer } from 'buffer'; import { RSA_PKCS1_PADDING } from 'constants'; import { publicEncrypt } from 'crypto'; import { promises } from 'fs'; import { resolve } from 'path'; import { AccountBalanceInterface, AccountBalanceResponseInterface, AuthorizeResponseInterface, B2CInterface, B2CResponseInterface, C2BRegisterInterface, C2BRegisterResponseInterface, C2BSimulateInterface, C2BSimulateResponseInterface, CredentialsInterface, ReversalInterface, ReversalResponseInterface, StkPushInterface, StkPushResponseInterface, StkQueryInterface, StkQueryResponseInterface, TransactionStatusInterface, TransactionStatusResponseInterface, } from './models/interfaces'; import { routes } from './routes'; import { HttpService } from './services/http.service'; export class Mpesa { private http: HttpService; private environment: string; private clientKey: string; private clientSecret: string; private securityCredential: string; constructor( { clientKey, clientSecret, securityCredential, initiatorPassword, certificatePath, }: CredentialsInterface, environment: 'production' | 'sandbox', ) { this.clientKey = clientKey; this.clientSecret = clientSecret; this.http = new HttpService({ baseURL: environment === 'production' ? routes.production : routes.sandbox, headers: { 'Content-Type': 'application/json' }, }); if (!securityCredential && !initiatorPassword) { throw new Error( 'You must provide either the security credential or initiator password. Both cannot be null', ); } if (!securityCredential) { this.generateSecurityCredential(initiatorPassword, certificatePath); } else { this.securityCredential = securityCredential; } } private async authenticate(): Promise<string> { const response = await this.http.get<AuthorizeResponseInterface>( routes.oauth, { headers: { Authorization: 'Basic ' + Buffer.from(this.clientKey + ':' + this.clientSecret).toString( 'base64', ), }, }, ); return response.data.access_token; } private async generateSecurityCredential( password: string, certificatePath: string, ) { let certificate: string; if (certificatePath != null) { const certificateBuffer = await promises.readFile(certificatePath); certificate = String(certificateBuffer); } else { const certificateBuffer = await promises.readFile( resolve( __dirname, this.environment === 'production' ? 'keys/production-cert.cer' : 'keys/sandbox-cert.cer', ), ); certificate = String(certificateBuffer); } this.securityCredential = publicEncrypt( { key: certificate, padding: RSA_PKCS1_PADDING, }, Buffer.from(password), ).toString('base64'); } /** * C2B Register * * @name C2BRegister * * @description The C2B Register URL API registers the 3rd party’s confirmation and validation URLs to M-Pesa ; which then maps these URLs to the 3rd party shortcode. Whenever M-Pesa receives a transaction on the shortcode, M-Pesa triggers a validation request against the validation URL and the 3rd party system responds to M-Pesa with a validation response (either a success or an error code). The response expected is the success code the 3rd party. * M-Pesa completes or cancels the transaction depending on the validation response it receives from the 3rd party system. A confirmation request of the transaction is then sent by M-Pesa through the confirmation URL back to the 3rd party which then should respond with a success acknowledging the confirmation. * The 3rd party resource URLs for both confirmation and validation must be HTTPS in production. Validation is an optional feature that needs to be activated on M-Pesa, the owner of the shortcode needs to make this request for activation. * @see {@link https://developer.safaricom.co.ke/docs?javascript#c2b-api } * @param {C2BRegisterInterface} data Data * @param {string} data.ValidationURLValidation URL for the client. * @param {string} data.ConfirmationURL Confirmation URL for the client. * @param {string} data.ResponseType Default response type for timeout. Can either be `Completed` or `Cancelled` * @param {string} data.ShortCode The short code of the organization. * @returns {Promise} Returns a Promise with data from Safaricom if successful Returns */ public async c2bRegister({ ShortCode, ResponseType, ConfirmationURL, ValidationURL, }: C2BRegisterInterface): Promise<C2BRegisterResponseInterface> { const token = await this.authenticate(); const response = await this.http.post<C2BRegisterResponseInterface>( routes.c2bregister, { ShortCode, ResponseType, ConfirmationURL, ValidationURL }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * C2B Simulate * * @name C2BSimulate * * @description C2B Simulate * @see {@link https://developer.safaricom.co.ke/docs?javascript#c2b-api } * @param {C2BSimulateInterface} data Data * @param {string} data.CommandID Unique command for each transaction type. * @param {number} data.Amount The amount been transacted. * @param {string} data.Msisdn MSISDN (phone number) sending the transaction, start with country code without the plus(+) sign. * @param {any} data.BillRefNumber Bill Reference Number. * @param {string} data.ShortCode 6 digit M-Pesa Till Number or PayBill Number * @returns {Promise} Returns a Promise with data from Safaricom if successful Promise */ public async c2bSimulate({ ShortCode, CommandID, Amount, Msisdn, BillRefNumber, }: C2BSimulateInterface): Promise<C2BSimulateResponseInterface> { const token = await this.authenticate(); const response = await this.http.post<C2BSimulateResponseInterface>( routes.c2bsimulate, { ShortCode, CommandID, Amount, Msisdn, BillRefNumber: BillRefNumber ?? 'account', }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * Transaction Status * * @name Transaction Status * * @description Transaction Status API checks the status of a B2B, B2C and C2B APIs transactions. * @see {@link https://developer.safaricom.co.ke/docs#transaction-status } * @param {TransactionStatusInterface} data Data * @param {string} data.Initiator The name of Initiator to initiating the request. * @param {string} data.SecurityCredential Encrypted Credential of user getting transaction status. * @param {string} data.CommandID only 'TransactionStatusQuery' command id. * @param {string} data.TransactionID Unique identifier to identify a transaction on M-Pesa. * @param {string} data.PartyA Organization’s shortcode initiating the transaction. * @param {any|number} data.IdentifierType - Type of organization receiving the transaction * @param {string} data.ResultURL The end-point that receives the response of the transaction * @param {string} data.QueueTimeOutURL The timeout end-point that receives a timeout response. * @param {string} data.Remarks Comments that are sent along with the transaction. * @param {string} data.Occasion Optional * @returns {Promise} Returns a Promise with data from Safaricom if successful Promise */ public async transactionStatus({ Initiator, CommandID, TransactionID, PartyA, IdentifierType, ResultURL, QueueTimeOutURL, Remarks, Occasion, }: TransactionStatusInterface): Promise<TransactionStatusResponseInterface> { const token = await this.authenticate(); const response = await this.http.post<TransactionStatusResponseInterface>( routes.transactionstatus, { Initiator, SecurityCredential: this.securityCredential, CommandID: CommandID ?? 'TransactionStatusQuery', TransactionID, PartyA, IdentifierType, ResultURL, QueueTimeOutURL, Remarks: Remarks ?? 'Transaction Status', Occasion: Occasion ?? 'TransactionStatus', }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * Business to Customer(B2C) * * @name B2C * * @description This API enables Business to Customer (B2C) transactions between a company and customers who are the end-users of its products or services. Use of this API requires a valid and verified B2C M-Pesa Short code. * @see {@link https://developer.safaricom.co.ke/docs?javascript#b2c-api } * @param {B2CInterface} data Data * @param {string} data.InitiatorName This is the credential/username used to authenticate the transaction request. * @param {string} data.CommandID Unique command for each transaction type e.g. SalaryPayment, BusinessPayment, PromotionPayment. * @param {number} data.Amount The amount being transacted * @param {string} data.PartyA Organization’s shortcode initiating the transaction. * @param {string} data.PartyB Phone number receiving the transaction * @param {string} data.Remarks Comments that are sent along with the transaction. * @param {string} data.QueueTimeOutURL The timeout end-point that receives a timeout response. * @param {string} data.ResultURL The end-point that receives the response of the transaction * @param {string} data.Occasion Optional * @returns {Promise} Returns a Promise with data from Safaricom if successful */ public async b2c({ Initiator, CommandID, Amount, PartyA, PartyB, Remarks, QueueTimeOutURL, ResultURL, Occasion, }: B2CInterface): Promise<B2CResponseInterface> { const token = await this.authenticate(); const response = await this.http.post<B2CResponseInterface>( routes.b2c, { InitiatorName: Initiator, SecurityCredential: this.securityCredential, CommandID: CommandID, Amount: Amount, PartyA: PartyA, PartyB: PartyB, Remarks: Remarks ?? 'account', QueueTimeOutURL: QueueTimeOutURL, ResultURL: ResultURL, Occasion: Occasion ?? 'account', }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * Lipa na Mpesa Online * * @name Lipa Na Mpesa Online * * @description Lipa na M-Pesa Online Payment API is used to initiate a M-Pesa transaction on behalf of a customer using STK Push. This is the same technique mySafaricom App uses whenever the app is used to make payments. * @see {@link https://developer.safaricom.co.ke/docs?javascript#lipa-na-m-pesa-online-payment } * @param {StkPushInterface} data Data * @param {string} data.BusinessShortCode The organization shortcode used to receive the transaction. * @param {number} data.Amount The amount to be transacted. * @param {string} data.PartyA The MSISDN sending the funds. * @param {string} data.PartyB The organization shortcode receiving the funds * @param {string} data.PhoneNumber The MSISDN sending the funds. * @param {string} data.CallBackURL The url to where responses from M-Pesa will be sent to. * @param {string} data.AccountReference Used with M-Pesa PayBills. * @param {string} data.TransactionDesc A description of the transaction. * @param {any} data.passKey Lipa Na Mpesa Pass Key * @returns {Promise} Returns a Promise with data from Safaricom if successful */ public async lipaNaMpesaOnline({ BusinessShortCode, passKey, TransactionDesc, TransactionType, PartyA, PartyB, Amount, AccountReference, CallBackURL, PhoneNumber, }: StkPushInterface): Promise<StkPushResponseInterface> { const Timestamp = new Date() .toISOString() .replace(/[^0-9]/g, '') .slice(0, -3); const Password = Buffer.from( BusinessShortCode + passKey + Timestamp, ).toString('base64'); const token = await this.authenticate(); const response = await this.http.post<StkPushResponseInterface>( routes.stkpush, { BusinessShortCode, Password, Timestamp, TransactionType: TransactionType ?? 'CustomerPayBillOnline ', Amount, PartyA, PartyB, PhoneNumber, CallBackURL, AccountReference, TransactionDesc: TransactionDesc ?? 'Lipa Na Mpesa Online', }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * Lipa na Mpesa Online * * @name StkQuery * * @description Lipa na M-Pesa Online Query is used to check for Payment status. * @see {@link https://developer.safaricom.co.ke/docs?javascript#lipa-na-m-pesa-online-query-request } * @param {StkQueryInterface} data Data * @param {string} data.BusinessShortCode The organization shortcode used to receive the transaction. * @param {number} data.CheckoutRequestID Check out Request ID. * @param {any} data.passKey Lipa Na Mpesa Pass Key * @returns {Promise} Returns a Promise with data from Safaricom if successful */ public async lipaNaMpesaQuery({ BusinessShortCode, passKey, CheckoutRequestID, }: StkQueryInterface): Promise<StkQueryResponseInterface> { const Timestamp = new Date() .toISOString() .replace(/[^0-9]/g, '') .slice(0, -3); const Password = Buffer.from( BusinessShortCode + passKey + Timestamp, ).toString('base64'); const token = await this.authenticate(); const response = await this.http.post<StkQueryResponseInterface>( routes.stkquery, { BusinessShortCode, Password, Timestamp, CheckoutRequestID, }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * Reversal Request * * @name ReversalRequest * * @description Transaction Reversal API reverses a M-Pesa transaction. * @see {@link https://developer.safaricom.co.ke/reversal/apis/post/request| Reversal Request} * @param {ReversalInterface} data Data * @param {string} data.Initiator The name of Initiator to initiating the request * @param {string} data.TransactionID The transaction id for reversal eg QLXXXX1234 * @param {string} data.CommandID Takes only 'TransactionReversal' Command id * @param {string} data.QueueTimeOutURL The path that stores information of time out transaction * @param {string} data.ReceiverParty Organization receiving the transaction * @param {number} data.RecieverIdentifierType Type of organization receiving the transaction * @param {string} data.ResultURL The path that stores information of transaction * @param {string} data.Remarks Comments that are sent along with the transaction. * @param {string} data.Occasion Optional Parameter * @returns {Promise} Returns a Promise with data from Safaricom if successful */ public async reversal({ Initiator, CommandID, TransactionID, Amount, ReceiverParty, RecieverIdentifierType, ResultURL, QueueTimeOutURL, Remarks, Occasion, }: ReversalInterface): Promise<ReversalResponseInterface> { const token = await this.authenticate(); const response = await this.http.post<ReversalResponseInterface>( routes.reversal, { Initiator, SecurityCredential: this.securityCredential, CommandID: CommandID ?? 'TransactionReversal', TransactionID, Amount, ReceiverParty, RecieverIdentifierType: RecieverIdentifierType ?? '4', ResultURL, QueueTimeOutURL, Remarks: Remarks ?? 'Transaction Reversal', Occasion: Occasion ?? 'TransactionReversal', }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } /** * Account Balance * * @name AccountBalance * * @description The Account Balance API requests for the account balance of a shortcode. * @see {@link https://developer.safaricom.co.ke/docs?javascript#account-balance-api } * @param {AccountBalanceInterface} data Data * @param {string} data.Initiator This is the credential/username used to authenticate the transaction request. * @param {string} data.SecurityCredential Base64 encoded string of the Security Credential, which is encrypted using M-Pesa public key and validates the transaction on M-Pesa Core system. * @param {string} data.CommandID A unique command passed to the M-Pesa system. * @param {string} data.PartyA The shortcode of the organisation initiating the transaction. * @param {string} data.IdentifierType Type of the organisation receiving the transaction. * @param {string} data.Remarks Comments that are sent along with the transaction. * @param {string} data.QueueTimeOutURL The timeout end-point that receives a timeout message. * @param {string} data.ResultURL The end-point that receives a successful transaction. * @returns {Promise} Returns a Promise with data from Safaricom if successful */ public async accountBalance({ Initiator, CommandID, PartyA, IdentifierType, Remarks, QueueTimeOutURL, ResultURL, }: AccountBalanceInterface): Promise<AccountBalanceResponseInterface> { const token = await this.authenticate(); const response = await this.http.post<AccountBalanceResponseInterface>( routes.accountbalance, { Initiator, SecurityCredential: this.securityCredential, CommandID: CommandID ?? 'AccountBalance', PartyA, IdentifierType: IdentifierType ?? '4', Remarks: Remarks ?? 'Account Balance', QueueTimeOutURL, ResultURL, }, { headers: { Authorization: 'Bearer ' + token, }, }, ); return response.data; } }
the_stack
import * as fse from "fs-extra" import os from "os" import path, { join } from "path" import { ExifDateTime } from "./ExifDateTime" import { exiftool, ExifTool } from "./ExifTool" import { ReadTask } from "./ReadTask" import { Tags } from "./Tags" import { expect, isWin32, renderTagsWithISO, renderTagsWithRawValues, testDir, } from "./_chai.spec" function parse({ tags, error, SourceFile = "/tmp/example.jpg", numericTags = [], optionalArgs = [], }: { tags: any error?: Error SourceFile?: string numericTags?: never[] optionalArgs?: never[] }): Tags { const tt = ReadTask.for(SourceFile, numericTags, optionalArgs) const json = JSON.stringify([{ ...tags, SourceFile }]) return tt.parse(json, error) } after(() => exiftool.end()) describe("ReadTask", () => { describe("Lat/Lon parsing", () => { /* Example: $ exiftool -j -coordFormat '%.8f' -fast ../test-images/important/Apple_iPhone7Plus.jpg | grep itude "GPSLatitudeRef": "North", "GPSLongitudeRef": "East", "GPSAltitudeRef": "Above Sea Level", "GPSAltitude": "73 m Above Sea Level", "GPSLatitude": 22.33543889, "GPSLongitude": 114.16401667, */ it("N lat is positive", () => { expect( parse({ tags: { GPSLatitude: 22.33543889, GPSLatitudeRef: "N" } }) .GPSLatitude ).to.be.closeTo(22.33543889, 0.00001) }) it("S lat is negative", () => { expect( parse({ tags: { GPSLatitude: 33.84842123, GPSLatitudeRef: "S" } }) .GPSLatitude ).to.be.closeTo(-33.84842123, 0.00001) }) it("E lon is positive", () => { expect( parse({ tags: { GPSLongitude: 114.16401667, GPSLongitudeRef: "E" } }) .GPSLongitude ).to.be.closeTo(114.16401667, 0.00001) }) it("W lon is negative", () => { expect( parse({ tags: { GPSLongitude: 122.4406148, GPSLongitudeRef: "W" } }) .GPSLongitude ).to.be.closeTo(-122.4406148, 0.00001) }) it("parses lat lon even if timezone is given", () => { expect( parse({ tags: { GPSLongitude: 122.4406148, GPSLongitudeRef: "West", OffsetTime: "+02:00", }, }).GPSLongitude ).to.be.closeTo(-122.4406148, 0.00001) }) it("extracts problematic GPSDateTime", async () => { const t = await exiftool.read(join(testDir, "nexus5x.jpg")) expect(t).to.containSubset({ MIMEType: "image/jpeg", Make: "LGE", Model: "Nexus 5X", ImageWidth: 16, ImageHeight: 16, tz: "Europe/Zurich", tzSource: "from Lat/Lon", }) const gpsdt = t.GPSDateTime as any as ExifDateTime expect(gpsdt.toString()).to.eql("2016-07-19T10:00:24.000Z") expect(gpsdt.rawValue).to.eql("2016:07:19 10:00:24Z") expect(gpsdt.zoneName).to.eql("UTC") }) describe("without *Ref fields", () => { for (const latSign of [1, -1]) { for (const lonSign of [1, -1]) { const input = { GPSLatitude: latSign * 34.4, GPSLongitude: lonSign * 119.8, } it(`extracts (${JSON.stringify(input)})`, () => { expect(parse({ tags: input })).to.containSubset(input) }) } } }) }) describe("Time zone extraction", () => { it("finds singular positive TimeZoneOffset and sets accordingly", () => { const t = parse({ tags: { TimeZoneOffset: 9, DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(9 * 60) }) it("finds positive array TimeZoneOffset and sets accordingly", () => { const t = parse({ tags: { TimeZoneOffset: [9, 8], DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(9 * 60) }) it("finds zulu TimeZoneOffset and sets accordingly", () => { const t = parse({ tags: { TimeZoneOffset: 0, DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(0) }) it("finds negative TimeZoneOffset in array and sets accordingly", () => { const t = parse({ tags: { TimeZoneOffset: [-4], DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(-4 * 60) }) it("respects positive HH:MM OffsetTime", () => { const t = parse({ tags: { OffsetTime: "+02:30", DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(2 * 60 + 30) }) it("respects positive HH OffsetTime", () => { const t = parse({ tags: { OffsetTime: "+07", DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(7 * 60) }) it("respects negative HH:MM OffsetTime", () => { const t = parse({ tags: { OffsetTime: "-06:30", DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(-(6 * 60 + 30)) }) it("respects negative H OffsetTime", () => { const t = parse({ tags: { OffsetTime: "-9", DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(-9 * 60) expect(t.tz).to.eql("UTC-9") expect(t.tzSource).to.eql("offsetMinutesToZoneName from OffsetTime") }) it("respects negative HH OffsetTime", () => { const t = parse({ tags: { OffsetTime: "-09", DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(-9 * 60) expect(t.tz).to.eql("UTC-9") expect(t.tzSource).to.eql("offsetMinutesToZoneName from OffsetTime") }) it("determines timezone offset from GPS (specifically, Landscape Arch!)", () => { const t = parse({ tags: { GPSLatitude: 38.791121, GPSLatitudeRef: "North", GPSLongitude: 109.606407, GPSLongitudeRef: "West", DateTimeOriginal: "2016:08:12 13:28:50", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(-6 * 60) expect(t.tz).to.eql("America/Denver") expect(t.tzSource).to.eql("from Lat/Lon") }) it("uses GPSDateTime and DateTimeOriginal and sets accordingly for -7", () => { const t = parse({ tags: { DateTimeOriginal: "2016:10:19 11:15:14", GPSDateTime: "2016:10:19 18:15:12", DateTimeCreated: "2016:10:19 11:15:14", }, }) expect((t.DateTimeOriginal as ExifDateTime).tzoffsetMinutes).to.eql( -7 * 60 ) expect((t.DateTimeCreated as ExifDateTime).tzoffsetMinutes).to.eql( -7 * 60 ) expect(t.tz).to.eql("UTC-7") expect(t.tzSource).to.eql( "offset between DateTimeOriginal and GPSDateTime" ) }) it("uses DateTimeUTC and DateTimeOriginal and sets accordingly for +8", () => { const t = parse({ tags: { DateTimeOriginal: "2016:10:19 11:15:14", DateTimeUTC: "2016:10:19 03:15:12", DateTimeCreated: "2016:10:19 11:15:14", }, }) expect((t.DateTimeOriginal as ExifDateTime).tzoffsetMinutes).to.eql( 8 * 60 ) expect((t.DateTimeCreated as ExifDateTime).tzoffsetMinutes).to.eql(8 * 60) expect(t.tz).to.eql("UTC+8") expect(t.tzSource).to.eql( "offset between DateTimeOriginal and DateTimeUTC" ) }) it("uses DateTimeUTC and DateTimeOriginal and sets accordingly for +5:30", () => { const t = parse({ tags: { DateTimeOriginal: "2018:10:19 11:15:14", DateTimeUTC: "2018:10:19 05:45:12", DateTimeCreated: "2018:10:19 11:15:14", }, }) expect((t.DateTimeOriginal as ExifDateTime).tzoffsetMinutes).to.eql( 5.5 * 60 ) expect((t.DateTimeCreated as ExifDateTime).tzoffsetMinutes).to.eql( 5.5 * 60 ) expect(t.tz).to.eql("UTC+5:30") expect(t.tzSource).to.eql( "offset between DateTimeOriginal and DateTimeUTC" ) }) it("renders SubSecDateTimeOriginal with no zone if no tz is inferrable", () => { const input = { DateTimeOriginal: "2016:12:13 09:05:27", SubSecDateTimeOriginal: "2016:12:13 09:05:27.12038200", } const t = parse({ tags: input }) expect(renderTagsWithRawValues(t)).to.eql(input) expect(renderTagsWithISO(t)).to.eql({ DateTimeOriginal: "2016-12-13T09:05:27.000", SubSecDateTimeOriginal: "2016-12-13T09:05:27.120", errors: [], }) }) it("renders SubSecDateTimeOriginal for -8", () => { const input = { DateTimeOriginal: "2016:12:13 09:05:27", GPSDateTime: "2016:12:13 17:05:25Z", SubSecDateTimeOriginal: "2016:12:13 09:05:27.12038200", } const t = parse({ tags: input }) expect(renderTagsWithRawValues(t)).to.eql(input) expect(renderTagsWithISO(t)).to.eql({ DateTimeOriginal: "2016-12-13T09:05:27.000-08:00", GPSDateTime: "2016-12-13T17:05:25.000Z", SubSecDateTimeOriginal: "2016-12-13T09:05:27.120-08:00", errors: [], tz: "UTC-8", tzSource: "offset between SubSecDateTimeOriginal and GPSDateTime", }) }) it("skips invalid timestamps", () => { const t = parse({ tags: { DateTimeOriginal: "2016:08:12 13:28:50", GPSDateTime: "not a timestamp", }, }) expect((t.DateTimeOriginal as any).tzoffsetMinutes).to.eql(undefined) expect(t.tz).to.eql(undefined) expect(t.tzSource).to.eql(undefined) }) describe("timezone normalization", () => { it("normalizes to GMT timezone", () => { const t = parse({ tags: { TimeZone: "+00:00", CreateDate: "2020:08:03 08:00:19-07:00", SubSecCreateDate: "2020:08:03 15:00:19.01+00:00", DateTimeOriginal: "2020:08:03 15:00:19", TimeStamp: "2020:08:03 15:00:19.01", }, }) expect(renderTagsWithISO(t)).to.eql({ // ALL DATES ARE IN ZULU! CreateDate: "2020-08-03T15:00:19.000Z", SubSecCreateDate: "2020-08-03T15:00:19.010Z", DateTimeOriginal: "2020-08-03T15:00:19.000Z", TimeStamp: "2020-08-03T15:00:19.010Z", tz: "UTC", tzSource: "offsetMinutesToZoneName from TimeZone", TimeZone: "+00:00", errors: [], }) }) it("normalizes to CET timezone", () => { const t = parse({ tags: { TimeZone: "+01:00", TimeZoneCity: "Rome", CreateDate: "2020:08:03 08:00:19-07:00", // < different (local system) zone! SubSecCreateDate: "2020:08:03 16:00:19.01+01:00", DateTimeOriginal: "2020:08:03 16:00:19", // < missing zone! TimeStamp: "2020:08:03 16:00:19.01", // < missing zone! }, }) expect(renderTagsWithISO(t)).to.eql({ // NEAT THEY ARE ALL +01:00 NOW YAY CreateDate: "2020-08-03T16:00:19.000+01:00", DateTimeOriginal: "2020-08-03T16:00:19.000+01:00", SubSecCreateDate: "2020-08-03T16:00:19.010+01:00", TimeStamp: "2020-08-03T16:00:19.010+01:00", TimeZone: "+01:00", TimeZoneCity: "Rome", tz: "UTC+1", tzSource: "offsetMinutesToZoneName from TimeZone", errors: [], }) }) it("doesn't normalize if timezone is missing", () => { const t = parse({ tags: { CreateDate: "2020:08:03 08:00:19-07:00", DateTimeOriginal: "2020:08:03 15:00:19", // < no zone! SubSecCreateDate: "2020:08:03 15:00:19.01+00:00", TimeStamp: "2020:08:03 15:00:19.01", // < no zone! }, }) expect(renderTagsWithISO(t)).to.eql({ // No timezone found, so no normalization: CreateDate: "2020-08-03T08:00:19.000-07:00", DateTimeOriginal: "2020-08-03T15:00:19.000", // < no zone! SubSecCreateDate: "2020-08-03T15:00:19.010Z", TimeStamp: "2020-08-03T15:00:19.010", // < no zone! errors: [], }) expect(t.tz).to.eql(undefined) expect(t.tzSource).to.eql(undefined) }) it("normalizes when in EST", () => { const t = parse({ tags: { CreateDate: "2020:12:29 14:24:45", DateTimeOriginal: "2020:12:29 14:24:45", GPSAltitude: 259.016, GPSDateStamp: "2020:12:29", GPSLatitude: 34.15, GPSLongitude: -84.73, ModifyDate: "2020:12:29 14:24:45", OffsetTime: "-05:00", OffsetTimeDigitized: "-05:00", OffsetTimeOriginal: "-05:00", SubSecCreateDate: "2020:12:29 14:24:45.700-05:00", SubSecDateTimeOriginal: "2020:12:29 14:24:45.700-05:00", SubSecModifyDate: "2020:12:29 14:24:45-05:00", SubSecTimeDigitized: 700, SubSecTimeOriginal: 700, }, }) expect(renderTagsWithISO(t)).to.eql({ // Everything normalized to PST: CreateDate: "2020-12-29T14:24:45.000-05:00", DateTimeOriginal: "2020-12-29T14:24:45.000-05:00", SubSecCreateDate: "2020-12-29T14:24:45.700-05:00", SubSecDateTimeOriginal: "2020-12-29T14:24:45.700-05:00", SubSecModifyDate: "2020-12-29T14:24:45.000-05:00", ModifyDate: "2020-12-29T14:24:45.000-05:00", GPSAltitude: 259.016, GPSDateStamp: "2020-12-29", GPSLatitude: 34.15, GPSLongitude: -84.73, OffsetTime: "-05:00", OffsetTimeDigitized: "-05:00", OffsetTimeOriginal: "-05:00", SubSecTimeDigitized: 700, SubSecTimeOriginal: 700, errors: [], tz: "America/New_York", tzSource: "from Lat/Lon", }) }) it("normalizes when in EST with only OffsetTime", () => { const t = parse({ tags: { CreateDate: "2020:12:29 14:24:45", // < no zone DateTimeOriginal: "2020:12:29 14:24:45", // < no zone ModifyDate: "2020:12:29 14:24:45", // < no zone OffsetTime: "-05:00", OffsetTimeDigitized: "-05:00", OffsetTimeOriginal: "-05:00", SubSecCreateDate: "2020:12:29 14:24:45.700-05:00", SubSecDateTimeOriginal: "2020:12:29 14:24:45.700-05:00", SubSecModifyDate: "2020:12:29 14:24:45-05:00", SubSecTimeDigitized: 700, SubSecTimeOriginal: 700, }, }) expect(renderTagsWithISO(t)).to.eql({ // Everything normalized to PST: CreateDate: "2020-12-29T14:24:45.000-05:00", DateTimeOriginal: "2020-12-29T14:24:45.000-05:00", ModifyDate: "2020-12-29T14:24:45.000-05:00", SubSecCreateDate: "2020-12-29T14:24:45.700-05:00", SubSecDateTimeOriginal: "2020-12-29T14:24:45.700-05:00", SubSecModifyDate: "2020-12-29T14:24:45.000-05:00", OffsetTime: "-05:00", OffsetTimeDigitized: "-05:00", OffsetTimeOriginal: "-05:00", SubSecTimeDigitized: 700, SubSecTimeOriginal: 700, errors: [], tz: "UTC-5", tzSource: "offsetMinutesToZoneName from OffsetTime", }) }) }) }) describe("SubSecDateTimeOriginal", () => { it("extracts datetimestamp with millis", () => { const t = parse({ tags: { SubSecDateTimeOriginal: "2016:10:19 11:15:14.437831" }, }).SubSecDateTimeOriginal as ExifDateTime expect(t.year).to.eql(2016) expect(t.month).to.eql(10) expect(t.day).to.eql(19) expect(t.hour).to.eql(11) expect(t.minute).to.eql(15) expect(t.second).to.eql(14) expect(t.tzoffsetMinutes).to.eql(undefined) expect(t.millisecond).to.eql(437) const d = t.toDate() expect(d.getFullYear()).to.eql(2016) expect(d.getMonth()).to.eql(10 - 1) expect(d.getDate()).to.eql(19) expect(d.getHours()).to.eql(11) expect(d.getMinutes()).to.eql(15) expect(d.getSeconds()).to.eql(14) expect(d.getMilliseconds()).to.eql(437) // Javascript Date doesn't do fractional millis. }) }) describe("EXIFTOOL_HOME", () => { let et: ExifTool before( () => (et = new ExifTool({ exiftoolEnv: { EXIFTOOL_HOME: path.resolve(__dirname, "..", "test") }, })) ) after(() => et.end()) it("returns the new custom tag", async () => { const t: any = await et.read("./test/pixel.jpg") // This is a non-standard tag, added by the custom user configuration: expect(t.UppercaseBaseName).to.eql("PIXEL") }) }) describe("quotes in filenames", () => { const base = isWin32() ? `it's a file.jpg` : `it's a "file".jpg` it("reads from " + base, async () => { const tmp = path.join(os.tmpdir(), base) await fse.mkdirp(os.tmpdir()) await fse.copyFile("./test/quotes.jpg", tmp) const t = await exiftool.read(tmp) expect(t.FileName).to.eql(base) expect(t.MIMEType).to.eql("image/jpeg") expect(t.ImageDescription).to.eql("image description for quotes test") expect(t.Keywords).to.eql("quotes") expect(t.DateTimeOriginal?.toString()?.split(/000/)[0]).to.eql( "2016-08-12T13:28:50." ) }) }) })
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormTask { interface Header extends DevKit.Controls.IHeader { /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Enter the expected due date and time. */ ScheduledEnd: DevKit.Controls.DateTime; /** Shows whether the task is open, completed, or canceled. Completed and canceled tasks are read-only and can't be edited. */ StateCode: DevKit.Controls.OptionSet; } interface tab_TASK_TAB_Sections { Description: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; TASK: DevKit.Controls.Section; task_details: DevKit.Controls.Section; } interface tab_TASK_TAB extends DevKit.Controls.ITab { Section: tab_TASK_TAB_Sections; } interface Tabs { TASK_TAB: tab_TASK_TAB; } interface Body { Tab: Tabs; /** Type the number of minutes spent on the task. The duration is used in reporting. */ ActualDurationMinutes: DevKit.Controls.Integer; /** Type additional information to describe the task. */ Description: DevKit.Controls.String; /** Unique identifier of the object with which the task is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Type a short description about the objective or primary topic of the task. */ Subject: DevKit.Controls.String; } } class FormTask extends DevKit.IForm { /** * DynamicsCrm.DevKit form Task * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Task */ Body: DevKit.FormTask.Body; /** The Header section of form Task */ Header: DevKit.FormTask.Header; } namespace FormTask_for_Interactive_experience { interface Header extends DevKit.Controls.IHeader { /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Enter the expected due date and time. */ ScheduledEnd: DevKit.Controls.DateTime; /** Shows whether the task is open, completed, or canceled. Completed and canceled tasks are read-only and can't be edited. */ StateCode: DevKit.Controls.OptionSet; } interface tab_tab_4_Sections { tab_3_section_3: DevKit.Controls.Section; tab_4_section_2: DevKit.Controls.Section; tab_4_section_4: DevKit.Controls.Section; } interface tab_tab_4 extends DevKit.Controls.ITab { Section: tab_tab_4_Sections; } interface Tabs { tab_4: tab_tab_4; } interface Body { Tab: Tabs; /** Type the number of minutes spent on the task. The duration is used in reporting. */ ActualDurationMinutes: DevKit.Controls.Integer; /** Type additional information to describe the task. */ Description: DevKit.Controls.String; /** Unique identifier of the object with which the task is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Unique identifier of the object with which the task is associated. */ RegardingObjectId_1: DevKit.Controls.Lookup; /** Type a short description about the objective or primary topic of the task. */ Subject: DevKit.Controls.String; } } class FormTask_for_Interactive_experience extends DevKit.IForm { /** * DynamicsCrm.DevKit form Task_for_Interactive_experience * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Task_for_Interactive_experience */ Body: DevKit.FormTask_for_Interactive_experience.Body; /** The Header section of form Task_for_Interactive_experience */ Header: DevKit.FormTask_for_Interactive_experience.Header; } namespace FormTask_quick_create_form { interface tab_createtask_Sections { task: DevKit.Controls.Section; task_2: DevKit.Controls.Section; task_3: DevKit.Controls.Section; } interface tab_createtask extends DevKit.Controls.ITab { Section: tab_createtask_Sections; } interface Tabs { createtask: tab_createtask; } interface Body { Tab: Tabs; /** Type the number of minutes spent on the task. The duration is used in reporting. */ ActualDurationMinutes: DevKit.Controls.Integer; /** Type additional information to describe the task. */ Description: DevKit.Controls.String; /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Unique identifier of the object with which the task is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Enter the expected due date and time. */ ScheduledEnd: DevKit.Controls.DateTime; /** Type a short description about the objective or primary topic of the task. */ Subject: DevKit.Controls.String; } } class FormTask_quick_create_form extends DevKit.IForm { /** * DynamicsCrm.DevKit form Task_quick_create_form * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Task_quick_create_form */ Body: DevKit.FormTask_quick_create_form.Body; } class TaskApi { /** * DynamicsCrm.DevKit TaskApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the task. */ ActivityId: DevKit.WebApi.GuidValue; /** Type the number of minutes spent on the task. The duration is used in reporting. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the actual end date and time of the task. By default, it displays when the activity was completed or canceled. */ ActualEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the actual start date and time for the task. By default, it displays when the task was created. */ ActualStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Type a category to identify the task type, such as lead gathering or customer follow up, to tie the task to a business group or function. */ Category: DevKit.WebApi.StringValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Assigned Task Unique Id */ CrmTaskAssignedUniqueId: DevKit.WebApi.GuidValue; /** Type additional information to describe the task. */ Description: DevKit.WebApi.StringValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Information which specifies whether the task was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information which specifies if the task was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Shows the record owner's business unit. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the task. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the task. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Type the percentage complete value for the task to track tasks to completion. */ PercentComplete: DevKit.WebApi.IntegerValue; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Shows the ID of the process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_account_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_bookableresourcebooking_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_bookableresourcebookingheader_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_bulkoperation_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_campaign_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_campaignactivity_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_contact_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_contract_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_entitlement_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_entitlementtemplate_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_incident_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_invoice_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_knowledgearticle_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_knowledgebaserecord_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_lead_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreement_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementbookingdate_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementbookingincident_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementbookingproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementbookingservice_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementbookingsetup_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementinvoicedate_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_bookingalertstatus_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_bookingrule_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_bookingtimestamp_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_customerasset_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_fieldservicesetting_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_incidenttypeproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_incidenttypeservice_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_inventoryadjustment_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_inventoryjournal_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_inventorytransfer_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_payment_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_paymentdetail_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_paymentmethod_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_paymentterm_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_playbookinstance_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_postalbum_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_postalcode_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_processnotes_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_productinventory_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_projectteam_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_purchaseorder_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_purchaseorderbill_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_purchaseorderproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_quotebookingincident_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_quotebookingproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_quotebookingservice_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_quotebookingservicetask_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_resourceterritory_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rma_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rmaproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rmareceipt_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rmareceiptproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rmasubstatus_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rtv_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rtvproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_rtvsubstatus_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_shipvia_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_timegroup_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_timegroupdetail_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_timeoffrequest_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_warehouse_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workorder_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workordercharacteristic_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workorderincident_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workorderproduct_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workorderservice_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_msdyn_workorderservicetask_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_opportunity_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_quote_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_salesorder_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_site_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_action_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_hostedapplication_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_nonhostedapplication_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_option_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_savedsession_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_workflow_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_workflowstep_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the task is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_task: DevKit.WebApi.LookupValue; /** Scheduled duration of the task, specified in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValueReadonly; /** Enter the expected due date and time. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the expected due date and time. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Choose the service that is associated with this activity. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the Task record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this Task. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the ID of the stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the task is open, completed, or canceled. Completed and canceled tasks are read-only and can't be edited. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the task's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Type a subcategory to identify the task type and relate the activity to a specific product, sales region, business group, or other function. */ Subcategory: DevKit.WebApi.StringValue; /** Type a short description about the objective or primary topic of the task. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ SubscriptionId: DevKit.WebApi.GuidValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the task. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Task { enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open } enum StatusCode { /** 6 */ Canceled, /** 5 */ Completed, /** 7 */ Deferred, /** 3 */ In_Progress, /** 2 */ Not_Started, /** 4 */ Waiting_on_someone_else } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Task','Task for Interactive experience','Task quick create form.'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import Service from '@ember/service'; import { getOwner } from '@ember/application'; import DS from 'ember-data'; import { get } from '@ember/object'; import { run } from '@ember/runloop'; import { firestore, database } from 'firebase/app'; // TODO don't hardcode these, but having trouble otherwise import { rootCollection as firestoreRootCollection } from '../adapters/firestore'; import { rootCollection as realtimeDatabaseRootCollection } from '../adapters/realtime-database'; import { resolve } from 'rsvp'; const getService = (object:Object) => getOwner(object).lookup('service:realtime-listener') as RealtimeListenerService; const isFastboot = (object:Object) => { const fastboot = getOwner(object).lookup('service:fastboot'); return fastboot && fastboot.isFastBoot; } export const subscribe = (route: Object, model: DS.Model) => !isFastboot(route) && getService(route).subscribe(route, model); export const unsubscribe = (route: Object, model?: DS.Model) => !isFastboot(route) && getService(route).unsubscribe(route, model); const setRouteSubscription = (service: RealtimeListenerService, route: Object, uniqueIdentifier: string, unsubscribe: () => void) => { const routeSubscriptions = get(service, `routeSubscriptions`); const existingSubscriptions = routeSubscriptions[route.toString()]; if (existingSubscriptions) { const existingSubscription = existingSubscriptions[uniqueIdentifier]; if (existingSubscription) { existingSubscription() } } else { routeSubscriptions[route.toString()] = {}; } routeSubscriptions[route.toString()][uniqueIdentifier] = unsubscribe; } const unsubscribeRoute = (service: RealtimeListenerService, route: Object, uniqueIdentifier?: string) => { const routeSubscriptions = get(service, `routeSubscriptions`); const existingSubscriptions = get(routeSubscriptions, route.toString()); if (existingSubscriptions) { if (uniqueIdentifier) { if (existingSubscriptions[uniqueIdentifier]) { existingSubscriptions[uniqueIdentifier](); delete existingSubscriptions[uniqueIdentifier]; } } else { Object.keys(existingSubscriptions).forEach(key => { existingSubscriptions[key](); }); delete routeSubscriptions[route.toString()]; } } } function isFirestoreDocumentRefernce(arg: any): arg is firestore.DocumentReference { return arg.onSnapshot !== undefined; } export default class RealtimeListenerService extends Service.extend({ routeSubscriptions: {} as {[key:string]: {[key:string]: () => void}} }) { subscribe(route: Object, model: any, parentModel?: any, relationship?:any) { if (!model) { return } const store = model.store as DS.Store; const modelName = (model.get('type.modelName') || model.get('_internalModel.modelName') || model.modelName) as never const modelClass = store.modelFor(modelName) as any; const ref = (model.get('meta._ref') || model.get('_recordData._data._ref') || model.get('_internalModel._recordData._data._ref')) as firestore.DocumentReference|database.Reference|undefined; const uniqueIdentifier = model.toString(); const serializer = store.serializerFor(modelName) as any; // TODO type const adapter = store.adapterFor(modelName); const observeRelationships = (internalModel: any) => { // HACK HACK HACK const movedKey = '__original___updatePromiseProxyFor'; const proxyPromiseListenersKey = `_updatePromiseProxyListeners`; const requestedRelationshipsKey = '_requestedRelationships'; if (!internalModel[requestedRelationshipsKey]) { internalModel[requestedRelationshipsKey] = [] } const movedMethod = internalModel[movedKey]; if (!movedMethod) { internalModel[movedKey] = internalModel._updatePromiseProxyFor; internalModel[proxyPromiseListenersKey] = []; internalModel._updatePromiseProxyFor = ((kind: string, key: string, args: Object) => { const proxy = internalModel[movedKey](kind, key, args); proxy.then((result:any) => { if (internalModel[requestedRelationshipsKey].indexOf(key) < 0) { internalModel[requestedRelationshipsKey] = [...internalModel[requestedRelationshipsKey], key]; internalModel[proxyPromiseListenersKey].forEach((f:any) => f(kind, key, args, result)); } }); return proxy; }) } internalModel[proxyPromiseListenersKey] = [ ...internalModel[proxyPromiseListenersKey], ((_kind: string, key: string, _args: Object, result: any) => { const triggerdRelationship = modelClass.relationshipsObject[key]; this.subscribe(route, result, model, triggerdRelationship); }) ]; } let content = model.content || parentModel && get(parentModel, `${relationship.key}.content`); if (model._internalModel) { observeRelationships(model._internalModel); } else if (content) { // TODO find backing content for hasMany content.forEach((internalModel:any) => { observeRelationships(internalModel); }); } if (ref) { if (isFirestoreDocumentRefernce(ref)) { // Firestore find const unsubscribe = ref.onSnapshot(doc => { run(() => { const normalizedData = serializer.normalizeSingleResponse(store, modelClass, doc); store.push(normalizedData); }); }); setRouteSubscription(this, route, uniqueIdentifier, unsubscribe); } else { // RTDB find const listener = ref.on('value', snapshot => { run(() => { if (snapshot) { if (snapshot.exists()) { const normalizedData = serializer.normalizeSingleResponse(store, modelClass, snapshot); store.push(normalizedData); } else { const record = store.findRecord(modelName, snapshot.key!) if (record) { store.deleteRecord(record) } } } }); }); const unsubscribe = () => ref.off('value', listener); setRouteSubscription(this, route, uniqueIdentifier, unsubscribe); } } else { if (serializer.constructor.name == 'FirestoreSerializer') { // Firestore findAll const query = model.get('meta.query') as firestore.Query|undefined; const queryOrRoot = query && resolve(query) || firestoreRootCollection(adapter, modelName); queryOrRoot.then(query => { const unsubscribe = query.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => run(() => { const normalizedData = serializer.normalizeSingleResponse(store, modelClass, change.doc); switch(change.type) { case 'added': { const current = content.objectAt(change.newIndex); if (current == null || current.id !== change.doc.id ) { const doc = store.push(normalizedData) as any; content.insertAt(change.newIndex, doc._internalModel); } break; } case 'modified': { const current = content.objectAt(change.oldIndex); if (current == null || current.id == change.doc.id) { if (change.newIndex !== change.oldIndex) { content.removeAt(change.oldIndex); content.insertAt(change.newIndex, current) } } store.push(normalizedData); break; } case 'removed': { const current = content.objectAt(change.oldIndex); if (current && current.id == change.doc.id) { content.removeAt(change.oldIndex); } break; } } })) }); setRouteSubscription(this, route, uniqueIdentifier, unsubscribe); }); } else if (serializer.constructor.name == 'RealtimeDatabaseSerializer') { // RTDB findAll const ref = (model.get('meta.query') || model.get('recordData._data._ref')) as database.Reference|undefined; const refOrRoot = ref ? resolve(ref) : realtimeDatabaseRootCollection(adapter, modelName); refOrRoot.then(ref => { const onChildAdded = ref.on('child_added', (snapshot, priorKey) => { run(() => { if (snapshot) { const normalizedData = serializer.normalizeSingleResponse(store, modelClass, snapshot); const doc = store.push(normalizedData) as any; const existing = content.find((record:any) => record.id === doc.id); if (existing) { content.removeObject(existing); } let insertIndex = 0; if (priorKey) { const record = content.find((record:any) => record.id === priorKey); insertIndex = content.indexOf(record) + 1; } const current = content.objectAt(insertIndex); if (current == null || current.id !== doc.id ) { content.insertAt(insertIndex, doc._internalModel); } } }); }); const onChildRemoved = ref.on('child_removed', snapshot => { run(() => { if (snapshot) { const record = content.find((record:any) => record.id === snapshot.key) if (record) { content.removeObject(record); } } }); }); const onChildChanged = ref.on('child_changed', snapshot => { run(() => { if (snapshot) { const normalizedData = serializer.normalizeSingleResponse(store, modelClass, snapshot); store.push(normalizedData); } }); }); const onChildMoved = ref.on('child_moved', (snapshot, priorKey) => { run(() => { if (snapshot) { const normalizedData = serializer.normalizeSingleResponse(store, modelClass, snapshot); const doc = store.push(normalizedData) as any; const existing = content.find((record:any) => record.id === doc.id); if (existing) { content.removeObject(existing); } if (priorKey) { const record = content.find((record:any) => record.id === priorKey); const index = content.indexOf(record); content.insertAt(index+1, doc._internalModel); } else { content.insertAt(0, doc._internalModel); } } }); }); const unsubscribe = () => { ref.off('child_added', onChildAdded); ref.off('child_removed', onChildRemoved); ref.off('child_changed', onChildChanged); ref.off('child_moved', onChildMoved); } setRouteSubscription(this, route, uniqueIdentifier, unsubscribe); }); } } } unsubscribe(route: Object, model?: DS.Model) { unsubscribeRoute(this, route, model && model.toString()); } } declare module '@ember/service' { interface Registry { "realtime-listener": RealtimeListenerService; } }
the_stack
import { expect } from "chai"; import { FirestoreIndexes } from "../../firestore/indexes"; import { FirebaseError } from "../../error"; import * as API from "../../firestore/indexes-api"; import * as Spec from "../../firestore/indexes-spec"; import * as sort from "../../firestore/indexes-sort"; import * as util from "../../firestore/util"; const idx = new FirestoreIndexes(); const VALID_SPEC = { indexes: [ { collectionGroup: "collection", queryScope: "COLLECTION", fields: [ { fieldPath: "foo", order: "ASCENDING" }, { fieldPath: "bar", order: "DESCENDING" }, { fieldPath: "baz", arrayConfig: "CONTAINS" }, ], }, ], fieldOverrides: [ { collectionGroup: "collection", fieldPath: "foo", indexes: [ { order: "ASCENDING", scope: "COLLECTION" }, { arrayConfig: "CONTAINS", scope: "COLLECTION" }, ], }, ], }; describe("IndexValidation", () => { it("should accept a valid v1beta2 index spec", () => { idx.validateSpec(VALID_SPEC); }); it("should not change a valid v1beta2 index spec after upgrade", () => { const upgraded = idx.upgradeOldSpec(VALID_SPEC); expect(upgraded).to.eql(VALID_SPEC); }); it("should accept an empty spec", () => { const empty = { indexes: [], }; idx.validateSpec(idx.upgradeOldSpec(empty)); }); it("should accept a valid v1beta1 index spec after upgrade", () => { idx.validateSpec( idx.upgradeOldSpec({ indexes: [ { collectionId: "collection", fields: [ { fieldPath: "foo", mode: "ASCENDING" }, { fieldPath: "bar", mode: "DESCENDING" }, { fieldPath: "baz", mode: "ARRAY_CONTAINS" }, ], }, ], }) ); }); it("should reject an incomplete index spec", () => { expect(() => { idx.validateSpec({ indexes: [ { collectionGroup: "collection", fields: [ { fieldPath: "foo", order: "ASCENDING" }, { fieldPath: "bar", order: "DESCENDING" }, ], }, ], }); }).to.throw(FirebaseError, /Must contain "queryScope"/); }); it("should reject an overspecified index spec", () => { expect(() => { idx.validateSpec({ indexes: [ { collectionGroup: "collection", queryScope: "COLLECTION", fields: [ { fieldPath: "foo", order: "ASCENDING", arrayConfig: "CONTAINES" }, { fieldPath: "bar", order: "DESCENDING" }, ], }, ], }); }).to.throw(FirebaseError, /Must contain exactly one of "order,arrayConfig"/); }); }); describe("IndexNameParsing", () => { it("should parse an index name correctly", () => { const name = "/projects/myproject/databases/(default)/collectionGroups/collection/indexes/abc123/"; expect(util.parseIndexName(name)).to.eql({ projectId: "myproject", collectionGroupId: "collection", indexId: "abc123", }); }); it("should parse a field name correctly", () => { const name = "/projects/myproject/databases/(default)/collectionGroups/collection/fields/abc123/"; expect(util.parseFieldName(name)).to.eql({ projectId: "myproject", collectionGroupId: "collection", fieldPath: "abc123", }); }); }); describe("IndexSpecMatching", () => { it("should identify a positive index spec match", () => { const apiIndex: API.Index = { name: "/projects/myproject/databases/(default)/collectionGroups/collection/indexes/abc123", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "foo", order: API.Order.ASCENDING }, { fieldPath: "bar", arrayConfig: API.ArrayConfig.CONTAINS }, ], state: API.State.READY, }; const specIndex = { collectionGroup: "collection", queryScope: "COLLECTION", fields: [ { fieldPath: "foo", order: "ASCENDING" }, { fieldPath: "bar", arrayConfig: "CONTAINS" }, ], } as Spec.Index; expect(idx.indexMatchesSpec(apiIndex, specIndex)).to.eql(true); }); it("should identify a negative index spec match", () => { const apiIndex = { name: "/projects/myproject/databases/(default)/collectionGroups/collection/indexes/abc123", queryScope: "COLLECTION", fields: [ { fieldPath: "foo", order: "DESCENDING" }, { fieldPath: "bar", arrayConfig: "CONTAINS" }, ], state: API.State.READY, } as API.Index; const specIndex = { collectionGroup: "collection", queryScope: "COLLECTION", fields: [ { fieldPath: "foo", order: "ASCENDING" }, { fieldPath: "bar", arrayConfig: "CONTAINS" }, ], } as Spec.Index; // The second spec contains ASCENDING where the former contains DESCENDING expect(idx.indexMatchesSpec(apiIndex, specIndex)).to.eql(false); }); it("should identify a positive field spec match", () => { const apiField = { name: "/projects/myproject/databases/(default)/collectionGroups/collection/fields/abc123", indexConfig: { indexes: [ { queryScope: "COLLECTION", fields: [{ fieldPath: "abc123", order: "ASCENDING" }], }, { queryScope: "COLLECTION", fields: [{ fieldPath: "abc123", arrayConfig: "CONTAINS" }], }, ], }, } as API.Field; const specField = { collectionGroup: "collection", fieldPath: "abc123", indexes: [ { order: "ASCENDING", queryScope: "COLLECTION" }, { arrayConfig: "CONTAINS", queryScope: "COLLECTION" }, ], } as Spec.FieldOverride; expect(idx.fieldMatchesSpec(apiField, specField)).to.eql(true); }); it("should match a field spec with all indexes excluded", () => { const apiField = { name: "/projects/myproject/databases/(default)/collectionGroups/collection/fields/abc123", indexConfig: {}, } as API.Field; const specField = { collectionGroup: "collection", fieldPath: "abc123", indexes: [], } as Spec.FieldOverride; expect(idx.fieldMatchesSpec(apiField, specField)).to.eql(true); }); it("should identify a negative field spec match", () => { const apiField = { name: "/projects/myproject/databases/(default)/collectionGroups/collection/fields/abc123", indexConfig: { indexes: [ { queryScope: "COLLECTION", fields: [{ fieldPath: "abc123", order: "ASCENDING" }], }, { queryScope: "COLLECTION", fields: [{ fieldPath: "abc123", arrayConfig: "CONTAINS" }], }, ], }, } as API.Field; const specField = { collectionGroup: "collection", fieldPath: "abc123", indexes: [ { order: "DESCENDING", queryScope: "COLLECTION" }, { arrayConfig: "CONTAINS", queryScope: "COLLECTION" }, ], } as Spec.FieldOverride; // The second spec contains "DESCENDING" where the first contains "ASCENDING" expect(idx.fieldMatchesSpec(apiField, specField)).to.eql(false); }); }); describe("IndexSorting", () => { it("should be able to handle empty arrays", () => { expect(([] as Spec.Index[]).sort(sort.compareSpecIndex)).to.eql([]); expect(([] as Spec.FieldOverride[]).sort(sort.compareFieldOverride)).to.eql([]); expect(([] as API.Index[]).sort(sort.compareApiIndex)).to.eql([]); expect(([] as API.Field[]).sort(sort.compareApiField)).to.eql([]); }); it("should correctly sort an array of Spec indexes", () => { // Sorts first because of collectionGroup const a: Spec.Index = { collectionGroup: "collectionA", queryScope: API.QueryScope.COLLECTION, fields: [], }; // fieldA ASCENDING should sort before fieldA DESCENDING const b: Spec.Index = { collectionGroup: "collectionB", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldA", order: API.Order.ASCENDING, }, ], }; // This compound index sorts before the following simple // index because the first element sorts first. const c: Spec.Index = { collectionGroup: "collectionB", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldA", order: API.Order.ASCENDING, }, { fieldPath: "fieldB", order: API.Order.ASCENDING, }, ], }; const d: Spec.Index = { collectionGroup: "collectionB", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldB", order: API.Order.ASCENDING, }, ], }; const e: Spec.Index = { collectionGroup: "collectionB", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldB", order: API.Order.ASCENDING, }, { fieldPath: "fieldA", order: API.Order.ASCENDING, }, ], }; expect([b, a, e, d, c].sort(sort.compareSpecIndex)).to.eql([a, b, c, d, e]); }); it("should correcty sort an array of Spec field overrides", () => { // Sorts first because of collectionGroup const a: Spec.FieldOverride = { collectionGroup: "collectionA", fieldPath: "fieldA", indexes: [], }; const b: Spec.FieldOverride = { collectionGroup: "collectionB", fieldPath: "fieldA", indexes: [], }; // Order indexes sort before Array indexes const c: Spec.FieldOverride = { collectionGroup: "collectionB", fieldPath: "fieldB", indexes: [ { queryScope: API.QueryScope.COLLECTION, order: API.Order.ASCENDING, }, ], }; const d: Spec.FieldOverride = { collectionGroup: "collectionB", fieldPath: "fieldB", indexes: [ { queryScope: API.QueryScope.COLLECTION, arrayConfig: API.ArrayConfig.CONTAINS, }, ], }; expect([b, a, d, c].sort(sort.compareFieldOverride)).to.eql([a, b, c, d]); }); it("should correctly sort an array of API indexes", () => { // Sorts first because of collectionGroup const a: API.Index = { name: "/projects/project/databases/(default)/collectionGroups/collectionA/indexes/a", queryScope: API.QueryScope.COLLECTION, fields: [], }; // fieldA ASCENDING should sort before fieldA DESCENDING const b: API.Index = { name: "/projects/project/databases/(default)/collectionGroups/collectionB/indexes/b", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldA", order: API.Order.ASCENDING, }, ], }; // This compound index sorts before the following simple // index because the first element sorts first. const c: API.Index = { name: "/projects/project/databases/(default)/collectionGroups/collectionB/indexes/c", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldA", order: API.Order.ASCENDING, }, { fieldPath: "fieldB", order: API.Order.ASCENDING, }, ], }; const d: API.Index = { name: "/projects/project/databases/(default)/collectionGroups/collectionB/indexes/d", queryScope: API.QueryScope.COLLECTION, fields: [ { fieldPath: "fieldA", order: API.Order.DESCENDING, }, ], }; expect([b, a, d, c].sort(sort.compareApiIndex)).to.eql([a, b, c, d]); }); it("should correctly sort an array of API field overrides", () => { // Sorts first because of collectionGroup const a: API.Field = { name: "/projects/myproject/databases/(default)/collectionGroups/collectionA/fields/fieldA", indexConfig: { indexes: [], }, }; const b: API.Field = { name: "/projects/myproject/databases/(default)/collectionGroups/collectionB/fields/fieldA", indexConfig: { indexes: [], }, }; // Order indexes sort before Array indexes const c: API.Field = { name: "/projects/myproject/databases/(default)/collectionGroups/collectionB/fields/fieldB", indexConfig: { indexes: [ { queryScope: API.QueryScope.COLLECTION, fields: [{ fieldPath: "fieldB", order: API.Order.DESCENDING }], }, ], }, }; const d: API.Field = { name: "/projects/myproject/databases/(default)/collectionGroups/collectionB/fields/fieldB", indexConfig: { indexes: [ { queryScope: API.QueryScope.COLLECTION, fields: [{ fieldPath: "fieldB", arrayConfig: API.ArrayConfig.CONTAINS }], }, ], }, }; expect([b, a, d, c].sort(sort.compareApiField)).to.eql([a, b, c, d]); }); });
the_stack
* SetTrafficMirrorHealthSwitch请求参数结构体 */ export interface SetTrafficMirrorHealthSwitchRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 健康检查开关,0:关闭,1:打开 */ HealthSwitch: number /** * 健康检查判断健康的次数,最小值2,最大值10。 */ HealthNum?: number /** * 健康检查判断不健康的次数,最小值2,最大值10。 */ UnhealthNum?: number /** * 健康检查间隔,单位:秒,最小值5,最大值300。 */ IntervalTime?: number /** * 检查的域名配置。 */ HttpCheckDomain?: string /** * 检查的路径配置。 */ HttpCheckPath?: string /** * 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。 */ HttpCodes?: Array<number> } /** * SetTrafficMirrorAlias返回参数结构体 */ export interface SetTrafficMirrorAliasResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteL7Rules请求参数结构体 */ export interface DeleteL7RulesRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId: string /** * 转发路径实例ID列表,可通过接口DescribeL7Rules查询。 */ LocationIds: Array<string> } /** * DeleteTrafficMirror返回参数结构体 */ export interface DeleteTrafficMirrorResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL7BackendPort返回参数结构体 */ export interface ModifyL7BackendPortResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL4BackendProbePort返回参数结构体 */ export interface ModifyL4BackendProbePortResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 待与流量镜像绑定的接收机信息。 */ export interface BindTrafficMirrorReceiver { /** * 待绑定的主机端口,可选值1~65535。 */ Port: number /** * 待绑定的主机实例ID。 */ InstanceId: string /** * 待绑定的主机权重,可选值0~100。 */ Weight: number } /** * ModifyL4BackendPort返回参数结构体 */ export interface ModifyL4BackendPortResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL7Locations返回参数结构体 */ export interface ModifyL7LocationsResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTrafficMirrorReceiverHealthStatus请求参数结构体 */ export interface DescribeTrafficMirrorReceiverHealthStatusRequest { /** * 查询所在的流量镜像ID。 */ TrafficMirrorId: string /** * 流量镜像接收机实例ID和端口数组。 */ ReceiverSet: Array<DescribeTrafficMirrorReceiver> } /** * 待与四层监听器解绑的物理机主机、虚拟机或半托管主机信息。 */ export interface UnbindL4Backend { /** * 待解绑的主机端口,可选值1~65535。 */ Port?: number /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId?: string } /** * ModifyL4Listener返回参数结构体 */ export interface ModifyL4ListenerResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取设备绑定信息时返回的四层监听器信息。 */ export interface DevicesBindInfoL4Listener { /** * 七层监听器实例ID。 */ ListenerId?: string /** * 七层监听器协议类型,可选值:http,https。 */ Protocol?: string /** * 七层监听器的监听端口。 */ LoadBalancerPort?: number /** * 该转发路径所绑定的主机列表。 */ BackendSet?: Array<DevicesBindInfoBackend> } /** * DescribeL4ListenerInfo请求参数结构体 */ export interface DescribeL4ListenerInfoRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 查找的键值,可用于模糊查找该名称的监听器。 */ SearchKey?: string /** * 主机ID或虚机IP列表,可用于获取绑定了该主机的监听器。 */ InstanceIds?: Array<string> } /** * 查询绑定了某主机的四层监听器时返回的四层监听器信息。 */ export interface L4ListenerInfo { /** * 监听器ID。 */ ListenerId?: string /** * 用户自定义的监听器名称。 */ ListenerName?: string /** * 负载均衡实例监听器协议类型,可选值tcp,udp。 */ Protocol?: string /** * 负载均衡监听器的监听接口,可选值1~65535。 */ LoadBalancerPort?: number /** * 用于计费模式为固定带宽计费,指定监听器最大带宽值,可选值:0-1000,单位:Mbps。 */ Bandwidth?: number /** * 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。 */ ListenerType?: string /** * 会话保持时间。单位:秒 */ SessionExpire?: number /** * 是否开启了检查:1(开启)、0(关闭)。 */ HealthSwitch?: number /** * 响应超时时间,单位:秒。 */ TimeOut?: number /** * 检查间隔,单位:秒。 */ IntervalTime?: number /** * 负载均衡监听器健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。 */ HealthNum?: number /** * 负载均衡监听器不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。 */ UnhealthNum?: number /** * 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效) */ CustomHealthSwitch?: number /** * 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。 */ InputType?: string /** * 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。 */ LineSeparatorType?: number /** * 自定义探测请求内容。 */ HealthRequest?: string /** * 自定义探测返回内容。 */ HealthResponse?: string /** * 是否开启toa:1(开启)、0(关闭)。 */ ToaFlag?: number /** * 转发后端服务器调度类型。 */ BalanceMode?: string } /** * DescribeL7Rules请求参数结构体 */ export interface DescribeL7RulesRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名ID列表,可通过接口DescribeL7Rules查询。 */ DomainIds?: Array<string> } /** * UnbindL7Backends返回参数结构体 */ export interface UnbindL7BackendsResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL4BackendWeight返回参数结构体 */ export interface ModifyL4BackendWeightResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteL7Domains返回参数结构体 */ export interface DeleteL7DomainsResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取设备绑定信息时返回的所绑定的主机信息。 */ export interface DevicesBindInfoBackend { /** * 黑石物理机的主机ID、托管主机ID或虚拟机IP。 */ InstanceId?: string /** * 主机端口。 */ Port?: number } /** * UnbindL4Backends请求参数结构体 */ export interface UnbindL4BackendsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。 */ ListenerId: string /** * 待解绑的主机信息。可以绑定多个主机端口。目前一个四层监听器下面最多允许绑定255个主机端口。 */ BackendSet: Array<UnbindL4Backend> /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * DescribeL7Listeners请求参数结构体 */ export interface DescribeL7ListenersRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID列表,可通过接口DescribeL7Listeners查询。 */ ListenerIds?: Array<string> } /** * DescribeTrafficMirrorListeners请求参数结构体 */ export interface DescribeTrafficMirrorListenersRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 分页的偏移量,也即从第几条记录开始查询 */ Offset?: number /** * 单次查询返回的条目数,默认值:500。 */ Limit?: number /** * 待搜索的负载均衡Id。 */ SearchLoadBalancerIds?: Array<string> /** * 待搜索的负载均衡名称。 */ SearchLoadBalancerNames?: Array<string> /** * 待搜索的Vip。 */ SearchVips?: Array<string> /** * 待搜索的监听器ID。 */ SearchListenerIds?: Array<string> /** * 待搜索的监听器名称。 */ SearchListenerNames?: Array<string> /** * 待搜索的协议名称。 */ SearchProtocols?: Array<string> /** * 待搜索的端口。 */ SearchLoadBalancerPorts?: Array<number> } /** * 待与七层监听器转发规则绑定的物理机主机、虚拟机或半托管主机信息。目前一个七层转发路径下面最多允许绑定255个主机端口。 */ export interface BindL7Backend { /** * 待绑定的主机端口,可选值1~65535。 */ Port?: number /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId?: string /** * 待绑定的主机权重,可选值0~100。 */ Weight?: number } /** * ModifyL7Listener返回参数结构体 */ export interface ModifyL7ListenerResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用[DescribeLoadBalancerTaskResult](/document/product/386/9308)接口来查询任务操作结果 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeLoadBalancerTaskResult请求参数结构体 */ export interface DescribeLoadBalancerTaskResultRequest { /** * 任务ID。由具体的异步操作接口提供。 */ TaskId: string } /** * DescribeL7Rules返回参数结构体 */ export interface DescribeL7RulesResponse { /** * 返回的转发规则列表。 */ RuleSet?: Array<L7Rule> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateTrafficMirror返回参数结构体 */ export interface CreateTrafficMirrorResponse { /** * 流量镜像实例ID */ TrafficMirrorId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeDevicesBindInfo请求参数结构体 */ export interface DescribeDevicesBindInfoRequest { /** * 黑石私有网络唯一ID。 */ VpcId: string /** * 主机ID或虚机IP列表,可用于获取绑定了该主机的负载均衡列表。 */ InstanceIds: Array<string> } /** * BindL4Backends返回参数结构体 */ export interface BindL4BackendsResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取流量镜像的监听器列表信息时返回的与流量镜像绑定的监听器信息。 */ export interface TrafficMirrorListener { /** * 监听器ID。 */ ListenerId: string /** * 监听器名称。 */ ListenerName: string /** * 七层监听器协议类型,可选值:http,https。 */ Protocol: string /** * 监听器的监听端口。 */ LoadBalancerPort: number /** * 当前带宽。 */ Bandwidth: number /** * 带宽上限。 */ MaxBandwidth: number /** * 监听器类型。 */ ListenerType: string /** * 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。 */ SslMode: number /** * 服务端证书ID。 */ CertId: string /** * 客户端证书ID。 */ CertCaId: string /** * 添加时间。 */ AddTimestamp: string /** * 负载均衡ID。 */ LoadBalancerId: string /** * 私有网络名称。 */ VpcName: string /** * 私有网络Cidr。 */ VpcCidrBlock: string /** * 负载均衡的VIP。 */ LoadBalancerVips: Array<string> /** * 负载均衡名称。 */ LoadBalancerName: string /** * 负载均衡的IPV6的VIP。 */ LoadBalancerVipv6s: Array<string> /** * 支持的IP协议类型。ipv4或者是ipv6。 */ IpProtocolType: string } /** * DescribeL7ListenersEx返回参数结构体 */ export interface DescribeL7ListenersExResponse { /** * 此指定VPC中负载均衡的总数。 */ TotalCount?: number /** * 符合条件的监听器。 */ ListenerSet?: Array<L7ExListener> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 待与七层监听器转发规则解绑的物理机主机、虚拟机或半托管主机信息。 */ export interface UnbindL7Backend { /** * 待解绑的主机端口,可选值1~65535。 */ Port?: number /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId?: string } /** * 获取与流量镜像绑定的接收机信息时返回的接收机信息。 */ export interface TrafficMirrorReceiver { /** * 接收机实例ID。 */ InstanceId?: string /** * 接收机接收端口。 */ Port?: number /** * 接收机权重。 */ Weight?: number /** * 流量镜像ID。 */ TrafficMirrorId: string /** * 接收机别名。 */ Alias: string /** * 接收机内网IP地址。 */ LanIp: string /** * 接收机所在的子网的ID。 */ SubnetId: string /** * 接收机所在的子网的名称。 */ SubnetName: string /** * 接收机所在的子网的Cidr。 */ SubnetCidrBlock: string /** * 接收机所在的私有网络的ID。 */ VpcId: string /** * 接收机所在的私有网络的名称。 */ VpcName: string /** * 接收机所在的私有网络的Cidr。 */ VpcCidrBlock: string /** * 接收机的健康状态。 */ HealthStatus: string /** * 接收机的可以执行的操作集合。 */ Operates: Array<string> } /** * 流量镜像健康检查返回的接收机的端口及状态信息。 */ export interface TrafficMirrorPortStatus { /** * 接收机端口。 */ Port: number /** * 状态。 */ Status: string } /** * UploadCert返回参数结构体 */ export interface UploadCertResponse { /** * 新建的证书ID。 */ CertId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTrafficMirrorReceivers返回参数结构体 */ export interface DescribeTrafficMirrorReceiversResponse { /** * 接收机列表,具体结构描述如data结构所示。 */ ReceiverSet?: Array<TrafficMirrorReceiver> /** * 接收机总数。 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteListeners请求参数结构体 */ export interface DeleteListenersRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 待删除的负载均衡四层和七层监听器ID列表,可通过接口DescribeL4Listeners和DescribeL7Listeners查询。目前同时只能删除一种类型的监听器,并且删除七层监听器的数量上限为一个。 */ ListenerIds: Array<string> } /** * ModifyL4BackendProbePort请求参数结构体 */ export interface ModifyL4BackendProbePortRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 负载均衡四层监听器ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId: string /** * 已绑定的主机端口。 */ Port: number /** * 新的探测端口,可选值1~65535。 */ ProbePort: number /** * 绑定类型。0:物理机 1:虚拟机IP 2:半托管机器 */ BindType: number } /** * DescribeTrafficMirrors请求参数结构体 */ export interface DescribeTrafficMirrorsRequest { /** * 流量镜像实例ID的数组,支持批量查询 */ TrafficMirrorIds?: Array<string> /** * 流量镜像实例别名数组。 */ Aliases?: Array<string> /** * 流量镜像实例所属的私有网络ID数组,形如:vpc-xxx。 */ VpcIds?: Array<string> /** * 分页的偏移量,也即从第几条记录开始查询 */ Offset?: number /** * 单次查询返回的条目数,默认值:500。 */ Limit?: number /** * 排序字段。trafficMirrorId或者createTime。 */ OrderField?: string /** * 排序方式,取值:0:增序(默认),1:降序 */ Order?: number /** * 模糊匹配trafficMirrorId或者alias字段。 */ SearchKey?: string } /** * UploadCert请求参数结构体 */ export interface UploadCertRequest { /** * 证书类型,可选值:CA,SVR。 */ CertType: string /** * 证书内容。 */ Cert: string /** * 证书别名。 */ Alias?: string /** * 私钥内容,证书类型为SVR时不需要传递。 */ Key?: string } /** * DescribeL4ListenerInfo返回参数结构体 */ export interface DescribeL4ListenerInfoResponse { /** * 返回的四层监听器列表。 */ ListenerSet?: Array<L4ListenerInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * BindTrafficMirrorListeners请求参数结构体 */ export interface BindTrafficMirrorListenersRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 七层监听器实例ID数组,可通过接口DescribeL7Listeners查询。 */ ListenerIds: Array<string> } /** * ModifyL7BackendPort请求参数结构体 */ export interface ModifyL7BackendPortRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId: string /** * 转发路径实例ID,可通过接口DescribeL7Rules查询。 */ LocationId: string /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId: string /** * 已绑定的主机端口。 */ Port: number /** * 新的主机端口,可选值1~65535。 */ NewPort: number /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * ModifyL4BackendPort请求参数结构体 */ export interface ModifyL4BackendPortRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。 */ ListenerId: string /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId: string /** * 已绑定的主机端口。 */ Port: number /** * 新的主机端口,可选值1~65535。 */ NewPort: number /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * DescribeL4Listeners返回参数结构体 */ export interface DescribeL4ListenersResponse { /** * 监听器信息数组。 */ ListenerSet?: Array<L4Listener> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL7Locations请求参数结构体 */ export interface ModifyL7LocationsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 待更新的七层转发规则信息数组。 */ RuleSet: Array<ModifyL7LocationRule> } /** * ModifyLoadBalancer返回参数结构体 */ export interface ModifyLoadBalancerResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateL4Listeners返回参数结构体 */ export interface CreateL4ListenersResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL7BackendWeight返回参数结构体 */ export interface ModifyL7BackendWeightResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTrafficMirrors返回参数结构体 */ export interface DescribeTrafficMirrorsResponse { /** * 流量镜像总数。 */ TotalCount?: number /** * 对象数组。数组元素为流量镜像信息,具体结构描述如list结构所示。 */ TrafficMirrorSet?: Array<TrafficMirror> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeL7Backends请求参数结构体 */ export interface DescribeL7BackendsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId?: string /** * 转发路径实例ID,可通过接口DescribeL7Rules查询。 */ LocationId?: string /** * 查询条件,传'all'则查询所有与规则绑定的主机信息。如果为all时,DomainId和LocationId参数没有意义不必传入,否则DomainId和LocationId参数必须传入。 */ QueryType?: string } /** * 获取黑石负载均衡七层监听器时返回的七层监听器信息。 */ export interface L7Listener { /** * 七层监听器实例ID。 */ ListenerId?: string /** * 七层监听器名称。 */ ListenerName?: string /** * 七层监听器协议类型,可选值:http,https。 */ Protocol?: string /** * 七层监听器的监听端口。 */ LoadBalancerPort?: number /** * 计费模式为按固定带宽方式时监听器的限速值,单位:Mbps。 */ Bandwidth?: number /** * 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。 */ ListenerType?: string /** * 七层监听器的认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。 */ SslMode?: number /** * 七层监听器关联的服务端证书ID。 */ CertId?: string /** * 七层监听器关联的客户端证书ID。 */ CertCaId?: string /** * 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * https转发类型。0:https。1:spdy。2:http2。3:spdy+http2。 */ ForwardProtocol?: number } /** * CreateL7Rules请求参数结构体 */ export interface CreateL7RulesRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 七层转发规则信息数组,可以创建多个七层转发规则。目前一个七层监听器下面最多允许创建50个七层转发域名,而每一个转发域名下最多可以创建100个转发规则。目前只能单条创建,不能批量创建。 */ RuleSet: Array<CreateL7Rule> } /** * ModifyL7BackendWeight请求参数结构体 */ export interface ModifyL7BackendWeightRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId: string /** * 转发路径实例ID,可通过接口DescribeL7Rules查询。 */ LocationId: string /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId: string /** * 权重信息,可选值0~100。 */ Weight: number /** * 已绑定的主机端口。 */ Port: number /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * CreateL4Listeners请求参数结构体 */ export interface CreateL4ListenersRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 监听器信息数组,可以创建多个监听器。目前一个负载均衡下面最多允许创建50个监听器 */ ListenerSet: Array<CreateL4Listener> } /** * ReplaceCert请求参数结构体 */ export interface ReplaceCertRequest { /** * 要被替换的证书ID */ OldCertId: string /** * 证书内容 */ NewCert: string /** * 证书名称 */ NewAlias?: string /** * 私钥内容,证书类型为SVR时不需要传递 */ NewKey?: string /** * 是否删除旧证书,0 表示不删除,1 表示删除 */ DeleteOld?: number } /** * BindL7Backends返回参数结构体 */ export interface BindL7BackendsResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取七层监听器转发规则时返回的转发规则。 */ export interface L7Rule { /** * 转发域名。 */ Domain?: string /** * 转发域名实例ID。 */ DomainId?: string /** * 转发路径当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * 该转发域名下面的转发路径列表。 */ LocationSet?: Array<L7RulesLocation> } /** * UnbindTrafficMirrorReceivers返回参数结构体 */ export interface UnbindTrafficMirrorReceiversResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteL7Domains请求参数结构体 */ export interface DeleteL7DomainsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID列表,可通过接口DescribeL7Rules查询。 */ DomainIds: Array<string> } /** * BindTrafficMirrorReceivers请求参数结构体 */ export interface BindTrafficMirrorReceiversRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 待绑定的黑石物理机信息数组。 */ ReceiverSet: Array<BindTrafficMirrorReceiver> } /** * BindTrafficMirrorListeners返回参数结构体 */ export interface BindTrafficMirrorListenersResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * BindL7Backends请求参数结构体 */ export interface BindL7BackendsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId: string /** * 转发路径实例ID,可通过接口DescribeL7Rules查询。 */ LocationId: string /** * 待绑定的主机信息。可以绑定多个主机端口。目前一个七层转发路径下面最多允许绑定255个主机端口。 */ BackendSet: Array<BindL7Backend> /** * 绑定类型。0:物理机,1:虚拟机 2:半托管机器。 */ BindType: number } /** * 待查询四层监听器绑定的主机信息。 */ export interface DescribeL4Backend { /** * 待绑定的主机端口,可选值1~65535。 */ Port?: number /** * 黑石物理机的主机ID。 */ InstanceId?: string } /** * DescribeCertDetail返回参数结构体 */ export interface DescribeCertDetailResponse { /** * 证书ID。 */ CertId?: string /** * 证书名称。 */ CertName?: string /** * 证书类型(SVR=服务器证书,CA=客户端证书)。 */ CertType?: string /** * 证书内容。 */ CertContent?: string /** * 证书主域名。 */ CertDomain?: string /** * 证书子域名列表。 */ CertSubjectDomain?: Array<string> /** * 证书上传时间。 */ CertUploadTime?: string /** * 证书生效时间。 */ CertBeginTime?: string /** * 证书失效时间。 */ CertEndTime?: string /** * 该证书关联的黑石负载均衡对象列表。 */ CertLoadBalancerSet?: Array<CertDetailLoadBalancer> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeL4Backends请求参数结构体 */ export interface DescribeL4BackendsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。 */ ListenerId: string /** * 待查询的主机信息。 */ BackendSet?: Array<DescribeL4Backend> } /** * DescribeTrafficMirrorReceiverHealthStatus返回参数结构体 */ export interface DescribeTrafficMirrorReceiverHealthStatusResponse { /** * 内网IP和端口对应的状态。 */ ReceiversStatusSet?: Array<TrafficMirrorReciversStatus> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * BindTrafficMirrorReceivers返回参数结构体 */ export interface BindTrafficMirrorReceiversResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ReplaceCert返回参数结构体 */ export interface ReplaceCertResponse { /** * 新证书ID。 */ NewCertId?: string /** * 旧证书ID。 */ OldCertId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeLoadBalancerPortInfo请求参数结构体 */ export interface DescribeLoadBalancerPortInfoRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string } /** * 获取设备绑定信息时返回的设备所绑定的转发路径信息。 */ export interface DevicesBindInfoLocation { /** * 转发路径。 */ Url?: string /** * 转发路径实例ID。 */ LocationId?: string /** * 该转发路径所绑定的主机列表。 */ BackendSet?: Array<DevicesBindInfoBackend> } /** * SetTrafficMirrorHealthSwitch返回参数结构体 */ export interface SetTrafficMirrorHealthSwitchResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteLoadBalancer请求参数结构体 */ export interface DeleteLoadBalancerRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string } /** * UnbindTrafficMirrorListeners返回参数结构体 */ export interface UnbindTrafficMirrorListenersResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 用于创建七层监听器的转发规则的信息。目前一个七层监听器下面最多允许创建50个七层转发域名,而每一个转发域名下最多可以创建100个转发规则。 */ export interface CreateL7Rule { /** * 七层转发规则的转发域名。 */ Domain: string /** * 七层转发规则的转发路径。 */ Url: string /** * 会话保持时间,单位:秒。可选值:30~3600。默认值0,表示不开启会话保持。 */ SessionExpire?: number /** * 健康检查开关:1(开启)、0(关闭)。默认值0,表示关闭。 */ HealthSwitch?: number /** * 健康检查检查间隔时间,默认值:5,可选值:5-300,单位:秒。 */ IntervalTime?: number /** * 健康检查健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。 */ HealthNum?: number /** * 健康检查不健康阈值,默认值:5,表示当连续探测五次不健康则表示该转发不正常,可选值:2-10,单位:次。 */ UnhealthNum?: number /** * 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。 */ HttpCodes?: Array<number> /** * 健康检查检查路径。 */ HttpCheckPath?: string /** * 健康检查检查域名。如果创建规则的域名使用通配符或正则表达式,则健康检查检查域名可自定义,否则必须跟健康检查检查域名一样。 */ HttpCheckDomain?: string /** * 均衡方式:ip_hash、wrr。默认值wrr。 */ BalanceMode?: string } /** * CreateL7Rules返回参数结构体 */ export interface CreateL7RulesResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyL7Listener请求参数结构体 */ export interface ModifyL7ListenerRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 七层监听器名称。 */ ListenerName?: string /** * 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。 */ SslMode?: number /** * 服务端证书ID。 */ CertId?: string /** * 服务端证书名称。 */ CertName?: string /** * 服务端证书内容。 */ CertContent?: string /** * 服务端证书密钥。 */ CertKey?: string /** * 客户端证书ID。 */ CertCaId?: string /** * 客户端证书名称。 */ CertCaName?: string /** * 客户端证书内容。 */ CertCaContent?: string /** * 计费模式为按固定带宽方式时监听器的限速值,可选值:0-1000,单位:Mbps。 */ Bandwidth?: number /** * 转发协议。当监听器Protocol为https时并且SslMode为1或2时,有意义。可选的值为0:https,1:spdy,2:http2,3:spdy+http2。 */ ForwardProtocol?: number } /** * 流量镜像进行健康检查的接收机信息。 */ export interface DescribeTrafficMirrorReceiver { /** * 物理机实例ID。 */ InstanceId: string /** * 物理机绑定的端口。 */ Port: number } /** * 监听器信息。 */ export interface L7ExListener { /** * 绑定的监听器唯一ID。 */ ListenerId?: string /** * 监听器名称。 */ ListenerName?: string /** * 七层监听器协议类型,可选值:http,https。 */ Protocol: string /** * 监听器的监听端口。 */ LoadBalancerPort: number /** * 当前带宽。 */ Bandwidth: number /** * 带宽上限。 */ MaxBandwidth: number /** * 监听器类型。 */ ListenerType: string /** * 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。 */ SslMode: number /** * 服务端证书ID。 */ CertId: string /** * 客户端证书ID。 */ CertCaId: string /** * 添加时间。 */ AddTimestamp: string /** * 负载均衡名ID。 */ LoadBalancerId: string /** * 私有网络名称。 */ VpcName: string /** * 私有网络Cidr。 */ VpcCidrBlock: string /** * 负载均衡的VIP。 */ LoadBalancerVips: Array<string> /** * 负载均衡名称。 */ LoadBalancerName: string /** * 负载均衡IPV6的VIP。 */ LoadBalancerVipv6s: Array<string> /** * 支持的IP协议类型。ipv4或者是ipv6。 */ IpProtocolType: string /** * 是否绑定在入参指定的流量镜像中。 */ BindTrafficMirror: boolean } /** * 查询绑定了某主机的七层监听器时返回的七层监听器信息。 */ export interface L7ListenerInfo { /** * 七层监听器实例ID。 */ ListenerId?: string /** * 七层监听器名称。 */ ListenerName?: string /** * 七层监听器协议类型,可选值:http,https。 */ Protocol?: string /** * 七层监听器的监听端口。 */ LoadBalancerPort?: number /** * 计费模式为按固定带宽方式时监听器的限速值,单位:Mbps。 */ Bandwidth?: number /** * 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。 */ ListenerType?: string /** * 七层监听器的认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。 */ SslMode?: number /** * 七层监听器关联的服务端证书ID。 */ CertId?: string /** * 七层监听器关联的客户端证书ID。 */ CertCaId?: string /** * 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * 返回的转发规则列表。 */ RuleSet?: Array<L7ListenerInfoRule> /** * https转发类型。0:https。1:spdy。2:http2。3:spdy+http2。 */ ForwardProtocol?: number } /** * 查询绑定了某主机的七层监听器时返回的转发规则。 */ export interface L7ListenerInfoRule { /** * 转发域名。 */ Domain?: string /** * 转发域名实例ID。 */ DomainId?: string /** * 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * 该转发域名下面的转发路径列表。 */ LocationSet?: Array<L7ListenerInfoLocation> } /** * DescribeL7Backends返回参数结构体 */ export interface DescribeL7BackendsResponse { /** * 返回的绑定关系列表。 */ BackendSet?: Array<L7Backend> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 过滤器 */ export interface Filter { /** * 属性名称, 若存在多个Filter时,Filter间的关系为逻辑与(AND)关系。 */ Name: string /** * 属性值, 若同一个Filter存在多个Values,同一Filter下Values间的关系为逻辑或(OR)关系。 */ Values: Array<string> } /** * 获取设备绑定信息时返回的设备所绑定的转发规则信息。 */ export interface DevicesBindInfoRule { /** * 转发域名。 */ Domain?: string /** * 转发域名ID。 */ DomainId?: string /** * 转发路径列表。 */ LocationSet?: Array<DevicesBindInfoLocation> } /** * 获取流量镜像实例的列表信息时返回的流量镜像信息。 */ export interface TrafficMirror { /** * 流量镜像ID。 */ TrafficMirrorId?: string /** * 流量镜像名称。 */ Alias?: string /** * 流量镜像所在的私有网络ID。 */ VpcId?: string /** * 接收机负载均衡方式。wrr,ip_hash,wlc。 */ LoadBalancerType?: string /** * 是否开始对接收机的健康检查。0:关闭,非0:开启。 */ HealthSwitch?: number /** * 健康阈值。 */ HealthNum?: number /** * 不健康阈值。 */ UnhealthNum?: number /** * 检查间隔。 */ IntervalTime?: number /** * 检查域名。 */ HttpCheckDomain?: string /** * 检查目录。 */ HttpCheckPath?: string /** * 健康检查返回码。 1:1xx,2:2xx,3:3xx,4:4xx,5:5xx。 */ HttpCodes?: Array<number> /** * 创建时间。 */ CreateTime?: string /** * 流量镜像所在私有网络的Cidr。 */ VpcCidrBlock?: string /** * 流量镜像所在私有网络的名称。 */ VpcName?: string } /** * DescribeLoadBalancers请求参数结构体 */ export interface DescribeLoadBalancersRequest { /** * 负载均衡器ID数组 */ LoadBalancerIds?: Array<string> /** * 负载均衡的类型 : open表示公网LB类型,internal表示内网LB类型 */ LoadBalancerType?: string /** * 负载均衡器名称 */ LoadBalancerName?: string /** * 负载均衡域名。规则:1-60个小写英文字母、数字、点号“.”或连接线“-”。内网类型的负载均衡不能配置该字段 */ Domain?: string /** * 负载均衡获得的公网IP地址,支持多个 */ LoadBalancerVips?: Array<string> /** * 数据偏移量,默认为0 */ Offset?: number /** * 返回数据长度,默认为20 */ Limit?: number /** * 模糊查找名称、域名、VIP */ SearchKey?: string /** * 排序字段,支持:loadBalancerName,createTime,domain,loadBalancerType */ OrderBy?: string /** * 1倒序,0顺序,默认顺序 */ OrderType?: number /** * 项目ID */ ProjectId?: number /** * 是否筛选独占集群,0表示非独占集群,1表示四层独占集群,2表示七层独占集群,3表示四层和七层独占集群,4表示共享容灾 */ Exclusive?: number /** * 该负载均衡对应的tgw集群(fullnat,tunnel,dnat) */ TgwSetType?: string /** * 该负载均衡对应的所在的私有网络ID */ VpcId?: string /** * 'CONFLIST' 查询带confId的LB列表,'CONFID' 查询某个confId绑定的LB列表 */ QueryType?: string /** * 个性化配置ID */ ConfId?: string } /** * 获取设备绑定信息时返回的设备被绑定所在的负载均衡信息。 */ export interface DevicesBindInfoLoadBalancer { /** * 负载均衡实例ID。 */ LoadBalancerId?: string /** * 开发商AppId。 */ AppId?: number /** * 负载均衡所属的项目ID。 */ ProjectId?: number /** * 黑石私有网络唯一ID。 */ VpcId?: string /** * 负载均衡的IP地址。 */ Vip?: string /** * 负载均衡对应的TGW集群类别,取值为tunnel或fullnat。tunnel表示隧道集群,fullnat表示FULLNAT集群。 */ TgwSetType?: string /** * 是否独占TGW集群。 */ Exclusive?: number /** * 具有该绑定关系的四层监听器列表。 */ L4ListenerSet?: Array<DevicesBindInfoL4Listener> /** * 具有该绑定关系的七层监听器列表。 */ L7ListenerSet?: Array<DevicesBindInfoL7Listener> } /** * 查询四层监听器时返回的四层监听器信息。 */ export interface L4Listener { /** * 监听器ID。 */ ListenerId?: string /** * 用户自定义的监听器名称。 */ ListenerName?: string /** * 负载均衡实例监听器协议类型,可选值tcp,udp。 */ Protocol?: string /** * 负载均衡监听器的监听接口,可选值1~65535。 */ LoadBalancerPort?: number /** * 用于计费模式为固定带宽计费,指定监听器最大带宽值,可选值:0-1000,单位:Mbps。 */ Bandwidth?: number /** * 监听器的类别:L4Listener(四层监听器),L7Listener(七层监听器)。 */ ListenerType?: string /** * 会话保持时间。单位:秒 */ SessionExpire?: number /** * 是否开启了检查:1(开启)、0(关闭)。 */ HealthSwitch?: number /** * 响应超时时间,单位:秒。 */ TimeOut?: number /** * 检查间隔,单位:秒。 */ IntervalTime?: number /** * 负载均衡监听器健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。 */ HealthNum?: number /** * 负载均衡监听器不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。 */ UnhealthNum?: number /** * 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效) */ CustomHealthSwitch?: number /** * 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。 */ InputType?: string /** * 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。 */ LineSeparatorType?: number /** * 自定义探测请求内容。 */ HealthRequest?: string /** * 自定义探测返回内容。 */ HealthResponse?: string /** * 是否开启toa:1(开启)、0(关闭)。 */ ToaFlag?: number /** * 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * 转发后端服务器调度类型。 */ BalanceMode?: string } /** * 用于创建四层监听器的监听器信息。目前一个负载均衡下面最多允许创建50个七层监听器。 */ export interface CreateL7Listener { /** * 七层监听器端口,可选值1~65535。 */ LoadBalancerPort: number /** * 七层监听器协议类型,可选值:http,https。 */ Protocol: string /** * 七层监听器名称。 */ ListenerName: string /** * 认证方式:0(不认证,用于http),1(单向认证,用于https),2(双向认证,用于https)。当创建的是https类型的监听器时,此值必选。 */ SslMode?: number /** * 服务端证书ID。当创建的是https类型的监听器时,此值必选。 */ CertId?: string /** * 服务端证书名称。 */ CertName?: string /** * 服务端证书内容。 */ CertContent?: string /** * 服务端证书密钥。 */ CertKey?: string /** * 客户端证书ID。 */ CertCaId?: string /** * 客户端证书名称。 */ CertCaName?: string /** * 客户端证书内容。 */ CertCaContent?: string /** * 用于计费模式为固定带宽计费,指定监听器最大带宽值,可选值:0-1000,单位:Mbps。 */ Bandwidth?: number /** * 转发协议。当Protocol为https时并且SslMode为1或2时,有意义。可选的值为0:https,1:spdy,2:http2,3:spdy+http2。 */ ForwardProtocol?: number } /** * DeleteLoadBalancer返回参数结构体 */ export interface DeleteLoadBalancerResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateTrafficMirror请求参数结构体 */ export interface CreateTrafficMirrorRequest { /** * 流量镜像实例别名。 */ Alias: string /** * 流量镜像实例所属的私有网络ID,形如:vpc-xxx。 */ VpcId: string } /** * BindL4Backends请求参数结构体 */ export interface BindL4BackendsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 四层监听器实例ID,可通过接口DescribeL4Listeners查询。 */ ListenerId: string /** * 待绑定的主机信息。可以绑定多个主机端口。目前一个四层监听器下面最多允许绑定255个主机端口。 */ BackendSet: Array<BindL4Backend> /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * DescribeL7ListenerInfo返回参数结构体 */ export interface DescribeL7ListenerInfoResponse { /** * 返回的七层监听器列表。 */ ListenerSet?: Array<L7ListenerInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeL7Listeners返回参数结构体 */ export interface DescribeL7ListenersResponse { /** * 返回的七层监听器列表。 */ ListenerSet?: Array<L7Listener> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteListeners返回参数结构体 */ export interface DeleteListenersResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateLoadBalancers返回参数结构体 */ export interface CreateLoadBalancersResponse { /** * 创建的黑石负载均衡实例ID。 */ LoadBalancerIds?: Array<string> /** * 创建负载均衡的异步任务ID。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 待与流量镜像解绑的接收机信息。 */ export interface UnbindTrafficMirrorReceiver { /** * 待解绑的主机端口,可选值1~65535。 */ Port: number /** * 待解绑的主机实例ID。 */ InstanceId: string } /** * ModifyLoadBalancerChargeMode返回参数结构体 */ export interface ModifyLoadBalancerChargeModeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * UnbindL7Backends请求参数结构体 */ export interface UnbindL7BackendsRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 七层监听器实例ID,可通过接口DescribeL7Listeners查询。 */ ListenerId: string /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId: string /** * 转发路径实例ID,可通过接口DescribeL7Rules查询。 */ LocationId: string /** * 待绑定的主机信息。 */ BackendSet: Array<UnbindL7Backend> /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * 查询绑定了某主机的七层监听器时返回的转发路径。 */ export interface L7ListenerInfoLocation { /** * 转发路径。 */ Url?: string /** * 转发路径实例ID。 */ LocationId?: string /** * 会话保持时间。 */ SessionExpire?: number /** * 是否开启健康检查。 */ HealthSwitch?: number /** * 健康检查检查路径。 */ HttpCheckPath?: string /** * 健康检查检查域名。 */ HttpCheckDomain?: string /** * 健康检查检查间隔时间。 */ IntervalTime?: number /** * 健康检查健康阈值。 */ HealthNum?: number /** * 健康检查不健康阈值。 */ UnhealthNum?: number /** * 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。 */ HttpCodes?: Array<number> /** * 均衡方式。 */ BalanceMode?: string /** * 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string /** * 该转发路径所绑定的主机列表。 */ BackendSet?: Array<L7ListenerInfoBackend> } /** * 获取七层转发规则时返回的转发域名下面的转发路径。 */ export interface L7RulesLocation { /** * 转发路径。 */ Url?: string /** * 转发路径实例ID。 */ LocationId?: string /** * 会话保持时间。 */ SessionExpire?: number /** * 是否开启健康检查。 */ HealthSwitch?: number /** * 健康检查检查路径。 */ HttpCheckPath?: string /** * 健康检查检查域名。 */ HttpCheckDomain?: string /** * 健康检查检查间隔时间。 */ IntervalTime?: number /** * 健康检查健康阈值。 */ HealthNum?: number /** * 健康检查不健康阈值。 */ UnhealthNum?: number /** * 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。 */ HttpCodes?: Array<number> /** * 均衡方式。 */ BalanceMode?: string /** * 转发路径当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。 */ Status?: number /** * 创建时间戳。 */ AddTimestamp?: string } /** * 修改负载均衡计费方式的监听器信息。 */ export interface ModifyLoadBalancerChargeModeListener { /** * 监听器ID。 */ ListenerId: string /** * 协议类型。 */ Protocol: string /** * 带宽。 */ Bandwidth: number } /** * 流量镜像健康检查返回的接收机状态信息。 */ export interface TrafficMirrorReciversStatus { /** * 内网IP。 */ LanIp: string /** * 端口及对应的状态。 */ ReceiversPortStatusSet: Array<TrafficMirrorPortStatus> } /** * CreateLoadBalancers请求参数结构体 */ export interface CreateLoadBalancersRequest { /** * 黑石负载均衡实例所属的私有网络ID。 */ VpcId: string /** * 负载均衡的类型,取值为open或internal。open表示公网(有日租),internal表示内网。 */ LoadBalancerType: string /** * 在私有网络内购买内网负载均衡实例的时候需要指定子网ID,内网负载均衡实例的VIP将从这个子网中产生。其他情况不用填写该字段。 */ SubnetId?: string /** * 负载均衡所属项目ID。不填则属于默认项目。 */ ProjectId?: number /** * 购买黑石负载均衡实例的数量。默认值为1, 最大值为20。 */ GoodsNum?: number /** * 黑石负载均衡的计费模式,取值为flow和bandwidth,其中flow模式表示流量模式,bandwidth表示带宽模式。默认值为flow。 */ PayMode?: string /** * 负载均衡对应的TGW集群类别,取值为tunnel、fullnat或dnat。tunnel表示隧道集群,fullnat表示FULLNAT集群(普通外网负载均衡),dnat表示DNAT集群(增强型外网负载均衡)。默认值为fullnat。如需获取client IP,可以选择 tunnel 模式,fullnat 模式(tcp 通过toa 获取),dnat 模式。 */ TgwSetType?: string /** * 负载均衡的独占类别,取值为0表示非独占,1表示四层独占,2表示七层独占,3表示四层和七层独占,4表示共享容灾。 */ Exclusive?: number /** * 指定的VIP,如果指定,则数量必须与goodsNum一致。如果不指定,则由后台分配随机VIP。 */ SpecifiedVips?: Array<string> /** * (未全地域开放)保障型负载均衡设定参数,如果类别选择保障型则需传入此参数。 */ BzConf?: CreateLoadBalancerBzConf /** * IP协议类型。可取的值为“ipv4”或“ipv6”。 */ IpProtocolType?: string } /** * DescribeLoadBalancerPortInfo返回参数结构体 */ export interface DescribeLoadBalancerPortInfoResponse { /** * 返回的监听器列表(四层和七层)。 */ ListenerSet?: Array<LoadBalancerPortInfoListener> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeL7ListenerInfo请求参数结构体 */ export interface DescribeL7ListenerInfoRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 查找的键值,可用于模糊查找有该转发域名的监听器。 */ SearchKey?: string /** * 主机ID或虚机IP列表,可用于获取绑定了该主机的监听器。 */ InstanceIds?: Array<string> /** * 是否获取转发规则下的主机信息。默认为0,不获取。 */ IfGetBackendInfo?: number } /** * ModifyL4Listener请求参数结构体 */ export interface ModifyL4ListenerRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 四层监听器ID。可通过接口DescribeL4Listeners查询。 */ ListenerId: string /** * 四层监听器名称。 */ ListenerName?: string /** * 会话保持时间,单位:秒。可选值:900~3600。 */ SessionExpire?: number /** * 是否开启健康检查:1(开启)、0(关闭)。默认值0,表示关闭。 */ HealthSwitch?: number /** * 健康检查的响应超时时间,可选值:2-60,默认值:2,单位:秒。<br><font color="red">响应超时时间要小于检查间隔时间。</font> */ TimeOut?: number /** * 健康检查间隔,默认值:5,可选值:5-300,单位:秒。 */ IntervalTime?: number /** * 健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。 */ HealthNum?: number /** * 不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。 */ UnhealthNum?: number /** * 监听器最大带宽值,用于计费模式为固定带宽计费。可选值:0-1000,单位:Mbps。 */ Bandwidth?: number /** * 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效) */ CustomHealthSwitch?: number /** * 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。 */ InputType?: string /** * 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。 */ LineSeparatorType?: number /** * 自定义探测请求内容。 */ HealthRequest?: string /** * 自定义探测返回内容。 */ HealthResponse?: string /** * 是否开启toa。可选值:0(关闭)、1(开启),默认关闭。(该字段在负载均衡为fullnat类型下才生效) */ ToaFlag?: number /** * 四层调度方式。wrr,wlc。 */ BalanceMode?: string } /** * 查询四层监听器返回的与监听器绑定关系的主机信息。 */ export interface L4Backend { /** * 绑定类别(0代表黑石物理机,1代表虚拟机IP)。 */ BindType?: number /** * 主机端口。 */ Port?: number /** * 权重。 */ Weight?: number /** * 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。 */ Status?: string /** * 黑石物理机的主机ID。 */ InstanceId?: string /** * 黑石物理机的别名。 */ Alias?: string /** * 主机IP。 */ LanIp?: string /** * 黑石物理机当前可以执行的操作。 */ Operates?: Array<string> /** * 主机探测端口。 */ ProbePort?: number } /** * 获取七层转发路径绑定的主机列表时返回的主机信息。 */ export interface L7Backend { /** * 绑定类别(0代表黑石物理机,1代表虚拟机IP)。 */ BindType?: number /** * 主机端口。 */ Port?: number /** * 权重。 */ Weight?: number /** * 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。 */ Status?: string /** * 黑石物理机的主机ID。 */ InstanceId?: string /** * 黑石物理机的别名。 */ Alias?: string /** * 主机IP。 */ LanIp?: string /** * 黑石物理机的管理IP。 */ MgtIp?: string /** * 黑石物理机当前可以执行的操作。 */ Operates?: Array<string> } /** * 修改黑石负载均衡七层转发路径时待修改的七层转发规则信息。 */ export interface ModifyL7LocationRule { /** * 转发域名实例ID,可通过接口DescribeL7Rules查询。 */ DomainId: string /** * 转发路径实例ID,可通过接口DescribeL7Rules查询。 */ LocationId: string /** * 转发路径。 */ Url?: string /** * 会话保持时间,单位:秒。可选值:30~3600。默认值0,表示不开启会话保持。 */ SessionExpire?: number /** * 健康检查开关:1(开启)、0(关闭)。默认值0,表示关闭。 */ HealthSwitch?: number /** * 健康检查检查间隔时间,默认值:5,可选值:5-300,单位:秒。 */ IntervalTime?: number /** * 健康检查健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。 */ HealthNum?: number /** * 健康检查不健康阈值,默认值:5,表示当连续探测五次不健康则表示该转发不正常,可选值:2-10,单位:次。 */ UnhealthNum?: number /** * 健康检查中认为健康的HTTP返回码的组合。可选值为1~5的集合,1表示HTTP返回码为1xx认为健康。2表示HTTP返回码为2xx认为健康。3表示HTTP返回码为3xx认为健康。4表示HTTP返回码为4xx认为健康。5表示HTTP返回码为5xx认为健康。 */ HttpCodes?: Array<number> /** * 健康检查检查路径。 */ HttpCheckPath?: string /** * 健康检查检查域名。如果规则的域名使用通配符或正则表达式,则健康检查检查域名可自定义,否则必须跟健康检查检查域名一样。不填表示不修改。 */ HttpCheckDomain?: string /** * 均衡方式:ip_hash、wrr。默认值wrr。 */ BalanceMode?: string /** * 转发域名。 */ Domain?: string } /** * ModifyLoadBalancer请求参数结构体 */ export interface ModifyLoadBalancerRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 负载均衡器名称,规则:1-20个英文、汉字、数字、连接线“-”或下划线“_”。 */ LoadBalancerName?: string /** * 域名前缀,负载均衡的域名由用户输入的域名前缀与配置文件中的域名后缀一起组合而成,保证是唯一的域名。规则:1-20个小写英文字母、数字或连接线“-”。内网类型的负载均衡不能配置该字段。 */ DomainPrefix?: string } /** * 获取设备绑定信息时返回的七层监听器信息。 */ export interface DevicesBindInfoL7Listener { /** * 七层监听器实例ID。 */ ListenerId?: string /** * 七层监听器协议类型,可选值:http,https。 */ Protocol?: string /** * 七层监听器的监听端口。 */ LoadBalancerPort?: number /** * 返回的转发规则列表。 */ RuleSet?: Array<DevicesBindInfoRule> } /** * DescribeL4Listeners请求参数结构体 */ export interface DescribeL4ListenersRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 四层监听器实例ID数组,可通过接口DescribeL4Listeners查询。 */ ListenerIds?: Array<string> } /** * CreateL7Listeners返回参数结构体 */ export interface CreateL7ListenersResponse { /** * 新建的负载均衡七层监听器的唯一ID列表。 */ ListenerIds?: Array<string> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 用于创建负载均衡的个性化配置。 */ export interface CreateLoadBalancerBzConf { /** * 按月/按小时计费。 */ BzPayMode?: string /** * 四层可选按带宽,连接数衡量。 */ BzL4Metrics?: string /** * 七层可选按qps衡量。 */ BzL7Metrics?: string } /** * DeleteTrafficMirror请求参数结构体 */ export interface DeleteTrafficMirrorRequest { /** * 流量镜像实例ID数组,可以批量删除,每次删除上限为20 */ TrafficMirrorIds: Array<string> } /** * CreateL7Listeners请求参数结构体 */ export interface CreateL7ListenersRequest { /** * 负载均衡实例ID */ LoadBalancerId: string /** * 七层监听器信息数组,可以创建多个七层监听器。目前一个负载均衡下面最多允许创建50个七层监听器。 */ ListenerSet: Array<CreateL7Listener> } /** * 待与四层监听器绑定的物理机主机、虚拟机或半托管主机信息。目前一个四层监听器下面最多允许绑定255个主机端口。 */ export interface BindL4Backend { /** * 待绑定的主机端口,可选值1~65535。 */ Port: number /** * 待绑定的黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId: string /** * 待绑定的主机权重,可选值0~100。 */ Weight: number /** * 自定义探测的主机端口,可选值1~65535。(需要监听器开启自定义健康检查) */ ProbePort?: number } /** * DescribeL7ListenersEx请求参数结构体 */ export interface DescribeL7ListenersExRequest { /** * 返回的监听器中标识是否绑定在此流量镜像中。 */ TrafficMirrorId: string /** * 待获取监听器所在的VPC的ID。 */ VpcId: string /** * 此VPC中获取负载均衡的偏移。 */ Offset?: number /** * 此VPC中获取负载均衡的数量。 */ Limit?: number /** * 过滤条件。 LoadBalancerId - String - (过滤条件)负载均衡ID。 LoadBalancerName - String - (过滤条件)负载均衡名称。 Vip - String - (过滤条件)VIP。 ListenerId - String - (过滤条件)监听器ID。 ListenerName - String - (过滤条件)监听器名称。 Protocol - String - (过滤条件)七层协议。 LoadBalancerPort - String - (过滤条件)监听器端口。 */ Filters?: Array<Filter> } /** * DescribeLoadBalancerTaskResult返回参数结构体 */ export interface DescribeLoadBalancerTaskResultResponse { /** * 任务当前状态。0:成功,1:失败,2:进行中。 */ Status?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * UnbindTrafficMirrorReceivers请求参数结构体 */ export interface UnbindTrafficMirrorReceiversRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 待绑定的主机实例ID和端口数组。 */ ReceiverSet: Array<UnbindTrafficMirrorReceiver> } /** * UnbindTrafficMirrorListeners请求参数结构体 */ export interface UnbindTrafficMirrorListenersRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 七层监听器实例ID数组,可通过接口DescribeL7Listeners查询。 */ ListenerIds: Array<string> } /** * DescribeCertDetail请求参数结构体 */ export interface DescribeCertDetailRequest { /** * 证书ID。 */ CertId: string } /** * DescribeDevicesBindInfo返回参数结构体 */ export interface DescribeDevicesBindInfoResponse { /** * 返回的负载均衡绑定信息。 */ LoadBalancerSet?: Array<DevicesBindInfoLoadBalancer> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取黑石负载均衡端口相关信息时返回的监听器信息(四层和七层)。 */ export interface LoadBalancerPortInfoListener { /** * 负载均衡监听器ID。 */ ListenerId?: string /** * 监听器名称。 */ ListenerName?: string /** * 监听器协议类型,可选值:http,https,tcp,udp。 */ Protocol?: string /** * 监听器的监听端口。 */ LoadBalancerPort?: number /** * 计费模式为按固定带宽方式时监听器的限速值,单位:Mbps。 */ Bandwidth?: number /** * 监听器当前状态(0代表创建中,1代表正常运行,2代表创建失败,3代表删除中,4代表删除失败)。 */ Status?: number /** * 与监听器绑定的主机端口。 */ Port: number } /** * DescribeL4Backends返回参数结构体 */ export interface DescribeL4BackendsResponse { /** * 返回的绑定关系列表。 */ BackendSet?: Array<L4Backend> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 用于创建四层监听器的监听器信息。目前一个负载均衡下面最多允许创建50个监听器。 */ export interface CreateL4Listener { /** * 监听器监听端口,可选值1~65535。 */ LoadBalancerPort: number /** * 监听器协议类型,可选值tcp,udp。 */ Protocol: string /** * 监听器名称。 */ ListenerName: string /** * 监听器的会话保持时间,单位:秒。可选值:900~3600,不传表示不开启会话保持。 */ SessionExpire?: number /** * 是否开启健康检查:1(开启)、0(关闭)。默认值0,表示关闭。 */ HealthSwitch?: number /** * 健康检查的响应超时时间,可选值:2-60,默认值:2,单位:秒。<br><font color="red">响应超时时间要小于检查间隔时间。</font> */ TimeOut?: number /** * 健康检查检查间隔时间,默认值:5,可选值:5-300,单位:秒。 */ IntervalTime?: number /** * 健康阈值,默认值:3,表示当连续探测三次健康则表示该转发正常,可选值:2-10,单位:次。 */ HealthNum?: number /** * 不健康阈值,默认值:3,表示当连续探测三次不健康则表示该转发不正常,可选值:2-10,单位:次。 */ UnhealthNum?: number /** * 监听器最大带宽值,用于计费模式为固定带宽计费,可选值:0-1000,单位:Mbps。 */ Bandwidth?: number /** * 是否开启自定义健康检查:1(开启)、0(关闭)。默认值0,表示关闭。(该字段在健康检查开启的情况下才生效) */ CustomHealthSwitch?: number /** * 自定义健康探测内容类型,可选值:text(文本)、hexadecimal(十六进制)。 */ InputType?: string /** * 探测内容类型为文本方式时,针对请求文本中换行替换方式。可选值:1(替换为LF)、2(替换为CR)、3(替换为LF+CR)。 */ LineSeparatorType?: number /** * 自定义探测请求内容。 */ HealthRequest?: string /** * 自定义探测返回内容。 */ HealthResponse?: string /** * 是否开启toa。可选值:0(关闭)、1(开启),默认关闭。(该字段在负载均衡为fullnat类型下才生效) */ ToaFlag?: number } /** * DescribeTrafficMirrorListeners返回参数结构体 */ export interface DescribeTrafficMirrorListenersResponse { /** * 监听器列表。 */ ListenerSet?: Array<TrafficMirrorListener> /** * 监听器总数。 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeLoadBalancers返回参数结构体 */ export interface DescribeLoadBalancersResponse { /** * 返回负载均衡信息列表。 */ LoadBalancerSet?: Array<LoadBalancer> /** * 符合条件的负载均衡总数。 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteL7Rules返回参数结构体 */ export interface DeleteL7RulesResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取证书信息时返回的所用在的负载均衡信息。 */ export interface CertDetailLoadBalancer { /** * 黑石负载均衡实例ID。 */ LoadBalancerId?: string /** * 黑石负载均衡实例名称。 */ LoadBalancerName?: string /** * 该黑石负载均衡所在的VpcId。 */ VpcId?: string /** * 该黑石负载均衡所在的regionId。 */ RegionId?: number } /** * DescribeTrafficMirrorReceivers请求参数结构体 */ export interface DescribeTrafficMirrorReceiversRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 接收机黑石物理机实例ID数组。 */ InstanceIds?: Array<string> /** * 接收机接收端口数组。 */ Ports?: Array<number> /** * 接收机实例权重数组。 */ Weights?: Array<number> /** * 分页的偏移量,也即从第几条记录开始查询 */ Offset?: number /** * 单次查询返回的条目数,默认值:500。 */ Limit?: number /** * 搜索instance或者alias */ VagueStr?: string /** * 搜索IP */ VagueIp?: string } /** * SetTrafficMirrorAlias请求参数结构体 */ export interface SetTrafficMirrorAliasRequest { /** * 流量镜像实例ID。 */ TrafficMirrorId: string /** * 流量镜像实例别名。 */ Alias: string } /** * UnbindL4Backends返回参数结构体 */ export interface UnbindL4BackendsResponse { /** * 任务ID。该接口为异步任务,可根据本参数调用DescribeLoadBalancerTaskResult接口来查询任务操作结果。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 查询绑定了某主机七层监听器时返回的与转发路径所绑定的主机信息。 */ export interface L7ListenerInfoBackend { /** * 绑定类别(0代表黑石物理机,1代表虚拟机IP)。 */ BindType?: number /** * 主机端口。 */ Port?: number /** * 权重。 */ Weight?: number /** * 当前绑定关系的健康检查状态(Dead代表不健康,Alive代表健康)。 */ Status?: string /** * 黑石物理机的主机ID。 */ InstanceId?: string /** * 黑石物理机的别名。 */ Alias?: string /** * 主机IP。 */ LanIp?: string } /** * ModifyLoadBalancerChargeMode请求参数结构体 */ export interface ModifyLoadBalancerChargeModeRequest { /** * 负载均衡实例ID。 */ LoadBalancerId: string /** * 计费方式。flow或bandwidth。 */ PayMode: string /** * 监听器信息,当计费方式选为 bandwidth 且此负载均衡实例下存在监听器时需填入此字段,可以自定义每个监听器带宽上限。 */ ListenerSet?: Array<ModifyLoadBalancerChargeModeListener> } /** * ModifyL4BackendWeight请求参数结构体 */ export interface ModifyL4BackendWeightRequest { /** * 负载均衡实例ID,可通过接口DescribeLoadBalancers查询。 */ LoadBalancerId: string /** * 负载均衡四层监听器ID,可通过接口DescribeL4Listeners查询。 */ ListenerId: string /** * 黑石物理机主机ID、虚拟机IP或者是半托管主机ID。 */ InstanceId: string /** * 权重信息,可选值0~100。 */ Weight: number /** * 已绑定的主机端口。 */ Port: number /** * 绑定类型。0:物理机 1:虚拟机 2:半托管机器 */ BindType: number } /** * 获取负载均衡实例列表时返回的负载均衡信息。 */ export interface LoadBalancer { /** * 负载均衡器ID */ LoadBalancerId?: string /** * 项目ID,通过v2/DescribeProject 接口获得 */ ProjectId?: number /** * 负载均衡器名称 */ LoadBalancerName?: string /** * 负载均衡的类型 : open表示公网负载均衡类型,internal表示内网负载均衡类型 */ LoadBalancerType?: string /** * 是否筛选独占集群,0表示非独占集群,1表示四层独占集群,2表示七层独占集群,3表示四层和七层独占集群,4表示共享容灾 */ Exclusive?: number /** * 该负载均衡对应的tgw集群(fullnat,tunnel,dnat) */ TgwSetType?: string /** * 负载均衡域名。规则:1-60个小写英文字母、数字、点号“.”或连接线“-”。内网类型的负载均衡不能配置该字段 */ Domain?: string /** * 该负载均衡对应的所在的VpcId */ VpcId?: string /** * 该负载均衡对应的所在的SubnetId */ SubnetId?: string /** * 无 */ Status?: number /** * 无 */ PayMode?: string /** * 无 */ LatestPayMode?: string /** * 无 */ CreateTime?: string /** * 无 */ StatusTime?: string /** * 私有网络名称。 */ VpcName?: string /** * 私有网络Cidr。 */ VpcCidrBlock?: string /** * 负载均衡的IPV4的VIP。 */ LoadBalancerVips?: Array<string> /** * 无 */ SupportListenerTypes?: Array<string> /** * 无 */ Bandwidth?: number /** * 负载均衡个性化配置ID */ ConfId?: string /** * 无 */ ConfName?: string /** * 负载均衡的IPV6的VIP。 */ LoadBalancerVipv6s?: Array<string> /** * 负载均衡IP协议类型。ipv4或者ipv6。 */ IpProtocolType?: string /** * 保障型网关计费形式 */ BzPayMode?: string /** * 保障型网关四层计费指标 */ BzL4Metrics?: string /** * 保障型网关七层计费指标 */ BzL7Metrics?: string /** * 该负载均衡对应的所在的整形类型的VpcId */ IntVpcId?: number /** * 负载均衡的IPV6或者IPV4的VIP。 注意:此字段可能返回 null,表示取不到有效值。 */ CurVips?: Array<string> }
the_stack
import * as builder from "botbuilder"; import { TriggerActionDialog } from "../../../utils/TriggerActionDialog"; import { DialogIds } from "../../../utils/DialogIds"; import { DialogMatches } from "../../../utils/DialogMatches"; import { Strings } from "../../../locale/locale"; import * as teams from "botbuilder-teams"; export class O365ConnectorCardActionsDialog extends TriggerActionDialog { private static async step1(session: builder.Session, args?: any | builder.IDialogResult<any>, next?: (args?: builder.IDialogResult<any>) => void): Promise<void> { let choice = session.gettext(Strings.choice); // get the input number for the example to show if the user passed it into the command - e.g. 'show connector card 2' let inputNumber = args.intent.matched[1].trim(); let card; switch (inputNumber) { case "2": { // Actionable cards can have multiple sections, each with its own set of actions. // If a section contains only 1 card action, that is automatically expanded let cardAction1 = new teams.O365ConnectorCardActionCard(session) .id("CardsTypeSection1") .name(Strings.multiple_choice) .inputs([ // multiple choice control with required, multiselect, compact style new teams.O365ConnectorCardMultichoiceInput(session) .id("list-1") .title(Strings.pick_a_card) .isMultiSelect(true) .isRequired(true) .style("compact") .choices([ new teams.O365ConnectorCardMultichoiceInputChoice(session).display("Hero Card").value("Hero Card"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display("Thumbnail Card").value("Thumbnail Card"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display("O365 Connector Card").value("O365 Connector Card"), ]), ]) .actions([ new teams.O365ConnectorCardHttpPOST(session) .id("cardAction-1-btn-1") .name(Strings.send) .body(JSON.stringify({ list1: "{{list-1.value}}", })), ]); let section1 = new teams.O365ConnectorCardSection(session) .markdown(true) .title(Strings.section_title1) .potentialAction([cardAction1]); // text input examples let cardAction2 = new teams.O365ConnectorCardActionCard(session) .id("cardAction-2") .name(Strings.text_input) .inputs([ // text input control with multiline new teams.O365ConnectorCardTextInput(session) .id("text-1") .title(Strings.text_box_title) .isMultiline(true), ]) .actions([ new teams.O365ConnectorCardHttpPOST(session) .id("cardAction-2-btn-1") .name(Strings.send) .body(JSON.stringify({ text1: "{{text-1.value}}", })), ]); let cardAction3 = new teams.O365ConnectorCardActionCard(session) .id("CardsTypeSection2") .name(Strings.multiple_choice) .inputs([ // multiple choice control with not required, multiselect, compact style new teams.O365ConnectorCardMultichoiceInput(session) .id("list-2") .title(Strings.combo_box_title) .isMultiSelect(true) .isRequired(false) .style("compact") .choices([ new teams.O365ConnectorCardMultichoiceInputChoice(session).display("Hero Card").value("Hero Card"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display("Thumbnail Card").value("Thumbnail Card"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display("O365 Connector Card").value("O365 Connector Card"), ]), ]) .actions([ new teams.O365ConnectorCardHttpPOST(session) .id("cardAction-1-btn-2") .name(Strings.send) .body(JSON.stringify({ list5: "{{list-2.value}}", })), ]); let section2 = new teams.O365ConnectorCardSection(session) .markdown(true) .title(Strings.section_title2) .potentialAction([cardAction2, cardAction3]); card = new teams.O365ConnectorCard(session) .summary(Strings.o365_card_summary) .themeColor("#E67A9E") .title(Strings.actionable_card_title) .sections([section1, section2]); break; } case "1": default: { // this is the default example's content // multiple choice (compact & expanded), text input, date and placing images in card let cardAction1 = new teams.O365ConnectorCardActionCard(session) .id("cardAction-1") .name(Strings.multiple_choice) .inputs([ // multiple choice control with required, multiselect, expanded style new teams.O365ConnectorCardMultichoiceInput(session) .id("list-1") .title(Strings.pick_multiple_options) .isMultiSelect(true) .isRequired(true) .style("expanded") .choices([ new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " 1").value("1"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " 2").value("2"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " 3").value("3"), ]), // multiple choice control with required, multiselect, compact style new teams.O365ConnectorCardMultichoiceInput(session) .id("list-2") .title(Strings.pick_multiple_options) .isMultiSelect(true) .isRequired(true) .style("compact") .choices([ new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " 4").value("4"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " 5").value("5"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " 6").value("6"), ]), // multiple choice control with single item select, expanded style new teams.O365ConnectorCardMultichoiceInput(session) .id("list-3") .title(Strings.pick_an_option) .isMultiSelect(false) .style("expanded") .choices([ new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " a").value("a"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " b").value("b"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " c").value("c"), ]), // multiple choice control with single item select, compact style new teams.O365ConnectorCardMultichoiceInput(session) .id("list-4") .title(Strings.pick_an_option) .isMultiSelect(false) .style("compact") .choices([ new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " x").value("x"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " y").value("y"), new teams.O365ConnectorCardMultichoiceInputChoice(session).display(choice + " z").value("z"), ]), ]) .actions([ new teams.O365ConnectorCardHttpPOST(session) .id("cardAction-1-btn-1") .name(Strings.send) .body(JSON.stringify({ list1: "{{list-1.value}}", list2: "{{list-2.value}}", list3: "{{list-3.value}}", list4: "{{list-4.value}}", })), ]); // text input examples let cardAction2 = new teams.O365ConnectorCardActionCard(session) .id("cardAction-2") .name(Strings.text_input) .inputs([ // text input control with multiline new teams.O365ConnectorCardTextInput(session) .id("text-1") .title(Strings.multiline_no_max) .isMultiline(true), // text input control without multiline new teams.O365ConnectorCardTextInput(session) .id("text-2") .title(Strings.singleline_no_max) .isMultiline(false), // text input control with multiline, reuired, // and control the length of input box new teams.O365ConnectorCardTextInput(session) .id("text-3") .title(Strings.multiline_max_ten) .isMultiline(true) .isRequired(true) .maxLength(10), // text input control without multiline, reuired, // and control the length of input box new teams.O365ConnectorCardTextInput(session) .id("text-4") .title(Strings.singleline_max_ten) .isMultiline(false) .isRequired(true) .maxLength(10), ]) .actions([ new teams.O365ConnectorCardHttpPOST(session) .id("cardAction-2-btn-1") .name(Strings.send) .body(JSON.stringify({ text1: "{{text-1.value}}", text2: "{{text-2.value}}", text3: "{{text-3.value}}", text4: "{{text-4.value}}", })), ]); // date / time input examples let cardAction3 = new teams.O365ConnectorCardActionCard(session) .id("cardAction-3") .name(Strings.date_input) .inputs([ // date input control, with date and time, required new teams.O365ConnectorCardDateInput(session) .id("date-1") .title(Strings.date_with_time) .includeTime(true) .isRequired(true), // date input control, only date, no time, not required new teams.O365ConnectorCardDateInput(session) .id("date-2") .title(Strings.date_only) .includeTime(false) .isRequired(false), ]) .actions([ new teams.O365ConnectorCardHttpPOST(session) .id("cardAction-3-btn-1") .name(Strings.send) .body(JSON.stringify({ date1: "{{date-1.value}}", date2: "{{date-2.value}}", })), ]); let section = new teams.O365ConnectorCardSection(session) .markdown(true) .title(Strings.section_title) .text(Strings.section_text) .activityTitle(Strings.activity_title) .activitySubtitle(Strings.activity_subtitle) .activityImage("http://connectorsdemo.azurewebsites.net/images/MSC12_Oscar_002.jpg") .activityText(Strings.activity_text) .facts([ new teams.O365ConnectorCardFact(session).name(Strings.fact_name_1).value(Strings.fact_value_1), new teams.O365ConnectorCardFact(session).name(Strings.fact_name_2).value(Strings.fact_value_2), ]) .images([ new teams.O365ConnectorCardImage(session).title(Strings.image_one).image("http://connectorsdemo.azurewebsites.net/images/WIN12_Anthony_02.jpg"), new teams.O365ConnectorCardImage(session).title(Strings.image_two).image("http://connectorsdemo.azurewebsites.net/images/WIN12_Scene_01.jpg"), new teams.O365ConnectorCardImage(session).title(Strings.image_three).image("http://connectorsdemo.azurewebsites.net/images/WIN12_Anthony_02.jpg"), ]); card = new teams.O365ConnectorCard(session) .summary(Strings.o365_card_summary) .themeColor("#E67A9E") .title(Strings.card_title) .text(Strings.card_text) .sections([section]) .potentialAction([ cardAction1, cardAction2, cardAction3, new teams.O365ConnectorCardViewAction(session) .name(Strings.view_action) .target("http://microsoft.com"), new teams.O365ConnectorCardOpenUri(session) .id("open-uri") .name(Strings.open_uri) .default("http://microsoft.com") .iOS("http://microsoft.com") .android("http://microsoft.com") .windowsPhone("http://microsoft.com"), ]); } } let msg = new teams.TeamsMessage(session) .summary(Strings.message_summary) .attachments([card]); session.send(msg); session.endDialog(); } constructor( bot: builder.UniversalBot, ) { super(bot, DialogIds.O365ConnectorCardActionsDialogId, DialogMatches.O365ConnectorCardActionsDialogMatch, O365ConnectorCardActionsDialog.step1, ); } }
the_stack
import { HTMLDocument } from "./deps/dom.ts"; /** The data of a page */ export interface Data { /** List of tags assigned to a page or folder */ tags?: string[]; /** The url of a page */ url?: string | ((page: Page) => string); /** If is `true`, the page will be visible only in `dev` mode */ draft?: boolean; /** The date creation of the page */ date?: Date; /** To configure the render order of a page */ renderOrder?: number; /** The content of a page */ content?: unknown; /** The layout used to render a page */ layout?: string; /** To configure a different template engine(s) to render a page */ templateEngine?: string | string[]; [index: string]: unknown; } /** A generic helper to be used in template engines */ export type Helper = (...args: unknown[]) => unknown | Promise<unknown>; /** The options for a template helper */ export interface HelperOptions { /** The type of the helper (tag, filter, etc) */ type: string; /** Whether the helper returns an instance or not */ async?: boolean; /** Whether the helper has a body or not (used for tag types) */ body?: boolean; } /** The event types */ export type EventType = | "beforeBuild" | "afterBuild" | "beforeUpdate" | "afterUpdate" | "afterRender" | "beforeSave"; /** An event object */ export interface Event { /** The event type */ type: EventType; /** * Available only in "beforeUpdate" and "afterUpdate" * contains the files that were changed */ files?: Set<string>; } /** An event listener */ export type EventListener = (event: Event) => unknown; /** The .src property for a Page or Directory */ export interface Src { /** The path to the file (without extension) */ path: string; /** The extension of the file (undefined for folders) */ ext?: string; /** The last modified time */ lastModified?: Date; /** The creation time */ created?: Date; } /** The .dest property for a Page */ export interface Dest { /** The path to the file (without extension) */ path: string; /** The extension of the file */ ext: string; /** The hash (used to detect content changes) */ hash?: string; } /** The .content property for a Page */ export type Content = Uint8Array | string; /** A command executed by a script */ export type Command = string | ((site: Site) => unknown) | Command[]; /** The options for a Command */ export type CommandOptions = Omit<Deno.RunOptions, "cmd">; /** A function that loads and returns the file content */ export type Loader = (path: string) => Promise<Data>; /** The options to configure the site build */ export interface SiteOptions { /** The path of the current working directory */ cwd: string; /** The path of the site source */ src: string; /** The path of the built destination */ dest: string; /** The default includes path */ includes: string; /** Set `true` to enable the `dev` mode */ dev: boolean; /** The site location (used to generate final urls) */ location: URL; /** Set true to collect metrics and measure the build performance */ metrics: boolean; /** Set true to generate pretty urls (`/about-me/`) */ prettyUrls: boolean; /** The list of flags to pass to the site build */ flags: string[]; /** Set `true` to skip logs */ quiet: boolean; /** Set `true` for testing mode (output files won't be saved in `dest` folder) */ test: boolean; /** The local server options */ server: ServerOptions; } /** The options to configure the local server */ export interface ServerOptions { /** The port to listen on */ port: number; /** To open the server in a browser */ open: boolean; /** The file to serve on 404 error */ page404: string; } /** A (pre)processor */ export type Processor = (page: Page, site: Site) => void; /** The method that installs a plugin */ export type PluginSetup = ((options: unknown) => Plugin); /** A generic Lume plugin */ export type Plugin = (site: Site) => void; /** An interface used by all template engines */ export interface Engine { /** Render a template */ render( content: unknown, data: Data, filename: string, ): unknown | Promise<unknown>; /** Add a helper to the template engine */ addHelper( name: string, fn: Helper, options: HelperOptions, ): void; } /** A page */ export interface Page { /** The directory this page is in */ parent?: Directory; /** The src info of this page */ src: Src; /** The destination of the page */ dest: Dest; /** Is `true` if the data assigned to this page was merged */ dataLoaded: boolean; /** The associated merged data */ data: Data; /** Internal data, used by plugins, processors, etc to save arbitrary values */ _data: Record<string, unknown>; /** The content of this page */ content?: Content; /** The parsed HTML code from the content */ document?: HTMLDocument; /** Duplicate this page. Optionally, you can provide new data */ duplicate(data?: Data): Page; /** Refresh the cached merged data (used for rebuild) */ refreshCache(): void; /** Merge more data with the existing */ addData(data: Data): void; } /** A directory */ export interface Directory { /** The parent directory */ parent?: Directory; /** The src info of this directory */ src: Src; /** * Is `true` if the data assigned to this directory was loaded * _data or _data.* files, and merged */ dataLoaded: boolean; /** The associated merged data */ data: Data; /** The list of pages included in this directory */ pages: Map<string, Page>; /** The list os subdirectories */ dirs: Map<string, Directory>; /** Create a subdirectory and return it */ createDirectory(name: string): Directory; /** Add a page to this directory */ setPage(name: string, page: Page): void; /** Remove a page from this directory */ unsetPage(name: string): void; /** Return the list of pages in this directory recursively */ getPages(): Iterable<Page>; /** Refresh the data cache in this directory recursively (used for rebuild) */ refreshCache(): void; /** Merge more data with the existing */ addData(data: Data): void; } /** A source loader */ export interface Source { /** The Site instance associated with this source */ site: Site; /** The root of the src directory */ root: Directory; /** List of extensions to load data files and the loader used */ data: Map<string, Loader>; /** List of extensions to load page files and the loader used */ pages: Map<string, Loader>; /** List of files and folders to copy */ staticFiles: Map<string, string>; /** List of extensions that must be treated as assets (`.css`, `.js`, etc) */ assets: Set<string>; /** The list of paths to ignore */ ignored: Set<string>; /** Return the File or Directory of a path */ getFileOrDirectory(path: string): Directory | Page | undefined; /** * Check whether a file is included in the list of static files * and return a [from, to] tuple */ isStatic(file: string): [string, string] | false; /** Check whether a path is ignored or not */ isIgnored(path: string): boolean; /** Load a directory recursively */ loadDirectory(directory?: Directory): Promise<void>; /** Reload a file */ loadFile(file: string): Promise<void>; /** Load a file using a loader */ load(path: string, loader: Loader): Promise<Data>; } /** A script runner */ export interface Scripts { /** All registered scripts */ scripts: Map<string, Command[]>; /** Register a new script */ set(name: string, ...commands: Command[]): void; /** Run one or more scripts */ run(options: CommandOptions, ...names: Command[]): Promise<boolean>; } /** A site builder */ export interface Site { /** The site options */ options: SiteOptions; /** The source handler instance */ source: Source; /** The script runner instance */ scripts: Scripts; /** The metric handler instance */ metrics: Metrics; /** Template engines by extension */ engines: Map<string, Engine>; /** The registered helpers */ helpers: Map<string, [Helper, HelperOptions]>; /** Extra data to be passed to the layouts */ extraData: Record<string, unknown>; /** Event listeners */ listeners: Map<EventType, Set<EventListener | string>>; /** All preprocessors */ preprocessors: Map<Processor, string[]>; /** All processors */ processors: Map<Processor, string[]>; /** List of pages generated by the build */ pages: Page[]; /** Flags passed after `--` */ flags: string[]; /** To store the includes paths by extension */ includes: Map<string, string>; /** Return the src path */ src(...path: string[]): string; /** Return the dest path */ dest(...path: string[]): string; /** Add an event */ addEventListener(type: EventType, listener: EventListener | string): this; /** Dispatch an event */ dispatchEvent(event: Event): Promise<boolean>; /** Use a plugin */ use(plugin: Plugin): this; /** Register a script */ script(name: string, ...scripts: Command[]): this; /** Register a data loader for some extensions */ loadData(extensions: string[], loader: Loader): this; /** Register a page loader for some extensions */ loadPages(extensions: string[], loader?: Loader, engine?: Engine): this; /** Register an assets loader for some extensions */ loadAssets(extensions: string[], loader?: Loader): this; /** Register a preprocessor for some extensions */ preprocess(extensions: string[], preprocessor: Processor): this; /** Register a processor for some extensions */ process(extensions: string[], processor: Processor): this; /** Register a template filter */ filter(name: string, filter: Helper, async?: boolean): this; /** Register a template helper */ helper(name: string, fn: Helper, options: HelperOptions): this; /** Register extra data accessible by layouts */ data(name: string, data: unknown): this; /** Copy static files or directories without processing */ copy(from: string, to?: string): this; /** Ignore one or several files or directories */ ignore(...paths: string[]): this; /** Clear the dest directory */ clear(): Promise<void>; /** Build the entire site */ build(watchMode: boolean): Promise<void>; /** Reload some files that might be changed */ update(files: Set<string>): Promise<void>; /** Run a script */ run(name: string, options?: CommandOptions): Promise<boolean>; /** Return the URL of a page */ url(path: string, absolute?: boolean): string; /** Return the content of a file of the site */ getFileContent(url: string): Promise<string | Uint8Array>; } /** A collection of all metrics */ export interface Metrics { /** Start measuring */ start(name: string, details?: MetricDetail): Metric; /** Print the metrics in the console */ print(): void; /** Save the metrics data in a file */ save(file: string): Promise<void>; } /** A single metric */ export interface Metric { /** The metric name */ name: string; /** Additional info of the metric */ details?: MetricDetail; /** Stop measuring */ stop(): void; } /** The details associated to a metric */ export interface MetricDetail { /** Page related with this metric */ page?: Page; [key: string]: unknown; }
the_stack
import allSettled from 'promise.allsettled'; import { Writer } from '@transcend-io/conflux'; // import streamSaver from 'streamsaver'; import { createWriteStream } from 'streamsaver'; import mime from 'mime-types'; // import { WritableStreamPonyfill, WritableStreamIsNative } from './streams'; import { PenumbraFile, ZipOptions } from './types'; import { isNumber, emitZipProgress, emitZipCompletion } from './utils'; import { Compression } from './enums'; import { ReadableStream } from './streams'; import throwOutside from './utils/throwOutside'; const sumWrites = async (writes: Promise<number>[]): Promise<number> => { const results = await allSettled<Promise<number>[]>(writes); const sum = (results.filter( ({ status }) => status === 'fulfilled', ) as PromiseFulfilledResult<number>[]) .map(({ value }) => value) .reduce((acc, item) => acc + item, 0); if (results.some(({ status }) => status === 'rejected')) { const errors = results.filter( ({ status }) => status === 'rejected', ) as PromiseRejectedResult[]; // eslint-disable-next-line no-restricted-syntax for (const error of errors) { console.error(error.reason); } // Throw AggregateError to console throwOutside( // eslint-disable-next-line @typescript-eslint/no-explicit-any new (self as any).AggregateError( errors, `File${errors.length > 1 ? 's' : ''} failed to be written to zip`, ), ); } return sum; }; /** * Save a zip containing files retrieved by Penumbra * * @example new PenumbraZipWriter(options) * @param options - ZipOptions * @returns PenumbraZipWriter class instance */ export class PenumbraZipWriter extends EventTarget { /** Conflux zip writer instance */ private conflux: Writer = new Writer(); /** Conflux WritableStream interface */ private writer: WritableStreamDefaultWriter = this.conflux.writable.getWriter(); /** Save completion state */ private closed = false; /** Save complete buffer */ private saveBuffer = false; /** Zip buffer used for testing */ private zipBuffer: Promise<ArrayBuffer> | undefined; /** Allow & auto-rename duplicate files sent to writer */ private allowDuplicates: boolean; /** All written & pending file paths */ private files = new Set<string>(); /** Abort controller */ private controller: AbortController; /** All pending finished and unfinished zip file writes */ private writes: Promise<number>[] = []; /** Number of finished zip file writes */ private completedWrites = 0; /** Total zip archive size */ private byteSize: number | null = 0; /** Current zip archive size */ private bytesWritten = 0; /** * Penumbra zip writer constructor * * @param options - ZipOptions * @returns PenumbraZipWriter class instance */ constructor(options: ZipOptions = {}) { super(); const { name = 'download', size, files, controller = new AbortController(), compressionLevel = Compression.Store, saveBuffer = false, allowDuplicates = true, onProgress, onComplete, } = options; if (compressionLevel !== Compression.Store) { throw new Error( // eslint-disable-next-line max-len 'penumbra.saveZip() does not support compression yet. Voice your support here: https://github.com/transcend-io/penumbra/issues', ); } if (isNumber(size)) { this.byteSize = size; } this.allowDuplicates = allowDuplicates; this.controller = controller; const { signal } = controller; signal.addEventListener( 'abort', () => { this.close(); }, { once: true }, ); // Auto-register onProgress & onComplete listeners if (typeof onProgress === 'function') { this.addEventListener('progress', onProgress as EventListener); } if (typeof onComplete === 'function') { this.addEventListener('complete', onComplete as EventListener, { once: true, }); } const saveStream = createWriteStream( // Append .zip to filename unless it is already present /\.zip\s*$/i.test(name) ? name : `${name}.zip`, size, ); const { readable } = this.conflux; const [zipStream, bufferedZipStream]: [ ReadableStream, ReadableStream | null, ] = saveBuffer ? readable.tee() : [readable, null]; zipStream.pipeTo(saveStream, { signal }); // Buffer zip stream for debug & testing if (saveBuffer && bufferedZipStream) { this.saveBuffer = saveBuffer; this.zipBuffer = new Response(bufferedZipStream).arrayBuffer(); } if (files) { this.write(...files); } } /** * Get observed zip size after all pending writes are resolved */ getSize(): Promise<number> { return sumWrites(this.writes); } /** * Add decrypted PenumbraFiles to zip * * @param files - Decrypted PenumbraFile[] to add to zip * @returns Total observed size of write call in bytes */ async write(...files: PenumbraFile[]): Promise<number> { // eslint-disable-next-line @typescript-eslint/no-this-alias const zip = this; // Add file sizes to total zip size const sizes = files.map(({ size }) => size); const totalWriteSize = sizes.every((size) => isNumber(size)) ? (sizes as number[]).reduce((acc, val) => acc + val, 0) : null; if (zip.byteSize !== null) { if (totalWriteSize === null) { zip.byteSize = null; } else { zip.byteSize += totalWriteSize; } } return sumWrites( files.map( async ({ path, filePrefix, stream, mimetype, lastModified = new Date(), }) => { let writeSize = 0; // Resolve file path const name = path || filePrefix; if (!name) { throw new Error( 'PenumbraZipWriter.write(): Unable to determine filename', ); } const [ filename, extension = mimetype ? mime.extension(mimetype) : '', ] = name .split(/(\.\w+\s*$)/) // split filename extension .filter(Boolean); // filter empty matches let filePath = `${filename}${extension}`; // Handle duplicate files if (zip.files.has(filePath)) { const dupe = filePath; // This code picks a filename when auto-renaming conflicting files. // If {filename}{extension} exists it will create {filename} (1){extension}, etc. let i = 0; // eslint-disable-next-line no-plusplus while (zip.files.has(`${filename} (${++i})${extension}`)); filePath = `${filename} (${i})${extension}`; const warning = `penumbra.saveZip(): Duplicate file ${JSON.stringify( dupe, )}`; if (zip.allowDuplicates) { console.warn(`${warning} renamed to ${JSON.stringify(filePath)}`); } else { zip.abort(); throw new Error(warning); } } zip.files.add(filePath); const reader = stream.getReader(); const writeComplete = new Promise<number>((resolve) => { const completionTrackerStream = new ReadableStream({ /** Start completion tracker-wrapped ReadableStream */ async start(controller) { // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-next-line no-await-in-loop const { done, value } = await reader.read(); if (value) { const chunkSize = value.byteLength; writeSize += chunkSize; if (zip.byteSize !== null) { zip.bytesWritten += chunkSize; emitZipProgress(zip, zip.bytesWritten, zip.byteSize); } } // When no more data needs to be consumed, break the reading if (done) { resolve(writeSize); // eslint-disable-next-line no-plusplus zip.completedWrites++; // Emit file-granular progress events when total byte size can't be determined if (zip.byteSize === null) { emitZipProgress( zip, zip.completedWrites, zip.writes.length, ); } if (zip.completedWrites >= zip.writes.length) { emitZipCompletion(zip); } // Re-calculate zip.byteSize after indeterminate writes if (totalWriteSize === null) { let size = 0; // eslint-disable-next-line no-await-in-loop, no-restricted-syntax for await (const write of zip.writes) { size += write; } if (zip.byteSize === null) { zip.byteSize = size; } } break; } // Enqueue the next data chunk into our target stream controller.enqueue(value); } // Close the stream controller.close(); reader.releaseLock(); }, }); zip.writer.write({ name: filePath, lastModified, stream: () => completionTrackerStream, }); }); zip.writes.push(writeComplete); return writeComplete; }, ), ); } /** * Enqueue closing of the Penumbra zip writer (after pending writes finish) * * @returns Total observed zip size in bytes after close completes */ async close(): Promise<number> { const size = this.getSize(); if (!this.closed) { this.writer.close(); this.closed = true; } return size; } /** Cancel Penumbra zip writer */ abort(): void { if (!this.controller.signal.aborted) { this.controller.abort(); } } /** Get buffered output (requires saveBuffer mode) */ getBuffer(): Promise<ArrayBuffer> { if (!this.closed) { throw new Error( 'getBuffer() can only be called when a PenumbraZipWriter is closed', ); } if (!this.saveBuffer || !this.zipBuffer) { throw new Error( 'getBuffer() can only be called on a PenumbraZipWriter in buffered mode, e.g. createZip({ saveBuffer: true })', ); } return this.zipBuffer; } /** Get all written & pending file paths */ getFiles(): string[] { return [...this.files]; } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of the author nor the names of the program's contributors may 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 AUTHORS OF THE SOFTWARE 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. */ /** * @fileoverview Describes an aircraft that is being tracked. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.suppressTrails = VRS.globalOptions.suppressTrails || false; // If true then position history is not stored, significantly reducing memory footprint for each aircraft but prevents trails from being shown for the aircraft VRS.globalOptions.aircraftHideUncertainCallsigns = VRS.globalOptions.aircraftHideUncertainCallsigns !== undefined ? VRS.globalOptions.aircraftHideUncertainCallsigns : false; // True if callsigns that we're not 100% sure about are to be hidden from view. VRS.globalOptions.aircraftMaxAvgSignalLevelHistory = VRS.globalOptions.aircraftMaxAvgSignalLevelHistory !== undefined ? VRS.globalOptions.aircraftMaxAvgSignalLevelHistory : 6; // The number of signal levels to average out to determine average signal level. Don't make this more than about 10. /** * An object that carries an abstract value and a flag indicating whether it has changed or not. */ export class Value<T> { val: T; chg: boolean = false; constructor(value?: T) { this.val = value; } /** * Forces a value onto the object and always sets the chg flag. This is used more by reports when creating fake * aircraft to ensure that all values set up for a fake aircraft will trigger a render in the objects that use * them. */ setValue(value: T) { this.val = value; this.chg = true; } } /** * A string value held by an aircraft and whether it changed in the last update. */ export class StringValue extends Value<string> { constructor(value?: string) { super(value); } } /** * A boolean value held by an aircraft and whether it changed in the last update. */ export class BoolValue extends Value<boolean> { constructor(value?: boolean) { super(value); } } /** * A number value held by an aircraft and whether it changed in the last update. */ export class NumberValue extends Value<number> { constructor(value?: number) { super(value); } } /** * Describes an array of values held by an aircraft and whether it changed in the last update. */ export class ArrayValue<T> { /** * The array of values held by the aircraft. */ arr: T[] = []; /** * True if the array changed in the last update refresh. */ chg: boolean = false; /** * The index of the values added by the last update. Only meaningful if chg is true. */ chgIdx: number = -1; /** * The number of array elements trimmed from the start of the array in the last update. */ trimStartCount: number = 0; constructor(initialArray?: T[]) { this.arr = initialArray || []; } /** * Sets the array and configures the other fields to indicate that the entire array is new. Used when setting * up fake aircraft for reports etc. */ setValue(value: T[]) { if(value && value.length) { this.arr = value; this.chg = true; this.chgIdx = 0; this.trimStartCount = 0; } } /** * Sets the fields to indicate that nothing changed in the last update. */ setNoChange() { this.chg = false; this.chgIdx = -1; this.trimStartCount = 0; } /** * Sets the fields to indicate that the array was reset back to an empty state in the last update. */ resetArray() { if(this.arr.length > 0) { this.trimStartCount = this.arr.length; this.arr = []; this.chg = true; this.chgIdx = -1; } } /** * Trims elements from the start of the array and sets the fields to indicate that this has happened. */ trimStart(trimCount: number) { if(trimCount > 0) { if(trimCount > this.arr.length) trimCount = this.arr.length; this.arr.splice(0, trimCount); this.trimStartCount = trimCount; this.chg = true; } } } /** * Describes a route held by an aircraft and whether it changed in the last update. * @param {string} [value] An airport code followed by the description of the airport. * @constructor * @augments VRS.Value */ export class RouteValue extends Value<string> { private _AirportCodeDerivedFromVal: string; private _AirportCode: string; constructor(value?: string) { super(value); } /** * Returns the airport code from the route value. */ getAirportCode() : string { if(this._AirportCodeDerivedFromVal !== this.val) { this._AirportCodeDerivedFromVal = this.val; this._AirportCode = VRS.format.routeAirportCode(this._AirportCodeDerivedFromVal); } return this._AirportCode; } } /** * Describes a set of thumbnails that have been fetched for the aircraft from www.airport-data.com. */ export class AirportDataThumbnailValue extends Value<IAirportDataThumbnails> { private _LastResetChgValue: boolean = false; constructor(value?: IAirportDataThumbnails) { super(value); } /** * Called on every refresh. Thumbnails are set asynchronously, they are set when some code calls a fetch method * for them on VRS.Aircraft. Once the response comes back from the server chg is set to true. We want that chg * value to remain true for the next refresh of the aircraft list and then for all future refreshes it should * be false unless the ICAO changes. This method is called on every refresh - if the chg value has changed from * the previous refresh then it is left alone, otherwise it is set to false. */ resetChg() { if(this.chg && this._LastResetChgValue) this.chg = false; this._LastResetChgValue = this.chg; } } /** * Describes a coordinate held by an aircraft in its short trail. These have no Chg field, the array holding these * values records the index of any new entries. */ export class ShortTrailValue { /** * The latitude of the aircraft. */ lat: number; /** * The longitude of the aircraft. */ lng: number; /** * The time at which the aircraft was observed at the coordinate, in ticks. */ posnTick: number; /** * The altitude, if any, that the aircraft had reached at this point. */ altitude: number; /** * The speed, if any, that the aircraft had reached at this point. */ speed: number; constructor(latitude: number, longitude: number, posnTick: number, altitude: number, speed: number) { this.lat = latitude; this.lng = longitude; this.posnTick = posnTick; this.altitude = altitude; this.speed = speed; } } /** * Describes a coordinate held by an aircraft in its full trail. */ export class FullTrailValue { /** * The latitude of the aircraft. */ lat: number; /** * The longitude of the aircraft. */ lng: number; /** * The heading that the aircraft was pointing in. */ heading: number; /** * The altitude, if any, that the aircraft had reached at this point. */ altitude: number; /** * The speed, if any, that the aircraft had reached at this point. */ speed: number; /** * True when this is the last element in the array. It is set to true if the aircraft changed position but its * heading was the same as it was in the previous update, in which case the last element in the trail is set to * the new position and the polyline describing the trail should just be extended to this new location. */ chg: boolean; constructor(latitude: number, longitude: number, heading: number, altitude?: number, speed?: number) { this.lat = latitude; this.lng = longitude; this.heading = heading; this.altitude = altitude; this.speed = speed; this.chg = false; } } /** * A type alias for the different kinds of trail arrays. */ export type TrailArray = ArrayValue<ShortTrailValue> | ArrayValue<FullTrailValue>; /** * The settings that control how Aircraft.ApplyJson applies updates. */ export interface Aircraft_ApplyJsonSettings { /** * The earliest allowable tick in a short trail list. Coordinates for ticks before this value must be * removed on update. If -1 then no short trails should be recorded. */ shortTrailTickThreshold: number; /** * True if the user can see local pictures. */ picturesEnabled: boolean; } /** * Describes an aircraft tracked by the server. */ export class Aircraft { /** * The aircraft list fetcher that last supplied details for the aircraft. Usually there's just one of these for * the lifetime of the site. * @type {VRS.AircraftListFetcher} * @private */ private _AircraftListFetcher: AircraftListFetcher = null; /** * A fixed length array of the signal levels for the aircraft, used to determine averageSignalLevel. */ private signalLevelHistory: number[] = []; /** * The unique identifier of the aircraft, derived from the ICAO. */ id: number = 0; /** * The number of seconds that the aircraft has been tracked for. */ secondsTracked: number = 0; /** * The number of times the aircraft details have been updated. */ updateCounter: number = 0; // The value fields receiverId: NumberValue = new NumberValue(); icao: StringValue = new StringValue(); icaoInvalid: BoolValue = new BoolValue(); registration: StringValue = new StringValue(); altitude: NumberValue = new NumberValue(); // Pressure altitude geometricAltitude: NumberValue = new NumberValue(); // Geometric altitude airPressureInHg: NumberValue = new NumberValue(); // Air pressure in inches of mercury either transmitted by the aircraft or, failing that, from the closest weather station altitudeType: Value<AltitudeTypeEnum> = new Value<AltitudeTypeEnum>(); // The altitude field that was transmitted by the aircraft targetAltitude: NumberValue = new NumberValue(); callsign: StringValue = new StringValue(); callsignSuspect: BoolValue = new BoolValue(); latitude: NumberValue = new NumberValue(); longitude: NumberValue = new NumberValue(); isMlat: BoolValue = new BoolValue(); positionAgeSeconds: NumberValue = new NumberValue(); positionTime: NumberValue = new NumberValue(); positionStale: BoolValue = new BoolValue(); speed: NumberValue = new NumberValue(); speedType: Value<SpeedTypeEnum> = new Value<SpeedTypeEnum>(); verticalSpeed: NumberValue = new NumberValue(); verticalSpeedType: Value<AltitudeTypeEnum> = new Value<AltitudeTypeEnum>(); heading: NumberValue = new NumberValue(); // The track across the ground that the aircraft is following, unless headingIsTrue is true in which case it's the aircraft's true heading (i.e. the direction the nose is pointing in) headingIsTrue: BoolValue = new BoolValue(); // True if heading is the aircraft's true heading, false if it's the ground track. targetHeading: NumberValue = new NumberValue(); manufacturer: StringValue = new StringValue(); serial: StringValue = new StringValue(); yearBuilt: StringValue = new StringValue(); model: StringValue = new StringValue(); modelIcao: StringValue = new StringValue(); from: RouteValue = new RouteValue(); to: RouteValue = new RouteValue(); via: ArrayValue<RouteValue> = new ArrayValue<RouteValue>(); isCharterFlight: BoolValue = new BoolValue(); isPositioningFlight: BoolValue = new BoolValue(); operator: StringValue = new StringValue(); operatorIcao: StringValue = new StringValue(); squawk: StringValue = new StringValue(); identActive: BoolValue = new BoolValue(); isEmergency: BoolValue = new BoolValue(); distanceFromHereKm: NumberValue = new NumberValue(); bearingFromHere: NumberValue = new NumberValue(); // The bearing from the browser's location to the aircraft, assuming that the browser is pointing due north wakeTurbulenceCat: Value<WakeTurbulenceCategoryEnum> = new Value<WakeTurbulenceCategoryEnum>(); countEngines: StringValue = new StringValue(); engineType: Value<EngineTypeEnum> = new Value<EngineTypeEnum>(); enginePlacement: NumberValue = new NumberValue(); species: Value<SpeciesEnum> = new Value<SpeciesEnum>(); isMilitary: BoolValue = new BoolValue(); isTisb: BoolValue = new BoolValue(); country: StringValue = new StringValue(); hasPicture: BoolValue = new BoolValue(); pictureWidth: NumberValue = new NumberValue(); pictureHeight: NumberValue = new NumberValue(); countFlights: NumberValue = new NumberValue(); countMessages: NumberValue = new NumberValue(); isOnGround: BoolValue = new BoolValue(); userNotes: StringValue = new StringValue(); userTag: StringValue = new StringValue(); userInterested: BoolValue = new BoolValue(); signalLevel: NumberValue = new NumberValue(); averageSignalLevel: NumberValue = new NumberValue(); airportDataThumbnails: AirportDataThumbnailValue = new AirportDataThumbnailValue(); transponderType: Value<TransponderTypeEnum> = new Value<TransponderTypeEnum>(); shortTrail: ArrayValue<ShortTrailValue> = new ArrayValue<ShortTrailValue>(); fullTrail: ArrayValue<FullTrailValue> = new ArrayValue<FullTrailValue>(); /** * Applies details about an individual aircraft's current state to the aircraft object. * In general most of the fields are optional. If they are missing then the value has not * changed. We need to track values that changed so that we only update the UI for those * and not for every value on every refresh. At best that can cause flicker, at worst it * can hammer the browser. */ applyJson(aircraftJson: IAircraftListAircraft, aircraftListFetcher: AircraftListFetcher, settings: Aircraft_ApplyJsonSettings, serverTicks: number) { this.id = aircraftJson.Id; this.secondsTracked = aircraftJson.TSecs; this._AircraftListFetcher = aircraftListFetcher; ++this.updateCounter; this.setValue(this.receiverId, aircraftJson.Rcvr); this.setValue(this.icao, aircraftJson.Icao); this.setValue(this.icaoInvalid, aircraftJson.Bad); this.setValue(this.registration, aircraftJson.Reg); this.setValue(this.altitude, aircraftJson.Alt); this.setValue(this.geometricAltitude, aircraftJson.GAlt); this.setValue(this.airPressureInHg, aircraftJson.InHg); this.setValue(this.altitudeType, aircraftJson.AltT); this.setValue(this.targetAltitude, aircraftJson.TAlt); this.setValue(this.callsign, aircraftJson.Call); this.setValue(this.callsignSuspect, aircraftJson.CallSus); this.setValue(this.latitude, aircraftJson.Lat); this.setValue(this.longitude, aircraftJson.Long); this.setValue(this.isMlat, aircraftJson.Mlat); this.setValue(this.positionTime, aircraftJson.PosTime); this.setValue(this.positionStale, !!aircraftJson.PosStale, true); this.setValue(this.positionAgeSeconds, isNaN(this.positionTime.val) ? undefined : Math.max(0, (serverTicks - this.positionTime.val) / 1000)); this.setValue(this.speed, aircraftJson.Spd); this.setValue(this.speedType, aircraftJson.SpdTyp); this.setValue(this.verticalSpeed, aircraftJson.Vsi); this.setValue(this.verticalSpeedType, aircraftJson.VsiT); this.setValue(this.heading, aircraftJson.Trak); this.setValue(this.headingIsTrue, aircraftJson.TrkH); this.setValue(this.targetHeading, aircraftJson.TTrk); this.setValue(this.manufacturer, aircraftJson.Man); this.setValue(this.serial, aircraftJson.CNum); this.setValue(this.yearBuilt, aircraftJson.Year); this.setValue(this.model, aircraftJson.Mdl); this.setValue(this.modelIcao, aircraftJson.Type); this.setValue(this.from, aircraftJson.From); this.setValue(this.to, aircraftJson.To); this.setValue(this.isCharterFlight, aircraftJson.IsCharterFlight); this.setValue(this.isPositioningFlight, aircraftJson.IsFerryFlight); this.setValue(this.operator, aircraftJson.Op); this.setValue(this.operatorIcao, aircraftJson.OpIcao); this.setValue(this.squawk, aircraftJson.Sqk); this.setValue(this.identActive, aircraftJson.Ident); this.setValue(this.isEmergency, aircraftJson.Help); this.setValue(this.distanceFromHereKm, aircraftJson.Dst, true); this.setValue(this.bearingFromHere, aircraftJson.Brng, true); this.setValue(this.wakeTurbulenceCat, aircraftJson.WTC); this.setValue(this.countEngines, aircraftJson.Engines); this.setValue(this.engineType, aircraftJson.EngType); this.setValue(this.enginePlacement, aircraftJson.EngMount); this.setValue(this.species, aircraftJson.Species); this.setValue(this.isMilitary, aircraftJson.Mil); this.setValue(this.isTisb, aircraftJson.Tisb); this.setValue(this.country, aircraftJson.Cou); this.setValue(this.hasPicture, aircraftJson.HasPic && settings.picturesEnabled); this.setValue(this.pictureWidth, aircraftJson.PicX); this.setValue(this.pictureHeight, aircraftJson.PicY); this.setValue(this.countFlights, aircraftJson.FlightsCount); this.setValue(this.countMessages, aircraftJson.CMsgs); this.setValue(this.isOnGround, aircraftJson.Gnd); this.setValue(this.userNotes, aircraftJson.Notes); this.setValue(this.userTag, aircraftJson.Tag); this.setValue(this.userInterested, aircraftJson.Interested); this.setValue(this.transponderType, aircraftJson.Trt); this.setRouteArray(this.via, aircraftJson.Stops); if(aircraftJson.HasSig !== undefined) { this.setValue(this.signalLevel, aircraftJson.Sig); } this.recordSignalLevelHistory(this.signalLevel.val); if(!VRS.globalOptions.suppressTrails) { this.setShortTrailArray(this.shortTrail, aircraftJson.Cos, aircraftJson.ResetTrail, settings.shortTrailTickThreshold, aircraftJson.TT); this.setFullTrailArray(this.fullTrail, aircraftJson.Cot, aircraftJson.ResetTrail, aircraftJson.TT) } if(VRS.globalOptions.aircraftHideUncertainCallsigns && this.callsignSuspect.val) { this.callsign.val = undefined; this.callsign.chg = false; } this.airportDataThumbnails.resetChg(); } /** * Assigns content to a value object and sets / clears the chg flag. */ private setValue<T>(field: Value<T>, jsonValue: T, alwaysSent?: boolean) { if(jsonValue === undefined) field.chg = false; else if(!alwaysSent) { field.val = jsonValue; field.chg = true; } else { field.chg = field.val !== jsonValue; if(field.chg) field.val = jsonValue; } } /** * Assigns content to an array object. */ private setRouteArray<T>(field: ArrayValue<RouteValue>, jsonArray: string[]) { field.setNoChange(); if(jsonArray) { field.arr = []; field.chg = true; field.chgIdx = 0; $.each(jsonArray, function(idx, val) { field.arr.push(new VRS.RouteValue(val)); }); } } /** * Updates the short trail array. */ private setShortTrailArray(field: ArrayValue<ShortTrailValue>, jsonArray: number[], resetTrail: boolean, shortTrailTickThreshold: number, trailType: string) { field.setNoChange(); var length = field.arr.length; var i = 0; // Clean up expired coordinates first - this must happen even if no new points have been supplied if(length > 0) { if(resetTrail) field.resetArray(); else { if(shortTrailTickThreshold === -1) field.resetArray(); else { var indexFirstValidCoordinate = -1; for(i = 0;i < length;++i) { if(field.arr[i].posnTick >= shortTrailTickThreshold) { indexFirstValidCoordinate = i; break; } } if(indexFirstValidCoordinate !== 0) { if(indexFirstValidCoordinate === -1) field.resetArray(); else field.trimStart(indexFirstValidCoordinate); } } } length = field.arr.length; } // Add the new coordinates to the end of the trail var addLength = jsonArray ? jsonArray.length : 0; if(addLength > 0) { field.chg = true; field.chgIdx = length; for(i = 0;i < addLength;) { var lat = jsonArray[i++]; var lng = jsonArray[i++]; var tik = jsonArray[i++]; var alt = trailType === 'a' ? jsonArray[i++] : undefined; var spd = trailType === 's' ? jsonArray[i++] : undefined; field.arr.push(new VRS.ShortTrailValue(lat, lng, tik, alt, spd)); } } } /** * Manages updates to the full trail for the aircraft. */ private setFullTrailArray(field: ArrayValue<FullTrailValue>, jsonArray: number[], resetTrail: boolean, trailType: string) { field.setNoChange(); var length = field.arr.length; var lastTrail = length ? field.arr[length - 1] : null; var lastButOne = length > 1 ? field.arr[length - 2] : null; if(lastTrail) lastTrail.chg = false; if(resetTrail) { field.resetArray(); length = field.arr.length; } var addLength = jsonArray ? jsonArray.length : 0; if(addLength > 0) { field.chg = true; var i; field.chgIdx = length; for(i = 0;i < addLength;) { var lat = jsonArray[i++]; var lng = jsonArray[i++]; var hdg = jsonArray[i++]; var alt = trailType === 'a' ? jsonArray[i++] : undefined; var spd = trailType === 's' ? jsonArray[i++] : undefined; if(hdg && lastTrail && lastButOne && lastTrail.heading === hdg && lastButOne.heading === hdg && lastTrail.altitude === alt && lastButOne.altitude === alt && lastTrail.speed === spd && lastButOne.speed === spd) { if(lastTrail.lat !== lat || lastTrail.lng !== lng) { lastTrail.lat = lat; lastTrail.lng = lng; lastTrail.chg = true; } } else { lastButOne = lastTrail; lastTrail = new VRS.FullTrailValue(lat, lng, hdg, alt, spd); field.arr.push(lastTrail); ++length; } } // Were they all just updates to the last trail entry? if(field.chgIdx === length) { field.chgIdx = -1; } else { // Nope, we had to add at least one new point. We need to reset the chg flag and, if we had changed // what had been the latest trail point, then we need to indicate that it's a new point so that it // all joins up correctly. var oldLastIndex = field.chgIdx - 1; for(i = Math.max(0, field.chgIdx - 1);i < length;++i) { if(i === oldLastIndex && field.arr[i].chg) --field.chgIdx; field.arr[i].chg = false; } } } } /** * Records the signal level history. */ private recordSignalLevelHistory(signalLevel: number) { /** @type {Number} */ var averageSignalLevel = 0; if(VRS.globalOptions.aircraftMaxAvgSignalLevelHistory) { if(signalLevel === null) { if(this.signalLevelHistory.length !== 0) this.signalLevelHistory = []; } else { var i; averageSignalLevel = signalLevel; var length = this.signalLevelHistory.length; if(length < VRS.globalOptions.aircraftMaxAvgSignalLevelHistory) { for(i = 0;i < length;++i) { averageSignalLevel += this.signalLevelHistory[i]; } this.signalLevelHistory.push(signalLevel); ++length; } else { var shiftLength = length - 1; for(i = 0;i < shiftLength;++i) { var useValue = this.signalLevelHistory[i + 1]; this.signalLevelHistory[i] = useValue; averageSignalLevel += useValue; } this.signalLevelHistory[shiftLength] = signalLevel; } averageSignalLevel = Math.floor(averageSignalLevel / length); } } this.setValue(this.averageSignalLevel, averageSignalLevel, true); } /** * Returns true if the aircraft has a position associated with it. */ hasPosition() : boolean { return this.positionTime.val > 0; } /** * Returns the position of the aircraft as an object or null if the aircraft has no position. */ getPosition() : ILatLng { return this.hasPosition() ? { lat: this.latitude.val, lng: this.longitude.val } : null; } /** * Returns true if the aircraft is within the bounding box described by the parameters. */ positionWithinBounds(bounds: IBounds) : boolean { var result = this.hasPosition(); if(result) result = VRS.greatCircle.isLatLngInBounds(this.latitude.val, this.longitude.val, bounds); return result; } /** * Returns true if the aircraft has a route, false if it does not. */ hasRoute() : boolean { return !this.isCharterFlight.val && !this.isPositioningFlight.val && !!this.from.val && !!this.to.val; } /** * Returns true if the SDM site allows routes for the aircraft. */ canSubmitRoute() : boolean { return !this.isCharterFlight.val && !this.isPositioningFlight.val; } /** * Returns true if the aircraft's route has changed. */ hasRouteChanged() : boolean { return this.from.chg || this.to.chg || this.via.chg; } /** * Returns a copy of the airports from the via routes array. */ getViaAirports() : string[] { var result: string[] = []; var length = this.via.arr.length; for(var i = 0;i < length;++i) { result.push(this.via.arr[i].val); } return result; } /** * Returns an array of all of the airport codes in the route. */ getAirportCodes(distinctOnly?: boolean) : string[] { distinctOnly = !!distinctOnly; var result = []; var addAirportCode = function(code) { if(code && (!distinctOnly || VRS.arrayHelper.indexOf(result, code) === -1)) { result.push(code); } }; if(this.from.val) addAirportCode(this.from.getAirportCode()); var length = this.via.arr.length; for(var i = 0;i < length;++i) { addAirportCode(this.via.arr[i].getAirportCode()); } if(this.to.val) addAirportCode(this.to.getAirportCode()); return result; } /** * Returns either the pressure or geometric altitude, depending on the "UsePressureAltitude" * switch in unit display preferences. */ getMixedAltitude(usePressureAltitude: boolean) : number { return usePressureAltitude ? this.altitude.val : this.geometricAltitude.val; } /** * Returns the value changed flag for either the pressure or geometric altitude, depending * on the "UsePressureAltitude" switch in unit display preferences. * @param usePressureAltitude */ hasMixedAltitudeChanged(usePressureAltitude: boolean) : boolean { return usePressureAltitude ? this.altitude.chg : this.geometricAltitude.chg; } /** * Returns true if the aircraft is some kind of aircraft, false if it is a ground vehicle or radio mast. */ isAircraftSpecies() : boolean { return this.species.val !== VRS.Species.GroundVehicle && this.species.val !== VRS.Species.Tower; } /** * Returns the speed converted from knots (as sent by the server) to the unit passed across. */ convertSpeed(toUnit: SpeedEnum) : number { var result = this.speed.val; if(result !== undefined && toUnit !== VRS.Speed.Knots) { result = VRS.unitConverter.convertSpeed(result, VRS.Speed.Knots, toUnit); } return result; } /** * Returns the pressure altitude converted from feet (as sent by the server) to the unit passed across. */ convertAltitude(toUnit: HeightEnum) : number { return this.convertMixedAltitude(true, toUnit); } /** * Returns the geometric altitude converted from feet to the unit passed across. */ convertGeometricAltitude(toUnit: HeightEnum) : number { return this.convertMixedAltitude(false, toUnit); } /** * Returns either the pressure or geometric altitude converted from feet to the unit passed across. */ convertMixedAltitude(usePressureAltitude: boolean, toUnit: HeightEnum) : number { var result = usePressureAltitude ? this.altitude.val : this.geometricAltitude.val; if(result !== undefined && toUnit !== VRS.Height.Feet) { result = VRS.unitConverter.convertHeight(result, VRS.Height.Feet, toUnit); } return result; } /** * Returns the air pressure converted from inches of mercury to the unit passed across. */ convertAirPressure(toUnit: PressureEnum) : number { var result = this.airPressureInHg.val; if(result !== undefined && toUnit !== VRS.Pressure.InHg) { result = VRS.unitConverter.convertPressure(result, VRS.Pressure.InHg, toUnit); } return result; } /** * Returns the distance from here converted from kilometres (as sent by the server) to the unit passed across. */ convertDistanceFromHere(toUnit: DistanceEnum) : number { var result = this.distanceFromHereKm.val; if(result !== undefined && toUnit !== VRS.Distance.Kilometre) { result = VRS.unitConverter.convertDistance(result, VRS.Distance.Kilometre, toUnit); } return result; } /** * Returns the vertical speed converted from feet per minute to the unit passed across. */ convertVerticalSpeed(toUnit: HeightEnum, perSecond: boolean) : number { return VRS.unitConverter.convertVerticalSpeed(this.verticalSpeed.val, VRS.Height.Feet, toUnit, perSecond); } /** * Fetches thumbnails for the aircraft from www.airport-data.com. Once the fetch has been satisfied the chg * value for airportDataThumbnail will be set for the next refresh of aircraft data, and then cleared on the * subsequent refresh. */ fetchAirportDataThumbnails(numThumbnails: number = 1) { if(this.icao.val) { var self = this; var fetcher = new AirportDataApi(); fetcher.getThumbnails(this.icao.val, this.registration.val, numThumbnails, function(icao, thumbnails) { if(icao === self.icao.val) self.airportDataThumbnails.setValue(thumbnails); }); } } /** * Formats the airport-data.com thumbnails as an IMG tag HTML. */ formatAirportDataThumbnails(showLinkToSite?: boolean) : string { if(showLinkToSite === undefined) showLinkToSite = true; return VRS.format.airportDataThumbnails(this.airportDataThumbnails.val, showLinkToSite); } /** * Formats the pressure altitude as a string. */ formatAltitude(heightUnit: HeightEnum, distinguishOnGround: boolean, showUnits: boolean, showType: boolean) : string { return VRS.format.altitude(this.altitude.val, VRS.AltitudeType.Barometric, this.isOnGround.val, heightUnit, distinguishOnGround, showUnits, showType); } /** * Formats the geometric altitude as a string. */ formatGeometricAltitude(heightUnit: HeightEnum, distinguishOnGround: boolean, showUnits: boolean, showType: boolean) : string { return VRS.format.altitude(this.geometricAltitude.val, VRS.AltitudeType.Geometric, this.isOnGround.val, heightUnit, distinguishOnGround, showUnits, showType); } /** * Formats either the pressure or geometric altitude as a string. */ formatMixedAltitude(usePressureAltitude: boolean, heightUnit: HeightEnum, distinguishOnGround: boolean, showUnits: boolean, showType: boolean) : string { var value = usePressureAltitude ? this.altitude.val : this.geometricAltitude.val; var valueType = usePressureAltitude ? VRS.AltitudeType.Barometric : VRS.AltitudeType.Geometric; return VRS.format.altitude(value, valueType, this.isOnGround.val, heightUnit, distinguishOnGround, showUnits, showType); } /** * Formats the altitude type as a string. */ formatAltitudeType() : string { return VRS.format.altitudeType(this.altitudeType.val); } /** * Formats the air pressure as a string. */ formatAirPressureInHg(pressureUnit: PressureEnum, showUnits: boolean) : string { return VRS.format.pressure(this.airPressureInHg.val, pressureUnit, showUnits); } /** * Formats the average signal level as a string. */ formatAverageSignalLevel() : string { return VRS.format.averageSignalLevel(this.averageSignalLevel.val); } /** * Formats the bearing from here as a string. */ formatBearingFromHere(showUnits: boolean) : string { return VRS.format.bearingFromHere(this.bearingFromHere.val, showUnits); } /** * Formats the bearing from here as an HTML IMG tag. */ formatBearingFromHereImage() : string { return VRS.format.bearingFromHereImage(this.bearingFromHere.val); } /** * Formats the callsign as a string. */ formatCallsign(showUncertainty: boolean) : string { return VRS.format.callsign(this.callsign.val, this.callsignSuspect.val, showUncertainty); } /** * Formats the count of flights as a string. */ formatCountFlights(format?: string) : string { return VRS.format.countFlights(this.countFlights.val, format); } /** * Formats the count of messages as a string. */ formatCountMessages(format?: string) : string { return VRS.format.countMessages(this.countMessages.val, format); } /** * Formats the country as a string. */ formatCountry() : string { return VRS.format.country(this.country.val); } /** * Formats the distance from here as a string. */ formatDistanceFromHere(distanceUnit: DistanceEnum, showUnits: boolean) : string { return VRS.format.distanceFromHere(this.distanceFromHereKm.val, distanceUnit, showUnits); } /** * Formats the count of engines and engine type as a string. */ formatEngines() : string { return VRS.format.engines(this.countEngines.val, this.engineType.val); } /** * Formats the flight level as a string. */ formatFlightLevel(transitionAltitude: number, transitionAltitudeUnit: HeightEnum, flightLevelAltitudeUnit: HeightEnum, altitudeUnit: HeightEnum, distinguishOnGround: boolean, showUnits: boolean, showType: boolean) : string { return VRS.format.flightLevel(this.altitude.val, this.geometricAltitude.val, this.altitudeType.val, this.isOnGround.val, transitionAltitude, transitionAltitudeUnit, flightLevelAltitudeUnit, altitudeUnit, distinguishOnGround, showUnits, showType); } /** * Formats the aircraft's heading as a string. */ formatHeading(showUnit: boolean, showType: boolean) : string { return VRS.format.heading(this.heading.val, this.headingIsTrue.val, showUnit, showType); } /** * Formats the aircraft's heading type as a string. */ formatHeadingType() : string { return VRS.format.headingType(this.headingIsTrue.val); } /** * Formats the aircraft's ICAO as a string. */ formatIcao() : string { return VRS.format.icao(this.icao.val); } /** * Returns 'IDENT' if the ident is active or an empty string if it is not. */ formatIdent() : string { return VRS.format.ident(this.identActive.val); } /** * Formats the aircraft's Ident Active value as a string. */ formatIdentActive() : string { return VRS.format.identActive(this.identActive.val); } /** * Formats the aircraft's military status as a string. */ formatIsMilitary() : string { return VRS.format.isMilitary(this.isMilitary.val); } /** * Formats the aircraft's is MLAT value as a string. */ formatIsMlat() : string { return VRS.format.isMlat(this.isMlat.val); } /** * Formats the aircraft's is TIS-B value as a string. */ formatIsTisb() : string { return VRS.format.isTisb(this.isTisb.val); } /** * Formats the aircraft's latitude as a string. */ formatLatitude(showUnit: boolean) : string { return VRS.format.latitude(this.latitude.val, showUnit); } /** * Formats the aircraft's longitude as a string. */ formatLongitude(showUnit: boolean) : string { return VRS.format.longitude(this.longitude.val, showUnit); } /** * Format's the aircraft's manufacturer as a string. */ formatManufacturer() : string { return VRS.format.manufacturer(this.manufacturer.val); } /** * Formats the aircraft's model as a string. */ formatModel() : string { return VRS.format.model(this.model.val); } /** * Formats the aircraft ICAO code for its model as a string. */ formatModelIcao() : string { return VRS.format.modelIcao(this.modelIcao.val); } /** * Formats the aircraft's ICAO code for its model as an HTML IMG tag for a silhouette image. */ formatModelIcaoImageHtml() : string { return VRS.format.modelIcaoImageHtml(this.modelIcao.val, this.icao.val, this.registration.val); } /** * Formats the aircraft's ICAO code for its model as a description of engines, wake turbulence and species. */ formatModelIcaoNameAndDetail() : string { return VRS.format.modelIcaoNameAndDetail(this.modelIcao.val, this.model.val, this.countEngines.val, this.engineType.val, this.species.val, this.wakeTurbulenceCat.val); } /** * Formats the aircraft's operator as a string. */ formatOperator() : string { return VRS.format.operator(this.operator.val); } /** * Formats the aircraft's operator's ICAO code as a string. */ formatOperatorIcao() : string { return VRS.format.operatorIcao(this.operatorIcao.val); } /** * Formats the aircraft's operator ICAO code and name as a string. */ formatOperatorIcaoAndName() : string { return VRS.format.operatorIcaoAndName(this.operator.val, this.operatorIcao.val); } /** * Formats the aircraft's operator ICAO as an HTML IMG tag to the operator flag image. */ formatOperatorIcaoImageHtml() : string { return VRS.format.operatorIcaoImageHtml(this.operator.val, this.operatorIcao.val, this.icao.val, this.registration.val); } /** * Returns an HTML IMG tag to a picture of the aircraft. */ formatPictureHtml(requestSize: ISizePartial, allowResizeUp?: boolean, linkToOriginal?: boolean, blankSize?: ISize) : string { return VRS.format.pictureHtml(this.registration.val, this.icao.val, this.pictureWidth.val, this.pictureHeight.val, requestSize, allowResizeUp, linkToOriginal, blankSize); } /** * Formats the position age in seconds as a string. */ formatPositionAgeSeconds() : string { return VRS.format.positionAgeSeconds(this.positionAgeSeconds.val); } /** * Returns the formatted name of the receiver that last picked up a message for this aircraft. */ formatReceiver() : string { return VRS.format.receiver(this.receiverId.val, this._AircraftListFetcher); } /** * Returns the registration formatted as a string. */ formatRegistration(onlyAlphaNumeric?: boolean) : string { return VRS.format.registration(this.registration.val, onlyAlphaNumeric); } /** * Returns the full route, including all stopovers and airport names, formatted as a string. */ formatRouteFull() : string { return VRS.format.routeFull(this.callsign.val, this.from.val, this.to.val, this.getViaAirports(), this.isCharterFlight.val, this.isPositioningFlight.val); } /** * Returns HTML for the full route spread over multiple lines (separated by BR tags). */ formatRouteMultiLine() : string { return VRS.format.routeMultiLine(this.callsign.val, this.from.val, this.to.val, this.getViaAirports(), this.isCharterFlight.val, this.isPositioningFlight.val); } /** * Returns HTML for the short route (where only airport codes are shown and stopovers can be reduced to an asterisk). */ formatRouteShort(abbreviateStopovers?: boolean, showRouteNotKnown?: boolean) : string { return VRS.format.routeShort(this.callsign.val, this.from.val, this.to.val, this.getViaAirports(), abbreviateStopovers, showRouteNotKnown, this.isCharterFlight.val, this.isPositioningFlight.val); } /** * Formats the seconds tracked as a string. */ formatSecondsTracked() : string { return VRS.format.secondsTracked(this.secondsTracked); } /** * Formats the serial number. */ formatSerial = function() : string { return VRS.format.serial(this.serial.val); } /** * Formats the signal level as a string. */ formatSignalLevel() : string { return VRS.format.signalLevel(this.signalLevel.val); } /** * Formats the aircraft species as a string. */ formatSpecies(ignoreNone: boolean) : string { return VRS.format.species(this.species.val, ignoreNone); } /** * Returns the speed formatted as a string. */ formatSpeed(speedUnit: SpeedEnum, showUnit: boolean, showType: boolean) { return VRS.format.speed(this.speed.val, this.speedType.val, speedUnit, showUnit, showType); } /** * Returns the speed type formatted as a string. */ formatSpeedType() : string { return VRS.format.speedType(this.speedType.val); } /** * Returns the squawk formatted as a string. */ formatSquawk() : string { return VRS.format.squawk(this.squawk.val); } /** * Returns a description of the aircraft's squawk. */ formatSquawkDescription() : string { return VRS.format.squawkDescription(this.squawk.val); } /** * Formats the target altitude as a string. */ formatTargetAltitude(heightUnit: HeightEnum, showUnits: boolean, showType: boolean) : string { return VRS.format.altitude(this.targetAltitude.val, VRS.AltitudeType.Barometric, false, heightUnit, false, showUnits, showType); } /** * Formats the target heading as a string. */ formatTargetHeading(showUnits: boolean, showType: boolean) { return VRS.format.heading(this.targetHeading.val, false, showUnits, showType); } /** * Returns the transponder type formatted as a string. */ formatTransponderType() : string { return VRS.format.transponderType(this.transponderType.val); } /** * Returns the transponder type formatted as an IMG HTML element. */ formatTransponderTypeImageHtml() : string { return VRS.format.transponderTypeImageHtml(this.transponderType.val); } /** * Returns the interested flag formatted as a string. */ formatUserInterested() : string { return VRS.format.userInterested(this.userInterested.val); } /** * Returns the user notes formatted as a string. */ formatUserNotes() : string { return VRS.format.userNotes(this.userNotes.val); } /** * Returns the user notes formatted as HTML with line breaks. */ formatUserNotesMultiline() : string { return VRS.format.userNotesMultiline(this.userNotes.val); } /** * Returns the user tag formatted as a string. */ formatUserTag() : string { return VRS.format.userTag(this.userTag.val); } /** * Returns the vertical speed formatted as a string. */ formatVerticalSpeed(heightUnit: HeightEnum, perSecond: boolean, showUnit: boolean, showType: boolean) : string { return VRS.format.verticalSpeed(this.verticalSpeed.val, this.isOnGround.val, this.verticalSpeedType.val, heightUnit, perSecond, showUnit, showType); } /** * Returns the vertical speed type formatted as a string. */ formatVerticalSpeedType() : string { return VRS.format.verticalSpeedType(this.verticalSpeedType.val); } /** * Returns the wake turbulence category formatted as a string. */ formatWakeTurbulenceCat(ignoreNone: boolean, expandedDescription: boolean) : string { return VRS.format.wakeTurbulenceCat(this.wakeTurbulenceCat.val, ignoreNone, expandedDescription); } /** * Returns the year built as a string. */ formatYearBuilt() : string { return VRS.format.yearBuilt(this.yearBuilt.val); } } }
the_stack
import ProxyOperation from "../../../../main/js/joynr/proxy/ProxyOperation"; import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos"; import * as Request from "../../../../main/js/joynr/dispatching/types/Request"; import * as OneWayRequest from "../../../../main/js/joynr/dispatching/types/OneWayRequest"; import TypeRegistrySingleton from "../../../../main/js/joynr/types/TypeRegistrySingleton"; import testDataOperation from "../../../../test/js/test/data/Operation"; import TestEnum from "../../../generated/joynr/tests/testTypes/TestEnum"; import RadioStation from "../../../generated/joynr/vehicle/radiotypes/RadioStation"; import DiscoveryEntryWithMetaInfo from "../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo"; import Version from "../../../../main/js/generated/joynr/types/Version"; import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos"; describe("libjoynr-js.joynr.proxy.ProxyOperation", () => { let addFavoriteStation: Function; let operationName: any; let proxyParticipantId: any; let providerParticipantId: any; let providerDiscoveryEntry: any; let proxy: any; let requestReplyManagerSpy: any; beforeEach(() => { requestReplyManagerSpy = { sendRequest: jest.fn(), sendOneWayRequest: jest.fn() }; requestReplyManagerSpy.sendRequest.mockImplementation((_settings: any, callbackSettings: any) => { const response = { result: "resultValue" }; return Promise.resolve({ response, settings: callbackSettings }); }); operationName = "myOperation"; proxyParticipantId = "proxyParticipantId"; providerParticipantId = "providerParticipantId"; providerDiscoveryEntry = new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 0, minorVersion: 23 }), domain: "testProviderDomain", interfaceName: "interfaceName", participantId: providerParticipantId, qos: new ProviderQos(undefined as any), lastSeenDateMs: Date.now(), expiryDateMs: Date.now() + 60000, publicKeyId: "publicKeyId", isLocal: true }); proxy = { proxyParticipantId, providerDiscoveryEntry, settings: { dependencies: { requestReplyManager: requestReplyManagerSpy } }, messagingQos: new MessagingQos() }; addFavoriteStation = new ProxyOperation(proxy, "addFavoriteStation", [ { inputParameter: [ { name: "radioStation", type: "joynr.vehicle.radiotypes.RadioStation" } ] }, { inputParameter: [ { name: "radioStation", type: "String" } ], outputParameter: [] } ]).buildFunction(); TypeRegistrySingleton.getInstance().addType(TestEnum); }); it("is of correct type", done => { expect(addFavoriteStation).toBeDefined(); expect(typeof addFavoriteStation === "function").toBeTruthy(); done(); }); it("expect correct error reporting after operation call with wrong argument", done => { addFavoriteStation({ nonexistingArgument: "value" }) .then(() => done.fail()) .catch((error: any) => { expect(error.message).toMatch("Cannot call operation with nullable value"); done(); }); }); it("expect correct error reporting after operation call with wrong type of argument", done => { addFavoriteStation({ radioStation: 1 }) .then(() => done.fail()) .catch((error: any) => { //expect(message).toContain( // "Signature does not match"); expect(error.message).toMatch("Signature does not match"); done(); }); }); it("expect no error reporting after operation call with correct string argument", async () => { await expect( addFavoriteStation({ radioStation: "correctValue" }) ).resolves.toBeUndefined(); }); async function testForCorrectReturnValues( methodName: any, outputParameter: any, replyResponse: any, expected?: any ) { const proxy = { proxyParticipantId, providerDiscoveryEntry, messagingQos: new MessagingQos(), settings: { dependencies: { requestReplyManager: requestReplyManagerSpy } } }; requestReplyManagerSpy.sendRequest.mockImplementation((_settings: any, callbackSettings: any) => { return Promise.resolve({ response: replyResponse, settings: callbackSettings }); }); const testMethod = new ProxyOperation(proxy, methodName, [ { inputParameter: [], outputParameter } ]).buildFunction(); const result = await testMethod(); expect(result).toEqual(expected); } it("expect correct joynr enum object as return value", () => { return testForCorrectReturnValues( "testMethodHavingEnumAsReturnValue", [ { name: "returnEnum", type: TestEnum.ZERO._typeName } ], ["ZERO"], { returnEnum: TestEnum.ZERO } ); }); it("expect undefined as return value for missing output parameters", () => { return testForCorrectReturnValues("testMethodHavingNoOutputParameter", [], [], undefined) .then(() => testForCorrectReturnValues("testMethodHavingNoOutputParameter", [], ["unexpected value"], undefined) ) .then(() => testForCorrectReturnValues("testMethodWithUndefinedOutputParameter", undefined, [], undefined)); }); it("expect multiple return values", done => { testForCorrectReturnValues( "testMultipleReturnValues", [ { name: "returnEnum", type: TestEnum.ZERO._typeName }, { name: "returnString", type: "String" } ], ["ZERO", "stringValue"], { returnEnum: TestEnum.ZERO, returnString: "stringValue" } ) .then(() => { done(); return null; }) .catch(() => done.fail()); }); it("expect correct joynr enum object array as return value", () => { return testForCorrectReturnValues( "testMethodHavingEnumArrayAsReturnValue", [ { name: "returnEnum", // currently, we generate the type of the array element into the signature type: `${TestEnum.ZERO._typeName}[]` } ], [["ZERO", "ONE"]], { returnEnum: [TestEnum.ZERO, TestEnum.ONE] } ); }); it("expect no error reporting after operation call with correct complex argument", async () => { const radioStation = new RadioStation({ name: "correctValue", byteBuffer: [] }); const returnValue = await addFavoriteStation({ radioStation }); expect(returnValue).toEqual(undefined); }); it("notifies", () => { return addFavoriteStation({ radioStation: "stringStation" }); }); async function testOperationOverloading(operationArguments: any, errorExpected?: boolean) { if (errorExpected) { await expect(addFavoriteStation(operationArguments)).rejects.toBeInstanceOf(Error); } else { await expect(addFavoriteStation(operationArguments)); } } it("provides overloading operations", done => { // correct version one testOperationOverloading({ radioStation: "stringStation" }) .then(() => { return testOperationOverloading({ radioStation: new RadioStation({ name: "typedStation", byteBuffer: [] }) }); // correct version two }) .then(() => { return testOperationOverloading( { wrongName: "stringStation" }, true ); // wrong argument name }) .then(() => { return testOperationOverloading({}, true); // wrong number of arguments }) .then(() => { return testOperationOverloading( { radioStation: [] }, true ); // wrong number argument type (Array instead of String|RadioStation) }) .then(() => { return testOperationOverloading( { radioStation: 1 }, true ); // wrong number argument type (Number instead of String|RadioStation) }) .then(() => { return testOperationOverloading( { radioStation: "stringStation", anotherArgument: 1 }, true ); // wrong additional argument }) .then(() => { return testOperationOverloading( { radioStation: new RadioStation({ name: "stringStation", byteBuffer: [] }), anotherArgument: 2 }, true ); // wrong additional arguments }) .then(() => { return testOperationOverloading( { radioStation: null }, true ); // nullable argument }) .then(() => { return testOperationOverloading( { radioStation: undefined }, true ); // nullable argument }) .then(() => { return testOperationOverloading(undefined, true); // nullable settings object }) .then(() => { return testOperationOverloading(null, true); // nullable settings object }) .then(() => { done(); return null; }) .catch(() => done.fail()); }); it("does not throw when giving wrong or nullable operation arguments", done => { const spy = { onFulfilled: jest.fn(), onRejected: jest.fn() }; expect(() => { addFavoriteStation({ radioStation: "myRadioStation" }) .then(spy.onFulfilled) .catch(spy.onRejected); }).not.toThrow(); expect(() => { addFavoriteStation({ radioStation: undefined }) .then(spy.onFulfilled) .catch(spy.onRejected); }).not.toThrow(); expect(() => { addFavoriteStation({}) .then(spy.onFulfilled) .catch(spy.onRejected); }).not.toThrow(); expect(() => { addFavoriteStation(undefined) .then(spy.onFulfilled) .catch(spy.onRejected); }).not.toThrow(); expect(() => { addFavoriteStation(null) .then(spy.onFulfilled) .catch(spy.onRejected); }).not.toThrow(); done(); }); function checkRequestReplyManagerCall(testData: any) { // construct new ProxyOperation const myOperation = new ProxyOperation(proxy, operationName, [testData.signature]).buildFunction(); requestReplyManagerSpy.sendRequest.mockImplementation((_settings: any, callbackSettings: any) => { return Promise.resolve({ response: testData.returnParams, settings: callbackSettings }); }); requestReplyManagerSpy.sendRequest.mockClear(); // do operation call myOperation(testData.namedArguments) .then(() => { // check if requestReplyManager has been called correctly expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalled(); const requestReplyId = requestReplyManagerSpy.sendRequest.calls.argsFor(0)[0].request.requestReplyId; expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalledWith( { toDiscoveryEntry: providerDiscoveryEntry, from: proxyParticipantId, messagingQos: new MessagingQos(), request: Request.create({ methodName: operationName, paramDatatypes: testData.paramDatatypes, params: testData.params, requestReplyId }) }, expect.any(Object) ); }) .catch(() => { expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalled(); }); } function checkRequestReplyManagerFireAndForgetCall(testData: any) { const myOperation = new ProxyOperation(proxy, operationName, [testData.signature]).buildFunction(); requestReplyManagerSpy.sendOneWayRequest.mockReturnValue(Promise.resolve()); requestReplyManagerSpy.sendOneWayRequest.mockClear(); // do operation call myOperation(testData.namedArguments) .then(() => { // check if requestReplyManager has been called correctly expect(requestReplyManagerSpy.sendOneWayRequest).toHaveBeenCalled(); expect(requestReplyManagerSpy.sendOneWayRequest).toHaveBeenCalledWith({ toDiscoveryEntry: providerDiscoveryEntry, from: proxyParticipantId, messagingQos: new MessagingQos(), request: OneWayRequest.create({ methodName: operationName, paramDatatypes: testData.paramDatatypes, params: testData.params }) }); }) .catch(() => { expect(requestReplyManagerSpy.sendRequest).toHaveBeenCalled(); }); } it("calls RequestReplyManager with correct request", async () => { if (testDataOperation[0].signature.fireAndForget) { await checkRequestReplyManagerFireAndForgetCall(testDataOperation[0]); } else { await checkRequestReplyManagerCall(testDataOperation[0]); } for (let i = 1; i < testDataOperation.length; ++i) { const testOp = testDataOperation[i]; if (testOp.signature.fireAndForget) { await checkRequestReplyManagerFireAndForgetCall(testOp); } else { await checkRequestReplyManagerCall(testOp); } } return; }); });
the_stack
import { Update, ClientState, ClientResponse, UpdateHandler, ResponseHandler, Event, } from './types' import { getWalletOp, getChannelOps } from './helpers' import { URL } from 'url' require('isomorphic-fetch') const StrKey = require('stellar-base').StrKey export { ClientState, UpdateHandler, ResponseHandler, Update } export const initialClientState: ClientState = { addressesForChannelAccount: {}, addressesForCounterpartyAccount: {}, updateNumberForSequenceNumber: {}, from: 0, } export interface InitConfigParams { HorizonURL: string Password: string Username: string } interface EditParams { HorizonURL?: string OldPassword?: string Password?: string } export interface ClientResponse { body: any ok: boolean status?: number error?: Error } /** * The Starlight API Client object is the root object for all API interactions. * To interact with Starlight, a Client object must always be instantiated * first. * @class */ export class Client { public updateHandler?: UpdateHandler public responseHandler?: ResponseHandler private cookie: string /** * @typedef Status * @type {object} * @property {boolean} IsConfigured * @property {boolean} IsLoggedIn */ /** * @typedef ClientResponse * @template T * @type {object} * @property {string} body - The body of the response. * @property {boolean} ok - Whether the request was successful. * @property {number | undefined} status - Status code from the HTTP response (if any). * @property {error | undefined} error - a JavaScript error, if there was an error making the request. */ /** * Create a Client. * @param {string} baseURL - The URL of the Starlight agent. * @param {object} clientState - The client state. */ constructor( public baseURL?: string, public clientState: ClientState = initialClientState ) {} /** * Resets the client's state to an initial state. */ public async clearState() { this.clientState = initialClientState } /** * Restore the client's state from a snapshot. * @param {object} clientState - The client state. */ public async setState(clientState: ClientState) { this.clientState = clientState } /** * Configure the instance with a username, password, and horizon URL. * * @async * @param {object} params - The configuration parameters. * @param {string} params.HorizonURL - The Horizon URL (by default, https://horizon-testnet.stellar.org). * @param {string} params.Username - This will be the first part of your Stellar address (as in "alice*stellar.org"). * @param {string} params.Password - This will also be used to encrypt the instance's private key in storage. * * @returns {Promise<ClientResponse<Status>>} */ public async configInit(params: InitConfigParams) { return this.request('/api/config-init', params) } /** * Edit the instance's configuration. * @param {object} params - The configuration parameters. * @param {string} [params.HorizonURL] - A new Horizon URL. * @param {string} [params.Password] - A new password. * @param {string} [params.OldPassword] - The old password, which must be provided if a new password is provided. * * @returns {Promise<ClientResponse<string>>} */ public async configEdit(params: EditParams) { return this.request('/api/config-edit', params) } /** * Attempt to open a channel with a specific counterparty. * @param {string} counterpartyAddress - The Stellar address of your counterparty (e.g., "alice*stellar.org"). * @param {number} initialDeposit - The amount (in stroops) you will initially deposit into the channel. * * @returns {Promise<ClientResponse<string>>} */ public async createChannel( counterpartyAddress: string, initialDeposit: number ) { return this.request('/api/do-create-channel', { GuestAddr: counterpartyAddress, HostAmount: initialDeposit, }) } /** * Cooperatively close a channel. * @param {string} channelID - The channel ID. * * @returns {Promise<ClientResponse<string>>} */ public async close(channelID: string) { return this.request('/api/do-command', { ChannelID: channelID, Command: { Name: 'CloseChannel', }, }) } /** * Cancel a proposed channel that your counterparty has not yet accepted. * @param {string} channelID - The channel ID. * * @returns {Promise<ClientResponse<string>>} */ public async cancel(channelID: string) { return this.request('/api/do-command', { ChannelID: channelID, Command: { Name: 'CleanUp', }, }) } /** * Attempt to force close a channel. * @param {string} channelID - The channel ID. * * @returns {Promise<ClientResponse<string>>} */ public async forceClose(channelID: string) { return this.request('/api/do-command', { ChannelID: channelID, Command: { Name: 'ForceClose', }, }) } /** * Make a payment over a channel. * @param {string} channelID - The channel ID. * @param {number} amount - The amount (in stroops) to be paid. * * @returns {Promise<ClientResponse<string>>} */ public async channelPay(channelID: string, amount: number) { return this.request('/api/do-command', { ChannelID: channelID, Command: { Name: 'ChannelPay', Amount: amount, }, }) } /** * Make a payment on the public network. * @param {string} channelID - The channel ID. * @param {number} amount - The amount (in stroops) to be paid. * * @returns {Promise<ClientResponse<string>>} */ public async walletPay(recipient: string, amount: number) { return this.request('/api/do-wallet-pay', { Dest: recipient, Amount: amount, }) } /** * Add more money to a channel you created. * @param {string} channelID - The channel ID. * @param {number} amount - The amount (in stroops) to be deposited. * @returns {Promise<ClientResponse<string>>} */ public async deposit(channelID: string, amount: number) { return this.request('/api/do-command', { ChannelID: channelID, Command: { Name: 'TopUp', Amount: amount, }, }) } /** * Authenticate with a Starlight instance. * This also decrypts the instance's private key, * allowing it to sign transactions and accept channels. * @param {string} username * @param {number} password * * @returns {Promise<ClientResponse<string>>} */ public async login(username: string, password: string) { return this.request('/api/login', { username, password, }) } /** * Log out of a Starlight instance. * @param {string} username * @param {number} password * * @returns {Promise<ClientResponse<string>>} */ public async logout() { return this.request('/api/logout') } /** * Find the account ID (e.g., "G...") corresponding to a Stellar address (e.g., "alice*stellar.org"). * @param {string} address * * @returns {Promise<ClientResponse<Status>>} accountID */ public async findAccount(address: string): Promise<ClientResponse> { return this.request('/api/find-account', { stellar_addr: address, }) } /** * Get the current status of the instance (whether the instance is configured, and if so, whether the user is logged in). * * @returns {Promise<Status | undefined>} */ public async getStatus() { return this.request('/api/status') } /** * Subscribe to updates from the Starlight instance. * The first time this is called, the handler will be called with all updates in the instance's history. * * @param {function} updateHandler - A handler function that updates will be passed to. */ public subscribe(updateHandler: UpdateHandler) { this.updateHandler = updateHandler this.loop() } /** * Stop subscribing to updates from the Starlight instance. */ public unsubscribe() { this.updateHandler = undefined } /** * This method is only public so it can be used in tests. * @ignore */ public handleFetchResponse(rawResponse: ClientResponse) { const handler = this.updateHandler const response = this.responseHandler ? this.responseHandler(rawResponse) : rawResponse if (handler && response.ok && response.body.length >= 1) { response.body.forEach((event: Event) => { if (event.Type === 'channel') { const channel = event.Channel const CounterpartyAccount = channel.Role === 'Host' ? channel.GuestAcct : channel.HostAcct this.clientState = { ...this.clientState, addressesForCounterpartyAccount: { ...this.clientState.addressesForCounterpartyAccount, [CounterpartyAccount]: channel.CounterpartyAddress, }, addressesForChannelAccount: { ...this.clientState.addressesForChannelAccount, [channel.EscrowAcct]: channel.CounterpartyAddress, }, } } this.clientState = { ...this.clientState, from: event.UpdateNum + 1, } const update = this.eventToUpdate(event) if (update) { handler(update) } }) } return response.ok } private async fetch() { const From = this.clientState.from const response = await this.request('/api/updates', { From }) return this.handleFetchResponse(response) } private async loop() { if (!this.updateHandler) { return } const ok = await this.fetch() if (!ok) { await this.backoff(10000) } this.loop() } private async backoff(ms: number) { await new Promise(resolve => setTimeout(resolve, ms)) } private eventToUpdate(event: Event): Update | undefined { const clientState = this.clientState switch (event.Type) { case 'account': { const op = getWalletOp( event, this.clientState.addressesForCounterpartyAccount ) if (event.InputTx) { // check if this is from a channel account const counterpartyAddress = this.clientState .addressesForChannelAccount[ StrKey.encodeEd25519PublicKey( event.InputTx.Env.Tx.SourceAccount.Ed25519 ) ] if (counterpartyAddress !== undefined) { // it's from a channel // activity is handled elsewhere return { Type: 'accountUpdate', Account: event.Account, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, ClientState: clientState, } } } return { Type: 'walletActivityUpdate', Account: event.Account, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, WalletOp: op, ClientState: clientState, } } case 'channel': // TODO: remove channel account from this mapping when channel is closed const ops = getChannelOps(event) if (ops.length === 0) { return { Type: 'channelUpdate', Account: event.Account, Channel: event.Channel, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, ClientState: clientState, } } else { return { Type: 'channelActivityUpdate', Account: event.Account, Channel: event.Channel, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, ChannelOp: ops[0], ClientState: clientState, } } case 'config': return { Type: 'configUpdate', Config: event.Config, Account: event.Account, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, ClientState: clientState, } case 'init': return { Type: 'initUpdate', Config: event.Config, Account: event.Account, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, ClientState: clientState, } case 'tx_failed': case 'tx_success': return { Type: event.Type === 'tx_failed' ? 'txFailureUpdate' : 'txSuccessUpdate', Tx: event.InputTx, Account: event.Account, UpdateLedgerTime: event.UpdateLedgerTime, UpdateNum: event.UpdateNum, ClientState: clientState, } } } private async request(path: string = '', data = {}) { let urlString: string if (this.baseURL) { const url = new URL(path, this.baseURL) urlString = url.href } else { urlString = path } const rawResponse = await this.post(urlString, data) const response = this.responseHandler ? this.responseHandler(rawResponse) : rawResponse return response } private async post(url = ``, data = {}): Promise<ClientResponse> { let response: Response try { // Default options marked with * response = await fetch(url, { method: 'POST', cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, same-origin, *omit headers: { 'Content-Type': 'application/json; charset=utf-8', Cookie: this.cookie, }, body: JSON.stringify(data), // body data type must match "Content-Type" }) const cookie = response.headers.get('set-cookie') if (cookie) { this.cookie = cookie } if ((response.headers.get('content-type') || '').includes('json')) { return { body: await response.json(), ok: response.ok, status: response.status, } } else { return { body: '', ok: response.ok, status: response.status } } } catch (error) { return { body: '', ok: false, error } } } }
the_stack
// Tipos que operan principalmente sobre interfaces y permiten realizar // cómodamente transformaciones de los mismos. // Esquema copy/paste para presentar: // *** X *************** // -- Caso Base -- // -- Caso Práctico -- // -- Definición -- // *** READONLY *************** // Convierte todas las propiedades de un interfaz en solo lectura: // -- Caso Base -- interface State { username: string; password: string; } type ROState = Readonly<State>; // También aplicable a arrays: type ROArray<T> = Readonly<Array<T>>; // De hecho existe el tipo ReadonlyArray // -- Caso Práctico -- // Un caso muy útil de Readonly se aplica para garantizar que una // implementación no va a mutar un objeto determinado. Así, el consumidor // de dicha implementación (una función por ejemplo) tiene garantías // de que los parámetros de entrada no serán mutados. Pongamos un // ejemplo con arrays, donde se ve más claro, aunque lo mismo serviría // para objetos: const sampleArray = [1, 2, 3]; const tailMutable = <T>(array: T[]): T[] => (array.shift(), array); const tailImmutable = <T>(array: Readonly<T[]>): T[] => { const [, ...tail] = array || []; return tail; }; console.log(sampleArray, tailMutable(sampleArray)); console.log(sampleArray, tailImmutable(sampleArray)); // -- Definición -- type MyReadonly<T> = { readonly [P in keyof T]: T[P]; }; // *** PARTIAL *************** // Convierte en opcionales las propiedades de una interfaz, en la práctica // esto permite usar implementaciones parciales de un tipo o interfaz: // -- Caso Base -- interface Person { name: string; age: number; } type PartialPerson = Partial<Person>; // -- Caso Práctico -- const createState = <T extends object>(initialState: T) => { let state: T = initialState; return { setState: (partialState: Partial<T>): T => (state = { ...state, ...partialState }) }; }; const { setState } = createState({ username: "b4dc4t", avatar: "cat.png", posts: 18, premium: false }); console.log(setState({ posts: 19, premium: true })); // -- Definición -- type MyPartial<T> = { [P in keyof T]?: T[P]; }; // *** REQUIRED *************** // La contraparte de Partial, convierte en requeridas las propiedades // de una interfaz: // -- Caso Base -- interface Coord { x: number; y: number; z?: number; } type Coord3D = Required<Coord>; // -- Caso Práctico 1 -- const c3d: Coord3D = { // TS: Property 'z' is missing x: 3, y: 0 // z: 5, }; // -- Caso Práctico 2 -- class Point3D { private coord: Required<Coord>; constructor(coord: Coord) { this.coord = { ...coord, z: coord.z || 0 }; } getZ() { return this.coord.z; } } const p3d = new Point3D({ x: 1, y: 1 }); console.log(p3d.getZ()); // -- Definición -- type MyRequired<T> = { [P in keyof T]-?: T[P]; }; // *** EXCLUDE & EXTRACT *************** // Utilidades para excluir/extraer elementos comunes en dos uniones. // EXCLUDE: excluye de la primera unión los tipos que tiene en común con la // segunda. Por tanto calcula la diferencia matemática. // EXTRACT: extrae de la primera unión los tipos que tiene en común con la // segunda. Por tanto calcula la intersección matemática. // -- Caso Base -- type WeekDay = "lun" | "mar" | "mie" | "jue" | "vie" | "sab" | "dom"; type WorkDay = Exclude<WeekDay, "sab" | "dom">; type Weekend = Extract<WeekDay, "sab" | "dom" | "x">; // -- Caso Práctico -- // Podriamos definir: type Diff<A extends object = {}, B extends object = {}> = { [P in Exclude<keyof A, keyof B>]: A[P]; }; type Common<A extends object = {}, B extends object = {}> = { [P in Extract<keyof A, keyof B>]: A[P] | B[P]; }; // Y ponerlo a prueba con: interface UserDetails { name: string; id: string; age: number; phone: number; married: boolean; } interface UserID { name: string; id: number; } type UserDiff = Diff<UserDetails, UserID>; // Check intellisense! type UserCommon = Common<UserDetails, UserID>; // Check intellisense! // Ejemplo de implementación en JS: // Implementación más compatible const calculateCommon = <A extends object, B extends object>(a: A, b: B) : Common<A, B> => { const result = { ...a }; for (const key in a) { if (a.hasOwnProperty(key) && !b.hasOwnProperty(key)) delete result[key]; } return result; }; // Implementación más elegante // const calculateCommon2 = <A extends object, B extends object>(a: A, b: B) // : Common<A, B> => // Object.fromEntries( // Object.entries(a).filter(([prop]) => b.hasOwnProperty(prop)) // ) as Common<A, B>; const userId: UserID = { name: "Javier", id: 324374 }; const userDetails: UserDetails = { name: "Javier", id: "324374", age: 36, phone: 900900900, married: true }; const userCommon = calculateCommon(userId, userDetails); console.log(userCommon); // userCommon. // Check intellisense! // -- Definición -- type MyExclude<T, U> = T extends U ? never : T; type MyExtract<T, U> = T extends U ? T : never; // -- Propuesta -- // ¿Podríais hacer un DiffSymetrical? Es decir, que tome las propiedades de A // que no tiene B pero también las propiedades de B que no tiene A. // type DiffSym<A extends object = {}, B extends object = {}> = { // [P in Exclude<keyof A, keyof B> | Exclude<keyof B, keyof A>]: P extends keyof A ? A[P] // : P extends keyof B ? B[P] : never; // }; // *** PICK & OMIT *************** // PICK nos permite generar un sub-interfaz, a partir de un interfaz ya // existente, escogiendo las propiedades que queremos del original y // tipándolas de igual forma. En definitiva, extrae un subconjunto de // propiedades (y sus tipos) de una interfaz para generar otra distinta. // OMIT es el opuesto de PICK, nos permite generar un interfaz a partir de // otro pero en este caso eliminando las propiedades que no deseamos. Es // decir, genera una nueva interfaz excluyendo propiedades de la original. // -- Caso Base -- interface EmployeeSummary { name: string; id: string; age: number; phone: number; married?: boolean; // Now we can safely use optionals. } type EmployeeID = Pick<EmployeeSummary, "id" | "name">; // Check intellisense! type EmployeeDetails = Omit<EmployeeSummary, keyof EmployeeID>; // Check intellisense! // También podríamos haber redefinido los Diff y Common anteriores como: type Diff2<A, B> = Omit<A, Extract<keyof A, keyof B>>; type Common2<A, B> = Pick<A, Extract<keyof A, keyof B>>; type EmployeeCredentials = Common2<EmployeeSummary, EmployeeID>; type EmployeeInfo = Diff2<EmployeeSummary, EmployeeID>; // -- Caso Práctico -- // Versión más espartana. const omit = <T extends object, K extends keyof T>( o: T, ...keys: K[] ): Omit<T, K> => { const result = { ...o }; keys.forEach(key => delete result[key]); return result; }; // Versión más funcional. const omit2 = <T extends object, K extends keyof T>( o: T, ...keys: K[] ): Omit<T, K> => Object.fromEntries( Object.entries(o).filter(([key]) => !keys.includes(key as K)) ) as Omit<T, K>; const sampleObj = { a: "A", b: "B", c: "C" }; const onlyC = omit(sampleObj, "a", "b"); console.log(onlyC); // onlyC. // Check intellisense! // -- Definición -- type MyPick<T, K extends keyof T> = { [P in K]: T[P]; }; type MyOmit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>; // *** RECORD *************** // Es un tipo bastante útil para armar objetos desde cero a partir de un // conjunto de claves definidas a las que asignamos un tipado concreto. // -- Caso Base -- type Sizes = "small" | "medium" | "large"; type EurSizes = Record<Sizes, string>; type UkSizes = Record<Sizes, number>; const eurSizes: EurSizes = { small: "s", medium: "m", large: "l" }; const ukSizes: UkSizes = { small: 8, medium: 10, large: 12 }; // -- Caso Práctico -- // Ejemplo más elaborado donde vamos a usar Record para transformar // una misma interfaz de distintas formas. interface Inventoriable { id: number; name: string; } type InventoryByName<T extends Inventoriable> = Record<T["name"], Omit<T, "name">>; type InventoryById<T extends Inventoriable> = Record<T["id"], Omit<T, "id">>; const pivotInventory = <T extends Inventoriable>( list: InventoryByName<T> ): InventoryById<T> => { return Object.entries<Omit<Inventoriable, "name">>(list) .reduce((result, [name, product]) => { result[product.id] = { name, ...omit(product, "id") }; return result; }, {} as InventoryById<T>); }; interface Product extends Inventoriable { stock?: boolean; } const productsByName = { arroz: { id: 7, stock: false }, papas: { id: 6, stock: true }, jamon: { id: 3, stock: true } }; const productsById = pivotInventory<Product>(productsByName); console.log(productsById); // productsById[7]. //Check intellisense! // -- Definición -- type MyRecord<K extends keyof any, T> = { [P in K]: T; }; // *** NON NULLABLE *************** // NonNullable genera un tipo nuevo a partir de otro, previniendo // que su valor pueda ser null o undefined. // -- Caso Base -- type Choice = "left" | "right" | "center" | undefined | null; type ValidChoice = NonNullable<Choice>; // -- Caso Práctico -- // Tiene sentido en un entorno estricto (strictNullChecks) de lo contrario // el compilador siempre permitirá valores a null/undefined para cualquier // tipo. // Un 'draft' puede ser usado tanto en un formulario de edición como en uno de inserción interface BookingDraft { id: number | null; // 'number' para edición, 'null' para inserción price: number; room: 'standard' | 'superior'; prepaid: boolean; } // Declaramos un helper que nos permita seleccionar qué propiedades no pueden ser 'null' type NonNullableKeys<O, K extends keyof O> = { [P in keyof O]: P extends K ? NonNullable<O[P]> : O[P]; } // Definimos la interfaz que la API REST nos devuelve. Este sí debe tener obligatoriamente 'id' no nulo type Booking = NonNullableKeys<BookingDraft, 'id'>; // Ejemplo de API, const bookings: Booking[] = [ { id: 31, prepaid: false, price: 80, room: 'standard' }, { id: 16, prepaid: true, price: 115, room: 'standard' }, { id: 25, prepaid: true, price: 250, room: 'superior' } ]; const bookingAPI = { async getBooking(id: number): Promise<Booking | null> { return bookings.find(b => b.id === id) || null; } } // Ejemplo intellisense const foo: Booking = { id: null, // Error: Type 'null' is not assignable to type 'number' prepaid: false, price: 31, room: 'superior' } // -- Definición -- type MyNonNullable<T> = T extends null | undefined ? never : T; // *** FUNCTION HELPERS *************** // RETURN TYPE: Permite inferir el tipo de dato que devuelve una función. // PARAMETERS: Permite inferir el tipado de los argumentos de entrada de // una función en formato tupla. // -- Caso Base -- const addTimestamp = (user: UserID, useLocale: boolean = false) => ({ ...user, timestamp: useLocale ? Date().toLocaleString() : Date.now() }); type UserWithTimestamp = ReturnType<typeof addTimestamp>; // Check intellisense! type Params = Parameters<typeof addTimestamp>; // Check intellisense! // -- Caso Práctico -- type GenericFunction = (...args: any[]) => any; const delay = <F extends GenericFunction>(f: F, t: number) => ( ...args: Parameters<F> ): Promise<ReturnType<F>> => { return new Promise(resolve => { setTimeout(() => resolve(f(...args)), t); }); }; const shout = (text: string) => `${text.toUpperCase()}!!!`; console.log(shout("pim pam")); const delayedShout = delay(shout, 1000); // Check intellisense over delayedShout delayedShout("toma lacasitos").then(message => console.log(message));
the_stack
* @packageDocumentation * @module DID */ import type { Option, u32, U128, GenericAccountId } from '@polkadot/types' import type { IIdentity, SubmittableExtrinsic, IDidKeyDetails, IDidServiceEndpoint, KeystoreSigningOptions, IDidDetails, } from '@kiltprotocol/types' import { KeyRelationship } from '@kiltprotocol/types' import { BlockchainApiConnection } from '@kiltprotocol/chain-helpers' import { Crypto } from '@kiltprotocol/utils' import type { Extrinsic, Hash } from '@polkadot/types/interfaces' import type { Codec } from '@polkadot/types/types' import { BN, hexToString } from '@polkadot/util' import type { AuthenticationTxCreationInput, IDidCreationOptions, IDidChainRecordJSON, DidPublicKeyDetails, INewPublicKey, IDidChainRecordCodec, IServiceEndpointChainRecordCodec, } from './types' import { encodeDidAuthorizedCallOperation, encodeDidCreationOperation, getKiltDidFromIdentifier, formatPublicKey, encodeServiceEndpoint, parseDidUrl, assembleDidFragment, } from './Did.utils' // ### RAW QUERYING (lowest layer) // Query a full DID given the identifier (a KILT address for v1). // Interacts with the Did storage map. export async function queryDidEncoded( didIdentifier: IIdentity['address'] ): Promise<Option<IDidChainRecordCodec>> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.query.did.did<Option<IDidChainRecordCodec>>(didIdentifier) } // Query ALL deleted DIDs, which can be very time consuming if the number of deleted DIDs gets large. export async function queryDeletedDidsEncoded(): Promise<GenericAccountId[]> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() // Query all the storage keys, and then only take the relevant property, i.e., the encoded DID identifier. return api.query.did.didBlacklist .keys<GenericAccountId[]>() .then((entries) => entries.map(({ args: [encodedDidIdentifier] }) => encodedDidIdentifier) ) } // Returns the raw representation of the storage entry for the given DID identifier. async function queryDidDeletionStatusEncoded( didIdentifier: IIdentity['address'] ): Promise<Uint8Array> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() const encodedStorageKey = await api.query.did.didBlacklist.key(didIdentifier) return ( api.rpc.state .queryStorageAt<Codec[]>([encodedStorageKey]) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .then((encodedValue) => encodedValue.pop()!.toU8a()) ) } // Query a DID service given the DID identifier and the service ID. // Interacts with the ServiceEndpoints storage double map. export async function queryServiceEncoded( didIdentifier: IIdentity['address'], serviceId: IDidServiceEndpoint['id'] ): Promise<Option<IServiceEndpointChainRecordCodec>> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.query.did.serviceEndpoints< Option<IServiceEndpointChainRecordCodec> >(didIdentifier, serviceId) } // Query all services for a DID given the DID identifier. // Interacts with the ServiceEndpoints storage double map. export async function queryAllServicesEncoded( didIdentifier: IIdentity['address'] ): Promise<IServiceEndpointChainRecordCodec[]> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() const encodedEndpoints = await api.query.did.serviceEndpoints.entries< Option<IServiceEndpointChainRecordCodec> >(didIdentifier) return encodedEndpoints.map(([, encodedValue]) => encodedValue.unwrap()) } // Query the # of services stored under a DID without fetching all the services. // Interacts with the DidEndpointsCount storage map. export async function queryEndpointsCountsEncoded( didIdentifier: IIdentity['address'] ): Promise<u32> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.query.did.didEndpointsCount<u32>(didIdentifier) } async function queryDepositAmountEncoded(): Promise<U128> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.consts.did.deposit as U128 } // ### DECODED QUERYING (builds on top of raw querying) // This should not be part of this layer, as it has knowledge of DID URI. // This level should only be concerned with IDs. // Building DID URIs from IDs should be a concern of a higher level, so // we might want to refactor this in the future when time pressure is off. function assembleKeyId(keyId: Codec, did: IDidDetails['did']): string { return `${did}#${keyId.toHex()}` } function decodeDidPublicKeyDetails( did: IDidDetails['did'], keyId: Hash, keyDetails: DidPublicKeyDetails ): IDidKeyDetails { const key = keyDetails.key.value return { id: assembleKeyId(keyId, did), type: key.type.toLowerCase(), controller: did, publicKeyHex: key.value.toHex(), includedAt: keyDetails.blockNumber.toNumber(), } } // Same reasoning as `assembleKeyId`. function decodeDidChainRecord( didDetail: IDidChainRecordCodec, did: IDidDetails['did'] ): IDidChainRecordJSON { const publicKeys: IDidKeyDetails[] = Array.from( didDetail.publicKeys.entries() ).map(([keyId, keyDetails]) => { return decodeDidPublicKeyDetails(did, keyId, keyDetails) }) const authenticationKeyId = assembleKeyId(didDetail.authenticationKey, did) const keyAgreementKeyIds = Array.from( didDetail.keyAgreementKeys.values() ).map((id) => assembleKeyId(id, did)) const didRecord: IDidChainRecordJSON = { did, publicKeys, authenticationKey: authenticationKeyId, keyAgreementKeys: keyAgreementKeyIds, lastTxCounter: didDetail.lastTxCounter, } if (didDetail.delegationKey.isSome) { didRecord.capabilityDelegationKey = assembleKeyId( didDetail.delegationKey.unwrap(), did ) } if (didDetail.attestationKey.isSome) { didRecord.assertionMethodKey = assembleKeyId( didDetail.attestationKey.unwrap(), did ) } return didRecord } // Same reasoning as `assembleKeyId`. function decodeServiceChainRecord( serviceDetails: IServiceEndpointChainRecordCodec, did: IDidDetails['did'] ): IDidServiceEndpoint { const decodedId = hexToString(serviceDetails.id.toString()) return { id: assembleDidFragment(did, decodedId), types: serviceDetails.serviceTypes.map((type) => hexToString(type.toString()) ), urls: serviceDetails.urls.map((url) => hexToString(url.toString())), } } export async function queryById( didIdentifier: IIdentity['address'] ): Promise<IDidChainRecordJSON | null> { const result = await queryDidEncoded(didIdentifier) if (result.isNone) { return null } return decodeDidChainRecord( result.unwrap(), getKiltDidFromIdentifier(didIdentifier, 'full') ) } // Query full DID details given the DID URI. export async function queryDidDetails( didUri: IDidDetails['did'] ): Promise<IDidChainRecordJSON | null> { const { identifier, fragment } = parseDidUrl(didUri) if (fragment) { throw new Error(`The provided URI ${didUri} must not contain any fragment.`) } return queryById(identifier) } // Query a given key given the DID identifier and the key ID. export async function queryDidKey( keyUri: IDidKeyDetails['id'] ): Promise<IDidKeyDetails | null> { const { identifier, fragment } = parseDidUrl(keyUri) if (!fragment) { throw new Error( `The provided URI ${keyUri} does not contain a valid fragment for key ID.` ) } const didDetails = await queryById(identifier) if (!didDetails) { return null } return didDetails.publicKeys.find((key) => key.id === keyUri) || null } export async function queryServiceEndpoints( didUri: IDidDetails['did'] ): Promise<IDidServiceEndpoint[]> { const { identifier, fragment } = parseDidUrl(didUri) if (fragment) { throw new Error(`The provided URI ${didUri} must not contain any fragment.`) } const encoded = await queryAllServicesEncoded(identifier) return encoded.map((e) => decodeServiceChainRecord(e, didUri)) } export async function queryServiceEndpoint( serviceUri: IDidServiceEndpoint['id'] ): Promise<IDidServiceEndpoint | null> { const { identifier, fragment } = parseDidUrl(serviceUri) if (!fragment) { throw new Error( `The provided URI ${serviceUri} does not contain a valid fragment for service ID.` ) } const serviceEncoded = await queryServiceEncoded(identifier, fragment) if (serviceEncoded.isNone) return null const didUri = getKiltDidFromIdentifier(identifier, 'full') return decodeServiceChainRecord(serviceEncoded.unwrap(), didUri) } export async function queryEndpointsCounts( didUri: IDidDetails['did'] ): Promise<number> { const { identifier, fragment } = parseDidUrl(didUri) if (fragment) { throw new Error(`The provided URI ${didUri} must not contain any fragment.`) } const blockchain = await BlockchainApiConnection.getConnectionOrConnect() const count = await blockchain.api.query.did.didEndpointsCount<u32>( identifier ) return count.toNumber() } export async function queryLastTxCounter( didUri: IDidDetails['did'] ): Promise<BN> { const { identifier, fragment } = parseDidUrl(didUri) if (fragment) { throw new Error(`The provided URI ${didUri} must not contain any fragment.`) } const encoded = await queryDidEncoded(identifier) return encoded.isSome ? encoded.unwrap().lastTxCounter.toBn() : new BN(0) } export async function queryDepositAmount(): Promise<BN> { const encodedDeposit = await queryDepositAmountEncoded() return encodedDeposit.toBn() } export async function queryDeletedDids(): Promise<Array<IDidDetails['did']>> { const encodedIdentifiers = await queryDeletedDidsEncoded() return encodedIdentifiers.map((id) => getKiltDidFromIdentifier(id.toHuman(), 'full') ) } export async function queryDidDeletionStatus( didUri: IDidDetails['did'] ): Promise<boolean> { const { identifier } = parseDidUrl(didUri) const encodedDeletionStorageEntry = await queryDidDeletionStatusEncoded( identifier ) // The result is a 1-byte array where the only element is 1 if the DID has been deleted, and 0 otherwise. return encodedDeletionStorageEntry[0] === 1 } // ### EXTRINSICS export async function generateCreateTx({ signer, signingPublicKey, alg, didIdentifier, submitter, keys = {}, endpoints = [], }: IDidCreationOptions & KeystoreSigningOptions): Promise<SubmittableExtrinsic> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() const encoded = encodeDidCreationOperation(api.registry, { didIdentifier, submitter, keys, endpoints, }) const signature = await signer.sign({ data: encoded.toU8a(), meta: {}, publicKey: Crypto.coToUInt8(signingPublicKey), alg, }) return api.tx.did.create(encoded, { [signature.alg]: signature.data, }) } export async function getSetKeyExtrinsic( keyRelationship: KeyRelationship, key: INewPublicKey ): Promise<Extrinsic> { const keyAsEnum = formatPublicKey(key) const { api } = await BlockchainApiConnection.getConnectionOrConnect() switch (keyRelationship) { case KeyRelationship.authentication: return api.tx.did.setAuthenticationKey(keyAsEnum) case KeyRelationship.capabilityDelegation: return api.tx.did.setDelegationKey(keyAsEnum) case KeyRelationship.assertionMethod: return api.tx.did.setAttestationKey(keyAsEnum) default: throw new Error( `setting a key is only allowed for the following key types: ${[ KeyRelationship.authentication, KeyRelationship.capabilityDelegation, KeyRelationship.assertionMethod, ]}` ) } } export async function getRemoveKeyExtrinsic( keyRelationship: KeyRelationship, keyId?: string ): Promise<Extrinsic> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() switch (keyRelationship) { case KeyRelationship.capabilityDelegation: return api.tx.did.removeDelegationKey() case KeyRelationship.assertionMethod: return api.tx.did.removeAttestationKey() case KeyRelationship.keyAgreement: if (!keyId) { throw new Error( `When removing a ${KeyRelationship.keyAgreement} key it is required to specify the id of the key to be removed.` ) } return api.tx.did.removeKeyAgreementKey(keyId) default: throw new Error( `key removal is only allowed for the following key types: ${[ KeyRelationship.keyAgreement, KeyRelationship.capabilityDelegation, KeyRelationship.assertionMethod, ]}` ) } } export async function getAddKeyExtrinsic( keyRelationship: KeyRelationship, key: INewPublicKey ): Promise<Extrinsic> { const keyAsEnum = formatPublicKey(key) const { api } = await BlockchainApiConnection.getConnectionOrConnect() if (keyRelationship === KeyRelationship.keyAgreement) { return api.tx.did.addKeyAgreementKey(keyAsEnum) } throw new Error( `adding to the key set is only allowed for the following key types: ${[ KeyRelationship.keyAgreement, ]}` ) } export async function getAddEndpointExtrinsic( endpoint: IDidServiceEndpoint ): Promise<Extrinsic> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() const encoded = encodeServiceEndpoint(api.registry, endpoint) return api.tx.did.addServiceEndpoint(encoded) } // The endpointId parameter is the service endpoint ID without the DID prefix. // So for a endpoint of the form did:kilt:<identifier>#<endpoint_id>, only <endpoint_id> must be passed as parameter here. export async function getRemoveEndpointExtrinsic( endpointId: string ): Promise<Extrinsic> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.tx.did.removeServiceEndpoint(endpointId) } export async function getDeleteDidExtrinsic( endpointsCount: number ): Promise<Extrinsic> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.tx.did.delete(endpointsCount) } export async function getReclaimDepositExtrinsic( didIdentifier: IIdentity['address'], endpointsCount: number ): Promise<SubmittableExtrinsic> { const { api } = await BlockchainApiConnection.getConnectionOrConnect() return api.tx.did.reclaimDeposit(didIdentifier, endpointsCount) } // The block number can either be provided by the DID subject, // or the latest one will automatically be fetched from the blockchain. export async function generateDidAuthenticatedTx({ signingPublicKey, alg, signer, txCounter, didIdentifier, call, submitter, blockNumber, }: AuthenticationTxCreationInput & KeystoreSigningOptions): Promise<SubmittableExtrinsic> { const blockchain = await BlockchainApiConnection.getConnectionOrConnect() const block = blockNumber || (await blockchain.api.query.system.number()) const signableCall = encodeDidAuthorizedCallOperation( blockchain.api.registry, { txCounter, didIdentifier, call, submitter, blockNumber: block } ) const signature = await signer.sign({ data: signableCall.toU8a(), meta: { method: call.method.toHex(), version: call.version, specVersion: blockchain.api.runtimeVersion.specVersion.toString(), transactionVersion: blockchain.api.runtimeVersion.transactionVersion.toString(), genesisHash: blockchain.api.genesisHash.toHex(), nonce: signableCall.txCounter.toHex(), address: Crypto.encodeAddress(signableCall.did), }, publicKey: Crypto.coToUInt8(signingPublicKey), alg, }) return blockchain.api.tx.did.submitDidCall(signableCall, { [signature.alg]: signature.data, }) }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of the author nor the names of the program's contributors may 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 AUTHORS OF THE SOFTWARE 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. */ /** * @fileoverview Code that handles the laying out of the panels within splitters. */ namespace VRS { /** * Describes a layout. */ export interface Layout_Options { name: string; vertical: boolean; savePane: number; collapsePane?: number; maxPane?: number; max?: number|string; startSizePane?: number; startSize?: number|string; fixedPane?: number; } /** * Describes an array that contains a layout. The array must be three elements long. The first element is the top or left * panel in the splitter (usually a JQuery), the middle element is an instance of Layout_Options and the third element is * the bottom or right panel. Each panel can itself be a Layout Array. */ export type Layout_Array = [JQuery | any[], Layout_Options, JQuery | any[]]; // Typescript doesn't allow circular type references, even in tuples /** * The settings to pass when creating a new Layout. */ export interface Layout_Settings { /** * The name of the layout. Must be unique. */ name: string; /** * The index into VRS.$$ of the text used to describe the layout. */ labelKey: string; /** * The description of the layout. */ layout: Layout_Array; /** * Called after the user has selected the layout, but before it is shown to the user. */ onFocus?: () => void; /** * Called after the user has selected another layout, after this layout has been torn down but before the new layout is shown. */ onBlur?: () => void; } /** * Describes a display layout. */ export class Layout { // Kept as public fields for backwards compatibility name: string; labelKey: string; layout: Layout_Array; onFocus: () => void; onBlur: () => void; constructor(settings: Layout_Settings) { if(!settings) throw 'You must supply a settings object'; if(!settings.name) throw 'The layout must be named'; if(!settings.labelKey) throw 'The layout must have a label'; if(!settings.layout) throw 'The layout must declare a layout'; if(!(settings.layout instanceof Array) || settings.layout.length != 3) throw 'The layout must be an array of 3 elements'; this.name = settings.name; this.labelKey = settings.labelKey; this.layout = settings.layout; this.onFocus = settings.onFocus || function() { }; this.onBlur = settings.onBlur || function() { }; } } /** * Describes the currently selected layout. */ interface Layout_Detail { layout: Layout; splitterGroupPersistence: SplitterGroupPersistence; topSplitter: JQuery; topSplitterIsSplitter?: boolean; } /** * Records the name of a layout and its label. */ export interface LayoutNameAndLabel { name: string; labelKey: string; } /** * The settings saved by the LayoutManager. */ export interface LayoutManager_SaveState { currentLayout: string; } /** * Manages the creation and destruction of splitters, and holds onto the list of registered splitter layouts. */ export class LayoutManager implements ISelfPersist<LayoutManager_SaveState> { private _Layouts: Layout[] = []; // An array of layouts registered with registerLayout(). private _CurrentLayout: Layout_Detail; private _Name: string; private _SplitterParent: JQuery; constructor(name?: string) { this._Name = name || 'default'; this._SplitterParent = $('body'); } getName() : string { return this._Name; } getSplitterParent() : JQuery { return this._SplitterParent; } setSplitterParent(value: JQuery) { if(this._CurrentLayout) throw 'You cannot change the splitter parent once a layout has been applied'; this._SplitterParent = value; this._SplitterParent.css({ width: '100%', height: '100%', position: 'fixed', top: '0,', left: '0' }) } /** * Gets the name of the currently selected layout. */ getCurrentLayout() : string { return this._CurrentLayout ? this._CurrentLayout.layout.name : null; } /** * Destroys the existing layout and applies a new one. */ applyLayout(layoutOrName: string | Layout, splitterParent?: JQuery) { var layout: Layout = <Layout>layoutOrName; if(!(layout instanceof Array)) { layout = this.findLayout(<string>layoutOrName); } if(layout === null) { throw 'Cannot find a layout with a name of ' + <string>layoutOrName; } this.undoLayout(); layout.onFocus(); var splitterGroupPersistence = new VRS.SplitterGroupPersistence(this._Name + '-' + layout.name); this._CurrentLayout = { layout: layout, splitterGroupPersistence: splitterGroupPersistence, topSplitter: this.doApplyLayout(layout.layout, splitterParent, splitterGroupPersistence, true) }; this._CurrentLayout.topSplitterIsSplitter = !!VRS.jQueryUIHelper.getSplitterPlugin(this._CurrentLayout.topSplitter); splitterGroupPersistence.setAutoSaveEnabled(true); } /** * Called recursively create a single splitter. */ private doApplyLayout(layout: Layout_Array, splitterParent, splitterGroupPersistence, isTopLevelSplitter) : JQuery { if(!(layout instanceof Array) || layout.length != 3) throw 'The layout must be an array of 3 elements'; if(!splitterParent) { splitterParent = this._SplitterParent; } var leftTop: JQuery = <JQuery>layout[0]; var splitterSettings: Splitter_Options = <Layout_Options>layout[1]; var rightBottom: JQuery = <JQuery>layout[2]; if(leftTop instanceof Array) leftTop = this.doApplyLayout(<any>leftTop, splitterParent, splitterGroupPersistence, false); if(rightBottom instanceof Array) rightBottom = this.doApplyLayout(<any>rightBottom, splitterParent, splitterGroupPersistence, false); var result = null; if(!leftTop) { result = rightBottom; } else if(!rightBottom) { result = leftTop; } else { splitterSettings.leftTopParent = leftTop.parent(); splitterSettings.rightBottomParent = rightBottom.parent(); splitterSettings.splitterGroupPersistence = splitterGroupPersistence; splitterSettings.isTopLevelSplitter = isTopLevelSplitter; result = $('<div/>') .appendTo(splitterParent); leftTop.appendTo(result); rightBottom.appendTo(result); result.vrsSplitter(splitterSettings); } return result; } /** * Destroys the current layout. */ private undoLayout() { if(this._CurrentLayout) { if(this._CurrentLayout.splitterGroupPersistence) { this._CurrentLayout.splitterGroupPersistence.dispose(); } if(this._CurrentLayout.topSplitter && this._CurrentLayout.topSplitterIsSplitter) { this._CurrentLayout.topSplitter.vrsSplitter('destroy'); } this._CurrentLayout.layout.onBlur(); } this._CurrentLayout = null; } /** * Registers a layout with the layout manager. */ registerLayout(layout: Layout) { if(!layout) throw 'You must supply a layout object'; var existingLayout = this.findLayout(layout.name); if(existingLayout) throw 'There is already a layout called ' + layout.name; this._Layouts.push(layout); } /** * Removes a registered layout. */ removeLayoutByName(name: string) { var layoutIndex = this.findLayoutIndex(name); if(layoutIndex !== -1) { this._Layouts.splice(layoutIndex, 1); } } /** * Returns a collection of all registered layouts. */ getLayouts() : LayoutNameAndLabel[] { var result: LayoutNameAndLabel[] = []; $.each(this._Layouts, function() { result.push({ name: this.name, labelKey: this.labelKey }); }); return result; } /** * Returns the layout with the given name or null if no such layout exists. */ private findLayout(name: string) : Layout { var idx = this.findLayoutIndex(name); return idx === -1 ? null : this._Layouts[idx]; } /** * Returns the index of the layout with the given name or -1 if no such layout exists. */ private findLayoutIndex(name: string) : number { var result = -1; $.each(this._Layouts, function(idx) { if(this.name === name) { result = idx; } return result === -1; }); return result; } /** * Saves the current state of the manager. */ saveState = function() { VRS.configStorage.save(this.persistenceKey(), this.createSettings()); } /** * Returns the previously saved state or the current state if no state was previously saved. */ loadState() : LayoutManager_SaveState { var savedSettings = VRS.configStorage.load(this.persistenceKey(), {}); var result = $.extend(this.createSettings(), savedSettings); if(result.currentLayout) { var existing = this.findLayout(result.currentLayout); if(!existing) { result.currentLayout = null; } } return result; } /** * Applies a previously saved state to the object. */ applyState(settings: LayoutManager_SaveState) { var layout = settings.currentLayout ? this.findLayout(settings.currentLayout) : null; if(layout) this.applyLayout(layout.name); } /** * Loads and applies the previously saved state. */ loadAndApplyState() { this.applyState(this.loadState()); } /** * Returns the key that the state will be saved against. */ private persistenceKey() : string { return 'vrsLayoutManager-' + this._Name; } /** * Returns the current state of the object. */ private createSettings() : LayoutManager_SaveState { return { currentLayout: this._CurrentLayout ? this._CurrentLayout.layout.name : null }; } } /* * Pre-builts */ export var layoutManager = new VRS.LayoutManager(); }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.PowerBIDedicated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: string; /** * Resource on which the operation is performed: capacity, etc. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resource?: string; /** * Operation type: create, update, delete, etc. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; } /** * Capacities REST API operation. */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation}. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The object that represents the operation. */ display?: OperationDisplay; } /** * Represents the SKU name and Azure pricing tier for PowerBI Dedicated resource. */ export interface ResourceSku { /** * Name of the SKU level. */ name: string; /** * The name of the Azure pricing tier to which the SKU applies. Possible values include: * 'PBIE_Azure' */ tier?: SkuTier; } /** * Represents an instance of an PowerBI Dedicated resource. */ export interface Resource extends BaseResource { /** * An identifier that represents the PowerBI Dedicated resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the PowerBI Dedicated resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the PowerBI Dedicated resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Location of the PowerBI Dedicated resource. */ location: string; /** * The SKU of the PowerBI Dedicated resource. */ sku: ResourceSku; /** * Key-value pairs of additional resource provisioning properties. */ tags?: { [propertyName: string]: string }; } /** * Represents an instance of a Dedicated Capacity resource. */ export interface DedicatedCapacity extends Resource { /** * A collection of Dedicated capacity administrators */ administration?: DedicatedCapacityAdministrators; /** * The current state of PowerBI Dedicated resource. The state is to indicate more states outside * of resource provisioning. Possible values include: 'Deleting', 'Succeeded', 'Failed', * 'Paused', 'Suspended', 'Provisioning', 'Updating', 'Suspending', 'Pausing', 'Resuming', * 'Preparing', 'Scaling' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly state?: State; /** * The current deployment state of PowerBI Dedicated resource. The provisioningState is to * indicate states for resource provisioning. Possible values include: 'Deleting', 'Succeeded', * 'Failed', 'Paused', 'Suspended', 'Provisioning', 'Updating', 'Suspending', 'Pausing', * 'Resuming', 'Preparing', 'Scaling' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; } /** * An array of administrator user identities */ export interface DedicatedCapacityAdministrators { /** * An array of administrator user identities. */ members?: string[]; } /** * Provision request specification */ export interface DedicatedCapacityUpdateParameters { /** * The SKU of the Dedicated capacity resource. */ sku?: ResourceSku; /** * Key-value pairs of additional provisioning properties. */ tags?: { [propertyName: string]: string }; /** * A collection of Dedicated capacity administrators */ administration?: DedicatedCapacityAdministrators; } /** * An object that represents enumerating SKUs for new resources */ export interface SkuEnumerationForNewResourceResult { /** * The collection of available SKUs for new resources */ value?: ResourceSku[]; } /** * An object that represents SKU details for existing resources */ export interface SkuDetailsForExistingResource { /** * The SKU in SKU details for existing resources. */ sku?: ResourceSku; } /** * An object that represents enumerating SKUs for existing resources */ export interface SkuEnumerationForExistingResourceResult { /** * The collection of available SKUs for existing resources */ value?: SkuDetailsForExistingResource[]; } /** * Describes the format of Error response. */ export interface ErrorResponse { /** * Error code */ code?: string; /** * Error message indicating why the operation failed. */ message?: string; } /** * Details of capacity name request body. */ export interface CheckCapacityNameAvailabilityParameters { /** * Name for checking availability. */ name?: string; /** * The resource type of PowerBI dedicated. Default value: * 'Microsoft.PowerBIDedicated/capacities'. */ type?: string; } /** * The checking result of capacity name availability. */ export interface CheckCapacityNameAvailabilityResult { /** * Indicator of availability of the capacity name. */ nameAvailable?: boolean; /** * The reason of unavailability. */ reason?: string; /** * The detailed message of the request unavailability. */ message?: string; } /** * An interface representing PowerBIDedicatedManagementClientOptions. */ export interface PowerBIDedicatedManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * An array of Dedicated capacities resources. * @extends Array<DedicatedCapacity> */ export interface DedicatedCapacities extends Array<DedicatedCapacity> { } /** * @interface * Result listing capacities. It contains a list of operations and a URL link to get the next set * of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * URL to get the next set of operation list results if there are any. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * Defines values for SkuTier. * Possible values include: 'PBIE_Azure' * @readonly * @enum {string} */ export type SkuTier = 'PBIE_Azure'; /** * Defines values for State. * Possible values include: 'Deleting', 'Succeeded', 'Failed', 'Paused', 'Suspended', * 'Provisioning', 'Updating', 'Suspending', 'Pausing', 'Resuming', 'Preparing', 'Scaling' * @readonly * @enum {string} */ export type State = 'Deleting' | 'Succeeded' | 'Failed' | 'Paused' | 'Suspended' | 'Provisioning' | 'Updating' | 'Suspending' | 'Pausing' | 'Resuming' | 'Preparing' | 'Scaling'; /** * Defines values for ProvisioningState. * Possible values include: 'Deleting', 'Succeeded', 'Failed', 'Paused', 'Suspended', * 'Provisioning', 'Updating', 'Suspending', 'Pausing', 'Resuming', 'Preparing', 'Scaling' * @readonly * @enum {string} */ export type ProvisioningState = 'Deleting' | 'Succeeded' | 'Failed' | 'Paused' | 'Suspended' | 'Provisioning' | 'Updating' | 'Suspending' | 'Pausing' | 'Resuming' | 'Preparing' | 'Scaling'; /** * Contains response data for the getDetails operation. */ export type CapacitiesGetDetailsResponse = DedicatedCapacity & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacity; }; }; /** * Contains response data for the create operation. */ export type CapacitiesCreateResponse = DedicatedCapacity & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacity; }; }; /** * Contains response data for the update operation. */ export type CapacitiesUpdateResponse = DedicatedCapacity & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacity; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type CapacitiesListByResourceGroupResponse = DedicatedCapacities & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacities; }; }; /** * Contains response data for the list operation. */ export type CapacitiesListResponse = DedicatedCapacities & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacities; }; }; /** * Contains response data for the listSkus operation. */ export type CapacitiesListSkusResponse = SkuEnumerationForNewResourceResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SkuEnumerationForNewResourceResult; }; }; /** * Contains response data for the listSkusForCapacity operation. */ export type CapacitiesListSkusForCapacityResponse = SkuEnumerationForExistingResourceResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SkuEnumerationForExistingResourceResult; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type CapacitiesCheckNameAvailabilityResponse = CheckCapacityNameAvailabilityResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckCapacityNameAvailabilityResult; }; }; /** * Contains response data for the beginCreate operation. */ export type CapacitiesBeginCreateResponse = DedicatedCapacity & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacity; }; }; /** * Contains response data for the beginUpdate operation. */ export type CapacitiesBeginUpdateResponse = DedicatedCapacity & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: DedicatedCapacity; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; };
the_stack
'use strict'; import { join, sep, dirname, basename, relative } from 'path'; import { setExtensionPath } from './providers/extensionPath' import { workspace, ExtensionContext, commands, window, Uri, WorkspaceConfiguration, debug, WorkspaceFolder, RelativePattern, OutputChannel } from 'vscode'; import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient'; import { CartridgesView } from './providers/CartridgesView'; import { LogsView } from './providers/LogsView'; import { ControllersView } from './providers/ControllersView'; import { existsSync, promises, createReadStream } from 'fs'; import { createServer, ServerResponse, IncomingMessage } from 'http'; import Uploader from "./providers/Uploader"; import { ProphetConfigurationProvider } from './providers/ConfigurationProvider'; import { Observable, of, empty } from 'rxjs'; import { flatMap, takeUntil, filter, reduce, merge } from 'rxjs/operators'; import { getDWConfig, getCartridgesFolder } from './lib/FileHelper'; import { SandboxFS } from './providers/SandboxFileSystemProvider'; import { createScriptLanguageServer, getOrderedCartridges } from './extensionScriptServer'; import * as unzip from 'unzip-stream'; import { spawnSync } from 'child_process'; import * as commandExist from 'command-exists'; import WebDav from './server/WebDav'; import { registerImportExportCSV } from './registerImportExportCSV'; /** * Create the ISML language server with the proper parameters * * @param context the extension context * @param configuration the extension configuration */ function createIsmlLanguageServer(context: ExtensionContext, configuration: WorkspaceConfiguration = workspace.getConfiguration('extension.prophet', null)) { // The server is implemented in node const serverModule = context.asAbsolutePath(join('dist', 'ismlServer.js')); // The debug options for the server const debugOptions = { execArgv: ['--nolazy', '--inspect=6004'] }; // If the extension is launched in debug mode then the debug server options are used // Otherwise the run options are used const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } }; const htmlConf = workspace.getConfiguration('html.format', null); // Options to control the language client const clientOptions: LanguageClientOptions = { // Register the server for plain text documents documentSelector: (configuration.get('ismlServer.activateOn', ['isml'])).map(type => ({ language: type, scheme: 'file' })), synchronize: { // Synchronize the setting section 'languageServerExample' to the server configurationSection: 'extension.prophet', // Notify the server about file changes to '.clientrc files contain in the workspace // fileEvents: workspace.createFileSystemWatcher('**/*.isml'), fileEvents: workspace.createFileSystemWatcher('**/.htmlhintrc') }, initializationOptions: { enableHtmlHint: configuration.get('htmlhint.enabled'), formatParams: { wrapLineLength: htmlConf.get('wrapLineLength'), unformatted: htmlConf.get('unformatted'), contentUnformatted: htmlConf.get('contentUnformatted'), indentInnerHtml: htmlConf.get('indentInnerHtml'), preserveNewLines: htmlConf.get('preserveNewLines'), maxPreserveNewLines: htmlConf.get('maxPreserveNewLines'), indentHandlebars: htmlConf.get('indentHandlebars'), endWithNewline: htmlConf.get('endWithNewline'), extraLiners: htmlConf.get('extraLiners'), wrapAttributes: htmlConf.get('wrapAttributes') } } }; context.subscriptions.push(commands.registerCommand('extension.prophet.command.override.template', async (fileURI?: Uri) => { if (workspace.workspaceFolders && fileURI && fileURI.scheme === 'file') { const cartridges = await getOrderedCartridges(workspace.workspaceFolders); if (cartridges && cartridges.length > 1) { const fileSep = '/cartridge/templates/'.split('/').join(sep); const [, filePath] = fileURI.fsPath.split(fileSep); const selected = await window.showQuickPick(cartridges.map(cartridge => cartridge.name)); if (selected) { const selectedCartridge = cartridges.find(cartridge => cartridge.name === selected); if (selectedCartridge && selectedCartridge.fsPath) { const newDestPath = join(selectedCartridge.fsPath, 'cartridge', 'templates', filePath); await promises.mkdir(dirname(newDestPath), { recursive: true }); try { await promises.access(newDestPath); } catch (e) { await promises.copyFile(fileURI.fsPath, newDestPath); } await commands.executeCommand('vscode.open', Uri.file(newDestPath)); } } } } })); // Create the language client and start the client. const ismlLanguageClient = new LanguageClient('ismlLanguageServer', 'ISML Language Server', serverOptions, clientOptions); //context.subscriptions.push(new SettingMonitor(ismlLanguageClient, 'extension.prophet.htmlhint.enabled').start()); ismlLanguageClient.onReady().then(() => { ismlLanguageClient.onNotification('isml:selectfiles', async (test) => { const data: string[] | undefined = test.data; if (workspace.workspaceFolders && data) { const orderedCartridges = await getOrderedCartridges(workspace.workspaceFolders); const cartPath = orderedCartridges?.map(cartridge => cartridge.name).join(':'); if (cartPath?.length) { const cartridges = cartPath.split(':'); const cartridge = cartridges.find(cartridgeItem => data.some(filename => filename.includes(cartridgeItem))); if (cartridge) { ismlLanguageClient.sendNotification('isml:selectedfile', data.find( filename => filename.includes(cartridge) )); return; } } window.showQuickPick(test.data).then(selected => { ismlLanguageClient.sendNotification('isml:selectedfile', selected); }, err => { ismlLanguageClient.sendNotification('isml:selectedfile', undefined); }); } }); ismlLanguageClient.onNotification('find:files', ({ searchID, workspacePath, pattern }) => { workspace.findFiles( new RelativePattern(Uri.parse(workspacePath).fsPath, pattern) ).then(result => { ismlLanguageClient.sendNotification('find:filesFound', { searchID, result: (result || []).map(uri => uri.fsPath) }); }) }); }).catch(err => { window.showErrorMessage(JSON.stringify(err)); }); return ismlLanguageClient; } function getWorkspaceFolders$$(context: ExtensionContext): Observable<Observable<WorkspaceFolder>> { return new Observable(observer => { function createObservableWorkspace(workspaceFolder: WorkspaceFolder) { return new Observable<WorkspaceFolder>(wrkObserver => { const wrkListener = workspace.onDidChangeWorkspaceFolders(event => { try { event.removed && event.removed.forEach(removedWrk => { if (removedWrk.uri.fsPath === workspaceFolder.uri.fsPath) { wrkObserver.complete(); wrkListener.dispose(); } }); } catch (e) { wrkObserver.error(e); } }); wrkObserver.next(workspaceFolder) return () => { wrkListener.dispose(); } }); } const listener = workspace.onDidChangeWorkspaceFolders(event => { event.added.forEach(addWrk => { if (addWrk.uri.scheme === 'file') { observer.next(createObservableWorkspace(addWrk)); } }); }); if (workspace.workspaceFolders) { workspace.workspaceFolders.forEach(addWrk => { if (addWrk.uri.scheme === 'file') { observer.next(createObservableWorkspace(addWrk)); } }); } context.subscriptions.push({ dispose() { observer.complete(); listener.dispose(); } }) return () => { listener.dispose(); }; }); } export function activate(context: ExtensionContext) { setExtensionPath(context.extensionPath); context.subscriptions.push( commands.registerCommand('extension.prophet.command.open.documentation', () => { commands.executeCommand('vscode.open', Uri.parse('https://documentation.b2c.commercecloud.salesforce.com/')); }) ); context.subscriptions.push( commands.registerCommand('extension.prophet.command.open.xchange', () => { commands.executeCommand('vscode.open', Uri.parse('https://developer.commercecloud.com/s/discussion-groups')); }) ); // register a configuration provider context.subscriptions.push( debug.registerDebugConfigurationProvider( 'prophet', new ProphetConfigurationProvider() ) ); initDebugger(); const workspaceFolders$$ = getWorkspaceFolders$$(context); // const configuration = workspace.getConfiguration('extension.prophet'); // var ismlLanguageServer = createIsmlLanguageServer(context, configuration); // context.subscriptions.push(ismlLanguageServer.start()); function subscribe2disposable($: Observable<any>) { const subscr = $.subscribe(() => { }, err => { window.showErrorMessage(JSON.stringify(err)); }); context.subscriptions.push({ dispose() { subscr.unsubscribe(); } }); } /// open files from browser subscribe2disposable(initializeToolkitActions().pipe(takeUntil(workspaceFolders$$.pipe(filter(() => false))))); /// uploader Uploader.initialize(context, workspaceFolders$$); // CartridgesView CartridgesView.initialize(context); ControllersView.initialize(context); context.subscriptions.push(...LogsView.initialize(commands, context)); context.subscriptions.push(createIsmlLanguageServer(context).start()); createScriptLanguageServer(context).then(SLS => { if (SLS) { context.subscriptions.push(SLS.start()); } }); const excludedMasks: { [key: string]: boolean } = workspace.getConfiguration('files', null).get<{}>('exclude') || {}; const ignoreProjects = Object.keys(excludedMasks || {}) .some(excludedMask => excludedMask.includes('.project') && excludedMasks && excludedMasks[excludedMask]); if (ignoreProjects) { window.showErrorMessage('Your `files.exclude` excludes `.project`. Cartridge detection may not work properly'); } initFS(context); initSOAPDownloadAPI(context); registerImportExportCSV(context); } let apiDocsGlobalChannel: OutputChannel | undefined; function initSOAPDownloadAPI(context: ExtensionContext) { context.subscriptions.push(commands.registerCommand('extension.prophet.command.download.webservice.api', async (fileURI?: Uri) => { const apiDocsChannel = apiDocsGlobalChannel || window.createOutputChannel('SOAP WebService Docs(Prophet)'); apiDocsGlobalChannel = apiDocsChannel; // local filesystem directory where docs will be downloaded & extracted const outputPath = await window.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, openLabel: 'Save SOAP API docs to ...' }); if (outputPath && outputPath.length && fileURI && workspace.workspaceFolders) { const dwConfig = await getDWConfig(workspace.workspaceFolders); const webdav = new WebDav(dwConfig); webdav.baseUrl = `https://${dwConfig.hostname}/on/demandware.servlet/WFS/StudioWS/Sites/`; const saveToFolder = outputPath[0].fsPath; const wsdlFullPath = fileURI.fsPath; const wsdlFileName = basename(wsdlFullPath, '.wsdl'); const wsdlFileNameWithZipExtension = wsdlFileName + '.zip'; const wsdlFileLocationOnServer = getWsdlPath(wsdlFullPath, wsdlFileName); const wsdlDownloadLocation = join(saveToFolder, wsdlFileNameWithZipExtension); apiDocsChannel.appendLine(`Going to download webservice api documentation from server: https://${dwConfig.hostname}/on/demandware.servlet/WFS/StudioWS/Sites/${wsdlFileLocationOnServer}`); try { const fileContents = await webdav.getBinary(wsdlFileLocationOnServer).toPromise(); if (fileContents) { // delete already existing zip file if (existsSync(wsdlDownloadLocation)) { await promises.unlink(wsdlDownloadLocation); } await promises.writeFile(wsdlDownloadLocation, fileContents, 'binary'); apiDocsChannel.appendLine('Successfully downloaded web-service api documentation from server'); //extract zip const unzipExtractor = unzip.Extract({ path: join(saveToFolder, 'src') }); createReadStream(wsdlDownloadLocation).pipe(unzipExtractor); unzipExtractor.on('error', function (error) { apiDocsChannel.appendLine(error); }) unzipExtractor.on('close', async () => { apiDocsChannel.appendLine('Successfully extracted web-service api documentation archive to ' + wsdlDownloadLocation); await promises.mkdir(join(saveToFolder, 'docs'), { recursive: true }) try { apiDocsChannel.show(); const isJavaDocInPath = commandExist.sync('javadoc'); if (isJavaDocInPath) { const files = await workspace.findFiles(new RelativePattern(join(saveToFolder, 'src'), '**/*')); const uniqFolders = new Set<string>(); files.forEach(file => { const name = dirname(file.fsPath); const fname = relative(join(saveToFolder, 'src'), name); uniqFolders.add(fname); }); const javaDocArgs = [ //'-verbose', '-J-Xmx256m', '-public', '-sourcepath', join(saveToFolder, 'src'), '-author', '-version', '-d', join(saveToFolder, 'docs'), Array.from(uniqFolders).map(file => file.replace(new RegExp(sep, 'ig'), '.')).join(' ')]; apiDocsChannel.appendLine('javadoc args:\n' + javaDocArgs.join('\n')); const result = spawnSync('javadoc', javaDocArgs, { cwd: saveToFolder, shell: true }); if (result.stderr) { result.stdout && apiDocsChannel.appendLine(result.stdout.toString()); apiDocsChannel.appendLine(result.stderr.toString()); apiDocsChannel.appendLine('Note: the extension require JDK8. Javadoc may fail if used another version. In the same moment generated java classes are downloaded and may be useful'); } else { result.stdout && apiDocsChannel.appendLine(result.stdout.toString()); apiDocsChannel.appendLine('Successfully generated web-service documentation to "docs" folder under ' + join(saveToFolder, 'docs')); window.showInformationMessage('Documentation Generated'); } } else { window.showInformationMessage('javadoc command not found. Check Error log'); apiDocsChannel.appendLine('javadoc not configured in path. Either configure it or manually run javadoc on the extracted zip'); } } catch (error) { apiDocsChannel.appendLine(error.message); } }); } } catch (error) { // handle request error if (error.statusCode) { if (error.statusCode === 404) { apiDocsChannel.appendLine('404: SOAP web-service API are not yet present on the server. System creates API after/during requesting them via custom script'); } else if (error.statusCode === 401) { apiDocsChannel.appendLine('401: Please check your credentials.'); } } else { // generic error apiDocsChannel.appendLine(error.message); } } } else { window.showInformationMessage('Folder path to save WSDL docs is mandatory'); } })); function getWsdlPath(wsdlFullPath: string, wsdlFileName: string) { if (wsdlFullPath.includes('webreferences2')) { return 'webrefgen2/' + wsdlFileName + '/' + wsdlFileName + '.api.zip'; } else { return 'webrefgen/webreferences/' + wsdlFileName + '/' + wsdlFileName + '.api.zip'; } } } function initFS(context: ExtensionContext) { if (!workspace.workspaceFolders) { return; } const fileWorkspaceFolders = workspace.workspaceFolders.filter(workspaceFolder => workspaceFolder.uri.scheme === 'file'); const sandboxFS = new SandboxFS(getDWConfig(fileWorkspaceFolders)); context.subscriptions.push(workspace.registerFileSystemProvider(SandboxFS.SCHEME, sandboxFS, { isCaseSensitive: true })); const extConf = workspace.getConfiguration('extension.prophet'); if (extConf.get('sandbox.filesystem.enabled')) { if (workspace.workspaceFolders) { if (!workspace.workspaceFolders.some(workspaceFolder => workspaceFolder.uri.scheme.toLowerCase() === SandboxFS.SCHEME)) { workspace.updateWorkspaceFolders(workspace.workspaceFolders.length, 0, { uri: Uri.parse(SandboxFS.SCHEME + '://current-sandbox'), name: "Sandbox - FileSystem", }); } } } } function initDebugger() { debug.onDidReceiveDebugSessionCustomEvent(event => { if (event.event === 'prophet.getdebugger.config' && workspace.workspaceFolders) { getDWConfig(workspace.workspaceFolders) .then(configData => { if (workspace.workspaceFolders) { const fileWorkspaceFolders = workspace.workspaceFolders.filter(workspaceFolder => workspaceFolder.uri.scheme === 'file'); return Promise.all(fileWorkspaceFolders.map( workspaceFolder => getCartridgesFolder(workspaceFolder) .pipe(reduce<string, string[]>((acc, r) => acc.concat(r), [] as string[])).toPromise() )).then(projects => { var flatten = ([] as string[]).concat(...projects); if (flatten.length) { return event.session.customRequest('DebuggerConfig', { config: configData, cartridges: flatten }); } else { return Promise.reject('Unable get cartridges list'); } }); } else { return Promise.reject('Unable detect workspaces'); } }).catch(err => { window.showErrorMessage(JSON.stringify(err)); }); } }); } interface IServerRequest { req: IncomingMessage, res: ServerResponse } function initializeToolkitActions() { return new Observable<IServerRequest>(observer => { const server = createServer((req, res) => { observer.next({ req, res }) }); server.once('error', err => { if (err instanceof Error) { window.showWarningMessage(`Unable open port for browsers files, probably other instance or Digital Studio is opened. Error: ${err.message}`); server.close(); } observer.error(err); }); server.listen(60606); return () => { server.close(); } }).pipe(flatMap(({ req, res }) => { if (workspace.workspaceFolders && workspace.workspaceFolders.length) { const fileWorkspaceFolders = workspace.workspaceFolders.filter(workspaceFolder => workspaceFolder.uri.scheme === 'file'); const cartridgesFolders = fileWorkspaceFolders .map(workspaceFolder => getCartridgesFolder(workspaceFolder)); return empty().pipe(merge(...cartridgesFolders)).pipe(reduce((acc, val) => { acc.add(val); return acc; }, new Set<string>())) .pipe(flatMap(cartridges => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); if (req.url && req.url.includes('/target')) { const reqUrl = req.url.split('/target=')[1].split('&')[0]; // fixme const clientFilePath = convertDebuggerPathToClient(reqUrl, Array.from(cartridges)); if (clientFilePath) { const filePaths = [ clientFilePath, clientFilePath.replace('.js', '.ds'), ]; const filePath = filePaths.find(existsSync); if (filePath) { commands.executeCommand('vscode.open', Uri.file(filePath)).then(() => { // DO NOTHING }, err => { window.showErrorMessage(err); }); } else { window.showWarningMessage(`Unable to find '${reqUrl}'`); } } else { window.showWarningMessage(`Unable to find '${reqUrl}'.`); } } return of(1); })); } else { return empty(); } })); } function convertDebuggerPathToClient(this: void, debuggerPath: string, cartridges: string[]): string { debuggerPath = debuggerPath.substr(1); const debuggerSep = debuggerPath.split('/'); const cartridgeName = debuggerSep.shift() || ''; const cartPath = cartridges.find(cartridge => cartridge.endsWith(cartridgeName)); if (cartPath) { const tmp = join(cartPath, debuggerSep.join(sep)); return tmp; } else { window.showErrorMessage("Unable match cartridge"); return ''; } } export function deactivate() { // nothing to do }
the_stack
"use strict"; import { GraphQLClient } from "graphql-request"; import { memoize, groupBy as _groupBy, sortBy as _sortBy, flatten as _flatten, uniq as _uniq, uniqBy as _uniqBy } from "lodash-es"; import { ResponseError } from "vscode-jsonrpc/lib/messages"; import { URI } from "vscode-uri"; import { InternalError, ReportSuppressedMessages } from "../agentError"; import { SessionContainer } from "../container"; import { GitRemoteParser } from "../git/parsers/remoteParser"; import { Logger } from "../logger"; import { EntityAccount, EntitySearchResponse, ERROR_NR_CONNECTION_INVALID_API_KEY, ERROR_NR_CONNECTION_MISSING_API_KEY, ERROR_NR_CONNECTION_MISSING_URL, ERROR_PIXIE_NOT_CONFIGURED, ErrorGroupResponse, ErrorGroupsResponse, GetNewRelicAccountsRequestType, GetNewRelicAccountsResponse, GetNewRelicAssigneesRequestType, GetNewRelicErrorGroupRequest, GetNewRelicErrorGroupRequestType, GetNewRelicErrorGroupResponse, GetObservabilityEntitiesRequest, GetObservabilityEntitiesRequestType, GetObservabilityEntitiesResponse, GetObservabilityErrorAssignmentsRequest, GetObservabilityErrorAssignmentsRequestType, GetObservabilityErrorAssignmentsResponse, GetObservabilityErrorGroupMetadataRequest, GetObservabilityErrorGroupMetadataRequestType, GetObservabilityErrorGroupMetadataResponse, GetObservabilityErrorsRequest, GetObservabilityErrorsRequestType, GetObservabilityErrorsResponse, GetObservabilityReposRequest, GetObservabilityReposRequestType, GetObservabilityReposResponse, NewRelicConfigurationData, NewRelicErrorGroup, ObservabilityError, ObservabilityErrorCore, RelatedEntity, ReposScm, ThirdPartyDisconnect, ThirdPartyProviderConfig, Entity, StackTraceResponse, ErrorGroupStateType, BuiltFromResult, ErrorGroup } from "../protocol/agent.protocol"; import { CSNewRelicProviderInfo } from "../protocol/api.protocol"; import { CodeStreamSession } from "../session"; import { log, lspHandler, lspProvider } from "../system"; import { Strings } from "../system/string"; import { ThirdPartyIssueProviderBase } from "./provider"; export interface Directive { type: "assignRepository" | "removeAssignee" | "setAssignee" | "setState"; data: any; } interface Directives { directives: Directive[]; } interface NewRelicId { accountId: number; unknownAbbreviation: string; entityType: string; unknownGuid: string; } interface NewRelicEntity { guid: string; name: string; tags: { key: string; values: string[] }[]; type: string; } class AccessTokenError extends Error { constructor(public text: string, public innerError: any, public isAccessTokenError: boolean) { super(text); } } @lspProvider("newrelic") export class NewRelicProvider extends ThirdPartyIssueProviderBase<CSNewRelicProviderInfo> { private _newRelicUserId: number | undefined = undefined; private _memoizedBuildRepoRemoteVariants: any; constructor(session: CodeStreamSession, config: ThirdPartyProviderConfig) { super(session, config); this._memoizedBuildRepoRemoteVariants = memoize( this.buildRepoRemoteVariants, (remotes: string[]) => remotes ); } get displayName() { return "New Relic"; } get name() { return "newrelic"; } get headers() { return { "Api-Key": this.accessToken!, "Content-Type": "application/json" }; } get apiUrl() { const data = this._providerInfo && this._providerInfo.data; return this.getApiUrlCore(data); } private getApiUrlCore(data?: { apiUrl?: string; usingEU?: boolean; [key: string]: any }): string { if (data) { if (data.apiUrl) { return Strings.trimEnd(data.apiUrl, "/").toLowerCase(); } if (data.usingEU) { return "https://api.eu.newrelic.com"; } } return "https://api.newrelic.com"; } get productUrl() { return this.apiUrl.replace("api", "one"); } get baseUrl() { return this.apiUrl; } get graphQlBaseUrl() { return `${this.baseUrl}/graphql`; } @log() async onDisconnected(request?: ThirdPartyDisconnect) { // delete the graphql client so it will be reconstructed if a new token is applied delete this._client; delete this._newRelicUserId; super.onDisconnected(request); } protected async client(): Promise<GraphQLClient> { const client = this._client || (this._client = this.createClient(this.graphQlBaseUrl, this.accessToken)); client.setHeaders({ "Api-Key": this.accessToken!, "Content-Type": "application/json", "NewRelic-Requesting-Services": "CodeStream" }); return client; } protected createClient(graphQlBaseUrl?: string, accessToken?: string): GraphQLClient { if (!graphQlBaseUrl) { throw new ResponseError(ERROR_NR_CONNECTION_MISSING_URL, "Could not get a New Relic API URL"); } if (!accessToken) { throw new ResponseError( ERROR_NR_CONNECTION_MISSING_API_KEY, "Could not get a New Relic API key" ); } const options: { [key: string]: any } = {}; if (this._httpsAgent) { options.agent = this._httpsAgent; } const client = new GraphQLClient(graphQlBaseUrl, options); // set accessToken on a per-usage basis... possible for accessToken // to be revoked from the source (github.com) and a stale accessToken // could be cached in the _client instance. client.setHeaders({ "Api-Key": accessToken!, "Content-Type": "application/json", "NewRelic-Requesting-Services": "CodeStream" }); return client; } @log() async configure(request: NewRelicConfigurationData) { // FIXME - this rather sucks as a way to ensure we have the access token // const userPromise = new Promise<void>(resolve => { // this.session.api.onDidReceiveMessage(e => { // if (e.type !== MessageType.Users) return; // // const me = e.data.find((u: any) => u.id === this.session.userId) as CSMe | null | undefined; // if (me == null) return; // // const providerInfo = this.getProviderInfo(me); // if (providerInfo == null || !providerInfo.accessToken) return; // // resolve(); // }); // }); const client = this.createClient( this.getApiUrlCore({ apiUrl: request.apiUrl }) + "/graphql", request.apiKey ); const { userId, accounts } = await this.validateApiKey(client); Logger.log(`Found ${accounts.length} New Relic accounts`); const accountIds = accounts.map(_ => _.id); const accountsToOrgs = await this.session.api.lookupNewRelicOrganizations({ accountIds }); const orgIdsSet = new Set(accountsToOrgs.map(_ => _.orgId)); const uniqueOrgIds = Array.from(orgIdsSet.values()); Logger.log(`Found ${uniqueOrgIds.length} associated New Relic organizations`); const team = await SessionContainer.instance().teams.getByIdFromCache(this.session.teamId); const company = team && (await SessionContainer.instance().companies.getByIdFromCache(team.companyId)); if (company) { const existingnOrgIds = company.nrOrgIds || []; const uniqueNewOrgIds = uniqueOrgIds.filter(_ => existingnOrgIds.indexOf(_) < 0); if (accountsToOrgs.length) { if (uniqueNewOrgIds.length) { Logger.log( `Associating company ${company.id} with NR orgs ${uniqueNewOrgIds.join(", ")}` ); await this.session.api.addCompanyNewRelicInfo(company.id, undefined, uniqueNewOrgIds); } } else if (accounts.length) { const existingAccountIds = company.nrAccountIds || []; const newAccountIds = accountIds.filter(_ => existingAccountIds.indexOf(_) < 0); if (newAccountIds.length) { Logger.log( `Associating company ${company.id} with NR accounts ${newAccountIds.join(", ")}` ); await this.session.api.addCompanyNewRelicInfo(company.id, newAccountIds, undefined); } } } await this.session.api.setThirdPartyProviderToken({ providerId: this.providerConfig.id, token: request.apiKey, data: { userId, accountId: request.accountId, apiUrl: request.apiUrl, orgIds: uniqueOrgIds } }); // update telemetry super-properties this.session.updateNewRelicSuperProps(userId, uniqueOrgIds[0]); } private async validateApiKey( client: GraphQLClient ): Promise<{ userId: number; organizationId?: number; accounts: any[]; }> { try { const response = await client.request<{ actor: { user: { id: number; }; organization?: { id: number; }; accounts: [ { id: number; name: string; } ]; }; }>(`{ actor { user { id } accounts { id, name } } }`); return { userId: response.actor.user.id, accounts: response.actor.accounts, organizationId: response.actor.organization?.id }; } catch (ex) { const accessTokenError = this.getAccessTokenError(ex); throw new ResponseError( ERROR_NR_CONNECTION_INVALID_API_KEY, accessTokenError?.message || ex.message || ex.toString() ); } } async mutate<T>(query: string, variables: any = undefined) { await this.ensureConnected(); return (await this.client()).request<T>(query, variables); } async query<T = any>(query: string, variables: any = undefined): Promise<T> { await this.ensureConnected(); if (this._providerInfo && this._providerInfo.tokenError) { delete this._client; throw new InternalError(ReportSuppressedMessages.AccessTokenInvalid); } let response: any; try { response = await (await this.client()).request<T>(query, variables); } catch (ex) { Logger.warn(`NR: query caught:`, ex); const exType = this._isSuppressedException(ex); if (exType !== undefined) { // this throws the error but won't log to sentry (for ordinary network errors that seem temporary) throw new InternalError(exType, { error: ex }); } else { const accessTokenError = this.getAccessTokenError(ex); if (accessTokenError) { throw new AccessTokenError(accessTokenError.message, ex, true); } // this is an unexpected error, throw the exception normally throw ex; } } return response; } private getAccessTokenError(ex: any): { message: string } | undefined { let requestError = ex as { response: { errors: { extensions: { error_code: string; }; message: string; }[]; }; }; if ( requestError && requestError.response && requestError.response.errors && requestError.response.errors.length ) { return requestError.response.errors.find( _ => _.extensions && _.extensions.error_code === "BAD_API_KEY" ); } return undefined; } private _applicationEntitiesCache: GetObservabilityEntitiesResponse | undefined = undefined; @lspHandler(GetObservabilityEntitiesRequestType) @log({ timed: true }) async getEntities( request: GetObservabilityEntitiesRequest ): Promise<GetObservabilityEntitiesResponse> { try { if (this._applicationEntitiesCache != null) { Logger.debug("NR: query entities (from cache)"); return this._applicationEntitiesCache; } let results: { guid: string; name: string }[] = []; let nextCursor: any = undefined; // let i = 0; // while (true) { if (request.appName != null) { // try to find the entity based on the app / remote name const response = await this.query<any>( `query { actor { entitySearch(query: "type='APPLICATION' and name LIKE '${Strings.sanitizeGraphqlValue( request.appName )}'", sortBy:MOST_RELEVANT) { results { entities { guid name } } } } }` ); results = results.concat( response.actor.entitySearch.results.entities.map((_: any) => { return { guid: _.guid, name: _.name }; }) ); } const response = await this.query<any>( `query search($cursor:String) { actor { entitySearch(query: "type='APPLICATION'", sortBy:MOST_RELEVANT) { results(cursor:$cursor) { nextCursor entities { guid name } } } } }`, { cursor: nextCursor } ); results = results.concat( response.actor.entitySearch.results.entities.map((_: any) => { return { guid: _.guid, name: _.name }; }) ); // nextCursor = response.actor.entitySearch.results.nextCursor; // i++; // if (!nextCursor) { // break; // } else { // Logger.log("NR: query entities ", { // i: i // }); // } // } results.sort((a, b) => a.name.localeCompare(b.name)); results = [...new Map(results.map(item => [item["guid"], item])).values()]; this._applicationEntitiesCache = { entities: results }; return { entities: results }; } catch (ex) { Logger.error(ex, "NR: getEntities"); } return { entities: [] }; } @lspHandler(GetObservabilityErrorGroupMetadataRequestType) @log({ timed: true }) async getErrorGroupMetadata( request: GetObservabilityErrorGroupMetadataRequest ): Promise<GetObservabilityErrorGroupMetadataResponse | undefined> { if (!request.errorGroupGuid) return undefined; try { const metricResponse = await this.getMetricData(request.errorGroupGuid); if (!metricResponse) return undefined; const mappedEntity = await this.findMappedRemoteByEntity(metricResponse?.entityGuid); return { entityId: metricResponse?.entityGuid, occurrenceId: metricResponse?.traceId, remote: mappedEntity?.url } as GetObservabilityErrorGroupMetadataResponse; } catch (ex) { Logger.error(ex, "NR: getErrorGroupMetadata", { request: request }); } return undefined; } @lspHandler(GetObservabilityErrorAssignmentsRequestType) @log({ timed: true }) async getObservabilityErrorAssignments(request: GetObservabilityErrorAssignmentsRequest) { const response: GetObservabilityErrorAssignmentsResponse = { items: [] }; try { const { users } = SessionContainer.instance(); const me = await users.getMe(); const result = await this.getErrorsInboxAssignments(me.user.email); if (result) { response.items = result.actor.errorsInbox.errorGroups.results .filter(_ => { // dont show IGNORED or RESOLVED errors return !_.state || _.state === "UNRESOLVED"; }) .map((_: any) => { return { entityId: _.entityGuid, errorGroupGuid: _.id, errorClass: _.name, message: _.message, errorGroupUrl: _.url } as ObservabilityErrorCore; }); if (response.items && response.items.find(_ => !_.errorClass)) { Logger.warn("NR: getObservabilityErrorAssignments has empties", { items: response.items }); } Logger.warn("NR: getObservabilityErrorAssignments", { itemsCount: response.items.length }); } else { Logger.log("NR: getObservabilityErrorAssignments (none)"); } } catch (ex) { Logger.warn("NR: getObservabilityErrorAssignments", { error: ex }); } return response; } @lspHandler(GetObservabilityReposRequestType) @log({ timed: true }) async getObservabilityRepos(request: GetObservabilityReposRequest) { const response: GetObservabilityReposResponse = { repos: [] }; try { const { scm } = SessionContainer.instance(); const reposResponse = await scm.getRepos({ inEditorOnly: true, includeRemotes: true }); let filteredRepos: ReposScm[] | undefined = reposResponse?.repositories; if (request?.filters?.length) { const repoIds = request.filters.map(_ => _.repoId); filteredRepos = reposResponse.repositories?.filter(r => r.id && repoIds.includes(r.id))!; } filteredRepos = filteredRepos?.filter(_ => _.id); if (!filteredRepos || !filteredRepos.length) return response; for (const repo of filteredRepos) { if (!repo.id || !repo.remotes || !repo.remotes.length) { Logger.warn( "NR: getObservabilityRepos skipping repo with missing id and/or repo.remotes", { repo: repo } ); continue; } const folderName = this.getRepoName(repo.folder); let remotes: string[] = []; for (const remote of repo.remotes) { if (remote.name === "origin" || remote.remoteWeight === 0) { // this is the origin remote remotes = [remote.uri.toString().replace("ssh://", "")]; break; } else { remotes.push(remote.uri.toString()); } } // find REPOSITORY entities tied to a remote const repositoryEntitiesResponse = await this.findRepositoryEntitiesByRepoRemotes(remotes); let remoteUrls: (string | undefined)[] = []; let hasRepoAssociation; let applicationAssociations; if (repositoryEntitiesResponse?.entities) { // find applications that are tied to repo entities const entitiesReponse = await this.findRelatedEntityByRepositoryGuids( repositoryEntitiesResponse?.entities?.map(_ => _.guid) ); // find the application entities applicationAssociations = entitiesReponse?.actor?.entities?.filter( _ => _.relatedEntities?.results?.filter(r => r.source?.entity?.type === "APPLICATION") .length ); hasRepoAssociation = applicationAssociations?.length > 0; // find all the unique remotes in all the entities found remoteUrls = _uniq( _flatten( repositoryEntitiesResponse.entities.map(_ => { return _.tags?.find(t => t.key === "url")?.values; }) ) ).filter(Boolean); Logger.log("NR: found repositories matching remotes", { remotes: remotes, entities: repositoryEntitiesResponse?.entities?.map(_ => { return { guid: _.guid, name: _.name }; }) }); } let remote = ""; if (remoteUrls && remoteUrls[0]) { if (remoteUrls.length > 1) { // if for some reason we have > 1 (user has bad remotes, or remotes that point to other places WITH entity mappings) Logger.warn(""); Logger.warn("NR: getEntitiesByRepoRemote FOUND MORE THAN 1 UNIQUE REMOTE", { remotes: remotes, entityRemotes: remoteUrls }); Logger.warn(""); } remote = remoteUrls[0]; } else { remote = remotes[0]; } let uniqueEntities: Entity[] = []; let uniqueAccounts = new Set<string>(); if (applicationAssociations && applicationAssociations.length) { for (const entity of applicationAssociations) { if (!entity.relatedEntities?.results) continue; for (const relatedResult of entity.relatedEntities.results) { if ( relatedResult?.source?.entity?.type === "APPLICATION" && relatedResult?.target?.entity?.type === "REPOSITORY" ) { const tags = relatedResult.target.entity.tags; if (!tags) continue; const accountIdTag = tags.find(_ => _.key === "accountId"); if (!accountIdTag || !accountIdTag.values) continue; const accountIdString = accountIdTag.values[0]; if (uniqueAccounts.has(accountIdString)) continue; uniqueEntities.push({ account: { id: parseInt(accountIdString || "0", 10), name: tags.find(_ => _.key === "account")?.values[0] || "Account" }, guid: relatedResult.source.entity.guid, name: relatedResult.source.entity.name }); uniqueAccounts.add(accountIdString); } } } } response.repos.push({ repoId: repo.id!, repoName: folderName, repoRemote: remote, hasRepoAssociation: hasRepoAssociation, // @ts-ignore entityAccounts: uniqueEntities .map(entity => { return { accountId: entity.account?.id, accountName: entity.account?.name || "Account", entityGuid: entity.guid, entityName: entity.name } as EntityAccount; }) .filter(Boolean) }); Logger.log(`NR: getObservabilityRepos hasRepoAssociation=${hasRepoAssociation}`, { repoId: repo.id, entities: repositoryEntitiesResponse?.entities?.map(_ => _.guid) }); } } catch (ex) { Logger.error(ex, "NR: getObservabilityRepos"); } return response; } @lspHandler(GetObservabilityErrorsRequestType) @log({ timed: true }) async getObservabilityErrors(request: GetObservabilityErrorsRequest) { const response: GetObservabilityErrorsResponse = { repos: [] }; try { // NOTE: might be able to eliminate some of this if we can get a list of entities const { scm } = SessionContainer.instance(); const reposResponse = await scm.getRepos({ inEditorOnly: true, includeRemotes: true }); let filteredRepos: ReposScm[] | undefined = reposResponse?.repositories; if (request?.filters?.length) { const repoIds = request.filters.map(_ => _.repoId); filteredRepos = reposResponse.repositories?.filter(r => r.id && repoIds.includes(r.id))!; } filteredRepos = filteredRepos?.filter(_ => _.id); if (!filteredRepos || !filteredRepos.length) return response; for (const repo of filteredRepos) { if (!repo.remotes) continue; const observabilityErrors: ObservabilityError[] = []; const remotes = repo.remotes.map(_ => { return (_ as any).uri!.toString(); }); const repositoryEntitiesResponse = await this.findRepositoryEntitiesByRepoRemotes(remotes); if (repositoryEntitiesResponse?.entities?.length) { const entityFilter = request.filters?.find(_ => _.repoId === repo.id!); let filteredEntities = repositoryEntitiesResponse.entities.filter((_, index) => entityFilter && entityFilter.entityGuid ? _.guid === entityFilter.entityGuid : index == 0 ); if (entityFilter && entityFilter.entityGuid && !filteredEntities.length) { filteredEntities = repositoryEntitiesResponse.entities.filter((r, i) => i === 0); Logger.warn("NR: getObservabilityErrors bad entityGuid passed", { entityGuid: entityFilter.entityGuid }); } for (const entity of filteredEntities) { const accountIdTag = entity.tags?.find(_ => _.key === "accountId"); if (!accountIdTag) { Logger.warn("NR: count not find accountId for entity", { entityGuid: entity.guid }); continue; } const accountIdValue = parseInt(accountIdTag.values[0] || "0", 10); const urlTag = entity.tags?.find(_ => _.key === "url"); const urlValue = urlTag?.values[0]; const related = await this.findRelatedEntityByRepositoryGuid(entity.guid); const applicationGuid = related.actor.entity.relatedEntities.results.find( (r: any) => r.type === "BUILT_FROM" )?.source.entity.guid; if (!applicationGuid) continue; const response = await this.findFingerprintedErrorTraces( accountIdValue, applicationGuid ); if (response.actor.account.nrql.results) { const groupedByFingerprint = _groupBy( response.actor.account.nrql.results, "fingerprint" ); const errorTraces = []; for (const k of Object.keys(groupedByFingerprint)) { const groupedObject = _sortBy(groupedByFingerprint[k], r => -r.timestamp); const lastObject = groupedObject[0]; errorTraces.push({ fingerPrintId: k, length: groupedObject.length, appName: lastObject.appName, lastOccurrence: lastObject.timestamp, occurrenceId: lastObject.id, errorClass: lastObject["error.class"], message: lastObject.message, entityGuid: lastObject.entityGuid }); } for (const errorTrace of errorTraces) { try { const response = await this.getErrorGroupFromNameMessageEntity( errorTrace.errorClass, errorTrace.message, errorTrace.entityGuid ); if (response && response.actor.errorsInbox.errorGroup) { observabilityErrors.push({ entityId: errorTrace.entityGuid, appName: errorTrace.appName, errorClass: errorTrace.errorClass, message: errorTrace.message, remote: urlValue!, errorGroupGuid: response.actor.errorsInbox.errorGroup.id, occurrenceId: errorTrace.occurrenceId, count: errorTrace.length, lastOccurrence: errorTrace.lastOccurrence, errorGroupUrl: response.actor.errorsInbox.errorGroup.url }); if (observabilityErrors.length > 4) { break; } } } catch (ex) { Logger.warn("NR: internal error getErrorGroupGuid", { ex: ex }); } } } } } else { } response.repos.push({ repoId: repo.id!, repoName: this.getRepoName(repo.folder), errors: observabilityErrors! }); } } catch (ex) { Logger.error(ex, "getObservabilityErrors"); } return response as any; } @log() async getPixieToken(accountId: number) { try { const response = await this.query( `query fetchPixieAccessToken($accountId:Int!) { actor { account(id: $accountId) { pixie { pixieAccessToken } } } } `, { accountId: accountId } ); const token = response.actor.account.pixie.pixieAccessToken; if (token == null) { throw new ResponseError(ERROR_PIXIE_NOT_CONFIGURED, "Unable to fetch Pixie token"); } return token; } catch (e) { Logger.error(e); throw new ResponseError(ERROR_PIXIE_NOT_CONFIGURED, e.message || e.toString()); } } @lspHandler(GetNewRelicAccountsRequestType) @log() async getAccounts(): Promise<GetNewRelicAccountsResponse> { try { const response = await this.query<{ actor: { accounts: { id: number; name: string }[]; }; }>(`{ actor { accounts { id, name } } }`); return response.actor; } catch (e) { Logger.error(e, "NR: getAccounts"); throw e; } } @lspHandler(GetNewRelicErrorGroupRequestType) @log() async getNewRelicErrorGroupData( request: GetNewRelicErrorGroupRequest ): Promise<GetNewRelicErrorGroupResponse | undefined> { let errorGroup: NewRelicErrorGroup | undefined = undefined; let accountId = 0; let entityGuid: string = ""; try { const errorGroupGuid = request.errorGroupGuid; const parsedId = NewRelicProvider.parseId(errorGroupGuid)!; accountId = parsedId?.accountId; let errorGroupFullResponse; if (request.entityGuid) { entityGuid = request.entityGuid; // if we have the entityId use this errorGroupFullResponse = await this.fetchErrorGroup( errorGroupGuid, entityGuid, request.occurrenceId ); } else { // no entity, look it up const errorGroupPartialResponse = await this.fetchErrorGroupDataById(errorGroupGuid); if (errorGroupPartialResponse?.entityGuid) { entityGuid = errorGroupPartialResponse?.entityGuid; errorGroupFullResponse = await this.fetchErrorGroup( errorGroupGuid, entityGuid, request.occurrenceId ); } } Logger.log( `NR: getNewRelicErrorGroupData hasRequest.entityGuid=${request.entityGuid != null}`, { request: request } ); if (errorGroupFullResponse) { const errorGroupResponse = errorGroupFullResponse.actor.errorsInbox.errorGroup; entityGuid = errorGroupResponse.entityGuid; errorGroup = { entity: {}, accountId: accountId, entityGuid: entityGuid, guid: errorGroupResponse.id, title: errorGroupResponse.name, message: errorGroupResponse.message, errorGroupUrl: `${this.productUrl}/redirect/errors-inbox/${errorGroupGuid}`, entityUrl: `${this.productUrl}/redirect/entity/${errorGroupResponse.entityGuid}` }; errorGroup.attributes = { // TODO fix me // Timestamp: { type: "timestamp", value: errorGroup.timestamp } // "Host display name": { type: "string", value: "11.11.11.11:11111" }, // "URL host": { type: "string", value: "value" }, // "URL path": { type: "string", value: "value" } }; let states; if (errorGroupFullResponse.actor.errorsInbox.errorGroupStateTypes) { states = errorGroupFullResponse.actor.errorsInbox.errorGroupStateTypes.map( (_: ErrorGroupStateType) => _.type ); } errorGroup.states = states && states.length ? states : ["UNRESOLVED", "RESOLVED", "IGNORED"]; errorGroup.errorGroupUrl = errorGroupFullResponse.actor.errorsInbox.errorGroup.url; errorGroup.entityName = errorGroupFullResponse.actor.entity.name; errorGroup.entityAlertingSeverity = errorGroupFullResponse.actor.entity.alertSeverity; errorGroup.state = errorGroupFullResponse.actor.errorsInbox.errorGroup.state || "UNRESOLVED"; const assignee = errorGroupFullResponse.actor.errorsInbox.errorGroup.assignment; if (assignee) { errorGroup.assignee = { email: assignee.email, id: assignee.userInfo?.id, name: assignee.userInfo?.name, gravatar: assignee.userInfo?.gravatar }; } const builtFromResult = this.findBuiltFrom( errorGroupFullResponse.actor.entity.relatedEntities.results ); if (errorGroup.entity && builtFromResult) { if (builtFromResult.error) { errorGroup.entity.relationship = { error: builtFromResult.error }; } else { errorGroup.entity = { repo: { name: builtFromResult.name!, urls: [builtFromResult.url!] } }; } } if (errorGroupFullResponse.actor?.entity?.exception?.stackTrace) { errorGroup.errorTrace = { path: errorGroupFullResponse.actor.entity.name, stackTrace: errorGroupFullResponse.actor.entity.crash ? errorGroupFullResponse.actor.entity.crash.stackTrace.frames : errorGroupFullResponse.actor.entity.exception.stackTrace.frames }; errorGroup.hasStackTrace = true; } Logger.log("NR: ErrorGroup found", { errorGroupGuid: errorGroup.guid, occurrenceId: request.occurrenceId, entityGuid: entityGuid, hasErrorGroup: errorGroup != null, hasStackTrace: errorGroup?.hasStackTrace === true }); } else { Logger.warn( `NR: No errorGroup results errorGroupGuid (${errorGroupGuid}) in account (${accountId})`, { request: request, entityGuid: entityGuid, accountId: accountId } ); return { accountId: accountId, error: { message: `Could not find error info for that errorGroupGuid in account (${accountId})`, details: (await this.buildErrorDetailSettings( accountId, entityGuid, errorGroupGuid )) as any } }; } return { accountId, errorGroup }; } catch (ex) { Logger.error(ex); let result: any = {}; if (ex.response?.errors) { result = { message: ex.response.errors.map((_: { message: string }) => _.message).join("\n") }; } else { result = { message: ex.message ? ex.message : ex.toString() }; } result.details = (await this.buildErrorDetailSettings( accountId, entityGuid, request.errorGroupGuid )) as any; return { error: result, accountId, errorGroup: undefined as any }; } } @lspHandler(GetNewRelicAssigneesRequestType) @log() async getAssignableUsers(request: { boardId: string }) { const { scm } = SessionContainer.instance(); const committers = await scm.getLatestCommittersAllRepos(); let users: any[] = []; if (committers?.scm) { users = users.concat( Object.keys(committers.scm).map((_: string) => { return { id: _, email: _, group: "GIT" }; }) ); } // TODO fix me get users from NR // users.push({ // id: "123", // displayName: "Some One", // email: "someone@newrelic.com", // avatarUrl: "http://...", // group: "NR" // }); return { users: users }; } @log() async setAssignee(request: { errorGroupGuid: string; emailAddress: string; }): Promise<Directives | undefined> { try { const response = await this.setAssigneeByEmail(request!); const assignment = response.errorsInboxAssignErrorGroup.assignment; // won't be a userInfo object if assigning by email return { directives: [ { type: "setAssignee", data: { assignee: { email: assignment.email, id: assignment?.userInfo?.id, name: assignment?.userInfo?.name } } } ] }; } catch (ex) { Logger.error(ex); return undefined; } } @log() async removeAssignee(request: { errorGroupGuid: string; emailAddress?: string; userId?: string; }): Promise<Directives | undefined> { try { await this.setAssigneeByUserId({ ...request, userId: "0" }); return { directives: [ { type: "removeAssignee", data: { assignee: null } } ] }; } catch (ex) { Logger.error(ex); return undefined; } } @log() async setState(request: { errorGroupGuid: string; state: "RESOLVED" | "UNRESOLVED" | "IGNORED"; }): Promise<Directives | undefined> { try { const response = await this.mutate<{ errorTrackingUpdateErrorGroupState: { errors?: { description: string }[]; state?: string; }; }>( `mutation UpdateErrorGroupState($errorGroupGuid: ID!, $state: ErrorsInboxErrorGroupState!) { errorsInboxUpdateErrorGroupState(id: $errorGroupGuid, state: $state) { state errors { description type } } } `, { errorGroupGuid: request.errorGroupGuid, state: request.state } ); Logger.log("NR: errorsInboxUpdateErrorGroupState", { request: request, response: response }); if (response?.errorTrackingUpdateErrorGroupState?.errors?.length) { const stateFailure = response.errorTrackingUpdateErrorGroupState.errors .map(_ => _.description) .join("\n"); Logger.warn("NR: errorsInboxUpdateErrorGroupState failure", { error: stateFailure }); throw new Error(stateFailure); } return { directives: [ { type: "setState", data: { state: request.state } } ] }; } catch (ex) { Logger.error(ex as Error); throw ex; } } @log() async assignRepository(request: { /** this is a field that can be parsed to get an accountId */ parseableAccountId: string; errorGroupGuid?: string; entityId?: string; name?: string; url: string; }): Promise<Directives | undefined> { try { const parsedId = NewRelicProvider.parseId(request.parseableAccountId)!; const accountId = parsedId?.accountId; const name = request.name; const response = await this.mutate<{ referenceEntityCreateOrUpdateRepository: { created: string[]; failures: { guid: string; message: string; type: string; }[]; }; }>( `mutation ReferenceEntityCreateOrUpdateRepository($accountId: Int!, $name: String!, $url: String!) { referenceEntityCreateOrUpdateRepository(repositories: [{accountId: $accountId, name: $name, url: $url}]) { created failures { guid message type } } } `, { accountId: accountId, name: name, url: request.url } ); Logger.log("NR: referenceEntityCreateOrUpdateRepository", { accountId: accountId, name: name, url: request.url, response: response }); if (response?.referenceEntityCreateOrUpdateRepository?.failures?.length) { const failures = response.referenceEntityCreateOrUpdateRepository.failures .map(_ => `${_.message} (${_.type})`) .join("\n"); Logger.warn("NR: referenceEntityCreateOrUpdateRepository failures", { accountId: accountId, name: name, url: request.url, failures: failures }); throw new Error(failures); } const repoEntityId = response.referenceEntityCreateOrUpdateRepository.created[0]; const entityId = request.entityId || (await this.getEntityGuidFromErrorGroupGuid(request.errorGroupGuid!)); if (entityId) { const entityRelationshipUserDefinedCreateOrReplaceResponse = await this.mutate<{ errors?: { message: string }[]; }>( `mutation EntityRelationshipUserDefinedCreateOrReplace($sourceEntityGuid:EntityGuid!, $targetEntityGuid:EntityGuid!) { entityRelationshipUserDefinedCreateOrReplace(sourceEntityGuid: $sourceEntityGuid, targetEntityGuid: $targetEntityGuid, type: BUILT_FROM) { errors { message type } } } `, { sourceEntityGuid: entityId, targetEntityGuid: repoEntityId } ); Logger.log("NR: entityRelationshipUserDefinedCreateOrReplace", { sourceEntityGuid: entityId, targetEntityGuid: repoEntityId, response: entityRelationshipUserDefinedCreateOrReplaceResponse }); if (entityRelationshipUserDefinedCreateOrReplaceResponse?.errors?.length) { const createOrReplaceError = entityRelationshipUserDefinedCreateOrReplaceResponse.errors .map(_ => _.message) .join("\n"); Logger.warn("NR: entityRelationshipUserDefinedCreateOrReplace failure", { error: createOrReplaceError }); throw new Error(createOrReplaceError); } return { directives: [ { type: "assignRepository", data: { id: request.errorGroupGuid, entityGuid: response.referenceEntityCreateOrUpdateRepository && response.referenceEntityCreateOrUpdateRepository.created ? response.referenceEntityCreateOrUpdateRepository.created[0] : undefined, repo: { accountId: accountId, name: request.name, urls: [request.url] } } } ] }; } else { Logger.warn("NR: entityId needed for entityRelationshipUserDefinedCreateOrReplace is null"); throw new Error("Could not locate entityId"); } } catch (ex) { Logger.error(ex, "NR: assignRepository", { request: request }); throw ex; } } @log() private async getUserId(): Promise<number | undefined> { try { if (this._newRelicUserId != null) { return this._newRelicUserId; } if (this._providerInfo && this._providerInfo.data && this._providerInfo.data.userId) { try { const id = this._providerInfo.data.userId; this._newRelicUserId = parseInt(id.toString(), 10); Logger.log("NR: getUserId (found data)", { userId: id }); } catch (ex) { Logger.warn("NR: getUserId", { error: ex }); } } if (this._newRelicUserId) return this._newRelicUserId; const response = await this.query(`{ actor { user { id } } }`); const id = response.actor?.user?.id; if (id) { this._newRelicUserId = parseInt(id, 10); Logger.log("NR: getUserId (found api)", { userId: id }); return this._newRelicUserId; } } catch (ex) { Logger.warn("NR: getUserId " + ex.message, { error: ex }); } return undefined; } private async getEntityGuidFromErrorGroupGuid( errorGroupGuid: string ): Promise<string | undefined> { try { const results = await this.fetchErrorGroupDataById(errorGroupGuid); return results ? results.entityGuid : undefined; } catch (ex) { Logger.error(ex, "NR: getEntityIdFromErrorGroupGuid", { errorGroupGuid: errorGroupGuid }); return undefined; } } private async fetchErrorGroupDataById(errorGroupGuid: string): Promise<ErrorGroup | undefined> { try { let response = await this.query<{ actor: { errorsInbox: { errorGroup: ErrorGroup; }; }; }>( `query errorGroupById($errorGroupId: ID) { actor { errorsInbox { errorGroup(id: $errorGroupId) { id message name state entityGuid } } } } `, { errorGroupId: errorGroupGuid } ); const results = response.actor.errorsInbox.errorGroup; if (results) { return results; } } catch (ex) { Logger.warn("NR: fetchErrorGroupDataById failure", { errorGroupGuid }); let accessTokenError = ex as { message: string; innerError?: { message: string }; isAccessTokenError: boolean; }; if (accessTokenError && accessTokenError.innerError && accessTokenError.isAccessTokenError) { throw new Error(accessTokenError.message); } } return undefined; } @log() private async fetchStackTrace( entityGuid: string, occurrenceId: string ): Promise<StackTraceResponse> { let fingerprintId = 0; try { // BrowserApplicationEntity uses a fingerprint instead of an occurrence and it's a number if (occurrenceId && occurrenceId.match(/^-?\d+$/)) { fingerprintId = parseInt(occurrenceId, 10); occurrenceId = ""; } } catch {} return this.query( `query getStackTrace($entityGuid: EntityGuid!, $occurrenceId: String!, $fingerprintId: Int!) { actor { entity(guid: $entityGuid) { ... on ApmApplicationEntity { guid name exception(occurrenceId: $occurrenceId) { message stackTrace { frames { filepath formatted line name } } } } ... on BrowserApplicationEntity { guid name exception(fingerprint: $fingerprintId) { message stackTrace { frames { column line formatted name } } } } ... on MobileApplicationEntity { guid name exception(occurrenceId: $occurrenceId) { stackTrace { frames { line formatted name } } } crash(occurrenceId: $occurrenceId) { stackTrace { frames { line formatted name } } } } } } } `, { entityGuid: entityGuid, occurrenceId: occurrenceId, fingerprintId: fingerprintId } ); } @log() private async fetchErrorGroup( errorGroupGuid: string, entityGuid: string, occurrenceId?: string ): Promise<ErrorGroupResponse> { let stackTracePromise; if (entityGuid && occurrenceId) { try { // kick this off stackTracePromise = this.fetchStackTrace(entityGuid, occurrenceId); } catch (ex) { Logger.warn("NR: fetchErrorGroup (stack trace missing)", { entityGuid: entityGuid, occurrenceId: occurrenceId }); stackTracePromise = undefined; } } const response: ErrorGroupResponse = await this.query( `query getErrorGroup($errorGroupGuid:ID!, $entityGuid:EntityGuid!) { actor { entity(guid: $entityGuid) { alertSeverity name relatedEntities(filter: {direction: BOTH, relationshipTypes: {include: BUILT_FROM}}) { results { source { entity { name guid type } } target { entity { name guid type tags { key values } } } type } } } errorsInbox { errorGroupStateTypes { type } errorGroup(id: $errorGroupGuid) { url id message name state entityGuid assignment { email userInfo { gravatar id name } } state } } } } `, { errorGroupGuid: errorGroupGuid, entityGuid: entityGuid } ); if (occurrenceId && response?.actor?.entity) { let stackTrace; try { stackTrace = await stackTracePromise; if (stackTrace) { if (response.actor.entity) { response.actor.entity.crash = stackTrace.actor.entity.crash; response.actor.entity.exception = stackTrace.actor.entity.exception; } } } catch (ex) { Logger.warn("NR: fetchErrorGroup (stack trace missing upon waiting)", { entityGuid: entityGuid, occurrenceId: occurrenceId }); } } return response; } private async buildErrorDetailSettings( accountId: number, entityGuid: string, errorGroupGuid: string ) { let meUser = undefined; const { users, session } = SessionContainer.instance(); try { meUser = await users.getMe(); } catch {} if ( meUser && meUser.user && (meUser.user.email.indexOf("@newrelic.com") > -1 || meUser.user.email.indexOf("@codestream.com") > -1) ) { return { settings: { accountId: accountId, errorGroupGuid: errorGroupGuid, entityGuid: entityGuid, codeStreamUserId: meUser?.user?.id, codeStreamTeamId: session?.teamId, apiUrl: this.apiUrl } }; } return undefined; } private async buildRepoRemoteVariants(remotes: string[]): Promise<string[]> { const set = new Set<string>(); await Promise.all( remotes.map(async _ => { const variants = await GitRemoteParser.getRepoRemoteVariants(_); variants.forEach(v => { set.add(v.value); }); return true; }) ); return Array.from(set); } /** * Finds any Repositories mapped to a remote[s] * * @private * @param {string[]} remotes * @return {*} {(Promise< * | { * entities?: { * guid: string; * name: String; * tags: { key: string; values: string[] }[]; * }[]; * remotes?: string[]; * } * | undefined * >)} * @memberof NewRelicProvider */ private async findRepositoryEntitiesByRepoRemotes( remotes: string[] ): Promise< | { entities?: Entity[]; remotes?: string[]; } | undefined > { try { const remoteVariants: string[] = await this._memoizedBuildRepoRemoteVariants(remotes); if (!remoteVariants.length) return undefined; const remoteFilters = remoteVariants.map((_: string) => `tags.url = '${_}'`).join(" OR "); const queryResponse = await this.query<EntitySearchResponse>(`{ actor { entitySearch(query: "type = 'REPOSITORY' and (${remoteFilters})") { count query results { entities { guid name tags { key values } } } } } } `); return { entities: queryResponse.actor.entitySearch.results.entities, remotes: remoteVariants }; } catch (ex) { Logger.warn("NR: getEntitiesByRepoRemote", { error: ex }); return undefined; } } private async findFingerprintedErrorTraces(accountId: number, applicationGuid: string) { return this.query( `query fetchErrorsInboxData($accountId:Int!) { actor { account(id: $accountId) { nrql(query: "SELECT id, fingerprint, appName, error.class, message, entityGuid FROM ErrorTrace WHERE fingerprint IS NOT NULL and entityGuid='${applicationGuid}' SINCE 3 days ago LIMIT 500") { nrql results } } } } `, { accountId: accountId } ); } private async findRelatedEntityByRepositoryGuids( repositoryGuids: string[] ): Promise<{ actor: { entities: { relatedEntities: { results: RelatedEntity[]; }; }[]; }; }> { return this.query( `query fetchRelatedEntities($guids:[EntityGuid]!){ actor { entities(guids: $guids) { relatedEntities(filter: {direction: BOTH, relationshipTypes: {include: BUILT_FROM}}) { results { source { entity { name guid type } } target { entity { name guid type tags { key values } } } type } } } } } `, { guids: repositoryGuids } ); } private async findRelatedEntityByRepositoryGuid( repositoryGuid: string ): Promise<{ actor: { entity: { relatedEntities: { results: RelatedEntity[]; }; }; }; }> { return this.query( `query fetchRelatedEntities($guid:EntityGuid!){ actor { entity(guid: $guid) { relatedEntities(filter: {direction: BOTH, relationshipTypes: {include: BUILT_FROM}}) { results { source { entity { name guid type } } target { entity { name guid type tags { key values } } } type } } } } } `, { guid: repositoryGuid } ); } private async getErrorGroupFromNameMessageEntity( name: string, message: string, entityGuid: string ) { return this.query( `query getErrorGroupGuid($name: String!, $message:String!, $entityGuid:EntityGuid!){ actor { errorsInbox { errorGroup(errorEvent: {name: $name, message: $message, entityGuid: $entityGuid}) { id url } } } } `, { name: name, message: message, entityGuid: entityGuid } ); } private async getErrorsInboxAssignments( emailAddress: string, userId?: number ): Promise<ErrorGroupsResponse | undefined> { try { if (userId == null || userId == 0) { // TODO fix me. remove this once we have a userId on a connection userId = await this.getUserId(); } return this.query( `query getAssignments($userId: Int, $emailAddress: String!) { actor { errorsInbox { errorGroups(filter: {isAssigned: true, assignment: {userId: $userId, userEmail: $emailAddress}}) { results { url state name message id entityGuid } } } } }`, { userId: userId, emailAddress: emailAddress } ); } catch (ex) { Logger.warn("NR: getErrorsInboxAssignments", { userId: userId, usingEmailAddress: emailAddress != null }); return undefined; } } private async getEntityGuidFromErrorGroupId(errorGroupGuid: string): Promise<string> { const response = await this.query( `query getErrorGroup($id:ID) { actor { errorsInbox { errorGroup(id:$id) { entityGuid } } } }`, { id: errorGroupGuid } ); let entityGuid; if (response?.actor?.errorsInbox?.errorGroup) { entityGuid = response.actor.errorsInbox.errorGroup.entityGuid; } return entityGuid; } /** * from an errorGroupGuid, returns a traceId and an entityId * * @private * @param {string} errorGroupGuid * @return {*} {(Promise< * | { * entityGuid: string; * traceId: string; * } * | undefined * >)} * @memberof NewRelicProvider */ private async getMetricData( errorGroupGuid: string ): Promise< | { entityGuid: string; traceId?: string; } | undefined > { try { if (!errorGroupGuid) { Logger.warn("NR: getMetric missing errorGroupGuid"); return undefined; } const accountId = NewRelicProvider.parseId(errorGroupGuid)?.accountId!; const entityGuid = await this.getEntityGuidFromErrorGroupId(errorGroupGuid); if (!entityGuid) { Logger.warn("NR: getMetric missing entityGuid", { accountId: accountId, errorGroupGuid: errorGroupGuid }); return undefined; } const response1 = await this.fetchErrorGroupDataById(errorGroupGuid); if (response1) { const response2 = await this.query<{ actor: { account: { nrql: { results: { entityGuid: string; id: string; }[]; }; }; }; }>( `query getErrorTrace($accountId: Int!) { actor { account(id: $accountId) { nrql(query: "FROM ErrorTrace SELECT * WHERE error.class LIKE '${Strings.sanitizeGraphqlValue( response1.name )}' AND error.message LIKE '${Strings.sanitizeGraphqlValue( response1.message )}' AND entityGuid='${Strings.sanitizeGraphqlValue( response1.entityGuid )}' SINCE 1 week ago LIMIT 1") { results } } } } `, { accountId: accountId } ); if (response2) { const errorTraceResult = response2.actor.account.nrql.results[0]; if (!errorTraceResult) { Logger.warn("NR: getMetric missing errorTraceResult", { accountId: accountId, errorGroupGuid: errorGroupGuid, metricResult: response1 }); return { entityGuid: entityGuid }; } if (errorTraceResult) { return { entityGuid: entityGuid || response1.entityGuid, traceId: errorTraceResult.id }; } } } } catch (ex) { Logger.error(ex, "NR: getMetric", { errorGroupGuid: errorGroupGuid }); } return undefined; } private async findMappedRemoteByEntity( entityGuid: string ): Promise< | { url: string; name: string; } | undefined > { if (!entityGuid) return undefined; const relatedEntityResponse = await this.findRelatedEntityByRepositoryGuid(entityGuid); if (relatedEntityResponse) { const result = this.findBuiltFrom(relatedEntityResponse.actor.entity.relatedEntities.results); if (result?.name && result.url) { return { name: result.name, url: result.url }; } } return undefined; } private setAssigneeByEmail(request: { errorGroupGuid: string; emailAddress: string }) { return this.query( `mutation errorsInboxAssignErrorGroup($email: String!, $errorGroupGuid: ID!) { errorsInboxAssignErrorGroup(assignment: {userEmail: $email}, id: $errorGroupGuid) { assignment { email userInfo { email gravatar id name } } } } `, { email: request.emailAddress, errorGroupGuid: request.errorGroupGuid } ); } private setAssigneeByUserId(request: { errorGroupGuid: string; userId: string }) { return this.query( `mutation errorsInboxAssignErrorGroup($userId: Int!, $errorGroupGuid: ID!) { errorsInboxAssignErrorGroup(assignment: {userId: $userId}, id: $errorGroupGuid) { assignment { email userInfo { email gravatar id name } } } }`, { errorGroupGuid: request.errorGroupGuid, userId: parseInt(request.userId, 10) } ); } private findBuiltFrom(relatedEntities: RelatedEntity[]): BuiltFromResult | undefined { if (!relatedEntities || !relatedEntities.length) return undefined; const builtFrom = relatedEntities.find(_ => _.type === "BUILT_FROM"); if (!builtFrom) return undefined; const targetEntity = builtFrom.target?.entity; if (targetEntity) { const targetEntityTags = targetEntity.tags; if (targetEntityTags) { const targetEntityTagsValues = targetEntityTags.find((_: any) => _.key === "url"); if (targetEntityTagsValues) { // why would there ever be more than 1?? if ( targetEntityTagsValues && targetEntityTagsValues.values && targetEntityTagsValues.values.length ) { return { url: targetEntityTagsValues.values[0], name: builtFrom.target.entity.name }; } else { Logger.warn("NR: findBuiltFrom missing tags with url[s]", { relatedEntities: relatedEntities }); return { error: { message: "Could not find a repository relationship. Please check your setup and try again." } }; } } } else { Logger.warn("NR: findBuiltFrom missing tags", { relatedEntities: relatedEntities }); return { error: { message: "Could not find a repository relationship. Please check your setup and try again." } }; } } return undefined; } public static parseId(idLike: string): NewRelicId | undefined { try { const parsed = Buffer.from(idLike, "base64").toString("utf-8"); if (!parsed) return undefined; const split = parsed.split(/\|/); //"140272|ERT|ERR_GROUP|12076a73-fc88-3205-92d3-b785d12e08b6" const [accountId, unknownAbbreviation, entityType, unknownGuid] = split; return { accountId: accountId != null ? parseInt(accountId, 10) : 0, unknownAbbreviation, entityType, unknownGuid }; } catch (e) { Logger.warn("NR: " + e.message, { idLike }); } return undefined; } private getRepoName(folder: { name?: string; uri: string }) { try { let folderName = (folder.name || URI.parse(folder.uri) .fsPath.split(/[\\/]+/) .pop())!; return folderName; } catch (ex) { Logger.warn("NR: getRepoName", { folder: folder, error: ex }); } return "repo"; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Kusto (also known as Azure Data Explorer) Event Grid Data Connection * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleCluster = new azure.kusto.Cluster("exampleCluster", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * sku: { * name: "Standard_D13_v2", * capacity: 2, * }, * }); * const exampleDatabase = new azure.kusto.Database("exampleDatabase", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * clusterName: exampleCluster.name, * hotCachePeriod: "P7D", * softDeletePeriod: "P31D", * }); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountReplicationType: "GRS", * }); * const testEventHubNamespace = new azure.eventhub.EventHubNamespace("testEventHubNamespace", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * sku: "Standard", * }); * const testEventHub = new azure.eventhub.EventHub("testEventHub", { * namespaceName: azurerm_eventhub_namespace.example.name, * resourceGroupName: exampleResourceGroup.name, * partitionCount: 1, * messageRetention: 1, * }); * const exampleConsumerGroup = new azure.eventhub.ConsumerGroup("exampleConsumerGroup", { * namespaceName: azurerm_eventhub_namespace.example.name, * eventhubName: azurerm_eventhub.example.name, * resourceGroupName: exampleResourceGroup.name, * }); * const exampleEventSubscription = new azure.eventgrid.EventSubscription("exampleEventSubscription", { * scope: exampleAccount.id, * eventhubEndpointId: azurerm_eventhub.example.id, * eventDeliverySchema: "EventGridSchema", * includedEventTypes: [ * "Microsoft.Storage.BlobCreated", * "Microsoft.Storage.BlobRenamed", * ], * retryPolicy: { * eventTimeToLive: 144, * maxDeliveryAttempts: 10, * }, * }); * const exampleEventGridDataConnection = new azure.kusto.EventGridDataConnection("exampleEventGridDataConnection", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * clusterName: exampleCluster.name, * databaseName: exampleDatabase.name, * storageAccountId: exampleAccount.id, * eventhubId: azurerm_eventhub.example.id, * eventhubConsumerGroupName: exampleConsumerGroup.name, * tableName: "my-table", * mappingRuleName: "my-table-mapping", * dataFormat: "JSON", * }, { * dependsOn: [exampleEventSubscription], * }); * ``` * * ## Import * * Kusto Event Grid Data Connections can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:kusto/eventGridDataConnection:EventGridDataConnection example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Kusto/Clusters/cluster1/Databases/database1/DataConnections/dataConnection1 * ``` */ export class EventGridDataConnection extends pulumi.CustomResource { /** * Get an existing EventGridDataConnection resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: EventGridDataConnectionState, opts?: pulumi.CustomResourceOptions): EventGridDataConnection { return new EventGridDataConnection(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:kusto/eventGridDataConnection:EventGridDataConnection'; /** * Returns true if the given object is an instance of EventGridDataConnection. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is EventGridDataConnection { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === EventGridDataConnection.__pulumiType; } /** * Specifies the blob storage event type that needs to be processed. Possible * Values are `Microsoft.Storage.BlobCreated` and `Microsoft.Storage.BlobRenamed`. Defaults * to `Microsoft.Storage.BlobCreated`. */ public readonly blobStorageEventType!: pulumi.Output<string | undefined>; /** * Specifies the name of the Kusto Cluster this data connection will be added to. Changing this forces a new resource to be created. */ public readonly clusterName!: pulumi.Output<string>; /** * Specifies the data format of the EventHub messages. Allowed values: `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSV` and `TXT` */ public readonly dataFormat!: pulumi.Output<string | undefined>; /** * Specifies the name of the Kusto Database this data connection will be added to. Changing this forces a new resource to be created. */ public readonly databaseName!: pulumi.Output<string>; /** * Specifies the Event Hub consumer group this data connection will use for * ingestion. Changing this forces a new resource to be created. */ public readonly eventhubConsumerGroupName!: pulumi.Output<string>; /** * Specifies the resource id of the Event Hub this data connection will use for ingestion. * Changing this forces a new resource to be created. */ public readonly eventhubId!: pulumi.Output<string>; /** * The location where the Kusto Database should be created. Changing this forces a new resource to be created. */ public readonly location!: pulumi.Output<string>; /** * Specifies the mapping rule used for the message ingestion. Mapping rule must exist before resource is created. */ public readonly mappingRuleName!: pulumi.Output<string | undefined>; /** * The name of the Kusto Event Grid Data Connection to create. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * Specifies the Resource Group where the Kusto Database should exist. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * is the first record of every file ignored? Defaults to `false`. */ public readonly skipFirstRecord!: pulumi.Output<boolean | undefined>; /** * Specifies the resource id of the Storage Account this data connection will use for ingestion. Changing this forces a new resource to be created. */ public readonly storageAccountId!: pulumi.Output<string>; /** * Specifies the target table name used for the message ingestion. Table must exist before resource is created. */ public readonly tableName!: pulumi.Output<string | undefined>; /** * Create a EventGridDataConnection resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: EventGridDataConnectionArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: EventGridDataConnectionArgs | EventGridDataConnectionState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as EventGridDataConnectionState | undefined; inputs["blobStorageEventType"] = state ? state.blobStorageEventType : undefined; inputs["clusterName"] = state ? state.clusterName : undefined; inputs["dataFormat"] = state ? state.dataFormat : undefined; inputs["databaseName"] = state ? state.databaseName : undefined; inputs["eventhubConsumerGroupName"] = state ? state.eventhubConsumerGroupName : undefined; inputs["eventhubId"] = state ? state.eventhubId : undefined; inputs["location"] = state ? state.location : undefined; inputs["mappingRuleName"] = state ? state.mappingRuleName : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["skipFirstRecord"] = state ? state.skipFirstRecord : undefined; inputs["storageAccountId"] = state ? state.storageAccountId : undefined; inputs["tableName"] = state ? state.tableName : undefined; } else { const args = argsOrState as EventGridDataConnectionArgs | undefined; if ((!args || args.clusterName === undefined) && !opts.urn) { throw new Error("Missing required property 'clusterName'"); } if ((!args || args.databaseName === undefined) && !opts.urn) { throw new Error("Missing required property 'databaseName'"); } if ((!args || args.eventhubConsumerGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'eventhubConsumerGroupName'"); } if ((!args || args.eventhubId === undefined) && !opts.urn) { throw new Error("Missing required property 'eventhubId'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.storageAccountId === undefined) && !opts.urn) { throw new Error("Missing required property 'storageAccountId'"); } inputs["blobStorageEventType"] = args ? args.blobStorageEventType : undefined; inputs["clusterName"] = args ? args.clusterName : undefined; inputs["dataFormat"] = args ? args.dataFormat : undefined; inputs["databaseName"] = args ? args.databaseName : undefined; inputs["eventhubConsumerGroupName"] = args ? args.eventhubConsumerGroupName : undefined; inputs["eventhubId"] = args ? args.eventhubId : undefined; inputs["location"] = args ? args.location : undefined; inputs["mappingRuleName"] = args ? args.mappingRuleName : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["skipFirstRecord"] = args ? args.skipFirstRecord : undefined; inputs["storageAccountId"] = args ? args.storageAccountId : undefined; inputs["tableName"] = args ? args.tableName : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(EventGridDataConnection.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering EventGridDataConnection resources. */ export interface EventGridDataConnectionState { /** * Specifies the blob storage event type that needs to be processed. Possible * Values are `Microsoft.Storage.BlobCreated` and `Microsoft.Storage.BlobRenamed`. Defaults * to `Microsoft.Storage.BlobCreated`. */ blobStorageEventType?: pulumi.Input<string>; /** * Specifies the name of the Kusto Cluster this data connection will be added to. Changing this forces a new resource to be created. */ clusterName?: pulumi.Input<string>; /** * Specifies the data format of the EventHub messages. Allowed values: `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSV` and `TXT` */ dataFormat?: pulumi.Input<string>; /** * Specifies the name of the Kusto Database this data connection will be added to. Changing this forces a new resource to be created. */ databaseName?: pulumi.Input<string>; /** * Specifies the Event Hub consumer group this data connection will use for * ingestion. Changing this forces a new resource to be created. */ eventhubConsumerGroupName?: pulumi.Input<string>; /** * Specifies the resource id of the Event Hub this data connection will use for ingestion. * Changing this forces a new resource to be created. */ eventhubId?: pulumi.Input<string>; /** * The location where the Kusto Database should be created. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * Specifies the mapping rule used for the message ingestion. Mapping rule must exist before resource is created. */ mappingRuleName?: pulumi.Input<string>; /** * The name of the Kusto Event Grid Data Connection to create. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * Specifies the Resource Group where the Kusto Database should exist. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * is the first record of every file ignored? Defaults to `false`. */ skipFirstRecord?: pulumi.Input<boolean>; /** * Specifies the resource id of the Storage Account this data connection will use for ingestion. Changing this forces a new resource to be created. */ storageAccountId?: pulumi.Input<string>; /** * Specifies the target table name used for the message ingestion. Table must exist before resource is created. */ tableName?: pulumi.Input<string>; } /** * The set of arguments for constructing a EventGridDataConnection resource. */ export interface EventGridDataConnectionArgs { /** * Specifies the blob storage event type that needs to be processed. Possible * Values are `Microsoft.Storage.BlobCreated` and `Microsoft.Storage.BlobRenamed`. Defaults * to `Microsoft.Storage.BlobCreated`. */ blobStorageEventType?: pulumi.Input<string>; /** * Specifies the name of the Kusto Cluster this data connection will be added to. Changing this forces a new resource to be created. */ clusterName: pulumi.Input<string>; /** * Specifies the data format of the EventHub messages. Allowed values: `AVRO`, `CSV`, `JSON`, `MULTIJSON`, `PSV`, `RAW`, `SCSV`, `SINGLEJSON`, `SOHSV`, `TSV` and `TXT` */ dataFormat?: pulumi.Input<string>; /** * Specifies the name of the Kusto Database this data connection will be added to. Changing this forces a new resource to be created. */ databaseName: pulumi.Input<string>; /** * Specifies the Event Hub consumer group this data connection will use for * ingestion. Changing this forces a new resource to be created. */ eventhubConsumerGroupName: pulumi.Input<string>; /** * Specifies the resource id of the Event Hub this data connection will use for ingestion. * Changing this forces a new resource to be created. */ eventhubId: pulumi.Input<string>; /** * The location where the Kusto Database should be created. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * Specifies the mapping rule used for the message ingestion. Mapping rule must exist before resource is created. */ mappingRuleName?: pulumi.Input<string>; /** * The name of the Kusto Event Grid Data Connection to create. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * Specifies the Resource Group where the Kusto Database should exist. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * is the first record of every file ignored? Defaults to `false`. */ skipFirstRecord?: pulumi.Input<boolean>; /** * Specifies the resource id of the Storage Account this data connection will use for ingestion. Changing this forces a new resource to be created. */ storageAccountId: pulumi.Input<string>; /** * Specifies the target table name used for the message ingestion. Table must exist before resource is created. */ tableName?: pulumi.Input<string>; }
the_stack
import _ from 'lodash'; import AggregateError from 'aggregate-error'; import ensureError from 'ensure-error'; import invariant from 'assert'; import objectHash from 'object-hash'; export function errorPrefix(resourcePath: ReadonlyArray<string>): string { return `[dataloader-codegen :: ${resourcePath.join('.')}]`; } /** * An error reflects missing item in response. It follows similar structure to ApolloError that has an `extension` field. * This makes it easier to link and integrate with apollo-server * @see https://github.com/apollographql/apollo-server/blob/faba52c689c22472a19fcb65d78925df549077f7/packages/apollo-server-errors/src/index.ts#L3 */ export class BatchItemNotFoundError extends Error { readonly extensions: Record<string, any>; constructor(message: string) { super(message); this.name = this.constructor.name; this.extensions = { code: 'BATCH_ITEM_NOT_FOUND_ERROR', }; Error.captureStackTrace(this, this.constructor); } } /** * An error class used internally to wrap an error returned from a batch resource call. * Should be caught and handled internally - never exposed to the outside world. * When created, we store the `reorderResultsByValue` - this lets the ordering logic know * where in the return array to place this object. (We do this so we can add extra attributes * to the error object in a typesafe way) */ export class CaughtResourceError extends Error { cause: Error; reorderResultsByValue: string | number | null; constructor(message: string, cause: Error, reorderResultsByValue: string | number | null) { super(message); this.name = this.constructor.name; Error.captureStackTrace(this, this.constructor); this.cause = cause; this.reorderResultsByValue = reorderResultsByValue; } } /** * DataLoader options that use object-hash to calculate a cache key. This allows * the use of objects, arrays, etc. as keys. We use it in "passthrough" mode so * that it stringifies objects but doesn't waste time hashing them. */ export const cacheKeyOptions = { cacheKeyFn: (key: any) => objectHash(key, { algorithm: 'passthrough' }), }; /** * Take in all objects passed to .load(), and bucket them by the non * batch keys (i.e. `batchKey` and `propertyBatchKey`) attributes. * * We use this to chunk up the requests to the resource. * * Example: * ```js * partitionItems('bar_id', [ * { bar_id: 2, include_extra_info: true }, * { bar_id: 3, include_extra_info: false }, * { bar_id: 4, include_extra_info: true }, * ]) * ``` * * Returns: * `[ [ 0, 2 ], [ 1 ] ]` * * TODO: add generic instead of 'object' for the items array argument */ export function partitionItems( ignoreKeys: Array<string> | string, items: ReadonlyArray<object>, ): ReadonlyArray<ReadonlyArray<number>> { const groups: { [key: string]: Array<number>; } = {}; items.forEach((item, i) => { const hash = objectHash(_.omit(item, ignoreKeys), { algorithm: 'passthrough' }); groups[hash] = groups[hash] || []; groups[hash].push(i); }); return Object.values(groups); } /** * Take in all objects passed to .load(), and bucket them by the non * batch keys (i.e. `batchKey` and `propertyBatchKey`) attributes. * Return batch keys value for each partition items. * * This function is only called when we have propertyBatchKey, and it's * used to map result to the order of requests. * * Example: * ```js * getBatchKeyForPartitionItems( * 'bar_id', * ['bar_id', 'properties'], * [ * { bar_id: 2, properties: ['name'], include_extra_info: true }, * { bar_id: 3, properties: ['rating'], include_extra_info: false }, * { bar_id: 2, properties: ['rating'], include_extra_info: true }, * ]) * ``` * * Returns: * `[ [ 2, 2 ], [ 3 ] ]` * * TODO: add generic instead of 'object' for the items array argument */ export function getBatchKeysForPartitionItems( batchKey: string, ignoreKeys: Array<string>, items: ReadonlyArray<any>, ): ReadonlyArray<ReadonlyArray<any>> { const groups: { [key: string]: Array<any>; } = {}; items.forEach((item, i) => { const hash = objectHash(_.omit(item, ignoreKeys), { algorithm: 'passthrough' }); groups[hash] = groups[hash] || []; groups[hash].push(items[i][batchKey]); }); return Object.values(groups); } /** * Utility function to sort array of objects by a list of corresponding IDs * * Example: * ```js * sortByKeys({ * items: [ { id: 2, name: 'mark' }, { id: 1, name: 'ryan' } ], * keys: [1, 2], * prop: 'id', * resourcePath: ['UserService', 'getUsers'], * }) * ``` * * Returns: * ```js * [ { id: 1, name: 'ryan' }, { id: 2, name: 'mark' } ] * ``` * * Items could be null, or contain unknown errors. If this is the case, we don't * know where in the results array the error should go, since there'll be no id * field to key off of. In this case, we have to throw an error and throw away * all results :/ * * TODO: Extend this to support endpionts that use multiple keys for sorting */ export function sortByKeys<V>({ /** List of objects returned by a batch endpoint */ items, /** The IDs we originally requested from the endpoint */ keys, /** The attribute of each element in `items` that maps it to an element in `keys`. */ prop, /** Some path that indicates what resource this is being used on. Used for stack traces. */ resourcePath, }: { items: ReadonlyArray<V>; keys: ReadonlyArray<string | number>; prop: string; resourcePath: ReadonlyArray<string>; }): ReadonlyArray<V | BatchItemNotFoundError> { // Construct a Map of: Map<item key, item> const itemsMap: Map<string | number, V | BatchItemNotFoundError> = new Map(); items.forEach((item: V) => { invariant(item != null, `${errorPrefix(resourcePath)} Cannot sort list of items containing an falsey element`); if (_.isError(item)) { /* istanbul ignore if: sanity check */ if (!(item instanceof CaughtResourceError)) { throw new AggregateError([ new Error( `${errorPrefix(resourcePath)} Cannot sort list of items containg an unknown error: ${ item.message }`, ), item, ]); } const { reorderResultsByValue } = item; /* istanbul ignore if: sanity check */ if (typeof reorderResultsByValue !== 'string' && typeof reorderResultsByValue !== 'number') { throw new Error( [ `${errorPrefix(resourcePath)} Cannot sort list of items if CaughtResourceError`, 'does not contain a string or number value for reorderResultsByValue', ].join(' '), ); } itemsMap.set(String(reorderResultsByValue), item); } else { // @ts-ignore: TODO: Work how to tell typescript item[prop] exists invariant(item[prop] != null, `${errorPrefix(resourcePath)} Could not find property "${prop}" in item`); // @ts-ignore: TODO: Work how to tell typescript item[prop] exists itemsMap.set(String(item[prop]), item); } }); // Loop through the keys and for each one retrieve proper item. For missing // items, generate an BatchItemNotFoundError. (This can be caught specifically in resolvers.) return keys.map( (key) => itemsMap.get(String(key)) || new BatchItemNotFoundError( `${errorPrefix(resourcePath)} Response did not contain item with ${prop} = ${String(key)}`, ), ); } /** * Perform the inverse mapping from partitionItems on the nested results we get * back from the service. * * Example * ```js * unPartitionResults( * [ [0, 2], [1] ], * [ [ { foo: 'foo' }, { bar: 'bar' } ], [ {'baz': 'baz'} ] ], * ) * ``` * * Returns: * ``` * [ * { foo: 'foo' }, * { baz: 'baz' }, * { bar: 'bar' }, * ] */ export function unPartitionResults<T>( /** Should be a nested array of IDs, as generated by partitionItems */ requestGroups: ReadonlyArray<ReadonlyArray<number>>, /** The results back from the service, in the same shape as groups */ resultGroups: ReadonlyArray<ReadonlyArray<T | CaughtResourceError | BatchItemNotFoundError>>, ): ReadonlyArray<T | Error> { /** * e.g. with our inputs, produce: * ```js * [ * [ * { order: 0, result: { foo: 'foo' } }, * { order: 2, result: { bar: 'bar' } }, * ], * [ * { order: 1, result: { baz: 'baz' } }, * ] * ] * ``` */ const zippedGroups = requestGroups.map((ids, i) => ids.map((id, j) => ({ order: id, result: resultGroups[i][j] }))); /** * Flatten and sort the groups - e.g.: * ```js * [ * { order: 0, result: { foo: 'foo' } }, * { order: 1, result: { baz: 'baz' } }, * { order: 2, result: { bar: 'bar' } } * ] * ``` */ const sortedResults: ReadonlyArray<{ order: number; result: T | Error }> = _.sortBy(_.flatten(zippedGroups), [ 'order', ]); // Now that we have a sorted array, return the actual results! return sortedResults .map((r) => r.result) .map((result) => { if (result instanceof CaughtResourceError) { return result.cause; } else { return result; } }); } /** * Perform the inverse mapping from partitionItems on the nested results we get * back from the service. This function is only called when we have propertyBatchKey. * We currently only support one specific response contract. * * propertyBatchKey is not returned in a nested object, but spread at top level as well. * If we have 'id' as responseKey and 'properties' as propertyBatchKey, * the resultGroups should look like this: * [ * [ { id: 2, name: 'Burger King', rating: 3 } ], * [ { id: 1, name: 'In N Out', rating: 4 } ] * ], * * * IMPORTANT NOTE: The contract must have a one-to-one correspondence between the input propertyBatchKey and the output propertyBatchKey. * i.e. if we have property: 'name' in the request, the response must have 'name' in it, and no extra data associated with it. * * Example * Request args: * [ * { bar_id: 2, properties: ['name'], include_extra_info: true }, * { bar_id: 1, properties: ['rating'], include_extra_info: false }, * { bar_id: 2, properties: ['rating'], include_extra_info: true }, * ] * * ```js * unPartitionResultsByBatchKeyPartition( * newKey = 'bar_id', * propertyBatchKey = 'properties', * responseKey = 'id' * batchKeyPartition = [ [2, 2], [1] ], * propertyBatchKeyPartion = [ [['name'], ['rating']], [['rating']] ], * requestGroups = [ [0, 2], [1] ], * resultGroups = [ * [ { id: 2, name: 'Burger King', rating: 3 } ], * [ { id: 1, name: 'In N Out', rating: 4 } ] * ], * ) * ``` * * Returns: * ``` * [ * { id: 2, name: 'Burger King' }, * { id: 1, rating: 4 }, * { id: 2, rating: 3 }, * ] */ export function unPartitionResultsByBatchKeyPartition<T extends Record<string, any>>( newKey: string, propertyBatchKey: string, responseKey: string, batchKeyPartition: ReadonlyArray<ReadonlyArray<any>>, propertyBatchKeyPartion: ReadonlyArray<ReadonlyArray<any>>, /** Should be a nested array of IDs, as generated by partitionItems */ requestGroups: ReadonlyArray<ReadonlyArray<number>>, /** The results back from the service, in the same shape as groups */ resultGroups: ReadonlyArray<ReadonlyArray<T | CaughtResourceError>>, ): ReadonlyArray<T | Error> { /** * e.g. with our inputs, produce: * ```js * [ * [ * { order: 0, result: { id: 2, name: 'Burger King' }, * { order: 2, result: { id: 2, rating: 3 } }, * ], * [ * { order: 1, result: { id: 1, rating: 4 } }, * ] * ] * ``` */ const zippedGroups: ReadonlyArray<ReadonlyArray<{ order: number; result: T | Error }>> = requestGroups.map( (ids, i) => { return ids.map((id, j) => { let result = null; for (const resultElement of Object.values(resultGroups)[i]) { // There's error in the result we should return if (resultElement instanceof CaughtResourceError) { result = resultElement; break; } // Find the response that matches the requested batchKey if (resultElement[responseKey] === batchKeyPartition[i][j]) { // Only responseKey and the requested properties will be in the final result. result = _.pick(resultElement, [responseKey, ...propertyBatchKeyPartion[i][j]]); break; } } // If requested property doesn't exist in resultElement, we should throw BatchItemNotFoundError error. if (result === null) { return { order: id, result: new BatchItemNotFoundError( [ `Could not find ${responseKey} = ${batchKeyPartition[i][j]} in the response dict.`, `Or your endpoint does not follow the contract we support.`, `Please read https://github.com/Yelp/dataloader-codegen/blob/master/API_DOCS.md.`, ].join(' '), ), }; } else { return { order: id, result }; } }); }, ); /** * Flatten and sort the groups - e.g.: * ```js * [ * { order: 0, result: { id: 2, name: 'Burger King' } }, * { order: 1, result: { id: 1, rating: 4 } }, * { order: 2, result: { id: 2, rating: 3 } } * ] * ``` */ const sortedResults: ReadonlyArray<{ order: number; result: T | Error }> = _.sortBy(_.flatten(zippedGroups), [ 'order', ]); // Now that we have a sorted array, return the actual results! return sortedResults .map((r) => r.result) .map((result) => { if (result instanceof CaughtResourceError) { return result.cause; } else { return result; } }); } /** * Turn a dictionary of results into an ordered list * * Example * ```js * resultsDictToList( * { * '3': { foo: '!' }, * '1': { foo: 'hello' }, * '2': { foo: 'world' }, * }, * [1, 2, 3], * resourcePath: ['FooService', 'getFoos'], * ) * ``` * * Returns: * ``` * [ * { foo: 'hello' }, * { foo: 'world' }, * { foo: '!' }, * ] */ export function resultsDictToList<V>( /** * A dictionary of results. Object keys that were numbers will get turned into strings by JavaScript. * @see https://stackoverflow.com/a/3633390 */ response: { [key: string]: V }, /** The IDs we originally requested from the endpoint */ keys: ReadonlyArray<string | number>, /** Some path that indicates what resource this is being used on. Used for stack traces. */ resourcePath: ReadonlyArray<string>, ): ReadonlyArray<V | Error> { return keys.map( (key) => response[String(key)] || new BatchItemNotFoundError( `${errorPrefix(resourcePath)} Could not find key = "${String(key)}" in the response dict.`, ), ); } /** * If no errorHandler option is passed to dataloader-codegen, we will use this by default. */ export async function defaultErrorHandler(resourcePath: ReadonlyArray<string>, error: any): Promise<Error> { // The error handler must return an error object. Turn all rejected strings/objects into errors. return ensureError(error); }
the_stack
import {assert} from '../platform/assert-web.js'; import {ArcId, IdGenerator, Id} from './id.js'; import {Manifest} from './manifest.js'; import {Recipe, Particle, Handle, Slot, effectiveTypeForHandle} from './recipe/lib-recipe.js'; import {SlotComposer} from './slot-composer.js'; import {Dictionary, Mutex} from '../utils/lib-utils.js'; import {newRecipe} from './recipe/lib-recipe.js'; import {CapabilitiesResolver} from './capabilities-resolver.js'; import {VolatileStorageKey} from './storage/drivers/volatile.js'; import {StorageKey} from './storage/storage-key.js'; import {PecFactory} from './particle-execution-context.js'; import {ArcInspectorFactory} from './arc-inspector.js'; import {AbstractSlotObserver} from './slot-observer.js'; import {Modality} from './arcs-types/modality.js'; import {Type, EntityType, ReferenceType, InterfaceType, SingletonType} from '../types/lib-types.js'; import {Capabilities} from './capabilities.js'; import {StoreInfo} from './storage/store-info.js'; import {Exists} from './storage/drivers/driver.js'; import {ReferenceModeStorageKey} from './storage/reference-mode-storage-key.js'; import {CollectionType, TupleType, TypeVariable, InterfaceInfo} from '../types/lib-types.js'; export type StorageKeyPrefixer = (arcId: ArcId) => StorageKey; export type NewArcInfoOptions = Readonly<{ arcName?: string; arcId?: ArcId; idGenerator?: IdGenerator; outerArcId?: ArcId; isSpeculative?: boolean; }>; export type RunArcOptions = Readonly<{ storageKeyPrefix?: StorageKeyPrefixer; pecFactories?: PecFactory[]; isSpeculative?: boolean; innerArc?: boolean; stub?: boolean; listenerClasses?: ArcInspectorFactory[]; inspectorFactory?: ArcInspectorFactory; modality?: Modality; slotObserver?: AbstractSlotObserver; }>; export type StartArcOptions = NewArcInfoOptions & RunArcOptions & {planName?: string}; export type PlanPartition = Readonly<{ particles: Particle[]; handles: Handle[]; reinstantiate?: boolean; arcInfo: ArcInfo; arcOptions: RunArcOptions; arcHostId: string; modality?: Modality; }>; export type DeserializeArcOptions = Readonly<{ serialization: string; pecFactories?: PecFactory[]; slotComposer?: SlotComposer; fileName: string; inspectorFactory?: ArcInspectorFactory; }>; export type ArcInfoOptions = Readonly<{ id: ArcId; context: Manifest; capabilitiesResolver: CapabilitiesResolver; idGenerator?: IdGenerator; outerArcId?: ArcId; isSpeculative?: boolean; slotContainers?: {}[]; // This should be avoided, if/when all ArcInfo are created via Allocator. }>; export class ArcInfo { public readonly id: ArcId; public readonly context: Manifest; public readonly capabilitiesResolver: CapabilitiesResolver; public readonly idGenerator: IdGenerator; public readonly isSpeculative: boolean; get isInnerArc(): boolean { return this.outerArcId !== null; } public readonly outerArcId: ArcId|null; public readonly partitions: PlanPartition[] = []; readonly storeInfoById: Dictionary<StoreInfo<Type>> = {}; public readonly storeTagsById: Dictionary<Set<string>> = {}; readonly storeDescriptions = new Map<StoreInfo<Type>, string>(); activeRecipe: Recipe = newRecipe(); readonly recipeDeltas: {handles: Handle[], particles: Particle[], slots: Slot[], patterns: string[]}[] = []; private readonly instantiateMutex = new Mutex(); readonly innerArcsByParticle: Map<Particle, ArcInfo[]> = new Map(); readonly slotContainers: {}[]; // TODO(mmandlis): declare SlotContainerInfo type. constructor(opts: ArcInfoOptions) { this.id = opts.id; this.context = opts.context; this.capabilitiesResolver = opts.capabilitiesResolver; this.idGenerator = opts.idGenerator || IdGenerator.newSession(); this.outerArcId = opts.outerArcId || null; this.isSpeculative = opts.isSpeculative || false; this.slotContainers = opts.slotContainers || []; } generateID(component: string = ''): Id { return this.idGenerator.newChildId(this.id, component); } // TODO(shanestephens): Once we stop auto-wrapping in singleton types below, convert this to return a well-typed store. async createStoreInfo<T extends Type>(type: T, opts?: {name?: string, id?: string, storageKey?: StorageKey, capabilities?: Capabilities, exists?: Exists, tags?: string[]}): Promise<StoreInfo<T>> { opts = opts || {}; let id = opts.id; if (id == undefined) { id = this.generateID().toString(); } const storageKey = opts.storageKey || // Consider passing `tags` to capabilities resolver. await this.capabilitiesResolver.createStorageKey(opts.capabilities || Capabilities.create(), type, id); const storeInfo = new StoreInfo({id, type, name: opts.name, storageKey, exists: opts.exists || Exists.MayExist}); await this.registerStore(storeInfo, opts.tags, /* registerReferenceMode= */ true); this.addHandleToActiveRecipe(storeInfo); return storeInfo; } get stores(): StoreInfo<Type>[] { return Object.values(this.storeInfoById); } findStoreById(id: string): StoreInfo<Type> { return this.storeInfoById[id]; } findStoreInfoByStorageKey(storageKey: StorageKey): StoreInfo<Type> { return Object.values(this.storeInfoById).find( storeInfo => storeInfo.storageKey.toString() === storageKey.toString()); } findStoresByType<T extends Type>(type: T, options?: {tags: string[]}): StoreInfo<T>[] { const typeKey = ArcInfo._typeToKey(type); let stores = Object.values(this.storeInfoById).filter(handle => { if (typeKey) { const handleKey = ArcInfo._typeToKey(handle.type); if (typeKey === handleKey) { return true; } } else { if (type instanceof TypeVariable && !type.isResolved() && handle.type instanceof EntityType || handle.type instanceof SingletonType) { return true; } // elementType will only be non-null if type is either Collection or BigCollection; the tag // comparison ensures that handle.type is the same sort of collection. const elementType = type.getContainedType(); if (elementType && elementType instanceof TypeVariable && !elementType.isResolved() && type.tag === handle.type.tag) { return true; } } return false; }); if (options && options.tags && options.tags.length > 0) { stores = stores.filter(store => options.tags.filter(tag => !this.storeTagsById[store.id].has(tag)).length === 0); } // Quick check that a new handle can fulfill the type contract. // Rewrite of this method tracked by https://github.com/PolymerLabs/arcs/issues/1636. return stores.filter(s => { const isInterface = s.type.getContainedType() ? s.type.getContainedType() instanceof InterfaceType : s.type instanceof InterfaceType; return !!effectiveTypeForHandle(type, [{type: s.type, direction: isInterface ? 'hosts' : 'reads writes'}]); }) as StoreInfo<T>[]; } // Convert a type to a normalized key that we can use for // equality testing. // // TODO: we should be testing the schemas for compatiblity instead of using just the name. // TODO: now that this is only used to implement findStoresByType we can probably replace // the check there with a type system equality check or similar. static _typeToKey(type: Type): string | InterfaceInfo | null { if (type.isSingleton) { type = type.getContainedType(); } const elementType = type.getContainedType(); if (elementType) { const key = this._typeToKey(elementType); if (key) { return `list:${key}`; } } else if (type instanceof EntityType) { return type.entitySchema.name; } else if (type instanceof InterfaceType) { // TODO we need to fix this too, otherwise all handles of interface type will // be of the 'same type' when searching by type. return type.interfaceInfo; } else if (type instanceof TypeVariable && type.isResolved()) { return ArcInfo._typeToKey(type.resolvedType()); } return null; } async registerStore(storeInfo: StoreInfo<Type>, tags?: string[], registerReferenceMode?: boolean): Promise<void> { assert(!this.storeInfoById[storeInfo.id], `Store already registered '${storeInfo.id}'`); const type = storeInfo.type; if (type instanceof TupleType) { throw new Error('Tuple type is not yet supported'); } // Catch legacy cases that expected us to wrap entity types in a singleton. if (type.isEntity || type.isInterface || type.isReference) { throw new Error('unwrapped type provided to arc.createStore'); } tags = tags || []; tags = Array.isArray(tags) ? tags : [tags]; if (!(storeInfo.type.handleConstructor())) { throw new Error(`Type not supported by storage: '${storeInfo.type.tag}'`); } this.storeInfoById[storeInfo.id] = storeInfo; this.storeTagsById[storeInfo.id] = new Set(tags); this.context.registerStore(storeInfo, tags); if (registerReferenceMode) { const type = storeInfo.type; if (storeInfo.storageKey instanceof ReferenceModeStorageKey) { const refContainedType = new ReferenceType(type.getContainedType()); const refType = type.isSingleton ? new SingletonType(refContainedType) : new CollectionType(refContainedType); await this.createStoreInfo(refType, { name: storeInfo.name ? storeInfo.name + '_referenceContainer' : null, storageKey: storeInfo.storageKey.storageKey }); await this.createStoreInfo(new CollectionType(type.getContainedType()), { name: storeInfo.name ? storeInfo.name + '_backingStore' : null, storageKey: storeInfo.storageKey.backingKey }); } } } tagStore(store: StoreInfo<Type>, tags: Set<string> = new Set()): void { assert(this.storeInfoById[store.id] && this.storeTagsById[store.id], `Store not registered '${store.id}'`); tags.forEach(tag => this.storeTagsById[store.id].add(tag)); } addHandleToActiveRecipe(storeInfo: StoreInfo<Type>) { const handle = this.activeRecipe.newHandle(); handle.mapToStorage(storeInfo); handle.fate = 'use'; // TODO(shans): is this the right thing to do? This seems not to be the right thing to do! handle['_type'] = handle.mappedType; } async instantiate(recipe: Recipe): Promise<{particles: Particle[], handles: Handle[]}> { const release = await this.instantiateMutex.acquire(); let result: {particles: Particle[], handles: Handle[]} = {particles: [], handles: []}; try { result = await this.mergeIntoActiveRecipe(recipe); } finally { release(); } return result; } async mergeIntoActiveRecipe(recipe: Recipe) { const {handles, particles, slots} = recipe.mergeInto(this.activeRecipe); // handles represents only the new handles; it doesn't include 'use' handles that have // resolved against the existing recipe. this.recipeDeltas.push({particles, handles, slots, patterns: recipe.patterns}); // TODO(mmandlis, jopra): Get rid of populating the missing local slot & slandle IDs here, // it should be done at planning stage. slots.forEach(slot => slot.id = slot.id || this.generateID('slot').toString()); handles.forEach(handle => { if (handle.toSlot()) { handle.id = handle.id || this.generateID('slandle').toString(); } }); for (const recipeHandle of handles) { assert(recipeHandle.immediateValue || ['use', 'map'].includes(recipeHandle.fate), `Unexpected fate: ${recipeHandle.fate}`); const fate = recipeHandle.originalFate && recipeHandle.originalFate !== '?' ? recipeHandle.originalFate : recipeHandle.fate; if (fate === 'use') { throw new Error(`store '${recipeHandle.id}' with "use" fate was not found in recipe`); } if (['copy', 'map', 'create'].includes(fate)) { let type = recipeHandle.type; if (recipeHandle.fate === 'create') { assert(type.maybeResolve(), `Can't assign resolved type to ${type}`); } type = type.resolvedType(); assert(type.isResolved(), `Can't create handle for unresolved type ${type}`); assert(recipeHandle.id); const storageKey = recipeHandle.immediateValue ? new VolatileStorageKey(this.id, '').childKeyForHandle(recipeHandle.id) : recipeHandle.storageKey; assert(storageKey, `Missing storage for recipe handle ${recipeHandle.id}`); // TODO(shanestephens): Remove this once singleton types are expressed directly in recipes. if (type instanceof EntityType || type instanceof ReferenceType || type instanceof InterfaceType) { type = new SingletonType(type); } const exists = fate === 'map' ? Exists.ShouldExist : Exists.MayExist; const newStore = new StoreInfo({storageKey, type, exists, id: recipeHandle.id}); await this.registerStore(newStore, recipeHandle.tags, /* registerReferenceMode= */ fate !== 'map'); if (fate === 'copy' && !recipeHandle.immediateValue) { const copiedStoreInfo = this.context.findStoreById(recipeHandle.originalId); newStore.name = copiedStoreInfo.name && `Copy of ${copiedStoreInfo.name}`; this.tagStore(newStore, this.context.findStoreTags(copiedStoreInfo)); const copiedStoreRef = this.context.findStoreById(recipeHandle.originalId); const copiedStoreDesc = this.getStoreDescription(copiedStoreRef); if (copiedStoreDesc) { this.storeDescriptions.set(newStore, copiedStoreDesc); } } } } return {handles, particles, slots}; } getStoreDescription(storeInfo: StoreInfo<Type>): string { return this.storeDescriptions.get(storeInfo) || storeInfo.description; } getVersionByStore({includeArc=true, includeContext=false}) { const versionById = {}; if (includeArc) { for (const id of Object.keys(this.storeInfoById)) { versionById[id] = this.storeInfoById[id].versionToken; } } if (includeContext) { this.context.allStores.forEach(handle => versionById[handle.id] = handle.versionToken); } return versionById; } findInnerArcs(particle: Particle): ArcInfo[] { return this.innerArcsByParticle.get(particle) || []; } get innerArcs(): ArcInfo[] { return ([] as ArcInfo[]).concat( ...this.innerArcsByParticle.values()); } // This arc and all its descendants. // *Does* include inner arcs of this arc's inner arcs. get allDescendingArcs(): ArcInfo[] { return [this as ArcInfo].concat(...this.innerArcs.map(arc => arc.allDescendingArcs)); } addInnerArc(particle: Particle, innerArcInfo: ArcInfo) { if (!this.innerArcsByParticle.has(particle)) { this.innerArcsByParticle.set(particle, []); } this.innerArcsByParticle.get(particle).push(innerArcInfo); } addSlotContainers(containers: {}[]) { for (const container of containers) { // Note: consider asserting, if trying to add duplicate slot container, // once SingletonAllocator is deprecated. if (!this.slotContainers.find(c => c['name'] === container['name'])) { this.slotContainers.push(container); } } } get modality(): Modality { const modalities = this.partitions.map(p => p.modality).filter(m => !!m); // TODO(sjmiles): Modality rules are unclear. Seems to me the Arc should declare it's own modality // but many tests fail without these conditionals. Note that a Modality can represent a set of modalities. if (!this.activeRecipe.isEmpty()) { modalities.push(this.activeRecipe.modality); } if (modalities.length === 0) { modalities.push(...this.context.allRecipes.map(recipe => recipe.modality)); } return Modality.union(modalities); } }
the_stack
// clang-format off import 'chrome://settings/lazy_load.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; // <if expr="not chromeos and not lacros"> import {listenOnce} from 'chrome://resources/js/util.m.js'; // </if> import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; // <if expr="not chromeos and not lacros"> import {CrCheckboxElement} from 'chrome://settings/lazy_load.js'; // </if> // <if expr="not lacros"> import {loadTimeData} from 'chrome://settings/settings.js'; // </if> import {pageVisibility, ProfileInfoBrowserProxyImpl, Router, routes, SettingsPeoplePageElement, StatusAction, SyncBrowserProxyImpl} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; // <if expr="not chromeos and not lacros"> import {assertLT} from 'chrome://webui-test/chai_assert.js'; import {flushTasks, waitBeforeNextRender} from 'chrome://webui-test/test_util.js'; // </if> import {simulateSyncStatus} from './sync_test_util.js'; // <if expr="not chromeos and not lacros"> import {simulateStoredAccounts} from './sync_test_util.js'; // </if> import {TestProfileInfoBrowserProxy} from './test_profile_info_browser_proxy.js'; import {TestSyncBrowserProxy} from './test_sync_browser_proxy.js'; // clang-format on let peoplePage: SettingsPeoplePageElement; let profileInfoBrowserProxy: TestProfileInfoBrowserProxy; let syncBrowserProxy: TestSyncBrowserProxy; suite('ProfileInfoTests', function() { suiteSetup(function() { // <if expr="chromeos"> loadTimeData.overrideValues({ // Account Manager is tested in people_page_test_cros.js isAccountManagerEnabled: false, }); // </if> }); setup(async function() { profileInfoBrowserProxy = new TestProfileInfoBrowserProxy(); ProfileInfoBrowserProxyImpl.setInstance(profileInfoBrowserProxy); syncBrowserProxy = new TestSyncBrowserProxy(); SyncBrowserProxyImpl.setInstance(syncBrowserProxy); document.body.innerHTML = ''; peoplePage = document.createElement('settings-people-page'); peoplePage.pageVisibility = pageVisibility; document.body.appendChild(peoplePage); await syncBrowserProxy.whenCalled('getSyncStatus'); await profileInfoBrowserProxy.whenCalled('getProfileInfo'); flush(); }); teardown(function() { peoplePage.remove(); }); test('GetProfileInfo', function() { assertEquals( profileInfoBrowserProxy.fakeProfileInfo.name, peoplePage.shadowRoot!.querySelector<HTMLElement>( '#profile-name')!.textContent!.trim()); const bg = peoplePage.shadowRoot!.querySelector<HTMLElement>( '#profile-icon')!.style.backgroundImage; assertTrue(bg.includes(profileInfoBrowserProxy.fakeProfileInfo.iconUrl)); const iconDataUrl = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEA' + 'LAAAAAABAAEAAAICTAEAOw=='; webUIListenerCallback( 'profile-info-changed', {name: 'pushedName', iconUrl: iconDataUrl}); flush(); assertEquals( 'pushedName', peoplePage.shadowRoot!.querySelector<HTMLElement>( '#profile-name')!.textContent!.trim()); const newBg = peoplePage.shadowRoot!.querySelector<HTMLElement>( '#profile-icon')!.style.backgroundImage; assertTrue(newBg.includes(iconDataUrl)); }); }); // <if expr="not chromeos and not lacros"> suite('SigninDisallowedTests', function() { setup(function() { loadTimeData.overrideValues({signinAllowed: false}); syncBrowserProxy = new TestSyncBrowserProxy(); SyncBrowserProxyImpl.setInstance(syncBrowserProxy); profileInfoBrowserProxy = new TestProfileInfoBrowserProxy(); ProfileInfoBrowserProxyImpl.setInstance(profileInfoBrowserProxy); document.body.innerHTML = ''; peoplePage = document.createElement('settings-people-page'); peoplePage.pageVisibility = pageVisibility; document.body.appendChild(peoplePage); }); teardown(function() { peoplePage.remove(); }); test('ShowCorrectRows', async function() { await syncBrowserProxy.whenCalled('getSyncStatus'); flush(); // The correct /manageProfile link row is shown. assertFalse(!!peoplePage.shadowRoot!.querySelector('#edit-profile')); assertTrue(!!peoplePage.shadowRoot!.querySelector('#profile-row')); // Control element doesn't exist when policy forbids sync. simulateSyncStatus({ signedIn: false, syncSystemEnabled: true, statusAction: StatusAction.NO_ACTION, }); assertFalse(!!peoplePage.shadowRoot!.querySelector( 'settings-sync-account-control')); }); }); suite('SyncStatusTests', function() { setup(async function() { loadTimeData.overrideValues({signinAllowed: true}); syncBrowserProxy = new TestSyncBrowserProxy(); SyncBrowserProxyImpl.setInstance(syncBrowserProxy); profileInfoBrowserProxy = new TestProfileInfoBrowserProxy(); ProfileInfoBrowserProxyImpl.setInstance(profileInfoBrowserProxy); document.body.innerHTML = ''; peoplePage = document.createElement('settings-people-page'); peoplePage.pageVisibility = pageVisibility; document.body.appendChild(peoplePage); }); teardown(function() { peoplePage.remove(); }); test('Toast', function() { assertFalse(peoplePage.$.toast.open); webUIListenerCallback('sync-settings-saved'); assertTrue(peoplePage.$.toast.open); }); test('ShowCorrectRows', async function() { await syncBrowserProxy.whenCalled('getSyncStatus'); simulateSyncStatus({ syncSystemEnabled: true, statusAction: StatusAction.NO_ACTION, }); flush(); // The correct /manageProfile link row is shown. assertTrue(!!peoplePage.shadowRoot!.querySelector('#edit-profile')); assertFalse(!!peoplePage.shadowRoot!.querySelector('#profile-row')); simulateSyncStatus({ signedIn: false, syncSystemEnabled: true, statusAction: StatusAction.NO_ACTION, }); // The control element should exist when policy allows. const accountControl = peoplePage.shadowRoot!.querySelector('settings-sync-account-control')!; assertTrue(window.getComputedStyle(accountControl)['display'] !== 'none'); // Control element doesn't exist when policy forbids sync. simulateSyncStatus({ syncSystemEnabled: false, statusAction: StatusAction.NO_ACTION, }); assertEquals('none', window.getComputedStyle(accountControl)['display']); const manageGoogleAccount = peoplePage.shadowRoot!.querySelector('#manage-google-account')!; // Do not show Google Account when stored accounts or sync status // could not be retrieved. simulateStoredAccounts(undefined); simulateSyncStatus(undefined); assertEquals( 'none', window.getComputedStyle(manageGoogleAccount)['display']); simulateStoredAccounts([]); simulateSyncStatus(undefined); assertEquals( 'none', window.getComputedStyle(manageGoogleAccount)['display']); simulateStoredAccounts(undefined); simulateSyncStatus({ statusAction: StatusAction.NO_ACTION, }); assertEquals( 'none', window.getComputedStyle(manageGoogleAccount)['display']); simulateStoredAccounts([]); simulateSyncStatus({ statusAction: StatusAction.NO_ACTION, }); assertEquals( 'none', window.getComputedStyle(manageGoogleAccount)['display']); // A stored account with sync off but no error should result in the // Google Account being shown. simulateStoredAccounts([{email: 'foo@foo.com'}]); simulateSyncStatus({ signedIn: false, hasError: false, statusAction: StatusAction.NO_ACTION, }); assertTrue( window.getComputedStyle(manageGoogleAccount)['display'] !== 'none'); // A stored account with sync off and error should not result in the // Google Account being shown. simulateStoredAccounts([{email: 'foo@foo.com'}]); simulateSyncStatus({ signedIn: false, hasError: true, statusAction: StatusAction.NO_ACTION, }); assertEquals( 'none', window.getComputedStyle(manageGoogleAccount)['display']); // A stored account with sync on but no error should result in the // Google Account being shown. simulateStoredAccounts([{email: 'foo@foo.com'}]); simulateSyncStatus({ signedIn: true, hasError: false, statusAction: StatusAction.NO_ACTION, }); assertTrue( window.getComputedStyle(manageGoogleAccount)['display'] !== 'none'); // A stored account with sync on but with error should not result in // the Google Account being shown. simulateStoredAccounts([{email: 'foo@foo.com'}]); simulateSyncStatus({ signedIn: true, hasError: true, statusAction: StatusAction.NO_ACTION, }); assertEquals( 'none', window.getComputedStyle(manageGoogleAccount)['display']); }); test('SignOutNavigationNormalProfile', async function() { // Navigate to chrome://settings/signOut Router.getInstance().navigateTo(routes.SIGN_OUT); await flushTasks(); const signoutDialog = peoplePage.shadowRoot!.querySelector('settings-signout-dialog')!; assertTrue(signoutDialog.$.dialog.open); const deleteProfileCheckbox = signoutDialog.shadowRoot!.querySelector<CrCheckboxElement>( '#deleteProfile'); assertTrue(!!deleteProfileCheckbox); assertFalse(deleteProfileCheckbox!.hidden); assertLT(0, deleteProfileCheckbox!.clientHeight); const disconnectConfirm = signoutDialog.$.disconnectConfirm; assertTrue(!!disconnectConfirm); assertFalse(disconnectConfirm.hidden); disconnectConfirm.click(); await new Promise(function(resolve) { listenOnce(window, 'popstate', resolve); }); const deleteProfile = await syncBrowserProxy.whenCalled('signOut'); assertFalse(deleteProfile); }); test('SignOutDialogManagedProfile', async function() { let accountControl = null; await syncBrowserProxy.whenCalled('getSyncStatus'); simulateSyncStatus({ signedIn: true, domain: 'example.com', syncSystemEnabled: true, statusAction: StatusAction.NO_ACTION, }); assertFalse(!!peoplePage.shadowRoot!.querySelector('#dialog')); accountControl = peoplePage.shadowRoot!.querySelector('settings-sync-account-control')!; await waitBeforeNextRender(accountControl); const turnOffButton = accountControl.shadowRoot!.querySelector<HTMLElement>('#turn-off')!; turnOffButton.click(); flush(); await flushTasks(); const signoutDialog = peoplePage.shadowRoot!.querySelector('settings-signout-dialog')!; assertTrue(signoutDialog.$.dialog.open); assertFalse(!!signoutDialog.shadowRoot!.querySelector('#deleteProfile')); const disconnectManagedProfileConfirm = signoutDialog.shadowRoot!.querySelector<HTMLElement>( '#disconnectManagedProfileConfirm'); assertTrue(!!disconnectManagedProfileConfirm); assertFalse(disconnectManagedProfileConfirm!.hidden); syncBrowserProxy.resetResolver('signOut'); disconnectManagedProfileConfirm!.click(); await new Promise(function(resolve) { listenOnce(window, 'popstate', resolve); }); const deleteProfile = await syncBrowserProxy.whenCalled('signOut'); assertTrue(deleteProfile); }); test('getProfileStatsCount', async function() { // Navigate to chrome://settings/signOut Router.getInstance().navigateTo(routes.SIGN_OUT); await flushTasks(); const signoutDialog = peoplePage.shadowRoot!.querySelector('settings-signout-dialog')!; assertTrue(signoutDialog.$.dialog.open); // Assert the warning message is as expected. const warningMessage = signoutDialog.shadowRoot!.querySelector<HTMLElement>( '.delete-profile-warning')!; webUIListenerCallback('profile-stats-count-ready', 0); assertEquals( loadTimeData.getStringF( 'deleteProfileWarningWithoutCounts', 'fakeUsername'), warningMessage.textContent!.trim()); webUIListenerCallback('profile-stats-count-ready', 1); assertEquals( loadTimeData.getStringF( 'deleteProfileWarningWithCountsSingular', 'fakeUsername'), warningMessage.textContent!.trim()); webUIListenerCallback('profile-stats-count-ready', 2); assertEquals( loadTimeData.getStringF( 'deleteProfileWarningWithCountsPlural', 2, 'fakeUsername'), warningMessage.textContent!.trim()); // Close the disconnect dialog. signoutDialog.$.disconnectConfirm.click(); await new Promise(function(resolve) { listenOnce(window, 'popstate', resolve); }); }); test('NavigateDirectlyToSignOutURL', async function() { // Navigate to chrome://settings/signOut Router.getInstance().navigateTo(routes.SIGN_OUT); await flushTasks(); assertTrue( peoplePage.shadowRoot!.querySelector( 'settings-signout-dialog')!.$.dialog.open); await profileInfoBrowserProxy.whenCalled('getProfileStatsCount'); // 'getProfileStatsCount' can be the first message sent to the // handler if the user navigates directly to // chrome://settings/signOut. if so, it should not cause a crash. new ProfileInfoBrowserProxyImpl().getProfileStatsCount(); // Close the disconnect dialog. peoplePage.shadowRoot!.querySelector('settings-signout-dialog')!.$ .disconnectConfirm.click(); await new Promise(function(resolve) { listenOnce(window, 'popstate', resolve); }); }); test('Signout dialog suppressed when not signed in', async function() { await syncBrowserProxy.whenCalled('getSyncStatus'); Router.getInstance().navigateTo(routes.SIGN_OUT); await flushTasks(); assertTrue( peoplePage.shadowRoot!.querySelector( 'settings-signout-dialog')!.$.dialog.open); simulateSyncStatus({ signedIn: false, statusAction: StatusAction.NO_ACTION, }); await new Promise(function(resolve) { listenOnce(window, 'popstate', resolve); }); Router.getInstance().navigateTo(routes.SIGN_OUT); await new Promise(function(resolve) { listenOnce(window, 'popstate', resolve); }); }); }); // </if> suite('SyncSettings', function() { setup(async function() { syncBrowserProxy = new TestSyncBrowserProxy(); SyncBrowserProxyImpl.setInstance(syncBrowserProxy); profileInfoBrowserProxy = new TestProfileInfoBrowserProxy(); ProfileInfoBrowserProxyImpl.setInstance(profileInfoBrowserProxy); document.body.innerHTML = ''; peoplePage = document.createElement('settings-people-page'); peoplePage.pageVisibility = pageVisibility; document.body.appendChild(peoplePage); await syncBrowserProxy.whenCalled('getSyncStatus'); flush(); }); teardown(function() { peoplePage.remove(); }); test('ShowCorrectSyncRow', function() { assertTrue(!!peoplePage.shadowRoot!.querySelector('#sync-setup')); assertFalse(!!peoplePage.shadowRoot!.querySelector('#sync-status')); // Make sures the subpage opens even when logged out or has errors. simulateSyncStatus({ signedIn: false, statusAction: StatusAction.REAUTHENTICATE, }); peoplePage.shadowRoot!.querySelector<HTMLElement>('#sync-setup')!.click(); flush(); assertEquals(Router.getInstance().getCurrentRoute(), routes.SYNC); }); });
the_stack
import localVarRequest from 'request'; export * from './accountingAppSettings'; export * from './accountingAppUrls'; export * from './accountingExtensionCustomer'; export * from './accountingExtensionInvoice'; export * from './accountingExtensionTerm'; export * from './accountingFeatures'; export * from './actionResponse'; export * from './address'; export * from './createInvoiceFeature'; export * from './createInvoiceSubFeatures'; export * from './createUserAccountRequestExternal'; export * from './customerSearchResponseExternal'; export * from './errorDetail'; export * from './exchangeRateResponse'; export * from './importInvoiceFeature'; export * from './invoiceCreatePaymentRequest'; export * from './invoicePdfResponse'; export * from './invoiceReadResponse'; export * from './invoiceSearchResponse'; export * from './invoiceUpdateRequest'; export * from './invoiceUpdateResponse'; export * from './invoicesResponseExternal'; export * from './modelError'; export * from './objectSyncFeature'; export * from './product'; export * from './productSearchResponse'; export * from './resultIdAccountingResponse'; export * from './syncContactsRequest'; export * from './syncProductsRequest'; export * from './tax'; export * from './taxSearchResponse'; export * from './taxType'; export * from './termsResponse'; export * from './unitPrice'; export * from './updatedContact'; export * from './updatedProduct'; import * as fs from 'fs'; export interface RequestDetailedFile { value: Buffer; options?: { filename?: string; contentType?: string; } } export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; import { AccountingAppSettings } from './accountingAppSettings'; import { AccountingAppUrls } from './accountingAppUrls'; import { AccountingExtensionCustomer } from './accountingExtensionCustomer'; import { AccountingExtensionInvoice } from './accountingExtensionInvoice'; import { AccountingExtensionTerm } from './accountingExtensionTerm'; import { AccountingFeatures } from './accountingFeatures'; import { ActionResponse } from './actionResponse'; import { Address } from './address'; import { CreateInvoiceFeature } from './createInvoiceFeature'; import { CreateInvoiceSubFeatures } from './createInvoiceSubFeatures'; import { CreateUserAccountRequestExternal } from './createUserAccountRequestExternal'; import { CustomerSearchResponseExternal } from './customerSearchResponseExternal'; import { ErrorDetail } from './errorDetail'; import { ExchangeRateResponse } from './exchangeRateResponse'; import { ImportInvoiceFeature } from './importInvoiceFeature'; import { InvoiceCreatePaymentRequest } from './invoiceCreatePaymentRequest'; import { InvoicePdfResponse } from './invoicePdfResponse'; import { InvoiceReadResponse } from './invoiceReadResponse'; import { InvoiceSearchResponse } from './invoiceSearchResponse'; import { InvoiceUpdateRequest } from './invoiceUpdateRequest'; import { InvoiceUpdateResponse } from './invoiceUpdateResponse'; import { InvoicesResponseExternal } from './invoicesResponseExternal'; import { ModelError } from './modelError'; import { ObjectSyncFeature } from './objectSyncFeature'; import { Product } from './product'; import { ProductSearchResponse } from './productSearchResponse'; import { ResultIdAccountingResponse } from './resultIdAccountingResponse'; import { SyncContactsRequest } from './syncContactsRequest'; import { SyncProductsRequest } from './syncProductsRequest'; import { Tax } from './tax'; import { TaxSearchResponse } from './taxSearchResponse'; import { TaxType } from './taxType'; import { TermsResponse } from './termsResponse'; import { UnitPrice } from './unitPrice'; import { UpdatedContact } from './updatedContact'; import { UpdatedProduct } from './updatedProduct'; /* tslint:disable:no-unused-variable */ let primitives = [ "string", "boolean", "double", "integer", "long", "float", "number", "any" ]; let enumsMap: {[index: string]: any} = { "AccountingExtensionInvoice.StatusEnum": AccountingExtensionInvoice.StatusEnum, "ActionResponse.StatusEnum": ActionResponse.StatusEnum, "CustomerSearchResponseExternal.ResultEnum": CustomerSearchResponseExternal.ResultEnum, "ExchangeRateResponse.ResultEnum": ExchangeRateResponse.ResultEnum, "InvoicePdfResponse.ResultEnum": InvoicePdfResponse.ResultEnum, "InvoiceReadResponse.InvoiceStatusEnum": InvoiceReadResponse.InvoiceStatusEnum, "InvoiceSearchResponse.ResultEnum": InvoiceSearchResponse.ResultEnum, "InvoiceUpdateResponse.InvoiceStatusEnum": InvoiceUpdateResponse.InvoiceStatusEnum, "InvoicesResponseExternal.ResultEnum": InvoicesResponseExternal.ResultEnum, "ProductSearchResponse.ResultEnum": ProductSearchResponse.ResultEnum, "ResultIdAccountingResponse.ResultEnum": ResultIdAccountingResponse.ResultEnum, "TaxSearchResponse.ResultEnum": TaxSearchResponse.ResultEnum, "TermsResponse.ResultEnum": TermsResponse.ResultEnum, "UpdatedContact.SyncActionEnum": UpdatedContact.SyncActionEnum, "UpdatedContact.CustomerTypeEnum": UpdatedContact.CustomerTypeEnum, "UpdatedProduct.SyncActionEnum": UpdatedProduct.SyncActionEnum, } let typeMap: {[index: string]: any} = { "AccountingAppSettings": AccountingAppSettings, "AccountingAppUrls": AccountingAppUrls, "AccountingExtensionCustomer": AccountingExtensionCustomer, "AccountingExtensionInvoice": AccountingExtensionInvoice, "AccountingExtensionTerm": AccountingExtensionTerm, "AccountingFeatures": AccountingFeatures, "ActionResponse": ActionResponse, "Address": Address, "CreateInvoiceFeature": CreateInvoiceFeature, "CreateInvoiceSubFeatures": CreateInvoiceSubFeatures, "CreateUserAccountRequestExternal": CreateUserAccountRequestExternal, "CustomerSearchResponseExternal": CustomerSearchResponseExternal, "ErrorDetail": ErrorDetail, "ExchangeRateResponse": ExchangeRateResponse, "ImportInvoiceFeature": ImportInvoiceFeature, "InvoiceCreatePaymentRequest": InvoiceCreatePaymentRequest, "InvoicePdfResponse": InvoicePdfResponse, "InvoiceReadResponse": InvoiceReadResponse, "InvoiceSearchResponse": InvoiceSearchResponse, "InvoiceUpdateRequest": InvoiceUpdateRequest, "InvoiceUpdateResponse": InvoiceUpdateResponse, "InvoicesResponseExternal": InvoicesResponseExternal, "ModelError": ModelError, "ObjectSyncFeature": ObjectSyncFeature, "Product": Product, "ProductSearchResponse": ProductSearchResponse, "ResultIdAccountingResponse": ResultIdAccountingResponse, "SyncContactsRequest": SyncContactsRequest, "SyncProductsRequest": SyncProductsRequest, "Tax": Tax, "TaxSearchResponse": TaxSearchResponse, "TaxType": TaxType, "TermsResponse": TermsResponse, "UnitPrice": UnitPrice, "UpdatedContact": UpdatedContact, "UpdatedProduct": UpdatedProduct, } export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { return expectedType; } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { return expectedType; } else if (expectedType === "Date") { return expectedType; } else { if (enumsMap[expectedType]) { return expectedType; } if (!typeMap[expectedType]) { return expectedType; // w/e we don't know the type } // Check the discriminator let discriminatorProperty = typeMap[expectedType].discriminator; if (discriminatorProperty == null) { return expectedType; // the type does not have a discriminator. use it. } else { if (data[discriminatorProperty]) { var discriminatorType = data[discriminatorProperty]; if(typeMap[discriminatorType]){ return discriminatorType; // use the type given in the discriminator } else { return expectedType; // discriminator did not map to a type } } else { return expectedType; // discriminator was not present (or an empty string) } } } } public static serialize(data: any, type: string) { if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index = 0; index < data.length; index++) { let datum = data[index]; transformedData.push(ObjectSerializer.serialize(datum, subType)); } return transformedData; } else if (type === "Date") { return data.toISOString(); } else { if (enumsMap[type]) { return data; } if (!typeMap[type]) { // in case we dont know the type return data; } // Get the actual type of this object type = this.findCorrectType(data, type); // get the map for the correct type. let attributeTypes = typeMap[type].getAttributeTypeMap(); let instance: {[index: string]: any} = {}; for (let index = 0; index < attributeTypes.length; index++) { let attributeType = attributeTypes[index]; instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); } return instance; } } public static deserialize(data: any, type: string) { // polymorphism may change the actual type. type = ObjectSerializer.findCorrectType(data, type); if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index = 0; index < data.length; index++) { let datum = data[index]; transformedData.push(ObjectSerializer.deserialize(datum, subType)); } return transformedData; } else if (type === "Date") { return new Date(data); } else { if (enumsMap[type]) {// is Enum return data; } if (!typeMap[type]) { // dont know the type return data; } let instance = new typeMap[type](); let attributeTypes = typeMap[type].getAttributeTypeMap(); for (let index = 0; index < attributeTypes.length; index++) { let attributeType = attributeTypes[index]; instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); } return instance; } } } export interface Authentication { /** * Apply authentication settings to header and query params. */ applyToRequest(requestOptions: localVarRequest.Options): Promise<void> | void; } export class HttpBasicAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } } } export class HttpBearerAuth implements Authentication { public accessToken: string | (() => string) = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { const accessToken = typeof this.accessToken === 'function' ? this.accessToken() : this.accessToken; requestOptions.headers["Authorization"] = "Bearer " + accessToken; } } } export class ApiKeyAuth implements Authentication { public apiKey: string = ''; constructor(private location: string, private paramName: string) { } applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (<any>requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } else if (this.location == 'cookie' && requestOptions && requestOptions.headers) { if (requestOptions.headers['Cookie']) { requestOptions.headers['Cookie'] += '; ' + this.paramName + '=' + encodeURIComponent(this.apiKey); } else { requestOptions.headers['Cookie'] = this.paramName + '=' + encodeURIComponent(this.apiKey); } } } } export class OAuth implements Authentication { public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } } } export class VoidAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(_: localVarRequest.Options): void { // Do nothing } } export type Interceptor = (requestOptions: localVarRequest.Options) => (Promise<void> | void);
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/changesMappers"; import * as Parameters from "../models/parameters"; import { AzureChangeAnalysisManagementClientContext } from "../azureChangeAnalysisManagementClientContext"; /** Class representing a Changes. */ export class Changes { private readonly client: AzureChangeAnalysisManagementClientContext; /** * Create a Changes. * @param {AzureChangeAnalysisManagementClientContext} client Reference to the service client. */ constructor(client: AzureChangeAnalysisManagementClientContext) { this.client = client; } /** * @summary List the changes of a resource group within the specified time range. Customer data * will always be masked. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param [options] The optional parameters * @returns Promise<Models.ChangesListChangesByResourceGroupResponse> */ listChangesByResourceGroup(resourceGroupName: string, startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesByResourceGroupOptionalParams): Promise<Models.ChangesListChangesByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param callback The callback */ listChangesByResourceGroup(resourceGroupName: string, startTime: Date | string, endTime: Date | string, callback: msRest.ServiceCallback<Models.ChangeList>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param options The optional parameters * @param callback The callback */ listChangesByResourceGroup(resourceGroupName: string, startTime: Date | string, endTime: Date | string, options: Models.ChangesListChangesByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.ChangeList>): void; listChangesByResourceGroup(resourceGroupName: string, startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesByResourceGroupOptionalParams | msRest.ServiceCallback<Models.ChangeList>, callback?: msRest.ServiceCallback<Models.ChangeList>): Promise<Models.ChangesListChangesByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, startTime, endTime, options }, listChangesByResourceGroupOperationSpec, callback) as Promise<Models.ChangesListChangesByResourceGroupResponse>; } /** * @summary List the changes of a subscription within the specified time range. Customer data will * always be masked. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param [options] The optional parameters * @returns Promise<Models.ChangesListChangesBySubscriptionResponse> */ listChangesBySubscription(startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesBySubscriptionOptionalParams): Promise<Models.ChangesListChangesBySubscriptionResponse>; /** * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param callback The callback */ listChangesBySubscription(startTime: Date | string, endTime: Date | string, callback: msRest.ServiceCallback<Models.ChangeList>): void; /** * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param options The optional parameters * @param callback The callback */ listChangesBySubscription(startTime: Date | string, endTime: Date | string, options: Models.ChangesListChangesBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.ChangeList>): void; listChangesBySubscription(startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesBySubscriptionOptionalParams | msRest.ServiceCallback<Models.ChangeList>, callback?: msRest.ServiceCallback<Models.ChangeList>): Promise<Models.ChangesListChangesBySubscriptionResponse> { return this.client.sendOperationRequest( { startTime, endTime, options }, listChangesBySubscriptionOperationSpec, callback) as Promise<Models.ChangesListChangesBySubscriptionResponse>; } /** * @summary List the changes of a resource group within the specified time range. Customer data * will always be masked. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param [options] The optional parameters * @returns Promise<Models.ChangesListChangesByResourceGroupNextResponse> */ listChangesByResourceGroupNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesByResourceGroupNextOptionalParams): Promise<Models.ChangesListChangesByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param callback The callback */ listChangesByResourceGroupNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, callback: msRest.ServiceCallback<Models.ChangeList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param options The optional parameters * @param callback The callback */ listChangesByResourceGroupNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, options: Models.ChangesListChangesByResourceGroupNextOptionalParams, callback: msRest.ServiceCallback<Models.ChangeList>): void; listChangesByResourceGroupNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesByResourceGroupNextOptionalParams | msRest.ServiceCallback<Models.ChangeList>, callback?: msRest.ServiceCallback<Models.ChangeList>): Promise<Models.ChangesListChangesByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, startTime, endTime, options }, listChangesByResourceGroupNextOperationSpec, callback) as Promise<Models.ChangesListChangesByResourceGroupNextResponse>; } /** * @summary List the changes of a subscription within the specified time range. Customer data will * always be masked. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param [options] The optional parameters * @returns Promise<Models.ChangesListChangesBySubscriptionNextResponse> */ listChangesBySubscriptionNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesBySubscriptionNextOptionalParams): Promise<Models.ChangesListChangesBySubscriptionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param callback The callback */ listChangesBySubscriptionNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, callback: msRest.ServiceCallback<Models.ChangeList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param startTime Specifies the start time of the changes request. * @param endTime Specifies the end time of the changes request. * @param options The optional parameters * @param callback The callback */ listChangesBySubscriptionNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, options: Models.ChangesListChangesBySubscriptionNextOptionalParams, callback: msRest.ServiceCallback<Models.ChangeList>): void; listChangesBySubscriptionNext(nextPageLink: string, startTime: Date | string, endTime: Date | string, options?: Models.ChangesListChangesBySubscriptionNextOptionalParams | msRest.ServiceCallback<Models.ChangeList>, callback?: msRest.ServiceCallback<Models.ChangeList>): Promise<Models.ChangesListChangesBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, startTime, endTime, options }, listChangesBySubscriptionNextOperationSpec, callback) as Promise<Models.ChangesListChangesBySubscriptionNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listChangesByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ChangeAnalysis/changes", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime, Parameters.skipToken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ChangeList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listChangesBySubscriptionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.ChangeAnalysis/changes", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime, Parameters.skipToken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ChangeList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listChangesByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime, Parameters.skipToken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ChangeList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listChangesBySubscriptionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], queryParameters: [ Parameters.apiVersion, Parameters.startTime, Parameters.endTime, Parameters.skipToken ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ChangeList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import {simpleArray, randomArray, oddArray, jsn} from "./data"; import {assert} from "chai"; import * as Linq from "../lib/linq"; describe('Immediate Execution -', function () { // Aggregate it('Aggregate() - No seed', function () { assert.equal(55, Linq.From(simpleArray).Aggregate((a, b) => a + b)); }); it('Aggregate()', function () { assert.equal(3628800, Linq.From(simpleArray).Aggregate(1, (a, b) => a * b)); }); it('Aggregate() - Transform', function () { assert.equal(1814400, Linq.From(simpleArray).Aggregate(1, (a, b) => a * b, o => o / 2)); }); it('Aggregate() - Default Value [String]', function () { assert.equal("123", Linq.From([1, 2, 3]).Aggregate("", (c, n) => c.toString() + n.toString())); }); // All it('All() - True', function () { assert.isTrue(Linq.From(oddArray).All(b => b % 2 == 1)) }); it('All() - False', function () { assert.isFalse(Linq.From(simpleArray).All(b => b % 2 == 1)) }); // Any it('Any() - No predicate', function () { assert.isTrue(Linq.From(simpleArray).Any()); }); it('Any() - True', function () { assert.isTrue(Linq.From(simpleArray).Any(i => i > 3)); }); it('Any() - False', function () { assert.isFalse(Linq.From(simpleArray).Any(i => i > simpleArray.length)); }); // Average it('Average() - No predicate', function () { assert.equal(4.0 / 3, Linq.From([-2, 1, 5]).Average()); }); it('Average()', function () { const expectedAvg = jsn.reduce((sum, o)=>sum+o.id, 0) / jsn.length; assert.equal(Linq.From(jsn).Average(o => o.id), expectedAvg); }); // Contains it('Contains - True', function () { assert.isTrue(Linq.From(simpleArray).Contains(4)); }); it('Contains - False', function () { assert.isFalse(Linq.From(simpleArray).Contains(43)); }); // Count it('Count() - Array', function () { assert.equal(10, Linq.From(simpleArray).Count()); }); it('Count() - String', function () { assert.equal(10, Linq.From("1234567890").Count()); }); it('Count() - No predicate', function () { assert.equal(10, Linq.Range(0, 10).Count()); }); it('Count()', function () { assert.equal(5, Linq.From(simpleArray).Count(b => b % 2 == 1)); }); // Max it('Max() - No predicate', function () { assert.equal(10, Linq.From(randomArray).Max()); }); it('Max()', function () { assert.equal(4, Linq.From(jsn).Max(o => o.id)); }); it('Max() - Empty', function () { assert.throws(function () { Linq.From([]).Max(); }); }); // Min it('Min() - No predicate', function () { assert.equal(Math.min(...randomArray), Linq.From(randomArray).Min()); }); it('Min()', function () { assert.equal(Math.min(...jsn.map(o => o.id)), Linq.From(jsn).Min(o => o.id)); }); it('Min() - Empty', function () { assert.throws(function () { Linq.From([]).Min(); }); }); // ElementAt it('ElementAt() - Iterable', function () { assert.equal(3, Linq.Range(0, 10).ElementAt(3)); }); it('ElementAt() - Array', function () { assert.equal(6, Linq.From(simpleArray).ElementAt(5)); }); it('ElementAt() - Out of Range', function () { assert.throw(function () { Linq.From(simpleArray).ElementAt(-1); }); assert.throw(function () { Linq.Range(0, 10).ElementAt(50); }); }); // ElementAtOrDefault it('ElementAtOrDefault() - Array', function () { assert.equal(Linq.From(simpleArray).ElementAtOrDefault(5), 6); }); it('ElementAtOrDefault() - Iterable', function () { assert.equal(Linq.Range(1, 10).ElementAtOrDefault(5), 6); }); it('ElementAtOrDefault() - Default of Array', function () { assert.equal(Linq.From(simpleArray).ElementAtOrDefault(-500), 0); }); it('ElementAtOrDefault() - Default of empty Array', function () { assert.equal(Linq.From([]).ElementAtOrDefault(-500), undefined); }); it('ElementAtOrDefault() - Default of Iterable', function () { assert.equal(Linq.Range(1, 10).ElementAtOrDefault(500), 0); }); it('ElementAtOrDefault() - Default Boolean', function () { assert.isFalse(Linq.From([true, false, false]).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default Null', function () { assert.isNull(Linq.Repeat(null, 1).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default Undefined', function () { assert.isUndefined(Linq.Repeat(undefined, 1).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default Object', function () { assert.isUndefined(Linq.From([this, this, {}]).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default String', function () { assert.isString(Linq.Repeat("String", 3).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default Symbol', function () { assert.isDefined(Linq.From([Symbol(), Symbol]).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default Function', function () { assert.isUndefined(Linq.Repeat(() => { }, 3).ElementAtOrDefault(5)); }); it('ElementAtOrDefault() - Default Class', function () { class Polygon { constructor(public height = 0, public width = 1) { this.height = height; this.width = width; } } assert.isUndefined(Linq.Repeat(Polygon, 3).ElementAtOrDefault(5)); }); // First it('First() - No predicate', function () { assert.equal(1, Linq.From(simpleArray).First()); }); it('First()', function () { assert.equal(6, Linq.From(simpleArray).First(a => a > 5)); }); it('First() - Empty', function () { assert.throw(function () { assert.equal(6, Linq.From(simpleArray).First(a => a > 50)); }); }); // FirstOrDefault it('FirstOrDefault() - No predicate', function () { assert.equal(1, Linq.From(simpleArray).FirstOrDefault()); }); it('FirstOrDefault()', function () { assert.equal(6, Linq.From(simpleArray).FirstOrDefault(a => a > 5)); }); it('FirstOrDefault() - Empty', function () { assert.doesNotThrow(function () { assert.equal(0, Linq.From(simpleArray).FirstOrDefault(a => a > 50)); }); }); // Last it('Last() - No predicate', function () { assert.equal(10, Linq.From(simpleArray).Last()); }); it('Last()', function () { assert.equal(4, Linq.From(simpleArray).Last(a => a < 5)); }); it('Last() - Empty', function () { assert.throw(function () { Linq.From(simpleArray).Last(a => a > 50); }); }); // LastOrDefault it('LastOrDefault() - No predicate', function () { assert.equal(10, Linq.From(simpleArray).LastOrDefault()); }); it('LastOrDefault()', function () { assert.equal(4, Linq.From(simpleArray).LastOrDefault(a => a < 5)); }); it('LastOrDefault() - Empty', function () { assert.doesNotThrow(function () { assert.equal(0, Linq.From(simpleArray).LastOrDefault(a => a > 50)); }); }); // SequenceEqual it('SequenceEqual() - Array', function () { assert.isTrue(Linq.From(simpleArray).SequenceEqual(simpleArray)) }); it('SequenceEqual() - Linq', function () { assert.isTrue(Linq.From(simpleArray).SequenceEqual(Linq.From(simpleArray))) }); it('SequenceEqual() - Shorter', function () { assert.isFalse(Linq.From([1, 2, 3, 4, 5, 6]).SequenceEqual(simpleArray)) }); it('SequenceEqual() - Longer', function () { assert.isFalse(Linq.From(simpleArray).SequenceEqual([1, 2, 3, 4, 5, 6])) }); it('SequenceEqual() - Not Equal', function () { assert.isFalse(Linq.From(simpleArray).SequenceEqual([1, 2, 3, 4, 50, 6, 7, 8, 9, 10])) }); // Singel it('Single() - No predicate', function () { assert.equal(4, Linq.From([4]).Single()); }); it('Single()', function () { assert.equal(2, Linq.From(simpleArray).Single(a => a == 2)); }); it('Single() - Empty', function () { assert.throw(function () { Linq.From(simpleArray).Single(a => a > 15); }); }); it('Single() - More than one', function () { assert.throw(function () { Linq.From(simpleArray).Single(a => a > 5); }); }); // SingleOrDefault it('SingleOrDefault() - No predicate', function () { assert.equal(4, Linq.From([4]).SingleOrDefault()); }); it('SingleOrDefault()', function () { assert.equal(2, Linq.From(simpleArray).SingleOrDefault(a => a == 2)); }); it('SingleOrDefault() - Empty', function () { assert.equal(0, Linq.From(simpleArray).SingleOrDefault(a => a == 20)); }); it('SingleOrDefault() - More than one', function () { assert.Throw(function () { Linq.From(simpleArray).SingleOrDefault(a => a > 5); }); }); // Sum it('Sum() - No predicate', function () { assert.equal(55, Linq.From(simpleArray).Sum()); }); it('Sum()', function () { assert.equal(10, Linq.From(jsn).Sum(o => o.id)); }); // ToArray it('ToArray()', function () { assert.isArray(Linq.From(simpleArray).ToArray()); }); // ToMap it('ToMap() - No Selector', function () { assert.equal(jsn[0], Linq.From(jsn).ToMap(o => o.id).get(1)); }); it('ToMap()', function () { assert.equal(jsn[0].name, Linq.From(jsn).ToMap(k => k.id, o => o.name).get(1)); }); it('ToDictionary() - No Selector', function () { assert.equal(jsn[0], Linq.From(jsn).ToDictionary(o => o.id).get(1)); }); it('ToDictionary()', function () { assert.equal(jsn[0].name, Linq.From(jsn).ToDictionary(k => k.id, o => o.name).get(1)); }); }); /** Copyright (c) ENikS. All rights reserved. */
the_stack
"use strict"; import assert from "assert"; import path from "path"; import { TextLintCore } from "../../src/index"; import { TextlintRuleSeverityLevelKeys } from "@textlint/kernel"; import { coreFlags, resetFlags } from "@textlint/feature-flag"; import { TextlintFilterRuleContext, TextlintFilterRuleReportHandler, TextlintRuleContext, TextlintRuleReportHandler } from "@textlint/types"; import throwErrorInRule from "./fixtures/rules/throw-error-in-rule"; /* TODO: rule-context-test has `lintText` and `fixText` test. These should be moved to core test */ describe("rule-context-test", function () { let textlint: TextLintCore; beforeEach(function () { textlint = new TextLintCore(); }); context("in traverse", function () { let callCount: number; beforeEach(function () { callCount = 0; }); context(":enter", function () { beforeEach(function () { textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { const exports: TextlintRuleReportHandler = {}; exports[context.Syntax.Str] = function (node) { callCount++; const parent = node?.parent; assert.equal(parent?.type, context.Syntax.Paragraph); const root = parent?.parent; assert.equal(root?.type, context.Syntax.Document); }; return exports; } }); }); it("should call Str callback, 1+1", function () { return textlint .lintMarkdown("text") .then(() => { assert.ok(callCount === 1); }) .then(() => { return textlint.lintText("text"); }) .then(() => { assert.ok(callCount === 2); }); }); }); context(":exit", function () { beforeEach(function () { textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { const exports: TextlintRuleReportHandler = {}; exports[`${context.Syntax.Str}:exit`] = function (node) { callCount++; const parent = node?.parent; assert.equal(parent?.type, context.Syntax.Paragraph); const root = parent?.parent; assert.equal(root?.type, context.Syntax.Document); }; return exports; } }); }); it("should call Str callback, 1+1", function () { return textlint .lintMarkdown("text") .then(() => { assert.ok(callCount === 1); }) .then(() => { return textlint.lintText("text"); }) .then(() => { assert.ok(callCount === 2); }); }); }); context("when throw error in a rule", function () { beforeEach(function () { textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "throw-error-in-rule": throwErrorInRule }); }); it("should catch error", function () { return textlint.lintMarkdown("text").catch((error) => { assert.ok(error instanceof Error); }); }); }); context("when throw error in a rule at file", function () { beforeEach(function () { textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "throw-error-in-rule": throwErrorInRule }); }); it("should catch error including <file path>", function () { const filePath = path.join(__dirname, "fixtures/test.md"); return textlint.lintFile(filePath).catch((error) => { assert.ok(error instanceof Error); assert.ok(error.message.indexOf(filePath) !== -1); }); }); }); }); describe("#getSource", function () { it("should get text from TxtNode", function () { const expectedText = "this is text."; textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { const exports: TextlintRuleReportHandler = {}; exports[context.Syntax.Document] = function (node) { const text = context.getSource(node); assert.equal(text, expectedText); }; return exports; } }); return textlint.lintMarkdown(expectedText); }); it("should get text with padding from TxtNode", function () { const expectedText = "this is text."; textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { const exports: TextlintRuleReportHandler = {}; exports[context.Syntax.Document] = function (node) { const text = context.getSource(node, -1, -1); assert.equal(text, expectedText.slice(1, expectedText.length - 1)); }; return exports; } }); return textlint.lintMarkdown(expectedText); }); }); describe("#serverity", function () { it("should return Error by default", function () { const expectedText = "this is text."; textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { const exports: TextlintRuleReportHandler = {}; exports[context.Syntax.Document] = function (_node) { assert.strictEqual(context.severity, TextlintRuleSeverityLevelKeys.error); }; return exports; } }); return textlint.lintMarkdown(expectedText); }); it("should get text with padding from TxtNode", function () { const expectedText = "this is text."; textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { const exports: TextlintRuleReportHandler = {}; exports[context.Syntax.Document] = function (node) { const text = context.getSource(node, -1, -1); assert.equal(text, expectedText.slice(1, expectedText.length - 1)); }; return exports; } }); return textlint.lintMarkdown(expectedText); }); }); describe("#report", function () { context("RuleError", function () { beforeEach(function () { coreFlags.runningTester = true; }); afterEach(function () { resetFlags(); }); context("[backward compatible]", function () { beforeEach(function () { coreFlags.runningTester = false; }); it("could use 2nd arguments as padding column", function () { textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { // FIXME: this is un-document // Please remove next version const ruleError = new context.RuleError("error", 1); context.report(node, ruleError); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 1); const message = result.messages[0]; assert.equal(message.line, 1); assert.equal(message.column, 2); }); }); }); it("could has padding column", function () { textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { // throw error in testing const ruleError = new context.RuleError("error", 1); context.report(node, ruleError); } }; } }); // catch error return textlint.lintMarkdown("test").catch((error) => { assert.ok(error instanceof Error); }); }); it("could has padding location", function () { textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Code](node) { const ruleError = new context.RuleError("error", { line: 5, column: 5 }); // if line >=1 // then start with 0 + column context.report(node, ruleError); } }; } }); return textlint.lintMarkdown("test`code`test").then((result) => { assert.ok(result.messages.length === 1); const message = result.messages[0]; assert.equal(message.line, 6); assert.equal(message.column, 5 + 1); }); }); }); it("can also report data", function () { const expectedData = { message: "message", key: "value" }; textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { context.report(node, expectedData); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 1); const message = result.messages[0]; assert.equal(message.message, expectedData.message); assert.deepEqual(message.data, expectedData); }); }); // deprecated it("report 3rd arguments should throw error", function () { // const expectedData = { message: "message", key: "value" }; textlint.setupRules({ // rule-key : rule function(see docs/rule.md) "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { context.report(node, new context.RuleError("message"), { index: 1 }); } }; } }); return textlint.lintMarkdown("test").catch((error) => { assert.ok(error instanceof Error); }); }); }); describe("#shouldIgnore", function () { context("when ignoreMessages only", function () { it("should return empty message", function () { textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Str](node) { context.shouldIgnore(node.range, {}); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 0); }); }); }); context("when ignoreMessages not match message", function () { it("should preserve messages", function () { textlint.setupRules({ rule(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { context.report(node, new context.RuleError("message")); } }; } }); textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Code](node) { context.shouldIgnore(node.range, {}); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 1); const [message] = result.messages; assert.equal(message.type, "lint"); }); }); }); context("when duplicated ignoreMessages", function () { it("should messages is ignore", function () { textlint.setupRules({ rule(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { context.report(node, new context.RuleError("message")); } }; } }); textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Str](node) { context.shouldIgnore(node.range, { ruleId: "*" }); context.shouldIgnore(node.range, { ruleId: "*" }); context.shouldIgnore(node.range, { ruleId: "*" }); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 0); }); }); }); context("when ignoreMessages that is not specified ruleId", function () { it("should filter all messages *", function () { textlint.setupRules({ rule(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { context.report(node, new context.RuleError("message")); } }; } }); textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Str](node) { // no specify ruleId context.shouldIgnore(node.range, {}); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 0); }); }); }); context("when exist messages and ignoreMessages", function () { it("should return filtered result by ignoreMessages", function () { textlint.setupRules({ rule(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Str](node) { context.report(node, new context.RuleError("message")); } }; } }); textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Str](node) { context.shouldIgnore(node.range, { ruleId: "*" }); } }; } }); return textlint.lintMarkdown("test").then((result) => { assert.ok(result.messages.length === 0); }); }); }); context("when --fix", function () { it("should fixer messages", function () { const reporter = (context: TextlintRuleContext): TextlintRuleReportHandler => { return { [context.Syntax.Str](node) { context.report(node, new context.RuleError("message", { fix: context.fixer.remove(node) })); } }; }; textlint.setupRules({ rule: { linter: reporter, fixer: reporter } }); textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Str](node) { context.shouldIgnore(node.range, { ruleId: "*" }); } }; } }); return textlint.fixText("test").then((result) => { assert.ok(result.applyingMessages.length === 0); assert.ok(result.remainingMessages.length === 0); assert.ok(result.messages.length === 0); }); }); context("when ignoreMessages that is not specified ruleId", function () { it("should filter all messages as `*`", function () { const reporter = (context: TextlintRuleContext): TextlintRuleReportHandler => { return { [context.Syntax.Str](node) { context.report( node, new context.RuleError("message", { fix: context.fixer.remove(node) }) ); } }; }; textlint.setupRules({ rule: { linter: reporter, fixer: reporter } }); // not match == not ignore textlint.setupFilterRules({ "filter-rule"(context: TextlintFilterRuleContext): TextlintFilterRuleReportHandler { return { [context.Syntax.Str](node) { // Not specify id = all filter context.shouldIgnore(node.range, {}); } }; } }); return textlint.fixText("test").then((result) => { assert.ok(result.output === "test"); assert.ok(result.applyingMessages.length === 0); assert.ok(result.remainingMessages.length === 0); assert.ok(result.messages.length === 0); }); }); }); }); }); describe("#getFilePath", function () { context("when linting text", function () { it("should return undefined", function () { textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Document]() { const filePath = context.getFilePath(); assert.ok(filePath === undefined); } }; } }); return textlint.lintMarkdown("test"); }); }); context("when linting file", function () { it("should return filePath that is linting now", function () { const lintFilePath = path.join(__dirname, "fixtures/test.md"); textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Document]() { const filePath = context.getFilePath(); assert.equal(filePath, lintFilePath); } }; } }); return textlint.lintFile(lintFilePath); }); }); }); describe("#getConfigBaseDir", function () { context("when linting text", function () { it("should return undefined", function () { textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Document]() { const baseDir = context.getConfigBaseDir(); assert.ok(baseDir === undefined); } }; } }); return textlint.lintMarkdown("test"); }); }); context("when pass config", function () { it("should return undefined", function () { const configBasedir = path.join(__dirname, "fixtures"); // TODO: it will be moved to kernel const textlint = new TextLintCore({ configFile: path.join(configBasedir, ".textlintrc") }); textlint.setupRules({ "rule-key"(context: TextlintRuleContext): TextlintRuleReportHandler { return { [context.Syntax.Document]() { const baseDir = context.getConfigBaseDir(); assert.ok(baseDir === configBasedir); } }; } }); return textlint.lintMarkdown("test"); }); }); }); });
the_stack
import { ObjectUtils } from '../utils/object.utils'; import { ClassParameter } from '../utils/typescript.utils'; import { IDiConstructorHandler, IDiDepLeft, IDiEntry, IDiServiceMetadata, IServiceIdentifier, OnInit, OnServiceReadyCallback } from './di.shared'; import { DiService } from './di.service'; /** * Service container. */ export class Container { // ------------------------------------------------------------------------- // Constants // ------------------------------------------------------------------------- /** * You can use this constant in order to inject services * from the global context in context scoped services. * ej `@Inject({ ctx: }) ` */ public static readonly globalCtx = 'GLOBAL'; /** * Defines the variation var name that interanlly wiil be used * to inject connection names */ public static readonly connection = 'connection'; private static readonly serviceMetadata = 'diServiceMetadata'; // ------------------------------------------------------------------------- // Private variables // ------------------------------------------------------------------------- private static onServiceReadyCallbacks: OnServiceReadyCallback[] = []; // ------------------------------------------------------------------------- // Public methods // ------------------------------------------------------------------------- /** * Registers the given Class as a new service and it will try to create a new instance * and return it to any Container.get requesting this IServiceIdentifier as soon as * all the dependecies are met */ public static registrerService<T>(inp: { id: IServiceIdentifier<T>; clazz: ClassParameter<T>; params?: ClassParameter<any>[]; ctx?: string; connection?: string; }) { const serviceId = DiService.genServiceId(inp.id); const entry = DiService.getTmpEnrySafely(serviceId, inp.clazz); this.setServiceMetadata(inp.clazz, inp.id, inp.ctx); DiService.discardTmpEntry(serviceId); entry.serviceId = DiService.genServiceId(inp.id); // Check if there is any dependency with @Inject // that requires the connection this.updateDependenciesWithConnectionIfNecessary(entry.depsLeft, inp.connection); // All property dependencies that are queued have to be called. // This also checks if the serviceId changes becouse of the connection this.resolveServiceProperties(entry, inp.connection); if (inp.params && inp.params.length > 0) { this.initConstructorService({ entry, params: inp.params, ctx: inp.ctx, connection: inp.connection }); } else { this.initService(entry, inp.ctx); } } /** * Sets the given service with its instance and marks it as ready, so * other services can have it as dependency. * @param serviceClass * @param instance * @param serviceId * @param ctx */ public static set<T>(serviceClass: ClassParameter<T>, instance: T, id?: string, ctx?: string) { const serviceId = id || serviceClass; this.setServiceMetadata(serviceClass, serviceId, ctx); const serviceName = DiService.genServiceId(serviceId); const entry = DiService.getEnrySafely(serviceName, serviceClass, ctx); entry.object = instance; entry.depsLeft = undefined; entry.constructorHandlers = undefined; this.initService(entry, ctx); } /** * Returns the requested service once all it's dependencies has been * met. This method keep the current thread alive until it returns * a value. * @param serviceId * @param ctx */ public static async get<T>( serviceId: string | ClassParameter<T>, variation?: Record<string, any>, ctx?: string ): Promise<T> { const serviceName = DiService.genServiceId(serviceId, variation); const entry = DiService.getEntry(serviceName, ctx); if (entry && entry.isReady) { return entry.object; } else { return await this.waitForDep<T>(serviceName, ctx, variation); } } /** * Shorcut for `Container.get()` when you want a dependency from * a specific context * @param serviceId * @param ctx */ public static async getFromContext<T>( serviceId: string | ClassParameter<T>, ctx?: string ): Promise<T> { return this.get(serviceId, undefined, ctx); } /** * * Used for internal operations * * This will wait for the target service to be ready and returns it. * It takes into consideration the service connection * @param serviceId * @param ctx */ public static async getServiceProperty<T>(inp: { originalService: { id: IServiceIdentifier; clazz: ClassParameter<T>; }; targetService: { id: IServiceIdentifier; ctx?: string; variation?: Record<string, any>; }; }): Promise<T> { const originalServiceId = DiService.genServiceId(inp.originalService.id); const orignalService = DiService.getTmpEnrySafely(originalServiceId, inp.originalService.clazz); if (!orignalService) { throw new Error('Service not found for this property'); } return new Promise(resolve => { orignalService.propertiesWaiting = (orignalService.propertiesWaiting || []).concat({ id: inp.targetService.id, ctx: inp.targetService.ctx, variation: inp.targetService.variation, cb: resolve }); }); } /** * Internal usage only, it registers a Class property as dependency for the service * @param serviceId * @param targetServiceId * @param ctx * @param update */ public static registerDepLeft(inp: { serviceId: IServiceIdentifier; targetServiceId: IServiceIdentifier; targetCtx?: string; update?: boolean; variation?: Record<string, any>; variationVarName?: string; }) { const serviceName = DiService.genServiceId(inp.serviceId); const targetServiceName = DiService.genServiceId(inp.targetServiceId, inp.variation); let entry = DiService.getTmpEnrySafely(serviceName); entry = this.registerEntryDepLeft({ entry, targetServiceName, targetCtx: inp.targetCtx, variationVarName: inp.variationVarName }); if (inp.update) { DiService.updateTmpEnry(entry); } } /** * Internal usage only, it register a class constructor property, it's the only way * you can se parameters like serviceId or context * @param id * @param targetId * @param index * @param ctx * @param update */ public static registrerConstructorHandler(inp: { id: IServiceIdentifier; targetId: IServiceIdentifier; index: number; targetCtx?: string; update?: boolean; variation?: Record<string, any>; variationVarName?: string; }) { const serviceName = DiService.genServiceId(inp.id); const targetServiceName = DiService.genServiceId(inp.targetId, inp.variation); let entry = DiService.getTmpEnrySafely(serviceName); entry = this.updateConstructorHandler({ entry, index: inp.index, targetServiceName, targetCtx: inp.targetCtx, variationVarName: inp.variationVarName, variation: inp.variation }); if (inp.update) { DiService.updateTmpEnry(entry); } } /** * Returns a promise that gets executed once all the dependecies * passed in the input array are met * @param deps */ public static async waitFor(deps: IDiServiceMetadata[]): Promise<void> { if (deps && deps.length > 0) { const contDeps: Promise<any>[] = []; deps.forEach(dep => { contDeps.push(Container.get(dep.serviceId, undefined, dep.ctx)); }); await Promise.all(contDeps); } else { throw new Error('Container.waitFor => Deps argument not defined or empty'); } } /** * Returns the service metadata attached to the function if it exists * (then it means this class is controlled by the container) or undefined * if no metadata is found * @param clazz */ public static getServiceMetadata(clazz: ClassParameter<any>): IDiServiceMetadata | undefined { let result: IDiServiceMetadata | undefined; const metadata = (<any>clazz)[this.serviceMetadata]; if (metadata) { result = <IDiServiceMetadata>metadata; } return result; } /** * Registar a callback that is going to be called for every service * that has been set as ready or that has already been marked * @param callback */ public static onServiceReady(callback: OnServiceReadyCallback) { // 1: Check if any entris has beed set as ready // before registreing this callback const readyEntries = DiService.getAllReadyEntries(); for (const entry of readyEntries) { callback(entry); } // 2: Then store the callback inside an array // for future services this.onServiceReadyCallbacks.push(callback); } // ------------------------------------------------------------------------- // Private methods // ------------------------------------------------------------------------- private static registerEntryDepLeft(inp: { entry: IDiEntry; targetServiceName: string; targetCtx?: string; variationVarName?: string; }): IDiEntry { const newDepLeft = { targetServiceId: inp.targetServiceName, depMet: inp.variationVarName !== undefined || DiService.depIsReady(inp.targetServiceName, inp.targetCtx), targetCtx: inp.targetCtx, variationVarName: inp.variationVarName }; if (inp.entry.depsLeft) { const hIndex = inp.entry.depsLeft .findIndex(el => el.targetServiceId === inp.targetServiceName); if (hIndex === -1) { inp.entry.depsLeft.push(newDepLeft); } else { inp.entry.depsLeft[hIndex] = newDepLeft; } } else { inp.entry.depsLeft = [newDepLeft]; } return inp.entry; } private static updateConstructorHandler(inp: { entry: IDiEntry; index: number; targetServiceName: string; targetCtx?: string; variationVarName?: string; variation?: Record<string, any>; }): IDiEntry { const newHandler = { targetServiceId: inp.targetServiceName, index: inp.index, targetCtx: inp.targetCtx, variationVarName: inp.variationVarName, variation: inp.variation }; if (inp.entry.constructorHandlers) { const hIndex = inp.entry.constructorHandlers .findIndex(el => el.index === inp.index); if (hIndex === -1) { inp.entry.constructorHandlers.push(newHandler); } } else { inp.entry.constructorHandlers = [newHandler]; } return inp.entry; } private static initConstructorService(inp: { entry: IDiEntry; params: ClassParameter<any>[]; ctx?: string; connection?: string; }) { for (const [index, targetClass] of inp.params.entries()) { const targetServiceName = DiService.genServiceId(targetClass); // This will create a dep only if it's not been decorated with @inject() before inp.entry = this.updateConstructorHandler({ entry: inp.entry, index, targetServiceName, targetCtx: inp.ctx }); } // Check if there is any dependency with @Inject // that requires the connection this.updateDependenciesWithConnectionIfNecessary(inp.entry.constructorHandlers, inp.connection); for (const element of inp.entry.constructorHandlers || []) { inp.entry = this.registerEntryDepLeft({ entry: inp.entry, targetServiceName: element.targetServiceId, targetCtx: element.targetCtx || inp.ctx, variationVarName: element.variationVarName }); if (element.variation) { const targetEntry = DiService.getEntry(element.targetServiceId, element.targetCtx || inp.ctx); if (inp.entry.depsLeft && targetEntry && targetEntry.isReady) { const targetDep = inp.entry.depsLeft.find(dl => dl.targetServiceId === element.targetServiceId); if (targetDep) { targetDep.depMet = true; } } if (!targetEntry) { this.waitForDep(element.targetServiceId, element.targetCtx || inp.ctx, element.variation).then(() => { const updatedEntry = DiService.getEntry(inp.entry.serviceId, inp.ctx); if (updatedEntry && !updatedEntry.isReady && updatedEntry.depsLeft) { for (const depLeft of updatedEntry.depsLeft) { const targetService = DiService.getEntry(depLeft.targetServiceId, depLeft.targetCtx); if (targetService && targetService.isReady) { depLeft.depMet = true; } } this.checkIfReady(inp.entry, inp.ctx); } }); } } } inp.entry.depsClosed = true; inp.entry.isOnlyTemplate = inp.entry.depsLeft && inp.entry.depsLeft.some(dl => dl.variationVarName !== undefined) || false; DiService.updateEntry(inp.entry, inp.ctx); this.checkIfReady(inp.entry, inp.ctx); } private static initService(entry: IDiEntry, ctx?: string) { if (entry.object === undefined && entry.serviceClass) { const clazz = entry.serviceClass; entry.object = new (<any>clazz)(); } entry.depsClosed = true; entry.isOnlyTemplate = entry.depsLeft && entry.depsLeft.some(dl => dl.variationVarName) || false; DiService.updateEntry(entry, ctx); this.checkIfReady(entry, ctx); } private static setServiceAsReady(entry: IDiEntry, ctx?: string) { if (entry.isReady) { return; } // If there are construction hadlers it means we need to create the object // with the required parameters before proceding if (entry.constructorHandlers) { const params: any[] = []; try { entry.constructorHandlers.forEach(handler => { if (handler.variationVarValue) { params[handler.index] = handler.variationVarValue; } else { const tEntry = DiService.getEntry(handler.targetServiceId, handler.targetCtx); if (tEntry) { params[handler.index] = tEntry.object; } } }); if (entry.serviceClass) { const clazz = entry.serviceClass; entry.object = new (<any>clazz)(...params); } } catch (error) { this.get('Logger').then((log: any) => log.error(error)); } } if (entry.object === undefined) { entry.object = new (<any>entry.serviceClass)(); } const constructorHandlers = entry.constructorHandlers || []; const depsToBeInjectedBecouseVaration = entry.depsLeft ? entry.depsLeft.filter(dl => dl.variationVarName && dl.variationVarValue && constructorHandlers.findIndex(ch => ch.variationVarName === dl.variationVarName) < 0 ) : []; if (depsToBeInjectedBecouseVaration.length > 0) { depsToBeInjectedBecouseVaration.forEach(dep => { entry.object[dep.variationVarName || ''] = dep.variationVarValue; }); } DiService.updateEntry(entry, ctx); // Process ready this.processReadyService(entry, ctx) .then(() => { /* */ }) .catch(error => { this.get('Logger').then((log: any) => log.error(error)); }); } private static async processReadyService(entry: IDiEntry, ctx?: string) { const servicesToSetAsReady: { entry: IDiEntry; ctx: string }[] = []; if (entry.serviceClass && this.hasOnInit(entry.object)) { await entry.object.onInit(); } const matchedDeps = DiService.getAllRelatedDeps(entry.serviceId, ctx); Object.keys(matchedDeps).forEach(matCtx => { (<IDiEntry[]>matchedDeps[matCtx]).forEach(matEntry => { if (matEntry.depsLeft) { const dep = matEntry.depsLeft.find(depL => depL.targetServiceId === entry.serviceId); if (dep) { dep.depMet = true; } } if (this.hasAllDeps(matEntry)) { servicesToSetAsReady.push({ entry: matEntry, ctx: matCtx }); } else { DiService.updateEntry(matEntry, matCtx); } }); }); if (entry.cbWaiting) { entry.cbWaiting.forEach(callBack => { callBack(entry.object); }); // Only di.container manages entries so there are no races // eslint-disable-next-line require-atomic-updates entry.cbWaiting = undefined; } // eslint-disable-next-line require-atomic-updates entry.isReady = true; DiService.updateEntry(entry, ctx); for (const callback of this.onServiceReadyCallbacks) { try { callback(entry); } catch (error) { this.get('Logger').then((log: any) => log.error(error)); } } if (servicesToSetAsReady.length > 0) { servicesToSetAsReady.forEach(element => { this.setServiceAsReady(element.entry, element.ctx); }); } } /** * Registers a new pending request for the given service, * once the service is loaded all the requests will be executed * @param serviceName * @param ctx */ private static async waitForDep<T>(serviceName: string, ctx?: string, variation?: Record<string, any>) { const entry = DiService.getEnrySafely(serviceName, undefined, ctx); return new Promise<T>((resolve) => { const callBack = (resulutObj: any) => { resolve(resulutObj); }; if (entry.cbWaiting) { entry.cbWaiting.push(callBack); } else { entry.cbWaiting = [callBack]; } let isVariation = false; if ( variation && entry.serviceClass === undefined && serviceName.indexOf(DiService.variationStart) >= 0 && serviceName.indexOf(DiService.variationEnd) >= 0 ) { const service = DiService.getTemplateEntry(serviceName, ctx); if (service) { entry.serviceClass = service.serviceClass; entry.depsClosed = true; entry.constructorHandlers = service.constructorHandlers ? service.constructorHandlers.map(a => ObjectUtils.deepClone(a)) : undefined; entry.depsLeft = service.depsLeft ? service.depsLeft.map(a => ObjectUtils.deepClone(a)) : undefined; if (entry.depsLeft) { for (const depLeft of entry.depsLeft) { if (variation[depLeft.variationVarName || ''] !== undefined) { depLeft.depMet = true; depLeft.variationVarValue = variation[depLeft.variationVarName || '']; } } } if (entry.constructorHandlers) { for (const constructorHandler of entry.constructorHandlers) { if (variation[constructorHandler.variationVarName || ''] !== undefined) { constructorHandler.variationVarValue = variation[constructorHandler.variationVarName || '']; } } } isVariation = true; } } DiService.updateEntry(entry, ctx); if (isVariation) { this.checkIfReady(entry, ctx); } }); } private static hasOnInit(arg: Record<string, any>): arg is OnInit { return arg && (arg as OnInit).onInit !== undefined; } private static hasAllDeps(entry: IDiEntry): boolean { let result = false; if (entry.depsLeft && entry.depsClosed) { let allPropsAreTrue = true; entry.depsLeft.forEach(dep => { if (!dep.depMet) { allPropsAreTrue = false; } }); result = allPropsAreTrue; } else if (!entry.depsLeft) { result = true; } return result; } private static checkIfReady(entry: IDiEntry, ctx?: string) { if (this.hasAllDeps(entry)) { try { this.setServiceAsReady(entry, ctx); } catch (error) { this.get('Logger').then((log: any) => log.error(error)); } } } private static setServiceMetadata(clazz: ClassParameter<any>, serviceId: IServiceIdentifier, ctx?: string) { (<any>clazz)[this.serviceMetadata] = <IDiServiceMetadata>{ serviceId, ctx }; } private static updateDependenciesWithConnectionIfNecessary( deps: IDiEntry['constructorHandlers'] | IDiEntry['depsLeft'], connection?: string ) { if (connection && deps) { for (const dep of deps) { const targetService = DiService.getTemplateEntry(dep.targetServiceId, dep.targetCtx); if ( targetService && targetService.depsLeft && targetService.depsLeft.findIndex(d => d.variationVarName === Container.connection) >= 0 ) { const variation = { [Container.connection]: connection }; const variationTargetId = DiService.genServiceId(dep.targetServiceId, variation); dep.targetServiceId = variationTargetId; if (this.isConstructorHandler(dep)) { dep.variation = Object.assign(dep.variation ||{}, variation); } else if (!dep.depMet) { this.waitForDep(variationTargetId, dep.targetCtx, variation).then(); } } } } } private static isConstructorHandler(dep: IDiDepLeft | IDiConstructorHandler): dep is IDiConstructorHandler { return typeof (<any>dep).index === 'number' || false; } private static resolveServiceProperties(entry: IDiEntry, connection?: string) { if (entry.propertiesWaiting) { for (const propWaiting of entry.propertiesWaiting) { if (connection) { const targetServiceId = DiService.genServiceId(propWaiting.id); const targetService = DiService.getEntry(targetServiceId, propWaiting.ctx); // If we are setting the properties of a service with a connection // then the service id and varation of the dependency will change if ( targetService && targetService.depsLeft && targetService.depsLeft.findIndex(d => d.variationVarName === Container.connection) >= 0 ) { const variation = Object.assign(propWaiting.variation || {}, { [Container.connection]: connection }); const newTargetId = DiService.genServiceId(propWaiting.id, variation); Container.get(newTargetId, propWaiting.variation, propWaiting.ctx).then(propWaiting.cb); } else { Container.get(propWaiting.id, propWaiting.variation, propWaiting.ctx).then(propWaiting.cb); } } else { Container.get(propWaiting.id, propWaiting.variation, propWaiting.ctx).then(propWaiting.cb); } } } } }
the_stack
import {assert, assertNotReached} from '../assert.js'; import {reportError} from '../error.js'; import {Point} from '../geometry.js'; import { ErrorLevel, ErrorType, MimeType, } from '../type.js'; import {windowController} from '../window_controller.js'; import { CameraAppHelper, CameraAppHelperRemote, CameraIntentAction, CameraUsageOwnershipMonitorCallbackRouter, DocumentOutputFormat, ExternalScreenMonitorCallbackRouter, FileMonitorResult, Rotation, ScreenState, ScreenStateMonitorCallbackRouter, TabletModeMonitorCallbackRouter, } from './type.js'; import {wrapEndpoint} from './util.js'; /** * The singleton instance of ChromeHelper. Initialized by the first * invocation of getInstance(). */ let instance: ChromeHelper|null = null; /** * Forces casting type from Uint8Array to number[]. */ function castToNumberArray(data: Uint8Array): number[] { return data as unknown as number[]; } /** * Casts from rotation degrees to mojo rotation. */ function castToMojoRotation(rotation: number): Rotation { switch (rotation) { case 0: return Rotation.ROTATION_0; case 90: return Rotation.ROTATION_90; case 180: return Rotation.ROTATION_180; case 270: return Rotation.ROTATION_270; } assertNotReached(`Invalid rotation ${rotation}`); } /** * Communicates with Chrome. */ export class ChromeHelper { /** * An interface remote that is used to communicate with Chrome. */ private remote: CameraAppHelperRemote = wrapEndpoint(CameraAppHelper.getRemote()); /** * Starts tablet mode monitor monitoring tablet mode state of device. * * @param onChange Callback called each time when tablet mode state of device * changes with boolean parameter indicating whether device is entering * tablet mode. * @return Resolved to initial state of whether device is is in tablet mode. */ async initTabletModeMonitor(onChange: (isTablet: boolean) => void): Promise<boolean> { const monitorCallbackRouter = wrapEndpoint(new TabletModeMonitorCallbackRouter()); monitorCallbackRouter.update.addListener(onChange); const {isTabletMode} = await this.remote.setTabletMonitor( monitorCallbackRouter.$.bindNewPipeAndPassRemote()); return isTabletMode; } /** * Starts monitor monitoring system screen state of device. * * @param onChange Callback called each time when device screen state changes * with parameter of newly changed value. * @return Resolved to initial system screen state. */ async initScreenStateMonitor(onChange: (state: ScreenState) => void): Promise<ScreenState> { const monitorCallbackRouter = wrapEndpoint(new ScreenStateMonitorCallbackRouter()); monitorCallbackRouter.update.addListener(onChange); const {initialState} = await this.remote.setScreenStateMonitor( monitorCallbackRouter.$.bindNewPipeAndPassRemote()); return initialState; } /** * Starts monitor monitoring the existence of external screens. * @param onChange Callback called when the existence of external screens * changes. * @return Resolved to the initial state. */ async initExternalScreenMonitor( onChange: (hasExternalScreen: boolean) => void): Promise<boolean> { const monitorCallbackRouter = wrapEndpoint(new ExternalScreenMonitorCallbackRouter()); monitorCallbackRouter.update.addListener(onChange); const {hasExternalScreen} = await this.remote.setExternalScreenMonitor( monitorCallbackRouter.$.bindNewPipeAndPassRemote()); return hasExternalScreen; } /** * Checks if the device is under tablet mode currently. */ async isTabletMode(): Promise<boolean> { const {isTabletMode} = await this.remote.isTabletMode(); return isTabletMode; } /** * Starts camera usage monitor. */ async initCameraUsageMonitor( exploitUsage: () => Promise<void>, releaseUsage: () => Promise<void>): Promise<void> { const usageCallbackRouter = wrapEndpoint(new CameraUsageOwnershipMonitorCallbackRouter()); usageCallbackRouter.onCameraUsageOwnershipChanged.addListener( async (hasUsage) => { if (hasUsage) { await exploitUsage(); } else { await releaseUsage(); } }); const {isSuccess} = await this.remote.setCameraUsageMonitor( usageCallbackRouter.$.bindNewPipeAndPassRemote()); if (!isSuccess) { throw new Error('Failed to set camera usage monitor'); } let {controller} = await this.remote.getWindowStateController(); controller = wrapEndpoint(controller); await windowController.bind(controller); } /** * Triggers the begin of event tracing in Chrome. * @param event Name of the event. */ startTracing(event: string): void { this.remote.startPerfEventTrace(event); } /** * Triggers the end of event tracing in Chrome. * @param event Name of the event. */ stopTracing(event: string): void { this.remote.stopPerfEventTrace(event); } /** * Opens the file in Downloads folder by its |name| in gallery. * @param name Name of the target file. */ openFileInGallery(name: string): void { this.remote.openFileInGallery(name); } /** * Opens the chrome feedback dialog. * @param placeholder The text of the placeholder in the description * field. */ openFeedbackDialog(placeholder: string): void { this.remote.openFeedbackDialog(placeholder); } /** * Checks return value from |handleCameraResult|. * @param caller Caller identifier. */ private async checkReturn( caller: string, value: Promise<{isSuccess: boolean}>): Promise<void> { const {isSuccess} = await value; if (!isSuccess) { reportError( ErrorType.HANDLE_CAMERA_RESULT_FAILURE, ErrorLevel.ERROR, new Error(`Return not isSuccess from calling intent ${caller}.`)); } } /** * Notifies ARC++ to finish the intent. * @param intentId Intent id of the intent to be finished. */ async finish(intentId: number): Promise<void> { const ret = this.remote.handleCameraResult(intentId, CameraIntentAction.FINISH, []); await this.checkReturn('finish()', ret); } /** * Notifies ARC++ to append data to intent result. * @param intentId Intent id of the intent to be appended data to. * @param data The data to be appended to intent result. */ async appendData(intentId: number, data: Uint8Array): Promise<void> { const ret = this.remote.handleCameraResult( intentId, CameraIntentAction.APPEND_DATA, castToNumberArray(data)); await this.checkReturn('appendData()', ret); } /** * Notifies ARC++ to clear appended intent result data. * @param intentId Intent id of the intent to be cleared its result. */ async clearData(intentId: number): Promise<void> { const ret = this.remote.handleCameraResult( intentId, CameraIntentAction.CLEAR_DATA, []); await this.checkReturn('clearData()', ret); } /** * Checks if the logging consent option is enabled. */ async isMetricsAndCrashReportingEnabled(): Promise<boolean> { const {isEnabled} = await this.remote.isMetricsAndCrashReportingEnabled(); return isEnabled; } /** * Sends the broadcast to ARC to notify the new photo/video is captured. */ async sendNewCaptureBroadcast( {isVideo, name}: {isVideo: boolean, name: string}): Promise<void> { this.remote.sendNewCaptureBroadcast(isVideo, name); } /** * Monitors for the file deletion of the file given by its |name| and triggers * |callback| when the file is deleted. Note that a previous monitor request * will be canceled once another monitor request is sent. * @param name The name of the file to monitor. * @param callback Function to trigger when deletion. * @return Resolved when the file is deleted or the current monitor is * canceled by future monitor call. * @throws {!Error} When error occurs during monitor. */ async monitorFileDeletion(name: string, callback: () => void): Promise<void> { const {result} = await this.remote.monitorFileDeletion(name); switch (result) { case FileMonitorResult.DELETED: callback(); return; case FileMonitorResult.CANCELED: // Do nothing if it is canceled by another monitor call. return; case FileMonitorResult.ERROR: throw new Error('Error happens when monitoring file deletion'); } } /** * Returns true if the document mode is supported on the device. */ async isDocumentModeSupported(): Promise<boolean> { const {isSupported} = await this.remote.isDocumentModeSupported(); return isSupported; } /** * Scans the blob data and returns the detected document corners. * @param blob * @return Promise resolve to positions of document corner. Null for failing * to detected corner positions. */ async scanDocumentCorners(blob: Blob): Promise<Point[]|null> { const buffer = new Uint8Array(await blob.arrayBuffer()); const {corners} = await this.remote.scanDocumentCorners(castToNumberArray(buffer)); if (corners.length === 0) { return null; } return corners.map(({x, y}) => new Point(x, y)); } /** * Converts the blob to document given by its |blob| data, |resolution| and * target |corners| to crop. The output will be converted according to given * |mimeType|. */ async convertToDocument( blob: Blob, corners: Point[], rotation: number, mimeType: MimeType): Promise<Blob> { assert(corners.length === 4, 'Unexpected amount of corners'); const buffer = new Uint8Array(await blob.arrayBuffer()); let outputFormat; if (mimeType === MimeType.JPEG) { outputFormat = DocumentOutputFormat.JPEG; } else if (mimeType === MimeType.PDF) { outputFormat = DocumentOutputFormat.PDF; } else { throw new Error(`Output mimetype unsupported: ${mimeType}`); } const {docData} = await this.remote.convertToDocument( castToNumberArray(buffer), corners, castToMojoRotation(rotation), outputFormat); return new Blob([new Uint8Array(docData)], {type: mimeType}); } /** * Converts given |jpegData| to PDF format. * @param jpegBlob Blob in JPEG format. * @return Blob in PDF format. */ async convertToPdf(jpegBlob: Blob): Promise<Blob> { const buffer = new Uint8Array(await jpegBlob.arrayBuffer()); const {pdfData} = await this.remote.convertToPdf(castToNumberArray(buffer)); return new Blob([new Uint8Array(pdfData)], {type: MimeType.PDF}); } /** * Creates a new instance of ChromeHelper if it is not set. Returns the * exist instance. * @return The singleton instance. */ static getInstance(): ChromeHelper { if (instance === null) { instance = new ChromeHelper(); } return instance; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as k8s from "@pulumi/kubernetes"; import * as rbac from "./rbac"; import { config } from "./config"; // TODO: import from a persisent package location import * as kx from "../../../kx"; export type NginxIngressControllerOptions = { namespace?: pulumi.Input<string>; provider?: k8s.Provider; nginxReplicas?: pulumi.Input<number>; ingressClass?: pulumi.Input<string>; svcPortType?: pulumi.Input<string>; svcPorts?: pulumi.Input<any>; }; const pulumiComponentNamespace: string = "pulumi:kx:NginxIngressController"; // Assemble the resources. const resources = { limits: {cpu: "256m", memory: "256Mi"}, requests: { cpu: "256m", memory: "256Mi"}, }; // Assemble the defaultHttpBackend resources. const defaultHttpBackendResources = { limits: {cpu: "10m", memory: "20Mi"}, requests: { cpu: "10m", memory: "20Mi"}, }; export class NginxIngressController extends pulumi.ComponentResource { public readonly serviceAccount: k8s.core.v1.ServiceAccount; public readonly serviceAccountName: pulumi.Output<string>; public readonly clusterRole: k8s.rbac.v1.ClusterRole; public readonly clusterRoleName: pulumi.Output<string>; public readonly role: k8s.rbac.v1.Role; public readonly roleName: pulumi.Output<string>; public readonly clusterRoleBinding: k8s.rbac.v1.ClusterRoleBinding; public readonly roleBinding: k8s.rbac.v1.RoleBinding; public readonly defaultBackendService: k8s.core.v1.Service; public readonly defaultBackendServiceName: pulumi.Output<string>; public readonly defaultBackendDeployment: k8s.apps.v1.Deployment; public readonly defaultBackendDeploymentName: pulumi.Output<string>; public readonly service: k8s.core.v1.Service; public readonly serviceName: pulumi.Output<string>; public readonly deployment: k8s.apps.v1.Deployment; constructor( name: string, args: NginxIngressControllerOptions = {}, opts?: pulumi.ComponentResourceOptions, ) { super(pulumiComponentNamespace, name, args, opts); if (args.namespace === undefined || args.provider === undefined || args.nginxReplicas === undefined || args.ingressClass === undefined || args.svcPortType === undefined || args.svcPorts === undefined ) { return {} as NginxIngressController; } const appName = kx.utils.trimString(`${name}`.toLowerCase(), 40); const defaultHttpBackendName = "nginx-default-http-backend"; const defaultBackendAppLabels = { app: defaultHttpBackendName}; const nginxAppLabels = { app: appName }; // ServiceAccount this.serviceAccount = rbac.makeNginxServiceAccount( name, args.provider, args.namespace); this.serviceAccountName = this.serviceAccount.metadata.apply(m => m.name); // RBAC ClusterRole & Role this.clusterRole = rbac.makeNginxClusterRole( name, args.provider); this.clusterRoleName = this.clusterRole.metadata.apply(m => m.name); this.clusterRoleBinding = rbac.makeNginxClusterRoleBinding( name, args.provider, args.namespace, this.serviceAccountName, this.clusterRoleName); this.role = rbac.makeNginxRole( name, args.provider, args.namespace, args.ingressClass); this.roleName = this.role.metadata.apply(m => m.name); this.roleBinding = rbac.makeNginxRoleBinding( name, args.provider, args.namespace, this.serviceAccountName, this.roleName); // Backend Deployment and Service this.defaultBackendService = makeNginxDefaultBackendService( defaultHttpBackendName, args.provider, defaultBackendAppLabels, args.namespace); this.defaultBackendServiceName = this.defaultBackendService.metadata.apply(m => m.name); this.defaultBackendDeployment = makeNginxDefaultBackendDeployment( defaultHttpBackendName, args.provider, defaultBackendAppLabels, args.namespace); this.defaultBackendDeploymentName = this.defaultBackendDeployment.metadata.apply(m => m.name); // Deployment and Service this.service = makeNginxService( appName, args.provider, nginxAppLabels, args.namespace, args.svcPortType, args.svcPorts); this.serviceName = this.service.metadata.apply(m => m.name); this.deployment = makeNginxDeployment( appName, args.provider, nginxAppLabels, args.nginxReplicas, args.namespace, args.ingressClass, this.serviceAccountName, this.defaultBackendServiceName, this.serviceName); } } // Create a default-http-backend Service. export function makeNginxDefaultBackendService( name: string, provider: k8s.Provider, labels: pulumi.Input<any>, namespace: pulumi.Input<string>): k8s.core.v1.Service { return new k8s.core.v1.Service( name, { metadata: { labels: labels, namespace: namespace, }, spec: { type: "ClusterIP", ports: [ { port: 80, protocol: "TCP", targetPort: "http", }, ], selector: labels, }, }, { provider: provider, }, ); } // Create a default-http-backend Deployment. export function makeNginxDefaultBackendDeployment( name: string, provider: k8s.Provider, labels: pulumi.Input<any>, namespace: pulumi.Input<string>): k8s.apps.v1.Deployment { // Define the Pod args. const podBuilder = new kx.PodBuilder(name, provider, { podSpec: { containers: [{ name: name, // Any image is permissable as long as: // 1. It serves a 404 page at / // 2. It serves 200 on a /healthz endpoint image: config.defaultBackendImage, resources: defaultHttpBackendResources, ports: [{ name: "http", containerPort: 8080 }], readinessProbe: { httpGet: { path: "/healthz", port: 8080, scheme: "HTTP", }, }, livenessProbe: { httpGet: { path: "/healthz", port: 8080, scheme: "HTTP", }, initialDelaySeconds: 30, timeoutSeconds: 5, }, }], }, }) .withMetadata({ labels: labels, namespace: namespace, }); // Create the Deployment. return podBuilder.createDeployment(name, { replicas: 1 }); } // Create a Service. export function makeNginxService( name: string, provider: k8s.Provider, labels: pulumi.Input<any>, namespace: pulumi.Input<string>, svcType: pulumi.Input<string>, svcPorts: pulumi.Input<any>): k8s.core.v1.Service { return new k8s.core.v1.Service( name, { metadata: { labels: labels, namespace: namespace, annotations: { "pulumi.com/skipAwait": "true", }, }, spec: { type: svcType, ports: svcPorts, selector: labels, }, }, { provider: provider, }, ); } // Create a Deployment. export function makeNginxDeployment( name: string, provider: k8s.Provider, labels: pulumi.Input<any>, nginxReplicas: pulumi.Input<number>, namespace: pulumi.Input<string>, ingressClass: pulumi.Input<string>, serviceAccountName: pulumi.Input<string>, defaultBackendServiceName: pulumi.Input<string>, serviceName: pulumi.Input<string>): k8s.apps.v1.Deployment { // Define the Pod args. const podBuilder = new kx.PodBuilder(name, provider, { podSpec: { serviceAccountName: serviceAccountName, terminationGracePeriodSeconds: 60, containers: [ { name: name, image: config.appImage, ports: [{ name: "http", containerPort: 80 }], readinessProbe: { httpGet: { path: "/healthz", port: 10254, scheme: "HTTP", }, }, livenessProbe: { httpGet: { path: "/healthz", port: 10254, scheme: "HTTP", }, initialDelaySeconds: 10, timeoutSeconds: 1, }, // For more info on all CLI args available: // https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/cli-arguments.md args: pulumi.all([ "/nginx-ingress-controller", pulumi.concat( "--default-backend-service=$(POD_NAMESPACE)/", defaultBackendServiceName, ), "--ingress-class=" + ingressClass, pulumi.concat( "--publish-service=$(POD_NAMESPACE)/", serviceName, ), ]), }, ], }, }) .withMetadata({ labels: labels, annotations: { "prometheus.io/port": "10254", "prometheus.io/scrape": "true", }, namespace: namespace, }); // Create the Deployment. return podBuilder.createDeployment(name, { replicas: 2 }); }
the_stack
declare module 'ember-cli/lib/broccoli/ember-app' { import { Node as BroccoliNode } from 'broccoli-node-api'; import CoreObject from 'core-object'; import Project from 'ember-cli/lib/models/project'; export default class EmberApp extends CoreObject { options: Record<string, unknown>; name: string; project: Project; isProduction: boolean; addonTree(): BroccoliNode; } } declare module 'ember-cli/lib/models/addon' { import { Node as BroccoliNode } from 'broccoli-node-api'; import CoreObject, { ExtendOptions } from 'core-object'; import UI from 'console-ui'; import { Application } from 'express'; import Project from 'ember-cli/lib/models/project'; import Command from 'ember-cli/lib/models/command'; import EmberApp from 'ember-cli/lib/broccoli/ember-app'; import PreprocessRegistry from 'ember-cli-preprocess-registry'; type Nullable<T> = T | null | undefined; type Tree = BroccoliNode | string; export type ThisAddon<T> = T & Addon & {_super: Addon}; export type AddonImplementation<A = {}> = AddonInterface<A> & A; export interface AddonInterface<A = {}> { name: string; /** * Initializes the addon. If you override this method make sure and call this._super.init && this._super.init.apply(this, arguments); or your addon will not work. */ init?(this: ThisAddon<A>, parent: Addon | EmberApp, project: Project): void; /** * Returns the module name for this addon. */ moduleName?(this: ThisAddon<A>): string; /** * Returns the path for addon blueprints. */ blueprintsPath?(this: ThisAddon<A>): string; /** * Augments the applications configuration settings. */ config?(this: ThisAddon<A>, env: string, baseConfig: EmberConfig): EmberConfig; /** * The addon's dependencies based on the addon's package.json */ dependencies?(this: ThisAddon<A>); /** * Return true if the addon is using module unification. */ isModuleUnification?(this: ThisAddon<A>): boolean; /** * Find an addon of the current addon. */ findOwnAddonByName?(this: ThisAddon<A>, name: string): EmberAddon; /** * Check if the current addon intends to be hinted. Typically this is for hinting/linting libraries such as eslint or jshint. */ hintingEnabled?(this: ThisAddon<A>): boolean; /** * Allows to mark the addon as developing, triggering live-reload in the project the addon is linked to. */ isDevelopingAddon?(this: ThisAddon<A>): boolean; /** * Returns a given type of tree (if present), merged with the application tree. For each of the trees available using this method, you can also use a direct method called treeFor[Type] (eg. treeForApp). */ treeFor?(this: ThisAddon<A>, name): Tree; /** * Calculates a cacheKey for the given treeType. It is expected to return a cache key allowing multiple builds of the same tree to simply return the original tree (preventing duplicate work). If it returns null / undefined the tree in question will opt out of this caching system. */ cacheKeyForTree?(this: ThisAddon<A>, treeType: TreeTypes): string; /** * Imports an asset into the app. */ import?(this: ThisAddon<A>, asset: string, options?: OpenObject): void; /** * Returns the tree for all app files */ treeForApp?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for app template files. */ treeForTemplates?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for this addon's templates. */ treeForAddonTemplates?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * Returns a tree for this addon */ treeForAddon?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for app style files. */ treeForStyles?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for all public files. */ treeForPublic?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for all test support files. */ treeForTestSupport?(this: ThisAddon<A>, tree): Tree /** * Returns the tree for all vendor files. */ treeForVendor?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree> /** * Returns the tree for all test files namespaced to a given addon. */ treeForAddonTestSupport?(this: ThisAddon<A>, tree: Nullable<Tree>): Nullable<Tree>; /** * compiles this addon's styles, the output tree has css files. * @private but useful */ compileStyles?(this: ThisAddon<A>, addonStylesTree: Nullable<Tree>): Nullable<Tree>; /** * Compiles this addon's templates, the output tree has js files. * @private but useful */ compileTemplates?(this: ThisAddon<A>, addonTree: Nullable<Tree>): Nullable<Tree>; /** * Compiles this addon's js, the output tree has gone through babel. * @private but useful */ processedAddonJsFiles?(this: ThisAddon<A>, addonTree: Nullable<Tree>): Nullable<Tree>; /** * Is the addon enabled? */ isEnabled?(this: ThisAddon<A>): boolean; /** * Can be used to exclude addons from being added as a child addon. */ shouldIncludeChildAddon?(this: ThisAddon<A>, addon: Addon): boolean; /** * This method is called when the addon is included in a build. You would typically use this hook to perform additional imports. */ included?(this: ThisAddon<A>, includer: Project | Addon): void; /** * Allows the specification of custom addon commands. Expects you to return an object whose key is the name of the command and value is the command instance. */ includedCommands?(this: ThisAddon<A>): Record<string, typeof Command | ExtendOptions<Command>> | void; /** * This hook allows you to make changes to the express server run by ember-cli. */ serverMiddleware?(this: ThisAddon<A>, options: { app: Application }): void | Promise<void>; /** * This hook allows you to make changes to the express server run by testem. */ testemMiddleware?(this: ThisAddon<A>, app: Application): void; /** * Used to add preprocessors to the preprocessor registry. This is often used by addons like ember-cli-htmlbars and ember-cli-coffeescript to add a template or js preprocessor to the registry. */ setupPreprocessorRegistry?(this: ThisAddon<A>, type: 'self' | 'parent', registry: PreprocessRegistry): void; /** * This hook is called when an error occurs during the preBuild, postBuild or outputReady hooks for addons, or when the build fails. * @param error */ buildError?(this: ThisAddon<A>, error: Error): void; /** * Allow addons to implement contentFor method to add string output into the associated {{content-for 'foo'}} section in index.html */ contentFor?(this: ThisAddon<A>, type, config, content): void; /** * Allows addons to define a custom transfrom function that other addons and app can use when using app.import. */ importTransforms?(this: ThisAddon<A>): Object; /** * Return value is merged into the tests tree. This lets you inject linter output as test results. */ lintTree?(this: ThisAddon<A>, treeType: string, tree: Tree): Tree; /** * This hook is called after the build has been processed and the build files have been copied to the output directory. */ outputReady?(this: ThisAddon<A>, result: any): void; /** * This hook is called after a build is complete. */ postBuild?(this: ThisAddon<A>, result: unknown): void; /** * Post-process a tree. */ postprocessTree?(this: ThisAddon<A>, type: "css" | "template" | "js", tree: Tree): Tree /** * This hook is called before a build takes place. */ preBuild?(this: ThisAddon<A>, result: unknown): void; /** * Pre-process a tree. */ preprocessTree?(this: ThisAddon<A>, type: "css" | "template" | "js", tree: Tree): Tree; } export default class Addon extends CoreObject { name: string; root: string; app?: EmberApp; parent: Addon | Project; project: Project; addons: Addon[]; ui: UI; options?: Record<string, unknown>; pkg: { name: string; version: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; }; /** * Initializes the addon. If you override this method make sure and call this._super.init && this._super.init.apply(this, arguments); or your addon will not work. */ init(parent: Addon | EmberApp, project: Project): void; /** * Returns the module name for this addon. */ moduleName(): string; /** * Returns the path for addon blueprints. */ blueprintsPath(): string; /** * Augments the applications configuration settings. */ config?(env: string, baseConfig: EmberConfig): EmberConfig; /** * The addon's dependencies based on the addon's package.json */ dependencies(); /** * Return true if the addon is using module unification. */ isModuleUnification(): boolean; /** * Find an addon of the current addon. */ findOwnAddonByName(name: string): EmberAddon; /** * Check if the current addon intends to be hinted. Typically this is for hinting/linting libraries such as eslint or jshint. */ hintingEnabled(): boolean; /** * Allows to mark the addon as developing, triggering live-reload in the project the addon is linked to. */ isDevelopingAddon(): boolean; /** * Returns a given type of tree (if present), merged with the application tree. For each of the trees available using this method, you can also use a direct method called treeFor[Type] (eg. treeForApp). */ treeFor(name): Tree; /** * Calculates a cacheKey for the given treeType. It is expected to return a cache key allowing multiple builds of the same tree to simply return the original tree (preventing duplicate work). If it returns null / undefined the tree in question will opt out of this caching system. */ cacheKeyForTree(treeType: TreeTypes): String /** * @private but useful */ _findHost(): EmberApp; /** * Imports an asset into the app. */ import(asset: string, options?: OpenObject): void; /** * Returns the tree for all app files */ treeForApp(tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for app template files. */ treeForTemplates(tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for this addon's templates. */ treeForAddonTemplates(tree: Nullable<Tree>): Nullable<Tree>; /** * Returns a tree for this addon */ treeForAddon(tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for app style files. */ treeForStyles(tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for all public files. */ treeForPublic(tree: Nullable<Tree>): Nullable<Tree>; /** * Returns the tree for all test support files. */ treeForTestSupport(tree: Nullable<Tree>): Nullable<Tree> /** * Returns the tree for all vendor files. */ treeForVendor(tree: Nullable<Tree>): Nullable<Tree> /** * Returns the tree for all test files namespaced to a given addon. */ treeForAddonTestSupport(tree: Nullable<Tree>): Nullable<Tree>; /** * compiles this addon's styles, the output tree has css files. * @private but useful */ compileStyles(addonStylesTree: Nullable<Tree>): Nullable<Tree>; /** * Compiles this addon's templates, the output tree has js files. * @private but useful */ compileTemplates(addonTree: Nullable<Tree>): Nullable<Tree>; /** * Compiles this addon's js, the output tree has gone through babel. * @private but useful */ processedAddonJsFiles(addonTree: Nullable<Tree>): Nullable<Tree>; /** * Is the addon enabled? */ isEnabled(): boolean; /** * Can be used to exclude addons from being added as a child addon. */ shouldIncludeChildAddon(addon: Addon): boolean; /** * This method is called when the addon is included in a build. You would typically use this hook to perform additional imports. */ included(includer: Project | Addon): void; /** * This structure represents the paths to use to use when `treeFor(TreeType)` is called, the paths are relative to the addon's own `this.root`. */ treePaths: { app: string; styles: string; templates: string; addon: string; 'addon-styles': string; 'addon-templates': string; vendor: string; 'test-support': string; 'addon-test-support': string; public: string; } } } declare module 'ember-cli/lib/models/blueprint' { class Blueprint { taskFor(taskName: string): void; } export = Blueprint; } declare module 'ember-cli/lib/models/command' { import CoreObject from 'core-object'; import UI from 'console-ui'; import Project from 'ember-cli/lib/models/project'; interface CommandOption { name: string; type: unknown; description?: string; required?: boolean; default?: unknown; aliases?: string[]; } export default class Command extends CoreObject { name: string; works: 'insideProject' | 'outsideProject' | 'everywhere'; description: string; availableOptions: CommandOption[]; anonymousOptions: string[]; ui: UI; project: Project; run(options: {}): void | Promise<unknown>; } } declare module 'ember-cli/lib/models/project' { import CoreObject from 'core-object'; import UI from 'console-ui'; import Addon from 'ember-cli/lib/models/addon'; export default class Project extends CoreObject { ui: UI; root: string; addons: Addon[]; pkg: { name: string; version: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string>; }; name(): string; isEmberCLIAddon(): boolean; require(module: string): unknown; findAddonByName(name): Addon; } }
the_stack
import { BaseResource } from 'ms-rest-azure'; import { CloudError } from 'ms-rest-azure'; import * as moment from 'moment'; export { BaseResource } from 'ms-rest-azure'; export { CloudError } from 'ms-rest-azure'; /** * @class * Initializes a new instance of the Resource class. * @constructor * Base resource object. * * @member {string} [id] ID of the resource. * @member {string} [name] Name of the resource. * @member {string} [type] Type of Resource. * @member {object} [tags] Custom tags for the resource. * @member {string} [etag] The entity tag used for optimistic concurency when * modifying the resource. */ export interface Resource extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; tags?: { [propertyName: string]: string }; etag?: string; } /** * @class * Initializes a new instance of the Display class. * @constructor * Contains the localized display information for this particular operation or * action. * * @member {string} [provider] The localized, friendly version of the resource * provider name. * @member {string} [resource] The localized, friendly version of the resource * type related to this action or operation; the resource type should match the * public documentation for the resource provider. * @member {string} [operation] The localized, friendly name for the operation. * Use the name as it will displayed to the user. * @member {string} [description] The localized, friendly description for the * operation. The description will be displayed to the user. It should be * thorough and concise for used in both tooltips and detailed views. */ export interface Display { provider?: string; resource?: string; operation?: string; description?: string; } /** * @class * Initializes a new instance of the Operation class. * @constructor * Describes the supported REST operation. * * @member {string} [name] The name of the operation being performed on this * particular object. * @member {object} [display] Contains the localized display information for * this particular operation or action. * @member {string} [display.provider] The localized, friendly version of the * resource provider name. * @member {string} [display.resource] The localized, friendly version of the * resource type related to this action or operation; the resource type should * match the public documentation for the resource provider. * @member {string} [display.operation] The localized, friendly name for the * operation. Use the name as it will displayed to the user. * @member {string} [display.description] The localized, friendly description * for the operation. The description will be displayed to the user. It should * be thorough and concise for used in both tooltips and detailed views. * @member {string} [origin] The intended executor of the operation. */ export interface Operation { name?: string; display?: Display; origin?: string; } /** * @class * Initializes a new instance of the OsDiskImage class. * @constructor * OS disk image. * * @member {string} [operatingSystem] OS operating system type. Possible values * include: 'None', 'Windows', 'Linux' * @member {string} [sourceBlobSasUri] SAS key for source blob. */ export interface OsDiskImage { readonly operatingSystem?: string; readonly sourceBlobSasUri?: string; } /** * @class * Initializes a new instance of the DataDiskImage class. * @constructor * Data disk image. * * @member {number} [lun] The LUN. * @member {string} [sourceBlobSasUri] SAS key for source blob. */ export interface DataDiskImage { readonly lun?: number; readonly sourceBlobSasUri?: string; } /** * @class * Initializes a new instance of the ExtendedProduct class. * @constructor * Extended description about the product required for installing it into Azure * Stack. * * @member {string} [galleryPackageBlobSasUri] The URI to the .azpkg file that * provides information required for showing product in the gallery. * @member {string} [productKind] Specifies the kind of the product * (virtualMachine or virtualMachineExtension). * @member {string} [computeRole] Specifies kind of compute role inclided in * the package. Possible values include: 'None', 'IaaS', 'PaaS' * @member {boolean} [isSystemExtension] Specifies if product is a Virtual * Machine Extension. * @member {string} [uri] The URI. * @member {boolean} [supportMultipleExtensions] Indicates if specified product * supports multiple extensions. * @member {string} [version] Specifies product version. * @member {string} [vmOsType] Specifies operating system used by the product. * Possible values include: 'None', 'Windows', 'Linux' * @member {boolean} [vmScaleSetEnabled] Indicates if virtual machine Scale Set * is enabled in the specified product. * @member {object} [osDiskImage] OS disk image used by product. * @member {string} [osDiskImage.operatingSystem] OS operating system type. * Possible values include: 'None', 'Windows', 'Linux' * @member {string} [osDiskImage.sourceBlobSasUri] SAS key for source blob. * @member {array} [dataDiskImages] List of attached data disks. */ export interface ExtendedProduct { readonly galleryPackageBlobSasUri?: string; readonly productKind?: string; readonly computeRole?: string; readonly isSystemExtension?: boolean; readonly uri?: string; readonly supportMultipleExtensions?: boolean; readonly version?: string; readonly vmOsType?: string; readonly vmScaleSetEnabled?: boolean; readonly osDiskImage?: OsDiskImage; readonly dataDiskImages?: DataDiskImage[]; } /** * @class * Initializes a new instance of the VirtualMachineExtensionProductProperties class. * @constructor * Product information. * * @member {string} [computeRole] Specifies kind of compute role inclided in * the package. Possible values include: 'None', 'IaaS', 'PaaS' * @member {boolean} [isSystemExtension] Specifies if product is a Virtual * Machine Extension. * @member {string} [uri] The URI. * @member {boolean} [supportMultipleExtensions] Indicates if specified product * supports multiple extensions. * @member {string} [version] Specifies product version. * @member {string} [vmOsType] Specifies operating system used by the product. * Possible values include: 'None', 'Windows', 'Linux' * @member {boolean} [vmScaleSetEnabled] Indicates if virtual machine Scale Set * is enabled in the specified product. */ export interface VirtualMachineExtensionProductProperties { readonly computeRole?: string; readonly isSystemExtension?: boolean; readonly uri?: string; readonly supportMultipleExtensions?: boolean; readonly version?: string; readonly vmOsType?: string; readonly vmScaleSetEnabled?: boolean; } /** * @class * Initializes a new instance of the VirtualMachineProductProperties class. * @constructor * Product information. * * @member {string} [version] Specifies product version. * @member {object} [osDiskImage] OS disk image used by product. * @member {string} [osDiskImage.operatingSystem] OS operating system type. * Possible values include: 'None', 'Windows', 'Linux' * @member {string} [osDiskImage.sourceBlobSasUri] SAS key for source blob. * @member {array} [dataDiskImages] List of attached data disks. */ export interface VirtualMachineProductProperties { readonly version?: string; readonly osDiskImage?: OsDiskImage; readonly dataDiskImages?: DataDiskImage[]; } /** * @class * Initializes a new instance of the IconUris class. * @constructor * Links to product icons. * * @member {string} [large] URI to large icon. * @member {string} [wide] URI to wide icon. * @member {string} [medium] URI to medium icon. * @member {string} [small] URI to small icon. * @member {string} [hero] URI to hero icon. */ export interface IconUris { large?: string; wide?: string; medium?: string; small?: string; hero?: string; } /** * @class * Initializes a new instance of the ProductLink class. * @constructor * Link with additional information about a product. * * @member {string} [displayName] The description of the link. * @member {string} [uri] The URI corresponding to the link. */ export interface ProductLink { displayName?: string; uri?: string; } /** * @class * Initializes a new instance of the ProductProperties class. * @constructor * Additional properties of the product * * @member {string} [version] The version. */ export interface ProductProperties { version?: string; } /** * @class * Initializes a new instance of the Product class. * @constructor * Product information. * * @member {string} [displayName] The display name of the product. * @member {string} [description] The description of the product. * @member {string} [publisherDisplayName] The user-friendly name of the * product publisher. * @member {string} [publisherIdentifier] Publisher identifier. * @member {string} [offer] The offer representing the product. * @member {string} [offerVersion] The version of the product offer. * @member {string} [sku] The product SKU. * @member {string} [billingPartNumber] The part number used for billing * purposes. * @member {string} [vmExtensionType] The type of the Virtual Machine * Extension. * @member {string} [galleryItemIdentity] The identifier of the gallery item * corresponding to the product. * @member {object} [iconUris] Additional links available for this product. * @member {string} [iconUris.large] URI to large icon. * @member {string} [iconUris.wide] URI to wide icon. * @member {string} [iconUris.medium] URI to medium icon. * @member {string} [iconUris.small] URI to small icon. * @member {string} [iconUris.hero] URI to hero icon. * @member {array} [links] Additional links available for this product. * @member {string} [legalTerms] The legal terms. * @member {string} [privacyPolicy] The privacy policy. * @member {number} [payloadLength] The length of product content. * @member {string} [productKind] The kind of the product (virtualMachine or * virtualMachineExtension) * @member {object} [productProperties] Additional properties for the product. * @member {string} [productProperties.version] The version. */ export interface Product extends Resource { displayName?: string; description?: string; publisherDisplayName?: string; publisherIdentifier?: string; offer?: string; offerVersion?: string; sku?: string; billingPartNumber?: string; vmExtensionType?: string; galleryItemIdentity?: string; iconUris?: IconUris; links?: ProductLink[]; legalTerms?: string; privacyPolicy?: string; payloadLength?: number; productKind?: string; productProperties?: ProductProperties; } /** * @class * Initializes a new instance of the Registration class. * @constructor * Registration information. * * @member {string} [objectId] The object identifier associated with the Azure * Stack connecting to Azure. * @member {string} [cloudId] The identifier of the registered Azure Stack. * @member {string} [billingModel] Specifies the billing mode for the Azure * Stack registration. */ export interface Registration extends Resource { objectId?: string; cloudId?: string; billingModel?: string; } /** * @class * Initializes a new instance of the ActivationKeyResult class. * @constructor * The resource containing the Azure Stack activation key. * * @member {string} [activationKey] Azure Stack activation key. */ export interface ActivationKeyResult { activationKey?: string; } /** * @class * Initializes a new instance of the RegistrationParameter class. * @constructor * Registration resource * * @member {string} registrationToken The token identifying registered Azure * Stack */ export interface RegistrationParameter extends Resource { registrationToken: string; } /** * @class * Initializes a new instance of the CustomerSubscription class. * @constructor * Customer subcription. * * @member {string} [tenantId] Tenant Id. */ export interface CustomerSubscription extends Resource { tenantId?: string; } /** * @class * Initializes a new instance of the OperationList class. * @constructor * List of Operations * * @member {string} [nextLink] URI to the next page of operations. */ export interface OperationList extends Array<Operation> { nextLink?: string; } /** * @class * Initializes a new instance of the ProductList class. * @constructor * Pageable list of products. * * @member {string} [nextLink] URI to the next page. */ export interface ProductList extends Array<Product> { nextLink?: string; } /** * @class * Initializes a new instance of the RegistrationList class. * @constructor * Pageable list of registrations. * * @member {string} [nextLink] URI to the next page. */ export interface RegistrationList extends Array<Registration> { nextLink?: string; } /** * @class * Initializes a new instance of the CustomerSubscriptionList class. * @constructor * Pageable list of customer subscriptions. * * @member {string} [nextLink] URI to the next page. */ export interface CustomerSubscriptionList extends Array<CustomerSubscription> { nextLink?: string; }
the_stack
import { cloneNode, getScrollingParent, getContainerGridGap, getEdgeOffset, getElementMargin, getPosition, setStyle, setTransitionDuration, setTranslate3d, addEventListener, removeEventListener, IBrowserEvent, } from './utils'; import { ISortableElement, IAxis, IPosition, IBounds, IOffset, ISortChange, } from './types'; import AutoScroller from './AutoScroller'; import Manager from './Manager'; interface ISorterOptions { manager: Manager; container: HTMLElement; el: ISortableElement; axis: IAxis; onComplete: (change: ISortChange) => void | Promise<any>; transitionDuration: number; event: IBrowserEvent; } export default class Sorter { manager: Manager; container: HTMLElement; el: HTMLElement; axis: IAxis; onComplete: (change: ISortChange) => void | Promise<any>; transitionDuration: number; initalIndex: number; newIndex: number | null; contentWindow: Window; scrollContainer: HTMLElement; margin: IPosition; elBounds: IBounds; containerBounds: IBounds; baseHelperX: number; baseHelperY: number; baseX: number; baseY: number; helper: HTMLElement; offset: IPosition = { x: 0, y: 0 }; autoScroller: AutoScroller; listenerNode: HTMLElement | Window; constructor({ manager, container, el, axis, onComplete, transitionDuration, event, }: ISorterOptions) { this.manager = manager; this.el = el; this.axis = axis; this.onComplete = onComplete; this.transitionDuration = transitionDuration; this.container = container; this.initalIndex = this.newIndex = el.sortableInfo.index; this.contentWindow = (container.ownerDocument || document).defaultView || window; this.scrollContainer = getScrollingParent(container) || container; const margin = getElementMargin(el); const gridGap = getContainerGridGap(container); const elBounds = el.getBoundingClientRect(); this.elBounds = elBounds; this.margin = { x: elBounds.width + margin.left + margin.right + gridGap.x, y: elBounds.height + Math.max(margin.top, margin.bottom, gridGap.y), }; this.containerBounds = this.scrollContainer.getBoundingClientRect(); const initialOffset = getPosition(event); const offsetEdge = getEdgeOffset(el, container); this.baseHelperX = this.contentWindow.pageXOffset - initialOffset.x; this.baseHelperY = this.contentWindow.pageYOffset - initialOffset.y; this.baseX = offsetEdge.left - this.scrollContainer.scrollLeft - initialOffset.x; this.baseY = offsetEdge.top - this.scrollContainer.scrollTop - initialOffset.y; this.helper = document.body.appendChild(cloneNode(el)) as HTMLElement; setStyle(this.helper, { boxSizing: 'border-box', height: `${elBounds.height}px`, left: `${elBounds.left - margin.left}px`, pointerEvents: 'none', position: 'fixed', top: `${elBounds.top - margin.top}px`, width: `${elBounds.width}px`, }); setStyle(el, { opacity: 0, visibility: 'hidden', }); const minTranslate: Partial<IPosition> = {}; const maxTranslate: Partial<IPosition> = {}; if (this.axis.indexOf('x') !== -1) { minTranslate.x = this.containerBounds.left - elBounds.left - elBounds.width / 2; maxTranslate.x = this.containerBounds.left + this.containerBounds.width - elBounds.left - elBounds.width / 2; } if (this.axis.indexOf('y') !== -1) { minTranslate.y = this.containerBounds.top - elBounds.top - elBounds.height / 2; maxTranslate.y = this.containerBounds.top + this.containerBounds.height - elBounds.top - elBounds.height / 2; } this.autoScroller = new AutoScroller({ container: this.scrollContainer, onScroll: this.onScroll, maxTranslate: maxTranslate as IPosition, minTranslate: minTranslate as IPosition, height: elBounds.height, width: elBounds.width, }); this.manager.sortedItems().forEach((sortable) => { sortable.el.bounds = { height: Math.min(sortable.el.offsetHeight, elBounds.height) / 2, width: Math.min(sortable.el.offsetWidth, elBounds.width) / 2, ...getEdgeOffset(sortable.el, container), }; setTransitionDuration(sortable.el, transitionDuration); }); this.listenerNode = event.touches ? el : this.contentWindow; addEventListener(this.listenerNode, 'move', this.onMove); addEventListener(this.listenerNode, 'end', this.onEnd); } onScroll = (offset: IOffset) => { this.offset.x += offset.left; this.offset.y += offset.top; this._sort(); }; onMove = (event: IBrowserEvent) => { // Prevent scrolling on mobile if (typeof event.preventDefault === 'function') { event.preventDefault(); } this.offset = getPosition(event); const position = { x: this.baseHelperX + this.offset.x - this.contentWindow.pageXOffset, y: this.baseHelperY + this.offset.y - this.contentWindow.pageYOffset, }; setTranslate3d(this.helper, position); this.autoScroller.update(position); this._sort(); }; onEnd = async () => { removeEventListener(this.listenerNode, 'move', this.onMove); removeEventListener(this.listenerNode, 'end', this.onEnd); await this.onComplete({ newIndex: this.newIndex!, oldIndex: this.initalIndex, }); this.helper.parentNode?.removeChild(this.helper); setStyle(this.el, { opacity: '', visibility: '', }); this.manager.sortedItems().forEach(({ el }) => { el.bounds = null; setTranslate3d(el, null); setTransitionDuration(el, null); }); this.autoScroller.stop(); this.manager.invalidateCache(); }; _sort() { const delta = { left: this.baseX + this.offset.x + this.scrollContainer.scrollLeft, top: this.baseY + this.offset.y + this.scrollContainer.scrollTop, }; const focused = this.newIndex === null ? this.initalIndex : this.newIndex; this.newIndex = null; const items = this.manager.sortedItems(); for ( let i = Math.max(0, focused - 1), len = Math.min(focused + 2, items.length); i < len; i++ ) { const { el } = items[i]; const { index } = el.sortableInfo; if (index === this.initalIndex) { continue; } const bounds = this._getBounds(el); const position = { x: 0, y: 0, }; if (this.axis === 'x') { if ( index > this.initalIndex && delta.left + bounds.width >= bounds.left ) { position.x -= this.margin.x; this.newIndex = index; } else if ( index < this.initalIndex && delta.left <= bounds.left + bounds.width ) { position.x = this.margin.x; if (this.newIndex == null) { this.newIndex = index; } } } else if (this.axis === 'y') { if ( index > this.initalIndex && delta.top + bounds.height >= bounds.top ) { position.y -= this.margin.y; this.newIndex = index; } else if ( index < this.initalIndex && delta.top <= bounds.top + bounds.height ) { position.y = this.margin.y; if (this.newIndex == null) { this.newIndex = index; } } } else if (this.axis === 'xy') { if ( index < this.initalIndex && ((delta.left - bounds.width <= bounds.left && delta.top <= bounds.top + bounds.height) || delta.top + bounds.height <= bounds.top) ) { // If the current node is to the left on the same row, or above the node that's being dragged // then move it to the right position.x = this.margin.x; if ( bounds.left + position.x > this.containerBounds.width - bounds.width ) { // If it moves passed the right bounds, then animate it to the first position of the next row. // We just use the offset of the next node to calculate where to move, because that node's original position // is exactly where we want to go const nextNode = items[i + 1]; if (nextNode) { const nextBounds = this._getBounds(nextNode.el); position.x = nextBounds.left - bounds.left; position.y = nextBounds.top - bounds.top; } } if (this.newIndex === null) { this.newIndex = index; } } else if ( index > this.initalIndex && ((delta.left + bounds.width >= bounds.left && delta.top + bounds.height >= bounds.top) || delta.top + bounds.height >= bounds.top + el.offsetHeight) ) { // If the current node is to the right on the same row, or below the node that's being dragged // then move it to the left position.x -= this.margin.x; if ( bounds.left + position.x < this.containerBounds.left + bounds.width ) { // If it moves passed the left bounds, then animate it to the last position of the previous row. // We just use the offset of the previous node to calculate where to move, because that node's // original position is exactly where we want to go const prevNode = items[i - 1]; if (prevNode) { const prevBounds = this._getBounds(prevNode.el); position.x = prevBounds.left - bounds.left; position.y = prevBounds.top - bounds.top; } } this.newIndex = index; } } setTranslate3d(el, position); } if (this.newIndex == null) { this.newIndex = this.initalIndex; } } _getBounds(el: ISortableElement): IBounds { if (el.bounds) { return el.bounds; } el.bounds = { height: Math.min(el.offsetHeight, this.elBounds.height) / 2, width: Math.min(el.offsetWidth, this.elBounds.width) / 2, ...getEdgeOffset(el, this.container), }; setTransitionDuration(el, this.transitionDuration); return el.bounds; } }
the_stack
(function language_init():void { "use strict"; const language:language = { setlexer: function language_setlexer(input:string):string { const langmap = { c_cpp : "script", coldfusion: "markup", csharp : "script", css : "style", csv : "csv", dustjs : "markup", ejs : "markup", go : "markup", handlebars: "markup", html : "markup", html_ruby : "markup", java : "script", javascript: "script", json : "script", jsp : "markup", jsx : "script", less : "style", markdown : "markdown", markup : "markup", php : "script", phphtml : "markup", qml : "style", scss : "style", silverstripe: "markup", "styled-jsx": "script", "styled-components": "script", swig : "markup", text : "text", titanium : "script", tss : "script", twig : "markup", typescript: "script", vapor : "markup", velocity : "markup", xhtml : "markup", xml : "markup" }; if (typeof input !== "string") { return "script"; } if (input.indexOf("html") > -1) { return "markup"; } if (langmap[input] === undefined) { return "script"; } return langmap[input]; }, nameproper: function language_nameproper(input:string):string { const langmap = { c_cpp : "C++ (Not yet supported)", coldfusion: "ColdFusion", csharp : "C#", dustjs : "Dust.js", ejs : "EJS Template", elm : "Elm Template", go : "Go Lang Template", handlebars: "Handlebars Template", html_ruby : "ERB (Ruby) Template", java : "Java", javascript: "JavaScript", jsp : "JSTL (JSP)", jsx : "React JSX", liquid : "Liquid Template", markdown : "markdown", markup : "markup", phphtml : "HTML/PHP", scss : "SCSS", silverstripe: "SilverStripe", text : "Plain Text", titanium : "Titanium Stylesheets", tss : "Titanium Stylesheets", twig : "HTML TWIG Template", typescript: "TypeScript", vapor : "Vapor Leaf", velocity : "Apache Velocity", volt : "Volt Template" }; if (typeof input !== "string" || langmap[input] === undefined) { return input.toUpperCase(); } return langmap[input]; }, // * [0] = language value // * [1] = lexer value // * [2] = pretty formatting for text output to user auto: function language_auto(sample:string, defaultLang:string):languageAuto { let b:string[] = [], c:number = 0; const vartest:boolean = (( /(((var)|(let)|(const)|(function)|(import))\s+(\w|\$)+[a-zA-Z0-9]*)/ ).test(sample) === true && (/@import/).test(sample) === false), finalstatic:boolean = (/((((final)|(public)|(private))\s+static)|(static\s+void))/).test( sample ), output = function language_auto_output(langname:string):languageAuto { if (langname === "unknown") { return [defaultLang, language.setlexer(defaultLang), "unknown"]; } if (langname === "xhtml" || langname === "markup") { return ["xml", language.setlexer("xml"), "XHTML"]; } if (langname === "tss") { return ["tss", language.setlexer("tss"), "Titanium Stylesheets"]; } if (langname === "phphtml") { return ["php", language.setlexer(langname), language.nameproper(langname)]; } return [langname, language.setlexer(langname), language.nameproper(langname)]; }, cssA = function language_auto_cssA():languageAuto { if ((/\n\s*#+\s+/).test(sample) === true || (/^#+\s+/).test(sample) === true) { return output("markdown"); } if ((/\$[a-zA-Z]/).test(sample) === true || (/\{\s*(\w|\.|\$|#)+\s*\{/).test(sample) === true) { return output("scss"); } if ((/@[a-zA-Z]/).test(sample) === true || (/\{\s*(\w|\.|@|#)+\s*\{/).test(sample) === true) { return output("less"); } return output("css"); }, notmarkup = function language_auto_notmarkup():languageAuto { let d:number = 1, join:string = "", flaga:boolean = false, flagb:boolean = false; const publicprivate:boolean = ( /((public)|(private))\s+(static\s+)?(((v|V)oid)|(class)|(final))/ ).test(sample), javascriptA = function language_auto_notmarkup_javascriptA():languageAuto { if (sample.indexOf("(") > -1 || sample.indexOf("=") > -1 || (sample.indexOf(";") > -1 && sample.indexOf("{") > -1)) { if (vartest === false && ((/\n\s+#region\s/).test(sample) === true || (/\[\w+:/).test(sample) === true)) { return output("csharp"); } if (finalstatic === true || (/\w<\w+(,\s+\w+)*>/).test(sample) === true) { if ((/:\s*((number)|(string))/).test(sample) === false && (finalstatic === true || publicprivate === true)) { return output("java"); } return output("typescript"); } if ((/final\s+static/).test(sample) === true) { return output("java"); } if ((/<\/\w+>/).test(sample) === true && (/<\w+((\s+\w)|>)/).test(sample) === true) { return output("jsx"); } if ((/((var)|(let)|(const))\s+\w+\s*:/).test(sample) === true || (/=\s*<\w+/).test(sample) === true) { return output("typescript"); } return output("javascript"); } return output("unknown"); }, cssOrJavaScript = function language_auto_notmarkup_cssOrJavaScript():languageAuto { if ((/:\s*((number)|(string))/).test(sample) === true && (/((public)|(private))\s+/).test(sample) === true) { return output("typescript"); } if ((/import\s+java(\.|(fx))/).test(sample) === true || (/((public)|(private))\s+static\s+/).test(sample) === true) { return output("java"); } if ((/\sclass\s+\w/).test(sample) === false && (/<[a-zA-Z]/).test(sample) === true && (/<\/[a-zA-Z]/).test(sample) === true && ((/\s?\{%/).test(sample) === true || (/\{(\{|#)(?!(\{|#|=))/).test(sample) === true)) { return output("twig"); } if ((/^(\s*(\$|@))/).test(sample) === false && (/(\};?\s*)$/).test(sample) === true) { if ((/export\s+default\s+\{/).test(sample) === true || (/(\?|:)\s*(\{|\[)/).test(sample) === true || (/(\{|\s|;)render\s*\(\)\s*\{/).test(sample) === true || (/^(\s*return;?\s*\{)/).test(sample) === true) { return output("javascript"); } } if ((/\{\{#/).test(sample) === true && (/\{\{\//).test(sample) === true && (/<\w/).test(sample) === true) { return output("handlebars"); } if ((/\{\s*(\w|\.|@|#)+\s*\{/).test(sample) === true) { return output("less"); } if ((/\$(\w|-)/).test(sample) === true) { return output("scss"); } if ((/(;|\{|:)\s*@\w/).test(sample) === true) { return output("less"); } if ((/class\s+\w+\s+\{/).test(sample) === true) { return output("java"); } return output("css"); }; if (d < c) { do { if (flaga === false) { if (b[d] === "*" && b[d - 1] === "/") { b[d - 1] = ""; flaga = true; } else if (flagb === false && b[d] === "f" && d < c - 6 && b[d + 1] === "i" && b[d + 2] === "l" && b[d + 3] === "t" && b[d + 4] === "e" && b[d + 5] === "r" && b[d + 6] === ":") { flagb = true; } } else if (flaga === true && b[d] === "*" && d !== c - 1 && b[d + 1] === "/") { flaga = false; b[d] = ""; b[d + 1] = ""; } else if (flagb === true && b[d] === ";") { flagb = false; b[d] = ""; } if (flaga === true || flagb === true) { b[d] = ""; } d = d + 1; } while (d < c); } join = b.join(""); if ((/\s\/\//).test(sample) === false && (/\/\/\s/).test(sample) === false && (/^(\s*(\{|\[)(?!%))/).test(sample) === true && (/((\]|\})\s*)$/).test(sample) && sample.indexOf(",") !== -1) { return output("json"); } if ((/((\}?(\(\))?\)*;?\s*)|([a-z0-9]("|')?\)*);?(\s*\})*)$/i).test(sample) === true && (vartest === true || publicprivate === true || (/console\.log\(/).test(sample) === true || (/export\s+default\s+class\s+/).test(sample) === true || (/document\.get/).test(sample) === true || (/((=|(\$\())\s*function)|(\s*function\s+(\w*\s+)?\()/).test(sample) === true || sample.indexOf("{") === -1 || (/^(\s*if\s+\()/).test(sample) === true)) { return javascriptA(); } // * u007b === { // * u0024 === $ // * u002e === . if (sample.indexOf("{") > -1 && ((/^(\s*[\u007b\u0024\u002e#@a-z0-9])/i).test(sample) === true || (/^(\s*\/(\*|\/))/).test(sample) === true || (/^(\s*\*\s*\{)/).test(sample) === true) && (/^(\s*if\s*\()/).test(sample) === false && (/=\s*(\{|\[|\()/).test(join) === false && (((/(\+|-|=|\?)=/).test(join) === false || (/\/\/\s*=+/).test(join) === true) || ((/=+('|")?\)/).test(sample) === true && (/;\s*base64/).test(sample) === true)) && (/function(\s+\w+)*\s*\(/).test(join) === false) { if ((/\s*#((include)|(define)|(endif))\s+/).test(sample)) { return output("c_cpp"); } return cssOrJavaScript(); } if ((/"\s*:\s*\{/).test(sample) === true) { return output("tss"); } if (sample.indexOf("{%") > -1) { return output("twig"); } return output("unknown"); }, markup = function language_auto_markup():languageAuto { const html = function language_auto_markup_html():languageAuto { if ((/<%\s*\}/).test(sample) === true) { return output("ejs"); } if ((/<%\s+end_((if)|(with)|(loop)|(control)|(cached)|(uncached))/).test(sample) === true) { return output("silverstripe"); } if ((/<%\s*end/).test(sample) === true) { return output("html_ruby"); } if ((/\{\{(#|\/|\{)/).test(sample) === true) { return output("handlebars"); } if ((/\{\{end\}\}/).test(sample) === true) { //place holder for Go lang templates return output("html"); } if ((/\s?\{%/).test(sample) === true && (/\{(\{|#)(?!(\{|#|=))/).test(sample) === true) { return output("twig"); } if ((/<\?/).test(sample) === true) { if ((/^\s*<\?/).test(sample) === true && (/\?>\s*$/).test(sample) === true) { return output("php"); } return output("phphtml"); } if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) { return output("jsp"); } if ((/\{(#|\?|\^|@|<|\+|~)/).test(sample) === true && (/\{\//).test(sample) === true && sample.indexOf("<![CDATA[") < 0) { return output("dustjs"); } if ((/#((if)|(for)|(set))?\(/).test(sample) === true) { return output("vapor"); } return output("html"); }; if ((/<cfset\s/i).test(sample) === true || (/<cfif\s/i).test(sample) === true) { return output("coldfusion"); } if ( (/^(\s*<!doctype\s+html>)/i).test(sample) === true || (/^(\s*<html)/i).test(sample) === true || ( (/<form\s/i).test(sample) === true && (/<label\s/i).test(sample) === true && (/<input\s/i).test(sample) === true ) || (/<((img)|(IMG))(\s+\w+=("|')?\S+("|')?)*\s+src\s*=/).test(sample) === true || ( (/^(\s*<!DOCTYPE\s+((html)|(HTML))\s+PUBLIC\s+)/).test(sample) === true && (/XHTML\s+1\.1/).test(sample) === false && (/XHTML\s+1\.0\s+(S|s)((trict)|(TRICT))/).test(sample) === false ) ) { return html(); } if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) { return output("jsp"); } if ((/<%\s*\}/).test(sample) === true) { return output("ejs"); } if ((/<%\s+end_((if)|(with)|(loop)|(control)|(cached)|(uncached))/).test(sample) === true) { return output("silverstripe"); } if ((/<%\s*end/).test(sample) === true) { return output("html_ruby"); } if ((/\{\{(#|\/|\{)/).test(sample) === true) { return output("handlebars"); } if ((/\{\{end\}\}/).test(sample) === true) { //place holder for Go lang templates return output("xml"); } if ((/\s?\{%/).test(sample) === true && (/\{\{(?!(\{|#|=))/).test(sample) === true) { return output("twig"); } if ((/<\?(?!(xml))/).test(sample) === true) { if ((/^\s*<\?/).test(sample) === true && (/\?>\s*$/).test(sample) === true) { return output("php"); } return output("phphtml"); } if ((/\{(#|\?|\^|@|<|\+|~)/).test(sample) === true && (/\{\//).test(sample) === true) { return output("dustjs"); } if ((/<jsp:include\s/).test(sample) === true || (/<c:((set)|(if))\s/).test(sample) === true) { return output("jsp"); } if ((/#((if)|(for)|(set))?\(/).test(sample) === true) { return output("vapor"); } return output("xml"); }; if (sample === null || sample.replace(/\s+/g, "") === "") { return output("unknown"); } if ( ((/\n\s*#{1,6}\s+/).test(sample) === true || ((/\n\s*(\*|-|(\d+\.))\s/).test(sample) === true) && (/\/\*/).test(sample) === false) && ((/\[( |x|X)\]/).test(sample) === true || (/\s\*\*?\S\D/).test(sample) === true || (/\n\s*```/).test(sample) === true || ((/-+\|(-+\|)+/).test(sample) === true && (/<!--/).test(sample) === false)) ) { return output("markdown"); } if ((/^(\s*<!DOCTYPE\s+html>)/i).test(sample) === true) { return markup(); } if ((/^\s*@((charset)|(import)|(include)|(keyframes)|(media)|(namespace)|(page))/).test(sample) === true) { return cssA(); } if ( finalstatic === false && (/=(>|=|-|\+|\*)/).test(sample) === false && (/^(\s*((if)|(for)|(function))\s*\()/).test(sample) === false && (/(\s|;|\})((if)|(for)|(function\s*\w*))\s*\(/).test(sample) === false && vartest === false && (/return\s*\w*\s*(;|\})/).test(sample) === false && ( sample === undefined || (/^(\s*#(?!(!\/)))/).test(sample) === true || ((/\n\s*(\.|@)\w+(\(|(\s*:))/).test(sample) === true && (/>\s*<\w/).test(sample) === false) ) ) { return cssA(); } b = sample .replace(/\[[a-zA-Z][\w-]*=("|')?[a-zA-Z][\w-]*("|')?\]/g, "") .split(""); c = b.length; if ((/^(\s*(\{|<)(%|#|\{))/).test(sample) === true) { return markup(); } if (((/^([\s\w-]*<)/).test(sample) === false && (/(>[\s\w-]*)$/).test(sample) === false) || finalstatic === true) { return notmarkup(); } if ((((/(>[\w\s:]*)?<(\/|!|#)?[\w\s:\-[]+/).test(sample) === true || ((/^\s*</).test(sample) === true && (/<\/\w+(\w|\d)+>\s*$/).test(sample) === true) || (/^(\s*<\?xml)/).test(sample) === true) && ((/^([\s\w]*<)/).test(sample) === true || (/(>[\s\w]*)$/).test(sample) === true)) || ((/^(\s*<s((cript)|(tyle)))/i).test(sample) === true && (/(<\/s((cript)|(tyle))>\s*)$/i).test(sample) === true)) { if ((/^([\s\w]*<)/).test(sample) === false || (/(>[\s\w]*)$/).test(sample) === false) { return notmarkup(); } return markup(); } return output("unknown"); } }; global.sparser.libs.language = language; }());
the_stack
import { StreamWriter } from '../src/stream-writer'; import { Encoding, EncodingType } from '../src/encoding'; /** * Stream Writer Spec Modules */ describe('Create StreamWriter instance', () => { beforeEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 500; }); it('Validate constructor', (done) => { /** * instantiate StreamWriter class */ let streamWriter: StreamWriter = new StreamWriter(); setTimeout(function (): void { expect(streamWriter.encoding.type).toBe('Utf8'); done(); }, 50); }); it('StreamWriter constructor with Null checking', () => { let streamWriter: StreamWriter = new StreamWriter(null); expect(streamWriter.encoding.type).toBe('Utf8'); expect(streamWriter.encoding.includeBom).toBe(false); }); it('StreamWriter constructor with undefined', () => { let streamWriter: StreamWriter = new StreamWriter(undefined); expect(streamWriter.encoding.type).toBe('Utf8'); }); it('StreamWriter constructor with encoding', () => { let enc: Encoding = new Encoding(); let streamWriter: StreamWriter = new StreamWriter(enc); expect(streamWriter.encoding.type).toBe('Ansi'); }); it('StreamWriter constructor with encoding with UTF-8', () => { let enc: Encoding = new Encoding(false); enc.type = 'Utf8'; let streamWriter: StreamWriter = new StreamWriter(enc); expect(streamWriter.encoding.type).toBe('Utf8'); }); }); describe('Streamwriter with Encoding Testing', () => { let streamWriter: StreamWriter; let fileReader: FileReader; let text: string | ArrayBuffer; beforeEach((): void => { /** * creates instance of FileReader class */ fileReader = new FileReader(); fileReader.onload = (): void => { /** * gets text from blob */ text = fileReader.result; } }); afterEach((): void => { streamWriter.destroy(); streamWriter = undefined; fileReader = undefined; text = ''; }); it('text writing with ANSI encoding', (done) => { let encoding: Encoding = new Encoding(false); encoding.type = 'Ansi'; streamWriter = new StreamWriter(encoding); streamWriter.write('numéro de téléphone'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(streamWriter.buffer.size).toBe(19); done(); }, 50); }); it('text writing with UTF8 without bom encoding', (done) => { let encoding: Encoding = new Encoding(false); encoding.type = 'Utf8'; streamWriter = new StreamWriter(encoding); streamWriter.write('numéro de téléphone'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(streamWriter.buffer.size).toBe(22); done(); }, 50); }); it('text writing with UTF8 with bom encoding', (done) => { let encoding: Encoding = new Encoding(true); encoding.type = 'Utf8'; streamWriter = new StreamWriter(encoding); streamWriter.write('numéro de téléphone'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(streamWriter.buffer.size).toBe(25); done(); }, 50); }); it('text writing with Unicode encoding with Bom', (done) => { let encoding: Encoding = new Encoding(true); encoding.type = 'Unicode'; streamWriter = new StreamWriter(encoding); streamWriter.write('numéro de téléphone'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(streamWriter.buffer.size).toBe(40); done(); }, 50); }); it('text writing with Unicode encoding without Bom ', (done) => { let encoding: Encoding = new Encoding(false); encoding.type = 'Unicode'; streamWriter = new StreamWriter(encoding); streamWriter.write('numéro de téléphone'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(streamWriter.buffer.size).toBe(38); done(); }, 50); }); }); /** * StreamWriter write Method Testing */ describe("StreamWriter write Method Testing", () => { let streamWriter: StreamWriter; let fileReader: FileReader; let text: string | ArrayBuffer; let originalTimeout: number; beforeEach((): void => { streamWriter = new StreamWriter(); /** * creates instance of FileReader class */ fileReader = new FileReader(); fileReader.onload = (): void => { /** * gets text from blob */ text = fileReader.result; } originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 500; }); afterEach((): void => { streamWriter.destroy(); streamWriter = undefined; fileReader = undefined; text = ''; jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('write with null parameter', (): void => { expect(function (): void { streamWriter.write(null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined')); }); it('write with undefined parameter', (): void => { expect(function (): void { streamWriter.write(undefined); }).toThrow(new Error('ArgumentException: string cannot be null or undefined')); }); it('write with empty string', () => { streamWriter.write(''); expect(streamWriter.buffer.size == 0).toBe(true); }); it('write with string parameter', (done) => { streamWriter.write('StreamWriter'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('StreamWriter'); done(); }, 50); }); it('write with integer parameter', (done) => { let x: number = 124; streamWriter.write(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('124'); expect(streamWriter.buffer.size).toBe(3); done(); }, 50); }); it('write with integer parameter', (done) => { let x: number = 124; streamWriter.write(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('124'); expect(streamWriter.buffer.size).toBe(3); done(); }, 50); }); it('write with decimal parameter', (done) => { let x: number = 124.66; streamWriter.write(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('124.66'); done(); }, 50); }); it('write with negative value parameter', (done) => { let x: number = -124; streamWriter.write(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('-124'); done(); }, 50); }); it('write with boolean parameter', (done) => { let x: boolean = true; streamWriter.write(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('true'); done(); }, 50); }); it('Test text appending in blob', (done) => { streamWriter.write('Stream'); streamWriter.write('Writer'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('StreamWriter'); done(); }, 50); }); it('Without write method', (done) => { fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe(''); done(); }, 50); }); }); /** * StreamWriter writeLine Method Testing */ describe("StreamWriter writeLine Method Testing", () => { let streamWriter: StreamWriter; let fileReader: FileReader; let text: string | ArrayBuffer; let originalTimeout: number; beforeEach((): void => { streamWriter = new StreamWriter(); /** * creates instance of FileReader class */ fileReader = new FileReader(); fileReader.onload = (): void => { /** * gets text from blob */ text = fileReader.result; } originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 500; }); afterEach((): void => { streamWriter.destroy(); streamWriter = undefined; fileReader = undefined; text = ''; jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('writeLine with null parameter', (): void => { expect(function (): void { streamWriter.writeLine(null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined')); }); it('writeLine with undefined parameter', (): void => { expect(function (): void { streamWriter.writeLine(null); }).toThrow(new Error('ArgumentException: string cannot be null or undefined')); }); it('writeLine with empty string', () => { streamWriter.writeLine(''); expect(streamWriter.buffer.size == 2).toBe(true); }); it('writeLine with string parameter', (done) => { streamWriter.writeLine('StreamWriter'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('StreamWriter\r\n'); done(); }, 50); }); it('writeLine with integer parameter', (done) => { let x: number = 124; streamWriter.writeLine(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(streamWriter.buffer.size).toBe(5); done(); }, 50); }); it('writeLine with decimal parameter', (done) => { let x: number = 124.66; streamWriter.writeLine(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('124.66\r\n'); done(); }, 50); }); it('writeLine with negative value parameter', (done) => { let x: number = -124; streamWriter.writeLine(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('-124\r\n'); done(); }, 50); }); it('writeLine with boolean parameter', (done) => { let x: boolean = true; streamWriter.writeLine(x.toString()); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('true\r\n'); done(); }, 50); }); it('Test text appending in blob', (done) => { streamWriter.write('Stream'); streamWriter.writeLine('Writer'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe('StreamWriter\r\n'); done(); }, 50); }); it('Without writeLine method', (done) => { fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text).toBe(''); done(); }, 50); }); it('writeline method testing with maximum string', () => { for (let i: number = 0; i < 10241; i++) { streamWriter.writeLine('a'); } let position: number = streamWriter.buffer.size; expect(position).toBe(30723); }); }); /** *StreamWriter save and destroy testing */ describe('StreamWriter save and destroy testing', () => { let streamWriter: StreamWriter; let fileReader: FileReader; let text: string | ArrayBuffer; let originalTimeout: number; beforeEach((): void => { let encoding: Encoding = new Encoding(true); encoding.type = 'Utf8'; streamWriter = new StreamWriter(encoding); fileReader = new FileReader(); fileReader.onload = (): void => { text = fileReader.result; } originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 500; }); afterEach((): void => { streamWriter.destroy(); streamWriter = undefined; fileReader = undefined; text = ''; jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('save method with null parameter', () => { expect((): void => { streamWriter.save(null) }).toThrow(new Error('ArgumentException: fileName cannot be undefined, null or empty')); }); it('save method with empty string', () => { expect((): void => { streamWriter.save('') }).toThrow(new Error('ArgumentException: fileName cannot be undefined, null or empty')); }); it('save method with valid string', (done) => { streamWriter.write('Stream'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text === 'Stream').toEqual(true); done(); }, 50); }); it('before calling destroy method', (done) => { streamWriter.write('Stream'); streamWriter.write('Writer'); fileReader.readAsText(streamWriter.buffer); setTimeout(function (): void { expect(text === 'Writer').toEqual(false); done(); }, 50); }); it('after calling destroy method ', (done) => { streamWriter.write('Stream'); streamWriter.destroy(); setTimeout(function (): void { expect(() => { streamWriter.write('Writer') }).toThrow(new Error('Object Disposed Exception: current writer is disposed')); done(); }, 50); }); it('after calling destroy method, call writeLine method', (done) => { streamWriter.write('Stream'); streamWriter.destroy(); setTimeout(function (): void { expect(() => { streamWriter.writeLine('Writer') }).toThrow(new Error('Object Disposed Exception: current writer is disposed')); done(); }, 50); }); it('save method testing', (done) => { for (let i: number = 0; i < 10241; i++) { streamWriter.write('a'); } let position: number = streamWriter.buffer.size; expect(position).toBe(10244); // streamWriter.save('sample.txt'); setTimeout(function (): void { expect(text).toBe(''); done() }, 100); }); // it('save method with MicrosoftBrowser testing', () => { // streamWriter.write('StreamWriter'); // expect(() => { streamWriter.save('sample.txt'); }).not.toThrowError(); // }); });
the_stack
declare module '*.css' declare module '*.png' declare module '*.svg' declare module '*.gif' declare module '*.less' declare module '@antv/g6' declare module 'react-json-tree' declare module '@antv/g6/plugins/layout.dagre' declare module '@antv/data-set' declare module 'filesize' declare module 'react-transition-group' declare module '@antv/data-set/lib/data-set' declare module 'pretty-bytes' declare module 'react-countup' declare module 'react-highlight-words' declare module 'moment/locale/zh-cn' declare module 'qs' declare const ENV: 'development' | 'production' declare const theme: any declare const apiHost: string // Global interface Window { Store: any React: any Promise: Promise<any> | null } interface Promise<T> { prototype: any } // Common interface KVType { [key: string]: string | number | boolean } // Common API Return data structure interface APIData<T> { code: number data: T msgCode: null | number msgContent: string } // Pagination interface PaginationData { currentPage: number totalCount: number totalPage: number } // Login interface LoginData { token: string tokenExpired: number userName: string } // STATUS type STATUS = 'UP' | 'DOWN' | 'OFFLINE' | 'UNKONW' // enum interface type NoticeType = 'info' | 'error' | 'success' // fetch Request CustomError interface RequestError { errorCode: number errorMsg: { error: string message: string path: string status: number timestamp: number } } // /admin/dashboard/basic interface DashboardBasicData { appNum: number downNum: number instanceNum: number myAppNum: number myInstanNum: number projectNum: number myProjectNum: number department?: string role: string } // admin/instances/events?pageNum=1&pageSize=8 interface EventLogData extends PaginationData { list: EventLogItem[] } interface EventLogItem { instance: string registration: { healthUrl: string managementUrl: string metadata: { 'gray.enable': string 'hazelcast.host': string 'hazelcast.port': string 'hazelcast.version': string 'management.port': string 'management.url': string } name: string serviceUrl: string source: string } timestamp: number type: string version: number } // Jar admin/instances/e9a9ea7cc0b7/actuator/jardeps interface JardepsData { pomInfos: PomInfo[] springBootVersion: string springCloudVersion: string summerframeworkVersion: string } interface PomInfo { artifactId: string dependencies: Dependence[] groupId: string location: string size: number version: string } interface Dependence { artifactId: string groupId: string scope?: string version: string } interface ActionDataIsObject { type: string data: { [index: string]: any } } // action map interface AsyncActionMap { ACTION: string SUCCESS: string FAILED: string } // Base callback function interface BCF { (err?: any, result?: any): void } // Base Action Shape interface BAS<T> { cb?: BCF data: T type: string } // Action Input declare namespace AI {} // Action Shape declare namespace AS {} // Base Action Function interface BAF<I, R> { (input: I, cb?: BCF): R } // action function declare namespace ActionFunction { interface Notice { (type: NoticeType, message: string, duration?: number): { data: { type: NoticeType message: string duration?: number } type: string } } } interface INotification { notices: INotice[] loading: number dialog?: DialogProps } interface INotice { type?: string message: string duration?: number count?: number removeNotice?: Function } interface DialogProps { type?: string message: string duration?: number } // admin/applications?appName=HALO-ADMIN-2.0&pageNum=1&pageSize=8 interface ServiceData extends PaginationData { list: ServiceItem[] } interface ServiceItem { starsNum: number twinkle: boolean attachType?: number buildVersion?: string instanceNum: number instances: InstanceItem[] name: string ownerName?: string projectKey?: string projectName?: string status: STATUS statusTimestamp: number takeOver: boolean } interface InstanceData extends PaginationData { list: InstanceItem[] pageSize?: number } interface InstanceItem { buildVersion?: string endpoints?: EndPoint[] id: string info: { [key: string]: string } registered: boolean registration: { healthUrl: string managementUrl: string metadata: { [key: string]: string } name: string serviceUrl: string source: string icon: string } statusInfo: { status: STATUS details: { [key: string]: string } } url?: string group?: string name: string ownerName?: string projectKey?: string instanceNum: string status: STATUS statusTimestamp: number takeOver: boolean tags?: any unsavedEvents?: any attachType: number version: number } interface EndPoint { id: string url: string } // admin/instances/965ce52d71e1/actuator/metricsInfo interface MetricsData { gcPsMarksweepCount: string gcPsMarksweepTime: string gcPsScavengeCount: string gcPsScavengeTime: string heapCommitted: string heapInit: string heapMax: string jvmMemoryUsedHeap: string jvmMemoryUsedNonHeap: string jvmThreadslive: string nonheapCommitted: string processors: string systemloadAverage: string } // admin/instances/965ce52d71e1/actuator/health interface HealthData { details: { db?: { status: STATUS; details: HealthDetail } description?: string discoveryComposite?: { status: STATUS; details: HealthDetail } diskSpace?: { status: STATUS; details: HealthDetail } hystrix?: { status: STATUS } } status: STATUS } interface HealthDetail { [key: string]: string } // admin/instances/965ce52d71e1/actuator/info interface Info { artifactId: string git: Git groupId: string version: string } interface Git { branch: string build: { host: string time: number user: { name: string; email: string } version: string } closest: { tag: { commit: { count: string }; name: string } } commit: any dirty: string remote: { origin: { url: string } } tags: string } // admin/instances/7e44bfad832e/actuator/appinfo interface AppDepInfo { summerframeworkVersion: string using: [{ [key: string]: string }] appName: string springBootVersion: string springCloudVersion: string } // admin/instances/events/965ce52d71e1 interface InstanceEvent { instance: string registration: Registration timestamp: number type: string version: number statusInfo?: { status: STATUS } } interface Registration { healthUrl: string managementUrl: string metadata: { [key: string]: string } name: string serviceUrl: string source: string } // admin/instances/00e8c3185557/actuator/gc?page=1&size=100 interface GCLogData { page: number size: number log: string[] total: number error?: any } // admin/user/menu/ interface MenuData { gmtCreate?: string gmtModified?: string icon: string id?: string key: string name?: string parentId?: string parentIds?: string roles?: string sort?: string src?: string subMenu: MenuData[] title: string url?: string isExternal: boolean } // RegisterCenter interface RegisterCenterData extends PaginationData { list: RegisterCenterModel[] id: number } interface RegisterCenterModel { code: string desc: string gmtModified: string id: number isDeleted: number url: string } // Project interface ProjectData extends PaginationData { list: ProjectModel[] type?: string id: number } interface ProjectModel { cname: string description: string gmtModified: string id: number isDeleted: number key: string name: string ownerId: string ownerName: string } // UserList interface UserModel { id: number username: string name: string email: string } interface ListData<T> { pageNum?: number pageSize?: number total?: number pages?: number list?: T[] currentPage: number totalCount: number } // /admin/dashboard/report interface ReportData { [key: string]: any count: number springCloudVersions: [ReportItem] sprintBootVersions: [ReportItem] summerFrameworkVersions: [ReportItem] takeOver: [ReportItem] } interface ReportItem { name: string count: number } interface ApplicationDetail { base: InstanceItem build: Info event: InstanceEvent[] health: HealthData depInfo: AppDepInfo } interface ApplicationMetricsData { timestamp: number [key: string]: any } // 数据字典 interface RemoteConfigData extends PaginationData { list: RemoteConfigModel[] } interface RemoteConfigModel { editing?: boolean new?: boolean dictCode: string dictDataModelList: Array<RemoteConfigModel> dictName?: string gmtCreate?: number gmtModified?: number id?: number isDeleted: number status?: number itemDesc?: string itemName?: string itemSort?: number itemValue?: string [key: string]: string } // Global Config - 数据字典编辑的配置项 interface GlobalConf { frameworkVerison: GlobalConfItem[] springBootVersion: GlobalConfItem[] springCloudVersion: GlobalConfItem[] registerCenter: GlobalConfItem[] } interface GlobalConfItem { name: string value: string desc: string } // 消息轨迹 interface TrajectoryData extends PaginationData { list: Trajectory[] } interface Trajectory { timestamp: string clientIp: string applicationName: string messageId: string type: string node: string connection: string vhost: string user: string channel: string exchange: string queue: string routingKeys: string properties: string payload: string success: string payload: string } interface TotalRequestNumData {} // 请求耗时 interface RequestCostTImeData {} type FieldOption = | { value: string key?: string label?: string disabled?: boolean className?: string } | string type FieldOptions = Array<FieldOption> type FieldOptionsInput = string | FieldOptions | Function type Dependency = string | Array<any> type Dependencies = string | Array<Dependency> interface FieldControl { name: string options?: FieldOptionsInput optionsFilter?: any extend?: FieldOptions | Function value?: any [key: string]: any } interface FieldData { fieldName: string label?: string tip?: string option?: { initialValue?: string | string[] | boolean | Function rules?: any[] } control: FieldControl dependencies?: Dependencies hidden?: boolean } interface FieldSetData { submit?: boolean title?: string fields?: FieldData[] dependencies?: Dependencies } type OrderServiceType = | 'order' | 'orderTran' | 'refundOrder' | 'refundTran' | 'repeatTran' | 'reconciliation' type WalletUserInfoServiceType = 'dashboard' | 'user' | 'card' | 'order' | 'feature' | 'faq' interface SearchBarConstructorData { onSubmit: (value: any, clear?: boolean) => void data: FieldSetData extend?: JSX.Element } interface PageConstructorData { columns: { [key: string]: any }[] searchBar?: FieldSetData controller?: any pageTitle?: string model: any service: any noExport?: boolean } interface ControllerData { title: string onClick: () => void icon: string } interface ColumnOperate { dependencies?: string linkTo?: String doAction?: { disabled?: string action: string params?: any } title: string then?: any } // User interface UserData extends PaginationData { list: UserMgmtModel[] id: number } interface UserMgmtModel { username: string name: string gmtModified: string id: number isDeleted: number email: string }
the_stack
export interface OpenApiV2 { swagger: "2.0"; info: InfoObject; host?: string; basePath?: string; schemes?: Schemes[]; consumes?: string[]; produces?: string[]; paths: PathsObject; definitions?: DefinitionsObject; parameters?: ParametersDefinitionsObject; responses?: ResponsesDefinitionsObject; securityDefinitions?: SecurityDefinitionsObject; security?: SecurityRequirementObject[]; tags?: TagObject[]; externalDocs?: ExternalDocumentationObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#infoObject export interface InfoObject { title: string; description?: string; termsOfService?: string; contact?: ContactObject; license?: LicenseObject; version: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#contactObject export interface ContactObject { name?: string; url?: string; email?: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#licenseObject export interface LicenseObject { name: string; url?: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#paths-object export interface PathsObject { [path: string]: PathItemObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathItemObject export interface PathItemObject { $ref?: string; get?: OperationObject; put?: OperationObject; post?: OperationObject; delete?: OperationObject; options?: OperationObject; head?: OperationObject; patch?: OperationObject; parameters?: (ParameterObject | ReferenceObject)[]; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operationObject export interface OperationObject { tags?: string[]; summary?: string; description?: string; externalDocs?: ExternalDocumentationObject; operationId?: string; consumes?: string[]; produces?: string[]; parameters?: (ParameterObject | ReferenceObject)[]; responses: ResponsesObject; schemes?: Schemes[]; deprecated?: boolean; security?: SecurityRequirementObject[]; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responsesObject export interface ResponsesObject { [statusCodeOrDefault: string]: ResponseObject | ReferenceObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject export interface ResponseObject { description: string; schema?: SchemaObject; headers?: HeadersObject; examples?: ExampleObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headersObject export interface HeadersObject { [name: string]: HeaderObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#headerObject export type HeaderObject = | StringHeaderObject | NumberHeaderObject | IntegerHeaderObject | BooleanHeaderObject | ArrayHeaderObject; export interface StringHeaderObject extends HeaderObjectBase, StringParameterObject {} export interface NumberHeaderObject extends HeaderObjectBase, NumberParameterObjectType {} export interface IntegerHeaderObject extends HeaderObjectBase, IntegerParameterObjectType {} export interface BooleanHeaderObject extends HeaderObjectBase, BooleanParameterObjectType {} export interface ArrayHeaderObject extends HeaderObjectBase, ArrayParameterObjectType {} interface HeaderObjectBase { description?: string; } /** * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject * There is a fair amount of duplication with the header object, however the differences * are complex enough to warrant keeping the definitions completely isolated from each other. */ export type ParameterObject = | QueryParameterObject | HeaderParameterObject | PathParameterObject | FormDataParameterObject | BodyParameterObject; export type QueryParameterObject = { in: "query"; allowEmptyValue?: boolean; } & ParameterObjectBase & QueryParameterObjectType; export type HeaderParameterObject = { in: "header"; } & ParameterObjectBase & HeaderParameterObjectType; export type PathParameterObject = { in: "path"; required: true; } & ParameterObjectBase & PathParameterObjectType; export type FormDataParameterObject = { in: "formData"; allowEmptyValue?: boolean; } & ParameterObjectBase & FormDataParameterObjectType; export type BodyParameterObject = { in: "body"; schema: SchemaObject; } & ParameterObjectBase; interface ParameterObjectBase { name: string; in: "query" | "header" | "path" | "formData" | "body"; description?: string; required?: boolean; } type QueryParameterObjectType = | BaseParameterObjectTypes | ArrayMultiParameterObjectType; type HeaderParameterObjectType = | BaseParameterObjectTypes | ArrayParameterObjectType; type PathParameterObjectType = | BaseParameterObjectTypes | ArrayParameterObjectType; type FormDataParameterObjectType = | BaseParameterObjectTypes | ArrayMultiParameterObjectType | FileParameterObjectType; type BaseParameterObjectTypes = | StringParameterObject | NumberParameterObjectType | IntegerParameterObjectType | BooleanParameterObjectType; export interface StringParameterObject { type: "string"; format?: "byte" | "binary" | "date" | "date-time" | "password"; default?: string; maxLength?: number; minLength?: number; pattern?: string; enum?: string[]; } export interface NumberParameterObjectType extends NumberParameterObjectTypeBase { type: "number"; format?: "float" | "double"; default?: number; } export interface IntegerParameterObjectType extends NumberParameterObjectTypeBase { type: "integer"; format?: "int32" | "int64"; default?: number; } export interface BooleanParameterObjectType { type: "boolean"; default?: boolean; enum?: boolean[]; } export interface FileParameterObjectType { type: "file"; } export interface ArrayParameterObjectType extends ArrayParameterObjectTypeBase { collectionFormat?: "csv" | "ssv" | "tsv" | "pipes"; } export interface ArrayMultiParameterObjectType extends ArrayParameterObjectTypeBase { collectionFormat?: "csv" | "ssv" | "tsv" | "pipes" | "multi"; } interface ArrayParameterObjectTypeBase { type: "array"; items: ItemsObject; default?: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any maxItems?: number; minItems?: number; uniqueItems?: boolean; } interface NumberParameterObjectTypeBase { default?: number; maximum?: number; exclusiveMaximum?: boolean; minimum?: number; exclusiveMinimum?: boolean; enum?: number[]; multipleOf?: number; } /** * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#itemsObject * The items object is similar enough to the header object to warrant use of the * `Exclude` utility type. */ export type ItemsObject = Exclude<HeaderObject, "description">; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#definitionsObject export interface DefinitionsObject { [name: string]: SchemaObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parametersDefinitionsObject export interface ParametersDefinitionsObject { [name: string]: ParameterObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responsesDefinitionsObject export interface ResponsesDefinitionsObject { [name: string]: ResponseObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityDefinitionsObject export interface SecurityDefinitionsObject { [name: string]: SecuritySchemeObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securitySchemeObject export type SecuritySchemeObject = | BasicSecuritySchemeObject | ApiKeySecuritySchemeObject | OAuth2SecuritySchemeObject; export interface BasicSecuritySchemeObject extends SecuritySchemeObjectBase { type: "basic"; } export interface ApiKeySecuritySchemeObject extends SecuritySchemeObjectBase { type: "apiKey"; name: string; in: "query" | "header"; } export type OAuth2SecuritySchemeObject = | ImplicitOAuth2SecuritySchemeObject | PasswordOAuth2SecuritySchemeObject | ApplicationOAuth2SecuritySchemeObject | AccessCodeOAuth2SecuritySchemeObject; export interface ImplicitOAuth2SecuritySchemeObject extends OAuth2SecuritySchemeObjectBase, SecuritySchemeObjectBase { flow: "implicit"; authorizationUrl: string; } export interface PasswordOAuth2SecuritySchemeObject extends OAuth2SecuritySchemeObjectBase, SecuritySchemeObjectBase { flow: "password"; tokenUrl: string; } export interface ApplicationOAuth2SecuritySchemeObject extends OAuth2SecuritySchemeObjectBase, SecuritySchemeObjectBase { flow: "application"; tokenUrl: string; } export interface AccessCodeOAuth2SecuritySchemeObject extends OAuth2SecuritySchemeObjectBase, SecuritySchemeObjectBase { flow: "accessCode"; authorizationUrl: string; tokenUrl: string; } interface OAuth2SecuritySchemeObjectBase { type: "oauth2"; scopes: ScopesObject; } interface SecuritySchemeObjectBase { description?: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#scopesObject export interface ScopesObject { [name: string]: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject export interface SecurityRequirementObject { [name: string]: string[]; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#tagObject export interface TagObject { name: string; description?: string; externalDocs?: ExternalDocumentationObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#externalDocumentationObject export interface ExternalDocumentationObject { description?: string; url: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#exampleObject export interface ExampleObject { [mimeType: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject export type SchemaObject = | NumberSchemaObject | IntegerSchemaObject | StringSchemaObject | BooleanSchemaObject | ArraySchemaObject | ObjectSchemaObject | AnySchemaObject | AllOfSchemaObject | ReferenceSchemaObject; interface SchemaObjectBase { /** * OpenAPI 2 does not support null types. We apply the commonly used * vendor extension `x-nullable` to describe nullability. * * See https://stackoverflow.com/a/48114322. */ "x-nullable"?: boolean; title?: string; description?: string; example?: any; // eslint-disable-line @typescript-eslint/no-explicit-any externalDocs?: ExternalDocumentationObject; } export interface NumberSchemaObject extends SchemaObjectBase, NumberSchemaObjectBase { type: "number"; format?: "float" | "double"; } export interface IntegerSchemaObject extends SchemaObjectBase, NumberSchemaObjectBase { type: "integer"; format?: "int32" | "int64"; } interface NumberSchemaObjectBase { default?: number; multipleOf?: number; maximum?: number; exclusiveMaximum?: boolean; minimum?: number; exclusiveMinimum?: boolean; enum?: (number | null)[]; } export interface StringSchemaObject extends SchemaObjectBase { type: "string"; default?: string; maxLength?: number; minLength?: number; /** * OpenAPI allows custom formats. We constrain the format here to those * that OpenAPI has defined and custom formats that Spot may produce. */ format?: "date" | "date-time" | "password" | "byte" | "binary"; pattern?: string; enum?: (string | null)[]; } export interface BooleanSchemaObject extends SchemaObjectBase { type: "boolean"; enum?: (boolean | null)[]; default?: boolean; } export interface ArraySchemaObject extends SchemaObjectBase { type: "array"; default?: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any maxItems?: number; minItems?: number; uniqueItems?: boolean; items: SchemaObject; } export interface ObjectSchemaObject extends SchemaObjectBase { type: "object"; default?: any; // eslint-disable-line @typescript-eslint/no-explicit-any required?: string[]; maxProperties?: number; minProperties?: number; properties?: ObjectPropertiesSchemaObject; additionalProperties?: SchemaObject | boolean; } export interface ObjectPropertiesSchemaObject { [name: string]: SchemaObject & ObjectPropertySchemaObjectBase; } interface ObjectPropertySchemaObjectBase { readOnly?: boolean; xml?: XmlObject; } export interface AnySchemaObject extends SchemaObjectBase { AnyValue: {}; } export interface AllOfSchemaObject extends SchemaObjectBase { allOf: SchemaObject[]; discriminator?: string; } export interface ReferenceSchemaObject { $ref: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#xmlObject export interface XmlObject { name?: string; namespace?: string; prefix?: string; attribute?: boolean; wrapped?: boolean; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#referenceObject export interface ReferenceObject { $ref: string; } type Schemes = "http" | "https" | "ws" | "wss";
the_stack
import avalanche_go_api from '@/avalanche_go_api' import { ISubnetData } from '@/store/modules/platform/ISubnet' import Blockchain from '@/js/Blockchain' import { IValidator, IValidatorData, IDelegator, IDelegatorData, IPendingValidatorData, IPendingValidator, IPendingDelegator, IPendingDelegatorData, } from '@/store/modules/platform/IValidator' import { AVALANCHE_SUBNET_ID } from '@/store/modules/platform/platform' export default class Subnet { id: string controlKeys: string[] threshold: number blockchains: Blockchain[] validators: IValidator[] delegators: IDelegator[] pendingValidators: IPendingValidator[] pendingDelegators: IPendingDelegator[] constructor(data: ISubnetData) { this.id = data.id this.controlKeys = data.controlKeys this.threshold = parseInt(data.threshold) this.blockchains = [] this.validators = [] this.pendingValidators = [] this.delegators = [] this.pendingDelegators = [] } // TODO: get address details for Platform Keys (https://docs.avax.network/v1.0/en/api/platform/#platformgetaccount) async updateValidators(endpoint: string) { /* ========================================== GET DATA FROM SERVICE ========================================== */ const req = { jsonrpc: '2.0', method: endpoint, params: { subnetID: this.id, }, id: 1, } const response = await avalanche_go_api.post('', req) // console.log(`------------- ${this.id.substring(0,4)} ------------ ${endpoint}`); // console.log("result: ", response.data.result); /* ========================================== CURRENT VALIDATORS ========================================== */ if (endpoint === 'platform.getCurrentValidators') { const validatorsData = response.data.result .validators as IValidatorData[] let validators: IValidator[] = [] let delegators: IDelegator[] = [] if (validatorsData.length > 0) { // All Subnets validators = this.setValidators(validatorsData) validators = this.sortByStake(validators, this.id) // Primary Network Only if (this.id === AVALANCHE_SUBNET_ID) { validators.forEach((v: IValidator) => { if (v.delegators !== null) { v.delegators?.forEach((d: IDelegator) => delegators.push(d) ) } }) } delegators = this.sortDelegators(delegators) } this.validators = validators this.delegators = delegators } else if (endpoint === 'platform.getPendingValidators') { /* ========================================== PENDING VALIDATORS ========================================== */ const pendingValidatorsData = response.data.result .validators as IPendingValidatorData[] let pendingValidators: IPendingValidator[] = [] let pendingDelegators: IPendingDelegator[] = [] // All Subnets if (pendingValidatorsData.length > 0) { pendingValidators = this.setPendingValidators( pendingValidatorsData ) } // Primary Network Only if (this.id === AVALANCHE_SUBNET_ID) { const pendingDelegatorsData = response.data.result .delegators as IPendingValidatorData[] if (pendingDelegatorsData.length > 0) { pendingDelegators = this.setPendingDelegators( pendingDelegatorsData ) } } this.pendingValidators = pendingValidators this.pendingDelegators = pendingDelegators } } addBlockchain(data: Blockchain) { this.blockchains.push(data) } /** * Convert API data to validators */ private setValidators(validatorsData: IValidatorData[]): IValidator[] { const validators = validatorsData.map((v: IValidatorData) => { const validator: IValidator = { nodeID: v.nodeID, startTime: new Date(parseInt(v.startTime) * 1000), endTime: new Date(parseInt(v.endTime) * 1000), } // Primary Network if ({}.hasOwnProperty.call(v, 'stakeAmount')) { validator.rewardOwner = { locktime: parseInt(v.rewardOwner!.locktime), threshold: parseInt(v.rewardOwner!.threshold), addresses: v.rewardOwner!.addresses, } validator.potentialReward = parseInt( v.potentialReward as string ) validator.stakeAmount = parseInt(v.stakeAmount as string) validator.uptime = parseFloat(v.uptime as string) * 100 // percentage validator.connected = v.connected validator.delegationFee = parseInt(v.delegationFee as string) validator.delegators = this.setDelegators(v.delegators!) as | IDelegator[] | null validator.totalStakeAmount = this.calculateTotalStakeAmount( validator.delegators, validator.stakeAmount ) validator.elapsed = this.getElapsedStakingPeriod(validator) } // Subnets if ({}.hasOwnProperty.call(v, 'weight')) { validator.weight = parseInt(v.weight as string) } return validator }) return validators } /** * Convert API data to delegators */ private setDelegators( delegatorsData: IDelegatorData[] | null ): IDelegator[] | null { let delegators = null if (delegatorsData) { delegators = delegatorsData.map((d) => { const delegator: IDelegator = { nodeID: d.nodeID, startTime: new Date(parseInt(d.startTime) * 1000), endTime: new Date(parseInt(d.endTime) * 1000), rewardOwner: { locktime: parseInt(d.rewardOwner.locktime), threshold: parseInt(d.rewardOwner.threshold), addresses: d.rewardOwner.addresses, }, potentialReward: parseInt(d.potentialReward), stakeAmount: parseInt(d.stakeAmount), } return delegator }) } return delegators } /** * Convert API data to pending validators */ private setPendingValidators( pendingValidatorsData: IPendingValidatorData[] ): IPendingValidator[] { const pendingValidators = pendingValidatorsData.map( (pv: IPendingValidatorData) => { const pendingValidator: IPendingValidator = { nodeID: pv.nodeID, startTime: new Date(parseInt(pv.startTime) * 1000), endTime: new Date(parseInt(pv.endTime) * 1000), stakeAmount: parseInt(pv.stakeAmount), delegators: null, } // Pending Validators - set optional props if ({}.hasOwnProperty.call(pv, 'connected')) { pendingValidator.connected = pv.connected as boolean pendingValidator.delegationFee = parseInt( pv.delegationFee as string ) } return pendingValidator } ) return pendingValidators } /** * Convert API data to pending delegators */ private setPendingDelegators( pendingDelegatorsData: IPendingDelegatorData[] | null ): IPendingDelegator[] { let pendingDelegators: IPendingDelegator[] = [] if (pendingDelegatorsData) { pendingDelegators = pendingDelegatorsData.map((pd) => { const pendingDelegator: IPendingDelegator = { nodeID: pd.nodeID, startTime: new Date(parseInt(pd.startTime) * 1000), endTime: new Date(parseInt(pd.endTime) * 1000), stakeAmount: parseInt(pd.stakeAmount), } return pendingDelegator }) } return pendingDelegators } /** * validated + delegated stake */ private calculateTotalStakeAmount( delegators: IDelegator[] | null, stakeAmount: number ): number { let totalStakeAmount = stakeAmount if (delegators) { let delegatedStakeAmount = 0 delegators.forEach((d) => (delegatedStakeAmount += d.stakeAmount)) totalStakeAmount += delegatedStakeAmount } return totalStakeAmount } /** * Sort by stake or weight and add rank */ private sortByStake(validators: IValidator[], id: string): IValidator[] { id === AVALANCHE_SUBNET_ID ? validators.sort( (a, b) => (b.totalStakeAmount as number) - (a.totalStakeAmount as number) ) : validators.sort( (a, b) => (b.weight as number) - (a.weight as number) ) validators.forEach((v, i) => (v.rank = i + 1)) return validators } /** * Sort by stake */ private sortDelegators(delegators: IDelegator[]): IDelegator[] { return delegators.length > 0 ? delegators.sort((a, b) => b.stakeAmount - a.stakeAmount) : [] } /** * Elapsed staking period (%) */ private getElapsedStakingPeriod(validator: IValidator): number { const currentTime = new Date().getTime() const numerator = currentTime - validator.startTime.getTime() const denominator = validator.endTime.getTime() - validator.startTime.getTime() return Math.round((numerator / denominator) * 100) } }
the_stack
import Color from 'color'; import ColorName from 'color-name'; import { ImageEdits, ImageFitTypes, ImageFormatTypes } from './lib'; export class ThumborMapper { private static readonly EMPTY_IMAGE_EDITS: ImageEdits = {}; /** * Initializer function for creating a new Thumbor mapping, used by the image * handler to perform image modifications based on legacy URL path requests. * @param path The request path. * @returns Image edits based on the request path. */ public mapPathToEdits(path: string): ImageEdits { const fileFormat = path.substr(path.lastIndexOf('.') + 1) as ImageFormatTypes; let edits: ImageEdits = this.mergeEdits(this.mapCrop(path), this.mapResize(path), this.mapFitIn(path)); // parse the image path. we have to sort here to make sure that when we have a file name without extension, // and `format` and `quality` filters are passed, then the `format` filter will go first to be able // to apply the `quality` filter to the target image format. const filters = path .match(/filters:[^)]+/g) ?.map(filter => `${filter})`) .sort() ?? []; for (const filter of filters) { edits = this.mapFilter(filter, fileFormat, edits); } return edits; } /** * Enables users to migrate their current image request model to the SIH solution, * without changing their legacy application code to accommodate new image requests. * @param path The URL path extracted from the web request. * @returns The parsed path using the match pattern and the substitution. */ public parseCustomPath(path: string): string { // Perform the substitution and return const { REWRITE_MATCH_PATTERN, REWRITE_SUBSTITUTION } = process.env; if (path === undefined) { throw new Error('ThumborMapping::ParseCustomPath::PathUndefined'); } else if (REWRITE_MATCH_PATTERN === undefined) { throw new Error('ThumborMapping::ParseCustomPath::RewriteMatchPatternUndefined'); } else if (REWRITE_SUBSTITUTION === undefined) { throw new Error('ThumborMapping::ParseCustomPath::RewriteSubstitutionUndefined'); } else { let parsedPath = ''; if (typeof REWRITE_MATCH_PATTERN === 'string') { const patternStrings = REWRITE_MATCH_PATTERN.split('/'); const flags = patternStrings.pop(); const parsedPatternString = REWRITE_MATCH_PATTERN.slice(1, REWRITE_MATCH_PATTERN.length - 1 - flags.length); const regExp = new RegExp(parsedPatternString, flags); parsedPath = path.replace(regExp, REWRITE_SUBSTITUTION); } else { parsedPath = path.replace(REWRITE_MATCH_PATTERN, REWRITE_SUBSTITUTION); } return parsedPath; } } /** * Scanner function for matching supported Thumbor filters and converting their capabilities into sharp.js supported operations. * @param filterExpression The URL path filter. * @param fileFormat The file type of the original image. * @param previousEdits Cumulative edit, to take into account the previous filters, i.g. `stretch` uses `resize.fit` to make a right update. * @returns Cumulative edits based on the previous edits and the current filter. */ public mapFilter(filterExpression: string, fileFormat: ImageFormatTypes, previousEdits: ImageEdits = {}): ImageEdits { const matched = filterExpression.match(/:(.+)\((.*)\)/); const [_, filterName, filterValue] = matched; const currentEdits = { ...previousEdits }; // Find the proper filter switch (filterName) { case 'autojpg': { currentEdits.toFormat = ImageFormatTypes.JPEG; break; } case 'background_color': { const color = !ColorName[filterValue] ? `#${filterValue}` : filterValue; currentEdits.flatten = { background: Color(color).object() }; break; } case 'blur': { const [radius, sigma] = filterValue.split(',').map(x => (x === '' ? NaN : Number(x))); currentEdits.blur = !isNaN(sigma) ? sigma : radius / 2; break; } case 'convolution': { const values = filterValue.split(','); const matrix = values[0].split(';').map(str => Number(str)); const matrixWidth = Number(values[1]); let matrixHeight = 0; let counter = 0; for (let i = 0; i < matrix.length; i++) { if (counter === matrixWidth - 1) { matrixHeight++; counter = 0; } else { counter++; } } currentEdits.convolve = { width: matrixWidth, height: matrixHeight, kernel: matrix }; break; } case 'equalize': { currentEdits.normalize = true; break; } case 'fill': { if (currentEdits.resize === undefined) { currentEdits.resize = {}; } let color = filterValue; if (!ColorName[color]) { color = `#${color}`; } currentEdits.resize.fit = ImageFitTypes.CONTAIN; currentEdits.resize.background = Color(color).object(); break; } case 'format': { const imageFormatType = filterValue.replace(/[^0-9a-z]/gi, '').replace(/jpg/i, 'jpeg') as ImageFormatTypes; const acceptedValues = [ ImageFormatTypes.HEIC, ImageFormatTypes.HEIF, ImageFormatTypes.JPEG, ImageFormatTypes.PNG, ImageFormatTypes.RAW, ImageFormatTypes.TIFF, ImageFormatTypes.WEBP ]; if (acceptedValues.includes(imageFormatType)) { currentEdits.toFormat = imageFormatType; } break; } case 'grayscale': { currentEdits.grayscale = true; break; } case 'no_upscale': { if (currentEdits.resize === undefined) { currentEdits.resize = {}; } currentEdits.resize.withoutEnlargement = true; break; } case 'proportion': { if (currentEdits.resize === undefined) { currentEdits.resize = {}; } const ratio = Number(filterValue); currentEdits.resize.width = Number(currentEdits.resize.width * ratio); currentEdits.resize.height = Number(currentEdits.resize.height * ratio); break; } case 'quality': { const toSupportedImageFormatType = (format: ImageFormatTypes): ImageFormatTypes => [ImageFormatTypes.JPG, ImageFormatTypes.JPEG].includes(format) ? ImageFormatTypes.JPEG : [ImageFormatTypes.PNG, ImageFormatTypes.WEBP, ImageFormatTypes.TIFF, ImageFormatTypes.HEIF].includes(format) ? format : null; // trying to get a target image type base on `fileFormat` passed to the current method. // if we cannot get the target format, then trying to get the target format from `format` filter. const targetImageFileFormat = toSupportedImageFormatType(fileFormat) ?? toSupportedImageFormatType(currentEdits.toFormat); if (targetImageFileFormat) { currentEdits[targetImageFileFormat] = { quality: Number(filterValue) }; } break; } case 'rgb': { const percentages = filterValue.split(','); const values = percentages.map(percentage => 255 * (Number(percentage) / 100)); const [r, g, b] = values; currentEdits.tint = { r, g, b }; break; } case 'rotate': { currentEdits.rotate = Number(filterValue); break; } case 'sharpen': { const values = filterValue.split(','); currentEdits.sharpen = 1 + Number(values[1]) / 2; break; } case 'stretch': { if (currentEdits.resize === undefined) { currentEdits.resize = {}; } // If fit-in is not defined, fit parameter would be 'fill'. if (currentEdits.resize.fit !== ImageFitTypes.INSIDE) { currentEdits.resize.fit = ImageFitTypes.FILL; } break; } case 'strip_exif': case 'strip_icc': { currentEdits.rotate = null; break; } case 'upscale': { if (currentEdits.resize === undefined) { currentEdits.resize = {}; } currentEdits.resize.fit = ImageFitTypes.INSIDE; break; } case 'watermark': { const options = filterValue.replace(/\s+/g, '').split(','); const [bucket, key, xPos, yPos, alpha, wRatio, hRatio] = options; currentEdits.overlayWith = { bucket, key, alpha, wRatio, hRatio, options: {} }; const allowedPosPattern = /^(100|[1-9]?[0-9]|-(100|[1-9][0-9]?))p$/; if (allowedPosPattern.test(xPos) || !isNaN(Number(xPos))) { currentEdits.overlayWith.options.left = xPos; } if (allowedPosPattern.test(yPos) || !isNaN(Number(yPos))) { currentEdits.overlayWith.options.top = yPos; } break; } } return currentEdits; } /** * Maps the image path to crop image edit. * @param path an image path. * @returns image edits associated with crop. */ private mapCrop(path: string): ImageEdits { const pathCropMatchResult = path.match(/\d+x\d+:\d+x\d+/g); if (pathCropMatchResult) { const [leftTopPoint, rightBottomPoint] = pathCropMatchResult[0].split(':'); const [leftTopX, leftTopY] = leftTopPoint.split('x').map(x => parseInt(x, 10)); const [rightBottomX, rightBottomY] = rightBottomPoint.split('x').map(x => parseInt(x, 10)); if (!isNaN(leftTopX) && !isNaN(leftTopY) && !isNaN(rightBottomX) && !isNaN(rightBottomY)) { const cropEdit: ImageEdits = { crop: { left: leftTopX, top: leftTopY, width: rightBottomX - leftTopX, height: rightBottomY - leftTopY } }; return cropEdit; } } return ThumborMapper.EMPTY_IMAGE_EDITS; } /** * Maps the image path to resize image edit. * @param path An image path. * @returns Image edits associated with resize. */ private mapResize(path: string): ImageEdits { // Process the dimensions const dimensionsMatchResult = path.match(/\/((\d+x\d+)|(0x\d+))\//g); if (dimensionsMatchResult) { // Assign dimensions from the first match only to avoid parsing dimension from image file names const [width, height] = dimensionsMatchResult[0] .replace(/\//g, '') .split('x') .map(x => parseInt(x)); // Set only if the dimensions provided are valid if (!isNaN(width) && !isNaN(height)) { const resizeEdit: ImageEdits = { resize: {} }; // If width or height is 0, fit would be inside. if (width === 0 || height === 0) { resizeEdit.resize.fit = ImageFitTypes.INSIDE; } resizeEdit.resize.width = width === 0 ? null : width; resizeEdit.resize.height = height === 0 ? null : height; return resizeEdit; } } return ThumborMapper.EMPTY_IMAGE_EDITS; } /** * Maps the image path to fit image edit. * @param path An image path. * @returns Image edits associated with fit-in filter. */ private mapFitIn(path: string): ImageEdits { return path.includes('fit-in') ? { resize: { fit: ImageFitTypes.INSIDE } } : ThumborMapper.EMPTY_IMAGE_EDITS; } /** * A helper method to merge edits. * @param edits Edits to merge. * @returns Merged edits. */ private mergeEdits(...edits: ImageEdits[]) { return edits.reduce((result, current) => { Object.keys(current).forEach(key => { if (Array.isArray(result[key]) && Array.isArray(current[key])) { result[key] = Array.from(new Set(result[key].concat(current[key]))); } else if (this.isObject(result[key]) && this.isObject(current[key])) { result[key] = this.mergeEdits(result[key], current[key]); } else { result[key] = current[key]; } }); return result; }, {}) as ImageEdits; } /** * A helper method to check whether a passed argument is object or not. * @param obj Object to check. * @returns Whether or not a passed argument is object. */ private isObject(obj: unknown): boolean { return obj && typeof obj === 'object' && !Array.isArray(obj); } }
the_stack
import { InitializationError, UniswapishPriceError, SERVICE_UNITIALIZED_ERROR_CODE, SERVICE_UNITIALIZED_ERROR_MESSAGE, } from '../../services/error-handler'; import { logger } from '../../services/logger'; import { UniswapConfig } from './uniswap.config'; import { Contract, ContractInterface } from '@ethersproject/contracts'; import { Token, CurrencyAmount, TradeType } from '@uniswap/sdk-core'; import * as uniV3 from '@uniswap/v3-sdk'; import { BigNumber, Transaction, Wallet, utils } from 'ethers'; import { ExpectedTrade, Uniswapish } from '../../services/common-interfaces'; import { UniswapV3Helper } from './uniswap.v3.helper'; const MaxUint128 = BigNumber.from(2).pow(128).sub(1); export type Overrides = { gasLimit: string; gasPrice?: string; value?: string; nonce?: number; maxFeePerGas?: BigNumber; maxPriorityFeePerGas?: BigNumber; }; type SellTrade = uniV3.Trade<Token, Token, TradeType.EXACT_INPUT>; type BuyTrade = uniV3.Trade<Token, Token, TradeType.EXACT_OUTPUT>; export class UniswapV3 extends UniswapV3Helper implements Uniswapish { private static _instances: { [name: string]: UniswapV3 }; private _chain: string; private _gasLimit: number; private _ready: boolean = false; private constructor(chain: string, network: string) { super(network); this._chain = chain; this._gasLimit = UniswapConfig.config.gasLimit(3); } public static getInstance(chain: string, network: string): UniswapV3 { if (UniswapV3._instances === undefined) { UniswapV3._instances = {}; } if (!(chain + network in UniswapV3._instances)) { UniswapV3._instances[chain + network] = new UniswapV3(chain, network); } return UniswapV3._instances[chain + network]; } public async init() { if (this._chain == 'ethereum' && !this.ethereum.ready()) throw new InitializationError( SERVICE_UNITIALIZED_ERROR_MESSAGE('ETH'), SERVICE_UNITIALIZED_ERROR_CODE ); this._ready = true; } public ready(): boolean { return this._ready; } /** * Default gas limit for swap transactions. */ public get gasLimit(): number { return this._gasLimit; } /** * Given the amount of `baseToken` to put into a transaction, calculate the * amount of `quoteToken` that can be expected from the transaction. * * This is typically used for calculating token sell prices. * * @param baseToken Token input for the transaction * @param quoteToken Output from the transaction * @param amount Amount of `baseToken` to put into the transaction */ async estimateSellTrade( baseToken: Token, quoteToken: Token, amount: BigNumber ): Promise<ExpectedTrade> { const tokenAmountIn: CurrencyAmount<Token> = CurrencyAmount.fromRawAmount( baseToken, amount.toString() ); const pools: uniV3.Pool[] = await this.getPairs(baseToken, quoteToken); const trades: SellTrade[] = await uniV3.Trade.bestTradeExactIn( pools, tokenAmountIn, quoteToken, { maxHops: 1 } ); if (!trades || trades.length === 0) { throw new UniswapishPriceError( `priceSwapOut: no trade pair found for ${baseToken.address} to ${quoteToken.address}.` ); } const trade: SellTrade = trades[0]; const expectedAmount: CurrencyAmount<Token> = trade.minimumAmountOut( this.getSlippagePercentage() ); return { trade, expectedAmount }; } /** * Given the amount of `baseToken` desired to acquire from a transaction, * calculate the amount of `quoteToken` needed for the transaction. * * This is typically used for calculating token buy prices. * * @param quoteToken Token input for the transaction * @param baseToken Token output from the transaction * @param amount Amount of `baseToken` desired from the transaction */ async estimateBuyTrade( quoteToken: Token, baseToken: Token, amount: BigNumber ): Promise<ExpectedTrade> { const tokenAmountOut: CurrencyAmount<Token> = CurrencyAmount.fromRawAmount( baseToken, amount.toString() ); const pools: uniV3.Pool[] = await this.getPairs(quoteToken, baseToken); const trades: BuyTrade[] = await uniV3.Trade.bestTradeExactOut( pools, quoteToken, tokenAmountOut, { maxHops: 1 } ); if (!trades || trades.length === 0) { throw new UniswapishPriceError( `priceSwapOut: no trade pair found for ${quoteToken.address} to ${baseToken.address}.` ); } const trade: BuyTrade = trades[0]; const expectedAmount: CurrencyAmount<Token> = trade.maximumAmountIn( this.getSlippagePercentage() ); return { trade, expectedAmount }; } /** * Given a wallet and a Uniswap-ish trade, try to execute it on blockchain. * * @param wallet Wallet * @param trade Expected trade * @param gasPrice Base gas price, for pre-EIP1559 transactions * @param uniswapRouter Router smart contract address * @param ttl How long the swap is valid before expiry, in seconds * @param abi Router contract ABI * @param gasLimit Gas limit * @param nonce (Optional) EVM transaction nonce * @param maxFeePerGas (Optional) Maximum total fee per gas you want to pay * @param maxPriorityFeePerGas (Optional) Maximum tip per gas you want to pay */ async executeTrade( wallet: Wallet, trade: uniV3.Trade<Token, Token, TradeType>, gasPrice: number, uniswapRouter: string, ttl: number, abi: ContractInterface, gasLimit: number, nonce?: number, maxFeePerGas?: BigNumber, maxPriorityFeePerGas?: BigNumber ): Promise<Transaction> { const { calldata, value } = uniV3.SwapRouter.swapCallParameters(trade, { deadline: ttl, recipient: wallet.address, slippageTolerance: this.getSlippagePercentage(), }); const contract: Contract = new Contract(uniswapRouter, abi, wallet); const tx: Transaction = await contract.multicall( [calldata], this.generateOverrides( gasLimit, gasPrice, nonce, maxFeePerGas, maxPriorityFeePerGas, value ) ); logger.info(`Uniswap V3 swap Tx Hash: ${tx.hash}`); return tx; } async getPosition( wallet: Wallet, tokenId: number ): Promise<{ token0: string | undefined; token1: string | undefined; fee: string | undefined; lowerPrice: string; upperPrice: string; amount0: string; amount1: string; unclaimedToken0: string; unclaimedToken1: string; }> { const contract = this.getContract('nft', wallet); const requests = [ contract.positions(tokenId), this.collectFees(wallet, tokenId, true), ]; const positionInfoReq = await Promise.allSettled(requests); const rejected = positionInfoReq.filter( (r) => r.status === 'rejected' ) as PromiseRejectedResult[]; if (rejected.length > 0) throw 'Unable to fetch position'; const positionInfo = ( positionInfoReq.filter( (r) => r.status === 'fulfilled' ) as PromiseFulfilledResult<any>[] ).map((r) => r.value); const position = positionInfo[0]; const feeInfo = positionInfo[1]; const token0 = this.getTokenByAddress(position.token0); const token1 = this.getTokenByAddress(position.token1); const fee = position.fee; const poolAddress = uniV3.Pool.getAddress(token0, token1, fee); const poolData = await this.getPoolState(poolAddress, fee, wallet); const positionInst = new uniV3.Position({ pool: new uniV3.Pool( token0, token1, poolData.fee, poolData.sqrtPriceX96.toString(), poolData.liquidity.toString(), poolData.tick ), tickLower: position.tickLower, tickUpper: position.tickUpper, liquidity: position.liquidity, }); return { token0: token0.symbol, token1: token1.symbol, fee: Object.keys(uniV3.FeeAmount).find( (key) => uniV3.FeeAmount[Number(key)] === position.fee ), lowerPrice: positionInst.token0PriceLower.toFixed(8), upperPrice: positionInst.token0PriceUpper.toFixed(8), amount0: positionInst.amount0.toFixed(8), amount1: positionInst.amount1.toFixed(8), unclaimedToken0: utils.formatUnits( feeInfo.amount0.toString(), token0.decimals ), unclaimedToken1: utils.formatUnits( feeInfo.amount1.toString(), token1.decimals ), }; } async addPosition( wallet: Wallet, tokenIn: Token, tokenOut: Token, amount0: string, amount1: string, fee: uniV3.FeeAmount, lowerPrice: number, upperPrice: number, tokenId: number = 0, gasLimit: number, gasPrice: number, nonce?: number, maxFeePerGas?: BigNumber, maxPriorityFeePerGas?: BigNumber ): Promise<Transaction> { const { calldata, value } = await this.addPositionHelper( wallet, tokenIn, tokenOut, amount0, amount1, fee, lowerPrice, upperPrice, tokenId ); const nftContract = this.getContract('nft', wallet); const tx = await nftContract.multicall( [calldata], this.generateOverrides( gasLimit, gasPrice, nonce, maxFeePerGas, maxPriorityFeePerGas, value ) ); logger.info(`Uniswap V3 Add position Tx Hash: ${tx.hash}`); return tx; } async reducePosition( wallet: Wallet, tokenId: number, decreasePercent: number = 100, getFee: boolean = false, gasLimit: number, gasPrice: number, nonce?: number, maxFeePerGas?: BigNumber, maxPriorityFeePerGas?: BigNumber ): Promise<BigNumber | Transaction> { // Reduce position and burn const contract = this.getContract('nft', wallet); const { calldata, value } = await this.reducePositionHelper( wallet, tokenId, decreasePercent ); if (getFee) { return await contract.estimateGas.multicall([calldata], { value: value, }); } else { const tx = await contract.multicall( [calldata], this.generateOverrides( gasLimit, gasPrice, nonce, maxFeePerGas, maxPriorityFeePerGas, value ) ); logger.info(`Uniswap V3 Remove position Tx Hash: ${tx.hash}`); return tx; } } async collectFees( wallet: Wallet, tokenId: number, isStatic: boolean = false, gasLimit: number = this.gasLimit, gasPrice: number = 0, nonce?: number, maxFeePerGas?: BigNumber, maxPriorityFeePerGas?: BigNumber ): Promise<Transaction | { amount0: BigNumber; amount1: BigNumber }> { const contract = this.getContract('nft', wallet); const collectData = { tokenId: tokenId, recipient: wallet.address, amount0Max: MaxUint128, amount1Max: MaxUint128, }; return isStatic ? await contract.callStatic.collect(collectData) : await contract.collect( collectData, this.generateOverrides( gasLimit, gasPrice, nonce, maxFeePerGas, maxPriorityFeePerGas ) ); } generateOverrides( gasLimit: number, gasPrice: number, nonce?: number, maxFeePerGas?: BigNumber, maxPriorityFeePerGas?: BigNumber, value?: string ): Overrides { const overrides: Overrides = { gasLimit: gasLimit.toFixed(0) }; if (maxFeePerGas && maxPriorityFeePerGas) { overrides.maxFeePerGas = maxFeePerGas; overrides.maxPriorityFeePerGas = maxPriorityFeePerGas; } else { overrides.gasPrice = (gasPrice * 1e9).toFixed(0); } if (nonce) overrides.nonce = nonce; if (value) overrides.value = value; return overrides; } }
the_stack
import React, { useEffect, useRef, useState, useContext } from 'react'; import { useThree } from '@react-three/fiber'; import useAnnounceStore from './announceStore'; import { useA11ySectionContext } from './A11ySection'; import { stylesHiddenButScreenreadable } from './A11yConsts'; import { Html } from './Html'; interface A11yCommonProps { role: 'button' | 'togglebutton' | 'link' | 'content' | 'image'; children: React.ReactNode; description: string; tabIndex?: number; showAltText?: boolean; focusCall?: (...args: any[]) => any; debug?: boolean; a11yElStyle?: Object; hidden?: boolean; } type RoleProps = | { role: 'content'; activationMsg?: never; deactivationMsg?: never; actionCall?: never; href?: never; disabled?: never; startPressed?: never; tag?: 'p' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'; } | { role: 'button'; activationMsg?: string; deactivationMsg?: never; actionCall?: () => any; href?: never; disabled?: boolean; startPressed?: never; tag?: never; } | { role: 'togglebutton'; activationMsg?: string; deactivationMsg?: string; actionCall?: () => any; href?: never; disabled?: boolean; startPressed?: boolean; tag?: never; } | { role: 'link'; activationMsg?: never; deactivationMsg?: never; actionCall: () => any; href: string; disabled?: never; startPressed?: never; tag?: never; } | { role: 'image'; activationMsg?: never; deactivationMsg?: never; actionCall?: never; href?: never; disabled?: never; startPressed?: never; tag?: never; }; type Props = A11yCommonProps & RoleProps; const A11yContext = React.createContext({ focus: false, hover: false, pressed: false, }); A11yContext.displayName = 'A11yContext'; const useA11y = () => { return useContext(A11yContext); }; export { useA11y }; export const A11y: React.FC<Props> = ({ children, description, activationMsg, deactivationMsg, tabIndex, href, role, showAltText = false, actionCall, focusCall, disabled, debug = false, a11yElStyle, startPressed = false, tag = 'p', hidden = false, ...props }) => { let constHiddenButScreenreadable = Object.assign( {}, stylesHiddenButScreenreadable, { opacity: debug ? 1 : 0 }, a11yElStyle ); const [a11yState, setA11yState] = useState({ hovered: false, focused: false, pressed: startPressed ? startPressed : false, }); const a11yScreenReader = useAnnounceStore(state => state.a11yScreenReader); const overHtml = useRef(false); const overMesh = useRef(false); const domElement = useThree(state => state.gl.domElement); // temporary fix to prevent error -> keep track of our component's mounted state const componentIsMounted = useRef(true); useEffect(() => { return () => { domElement.style.cursor = 'default'; componentIsMounted.current = false; }; }, []); // Using an empty dependency array ensures this on React.Children.only(children); // @ts-ignore const handleOnPointerOver = e => { if (e.eventObject) { overMesh.current = true; } else { overHtml.current = true; } if (overHtml.current || overMesh.current) { if (role !== 'content' && role !== 'image' && !disabled) { domElement.style.cursor = 'pointer'; } setA11yState({ hovered: true, focused: a11yState.focused, pressed: a11yState.pressed, }); } }; // @ts-ignore const handleOnPointerOut = e => { if (e.eventObject) { overMesh.current = false; } else { overHtml.current = false; } if (!overHtml.current && !overMesh.current) { if (componentIsMounted.current) { domElement.style.cursor = 'default'; setA11yState({ hovered: false, focused: a11yState.focused, pressed: a11yState.pressed, }); } } }; function handleBtnClick() { //msg is the same need to be clean for it to trigger again in case of multiple press in a row a11yScreenReader(''); window.setTimeout(() => { if (typeof activationMsg === 'string') a11yScreenReader(activationMsg); }, 100); if (typeof actionCall === 'function') actionCall(); } function handleToggleBtnClick() { if (a11yState.pressed) { if (typeof deactivationMsg === 'string') a11yScreenReader(deactivationMsg); } else { if (typeof activationMsg === 'string') a11yScreenReader(activationMsg); } setA11yState({ hovered: a11yState.hovered, focused: a11yState.focused, pressed: !a11yState.pressed, }); if (typeof actionCall === 'function') actionCall(); } const returnHtmlA11yEl = () => { if (role === 'button' || role === 'togglebutton') { let disabledBtnAttr = disabled ? { disabled: true, } : null; if (role === 'togglebutton') { return ( <button r3f-a11y="true" {...disabledBtnAttr} aria-pressed={a11yState.pressed ? 'true' : 'false'} tabIndex={tabIndex ? tabIndex : 0} style={Object.assign( constHiddenButScreenreadable, disabled ? { cursor: 'default' } : { cursor: 'pointer' }, hidden ? { visibility: 'hidden' as const } : { visibility: 'visible' as const } )} onPointerOver={handleOnPointerOver} onPointerOut={handleOnPointerOut} onClick={e => { e.stopPropagation(); if (disabled) { return; } handleToggleBtnClick(); }} onFocus={() => { if (typeof focusCall === 'function') focusCall(); setA11yState({ hovered: a11yState.hovered, focused: true, pressed: a11yState.pressed, }); }} onBlur={() => { setA11yState({ hovered: a11yState.hovered, focused: false, pressed: a11yState.pressed, }); }} > {description} </button> ); } else { //regular btn return ( <button r3f-a11y="true" {...disabledBtnAttr} tabIndex={tabIndex ? tabIndex : 0} style={Object.assign( constHiddenButScreenreadable, disabled ? { cursor: 'default' } : { cursor: 'pointer' }, hidden ? { visibility: 'hidden' as const } : { visibility: 'visible' as const } )} onPointerOver={handleOnPointerOver} onPointerOut={handleOnPointerOut} onClick={e => { e.stopPropagation(); if (disabled) { return; } handleBtnClick(); }} onFocus={() => { if (typeof focusCall === 'function') focusCall(); setA11yState({ hovered: a11yState.hovered, focused: true, pressed: a11yState.pressed, }); }} onBlur={() => { setA11yState({ hovered: a11yState.hovered, focused: false, pressed: a11yState.pressed, }); }} > {description} </button> ); } } else if (role === 'link') { return ( <a r3f-a11y="true" style={Object.assign( constHiddenButScreenreadable, hidden ? { visibility: 'hidden' as const } : { visibility: 'visible' as const } )} href={href} onPointerOver={handleOnPointerOver} onPointerOut={handleOnPointerOut} onClick={e => { e.stopPropagation(); e.preventDefault(); if (typeof actionCall === 'function') actionCall(); }} onFocus={() => { if (typeof focusCall === 'function') focusCall(); setA11yState({ hovered: a11yState.hovered, focused: true, pressed: a11yState.pressed, }); }} onBlur={() => { setA11yState({ hovered: a11yState.hovered, focused: false, pressed: a11yState.pressed, }); }} > {description} </a> ); } else { let tabIndexP = tabIndex ? { tabIndex: tabIndex, } : null; if (role === 'image') { return ( <img r3f-a11y="true" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E" alt={description} {...tabIndexP} style={Object.assign( constHiddenButScreenreadable, hidden ? { visibility: 'hidden' as const } : { visibility: 'visible' as const } )} onPointerOver={handleOnPointerOver} onPointerOut={handleOnPointerOut} onBlur={() => { setA11yState({ hovered: a11yState.hovered, focused: false, pressed: a11yState.pressed, }); }} onFocus={() => { if (typeof focusCall === 'function') focusCall(); setA11yState({ hovered: a11yState.hovered, focused: true, pressed: a11yState.pressed, }); }} /> ); } else { const Tag = tag; return ( <Tag r3f-a11y="true" {...tabIndexP} style={Object.assign( constHiddenButScreenreadable, hidden ? { visibility: 'hidden' as const } : { visibility: 'visible' as const } )} onPointerOver={handleOnPointerOver} onPointerOut={handleOnPointerOut} onBlur={() => { setA11yState({ hovered: a11yState.hovered, focused: false, pressed: a11yState.pressed, }); }} onFocus={() => { if (typeof focusCall === 'function') focusCall(); setA11yState({ hovered: a11yState.hovered, focused: true, pressed: a11yState.pressed, }); }} > {description} </Tag> ); } } }; const HtmlAccessibleElement = React.useMemo(returnHtmlA11yEl, [ description, a11yState, hidden, tabIndex, href, disabled, startPressed, tag, actionCall, focusCall, ]); let AltText = null; if (showAltText && a11yState.hovered) { AltText = ( <div aria-hidden={true} style={{ width: 'auto', maxWidth: '300px', display: 'block', position: 'absolute', top: '0px', left: '0px', transform: 'translate(-50%,-50%)', background: 'white', borderRadius: '4px', padding: '4px', }} > <p aria-hidden={true} style={{ margin: '0px', }} > {description} </p> </div> ); } const section = useA11ySectionContext(); let portal = {}; if (section.current instanceof HTMLElement) { portal = { portal: section }; } return ( <A11yContext.Provider value={{ hover: a11yState.hovered, focus: a11yState.focused, pressed: a11yState.pressed, }} > <group {...props} onClick={e => { e.stopPropagation(); if (disabled) { return; } if (role === 'button') { handleBtnClick(); } else if (role === 'togglebutton') { handleToggleBtnClick(); } else { if (typeof actionCall === 'function') actionCall(); } }} onPointerOver={handleOnPointerOver} onPointerOut={handleOnPointerOut} > {children} <Html style={{ width: '0px' }} position={ // @ts-ignore children.props.position ? children.props.position : 0 } {...portal} > {AltText} {HtmlAccessibleElement} </Html> </group> </A11yContext.Provider> ); };
the_stack
module fng.services { /*@ngInject*/ export function routingService($injector, $locationProvider) { var config:fng.IRoutingConfig = { // fixedRoutes: [] an array in the same format as builtInRoutes that is matched before the generic routes. Can be omitted hashPrefix: '', html5Mode: false, routing: 'ngroute', // What sort of routing do we want? ngroute or uirouter prefix: '' // How do we want to prefix our routes? If not empty string then first character must be slash (which is added if not) }; var postActions: Array<string> = ['edit','view']; var builtInRoutes:Array<fng.IBuiltInRoute> = [ { route: '/analyse/:model/:reportSchemaName', state: 'analyse::model::report', templateUrl: 'base-analysis.html' }, {route: '/analyse/:model', state: 'analyse::model', templateUrl: 'base-analysis.html'}, {route: '/:model/:id/edit', state: 'model::edit', templateUrl: 'base-edit.html'}, {route: '/:model/:id/edit/:tab', state: 'model::edit::tab', templateUrl: 'base-edit.html'}, {route: '/:model/:id/view', state: 'model::edit', templateUrl: 'base-view.html'}, {route: '/:model/:id/view/:tab', state: 'model::view::tab', templateUrl: 'base-view.html'}, {route: '/:model/new', state: 'model::new', templateUrl: 'base-edit.html'}, {route: '/:model', state: 'model::list', templateUrl: 'base-list.html'}, {route: '/:model/viewonly', state: 'model::view', templateUrl: 'base-list-view.html'}, // Non default form (subset of fields etc) {route: '/:model/:form/:id/edit', state: 'model::form::edit', templateUrl: 'base-edit.html'}, {route: '/:model/:form/:id/edit/:tab', state: 'model::form::edit::tab', templateUrl: 'base-edit.html'}, {route: '/:model/:form/:id/view', state: 'model::form::view', templateUrl: 'base-view.html'}, {route: '/:model/:form/:id/view/:tab', state: 'model::form::view::tab', templateUrl: 'base-view.html'}, {route: '/:model/:form/new', state: 'model::form::new', templateUrl: 'base-edit.html'}, {route: '/:model/:form', state: 'model::form::list', templateUrl: 'base-list.html'}, // list page with edit links to non default form {route: '/:model/:form/viewonly', state: 'model::form::list::view', templateUrl: 'base-list-view.html'} // list page with edit links to non default form ]; var _routeProvider, _stateProvider; var lastRoute = null; var lastObject:fng.IFngRoute = {}; function handleFolder(templateURL: string) : string { var retVal : string = templateURL; if (config.templateFolder) { if (config.templateFolder[config.templateFolder.length-1] !== '/') { retVal = config.templateFolder + '/' + retVal; } else { retVal = config.templateFolder + retVal; } } return retVal; } function _setUpNgRoutes(routes:Array<fng.IBuiltInRoute>, prefix:string = '', additional?:any):void { prefix = prefix || ''; angular.forEach(routes, function (routeSpec) { _routeProvider.when(prefix + routeSpec.route, angular.extend(routeSpec.options || {templateUrl: handleFolder(routeSpec.templateUrl)}, additional)); }); // This next bit is just for the demo website to allow demonstrating multiple CSS frameworks - not available with other routers if (config.variantsForDemoWebsite) { angular.forEach(config.variantsForDemoWebsite, function (variant) { angular.forEach(routes, function (routeSpec) { _routeProvider.when(prefix + variant + routeSpec.route, angular.extend(routeSpec.options || {templateUrl: handleFolder(routeSpec.templateUrl)}, additional)); }); }); } } function _setUpUIRoutes(routes:Array<fng.IBuiltInRoute>, prefix:string = '', additional?:any):void { prefix = prefix || ''; angular.forEach(routes, function (routeSpec) { _stateProvider.state(routeSpec.state, angular.extend(routeSpec.options || { url: prefix + routeSpec.route, templateUrl: routeSpec.templateUrl }, additional) ); }); } function _buildOperationUrl(prefix, operation, modelName, formName, id, tabName) { var formString = formName ? ('/' + formName) : ''; var modelString = prefix + '/' + modelName; var tabString = tabName ? ('/' + tabName) : ''; var urlStr; switch (operation) { case 'list' : urlStr = modelString + formString; break; case 'edit' : urlStr = modelString + formString + '/' + id + '/edit' + tabString; break; case 'view' : urlStr = modelString + formString + '/' + id + '/view' + tabString; break; case 'read' : urlStr = modelString + formString + '/' + id + '/read' + tabString; break; case 'new' : urlStr = modelString + formString + '/new' + tabString; break; } return urlStr; } function _setUpRoutes(fixedRoutes:Array<fng.IBuiltInRoute>, fngRoutes:Array<fng.IBuiltInRoute>) { switch (config.routing) { case 'ngroute' : _routeProvider = $injector.get('$routeProvider'); if (fixedRoutes) {_setUpNgRoutes(fixedRoutes)} _setUpNgRoutes(fngRoutes, config.prefix, config.add2fngRoutes); break; case 'uirouter' : _stateProvider = $injector.get('$stateProvider'); if (fixedRoutes) {_setUpUIRoutes(config.fixedRoutes);} _setUpUIRoutes(fngRoutes, config.prefix, config.add2fngRoutes); break; } } return { start: function (options:fng.IRoutingConfig) { angular.extend(config, options); if (config.prefix[0] && config.prefix[0] !== '/') { config.prefix = '/' + config.prefix; } $locationProvider.html5Mode(config.html5Mode); if (config.hashPrefix !== '') { $locationProvider.hashPrefix(config.hashPrefix); } else if (!config.html5Mode) { $locationProvider.hashPrefix(''); } _setUpRoutes(config.fixedRoutes, builtInRoutes); }, addRoutes: function(fixedRoutes:Array<fng.IBuiltInRoute>, fngRoutes:Array<fng.IBuiltInRoute>) { _setUpRoutes( fixedRoutes, fngRoutes); }, registerAction: function(action: string) { postActions.push(action); }, $get: function () { return { router: function () { return config.routing; }, prefix: function () { return config.prefix; }, parsePathFunc: function () { return function (location) { if (location !== lastRoute) { lastRoute = location; lastObject = {newRecord: false}; // Get rid of the prefix if (config.prefix.length > 0) { if (location.indexOf(config.prefix) === 0) { location = location.slice(config.prefix.length); } } var locationSplit = location.split('/'); // get rid of variant if present - just used for demo website if (config.variants) { if (config.variants.indexOf(locationSplit[1]) !== -1) { lastObject.variant = locationSplit[1]; locationSplit.shift(); } } let locationParts = locationSplit.length; if (locationSplit[1] === 'analyse') { lastObject.analyse = true; lastObject.modelName = locationSplit[2]; lastObject.reportSchemaName = locationParts >= 4 ? locationSplit[3] : null; } else { lastObject.modelName = locationSplit[1]; let lastParts = [locationSplit[locationParts - 1], locationSplit[locationParts - 2]]; let newPos = lastParts.indexOf('new'); let viewonlyPos = lastParts.indexOf('viewonly'); let actionPos; if (newPos === -1 && viewonlyPos === -1) { actionPos = postActions.reduce((previousValue, currentValue) => { let pos = lastParts.indexOf(currentValue); return pos > -1 ? pos : previousValue }, -1); if (actionPos !== -1) { locationParts -= (2 + actionPos); lastObject.id = locationSplit[locationParts]; } } else if (newPos !== -1) { lastObject.newRecord = true; locationParts -= (1 + newPos); } else { locationParts -= (1 + viewonlyPos); } if (actionPos === 1 || newPos === 1) { lastObject.tab = lastParts[0]; } if (locationParts > 2) { lastObject.formName = locationSplit[2]; } } } return lastObject; }; }, buildUrl: function (path) { var url = config.html5Mode ? '' : '#'; url += config.hashPrefix; url += config.prefix; if (url[0]) { url += '/'; } url += (path[0] === '/' ? path.slice(1) : path); return url; }, buildOperationUrl: function (operation, modelName, formName, id, tab) { return _buildOperationUrl(config.prefix, operation, modelName, formName, id, tab); }, redirectTo: function () { return function (operation, scope, location, id, tab) { location.search({}); // Lose any search parameters let urlStr: string; if (operation === 'onDelete') { if (config.onDelete) { if (config.onDelete === 'new') { urlStr = _buildOperationUrl(config.prefix, 'new', scope.modelName, scope.formName, id, tab); } else { urlStr = config.onDelete; } } else { urlStr = _buildOperationUrl(config.prefix, 'list', scope.modelName, scope.formName, id, tab); } } else { urlStr = _buildOperationUrl(config.prefix, operation, scope.modelName, scope.formName, id, tab); } location.path(urlStr); }; } }; } }; } }
the_stack
import React from 'react' import ReactDOM from 'react-dom' import * as MaterialUI from '@material-ui/core' import { requestProgress, requestBlockLimiterStatus } from '../scripts/background/request-sender' import { onStorageChanged } from '../scripts/background/storage' import { loadOptions } from '../scripts/background/storage/options' import { TwClient } from '../scripts/background/twitter-api' import BlocklistPage from './popup-ui/new-session-blocklist-page' import ChainBlockSessionsPage from './popup-ui/chainblock-sessions-page' import { isValidPageId, PageId, AvailablePages, pageIcon, pageLabel } from './popup-ui/pages' import { UIContext, RedBlockOptionsContext, BlockLimiterContext, MyselfContext, } from './popup-ui/contexts' import { FollowerChainBlockPageStatesProvider, TweetReactionChainBlockPageStatesProvider, ImportChainBlockPageStatesProvider, UserSearchChainBlockPageStatesProvider, AudioSpaceChainBlockPageStatesProvider, LockPickerPageStatesProvider, } from './popup-ui/ui-states' import MiscPage from './popup-ui/misc-page' import NewSessionFollowersPage from './popup-ui/new-session-followers-page' import NewSessionTweetPage from './popup-ui/new-session-tweet-page' import NewSessionSearchresultPage from './popup-ui/new-session-searchresult-page' import NewSessionAudioSpacePage from './popup-ui/new-session-audiospace-page' import NewSessionLockPickerPage from './popup-ui/new-session-lockpicker-page' import { DialogContent, RBDialog, RedBlockPopupUITheme, TabPanel, MyTooltip, } from './popup-ui/components' import { isRunningSession } from '../scripts/common' import { getCurrentTab } from '../scripts/background/misc' import { checkMessage, getTabContext, TabContext } from './popup' import { getCookieStoreIdFromTab } from '../scripts/background/cookie-handler' import * as i18n from '../scripts/i18n' const UI_UPDATE_DELAY_ON_BUSY = 500 const UI_UPDATE_DELAY_ON_IDLE = 1500 const M = MaterialUI function getVersionAndName() { const manifest = browser.runtime.getManifest() return `${manifest.name} v${manifest.version}` } // https://overreacted.io/making-setinterval-declarative-with-react-hooks/ function useInterval(callback: Function, delay: number | null) { const savedCallback = React.useRef<Function>() // Remember the latest callback. React.useEffect(() => { savedCallback.current = callback }, [callback]) // Set up the interval. React.useEffect(() => { function tick() { savedCallback.current?.() } if (delay === null) { return () => {} } const id = setInterval(tick, delay) return () => clearInterval(id) }, [delay]) } const StyledTab = MaterialUI.withStyles({ root: { minWidth: '48px', '&:disabled': { opacity: 0.3, }, }, })(MaterialUI.Tab) function PopupTopTab({ value, disabled, count, ...props }: { value: PageId count?: number disabled?: boolean }) { const icon = ( <M.Badge color="secondary" badgeContent={count} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} > {pageIcon(value)} </M.Badge> ) return ( <MyTooltip arrow title={pageLabel(value, count)}> <div> <StyledTab {...props} {...{ value, icon, disabled }} /> </div> </MyTooltip> ) } function PopupUITopMenu({ countOfRunningSessions }: { countOfRunningSessions: number }) { const { menuAnchorElem, setMenuAnchorElem, switchPage, popupOpenedInTab, availablePages } = React.useContext(UIContext) function handleOpenInTabClick() { browser.tabs.create({ active: true, url: '/popup/popup.html?istab=1', }) closeMenu() } function handleSettingsClick() { browser.runtime.openOptionsPage() closeMenu() } function switchPageFromMenu(page: PageId) { switchPage(page) closeMenu() } function closeMenu() { setMenuAnchorElem(null) } const MenuItem = React.forwardRef( ( { pageId, count, disabled, }: { pageId: PageId count?: number disabled?: boolean }, ref: React.Ref<any> ) => ( <M.MenuItem ref={ref} dense disabled={disabled} onClick={() => switchPageFromMenu(pageId)}> <M.ListItemIcon>{pageIcon(pageId)}</M.ListItemIcon> {pageLabel(pageId, count)} </M.MenuItem> ) ) return ( <M.Menu keepMounted anchorEl={menuAnchorElem} open={Boolean(menuAnchorElem)} onClose={closeMenu} > <MenuItem pageId="chainblock-sessions-page" count={countOfRunningSessions} /> <MenuItem pageId="new-session-followers-page" disabled={!availablePages['new-session-followers-page']} /> <MenuItem pageId="new-session-tweet-page" disabled={!availablePages['new-session-tweet-page']} /> <MenuItem pageId="new-session-searchresult-page" disabled={!availablePages['new-session-searchresult-page']} /> <MenuItem pageId="new-session-audiospace-page" disabled={!availablePages['new-session-audiospace-page']} /> <MenuItem pageId="new-session-blocklist-page" disabled={!availablePages['new-session-blocklist-page']} /> <MenuItem pageId="new-session-lockpicker-page" disabled={!availablePages['new-session-lockpicker-page']} /> <MenuItem pageId="misc-page" /> {!popupOpenedInTab && ( <M.MenuItem dense onClick={handleOpenInTabClick}> <M.ListItemIcon> <M.Icon>open_in_new</M.Icon> </M.ListItemIcon> {i18n.getMessage('open_in_new_tab')} </M.MenuItem> )} <M.MenuItem dense onClick={handleSettingsClick}> <M.ListItemIcon> <M.Icon>settings</M.Icon> </M.ListItemIcon> {i18n.getMessage('open_settings_ui')} </M.MenuItem> <M.Divider /> <M.MenuItem disabled>{getVersionAndName()}</M.MenuItem> </M.Menu> ) } function PopupMyselfIcon({ myself }: { myself: TwitterUser }) { const description = i18n.getMessage('current_account', [myself.screen_name, myself.name]) return ( <MyTooltip arrow placement="left" title={description}> <M.Button> <M.Avatar style={{ width: 24, height: 24, borderRadius: '50%', }} src={myself.profile_image_url_https} /> </M.Button> </MyTooltip> ) } function PopupApp({ myself, tabContext: { currentUser, currentTweet, currentSearchQuery, currentAudioSpace }, popupOpenedInTab, initialPage, initialRedBlockOptions, }: { myself: Actor | null tabContext: TabContext popupOpenedInTab: boolean initialPage: PageId initialRedBlockOptions: RedBlockStorage['options'] }) { const [tabPage, setTabPage] = React.useState<PageId>(initialPage) const [limiterStatus, setLimiterStatus] = React.useState<BlockLimiterStatus>({ current: 0, max: 500, remained: 500, }) const [modalOpened, setModalOpened] = React.useState(false) const [modalContent, setModalContent] = React.useState<DialogContent | null>(null) const [snackBarMessage, setSnackBarMessage] = React.useState('') const [snackBarOpen, setSnackBarOpen] = React.useState(false) const [menuAnchorElem, setMenuAnchorElem] = React.useState<HTMLElement | null>(null) const darkMode = MaterialUI.useMediaQuery('(prefers-color-scheme:dark)') const [initialLoading, setInitialLoading] = React.useState(true) const [redblockOptions, setRedBlockOptions] = React.useState(initialRedBlockOptions) const [sessions, setSessions] = React.useState<SessionInfo[]>([]) const [recurringInfos, setRecurringInfos] = React.useState<RecurringAlarmInfosObject>({}) // 파이어폭스의 팝업 가로폭 문제 // 참고: popup.css const shrinkedPopup = MaterialUI.useMediaQuery('(width:348px), (width:425px)') const theme = React.useMemo(() => RedBlockPopupUITheme(darkMode), [darkMode]) const [countOfRunningSessions, setCountOfRunningSessions] = React.useState(0) const [delay, setDelay] = React.useState<number | null>(null) useInterval(async () => { if (!myself) { setDelay(null) return } requestProgress().catch(() => {}) requestBlockLimiterStatus(myself.user.id_str).catch(() => {}) }, delay) function openDialog(content: DialogContent) { setModalOpened(true) setModalContent(content) } function closeModal() { setModalOpened(false) } function switchPage(page: PageId) { setTabPage(page) } function handleMenuButtonClick(event: React.MouseEvent<HTMLButtonElement>) { setMenuAnchorElem(event.currentTarget) } function openSnackBar(message: string) { setSnackBarMessage(message) setSnackBarOpen(true) } function handleSnackBarClose(_event: React.SyntheticEvent | React.MouseEvent, reason?: string) { if (reason === 'clickaway') { return } setSnackBarOpen(false) } const availablePages: AvailablePages = { 'new-session-followers-page': !!myself, 'new-session-tweet-page': !!(myself && currentTweet), 'new-session-searchresult-page': !!(myself && currentSearchQuery), 'new-session-blocklist-page': !!myself, 'new-session-audiospace-page': !!(myself && currentAudioSpace), 'new-session-lockpicker-page': !!myself, } React.useEffect(() => { const messageListener = (msg: object) => { if (!checkMessage(msg)) { console.debug('unknown message?', msg) return } switch (msg.messageType) { case 'ChainBlockInfo': setInitialLoading(false) const runningSessionsLength = msg.sessions.filter(isRunningSession).length setCountOfRunningSessions(runningSessionsLength) if (tabPage === 'chainblock-sessions-page') { setSessions(msg.sessions) setRecurringInfos(msg.recurringAlarmInfos) if (runningSessionsLength > 0) { setDelay(UI_UPDATE_DELAY_ON_BUSY) } else { setDelay(UI_UPDATE_DELAY_ON_IDLE) } } else { setDelay(UI_UPDATE_DELAY_ON_IDLE) } break case 'BlockLimiterInfo': if (myself && msg.userId === myself.user.id_str) { const oldValue = limiterStatus.current const newValue = msg.status.current if (oldValue !== newValue) { setLimiterStatus(msg.status) } } break case 'PopupSwitchTab': setTabPage(msg.page) break default: break } } browser.runtime.onMessage.addListener(messageListener) // clean-up return () => { browser.runtime.onMessage.removeListener(messageListener) } }, [limiterStatus, tabPage]) React.useEffect(() => onStorageChanged('options', setRedBlockOptions), []) return ( <M.ThemeProvider theme={theme}> <UIContext.Provider value={{ openDialog, openSnackBar, switchPage, shrinkedPopup, popupOpenedInTab, menuAnchorElem, setMenuAnchorElem, availablePages, initialLoading, }} > <MyselfContext.Provider value={myself}> <RedBlockOptionsContext.Provider value={redblockOptions}> <BlockLimiterContext.Provider value={limiterStatus}> <M.AppBar position="fixed"> <M.Toolbar variant="dense" disableGutters> <M.IconButton color="inherit" onClick={handleMenuButtonClick}> <M.Icon>menu</M.Icon> </M.IconButton> <M.Tabs style={{ flexGrow: 1 }} value={tabPage} onChange={(_ev, val) => setTabPage(val)} > <PopupTopTab value="chainblock-sessions-page" count={countOfRunningSessions} /> <PopupTopTab value="new-session-followers-page" disabled={!availablePages['new-session-followers-page']} /> <PopupTopTab value="new-session-tweet-page" disabled={!availablePages['new-session-tweet-page']} /> <PopupTopTab value="new-session-searchresult-page" disabled={!availablePages['new-session-searchresult-page']} /> {availablePages['new-session-audiospace-page'] && ( <PopupTopTab value="new-session-audiospace-page" disabled={!availablePages['new-session-audiospace-page']} /> )} <PopupTopTab value="new-session-blocklist-page" disabled={!availablePages['new-session-blocklist-page']} /> <PopupTopTab value="new-session-lockpicker-page" disabled={!availablePages['new-session-lockpicker-page']} /> <PopupTopTab value="misc-page" /> </M.Tabs> {myself && <PopupMyselfIcon {...{ myself: myself.user }} />} </M.Toolbar> </M.AppBar> <PopupUITopMenu {...{ countOfRunningSessions }} /> <div className="page"> <M.Container maxWidth="sm" disableGutters> <TabPanel value={tabPage} index="chainblock-sessions-page"> <ChainBlockSessionsPage {...{ sessions, recurringInfos }} /> </TabPanel> <FollowerChainBlockPageStatesProvider initialUser={currentUser}> <TabPanel value={tabPage} index="new-session-followers-page"> <NewSessionFollowersPage /> </TabPanel> </FollowerChainBlockPageStatesProvider> <TweetReactionChainBlockPageStatesProvider initialTweet={currentTweet}> <TabPanel value={tabPage} index="new-session-tweet-page"> <NewSessionTweetPage /> </TabPanel> </TweetReactionChainBlockPageStatesProvider> <UserSearchChainBlockPageStatesProvider currentSearchQuery={currentSearchQuery}> <TabPanel value={tabPage} index="new-session-searchresult-page"> <NewSessionSearchresultPage /> </TabPanel> </UserSearchChainBlockPageStatesProvider> {availablePages['new-session-audiospace-page'] && ( <AudioSpaceChainBlockPageStatesProvider audioSpace={currentAudioSpace!}> <TabPanel value={tabPage} index="new-session-audiospace-page"> <NewSessionAudioSpacePage /> </TabPanel> </AudioSpaceChainBlockPageStatesProvider> )} <LockPickerPageStatesProvider> <TabPanel value={tabPage} index="new-session-lockpicker-page"> <NewSessionLockPickerPage /> </TabPanel> </LockPickerPageStatesProvider> <ImportChainBlockPageStatesProvider> <TabPanel value={tabPage} index="new-session-blocklist-page"> <BlocklistPage /> </TabPanel> </ImportChainBlockPageStatesProvider> <TabPanel value={tabPage} index="misc-page"> <MiscPage /> </TabPanel> </M.Container> </div> </BlockLimiterContext.Provider> </RedBlockOptionsContext.Provider> </MyselfContext.Provider> </UIContext.Provider> <M.Snackbar anchorOrigin={{ horizontal: 'center', vertical: 'bottom', }} open={snackBarOpen} onClose={handleSnackBarClose} autoHideDuration={5000} message={snackBarMessage} action={ <M.IconButton size="small" aria-label="close" color="inherit" onClick={handleSnackBarClose} > <M.Icon fontSize="small">close</M.Icon> </M.IconButton> } /> <RBDialog isOpen={modalOpened} closeModal={closeModal} content={modalContent} /> </M.ThemeProvider> ) } export async function initializeUI() { const initialRedBlockOptions = await loadOptions() const popupOpenedInTab = /\bistab=1\b/.test(location.search) let initialPage: PageId const initialPageMatch = /\bpage=(\S+)\b/.exec(location.search) if (initialPageMatch && isValidPageId(initialPageMatch[1])) { initialPage = initialPageMatch[1] } else { initialPage = 'chainblock-sessions-page' } const tabContext: TabContext = { currentUser: null, currentTweet: null, currentSearchQuery: null, currentAudioSpace: null, } const contextless = { ...tabContext } const currentTab = await getCurrentTab() const cookieStoreId = await getCookieStoreIdFromTab(currentTab) const twClient = new TwClient({ cookieStoreId }) const me = await twClient.getMyself().catch(() => null) let myself: Actor | null if (me) { myself = { user: me, clientOptions: twClient.options, } const { currentTweet, currentUser, currentSearchQuery, currentAudioSpace } = await getTabContext(currentTab, myself, twClient).catch(() => contextless) Object.assign(tabContext, { currentTweet, currentUser, currentSearchQuery, currentAudioSpace, }) } else { myself = null } const appRoot = document.getElementById('app')! const app = ( <PopupApp {...{ myself, tabContext, popupOpenedInTab, initialPage, initialRedBlockOptions, }} /> ) ReactDOM.render(app, appRoot) if (popupOpenedInTab) { document.body.classList.add('ui-tab') } else { document.body.classList.add('ui-popup') } if (me) { requestBlockLimiterStatus(me.id_str).catch(() => {}) requestProgress().catch(() => {}) } fixOverlayScroll(appRoot) } initializeUI() // https://davidwalsh.name/detect-scrollbar-width // Whale 브라우저 등 Overlay 스크롤바 모드에선 스크롤이 안 되는 버그 고침 function fixOverlayScroll(appRoot: HTMLElement) { appRoot.parentElement!.style.height = `${window.innerHeight}px` const div = document.createElement('div') Object.assign(div.style, { width: '100px', height: '100px', overflow: 'scroll', position: 'absolute', top: '-9999px', }) document.body.appendChild(div) const result = div.offsetWidth - div.clientWidth document.body.removeChild(div) if (result !== 0) { return } appRoot.parentElement!.style.overflowY = 'auto' }
the_stack
namespace Textor { export class TextEditor { public set theme(value: ITheme) { for (const propertyName of Object.keys(value)) { this._theme[propertyName] = value[propertyName]; if (propertyName === "fontFamily" || propertyName === "fontSize") { this.updateFont(); } } this.invalidate(); this.update(); } public get theme(): ITheme { return this._theme; } public get themeManager(): IThemeManager { return this._themeManager; } public get language(): ILanguage { return this._languageService.language; } public set language(value: ILanguage) { this._languageService.language = value; } public get tabSize(): number { return this._textModel.tabSize; } public set tabSize(value: number) { this._textModel.tabSize = value; this.invalidate(); this.update(); } public set text(value: string) { this._undoService.begin(); this._undoService.add(new TextUndoUnit(this._textModel, this._textBuffer, this._textBuffer.getTextRange(), value)); this._undoService.add(new SelectionUndoUnit(this._textModel, new TextRange(new TextPosition(0, 0), new TextPosition(0, 0)))); this._undoService.commit(); this._undoService.clear(); this.update(); } public get text(): string { return this._textBuffer.getText(this._textBuffer.getTextRange()); } public get scrollPosition(): TextPosition { return this._scrollPosition; } public get fontSize(): Size { return this._fontSize; } public get size(): TextPosition { return this.getTextPosition(new Point(this._canvas.width, this._canvas.height)); } public get devicePixelRatio(): number { if (("devicePixelRatio" in window) && (window.devicePixelRatio > 1)) { return window.devicePixelRatio; } if (("deviceXDPI" in window.screen) && ("logicalXDPI" in window.screen)) { return window.screen.deviceXDPI / window.screen.logicalXDPI; } return 1; } private _canvas: HTMLCanvasElement; private _context: CanvasRenderingContext2D; private _theme: ITheme; private _themeManager: IThemeManager; private _undoService: UndoService = new UndoService(); private _textChangingHandlers: TextChangeHandler[] = []; private _textChangedHandlers: TextChangeHandler[] = []; private _selectionChangedHandlers: SelectionChangeHandler[] = []; private _textBuffer: TextBuffer; private _textModel: TextModel; private _textController: TextController; private _scrollPosition: TextPosition = new TextPosition(0, 0); private _languageService: LanguageService; private _invalidRectangles: Rectangle[] = []; private _maxColumns: number = -1; private _blinkTimer: number; private _blinkTimerEnabled: boolean = false; private _blinkState: boolean = true; private _fontSize: Size; private _textBuffer_textChanging: (e: TextChangeEvent) => void; private _textBuffer_textChanged: (e: TextChangeEvent) => void; private _textModel_selectionChanged: (e: SelectionChangeEvent) => void; constructor(canvas: HTMLCanvasElement) { this._canvas = canvas; this._context = canvas.getContext("2d"); this._textBuffer_textChanging = (e: TextChangeEvent) => { this.textBuffer_textChanging(e); }; this._textBuffer_textChanged = (e: TextChangeEvent) => { this.textBuffer_textChanged(e); }; this._textModel_selectionChanged = (e: SelectionChangeEvent) => { this.textModel_selectionChanged(e); }; this._textBuffer = new TextBuffer(); this._textBuffer.addEventListener("textchanging", this._textBuffer_textChanging); this._textBuffer.addEventListener("textchanged", this._textBuffer_textChanged); this._textModel = new TextModel(this._undoService, this._textBuffer); this._textModel.addEventListener("selectionchanged", this._textModel_selectionChanged); this._textModel.tabSize = 4; this._textController = new TextController(this, this._canvas); this._languageService = new LanguageService(this); this._themeManager = new ThemeManager(); this._theme = this._themeManager.get("default"); this.updateSize(this._canvas.clientWidth, this._canvas.clientHeight); this.focus(); } public dispose() { this._textController.dispose(); this._textController = null; this._textModel.removeEventListener("selectionchanged", this._textModel_selectionChanged); this._textBuffer.removeEventListener("textchanging", this._textBuffer_textChanging); this._textBuffer.removeEventListener("textchanged", this._textBuffer_textChanged); this._textChangedHandlers = []; this._selectionChangedHandlers = []; } public addEventListener(type: string, callback: (e) => void) { switch (type) { case "textchanging": this._textChangingHandlers.push(callback); break; case "textchanged": this._textChangedHandlers.push(callback); break; case "selectionchanged": this._selectionChangedHandlers.push(callback); break; } } public removeEventListener(type: string, callback: (e) => void) { switch (type) { case "textchanging": this._textChangingHandlers = this._textChangingHandlers.filter((item) => item !== callback); break; case "textchanged": this._textChangedHandlers = this._textChangedHandlers.filter((item) => item !== callback); break; case "selectionchanged": this._selectionChangedHandlers = this._selectionChangedHandlers.filter((item) => item !== callback); break; } } public focus() { this._textController.focus(); } public insertText(text: string) { this._textModel.insertText(text); } public deleteSelection() { this._textModel.deleteSelection(null); } public select(line: number, column: number) { if (line > (this._textBuffer.getLines() - 1)) { line = this._textBuffer.getLines() - 1; if (column > (this._textBuffer.getColumns(line) - 1)) { column = this._textBuffer.getColumns(line) - 1; } } const textPosition: TextPosition = new TextPosition(line, column); const startPosition: TextPosition = this._textModel.toScreenPosition( this._textModel.toBufferPosition(textPosition)); const endPosition: TextPosition = this._textModel.toScreenPosition( this._textModel.toBufferPosition(textPosition)); this._undoService.begin(); this._undoService.add(new SelectionUndoUnit(this._textModel, new TextRange(startPosition, endPosition))); this._undoService.commit(); this.updateScrollPosition(); this.update(); } public selectRange(startLine: number, startColumn: number, endLine: number, endColumn: number) { this._undoService.begin(); this._undoService.add(new SelectionUndoUnit(this._textModel, new TextRange(new TextPosition(startLine, startColumn), new TextPosition(endLine, endColumn)))); this._undoService.commit(); this.updateScrollPosition(); this.update(); } public selectAll() { this._undoService.begin(); this._undoService.add(new SelectionUndoUnit(this._textModel, this._textModel.toScreenRange(this._textBuffer.getTextRange()))); this._undoService.commit(); this.update(); } public selectTo(line: number, column: number) { let textPosition: TextPosition = new TextPosition(line, column); if (textPosition.line < 0) { textPosition.line = 0; } if (textPosition.line >= this._textBuffer.getLines()) { textPosition.line = this._textBuffer.getLines() - 1; } if (textPosition.column < 0) { textPosition.column = 0; } textPosition = this._textModel.toScreenPosition(this._textModel.toBufferPosition(textPosition)); if (!this._textModel.textRange.end.equals(textPosition)) { this._undoService.begin(); this._undoService.add(new SelectionUndoUnit(this._textModel, new TextRange(this._textModel.textRange.start.clone(), textPosition))); this._undoService.commit(); this.updateScrollPosition(); this.update(); } } public selectWord(line: number, column: number) { const textPosition: TextPosition = this._textModel.toBufferPosition(new TextPosition(line, column)); const text: string = this._textBuffer.getLine(textPosition.line); const startColumn: number = this._textModel.findWordBreak(text, textPosition.column + 1, -1); const endColumn: number = this._textModel.findWordBreak(text, textPosition.column, 1); const textRange: TextRange = new TextRange(new TextPosition(textPosition.line, startColumn), new TextPosition(textPosition.line, endColumn)); this._undoService.begin(); this._undoService.add(new SelectionUndoUnit(this._textModel, this._textModel.toScreenRange(textRange))); this._undoService.commit(); this.update(); } public scroll(vertical: number, horizontal: number) { this._scrollPosition.line += vertical; this._scrollPosition.column += horizontal; const size: TextPosition = this.size; const maxLine = ((this._textBuffer.getLines() - size.line) < 0) ? 0 : this._textBuffer.getLines() - size.line; const maxColumn = ((this.getMaxColumns() - size.column + 1) < 0) ? 0 : this.getMaxColumns() - size.column + 1; if (this._scrollPosition.line < 0) { this._scrollPosition.line = 0; } if (this._scrollPosition.line > maxLine) { this._scrollPosition.line = maxLine; } if (this._scrollPosition.column < 0) { this._scrollPosition.column = 0; } if (this._scrollPosition.column > maxColumn) { this._scrollPosition.column = maxColumn; } this.invalidate(); } public undo() { this._undoService.undo(); this.updateScrollPosition(); this.update(); } public redo() { this._undoService.redo(); this.updateScrollPosition(); this.update(); } public cut() { this.copy(); this.deleteSelection(); this.updateScrollPosition(); this.update(); } public copy() { const textRange: TextRange = this._textModel.toBufferRange(this._textModel.getTextRange()); if (!textRange.isEmpty) { const text: string = this._textBuffer.getText(textRange); if (window.clipboardData && window.clipboardData.getData) { window.clipboardData.setData("Text", text); // IE } else { this._textController.copy(text); } } } public paste(text: string) { if (text) { this.insertText(text); this.updateScrollPosition(); this.update(); } } public createTextReader(): TextReader { return new TextReader(this._textBuffer); } public processKey(keyCode: number, shiftKey: boolean, ctrlKey: boolean, altKey: boolean, metaKey: boolean) { if ((ctrlKey || metaKey) && !altKey) { if (keyCode === 65) { this.selectAll(); return true; } else if (keyCode === 88) { if (window.clipboardData && window.clipboardData.setData) { this.cut(); return true; } } else if (keyCode === 67) { if (window.clipboardData && window.clipboardData.setData) { this.copy(); return true; } } else if (keyCode === 86) { if (window.clipboardData && window.clipboardData.getData) { const text = window.clipboardData.getData("Text"); if (text) { this.paste(text); return true; } } } else if ((keyCode === 90) && (!shiftKey)) { this.undo(); return true; } else if (((keyCode === 90) && (shiftKey)) || (keyCode === 89)) { this.redo(); return true; } } if (!metaKey && !altKey) { if (keyCode === 37) { this._textModel.moveCursor("column", !ctrlKey ? "1" : "word", "previous", shiftKey); this.updateScrollPosition(); return true; } else if (keyCode === 39) { this._textModel.moveCursor("column", !ctrlKey ? "1" : "word", "next", shiftKey); this.updateScrollPosition(); return true; } else if (keyCode === 38) { if (!ctrlKey) { this._textModel.moveCursor("line", "1", "previous", shiftKey); this.updateScrollPosition(); } else { this.scroll(-1, 0); } return true; } else if (keyCode === 40) { if (!ctrlKey) { this._textModel.moveCursor("line", "1", "next", shiftKey); this.updateScrollPosition(); } else { this.scroll(+1, 0); } return true; } else if (!ctrlKey) { if (keyCode === 8) { this._textModel.deleteSelection("previous"); this.updateScrollPosition(); return true; } else if (keyCode === 9) { this.insertText("\t"); this.updateScrollPosition(); return true; } else if (keyCode === 13) { this.insertText("\n" + this._textModel.getIndent()); this.updateScrollPosition(); return true; } else if (keyCode === 45) { this._textModel.insertText(" "); this.updateScrollPosition(); return true; } else if (keyCode === 46) { this._textModel.deleteSelection("next"); this.updateScrollPosition(); return true; } else if (keyCode === 32) { this.insertText(" "); this.updateScrollPosition(); return true; } else if (keyCode === 33) { if (shiftKey) { this._textModel.moveCursor("line", this.size.line.toString(), "previous", shiftKey); this.updateScrollPosition(); } else { this.scroll(-this.size.line, 0); } return true; } else if (keyCode === 34) { if (shiftKey) { this._textModel.moveCursor("line", this.size.line.toString(), "next", shiftKey); this.updateScrollPosition(); } else { this.scroll(+this.size.line, 0); } return true; } else if (keyCode === 35) { this._textModel.moveCursor("column", "boundary", "next", shiftKey); this.updateScrollPosition(); return true; } else if (keyCode === 36) { this._textModel.moveCursor("column", "boundary", "previous", shiftKey); this.updateScrollPosition(); return true; } } } } public updateScrollPosition() { const size: TextPosition = this.size; size.line--; size.column--; const textRange = this._textModel.textRange; const selection = textRange.end.clone(); if (selection.line > this._textBuffer.getLines() - 1) { selection.line = this._textBuffer.getLines() - 1; } const maxPosition = this._textModel.toScreenPosition( new TextPosition(selection.line, this._textBuffer.getColumns(selection.line))); if (selection.column > maxPosition.column - 1) { selection.column = maxPosition.column - 1; } selection.line -= this._scrollPosition.line; selection.column -= this._scrollPosition.column; let vertical = 0; let horizontal = 0; if (selection.line < 0) { vertical = selection.line; } else if (selection.line > size.line) { vertical = selection.line - size.line; } if (selection.column < 5) { // scroll left with a 5 character margin horizontal = selection.column - 5; if (this._scrollPosition.column + horizontal < 0) { horizontal = -this._scrollPosition.column; } } else if (selection.column > (size.column - 5)) { // scroll right with a 5 character margin horizontal = selection.column - size.column + 5; const maxColumns = this.getMaxColumns(); if (this._scrollPosition.column + horizontal + size.column > maxColumns + 1) { horizontal = maxColumns - size.column - this._scrollPosition.column + 1; } } if ((horizontal !== 0) || (vertical !== 0)) { this.scroll(vertical, horizontal); } } public updateSize(width: number, height: number) { this._canvas.style.width = width.toString(); this._canvas.style.height = height.toString(); this._canvas.width = width * this.devicePixelRatio; this._canvas.height = height * this.devicePixelRatio; this.updateFont(); this.invalidate(); this.update(); } public getTextPosition(point: Point): TextPosition { const paddingLeft: number = parseFloat(this._theme.paddingLeft); const paddingTop: number = parseFloat(this._theme.paddingTop); const column: number = Math.floor((point.x - paddingLeft) / this.fontSize.width); const line: number = Math.floor((point.y - paddingTop) / this.fontSize.height); return new TextPosition(line, column); } public invalidate() { this.invalidateRectangle(new Rectangle(0, 0, this._canvas.width, this._canvas.height)); } public invalidateRange(textRange: TextRange) { const fontSize: Size = this.fontSize; const paddingLeft: number = parseFloat(this._theme.paddingLeft); const paddingTop: number = parseFloat(this._theme.paddingTop); const range = textRange.normalize(); range.start.line -= this._scrollPosition.line; range.end.line -= this._scrollPosition.line; range.start.column -= this._scrollPosition.column; range.end.column -= this._scrollPosition.column; let x = paddingLeft; const y = paddingTop + (range.start.line * fontSize.height); if (textRange.start.line === textRange.end.line) { x += range.start.column * fontSize.width; const width: number = (range.end.column - range.start.column) * fontSize.width; this.invalidateRectangle(new Rectangle(x, y , width, fontSize.height)); } else { const height: number = (range.end.line - range.start.line + 1) * fontSize.height; this.invalidateRectangle(new Rectangle(x, y, this._canvas.width, height)); } } public update() { if (this._invalidRectangles.length !== 0) { // merge invalid rectangles to a single clip rectangle let clipRectangle: Rectangle = this._invalidRectangles[0]; for (let i = 1; i < this._invalidRectangles.length; i++) { clipRectangle = clipRectangle.union(this._invalidRectangles[i]); } if ((clipRectangle.width !== 0) && (clipRectangle.height !== 0)) { this._context.save(); // apply clip rectangle this._context.beginPath(); this._context.rect(clipRectangle.x, clipRectangle.y, clipRectangle.width, clipRectangle.height); this._context.clip(); const focused: boolean = this._textController.isFocused(); // erase background this._context.fillStyle = focused ? this._theme.backgroundColor : this._theme.backgroundBlurColor; this._context.fillRect(0, 0, this._canvas.width, this._canvas.height); const size: TextPosition = this.size; const fontSize: Size = this.fontSize; const paddingLeft: number = parseFloat(this._theme.paddingLeft); const paddingTop: number = parseFloat(this._theme.paddingTop); const selection: TextRange = this._textModel.getTextRange(); selection.start.line -= this._scrollPosition.line; selection.end.line -= this._scrollPosition.line; selection.start.column -= this._scrollPosition.column; selection.end.column -= this._scrollPosition.column; if (this._textModel.isCursor()) { // draw selected line this._context.fillStyle = this._theme.cursorBackgroundColor; const y = (selection.start.line * fontSize.height) + paddingTop; this._context.fillRect(0, y, this._canvas.width, fontSize.height); if (this._blinkState && this._textController.isFocused()) { // draw insertion point this._context.fillStyle = this._theme.cursorColor; this._context.fillRect(paddingLeft + (selection.start.column * fontSize.width), y, 1, fontSize.height); } } else { // draw selection this._context.fillStyle = focused ? this._theme.selectionColor : this._theme.selectionBlurColor; let y = 0; for (let line = 0; line < size.line; line++) { let x = 0; let width = this._canvas.width; if (line === selection.start.line) { x = (selection.start.column < 0) ? 0 : selection.start.column * fontSize.width; } if (line === selection.end.line) { width = (selection.end.column * fontSize.width) - x; } if ((line >= selection.start.line) && (line <= selection.end.line) && (width > 0)) { this._context.fillRect(x + paddingLeft, y + paddingTop, width, fontSize.height); } y += fontSize.height; } } // draw text const stylesTable = { text: true }; const styles = [ "text" ]; const font = this._context.font; this._context.shadowOffsetX = 0; this._context.shadowOffsetY = 0; for (let i = 0; i < styles.length; i++) { // apply style const currentStyle = styles[i]; const theme: string = this._theme[currentStyle + "Style"]; const themeProperties: string[] = theme.split(" "); this._context.fillStyle = themeProperties[0]; this._context.font = ((themeProperties.length === 2) && (themeProperties[1] === "italic")) ? ("italic " + font) : font; this._context.font = ((themeProperties.length === 2) && (themeProperties[1] === "bold")) ? ("bold " + font) : font; let y = Math.floor(fontSize.height * 0.8) + paddingTop; for (let line = this._scrollPosition.line; line < (this._scrollPosition.line + size.line); line++) { if (line < this._textBuffer.getLines()) { const text: string = this._textBuffer.getLine(line); const syntax: LanguageStyle[] = this._languageService.getStyles(line); let index: number = 0; let style: string = "text"; // var state = null; let column: number = 0; let position: number = 0; while (position < text.length) { if (index < syntax.length) { style = syntax[index].style; // when rendering the first style collect all other styles in use. if ((i === 0) && !stylesTable.hasOwnProperty(style)) { stylesTable[style] = true; styles.push(style); } // debug code to show colorizer restart locations // if (syntax[index].state !== null) // { // this._context.save(); // this._context.fillStyle = "#ff0000"; // this._context.fillRect((column - this._scrollPosition.column) * fontSize.width + padding.left + 2.5, y - Math.floor(fontSize.height * 0.8) + 0.5, 0.5, fontSize.height - 2); // this._context.restore(); // } index++; } const length = (index < syntax.length) ? (syntax[index].start - position) : (text.length - position); let part = ""; for (let n: number = position; n < position + length; n++) { part += (text[n] !== "\t") ? text[n] : this._textModel.tabText; } if ((currentStyle === style) && ((column - this._scrollPosition.column + part.length) > 0) && ((column - this._scrollPosition.column) < size.column)) { this._context.fillText(part, (column - this._scrollPosition.column) * fontSize.width + paddingLeft, y); } position += length; column += part.length; } } y += fontSize.height; } } this._context.restore(); // draw clip rectangle // this._context.strokeStyle = "#f00"; // this._context.lineWidth = 2; // this._context.strokeRect(clipRectangle.x, clipRectangle.y, clipRectangle.width, clipRectangle.height); } this._invalidRectangles = []; this._textController.updateTextAreaPosition(); } } private updateFont() { const fontSize: number = parseFloat(this._theme.fontSize) * this.devicePixelRatio; this._context.font = fontSize + "px " + this._theme.fontFamily; const width = this._context.measureText("XXXXXXXXXXXXXXXXXXXX").width / 20; const height = Math.floor(fontSize * 1.5); this._fontSize = new Size(width, height); } private getMaxColumns(): number { // find the longest line in the buffer. if (this._maxColumns === -1) { // TODO can this be optimized to update incrementatlly? for (let line = 0; line < this._textBuffer.getLines(); line++) { const length = this._textModel.getColumns(line); if (this._maxColumns < length) { this._maxColumns = length; } } } return this._maxColumns; } private invalidateSelection(textRange: TextRange) { this.invalidateRange(textRange); // invalidate current line including padding area const paddingLeft: number = parseFloat(this._theme.paddingLeft); const paddingTop: number = parseFloat(this._theme.paddingTop); const fontSize = this.fontSize; const rectangle = new Rectangle(0, ((textRange.end.line - this._scrollPosition.line) * fontSize.height) + paddingTop, this._canvas.width, fontSize.height); this.invalidateRectangle(rectangle); } private invalidateRectangle(rectangle: Rectangle) { if (rectangle.x < 0) { rectangle.x = 0; } if (rectangle.y < 0) { rectangle.y = 0; } if ((rectangle.x + rectangle.width) > this._canvas.width) { rectangle.width = this._canvas.width - rectangle.x; } if ((rectangle.y + rectangle.height) > this._canvas.height) { rectangle.height = this._canvas.height - rectangle.y; } this._invalidRectangles.push(rectangle); } private textBuffer_textChanging(e: TextChangeEvent) { // invalidate old range const textRange: TextRange = this._textModel.toScreenRange(e.oldRange.normalize()); textRange.end.column = this.size.column + this._scrollPosition.column; if (textRange.start.line !== textRange.end.line) { textRange.end.line = this.size.line + this._scrollPosition.line; } this.invalidateRange(textRange); // propagate the event to client code this.onTextChanging(e); } private textBuffer_textChanged(e: TextChangeEvent) { // max width of text might have changed this._maxColumns = -1; // invalidate new range const textRange: TextRange = this._textModel.toScreenRange(e.newRange.normalize()); textRange.end.column = this.size.column + this._scrollPosition.column; if (textRange.start.line !== textRange.end.line) { textRange.end.line = this.size.line + this._scrollPosition.line; } this.invalidateRange(textRange); this._languageService.invalidate(e.oldRange, e.newRange, e.text); // propagate the event to client code this.onTextChanged(e); } private textModel_selectionChanged(e: SelectionChangeEvent) { this.invalidateSelection(e.oldRange); this.invalidateSelection(e.newRange); if (this._blinkTimerEnabled) { window.clearInterval(this._blinkTimer); this._blinkTimerEnabled = false; this._blinkState = true; } const textRange: TextRange = e.newRange.clone(); if (textRange.isEmpty) { // timer for blinking cursor this._blinkTimerEnabled = true; this._blinkTimer = window.setInterval(function() { this.invalidateSelection(textRange); this.update(); this._blinkState = !this._blinkState; }.bind(this), 600); } // propagate the event to client code this.onSelectionChanged(e); } private onTextChanged(e: TextChangeEvent) { for (const handler of this._textChangedHandlers) { handler(e); } } private onTextChanging(e: TextChangeEvent) { for (const handler of this._textChangingHandlers) { handler(e); } } private onSelectionChanged(e: SelectionChangeEvent) { for (const handler of this._selectionChangedHandlers) { handler(e); } } } }
the_stack
export const SEQ = 'sequential'; export const SIN = 'singlehue'; export const QUA = 'qualitative'; export const DIV = 'diverging'; export const DataVizColors = { aqua: '#12939A', tumbleweed: '#DDB27C', mule_fawn: '#88572C', tree_poppy: '#FF991F', flame: '#F15C17', sapphire: '#223F9A', orchid: '#DA70BF', chathams_blue: '#125C77', med_aquamarine: '#4DC19C', crocodile: '#776E57', java: '#17B8BE', chalky: '#F6D18A', light_taupe: '#B7885E', peach_orange: '#FFCB99', apricot: '#F89570', portage: '#829AE3', light_orchid: '#E79FD5', blue_green: '#1E96BE', bermuda: '#89DAC1', cloudy: '#B3AD9E' }; const quaColors = Object.values(DataVizColors); const qualitativeColors = [ { name: 'Uber Viz Qualitative 0', type: QUA, category: 'Uber', colors: quaColors.slice(0, 3) }, { name: 'Uber Viz Qualitative 0.5', type: QUA, category: 'Uber', colors: quaColors.slice(0, 4) }, { name: 'Uber Viz Qualitative 1', type: QUA, category: 'Uber', colors: quaColors.slice(0, 5) }, { name: 'Uber Viz Qualitative 1.2', type: QUA, category: 'Uber', colors: quaColors.slice(0, 6) }, { name: 'Uber Viz Qualitative 1.4', type: QUA, category: 'Uber', colors: quaColors.slice(0, 7) }, { name: 'Uber Viz Qualitative 1.6', type: QUA, category: 'Uber', colors: quaColors.slice(0, 8) }, { name: 'Uber Viz Qualitative 1.8', type: QUA, category: 'Uber', colors: quaColors.slice(0, 9) }, { name: 'Uber Viz Qualitative 2', type: QUA, category: 'Uber', colors: quaColors.slice(0, 10) }, { name: 'Uber Viz Qualitative 3', type: QUA, category: 'Uber', colors: quaColors.slice(0, 15) }, { name: 'Uber Viz Qualitative 4', type: QUA, category: 'Uber', colors: quaColors.slice(0, 20) } ]; const sequantialColors = [ { name: 'Uber Viz Sequential 1', type: SEQ, category: 'Uber', colors: ['#E6FAFA', '#89C6CA', '#00939C'] }, { name: 'Uber Viz Sequential 2', type: SEQ, category: 'Uber', colors: ['#E6FAFA', '#AAD7DA', '#68B4BB', '#00939C'] }, { name: 'Uber Viz Sequential 3', type: SEQ, category: 'Uber', colors: ['#E6FAFA', '#B8E0E1', '#89C6CA', '#56ACB3', '#00939C'] }, { name: 'Uber Viz Sequential 4', type: SEQ, category: 'Uber', colors: ['#E6FAFA', '#C1E5E6', '#9DD0D4', '#75BBC1', '#4BA7AF', '#00939C'] }, { name: 'Uber Viz Sequential 5', type: SEQ, category: 'Uber', colors: ['#E6FAFA', '#C1E5E6', '#9DD0D4', '#75BBC1', '#4BA7AF', '#00939C', '#108188'] }, { name: 'Uber Viz Sequential 6', type: SEQ, category: 'Uber', colors: ['#E6FAFA', '#C1E5E6', '#9DD0D4', '#75BBC1', '#4BA7AF', '#00939C', '#108188', '#0E7077'] } ]; const divergingColors = [ { name: 'Uber Viz Diverging 0', type: DIV, category: 'Uber', colors: ['#C22E00', '#FEEEE8', '#00939C'].reverse() }, { name: 'Uber Viz Diverging 0.5', type: DIV, category: 'Uber', colors: ['#C22E00', '#EFBEAE', '#A2D4D7', '#00939C'].reverse() }, { name: 'Uber Viz Diverging 1', type: DIV, category: 'Uber', colors: ['#C22E00', '#EC9370', '#FEEEE8', '#85C4C8', '#00939C'].reverse() }, { name: 'Uber Viz Diverging 1.5', type: DIV, category: 'Uber', colors: ['#C22E00', '#DD7755', '#F8C0AA', '#BAE1E2', '#5DBABF', '#00939C'].reverse() }, { name: 'Uber Viz Diverging 2', type: DIV, category: 'Uber', colors: ['#C22E00', '#E17449', '#F5B097', '#FEEEE8', '#A2D4D7', '#65B3BA', '#00939C'].reverse() }, { name: 'Uber Viz Diverging 2.5', type: DIV, category: 'Uber', colors: [ '#C22E00', '#D45F39', '#E68F71', '#F8C0AA', '#BAE1E2', '#7CC7CB', '#3EADB3', '#00939C' ].reverse() }, { name: 'Uber Viz Diverging 3', type: DIV, category: 'Uber', colors: [ '#C22E00', '#DA6436', '#EC9370', '#F8C0AA', '#FEEEE8', '#B2DCDF', '#65B3BA', '#49A6AE', '#00939C' ].reverse() }, { name: 'Uber Viz Diverging 3.5', type: DIV, category: 'Uber', colors: [ '#C22E00', '#D0532B', '#DD7755', '#EB9C80', '#F8C0AA', '#BAE1E2', '#8CCED1', '#5DBABF', '#2FA7AE', '#00939C' ].reverse() }, { name: 'Uber Viz Diverging 4', type: DIV, category: 'Uber', colors: [ '#C22E00', '#D55A2B', '#E68059', '#F2A587', '#F8C0AA', '#FEEEE8', '#BAE1E2', '#97CED1', '#71BABF', '#49A6AE', '#00939C' ].reverse() } ]; const customPalette = [ { name: 'UberPool', type: DIV, category: 'Uber', colors: [ '#223F9A', '#2C51BE', '#482BBD', '#7A0DA6', '#AE0E7F', '#CF1750', '#E31A1A', '#FD7900', '#FAC200', '#FAE300' ] }, { name: 'UberPool 9', type: DIV, category: 'Uber', colors: [ '#2C51BE', '#482BBD', '#7A0DA6', '#AE0E7F', '#CF1750', '#E31A1A', '#FD7900', '#FAC200', '#FAE300' ] }, { name: 'UberPool 8', type: DIV, category: 'Uber', colors: ['#213E9A', '#3C1FA7', '#811CB5', '#C318B0', '#D01367', '#DE0F0E', '#EC7007', '#F9E200'] }, { name: 'UberPool 7', type: DIV, category: 'Uber', colors: ['#213E9A', '#461FA9', '#9B1BBA', '#CA168E', '#DA102C', '#E95E08', '#F9E200'] }, { name: 'UberPool 6', type: DIV, category: 'Uber', colors: ['#213E9A', '#551EAD', '#C019BD', '#D31256', '#E6470A', '#F9E200'] }, { name: 'UberPool 5', type: DIV, category: 'Uber', colors: ['#213E9A', '#6E1DB2', '#CA168E', '#E2260C', '#F9E200'] }, { name: 'UberPool 4', type: DIV, category: 'Uber', colors: ['#213E9A', '#9B1BBA', '#DA102C', '#F9E200'] }, { name: 'UberPool 3', type: DIV, category: 'Uber', colors: ['#213E9A', '#CA168E', '#F9E200'] }, { name: 'Ice And Fire 3', type: DIV, category: 'Uber', colors: ['#0198BD', '#FAFEB3', '#D50255'] }, { name: 'Ice And Fire 4', type: DIV, category: 'Uber', colors: ['#0198BD', '#E8FEB5', '#FEAD54', '#D50255'] }, { name: 'Ice And Fire 5', type: DIV, category: 'Uber', colors: ['#0198BD', '#49E3CE', '#FAFEB3', '#FEAD54', '#D50255'] }, { name: 'Ice And Fire', type: DIV, category: 'Uber', colors: ['#0198BD', '#49E3CE', '#E8FEB5', '#FEEDB1', '#FEAD54', '#D50255'] }, { name: 'Ice And Fire 7', type: DIV, category: 'Uber', colors: ['#0198BD', '#54BAB9', '#A7DCB6', '#FAFEB3', '#FCD583', '#FEAD54', '#D50255'] }, { name: 'Ice And Fire 8', type: DIV, category: 'Uber', colors: ['#007A99', '#0198BD', '#49E3CE', '#E8FEB5', '#FEEDB1', '#FEAD54', '#D50255', '#7F1941'] }, { name: 'Global Warming 3', type: SEQ, category: 'Uber', colors: ['#5A1846', '#C70039', '#FFC300'] }, { name: 'Global Warming 4', type: SEQ, category: 'Uber', colors: ['#5A1846', '#831A3D', '#E3611C', '#FFC300'] }, { name: 'Global Warming 5', type: SEQ, category: 'Uber', colors: ['#5A1846', '#831A3D', '#AC1C17', '#D55D0E', '#FFC300'] }, { name: 'Global Warming', type: SEQ, category: 'Uber', colors: ['#5A1846', '#900C3F', '#C70039', '#E3611C', '#F1920E', '#FFC300'] }, { name: 'Global Warming 7', type: SEQ, category: 'Uber', colors: ['#5A1846', '#751A43', '#911932', '#AC1C17', '#C84411', '#E37B0A', '#FFC300'] }, { name: 'Global Warming 8', type: SEQ, category: 'Uber', colors: ['#4C0035', '#650031', '#7F0023', '#98000A', '#B21800', '#CB4600', '#E57F00', '#FFC300'] }, { name: 'Sunrise 3', type: SEQ, category: 'Uber', colors: ['#355C7D', '#C06C84', '#F8B195'] }, { name: 'Sunrise 4', type: SEQ, category: 'Uber', colors: ['#355C7D', '#9A627C', '#C86A7E', '#F8B195'] }, { name: 'Sunrise', type: SEQ, category: 'Uber', colors: ['#355C7D', '#6C5B7B', '#C06C84', '#F67280', '#F8B195'] }, { name: 'Sunrise 6', type: SEQ, category: 'Uber', colors: ['#355C7D', '#63617F', '#916681', '#D88185', '#E8998D', '#F8B195'] }, { name: 'Sunrise 7', type: SEQ, category: 'Uber', colors: ['#355C7D', '#63617F', '#916681', '#C06C84', '#D28389', '#E59A8F', '#F8B195'] }, { name: 'Sunrise 8', type: SEQ, category: 'Uber', colors: ['#194266', '#355C7D', '#63617F', '#916681', '#C06C84', '#D28389', '#E59A8F', '#F8B195'] }, { name: 'Ocean Green 3', type: SEQ, category: 'Uber', colors: ['#3A748A', '#3EACA8', '#E5EEc1'] }, { name: 'Ocean Green 4', type: SEQ, category: 'Uber', colors: ['#547A82', '#3EACA8', '#A2D4AB', '#E5EEc1'] }, { name: 'Ocean Green 5', type: SEQ, category: 'Uber', colors: ['#3A748A', '#54A38F', '#73BC84', '#A9D597', '#E5EEc1'] }, { name: 'Ocean Green 6', type: SEQ, category: 'Uber', colors: ['#37535E', '#3A748A', '#4095B5', '#52AEC9', '#72BFC4', '#93CFBF'] }, { name: 'Ocean Green 7', type: SEQ, category: 'Uber', colors: ['#3A748A', '#4B9A95', '#5EAB8B', '#73BC84', '#92CC8B', '#BEDDA5', '#E5EEc1'] }, { name: 'Ocean Green 8', type: SEQ, category: 'Uber', colors: ['#37535E', '#3A748A', '#4B9A95', '#5EAB8B', '#73BC84', '#92CC8B', '#BEDDA5', '#E5EEc1'] }, { name: 'Pink Wine 3', type: SEQ, category: 'Uber', colors: ['#50315E', '#956485', '#EDD1CA'] }, { name: 'Pink Wine 4', type: SEQ, category: 'Uber', colors: ['#50315E', '#774976', '#B28294', '#EDD1CA'] }, { name: 'Pink Wine 5', type: SEQ, category: 'Uber', colors: ['#50315E', '#643D68', '#956485', '#C1939D', '#EDD1CA'] }, { name: 'Pink Wine 6', type: SEQ, category: 'Uber', colors: ['#2C1E3D', '#573660', '#83537C', '#A6758E', '#C99DA4', '#EDD1CA'] }, { name: 'Pink Wine 7', type: SEQ, category: 'Uber', colors: ['#2C1E3D', '#4F315A', '#774976', '#956485', '#B28294', '#CFA4A8', '#EDD1CA'] }, { name: 'Pink Wine', type: SEQ, category: 'Uber', colors: ['#2C1E3D', '#50315E', '#764476', '#9A5B88', '#B77495', '#CF91A3', '#E0B1B3', '#EDD1CA'] }, { name: 'Purple Blue Yellow 3', type: SEQ, category: 'Uber', colors: ['#2B1E3E', '#5EA28D', '#D6DEBF'] }, { name: 'Purple Blue Yellow 4', type: SEQ, category: 'Uber', colors: ['#2B1E3E', '#466373', '#7BA889', '#D6DEBF'] }, { name: 'Purple Blue Yellow 5', type: SEQ, category: 'Uber', colors: ['#2B1E3E', '#3A4B66', '#5F8E86', '#8BB68D', '#D6DEBF'] }, { name: 'Purple Blue Yellow 6', type: SEQ, category: 'Uber', colors: ['#2B1E3E', '#343D5E', '#4F777E', '#709E87', '#99BE95', '#D6DEBF'] }, { name: 'Purple Blue Yellow 7', type: SEQ, category: 'Uber', colors: ['#2B1E3E', '#303558', '#466373', '#5F8E86', '#7BA889', '#A4C39B', '#D6DEBF'] }, { name: 'Purple Blue Yellow', type: SEQ, category: 'Uber', colors: ['#2B1E3E', '#383C65', '#3E5F7E', '#49838A', '#5EA28D', '#82BB92', '#AECEA1', '#D6DEBF'] } ]; export const VizColorPalette = [ ...divergingColors, ...sequantialColors, ...qualitativeColors, ...customPalette ];
the_stack
/** * * Copyright 2018 Infosys Ltd. * Use of this source code is governed by MIT license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT.” * **/ import { Component, OnInit } from "@angular/core"; import { IdprestapiService } from "../idprestapi.service"; import { IdpService } from "../idp-service.service"; import { IdpdataService } from "../idpdata.service"; import { Router } from "@angular/router"; import { Validators } from "@angular/forms"; import { FormControl, FormGroup } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { Renderer } from "@angular/core"; import { ViewChild } from "@angular/core"; import { IDPEncryption } from "../idpencryption.service"; import { IdpSubmitService } from "../idpsubmit.service"; import { ParentFormConnectComponent } from "../parent-form-connect/parent-form-connect.component"; import { BsModalService } from 'ngx-bootstrap/modal'; import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service'; import * as _ from 'lodash'; @Component({ selector: "app-deploy-info", templateUrl: "./deploy-info.component.html", styleUrls: ["./deploy-info.component.css"] }) export class DeployInfoComponent implements OnInit { env: any = {}; envtoolList: any=[]; scriptList: any = []; buildList: any= []; deploymentList: any = []; data: any = {}; testInfo: any = this.IdpdataService.data.testInfo; deployInfo: any = this.IdpService.copy(this.IdpdataService.data.deployInfo); buildInfo: any = this.IdpdataService.data.buildInfo; code: any = this.IdpdataService.data.code; list: any = []; radio: any = ""; runScriptFlag: any = "off"; envProvFlag: any = "off"; deployContainerFlag: any = "off"; deployDBFlag: any = "off"; deployDb: any = "off"; tempObject: any = this.IdpdataService.data.checkboxStatus.deployInfo; p: boolean; dbList: any; dataJson:any; geFlag: boolean; containerList: any; deployToContainer: any = {}; deployDatabase: any = {}; formStatusObject = this.IdpdataService.data.formStatus; copyEditOperation=this.IdpdataService.copyEditOperation; ssoId: any; isDockerRegistry=this.IdpdataService.isDockerRegistry; ssoName: any; serverIndex: any; srfServerIndex: any; module: String; s: any; outerIndex: any; innerIndex: any; msg: any; insightsFlag=this.IdpdataService.insightsFlag; cloudDeployFlag=this.IdpdataService.cloudDeployFlag; loc: any; passphrasefrombuild: any; Artifactvalue: any; buildTool: any; importexporttype: any; administrator: any; password: any; fileName: ""; pairName: ""; srcEnvName: ""; port: any; hostName: any; userName: any; sourceFolder: any; sourceRepo: any; targetFolder: any; targetFolderShared; artifactIndex: any; targetRepo: any; platform: any; sourceFolderShared: any; checkStepAdd = false; dbDeployRollbackTypeList: any; server: any; listToFillFields: any = []; index: any; indexI: any = -1; indexJ: any = -1; deployOperations = [ { "name": "EAR Deploy", "value": "earDeploy" }, { "name": "Start Weblogic", "value": "startWeb" }, { "name": "Stop Weblogic", "value": "stopWeb" }, { "name": "Update DBC", "value": "updateDBC" }, { "name": "XML Deploy", "value": "xmlDeploy" }, ]; deployAemOperations = [ { "name": "Upload & Install", "value": "packageUploadInstall" }, { "name": "Upload Only", "value": "packageUploadNotInstall" }, { "name": "Rebuild", "value": "packageRebuild" }, { "name": "Uninstall", "value": "packageUninstall" }, { "name": "Delete", "value": "packageDelete" }, ]; @ViewChild("modalforAlertDeploy") modalforAlertDeploy; @ViewChild("modalforDelDeployStep") modalforDelDeployStep; @ViewChild("modalforDelField") modalforDelField; @ViewChild("modalforDelAllField") modalforDelAllField; @ViewChild("modalforAlertDataMiss") modalforAlertDataMiss; @ViewChild("modalforDelAntProperties") modalforDelAntProperties; @ViewChild("modalforDotNet") modalforDotNet; @ViewChild("modalformandatoryFieldsDeployAlert") modalformandatoryFieldsDeployAlert; @ViewChild("modalforconfirmDeployAlert") modalforconfirmDeployAlert; @ViewChild('modalforMaximo') modalforMaximo; public rapidPage: any = { "pageRows": [{ "sections": [{ "sectionRows": [{ "secRowColumns": [] }, { "secRowColumns": [{ "colName": "users" }] }, { "secRowColumns": [{ "colName": "sample" }] }], "width": 0 }] }], "pageName": "DefaultPage", "pageLayout": "DEFAULT_LAYOUT", "editMode": true }; alertDeployModalRef: BsModalRef; missingDataModalRef: BsModalRef; dotnetAlertModalRef: BsModalRef; delDeployStepModalRef: BsModalRef; delFiledModalRef: BsModalRef; delAllFieldsModalRef: BsModalRef; delAntPropertyModalRef: BsModalRef; confirmSubmissionModalRef: BsModalRef; mandatoryMissingModalRef: BsModalRef; modalForMaximoRef: BsModalRef; deployStepsCollapseStatus:Array<Array<any>> = []; ngOnInit() { if (this.IdpdataService.data.formStatus.basicInfo.appNameStatus === "0") { this.TriggerAlert({msg:"Application Name",loc:"/createConfig/basicInfo"}); } else { if (this.IdpdataService.data.formStatus.buildInfo.buildToolStatus === "0") { console.log(1); this.msg = "Technology Type"; this.loc = "/createConfig/codeInfo"; // this.IdpdataService.data.p=true; this.TriggerAlert({msg:"Technology Type",loc:"/createConfig/codeInfo"}); } } if (this.buildInfo.buildtool === "maximo" && this.IdpdataService.data.basicInfo.buildServerOS !== "windows") { this.modalForMaximoRef = this.modalService.show(this.modalforMaximo); } const applName = this.IdpdataService.data.basicInfo.applicationName; } /* Constructor */ constructor( public IdpdataService: IdpdataService, private IdpService: IdpService, private IdpSubmitService: IdpSubmitService, private IdprestapiService: IdprestapiService, private idpencryption: IDPEncryption, private modalService: BsModalService, private httpClient:HttpClient, private router: Router) { this.IdpdataService.data.deployInfo = this.deployInfo; this.IdpdataService.data.buildInfo = this.buildInfo; this.init(); this.scriptList = [{ "name": "ANT Script", "value": "ant" }, { "name": "Shell Script", "value": "shellScript" }, { "name": "Batch Script", "value": "batchScript" }, { "name": "Powershell Script", "value": "powerShell" }, { "name": "SSH Execution", "value": "sshExecution" }]; this.deploymentList = [{ "name": "Mule Server", "value": "muleServer" }]; this.envtoolList=[{"name":"Ansible","value":"ansiblescript"}]; if (this.buildInfo.buildtool === "maven" || this.buildInfo.buildtool === "ant" || this.buildInfo.buildtool === "java_gradle" || this.buildInfo.buildtool === "catalog") { this.containerList = this.IdprestapiService.getIDPDropdownProperties().containerList; } if (this.buildInfo.buildtool === "general") { this.scriptList = [{ "name": "ANT Script", "value": "ant" }, { "name": "Shell Script", "value": "shellScript" }, { "name": "Batch Script", "value": "batchScript" }, { "name": "Powershell Script", "value": "powerShell" }]; } if (this.buildInfo.buildtool === "msBuild") { this.containerList = [{ "name": "IIS", "value": "iis" }]; } if (this.buildInfo.buildtool === "iib") { this.buildList = [{ "name": "IIB", "value": "iib" } ]; } if (this.buildInfo.buildtool === 'maximo') { this.containerList = [{ 'name': 'WebLogic', 'value': 'weblogic' }]; } if (this.buildInfo !== undefined && this.buildInfo !== "" && this.buildInfo != null) { if (this.buildInfo.buildtool === "reactjs") { this.server = { "osserver": "" }; this.server.osserver = this.IdpdataService.data.basicInfo.buildServerOS; } } if (this.formStatusObject.operation === "copy" || this.formStatusObject.operation === "edit") { this.buildTool = this.buildInfo.buildtool; this.checkCheckBox(); } } uploadForm = new FormGroup ({ file1: new FormControl() }); public fileUploader(event,envIndex,stepIndex) { const elem = event.target; if (elem.files.length > 0) { console.log(elem.files[0]); let reader = new FileReader(); reader.onload = () => { // this 'text' is the content of the file var text = reader.result; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].cloudData=JSON.parse(text); } reader.readAsText(elem.files[0]); } // ... } setFormStatus(data) { this.IdpdataService.allFormStatus.deployInfo = data; } get rapidPageValue() { return JSON.stringify(this.rapidPage, null, 2); } set rapidPageValue(v) { try { this.rapidPage = JSON.parse(v); } catch (e) { console.log("error occored while you were typing the JSON"); } } TriggerAlert(content) { this.alertDeployModalRef = this.modalService.show(this.modalforAlertDeploy); this.alertDeployModalRef.content = content; } redirectTo(modalRef) { modalRef.hide(); if (modalRef.content.loc) { this.router.navigate([modalRef.content.loc]); } } redirectToBasicInfo(modalRef) { modalRef.hide(); this.router.navigate(["/createConfig/basicInfo"]); } init() { this.deployInfo.deployEnv.forEach(()=>{this.deployStepsCollapseStatus.push([])}); this.dbList = [{ 'name': 'MySQL', 'value': 'MySQL' }, { 'name': 'PostgreSQL', 'value': 'PostgresSQL' }, { 'name': 'Derby', 'value': 'Derby' }, { 'name': 'Hypersonic', 'value': 'Hypersonic' }, { 'name': 'H2', 'value': 'H2' }, { 'name': 'Oracle', 'value': 'oracle' }, { 'name': 'MsSQL', 'value': 'mssql' }, ]; this.dbDeployRollbackTypeList = [{ 'name': 'byTag', 'value': 'byTag' }, { 'name': 'byChangeSet', 'value': 'byChangeSet' }, { 'name': 'byHours', 'value': 'byHours' }, { 'name': 'byDate', 'value': 'byDate' } ]; } checkStep(envIndex) { return "on"; } clearStep(envIndex) { return "off"; } /* To check if Deploy step is added or not */ checkDeployOperation(i, j) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployOperation === undefined) { this.deployInfo.deployEnv[i].deploySteps[j].deployOperation = ""; } this.deployInfo.deployEnv[i].deploySteps[j].deployFuntion = ""; } checkOracleDeployOperation(i, j) { console.log('polaplao') if (this.deployInfo.deployEnv[i].deploySteps[j].deployTech === undefined) this.deployInfo.deployEnv[i].deploySteps[j].deployTech = ""; //this.deployInfo.deployEnv[i].deploySteps[j].deployFuntion=""; } /* Checks for duplication of step name * and alerts */ checkStepName(i, j) { for (let x = 0; x < this.deployInfo.deployEnv.length; x++) { if (this.deployInfo.deployEnv[x] !== undefined && this.deployInfo.deployEnv[x].deploySteps !== undefined) { for (let y = 0; y < this.deployInfo.deployEnv[x].deploySteps.length; y++) { console.log(this.deployInfo.deployEnv[x].deploySteps[y].stepName); if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } if (j !== y && this.deployInfo.deployEnv[x].deploySteps[y].stepName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].stepName !== undefined && this.deployInfo.deployEnv[x].deploySteps[y].stepName === this.deployInfo.deployEnv[i].deploySteps[j].stepName) { this.tempObject.deployEnv[i].deploySteps[j].msgStep = "Step Name must be unique."; break; } else { this.tempObject.deployEnv[i].deploySteps[j].msgStep = ""; } } } } } printaa() { // if(this.env.runScript.scriptType===''){ // console.log( this.env); // } } /* Options for Java packaging */ optionList() { if (this.tempObject.warList === undefined) { this.tempObject.warList = []; } for (let i = 0; i < this.buildInfo.modules.length; i++) { if (this.buildInfo.modules[i].moduleName !== undefined && this.buildInfo.modules[i].moduleName != null && this.buildInfo.modules[i].moduleName !== "" && this.buildInfo.modules[i].warPackaging !== "" && this.buildInfo.modules[i].warPackaging !== null && this.buildInfo.modules[i].warPackaging !== undefined) { if (this.tempObject.warList.indexOf(this.buildInfo.modules[i].moduleName) === -1) { this.tempObject.warList.push(this.buildInfo.modules[i].moduleName); } } } return true; } clearTempObject(envIndex) { if (this.deployInfo.deployEnv[envIndex].envFlag === "off") { if (this.tempObject.deployEnv !== undefined && this.tempObject.deployEnv[envIndex] !== undefined) { this.tempObject.deployEnv[envIndex].deploySteps = []; } } } clearObjFlag(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].dbName = ""; this.deployInfo.deployEnv[i].deploySteps[j].dbServName = ""; this.tempObject.deployEnv[i].deploySteps[j].deployObjFlag = "off"; this.clearIntFlag(i, j); return "off"; } clearIntFlag(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].dbUName = ""; this.deployInfo.deployEnv[i].deploySteps[j].dbPwd = ""; this.tempObject.deployEnv[i].deploySteps[j].isInternetFlag = "off"; return "off"; } tomcatRestartoff(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].tomUname = ""; this.deployInfo.deployEnv[i].deploySteps[j].tomPwd = ""; this.deployInfo.deployEnv[i].deploySteps[j].tomHost = ""; this.deployInfo.deployEnv[i].deploySteps[j].tomPort = ""; this.deployInfo.deployEnv[i].deploySteps[j].appName = ""; return "off"; } tomcatRestarton(i, j) { this.tempObject.deployEnv[i].deploySteps[j].tomcatRestart = "on"; return "on"; } /* Addition of deploy step */ addDeployStep(key) { if (this.deployInfo.deployEnv === undefined) { this.deployInfo.deployEnv = []; console.log("chck"); } if (this.tempObject.deployEnv === undefined) { this.tempObject.deployEnv = []; } if (this.deployInfo.deployEnv[key] === undefined) { this.deployInfo.deployEnv[key] = {}; } if (this.tempObject.deployEnv[key] === undefined) { this.tempObject.deployEnv[key] = {}; } if (this.deployInfo.deployEnv[key].deploySteps === undefined) { this.deployInfo.deployEnv[key].deploySteps = []; } if (this.tempObject.deployEnv[key].deploySteps === undefined) { this.tempObject.deployEnv[key].deploySteps = []; } if (this.tempObject.deployEnv === undefined) { console.log(1); this.tempObject.deployEnv = []; } this.deployToContainer = { "containerName": "", "updateDB": "", "rollbackStrategy": "", "fileName": "", "pairName": "", "srcEnvName": "", "userName": "", "password": "", "aemPort":"", "aemProxy":"", "deployAemOperations":"", "groupName":"", "contextPath":"", "proxyun":"", "proxypw":"", "appName":"" }; this.deployDatabase = { "restorusername": "", "restorpassword": "", "dbusername": "", "dbpassword": "", "script": "" }; this.deployInfo.deployEnv[key].deploySteps.push({ "deployToContainer": this.deployToContainer, "deployDatabase": this.deployDatabase, "insightsFlag":"off", "insightsKafkaUrl":"", "insightsKafkaTopic":"", "deploymentOption": "", "runScript": { "scriptType": "", "scriptFilePath": "", "targets": "" }, "buildScript": { "buildType": "", "targets": "", "buildFilePath": "" }, "cloudDeployment": { }, "proxy": { "username": "", "password": "", "host": "", "enabled": "", "port": "" }, "deployOS": "", "abortScript": { "scriptType": "" }, "platform": "", "deployOperation": "", "envProv":{ "toolType":"", "scriptFilePath":"" } }); this.tempObject.deployEnv[key].deploySteps.push({}); } /* Removal of deploy step */ removeDeployStep(outerIndex, innerIndex) { this.delDeployStepModalRef = this.modalService.show(this.modalforDelDeployStep); this.delDeployStepModalRef.content = {innerIndex:innerIndex,outerIndex:outerIndex}; } /* Clears environment config */ clearcfg(i, j) { this.tempObject.deployEnv[i].deploySteps[j].envconfigNameCheckBox = []; this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails = []; return "off"; } clearconfig(i, j, k) { const idx = this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.indexOf(this.IdpdataService.application.environmentProvDetails[k]); if (idx > -1) { this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.splice(idx, 1); } else { this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.push(this.IdpdataService.application.environmentProvDetails[k]); } console.log(this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails); return "off"; } inscfgMain(i, j) { this.tempObject.deployEnv[i].deploySteps[j].envconfigNameCheckBox = []; this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails = []; return "on"; } insconfig(i, j, k) { const idx = this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.indexOf(this.IdpdataService.application.environmentProvDetails[k]); if (idx > -1) { this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.splice(idx, 1); } else { this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.push(this.IdpdataService.application.environmentProvDetails[k]); } console.log(this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails); return "on"; } confirmDeleteDeployStep(modelRef) { this.deployInfo.deployEnv[modelRef.content.outerIndex].deploySteps.splice(modelRef.content.innerIndex, 1); this.tempObject.deployEnv[modelRef.content.outerIndex].deploySteps.splice(modelRef.content.innerIndex, 1); modelRef.hide(); } checkCheckBox() { if (this.IdpdataService.data.buildInfo !== undefined && this.IdpdataService.data.buildInfo.modules !== undefined && this.IdpdataService.data.buildInfo.modules[0] !== undefined && this.IdpdataService.data.buildInfo.modules[0].unitTesting === "on") { this.IdpdataService.unitTest = true; } if (this.tempObject.deployEnv === undefined) { this.tempObject.deployEnv = []; } if (this.tempObject.deployEnv.deploySteps === undefined) { this.tempObject.deployEnv.push({}); this.tempObject.deployEnv.deploySteps = []; } for (let i = 0; i < this.deployInfo.deployEnv.length; i++) { const envFlag = "off"; if (this.tempObject.deployEnv[i] === undefined) { this.tempObject.deployEnv[i] = {}; } if (this.tempObject.deployEnv[i].deploySteps === undefined) { this.tempObject.deployEnv[i].deploySteps = []; } if (this.deployInfo.deployEnv[i].deploySteps !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps.length !== 0) { this.deployInfo.deployEnv[i].envFlag = "on"; } for (let j = 0; j < this.deployInfo.deployEnv[i].deploySteps.length; j++) { const runScriptFlag = "off"; const deployContainerFlag = "off"; if (this.deployInfo.deployEnv[i].deploySteps[j].s3location !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].s3location !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].s3Loc = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].s3Loc = "off"; } const deployDBFlag = "off"; if (this.deployInfo.deployEnv[i].deploySteps[j].runScript !== "" && this.deployInfo.deployEnv[i].deploySteps[j].runScript !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].runScript.scriptType !== "" && this.deployInfo.deployEnv[i].deploySteps[j].runScript.scriptType !== undefined) { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag = "on"; /* setting SSH on, if inputs are provided */ if (this.deployInfo.deployEnv[i].deploySteps[j].runScript.scriptType === "sshExecution") { if (this.deployInfo.deployEnv[i].deploySteps[j].runScript.pathToFiles !== "" && this.deployInfo.deployEnv[i].deploySteps[j].runScript.pathToFiles !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].transferFilesFlag = "on"; } } /* Setting Ant execution on, if ant targets, xml file are provided */ if (this.deployInfo.deployEnv[i].deploySteps[j].runScript.scriptType === "ant") { if (this.deployInfo.deployEnv[i].deploySteps[j].runScript && this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr && this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr[0] && this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr[0].antKey !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr[0].antValue !== undefined) { this.deployInfo.deployEnv[i].deploySteps[j].runScript.antProperty1 = "on"; } if (this.deployInfo.deployEnv[i].deploySteps[j].runScript && this.deployInfo.deployEnv[i].deploySteps[j].runScript.javaOptions !== undefined) { this.deployInfo.deployEnv[i].deploySteps[j].runScript.antJavaOption1 = "on"; } } } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag = "off"; } } else { this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag = "off"; } //env provision start if((this.buildInfo.buildtool!=="SapNonCharm" || this.buildInfo.buildtool!=='sapcharm')){ if(this.deployInfo.deployEnv[i].deploySteps[j].envProv ===undefined || this.deployInfo.deployEnv[i].deploySteps[j].envProv ==null || this.deployInfo.deployEnv[i].deploySteps[j].envProv.toolType === undefined || this.deployInfo.deployEnv[i].deploySteps[j].envProv.toolType ==="" ){ this.tempObject.deployEnv[i].deploySteps[j].envProvFlag="off"; this.deployInfo.deployEnv[i].deploySteps[j].envProv = {toolType:"",scriptFilePath:""}; }else{ this.tempObject.deployEnv[i].deploySteps[j].envProvFlag="on"; } } else{ //this.deployInfo.deployEnv[i].deploySteps[j].envProv = {toolType:"",scriptFilePath:""}; this.tempObject.deployEnv[i].deploySteps[j].envProvFlag="off"; } //envprovison end if (this.buildInfo.buildtool === "reactjs" && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hostName !== "") { this.tempObject.deployEnv[i].deploySteps[j].folderCopyFlag = "on"; } if (this.buildInfo.buildtool === 'bigData' && ((this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pigUsername !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pigUsername !== undefined) || (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hiveServerName !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hiveServerName !== undefined) || (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].scalaServerName !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].scalaServerName !== undefined))) { this.tempObject.deployEnv[i].deploySteps[j].bigDataFlag = 'on'; } if (this.buildInfo.buildtool === 'bigData' && (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pigUsername !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pigUsername !== undefined)) { this.tempObject.deployEnv[i].deploySteps[j].pig = 'on'; if (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pigScr !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pigScr !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].pigExec = 'on'; } } if (this.buildInfo.buildtool === 'bigData' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hiveServerName !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hiveServerName !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].hive = 'on'; if (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hiveScr !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].hiveScr !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].hiveExec = 'on'; } } if (this.buildInfo.buildtool === 'bigData' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].scalaServerName !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].scalaServerName !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].scala = 'on'; if (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].scalaUip !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].scalaUip !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].scalaExec = 'on'; } } // tibco deployment changes if ((this.buildInfo.buildtool === 'tibco') && this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles !== null && this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].tibcoDeploy = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].tibcoDeploy = "off"; } // ios deployment changes if ((this.buildInfo.buildtool === 'iOS(Swift)') && this.deployInfo.deployEnv[i].deploySteps[j].iosDataPath !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].iosDataPath !== null && this.deployInfo.deployEnv[i].deploySteps[j].iosDataPath !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].iosDeploy = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].iosDeploy = "off"; } // pega deployment changes if (this.buildInfo.buildtool === 'pega' && (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pegaDBDataPort !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].pegaDBDataPort !== undefined)) { this.tempObject.deployEnv[i].deploySteps[j].dataSchema = 'on'; } if (this.buildInfo.buildtool === 'pega' && (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].tomUname !== '' && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].tomUname !== undefined)) { this.tempObject.deployEnv[i].deploySteps[j].tomcatRestart = 'on'; } //siebel if ((this.buildTool === 'siebel') && this.deployInfo.deployEnv[i].deploySteps[j].deployUserName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].deployUserName !== null && this.deployInfo.deployEnv[i].deploySteps[j].deployUserName !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].automationScript = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].automationScript = "off"; } //oracle deployment steps if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].sqlFileName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].sqlFileName !== null && this.deployInfo.deployEnv[i].deploySteps[j].sqlFileName !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackages = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackages = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].sqlFolder !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].sqlFolder !== null && this.deployInfo.deployEnv[i].deploySteps[j].sqlFolder !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "otmoracle"; this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackagesOTM = "on"; //this.tempObject.deployEnv[i].deploySteps[j].deployTech="otmoracle"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackagesOTM = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].reportName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].reportName !== null && this.deployInfo.deployEnv[i].deploySteps[j].reportName !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].report = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].report = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].oafFolderName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].oafFolderName !== null && this.deployInfo.deployEnv[i].deploySteps[j].oafFolderName !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].oafObject = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].oafObject = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].formName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].formName !== null && this.deployInfo.deployEnv[i].deploySteps[j].formName !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].forms = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].forms = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].hostCtlfile !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].hostCtlfile !== null && this.deployInfo.deployEnv[i].deploySteps[j].hostCtlfile !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].hostCtl = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].hostCtl = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].oaMediaFile !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].oaMediaFile !== null && this.deployInfo.deployEnv[i].deploySteps[j].oaMediaFile !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].oaMedia = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].oaMedia = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].workFlowName !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].workFlowName !== null && this.deployInfo.deployEnv[i].deploySteps[j].workFlowName !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].workFlow = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].workFlow = "off"; } if ((this.buildInfo.buildtool === 'oracleEBS') && this.deployInfo.deployEnv[i].deploySteps[j].customTopPath !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].customTopPath !== null && this.deployInfo.deployEnv[i].deploySteps[j].customTopPath !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deployTech = "ebsoracle"; this.tempObject.deployEnv[i].deploySteps[j].aolScripts = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] == undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].aolScripts = "off"; } if (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length > 0) { this.tempObject.deployEnv[i].deploySteps[j].envconfigAbortCheckBox = "on"; this.tempObject.deployEnv[i].deploySteps[j].envconfigNameCheckBox = []; for (let s = 0; s < this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length; s++) { for (let f = 0; f < this.IdpdataService.application.environmentProvDetails.length; f++) { if (this.IdpdataService.application.environmentProvDetails[f].environmentProvName === this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails[s].environmentProvName) { this.tempObject.deployEnv[i].deploySteps[j].envconfigNameCheckBox[f] = "on"; this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails[s] = this.IdpdataService.application.environmentProvDetails[f]; break; } } } } if (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag !== undefined && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === "on") { console.log(this.IdpdataService.data.deployInfo); const deployData1 = this.IdpdataService.data.basicInfo.deployData1; console.log(this.IdpdataService.data.deployInfo.deployEnv[i]); if (deployData1 !== undefined) { const deployData = JSON.parse(deployData1); for (let l = 0; l < deployData.env.length; l++) { if (deployData.env[l].name === this.IdpdataService.data.deployInfo.deployEnv[i].envName) { for (let k = 0; k < deployData.env[l].step.length; k++) { if (deployData.env[l].step[k].index - 1 === j) { this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].dataRight = JSON.parse(this.idpencryption.decryptAES(deployData.env[l].step[k].pipelineInfo)); console.log(this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].dataRight + " " + this.idpencryption.decryptAES(deployData.env[l].step[k].pipelineInfo)); } } } } } } /* MSBUILD Deployment */ if (this.buildInfo.buildtool === "msBuild" && (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].appPackName !== "" && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].appPackName !== undefined)) { this.tempObject.deployEnv[i].deploySteps[j].deployFabFlag = "on"; } if (this.buildInfo.buildtool === "msBuild" && (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].dbServName !== "" && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].dbServName !== undefined)) { this.tempObject.deployEnv[i].deploySteps[j].deployObjFlag = "on"; } if (this.buildInfo.buildtool === "msBuild" && (this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].dbUName !== "" && this.IdpdataService.data.deployInfo.deployEnv[i].deploySteps[j].dbUName !== undefined)) { this.tempObject.deployEnv[i].deploySteps[j].isInternetFlag = "on"; } if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.containerName !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.containerName !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "on"; } else { this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "off"; } } else { this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "off"; } if ((this.buildTool === "ant" || this.buildTool === "maven") && this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles !== null && this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].scriptType = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].scriptType = "off"; } if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } if (this.deployInfo.deployEnv[i].deploySteps[j].dockerFilePath !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].dockerFilePath !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].dockerContainerFlag = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].dockerContainerFlag = "off"; } if (this.deployInfo.deployEnv[i].deploySteps[j].dockerComposePath !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].dockerComposePath !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag = "off"; } if (this.deployInfo.deployEnv[i].deploySteps[j].bizScriptPath !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].bizScriptPath !== "") { this.tempObject.deployEnv[i].deploySteps[j].deployBizFlag = "on"; } if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.updateDB !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.updateDB !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.rollbackStrategy !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.rollbackStrategy !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].rollbackOnFailFlag = "on"; } else { this.tempObject.deployEnv[i].deploySteps[j].rollbackOnFailFlag = "off"; } this.tempObject.deployEnv[i].deploySteps[j].dbDeployFlag = "on"; } else { this.tempObject.deployEnv[i].deploySteps[j].dbDeployFlag = "off"; } } else { this.tempObject.deployEnv[i].deploySteps[j].dbDeployFlag = "off"; } // dbDeployDBOwners if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployPipelineList !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployPipelineList !== "" && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployDBOwners !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployDBOwners !== "") { this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag = "on"; if (this.tempObject.deployEnv[i].deploySteps[j].dependentDBDeployPipelineList === undefined) { this.tempObject.deployEnv[i].deploySteps[j].dependentDBDeployPipelineList = []; } if (this.tempObject.deployEnv[i].deploySteps[j].dependentDBDeployPipelineList.length === 0) { for (const name of this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployPipelineList) { let itemIndex; itemIndex = this.IdpdataService.data.DBDeploypipelineList.map(function (e) { return e.itemName; }).indexOf(name); if (itemIndex !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].dependentDBDeployPipelineList. push(this.IdpdataService.data.DBDeploypipelineList[itemIndex]); } } } } else { this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag = "off"; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployPipelineList = []; } } else { this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag = "off"; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.dbDeployPipelineList = []; } if (this.deployInfo.deployEnv[i].deploySteps[j].deploymentOption !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].deploymentOption !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].muleESBDeployFlag = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.deployInfo.deployEnv[i].deploySteps[j].deploymentOption = ""; this.tempObject.deployEnv[i].deploySteps[j].muleESBDeployFlag = "off"; } if (this.deployInfo.deployEnv[i].deploySteps[j].timeout !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].timeout !== null && this.deployInfo.deployEnv[i].deploySteps[j].timeout !== "") { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].approvalCheckBox = "on"; } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { console.log(this.tempObject.deployEnv[i].deploySteps[j]); this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].approvalCheckBox = "off"; } if (this.buildInfo.buildtool !== 'gradle' && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== '' && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.containerName !== '' && this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.containerName !== undefined) { this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "on"; } else { //console.log("bcause here as well"); this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "off"; } } else { //console.log("bcause here as well"); this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "off"; } // general Deploy Steps if (this.deployInfo.deployEnv[i].deploySteps[j].abortScript !== "" && this.deployInfo.deployEnv[i].deploySteps[j].abortScript !== undefined) { if (this.deployInfo.deployEnv[i].deploySteps[j].abortScript.scriptType !== "" && this.deployInfo.deployEnv[i].deploySteps[j].abortScript.scriptType !== undefined) { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].runScriptAbortCheckBox = "on"; if (this.deployInfo.deployEnv[i].deploySteps[j].abortScript.scriptType === "ant") { if (this.deployInfo.deployEnv[i].deploySteps[j].abortScript && this.deployInfo.deployEnv[i].deploySteps[j].abortScript.antPropertiesArr && this.deployInfo.deployEnv[i].deploySteps[j].abortScript.antPropertiesArr[0].antKey !== undefined && this.deployInfo.deployEnv[i].deploySteps[j].abortScript.antPropertiesArr[0].antValue !== undefined) { this.deployInfo.deployEnv[i].deploySteps[j].abortScript.antProperty1 = "on"; } if (this.deployInfo.deployEnv[i].deploySteps[j].abortScript && this.deployInfo.deployEnv[i].deploySteps[j].abortScript.javaOptions !== undefined) { this.deployInfo.deployEnv[i].deploySteps[j].abortScript.antJavaOption1 = "on"; } } } else { if (this.tempObject.deployEnv[i].deploySteps[j] === undefined) { this.tempObject.deployEnv[i].deploySteps[j] = {}; } this.tempObject.deployEnv[i].deploySteps[j].runScriptAbortCheckBox = "off"; } } else { this.tempObject.deployEnv[i].deploySteps[j].runScriptAbortCheckBox = "off"; } this.IdpdataService.data.checkboxStatus.deployInfo = this.tempObject; } } else { continue; } } } addCloudDeployment(outerIndex,innerIndex){ if (this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].cloudDeployment === undefined) this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].cloudDeployment = ''; //this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].dataright=this.dataEditorLeft; return 'on'; } clearCloudDeployment(outerIndex,innerIndex){ return 'off'; } /* Resets data */ resetData() { const x = confirm("Are you sure to Reset ?"); if (x) { const val = this.deployInfo.deployEnv; this.deployInfo = { "deployEnv": [] }; for (let i = 0; i < val.length; i++) { this.deployInfo.deployEnv.push({ "envName": val[i].envName, "envFlag": "off", }); } this.IdpdataService.data.deployInfo = this.deployInfo; this.IdpdataService.data.checkboxStatus.deployInfo = {}; } } /* validation of deploy Steps * for each tech stack */ validatePage() { let f = true; for (let i = 0; i < this.deployInfo.deployEnv.length; i++) { if(this.deployInfo.deployEnv[i].envFlag === "on" && this.deployInfo.deployEnv[i].deploySteps === undefined){ f=false; break; } else if (this.deployInfo.deployEnv[i].envFlag === "on" && this.deployInfo.deployEnv[i].deploySteps !== undefined && this.deployInfo.deployEnv[i].deploySteps.length !== 0) { for (let j = 0; j < this.deployInfo.deployEnv[i].deploySteps.length; j++) { switch (this.buildInfo.buildtool) { /* Validation of Ant Deploy Steps */ case "ant": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].scriptType === undefined || this.tempObject.deployEnv[i].deploySteps[j].scriptType === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === "off") && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length <= 0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* Validation of Maven Deploy Steps */ case "maven": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].scriptType === undefined || this.tempObject.deployEnv[i].deploySteps[j].scriptType === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dockerContainerFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dockerContainerFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === "off") && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length <= 0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of Angular Deploy Steps */ case "angular": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag === "off") && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length <= 0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* Validation of .Net Deploy step */ case "msBuild": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dockerRegistryFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].deployBizFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployBizFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].deployFabFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployFabFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].deployObjFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployObjFlag === "off") && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length <= 0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* Validation of NodeJS Deploy Step */ case "nodeJs": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === "off") && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length <= 0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of Python Deploy step */ case "python": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].s3Loc === undefined || this.tempObject.deployEnv[i].deploySteps[j].s3Loc === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === "off") && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length <= 0) && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of Go Deploy step */ case "go": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of MainFrame Deploy step */ case "mainframe": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of MsSql Deploy step */ case 'mssql': { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of FileNet Deploy step */ case "fileNet": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of PHP Deploy step */ case "php": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of Siebel Deploy step */ case 'siebel': { if ((this.deployInfo.deployEnv[i].deploySteps[j].deployOS === undefined || this.deployInfo.deployEnv[i].deploySteps[j].deployOS != 'windows') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of IIB Deploy step */ case "iib": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off")) { f = false; break; } break; } /* validation of Pega Deploy step */ case "pega": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].dataSchema === undefined || this.tempObject.deployEnv[i].deploySteps[j].dataSchema === "off") && (this.tempObject.deployEnv[i].deploySteps[j].tomcatRestart === undefined || this.tempObject.deployEnv[i].deploySteps[j].tomcatRestart === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of Oracle Deploy step */ case 'oracleEBS': { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackages === undefined || this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackages === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackagesOTM === undefined || this.tempObject.deployEnv[i].deploySteps[j].sqlFilesPackagesOTM === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].forms === undefined || this.tempObject.deployEnv[i].deploySteps[j].forms === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].report === undefined || this.tempObject.deployEnv[i].deploySteps[j].report === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].oafObject === undefined || this.tempObject.deployEnv[i].deploySteps[j].oafObject === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].hostCtl === undefined || this.tempObject.deployEnv[i].deploySteps[j].hostCtl === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].oaMedia === undefined || this.tempObject.deployEnv[i].deploySteps[j].oaMedia === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].workFlow === undefined || this.tempObject.deployEnv[i].deploySteps[j].workFlow === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].aolScripts === undefined || this.tempObject.deployEnv[i].deploySteps[j].aolScripts === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === 'off') && (this.buildInfo.buildtool !== 'ibmsi' && this.buildInfo.buildtool !== 'informatica' && this.buildInfo.buildtool !== 'general') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of MuleESB Deploy step */ case 'muleESB': { if ((this.tempObject.deployEnv[i].deploySteps[j].muleESBDeployFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].muleESBDeployFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of iOS Deploy step */ // case "iOS(Objective C)": { // if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || // this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off")) { // f = false; // break; // } // break; // } /* validation of Android Deploy step */ case "Android(Ant based)": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of iOS Deploy step */ case "iOS(Swift)": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].iosDeploy === undefined || this.tempObject.deployEnv[i].deploySteps[j].iosDeploy === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of Maximo Deploy step */ case "maximo": { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === "off") && this.tempObject.deployEnv[i].deployOperation==='earDeploy' && (this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag === "off") && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } /* validation of BigData Deploy step */ case 'bigData': { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].bigDataFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].bigDataFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].pig === undefined || this.tempObject.deployEnv[i].deploySteps[j].pig === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].scala === undefined || this.tempObject.deployEnv[i].deploySteps[j].scala === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.tempObject.deployEnv[i].deploySteps[j].hive === undefined || this.tempObject.deployEnv[i].deploySteps[j].hive === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } //if((this.tempObject.deployEnv[i].deploySteps[j].bigDataFlag!=undefined && this.tempObject.deployEnv[i].deploySteps[j].bigDataFlag!='off' ) // && (this.tempObject.deployEnv[i].deploySteps[j].pig!=undefined && this.tempObject.deployEnv[i].deploySteps[j].pig!='off') && (this.tempObject.deployEnv[i].deploySteps[j].pigExec!=undefined && this.tempObject.deployEnv[i].deploySteps[j].pigExec!='off') && ( this.deployInfo.deployEnv[i].deploySteps[j].pigLocalMac===undefined || this.deployInfo.deployEnv[i].deploySteps[j].pigLocalMac==='off') && (this.deployInfo.deployEnv[i].deploySteps[j].pigMapRed===undefined || this.deployInfo.deployEnv[i].deploySteps[j].pigMapRed==='off')){ // f=false; // console.log("Inside if condition of pig"); //break; //} //console.log("outside if condition of pig"); break; } /* validation of Tibco Deploy step */ case 'tibco': { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].tibcoDeploy === undefined || this.tempObject.deployEnv[i].deploySteps[j].tibcoDeploy === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } case 'dbDeploy': { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === 'off') && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployFlag === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } case 'gradle': { if ((this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].runScriptFlag === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer !== undefined && (this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.containerName === undefined || this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.containerName === '')) && (this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === undefined || this.tempObject.deployEnv[i].deploySteps[j].dbDeployPipelineFlag === 'off') && (this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails === undefined || this.deployInfo.deployEnv[i].deploySteps[j].environmentProvDetails.length<=0) && (this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag === undefined || this.deployInfo.deployEnv[i].deploySteps[j].cloudDeploymentFlag==='off') && (this.tempObject.deployEnv[i].deploySteps[j].envProvFlag==="off"|| this.tempObject.deployEnv[i].deploySteps[j].envProvFlag===undefined) ) { f = false; break; } break; } default: { } } } } else { console.log(i); continue; } } if (f === true) { console.log(f); return true; } else { console.log(f); return false; } } /* Submitting Deploy job * With the details provided */ go() { if (this.validatePage()) { this.IdpdataService.data.deployInfo = this.deployInfo; this.IdpdataService.data.masterJson["deployInfo"] = this.deployInfo; console.log(this.IdpdataService.data); if (this.IdpdataService.testSubscription === true) { this.router.navigate(["/createConfig/testInfo"]); } else { if (this.IdpdataService.allFormStatus.basicInfo && this.IdpdataService.allFormStatus.codeInfo && this.IdpdataService.allFormStatus.buildInfo && this.IdpdataService.allFormStatus.deployInfo) { this.confirmSubmissionModalRef = this.modalService.show(this.modalforconfirmDeployAlert); } else { let listToFillFields = []; if (!this.IdpdataService.allFormStatus.basicInfo && this.listToFillFields.indexOf("BasicInfo") === -1) { listToFillFields.push("BasicInfo"); } if (!this.IdpdataService.allFormStatus.codeInfo && this.listToFillFields.indexOf("CodeInfo") === -1) { listToFillFields.push("CodeInfo"); } if (!this.IdpdataService.allFormStatus.buildInfo && this.listToFillFields.indexOf("BuildInfo") === -1) { listToFillFields.push("BuildInfo"); } if (!this.IdpdataService.allFormStatus.deployInfo && this.listToFillFields.indexOf("DeployInfo") === -1) { listToFillFields.push("DeployInfo"); } this.mandatoryMissingModalRef = this.modalService.show(this.modalformandatoryFieldsDeployAlert); this.mandatoryMissingModalRef.content = {listToFillFields:listToFillFields}; } } return true; } else { this.missingDataModalRef = this.modalService.show(this.modalforAlertDataMiss); } } clearDeploySteps(envIndex) { this.deployInfo.deployEnv[envIndex].deploySteps = []; console.log(this.tempObject); if (this.tempObject !== undefined && this.tempObject.deployEnv !== undefined && this.tempObject.deployEnv[envIndex] !== undefined) { this.tempObject.deployEnv[envIndex].deploySteps = []; } return false; } clearScriptType(envIndex) { this.deployInfo.deployEnv[envIndex].scriptType = ""; return false; } clearFabFlag(i,j){ this.deployInfo.deployEnv[i].deploySteps[j].appPackName = ''; this.deployInfo.deployEnv[i].deploySteps[j].pubProfName = ''; return "off"; } changeRunScript(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.scriptFilePath = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.targets = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.host = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.script = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.pathToFiles = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.destinationDir = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.flattenFilePath = "off"; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].transferFilesFlag = "off"; } clearApproval(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].timeout = ""; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].runScriptAbortCheckBox = this.clearRunScriptOnAbort(outerIndex, innerIndex); return "off"; } clearRunScriptOnAbort(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.scriptType = ""; this.changeAbortRunScript(outerIndex, innerIndex); return "off"; } /*addition of EnvironmentProvisioning */ addEnvironmentProvisioning(outerIndex,innerIndex){ if (this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].envProv === undefined) { this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].envProv = ""; } return "on"; } /*clear Environment Provisioning*/ clearEnvironmentProvisioning(outerIndex,innerIndex){ this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].envProv = {toolType:"",scriptFilePath:""}; // this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].envProv.toolType=""; // this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].envProv.scriptFilePath=""; } /*onchange of environment toolfor env provisioning*/ changeenvProv(outerIndex,innerIndex){ this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].envProv.scriptFilePath=""; } changeDeploymentOption(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].muleConsoleURL = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].muleServerGroup = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].hostName = ""; } changeAbortRunScript(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.scriptFilePath = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.targets = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.host = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.script = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.pathToFiles = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].abortScript.destinationDir = ""; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].transferFilesFlag = "off"; } /* addition of Run script */ addRunScript(outerIndex, innerIndex) { if (this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].runScript === undefined) { this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].runScript = ""; } return "on"; } // Addition of IIB Build addBuildScript(outerIndex, innerIndex) { if (this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].buildScript === undefined) { this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].buildScript = ""; } return "on"; } /* Clearing the values of runscript */ clearRunScript(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.scriptType = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.scriptFilePath = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.targets = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.host = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.script = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.pathToFiles = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.destinationDir = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.sshKey = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.sshPathToKey = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.flattenFilePath = "off"; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].transferFilesFlag = "off"; //this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployOperation = "" //this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].deployContainerFlag = "off"; return "off"; } /* Clearing the values of IIB build */ clearBuildScript(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.buildType = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.buildFilePath = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.targets = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.host = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.script = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.pathToFiles = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.destinationDir = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.sshKey = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.sshPathToKey = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].buildScript.flattenFilePath = "off"; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].transferFilesFlag = "off"; return "off"; } cleartransferFilesFlag(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.pathToFiles = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.destinationDir = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].runScript.flattenFilePath = "off"; return "off"; } /* Deletion of Deploy step */ removeDeploySteps(envIndex) { this.deployInfo.deployEnv[envIndex].deploySteps = []; this.tempObject.deployEnv[envIndex].deploySteps = []; return false; } /* Clearing the container values */ clearContainerValues(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.containerName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.serverManagerURL = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.warPath = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.resourceToBeDeployed = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.narOS = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.hostName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.resourceToBeDeployed = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.port = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetCellName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetServerName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.ipOrDns = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetServerName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetNodeName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.deployedFolder = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.contextPath = ""; return "off"; } changeContainerValues(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.serverManagerURL = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.warPath = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.resourceToBeDeployed = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.narOS = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.hostName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.resourceToBeDeployed = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.port = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetCellName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetServerName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.ipOrDns = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetServerName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.targetNodeName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.contextPath = ""; if (this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.containerName === "nifi") { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.deployedFolder = "lib"; } else { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.deployedFolder = ""; } } changeDBDeployRollbackValues(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.tagName = ""; } clearDatabaseDeployment(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.updateDB = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.serverManagerURL = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.userName = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.password = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.tagDB = 'off'; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.rollbackStrategy = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].deployToContainer.tagName = ""; } openDatabaseDeployment(outerIndex, innerIndex) { this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].rollbackOnFailFlag = 'on'; return 'on' } clearSpringBoot(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pathToFiles = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].port = ""; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].parameters = ""; return "off"; } clearSiebelScriptlValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].deployUserName = ''; this.deployInfo.deployEnv[i].deploySteps[j].deployPassword = ''; this.deployInfo.deployEnv[i].deploySteps[j].adminUserName = ''; this.deployInfo.deployEnv[i].deploySteps[j].adminPassword = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbOwner = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbOwnerPassword = ''; return 'off'; } setServerIndex(stepIndex) { this.serverIndex = stepIndex; return false; } checkVal(envIndex, stepIndex) { } dockerContainerOff(envIndex, stepIndex) { this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].dockerFilePath = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].tagName = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].dockerPort = 80; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].applicationPort = 80; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].userName = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].password = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].repoUrl = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].pullFromRepo = "off"; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].pushToRepo = "off"; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].artifact = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].artifactsToBeDeployed = []; return false; } dockerRegistryOff(envIndex, stepIndex) { this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].repoNameDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].tagNameDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].userNameDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].passwordDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].dockerRegistryUrlDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].dockerFilePathDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].dockerPortDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].applicationPortDR = ""; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].dockerComposePath = ""; return false; } muleESBDeployOff(envIndex, stepIndex) { // this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].muleConsoleURL = ''; // this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].userName = ''; // this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].password = ''; // this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].muleServerGroup = ''; this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].deploymentOption = ''; return false; } addArtifactField(key1, key2) { if (this.tempObject.deployEnv[key1].deploySteps[key2].dockerContainerFlag === "on") { console.log("here"); this.deployInfo.deployEnv[key1].deploySteps[key2].artifactsToBeDeployed = []; this.deployInfo.deployEnv[key1].deploySteps[key2].artifactsToBeDeployed.push(""); } } clearS3Values(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].s3location = ""; return "off"; } clearDeployOnEmulator(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.fileName = ''; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.avdName = ''; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.launcherActivity = ''; return ''; } clearDeployOnHockeyApp(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.token = ''; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.fileName = ''; return ''; } cleariosDeployValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].iosDataPath = ''; } clearOracleOTMSqlValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].sqlFolder = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbuserNameOTM = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbpasswordOTM = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbhostNameOTM = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbPort = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbSid = ''; return 'off'; } clearOracleSqlValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].sqlFileName = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbuserName = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbpassword = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbhostName = ''; return 'off'; } clearOracleReportValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].reportName = ''; this.deployInfo.deployEnv[i].deploySteps[j].reportPath = ''; return 'off'; } clearOracleFormsValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].formName = ''; this.deployInfo.deployEnv[i].deploySteps[j].formFTPPath = ''; this.deployInfo.deployEnv[i].deploySteps[j].formsBasePath = ''; this.deployInfo.deployEnv[i].deploySteps[j].formsEnvFile = ''; this.deployInfo.deployEnv[i].deploySteps[j].formsDbPass = ''; return 'off'; } clearOracleCtlValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].hostCtlfile = ''; this.deployInfo.deployEnv[i].deploySteps[j].reportPathCtl = ''; return 'off'; } clearOracleOaValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].oaMediaFile = ''; this.deployInfo.deployEnv[i].deploySteps[j].reportPathOa = ''; return 'off'; } clearOracleoafObjectValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].oafFolderName = ''; this.deployInfo.deployEnv[i].deploySteps[j].dbPassword = ''; return 'off'; } clearOracleWfValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].workFlowName = ''; this.deployInfo.deployEnv[i].deploySteps[j].workFlowFTPPath = ''; this.deployInfo.deployEnv[i].deploySteps[j].workFlowBasePath = ''; this.deployInfo.deployEnv[i].deploySteps[j].workFlowEnvFile = ''; this.deployInfo.deployEnv[i].deploySteps[j].workFlowDbPass = ''; return 'off'; } clearOracleAolValues(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].customTopPath = ''; this.deployInfo.deployEnv[i].deploySteps[j].aolBasePath = ''; this.deployInfo.deployEnv[i].deploySteps[j].aolEnvFile = ''; this.deployInfo.deployEnv[i].deploySteps[j].loadInFile = ''; this.deployInfo.deployEnv[i].deploySteps[j].upDownFile = ''; this.deployInfo.deployEnv[i].deploySteps[j].appsPass = ''; return 'off'; } checkDis(envIndex) { let f = false; for (let j = 0; j < this.tempObject.deployEnv[envIndex].deploySteps.length; j++) { if (this.tempObject.deployEnv[envIndex].deploySteps[j].tibcoDeploy === "on") { f = true; break; } } return f; } addField(key1, key2) { if (this.deployInfo.deployEnv[key1].deploySteps[key2].artifactsToBeDeployed === undefined || this.deployInfo.deployEnv[key1].deploySteps[key2].artifactsToBeDeployed == null) { this.deployInfo.deployEnv[key1].deploySteps[key2].artifactsToBeDeployed = []; } this.deployInfo.deployEnv[key1].deploySteps[key2].artifactsToBeDeployed.push(""); } removeField(key1, key2, index) { this.innerIndex = key2; this.outerIndex = key1; this.artifactIndex = index; this.delFiledModalRef = this.modalService.show(this.modalforDelField); this.delFiledModalRef.content = {innerIndex:key1,outerIndex:key1,artifactIndex:index} } confirmRemoveField(modelRef) { this.deployInfo.deployEnv[modelRef.content.outerIndex].deploySteps[modelRef.content.innerIndex].artifactsToBeDeployed.splice(modelRef.content.artifactIndex, 1); modelRef.hide(); } removeAllFields(key1, key2, index) { this.delAllFieldsModalRef = this.modalService.show(this.modalforDelAllField); this.delAllFieldsModalRef.content = {innerIndex:key2,outerIndex:key1,artifactIndex:index}; } confirmRemoveAllFields(modalRef) { this.deployInfo.deployEnv[modalRef.content.outerIndex].deploySteps[modalRef.content.innerIndex].artifactsToBeDeployed = []; } trackById(index, field) { return field.id; } clearbigDataFlag(outerIndex, innerIndex) { this.scalaOff(outerIndex, innerIndex); this.pigOff(outerIndex, innerIndex); this.hiveOff(outerIndex, innerIndex); } scalaOff(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaServerName = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaUsername = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaPassword = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaDir = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaUip = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaJfn = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaMmn = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaCfn = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].scalaOf = ''; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].scalaExec = 'off'; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].scala = 'off'; return 'off'; } pigOff(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigServerName = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigUsername = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigPassword = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigDir = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigScr = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigLocalMac = 'off'; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigMapRed = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].pigdf = ''; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].pig = 'off'; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].pigExec = 'off'; return 'off'; } hiveOff(outerIndex, innerIndex) { this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].hiveServerName = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].hiveUsername = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].hivePassword = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].hiveDir = ''; this.deployInfo.deployEnv[outerIndex].deploySteps[innerIndex].hiveScr = ''; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].hive = 'off'; this.tempObject.deployEnv[outerIndex].deploySteps[innerIndex].hiveExec = 'off'; return 'off'; } cleartibcoDeploy(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].path = ''; this.deployInfo.deployEnv[i].deploySteps[j].pathToFiles = ''; return "off"; } // reset fields for pega dataSchemaoff(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].pegaDBdataUname = ''; this.deployInfo.deployEnv[i].deploySteps[j].pegaDBName = ''; this.deployInfo.deployEnv[i].deploySteps[j].pegaDBHost = ''; this.deployInfo.deployEnv[i].deploySteps[j].pegaDBDataPort = ''; this.deployInfo.deployEnv[i].deploySteps[j].pegaSqlFile = ''; return "off"; } dataSchemaon(i, j) { this.tempObject.deployEnv[i].deploySteps[j].dataSchema = 'on'; return 'on'; } /* clearing Weblogic Details */ clearWeblogic(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.hostName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.port = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.userName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.password = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.contextPath = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.resourceToBeDeployed = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.targetServerName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.targetServerName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.targetServerName = ""; this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "off"; this.tempObject.deployEnv[i].deploySteps[j].maximoDisable = false; } enableWebLogic(i, j) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployOperation === "earDeploy") { if (this.tempObject.deployEnv === undefined) { this.tempObject.deployEnv = [{}]; } if (this.tempObject.deployEnv[i] === undefined) { this.tempObject.deployEnv[i] = { "deploySteps": [{}] }; } this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "on"; this.tempObject.deployEnv[i].deploySteps[j].maximoDisable = true; } } /* clearing AEM Details */ clearDeployAem(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.hostName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.aemPort = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.userName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.password = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.contextPath = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.packageName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.groupName = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.aemProxy = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.proxyun = ""; this.deployInfo.deployEnv[i].deploySteps[j].deployToContainer.proxypw = ""; } enableDeployAem(i, j) { if (this.deployInfo.deployEnv[i].deploySteps[j].deployOperation === "deployAemOperations") { if (this.tempObject.deployEnv === undefined) { this.tempObject.deployEnv = [{}]; } if (this.tempObject.deployEnv[i] === undefined) { this.tempObject.deployEnv[i] = { "deploySteps": [{}] }; }else{ this.tempObject.deployEnv[i][j] = { "deploySteps": [this.env.deployToContainer.deployAemOperations] }; } this.tempObject.deployEnv[i].deploySteps[j].deployContainerFlag = "on"; this.tempObject.deployEnv[i].deploySteps[j].maximoDisable = true; } } /* Ant java Options */ openAntPropertiesField(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr = []; this.addAntProperties(i, j); console.log("inside 1"); return "on"; } /* Addfing Ant properties for each deploy step */ addAntProperties(i, j) { console.log("qwerty"); this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr.push({ }); console.log(this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr); } clearAntPropertisField(i, j) { this.deployInfo.deployEnv[i].deploySteps[j].runScript.antPropertiesArr = []; console.log("inside 1"); return false; } /* Removal of Ant module */ deleteAntProp(index, i, j) { this.delAntPropertyModalRef = this.modalService.show(this.modalforDelAntProperties); this.delAntPropertyModalRef.content = {indexI:i,indexJ:j,index:index}; } deleteAntPropConfirm(modalRef) { this.deployInfo.deployEnv[modalRef.content.indexI].deploySteps[modalRef.content.indexJ].runScript.antPropertiesArr.splice(modalRef.content.index, 1); modalRef.hide(); } resetProxyFields(envIndex, stepIndex) { this.deployInfo.deployEnv[envIndex].deploySteps[stepIndex].proxy = { "username": "", "password": "", "host": "", "port": "" }; return "false"; } submitData(modalRef) { this.IdpSubmitService.submitData(); modalRef.hide(); } checkMsgSuccess() { if (this.IdpSubmitService.message === "success") { return true; } else { return false; } } checkMsgError() { if (this.IdpSubmitService.message === "error") { return true; } else { return false; } } freezeNavBarsCheck() { if (this.IdpdataService.freezeNavBars === true) { return true; } else { return false; } } deploySubscriptionNotSubmitCheck() { if (this.IdpdataService.deploySubscriptionSubmit !== true) { return true; } else { return false; } } deploySubscriptionSubmitCheck() { if (this.IdpdataService.deploySubscriptionSubmit === true) { return true; } else { return false; } } checkLoaderOn() { if (this.IdpSubmitService.loader === "on") { return true; } else { return false; } } checkLoaderOff() { if (this.IdpSubmitService.loader === "off") { return true; } else { return false; } } }
the_stack
import { action } from 'mobx'; import { observer } from 'mobx-react-lite'; import { useEffect, useState } from 'react'; import { Alert, Badge, Box, Button, Checkbox, FormField, Header, Input, Modal, Select, SpaceBetween, StatusIndicator, Table, } from '@awsui/components-react'; import { useI18n } from '@/components/i18n-context'; import { useCheckboxInput, useInput } from '@/utils/hooks'; import { valueAsArray } from '@/utils'; import { AcceleratorConfigurationNode } from '../configuration'; import { isDisabled, setDisabled } from '../util'; import { LabelWithDescription } from './label-with-description'; import { OptionDefinition } from '../../../../node_modules/@awsui/components-react/internal/components/option/interfaces'; interface SimpleAccountValue { key: string; description?: string; ou: string; name: string; email: string; budgetAmount: number; budgetEmail: string; useOuSettings: boolean; srcFile: string; } export interface AccountTableProps { state: any; accountType: 'workload' | 'mandatory'; } const mandatoryAccountConfigsNode = AcceleratorConfigurationNode.nested('mandatory-account-configs'); const workloadAccountConfigsNode = AcceleratorConfigurationNode.nested('workload-account-configs'); // TODO Get translations directly from a type instead of getting a dummy node const dummyAccountNode = mandatoryAccountConfigsNode.nested('dummy'); export const AccountTable = observer(({ state, accountType }: AccountTableProps) => { const { tr, currency } = useI18n(); const [modalVisible, setModalVisible] = useState(false); const [modalType, setModalType] = useState<'add' | 'edit'>('add'); const [modalInitialValue, setModalInitialValue] = useState<Partial<SimpleAccountValue>>({}); const [selectedItem, setSelectedItem] = useState<SimpleAccountValue | undefined>(undefined); const [cannotAddAccount, setCannotAddAccount] = useState(false); const [permAlertVisible, setPermAlertVisible] = useState(false); const [dependencyAlertVisible, setDependencyAlertVisible] = useState(false); const [editNameAlert, setEditNameAlert] = useState(false); const [addNameAlert, setAddNameAlert] = useState(false); // TODO Get translations directly from a type instead of getting a dummy node const { title: nameTitle } = tr(dummyAccountNode.nested('account-name')); const { title: emailTitle } = tr(dummyAccountNode.nested('email')); const { title: ouTitle } = tr(dummyAccountNode.nested('ou')); const useOuSettingTitle = tr('wizard.labels.account_budget_use_ou'); const budgetAmountTitle = tr('wizard.labels.account_budget_amount'); const budgetEmailTitle = tr('wizard.labels.account_budget_email'); const node = accountType === 'mandatory' ? mandatoryAccountConfigsNode : workloadAccountConfigsNode; const accounts = node.get(state) ?? {}; // Map OUs to items that are easy to render const items: SimpleAccountValue[] = Object.entries(accounts).map(([key, accountConfig]: [string, any]) => { const budget = accountConfig?.budget; return { key, description: accountConfig?.description ?? '', ou: accountConfig?.ou ?? '', name: accountConfig?.['account-name'] ?? '', email: accountConfig?.email ?? '', budgetAmount: budget?.amount ?? 1000, budgetEmail: budget?.alerts?.[0]?.emails?.[0] ?? 'you@example.com', useOuSettings: budget === undefined || isDisabled(state, [...node.path, key]), srcFile: accountConfig?.['src-file'] ?? '', }; }); const handleAdd = () => { setModalType('add'); setModalInitialValue({}); setModalVisible(true); }; const handleEdit = () => { setModalType('edit'); setModalInitialValue(selectedItem ?? {}); setModalVisible(true); }; const handleSubmitAdd = action((value: SimpleAccountValue) => { const { key, ou, name, budgetAmount: amount, budgetEmail: email, useOuSettings, srcFile } = value; console.log(key, ou, name, amount, email, useOuSettings, srcFile) if (keyExists(key) || nameExists(name)) { setAddNameAlert(true); return } else if (validateForm(key, ou, name, amount, email, srcFile)) { accounts[String(key)] = { 'account-name': name, ou, email, "src-filename": srcFile, budget: createInitialBudget(amount, email) } return } else { setCannotAddAccount(true); } // Disable the budget if the "use OU settings" field is checked setDisabled(state, [...node.path, key], useOuSettings ?? false); }); const handleSubmitEdit = action((value: SimpleAccountValue) => { const { key, ou, name, budgetAmount: amount, budgetEmail: email, useOuSettings } = value; accounts[key]['ou'] = ou; if (value.name != name && nameExists(name)) { setEditNameAlert(true); } else { accounts[key]['account-name'] = name; } let budget = accounts[key]['budget']; if (budget) { budget.amount = amount; // Update alert email addresses valueAsArray(budget.alerts).forEach(alert => (alert.emails = [email])); } else { accounts[key]['budget'] = createInitialBudget(amount, email); } // Disable the budget if the "use OU settings" field is checked setDisabled(state, [...node.path, key], useOuSettings ?? false); }); const validateForm = (key: string, ou: string, name: string, amount: number, email: string, srcFile: string ) => { if (key == '' || key == null|| ou == '' || name == '' || name == null || Number.isNaN(amount) || email == '' || srcFile == '') { return false } else { return true } } const keyExists = (addKey: string | undefined) => { for (let each in items) { if (items[each]['key'] == addKey) { return true; } } return false; } const nameExists = (editKey: string | undefined) => { for (let each in items) { if (items[each]['name'] == editKey) { return true; } } return false; } const handleSubmit = action((value: SimpleAccountValue) => { if (modalType === 'add') { handleSubmitAdd(value); } else { handleSubmitEdit(value); } setModalVisible(false); }); const checkDependency = (accountName: string, node: any) => { var dependencyExists = false; Object.entries(node).forEach(([key, value]) => { if (typeof(value) != 'object') { if (Array.isArray(value)) { for (const each of value) { if (typeof(each == 'object')) dependencyExists = dependencyExists || checkDependency(accountName, each) } } else { if ((key == 'target-account' && node[key] == accountName)) { dependencyExists = true; return true } return dependencyExists } } dependencyExists = dependencyExists || checkDependency(accountName, value) }) return dependencyExists }; const handleRemove = action(() => { const { key } = selectedItem ?? {}; if (accounts[String(key)]['gui-perm'] == true) { setPermAlertVisible(true); } else if (checkDependency(String(key), state) == true) { setDependencyAlertVisible(true); } else { delete accounts[String(key)]; } setSelectedItem(undefined); }); return ( <> <AddModifyAccountModal type={modalType} accountType={accountType} visible={modalVisible} initialValue={modalInitialValue} onDismiss={() => setModalVisible(false)} onSubmit={handleSubmit} state={state} /> <Table items={items} trackBy="key" selectionType="single" selectedItems={selectedItem ? [selectedItem] : []} onSelectionChange={e => setSelectedItem(e.detail.selectedItems?.[0])} columnDefinitions={[ { header: nameTitle, cell: ({ name, description }) => <LabelWithDescription label={name} description={description} />, }, { header: ouTitle, cell: ({ ou }) => ou, }, { header: emailTitle, cell: ({ email }) => email, }, { header: budgetEmailTitle, cell: ({ useOuSettings, budgetEmail }) => useOuSettings ? <Badge className="nowrap">{useOuSettingTitle}</Badge> : budgetEmail, }, { header: budgetAmountTitle, cell: ({ useOuSettings, budgetAmount: amount }) => useOuSettings ? ( <Box textAlign="right"> <Badge className="nowrap">{useOuSettingTitle}</Badge> </Box> ) : ( <Box textAlign="right">{currency(amount)}</Box> ), }, { header: "Source File Name", cell: ({ srcFile }) => srcFile, }, ]} header={ <> <Header variant="h2" counter={`(${items.length})`} description={ accountType === 'mandatory' ? tr('wizard.headers.mandatory_accounts_desc') : tr('wizard.headers.workload_accounts_desc') } actions={ <SpaceBetween size="xs" direction="horizontal"> <Button disabled={selectedItem == null} onClick={handleRemove}> {tr('buttons.remove')} </Button> <Button disabled={selectedItem == null} onClick={handleEdit}> {tr('buttons.edit')} </Button> <Button iconName="add-plus" variant="primary" onClick={handleAdd}> {tr('buttons.add')} </Button> </SpaceBetween> } > {accountType === 'mandatory' ? tr('wizard.headers.mandatory_accounts') : tr('wizard.headers.workload_accounts')} </Header> { cannotAddAccount === true && <Alert onDismiss={() => setCannotAddAccount(false)} visible={cannotAddAccount} dismissible type="error" dismissAriaLabel="Close alert" header="Can't add new account" > Account fields cannot be left empty when adding a new account. </Alert> } { permAlertVisible === true && <Alert onDismiss={() => setPermAlertVisible(false)} visible={permAlertVisible} dismissible type="error" dismissAriaLabel="Close alert" header="This has been marked as a non-removable account in the configuration file." > Review the configuration file and remove the "gui-perm" field under the account if you would like to change this. </Alert> } { dependencyAlertVisible === true && <Alert onDismiss={() => setDependencyAlertVisible(false)} visible={dependencyAlertVisible} dismissible type="error" dismissAriaLabel="Close alert" header="Cannot remove this account due to dependency" > There are other sections of your configuration that depend on this account. Remove those dependencies first and try again. </Alert> } { editNameAlert === true && <Alert onDismiss={() => setEditNameAlert(false)} visible={editNameAlert} dismissible type="error" dismissAriaLabel="Close alert" header="Unsuccessful name change for Account" > You cannot rename an account to an already existing account name. </Alert> } { addNameAlert === true && <Alert onDismiss={() => setAddNameAlert(false)} visible={addNameAlert} dismissible type="error" dismissAriaLabel="Close alert" header="Unable to add Account" > You cannot add an account with the same key or name as an already existing account. </Alert> } </> } footer={ <SpaceBetween size="m"> <StatusIndicator type="info">{tr('wizard.labels.account_name_email_change_text')}</StatusIndicator> <StatusIndicator type="info">{tr('wizard.labels.account_email_uniqueness_text')}</StatusIndicator> <StatusIndicator type="info">{tr('wizard.labels.account_existing_account_text')}</StatusIndicator> </SpaceBetween> } /> </> ); }); interface AddModifyAccountModalProps { accountType: 'workload' | 'mandatory'; type: 'add' | 'edit'; visible: boolean; initialValue: Partial<SimpleAccountValue>; onDismiss: () => void; onSubmit: (value: SimpleAccountValue) => void; state: any; } /** * Custom renderer for OU budget configuration. */ const AddModifyAccountModal = ({ accountType, type, visible, initialValue, onDismiss, onSubmit, state, }: AddModifyAccountModalProps) => { const { tr } = useI18n(); const accountKeyInputProps = useInput(); const accountNameInputProps = useInput(); const emailInputProps = useInput(); const useOuInputProps = useCheckboxInput(); const budgetAmountInputProps = useInput(); const budgetEmailInputProps = useInput(); const srcFileInputProps = useInput(); // prettier-ignore const headerText = type === 'add' ? accountType === 'mandatory' ? tr('wizard.headers.add_mandatory_account') : tr('wizard.headers.add_workload_account') : accountType === 'mandatory' ?tr('wizard.headers.edit_mandatory_account'): tr('wizard.headers.edit_workload_account'); // prettier-ignore const buttonText = type === 'add' ? tr('buttons.add') : tr('buttons.save_changes'); const { title: nameTitle, description: nameDesc } = tr(dummyAccountNode.nested('account-name')); const { title: emailTitle, description: emailDesc } = tr(dummyAccountNode.nested('email')); const { title: ouTitle, description: ouDesc } = tr(dummyAccountNode.nested('ou')); const organizationalUnitsNode = AcceleratorConfigurationNode.nested('organizational-units'); const organizationalUnits = organizationalUnitsNode.get(state) ?? {}; var options: { label: string; value: string; }[] = [] const populateSelect = () => { for (const each in organizationalUnits) { options.push({label: each, value: each}) } } const keyTitle = tr('wizard.labels.account_key'); const useOuSettingTitle = tr('wizard.labels.account_budget_use_ou'); const budgetAmountTitle = tr('wizard.labels.account_budget_amount'); const budgetEmailTitle = tr('wizard.labels.account_budget_email'); const [selectedOption, setSelectedOption] = useState<OptionDefinition>({ label: "", value: "" }); const handleSubmit = () => { onSubmit({ key: accountKeyInputProps.value ?? '', ou: String(selectedOption.value) ?? '', name: accountNameInputProps.value ?? '', email: emailInputProps.value ?? '', useOuSettings: useOuInputProps.checked, budgetAmount: Number(budgetAmountInputProps.value) ?? NaN, budgetEmail: budgetEmailInputProps.value ?? '', srcFile: srcFileInputProps.value ?? '', }); }; useEffect(() => { accountKeyInputProps.setValue(initialValue.key ?? ''); accountNameInputProps.setValue(initialValue.name ?? ''); emailInputProps.setValue(initialValue.email ?? ''); setSelectedOption({ label: initialValue.ou ?? '', value: initialValue.ou ?? ''}); useOuInputProps.setChecked(initialValue.useOuSettings ?? false); budgetAmountInputProps.setValue(`${initialValue.budgetAmount}`); budgetEmailInputProps.setValue(initialValue.budgetEmail ?? ''); srcFileInputProps.setValue(initialValue.srcFile ?? ''); }, [visible]); return ( <Modal visible={visible} onDismiss={onDismiss} header={<Header variant="h3">{headerText}</Header>} footer={ <Button variant="primary" className="float-button" onClick={handleSubmit}> {buttonText} </Button> } > <form onSubmit={event => { event.stopPropagation(); event.preventDefault(); handleSubmit(); }} > {populateSelect()} <SpaceBetween size="m"> <FormField label={keyTitle} stretch> <Input {...accountKeyInputProps} disabled={type === 'edit'} /> </FormField> <FormField label={nameTitle} description={nameDesc} stretch> <Input {...accountNameInputProps} /> </FormField> <FormField label={emailTitle} description={emailDesc} stretch> <Input {...emailInputProps} /> </FormField> <FormField label={ouTitle} description={ouDesc} stretch> <Select selectedOption={selectedOption} onChange={({ detail }) => setSelectedOption(detail.selectedOption) } options={options} selectedAriaLabel="Selected" /> </FormField> <FormField label={useOuSettingTitle} stretch> <Checkbox {...useOuInputProps} disabled /> </FormField> <FormField label={budgetAmountTitle} stretch> <Input {...budgetAmountInputProps} disabled={useOuInputProps.checked} type="number" /> </FormField> <FormField label={budgetEmailTitle} stretch> <Input {...budgetEmailInputProps} disabled={useOuInputProps.checked} /> </FormField> <FormField label={"Source File Path"} description={"Add the Src File path for this account"} stretch> <Input {...srcFileInputProps} /> </FormField> </SpaceBetween> </form> </Modal> ); }; export function createInitialBudget(amount: number, email: string) { return { name: 'Budget', period: 'Monthly', amount, include: [ 'Upfront-reservation-fees', 'Recurring-reservation-charges', 'Other-subscription-costs', 'Taxes', 'Support-charges', 'Discounts', ], alerts: [ { type: 'Actual', 'threshold-percent': 50, emails: [email], }, { type: 'Actual', 'threshold-percent': 75, emails: [email], }, { type: 'Actual', 'threshold-percent': 90, emails: [email], }, { type: 'Actual', 'threshold-percent': 100, emails: [email], }, ], }; }
the_stack
declare class MPSGraph extends NSObject { static alloc(): MPSGraph; // inherited from NSObject static new(): MPSGraph; // inherited from NSObject options: MPSGraphOptions; readonly placeholderTensors: NSArray<MPSGraphTensor>; L2NormPooling4DGradientWithGradientTensorSourceTensorDescriptorName(gradient: MPSGraphTensor, source: MPSGraphTensor, descriptor: MPSGraphPooling4DOpDescriptor, name: string): MPSGraphTensor; L2NormPooling4DWithSourceTensorDescriptorName(source: MPSGraphTensor, descriptor: MPSGraphPooling4DOpDescriptor, name: string): MPSGraphTensor; absoluteWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; acosWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; acoshWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; additionWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; applyStochasticGradientDescentWithLearningRateTensorVariableGradientTensorName(learningRateTensor: MPSGraphTensor, variable: MPSGraphVariableOp, gradientTensor: MPSGraphTensor, name: string): MPSGraphOperation; asinWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; asinhWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; assignVariableWithValueOfTensorName(variable: MPSGraphTensor, tensor: MPSGraphTensor, name: string): MPSGraphOperation; atan2WithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; atanWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; atanhWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; avgPooling2DGradientWithGradientTensorSourceTensorDescriptorName(gradient: MPSGraphTensor, source: MPSGraphTensor, descriptor: MPSGraphPooling2DOpDescriptor, name: string): MPSGraphTensor; avgPooling2DWithSourceTensorDescriptorName(source: MPSGraphTensor, descriptor: MPSGraphPooling2DOpDescriptor, name: string): MPSGraphTensor; avgPooling4DGradientWithGradientTensorSourceTensorDescriptorName(gradient: MPSGraphTensor, source: MPSGraphTensor, descriptor: MPSGraphPooling4DOpDescriptor, name: string): MPSGraphTensor; avgPooling4DWithSourceTensorDescriptorName(source: MPSGraphTensor, descriptor: MPSGraphPooling4DOpDescriptor, name: string): MPSGraphTensor; broadcastTensorToShapeName(tensor: MPSGraphTensor, shape: NSArray<number> | number[], name: string): MPSGraphTensor; broadcastTensorToShapeTensorName(tensor: MPSGraphTensor, shapeTensor: MPSGraphTensor, name: string): MPSGraphTensor; ceilWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; clampWithTensorMinValueTensorMaxValueTensorName(tensor: MPSGraphTensor, minValueTensor: MPSGraphTensor, maxValueTensor: MPSGraphTensor, name: string): MPSGraphTensor; compileWithDeviceFeedsTargetTensorsTargetOperationsCompilationDescriptor(device: MPSGraphDevice, feeds: NSDictionary<MPSGraphTensor, MPSGraphShapedType>, targetTensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[], compilationDescriptor: MPSGraphCompilationDescriptor): MPSGraphExecutable; concatTensorWithTensorDimensionName(tensor: MPSGraphTensor, tensor2: MPSGraphTensor, dimensionIndex: number, name: string): MPSGraphTensor; concatTensorsDimensionInterleaveName(tensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], dimensionIndex: number, interleave: boolean, name: string): MPSGraphTensor; concatTensorsDimensionName(tensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], dimensionIndex: number, name: string): MPSGraphTensor; controlDependencyWithOperationsDependentBlockName(operations: NSArray<MPSGraphOperation> | MPSGraphOperation[], dependentBlock: () => NSArray<MPSGraphTensor>, name: string): NSArray<MPSGraphTensor>; convolution2DDataGradientWithIncomingGradientTensorWeightsTensorOutputShapeForwardConvolutionDescriptorName(incomingGradient: MPSGraphTensor, weights: MPSGraphTensor, outputShape: NSArray<number> | number[], forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolution2DDataGradientWithIncomingGradientTensorWeightsTensorOutputShapeTensorForwardConvolutionDescriptorName(gradient: MPSGraphTensor, weights: MPSGraphTensor, outputShapeTensor: MPSGraphTensor, forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolution2DWeightsGradientWithIncomingGradientTensorSourceTensorOutputShapeForwardConvolutionDescriptorName(incomingGradient: MPSGraphTensor, source: MPSGraphTensor, outputShape: NSArray<number> | number[], forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolution2DWeightsGradientWithIncomingGradientTensorSourceTensorOutputShapeTensorForwardConvolutionDescriptorName(gradient: MPSGraphTensor, source: MPSGraphTensor, outputShapeTensor: MPSGraphTensor, forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolution2DWithSourceTensorWeightsTensorDescriptorName(source: MPSGraphTensor, weights: MPSGraphTensor, descriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolutionTranspose2DDataGradientWithIncomingGradientTensorWeightsTensorOutputShapeForwardConvolutionDescriptorName(incomingGradient: MPSGraphTensor, weights: MPSGraphTensor, outputShape: NSArray<number> | number[], forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolutionTranspose2DDataGradientWithIncomingGradientTensorWeightsTensorOutputShapeTensorForwardConvolutionDescriptorName(incomingGradient: MPSGraphTensor, weights: MPSGraphTensor, outputShape: MPSGraphTensor, forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolutionTranspose2DWeightsGradientWithIncomingGradientTensorSourceTensorOutputShapeForwardConvolutionDescriptorName(incomingGradientTensor: MPSGraphTensor, source: MPSGraphTensor, outputShape: NSArray<number> | number[], forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolutionTranspose2DWeightsGradientWithIncomingGradientTensorSourceTensorOutputShapeTensorForwardConvolutionDescriptorName(incomingGradientTensor: MPSGraphTensor, source: MPSGraphTensor, outputShape: MPSGraphTensor, forwardConvolutionDescriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolutionTranspose2DWithSourceTensorWeightsTensorOutputShapeDescriptorName(source: MPSGraphTensor, weights: MPSGraphTensor, outputShape: NSArray<number> | number[], descriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; convolutionTranspose2DWithSourceTensorWeightsTensorOutputShapeTensorDescriptorName(source: MPSGraphTensor, weights: MPSGraphTensor, outputShape: MPSGraphTensor, descriptor: MPSGraphConvolution2DOpDescriptor, name: string): MPSGraphTensor; cosWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; coshWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; depthToSpace2DTensorWidthAxisHeightAxisDepthAxisBlockSizeUsePixelShuffleOrderName(tensor: MPSGraphTensor, widthAxis: number, heightAxis: number, depthAxis: number, blockSize: number, usePixelShuffleOrder: boolean, name: string): MPSGraphTensor; depthToSpace2DTensorWidthAxisTensorHeightAxisTensorDepthAxisTensorBlockSizeUsePixelShuffleOrderName(tensor: MPSGraphTensor, widthAxisTensor: MPSGraphTensor, heightAxisTensor: MPSGraphTensor, depthAxisTensor: MPSGraphTensor, blockSize: number, usePixelShuffleOrder: boolean, name: string): MPSGraphTensor; depthwiseConvolution2DDataGradientWithIncomingGradientTensorWeightsTensorOutputShapeDescriptorName(incomingGradient: MPSGraphTensor, weights: MPSGraphTensor, outputShape: NSArray<number> | number[], descriptor: MPSGraphDepthwiseConvolution2DOpDescriptor, name: string): MPSGraphTensor; depthwiseConvolution2DWeightsGradientWithIncomingGradientTensorSourceTensorOutputShapeDescriptorName(incomingGradient: MPSGraphTensor, source: MPSGraphTensor, outputShape: NSArray<number> | number[], descriptor: MPSGraphDepthwiseConvolution2DOpDescriptor, name: string): MPSGraphTensor; depthwiseConvolution2DWithSourceTensorWeightsTensorDescriptorName(source: MPSGraphTensor, weights: MPSGraphTensor, descriptor: MPSGraphDepthwiseConvolution2DOpDescriptor, name: string): MPSGraphTensor; depthwiseConvolution3DDataGradientWithIncomingGradientTensorWeightsTensorOutputShapeDescriptorName(incomingGradient: MPSGraphTensor, weights: MPSGraphTensor, outputShape: NSArray<number> | number[], descriptor: MPSGraphDepthwiseConvolution3DOpDescriptor, name: string): MPSGraphTensor; depthwiseConvolution3DWeightsGradientWithIncomingGradientTensorSourceTensorOutputShapeDescriptorName(incomingGradient: MPSGraphTensor, source: MPSGraphTensor, outputShape: NSArray<number> | number[], descriptor: MPSGraphDepthwiseConvolution3DOpDescriptor, name: string): MPSGraphTensor; depthwiseConvolution3DWithSourceTensorWeightsTensorDescriptorName(source: MPSGraphTensor, weights: MPSGraphTensor, descriptor: MPSGraphDepthwiseConvolution3DOpDescriptor, name: string): MPSGraphTensor; divisionNoNaNWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; divisionWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; dropoutTensorRateName(tensor: MPSGraphTensor, rate: number, name: string): MPSGraphTensor; dropoutTensorRateTensorName(tensor: MPSGraphTensor, rate: MPSGraphTensor, name: string): MPSGraphTensor; equalWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; erfWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; exponentBase10WithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; exponentBase2WithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; exponentWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; flatten2DTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; flatten2DTensorAxisTensorName(tensor: MPSGraphTensor, axisTensor: MPSGraphTensor, name: string): MPSGraphTensor; floorModuloWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; floorWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; forLoopWithLowerBoundUpperBoundStepInitialBodyArgumentsBodyName(lowerBound: MPSGraphTensor, upperBound: MPSGraphTensor, step: MPSGraphTensor, initialBodyArguments: NSArray<MPSGraphTensor> | MPSGraphTensor[], body: (p1: MPSGraphTensor, p2: NSArray<MPSGraphTensor>) => NSArray<MPSGraphTensor>, name: string): NSArray<MPSGraphTensor>; forLoopWithNumberOfIterationsInitialBodyArgumentsBodyName(numberOfIterations: MPSGraphTensor, initialBodyArguments: NSArray<MPSGraphTensor> | MPSGraphTensor[], body: (p1: MPSGraphTensor, p2: NSArray<MPSGraphTensor>) => NSArray<MPSGraphTensor>, name: string): NSArray<MPSGraphTensor>; gatherNDWithUpdatesTensorIndicesTensorBatchDimensionsName(updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, batchDimensions: number, name: string): MPSGraphTensor; gatherWithUpdatesTensorIndicesTensorAxisBatchDimensionsName(updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, axis: number, batchDimensions: number, name: string): MPSGraphTensor; gradientForPrimaryTensorWithTensorsName(primaryTensor: MPSGraphTensor, tensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], name: string): NSDictionary<MPSGraphTensor, MPSGraphTensor>; greaterThanOrEqualToWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; greaterThanWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; identityWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; ifWithPredicateTensorThenBlockElseBlockName(predicateTensor: MPSGraphTensor, thenBlock: () => NSArray<MPSGraphTensor>, elseBlock: () => NSArray<MPSGraphTensor>, name: string): NSArray<MPSGraphTensor>; isFiniteWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; isInfiniteWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; isNaNWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; leakyReLUGradientWithIncomingGradientSourceTensorAlphaTensorName(gradient: MPSGraphTensor, source: MPSGraphTensor, alphaTensor: MPSGraphTensor, name: string): MPSGraphTensor; leakyReLUWithTensorAlphaName(tensor: MPSGraphTensor, alpha: number, name: string): MPSGraphTensor; leakyReLUWithTensorAlphaTensorName(tensor: MPSGraphTensor, alphaTensor: MPSGraphTensor, name: string): MPSGraphTensor; lessThanOrEqualToWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; lessThanWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; logarithmBase10WithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; logarithmBase2WithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; logarithmWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; logicalANDWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; logicalNANDWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; logicalNORWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; logicalORWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; logicalXNORWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; logicalXORWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; matrixMultiplicationWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; maxPooling2DGradientWithGradientTensorSourceTensorDescriptorName(gradient: MPSGraphTensor, source: MPSGraphTensor, descriptor: MPSGraphPooling2DOpDescriptor, name: string): MPSGraphTensor; maxPooling2DWithSourceTensorDescriptorName(source: MPSGraphTensor, descriptor: MPSGraphPooling2DOpDescriptor, name: string): MPSGraphTensor; maxPooling4DGradientWithGradientTensorSourceTensorDescriptorName(gradient: MPSGraphTensor, source: MPSGraphTensor, descriptor: MPSGraphPooling4DOpDescriptor, name: string): MPSGraphTensor; maxPooling4DWithSourceTensorDescriptorName(source: MPSGraphTensor, descriptor: MPSGraphPooling4DOpDescriptor, name: string): MPSGraphTensor; maximumWithNaNPropagationWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; maximumWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; meanOfTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; minimumWithNaNPropagationWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; minimumWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; moduloWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; multiplicationWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; negativeWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; normalizationBetaGradientWithIncomingGradientTensorSourceTensorReductionAxesName(incomingGradientTensor: MPSGraphTensor, sourceTensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; normalizationGammaGradientWithIncomingGradientTensorSourceTensorMeanTensorVarianceTensorReductionAxesEpsilonName(incomingGradientTensor: MPSGraphTensor, sourceTensor: MPSGraphTensor, meanTensor: MPSGraphTensor, varianceTensor: MPSGraphTensor, axes: NSArray<number> | number[], epsilon: number, name: string): MPSGraphTensor; normalizationGradientWithIncomingGradientTensorSourceTensorMeanTensorVarianceTensorGammaTensorGammaGradientTensorBetaGradientTensorReductionAxesEpsilonName(incomingGradientTensor: MPSGraphTensor, sourceTensor: MPSGraphTensor, meanTensor: MPSGraphTensor, varianceTensor: MPSGraphTensor, gamma: MPSGraphTensor, gammaGradient: MPSGraphTensor, betaGradient: MPSGraphTensor, axes: NSArray<number> | number[], epsilon: number, name: string): MPSGraphTensor; normalizationWithTensorMeanTensorVarianceTensorGammaTensorBetaTensorEpsilonName(tensor: MPSGraphTensor, mean: MPSGraphTensor, variance: MPSGraphTensor, gamma: MPSGraphTensor, beta: MPSGraphTensor, epsilon: number, name: string): MPSGraphTensor; notEqualWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; notWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; oneHotWithIndicesTensorDepthAxisName(indicesTensor: MPSGraphTensor, depth: number, axis: number, name: string): MPSGraphTensor; oneHotWithIndicesTensorDepthName(indicesTensor: MPSGraphTensor, depth: number, name: string): MPSGraphTensor; padGradientWithIncomingGradientTensorSourceTensorPaddingModeLeftPaddingRightPaddingName(incomingGradientTensor: MPSGraphTensor, sourceTensor: MPSGraphTensor, paddingMode: MPSGraphPaddingMode, leftPadding: NSArray<number> | number[], rightPadding: NSArray<number> | number[], name: string): MPSGraphTensor; padTensorWithPaddingModeLeftPaddingRightPaddingConstantValueName(tensor: MPSGraphTensor, paddingMode: MPSGraphPaddingMode, leftPadding: NSArray<number> | number[], rightPadding: NSArray<number> | number[], constantValue: number, name: string): MPSGraphTensor; placeholderWithShapeName(shape: NSArray<number> | number[], name: string): MPSGraphTensor; powerWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; reLUGradientWithIncomingGradientSourceTensorName(gradient: MPSGraphTensor, source: MPSGraphTensor, name: string): MPSGraphTensor; reLUWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; readVariableName(variable: MPSGraphTensor, name: string): MPSGraphTensor; reciprocalWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; reductionArgMaximumWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; reductionArgMinimumWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; reductionMaximumWithTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; reductionMaximumWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; reductionMinimumWithTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; reductionMinimumWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; reductionProductWithTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; reductionProductWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; reductionSumWithTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; reductionSumWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; reshapeTensorWithShapeName(tensor: MPSGraphTensor, shape: NSArray<number> | number[], name: string): MPSGraphTensor; reshapeTensorWithShapeTensorName(tensor: MPSGraphTensor, shapeTensor: MPSGraphTensor, name: string): MPSGraphTensor; resizeTensorSizeModeCenterResultAlignCornersLayoutName(imagesTensor: MPSGraphTensor, size: NSArray<number> | number[], mode: MPSGraphResizeMode, centerResult: boolean, alignCorners: boolean, layout: MPSGraphTensorNamedDataLayout, name: string): MPSGraphTensor; resizeTensorSizeTensorModeCenterResultAlignCornersLayoutName(imagesTensor: MPSGraphTensor, size: MPSGraphTensor, mode: MPSGraphResizeMode, centerResult: boolean, alignCorners: boolean, layout: MPSGraphTensorNamedDataLayout, name: string): MPSGraphTensor; resizeWithGradientTensorInputModeCenterResultAlignCornersLayoutName(gradient: MPSGraphTensor, input: MPSGraphTensor, mode: MPSGraphResizeMode, centerResult: boolean, alignCorners: boolean, layout: MPSGraphTensorNamedDataLayout, name: string): MPSGraphTensor; reverseSquareRootWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; reverseTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; reverseTensorAxesTensorName(tensor: MPSGraphTensor, axesTensor: MPSGraphTensor, name: string): MPSGraphTensor; reverseTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; rintWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; roundWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; runAsyncWithFeedsTargetTensorsTargetOperationsExecutionDescriptor(feeds: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, targetTensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[], executionDescriptor: MPSGraphExecutionDescriptor): NSDictionary<MPSGraphTensor, MPSGraphTensorData>; runAsyncWithMTLCommandQueueFeedsTargetOperationsResultsDictionaryExecutionDescriptor(commandQueue: MTLCommandQueue, feeds: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[], resultsDictionary: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, executionDescriptor: MPSGraphExecutionDescriptor): void; runAsyncWithMTLCommandQueueFeedsTargetTensorsTargetOperationsExecutionDescriptor(commandQueue: MTLCommandQueue, feeds: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, targetTensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[], executionDescriptor: MPSGraphExecutionDescriptor): NSDictionary<MPSGraphTensor, MPSGraphTensorData>; runWithFeedsTargetTensorsTargetOperations(feeds: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, targetTensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[]): NSDictionary<MPSGraphTensor, MPSGraphTensorData>; runWithMTLCommandQueueFeedsTargetOperationsResultsDictionary(commandQueue: MTLCommandQueue, feeds: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[], resultsDictionary: NSDictionary<MPSGraphTensor, MPSGraphTensorData>): void; runWithMTLCommandQueueFeedsTargetTensorsTargetOperations(commandQueue: MTLCommandQueue, feeds: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, targetTensors: NSArray<MPSGraphTensor> | MPSGraphTensor[], targetOperations: NSArray<MPSGraphOperation> | MPSGraphOperation[]): NSDictionary<MPSGraphTensor, MPSGraphTensorData>; scatterNDWithDataTensorUpdatesTensorIndicesTensorBatchDimensionsModeName(dataTensor: MPSGraphTensor, updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, batchDimensions: number, mode: MPSGraphScatterMode, name: string): MPSGraphTensor; scatterNDWithUpdatesTensorIndicesTensorShapeBatchDimensionsModeName(updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, shape: NSArray<number> | number[], batchDimensions: number, mode: MPSGraphScatterMode, name: string): MPSGraphTensor; scatterNDWithUpdatesTensorIndicesTensorShapeBatchDimensionsName(updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, shape: NSArray<number> | number[], batchDimensions: number, name: string): MPSGraphTensor; scatterWithDataTensorUpdatesTensorIndicesTensorAxisModeName(dataTensor: MPSGraphTensor, updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, axis: number, mode: MPSGraphScatterMode, name: string): MPSGraphTensor; scatterWithUpdatesTensorIndicesTensorShapeAxisModeName(updatesTensor: MPSGraphTensor, indicesTensor: MPSGraphTensor, shape: NSArray<number> | number[], axis: number, mode: MPSGraphScatterMode, name: string): MPSGraphTensor; selectWithPredicateTensorTruePredicateTensorFalsePredicateTensorName(predicateTensor: MPSGraphTensor, truePredicateTensor: MPSGraphTensor, falseSelectTensor: MPSGraphTensor, name: string): MPSGraphTensor; shapeOfTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; sigmoidGradientWithIncomingGradientSourceTensorName(gradient: MPSGraphTensor, source: MPSGraphTensor, name: string): MPSGraphTensor; sigmoidWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; signWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; signbitWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; sinWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; sinhWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; sliceGradientTensorFwdInShapeTensorStartsEndsStridesName(inputGradientTensor: MPSGraphTensor, fwdInShapeTensor: MPSGraphTensor, starts: NSArray<number> | number[], ends: NSArray<number> | number[], strides: NSArray<number> | number[], name: string): MPSGraphTensor; sliceGradientTensorFwdInShapeTensorStartsEndsStridesStartMaskEndMaskSqueezeMaskName(inputGradientTensor: MPSGraphTensor, fwdInShapeTensor: MPSGraphTensor, starts: NSArray<number> | number[], ends: NSArray<number> | number[], strides: NSArray<number> | number[], startMask: number, endMask: number, squeezeMask: number, name: string): MPSGraphTensor; sliceTensorDimensionStartLengthName(tensor: MPSGraphTensor, dimensionIndex: number, start: number, length: number, name: string): MPSGraphTensor; sliceTensorStartsEndsStridesName(tensor: MPSGraphTensor, starts: NSArray<number> | number[], ends: NSArray<number> | number[], strides: NSArray<number> | number[], name: string): MPSGraphTensor; sliceTensorStartsEndsStridesStartMaskEndMaskSqueezeMaskName(tensor: MPSGraphTensor, starts: NSArray<number> | number[], ends: NSArray<number> | number[], strides: NSArray<number> | number[], startMask: number, endMask: number, squeezeMask: number, name: string): MPSGraphTensor; softMaxCrossEntropyGradientWithIncomingGradientTensorSourceTensorLabelsTensorAxisReductionTypeName(gradientTensor: MPSGraphTensor, sourceTensor: MPSGraphTensor, labelsTensor: MPSGraphTensor, axis: number, reductionType: MPSGraphLossReductionType, name: string): MPSGraphTensor; softMaxCrossEntropyWithSourceTensorLabelsTensorAxisReductionTypeName(sourceTensor: MPSGraphTensor, labelsTensor: MPSGraphTensor, axis: number, reductionType: MPSGraphLossReductionType, name: string): MPSGraphTensor; softMaxGradientWithIncomingGradientSourceTensorAxisName(gradient: MPSGraphTensor, source: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; softMaxWithTensorAxisName(tensor: MPSGraphTensor, axis: number, name: string): MPSGraphTensor; spaceToDepth2DTensorWidthAxisHeightAxisDepthAxisBlockSizeUsePixelShuffleOrderName(tensor: MPSGraphTensor, widthAxis: number, heightAxis: number, depthAxis: number, blockSize: number, usePixelShuffleOrder: boolean, name: string): MPSGraphTensor; spaceToDepth2DTensorWidthAxisTensorHeightAxisTensorDepthAxisTensorBlockSizeUsePixelShuffleOrderName(tensor: MPSGraphTensor, widthAxisTensor: MPSGraphTensor, heightAxisTensor: MPSGraphTensor, depthAxisTensor: MPSGraphTensor, blockSize: number, usePixelShuffleOrder: boolean, name: string): MPSGraphTensor; sparseTensorWithDescriptorTensorsShapeName(sparseDescriptor: MPSGraphCreateSparseOpDescriptor, inputTensorArray: NSArray<MPSGraphTensor> | MPSGraphTensor[], shape: NSArray<number> | number[], name: string): MPSGraphTensor; squareRootWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; squareWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; stencilWithSourceTensorWeightsTensorDescriptorName(source: MPSGraphTensor, weights: MPSGraphTensor, descriptor: MPSGraphStencilOpDescriptor, name: string): MPSGraphTensor; stochasticGradientDescentWithLearningRateTensorValuesTensorGradientTensorName(learningRateTensor: MPSGraphTensor, valuesTensor: MPSGraphTensor, gradientTensor: MPSGraphTensor, name: string): MPSGraphTensor; subtractionWithPrimaryTensorSecondaryTensorName(primaryTensor: MPSGraphTensor, secondaryTensor: MPSGraphTensor, name: string): MPSGraphTensor; tanWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; tanhWithTensorName(tensor: MPSGraphTensor, name: string): MPSGraphTensor; tileGradientWithIncomingGradientTensorSourceTensorWithMultiplierName(incomingGradientTensor: MPSGraphTensor, sourceTensor: MPSGraphTensor, multiplier: NSArray<number> | number[], name: string): MPSGraphTensor; tileTensorWithMultiplierName(tensor: MPSGraphTensor, multiplier: NSArray<number> | number[], name: string): MPSGraphTensor; topKWithGradientTensorSourceKName(gradient: MPSGraphTensor, source: MPSGraphTensor, k: number, name: string): MPSGraphTensor; topKWithGradientTensorSourceKTensorName(gradient: MPSGraphTensor, source: MPSGraphTensor, kTensor: MPSGraphTensor, name: string): MPSGraphTensor; topKWithSourceTensorKName(source: MPSGraphTensor, k: number, name: string): NSArray<MPSGraphTensor>; topKWithSourceTensorKTensorName(source: MPSGraphTensor, kTensor: MPSGraphTensor, name: string): NSArray<MPSGraphTensor>; transposeTensorDimensionWithDimensionName(tensor: MPSGraphTensor, dimensionIndex: number, dimensionIndex2: number, name: string): MPSGraphTensor; varianceOfTensorAxesName(tensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; varianceOfTensorMeanTensorAxesName(tensor: MPSGraphTensor, meanTensor: MPSGraphTensor, axes: NSArray<number> | number[], name: string): MPSGraphTensor; whileWithInitialInputsBeforeAfterName(initialInputs: NSArray<MPSGraphTensor> | MPSGraphTensor[], before: (p1: NSArray<MPSGraphTensor>, p2: NSMutableArray<MPSGraphTensor>) => MPSGraphTensor, after: (p1: NSArray<MPSGraphTensor>) => NSArray<MPSGraphTensor>, name: string): NSArray<MPSGraphTensor>; } declare class MPSGraphCompilationDescriptor extends NSObject { static alloc(): MPSGraphCompilationDescriptor; // inherited from NSObject static new(): MPSGraphCompilationDescriptor; // inherited from NSObject disableTypeInference(): void; } declare class MPSGraphConvolution2DOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphConvolution2DOpDescriptor; // inherited from NSObject static descriptorWithStrideInXStrideInYDilationRateInXDilationRateInYGroupsPaddingLeftPaddingRightPaddingTopPaddingBottomPaddingStyleDataLayoutWeightsLayout(strideInX: number, strideInY: number, dilationRateInX: number, dilationRateInY: number, groups: number, paddingLeft: number, paddingRight: number, paddingTop: number, paddingBottom: number, paddingStyle: MPSGraphPaddingStyle, dataLayout: MPSGraphTensorNamedDataLayout, weightsLayout: MPSGraphTensorNamedDataLayout): MPSGraphConvolution2DOpDescriptor; static descriptorWithStrideInXStrideInYDilationRateInXDilationRateInYGroupsPaddingStyleDataLayoutWeightsLayout(strideInX: number, strideInY: number, dilationRateInX: number, dilationRateInY: number, groups: number, paddingStyle: MPSGraphPaddingStyle, dataLayout: MPSGraphTensorNamedDataLayout, weightsLayout: MPSGraphTensorNamedDataLayout): MPSGraphConvolution2DOpDescriptor; static new(): MPSGraphConvolution2DOpDescriptor; // inherited from NSObject dataLayout: MPSGraphTensorNamedDataLayout; dilationRateInX: number; dilationRateInY: number; groups: number; paddingBottom: number; paddingLeft: number; paddingRight: number; paddingStyle: MPSGraphPaddingStyle; paddingTop: number; strideInX: number; strideInY: number; weightsLayout: MPSGraphTensorNamedDataLayout; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; setExplicitPaddingWithPaddingLeftPaddingRightPaddingTopPaddingBottom(paddingLeft: number, paddingRight: number, paddingTop: number, paddingBottom: number): void; } declare class MPSGraphCreateSparseOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphCreateSparseOpDescriptor; // inherited from NSObject static new(): MPSGraphCreateSparseOpDescriptor; // inherited from NSObject sparseStorageType: MPSGraphSparseStorageType; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class MPSGraphDepthwiseConvolution2DOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphDepthwiseConvolution2DOpDescriptor; // inherited from NSObject static descriptorWithDataLayoutWeightsLayout(dataLayout: MPSGraphTensorNamedDataLayout, weightsLayout: MPSGraphTensorNamedDataLayout): MPSGraphDepthwiseConvolution2DOpDescriptor; static descriptorWithStrideInXStrideInYDilationRateInXDilationRateInYPaddingLeftPaddingRightPaddingTopPaddingBottomPaddingStyleDataLayoutWeightsLayout(strideInX: number, strideInY: number, dilationRateInX: number, dilationRateInY: number, paddingLeft: number, paddingRight: number, paddingTop: number, paddingBottom: number, paddingStyle: MPSGraphPaddingStyle, dataLayout: MPSGraphTensorNamedDataLayout, weightsLayout: MPSGraphTensorNamedDataLayout): MPSGraphDepthwiseConvolution2DOpDescriptor; static new(): MPSGraphDepthwiseConvolution2DOpDescriptor; // inherited from NSObject dataLayout: MPSGraphTensorNamedDataLayout; dilationRateInX: number; dilationRateInY: number; paddingBottom: number; paddingLeft: number; paddingRight: number; paddingStyle: MPSGraphPaddingStyle; paddingTop: number; strideInX: number; strideInY: number; weightsLayout: MPSGraphTensorNamedDataLayout; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; setExplicitPaddingWithPaddingLeftPaddingRightPaddingTopPaddingBottom(paddingLeft: number, paddingRight: number, paddingTop: number, paddingBottom: number): void; } declare class MPSGraphDepthwiseConvolution3DOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphDepthwiseConvolution3DOpDescriptor; // inherited from NSObject static descriptorWithPaddingStyle(paddingStyle: MPSGraphPaddingStyle): MPSGraphDepthwiseConvolution3DOpDescriptor; static descriptorWithStridesDilationRatesPaddingValuesPaddingStyle(strides: NSArray<number> | number[], dilationRates: NSArray<number> | number[], paddingValues: NSArray<number> | number[], paddingStyle: MPSGraphPaddingStyle): MPSGraphDepthwiseConvolution3DOpDescriptor; static new(): MPSGraphDepthwiseConvolution3DOpDescriptor; // inherited from NSObject channelDimensionIndex: number; dilationRates: NSArray<number>; paddingStyle: MPSGraphPaddingStyle; paddingValues: NSArray<number>; strides: NSArray<number>; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class MPSGraphDevice extends NSObject { static alloc(): MPSGraphDevice; // inherited from NSObject static deviceWithMTLDevice(metalDevice: MTLDevice): MPSGraphDevice; static new(): MPSGraphDevice; // inherited from NSObject readonly metalDevice: MTLDevice; readonly type: MPSGraphDeviceType; } declare const enum MPSGraphDeviceType { Metal = 0 } declare class MPSGraphExecutable extends NSObject { static alloc(): MPSGraphExecutable; // inherited from NSObject static new(): MPSGraphExecutable; // inherited from NSObject readonly feedTensors: NSArray<MPSGraphTensor>; options: MPSGraphOptions; readonly targetTensors: NSArray<MPSGraphTensor>; runAsyncWithMTLCommandQueueInputsArrayResultsArrayExecutionDescriptor(commandQueue: MTLCommandQueue, inputsArray: NSArray<MPSGraphTensorData> | MPSGraphTensorData[], resultsArray: NSArray<MPSGraphTensorData> | MPSGraphTensorData[], executionDescriptor: MPSGraphExecutableExecutionDescriptor): NSArray<MPSGraphTensorData>; runWithMTLCommandQueueInputsArrayResultsArrayExecutionDescriptor(commandQueue: MTLCommandQueue, inputsArray: NSArray<MPSGraphTensorData> | MPSGraphTensorData[], resultsArray: NSArray<MPSGraphTensorData> | MPSGraphTensorData[], executionDescriptor: MPSGraphExecutableExecutionDescriptor): NSArray<MPSGraphTensorData>; specializeWithDeviceInputTypesCompilationDescriptor(device: MPSGraphDevice, inputTypes: NSArray<MPSGraphType> | MPSGraphType[], compilationDescriptor: MPSGraphCompilationDescriptor): void; } declare class MPSGraphExecutableExecutionDescriptor extends NSObject { static alloc(): MPSGraphExecutableExecutionDescriptor; // inherited from NSObject static new(): MPSGraphExecutableExecutionDescriptor; // inherited from NSObject completionHandler: (p1: NSArray<MPSGraphTensorData>, p2: NSError) => void; scheduledHandler: (p1: NSArray<MPSGraphTensorData>, p2: NSError) => void; waitUntilCompleted: boolean; } declare class MPSGraphExecutionDescriptor extends NSObject { static alloc(): MPSGraphExecutionDescriptor; // inherited from NSObject static new(): MPSGraphExecutionDescriptor; // inherited from NSObject completionHandler: (p1: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, p2: NSError) => void; scheduledHandler: (p1: NSDictionary<MPSGraphTensor, MPSGraphTensorData>, p2: NSError) => void; waitUntilCompleted: boolean; } declare const enum MPSGraphLossReductionType { Axis = 0, Sum = 1, Mean = 2 } declare class MPSGraphOperation extends NSObject implements NSCopying { static alloc(): MPSGraphOperation; // inherited from NSObject static new(): MPSGraphOperation; // inherited from NSObject readonly controlDependencies: NSArray<MPSGraphOperation>; readonly graph: MPSGraph; readonly inputTensors: NSArray<MPSGraphTensor>; readonly name: string; readonly outputTensors: NSArray<MPSGraphTensor>; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare const enum MPSGraphOptions { None = 0, SynchronizeResults = 1, Verbose = 2, Default = 1 } declare const enum MPSGraphPaddingMode { Constant = 0, Reflect = 1, Symmetric = 2, ClampToEdge = 3, Zero = 4, Periodic = 5, AntiPeriodic = 6 } declare const enum MPSGraphPaddingStyle { Explicit = 0, TF_VALID = 1, TF_SAME = 2, ExplicitOffset = 3 } declare class MPSGraphPooling2DOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphPooling2DOpDescriptor; // inherited from NSObject static descriptorWithKernelWidthKernelHeightStrideInXStrideInYDilationRateInXDilationRateInYPaddingLeftPaddingRightPaddingTopPaddingBottomPaddingStyleDataLayout(kernelWidth: number, kernelHeight: number, strideInX: number, strideInY: number, dilationRateInX: number, dilationRateInY: number, paddingLeft: number, paddingRight: number, paddingTop: number, paddingBottom: number, paddingStyle: MPSGraphPaddingStyle, dataLayout: MPSGraphTensorNamedDataLayout): MPSGraphPooling2DOpDescriptor; static descriptorWithKernelWidthKernelHeightStrideInXStrideInYPaddingStyleDataLayout(kernelWidth: number, kernelHeight: number, strideInX: number, strideInY: number, paddingStyle: MPSGraphPaddingStyle, dataLayout: MPSGraphTensorNamedDataLayout): MPSGraphPooling2DOpDescriptor; static new(): MPSGraphPooling2DOpDescriptor; // inherited from NSObject ceilMode: boolean; dataLayout: MPSGraphTensorNamedDataLayout; dilationRateInX: number; dilationRateInY: number; includeZeroPadToAverage: boolean; kernelHeight: number; kernelWidth: number; paddingBottom: number; paddingLeft: number; paddingRight: number; paddingStyle: MPSGraphPaddingStyle; paddingTop: number; strideInX: number; strideInY: number; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; setExplicitPaddingWithPaddingLeftPaddingRightPaddingTopPaddingBottom(paddingLeft: number, paddingRight: number, paddingTop: number, paddingBottom: number): void; } declare class MPSGraphPooling4DOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphPooling4DOpDescriptor; // inherited from NSObject static descriptorWithKernelSizesPaddingStyle(kernelSizes: NSArray<number> | number[], paddingStyle: MPSGraphPaddingStyle): MPSGraphPooling4DOpDescriptor; static descriptorWithKernelSizesStridesDilationRatesPaddingValuesPaddingStyle(kernelSizes: NSArray<number> | number[], strides: NSArray<number> | number[], dilationRates: NSArray<number> | number[], paddingValues: NSArray<number> | number[], paddingStyle: MPSGraphPaddingStyle): MPSGraphPooling4DOpDescriptor; static new(): MPSGraphPooling4DOpDescriptor; // inherited from NSObject ceilMode: boolean; dilationRates: NSArray<number>; includeZeroPadToAverage: boolean; kernelSizes: NSArray<number>; paddingStyle: MPSGraphPaddingStyle; paddingValues: NSArray<number>; strides: NSArray<number>; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare const enum MPSGraphReductionMode { Min = 0, Max = 1, Sum = 2, Product = 3, ArgumentMin = 4, ArgumentMax = 5 } declare const enum MPSGraphResizeMode { Nearest = 0, Bilinear = 1 } declare const enum MPSGraphScatterMode { Add = 0, Sub = 1, Mul = 2, Div = 3, Min = 4, Max = 5, Set = 6 } declare class MPSGraphShapedType extends MPSGraphType { static alloc(): MPSGraphShapedType; // inherited from NSObject static new(): MPSGraphShapedType; // inherited from NSObject shape: NSArray<number>; isEqualTo(object: MPSGraphShapedType): boolean; } declare const enum MPSGraphSparseStorageType { COO = 0, CSC = 1, CSR = 2 } declare class MPSGraphStencilOpDescriptor extends NSObject implements NSCopying { static alloc(): MPSGraphStencilOpDescriptor; // inherited from NSObject static descriptorWithExplicitPadding(explicitPadding: NSArray<number> | number[]): MPSGraphStencilOpDescriptor; static descriptorWithOffsetsExplicitPadding(offsets: NSArray<number> | number[], explicitPadding: NSArray<number> | number[]): MPSGraphStencilOpDescriptor; static descriptorWithPaddingStyle(paddingStyle: MPSGraphPaddingStyle): MPSGraphStencilOpDescriptor; static descriptorWithReductionModeOffsetsStridesDilationRatesExplicitPaddingBoundaryModePaddingStylePaddingConstant(reductionMode: MPSGraphReductionMode, offsets: NSArray<number> | number[], strides: NSArray<number> | number[], dilationRates: NSArray<number> | number[], explicitPadding: NSArray<number> | number[], boundaryMode: MPSGraphPaddingMode, paddingStyle: MPSGraphPaddingStyle, paddingConstant: number): MPSGraphStencilOpDescriptor; static new(): MPSGraphStencilOpDescriptor; // inherited from NSObject boundaryMode: MPSGraphPaddingMode; dilationRates: NSArray<number>; explicitPadding: NSArray<number>; offsets: NSArray<number>; paddingConstant: number; paddingStyle: MPSGraphPaddingStyle; reductionMode: MPSGraphReductionMode; strides: NSArray<number>; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class MPSGraphTensor extends NSObject implements NSCopying { static alloc(): MPSGraphTensor; // inherited from NSObject static new(): MPSGraphTensor; // inherited from NSObject readonly operation: MPSGraphOperation; readonly shape: NSArray<number>; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class MPSGraphTensorData extends NSObject { static alloc(): MPSGraphTensorData; // inherited from NSObject static new(): MPSGraphTensorData; // inherited from NSObject readonly device: MPSGraphDevice; readonly shape: NSArray<number>; } declare const enum MPSGraphTensorNamedDataLayout { NCHW = 0, NHWC = 1, OIHW = 2, HWIO = 3, CHW = 4, HWC = 5, HW = 6 } declare class MPSGraphType extends NSObject implements NSCopying { static alloc(): MPSGraphType; // inherited from NSObject static new(): MPSGraphType; // inherited from NSObject copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class MPSGraphVariableOp extends MPSGraphOperation { static alloc(): MPSGraphVariableOp; // inherited from NSObject static new(): MPSGraphVariableOp; // inherited from NSObject readonly shape: NSArray<number>; }
the_stack
import { assertEquals } from "../../deps.ts"; import * as Drash from "../../../mod.ts"; import type { ConnInfo } from "../../../deps.ts"; const connInfo: ConnInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 1337, }, remoteAddr: { transport: "udp", hostname: "localhost", port: 1337, }, }; Deno.test("http/request_test.ts", async (t) => { await t.step("original", async (t) => { await originalRequestTests(t); }); await t.step("accepts()", async (t) => { await acceptsTests(t); }); await t.step("getCookie()", async (t) => { await getCookieTests(t); }); await t.step("bodyParam()", async (t) => { await bodyTests(t); }); await t.step("pathParam()", async (t) => { await paramTests(t); }); await t.step("queryParam()", async (t) => { await queryTests(t); }); }); //////////////////////////////////////////////////////////////////////////////// // FILE MARKER - TEST CASES //////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// async function acceptsTests(t: Deno.TestContext) { await t.step( "accepts the single type if it is present in the header", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", }, }); const request = new Drash.Request( req, new Map(), connInfo, ); let actual; actual = request.accepts("application/json"); assertEquals(actual, true); actual = request.accepts("text/html"); assertEquals(actual, true); }, ); await t.step( "rejects the single type if it is not present in the header", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", }, }); const request = new Drash.Request( req, new Map(), connInfo, ); const actual = request.accepts("text/xml"); assertEquals(actual, false); }, ); } async function getCookieTests(t: Deno.TestContext) { await t.step("Returns the cookie value if it exists", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", Cookie: "test_cookie=test_cookie_value", credentials: "include", }, }); const request = new Drash.Request( req, new Map(), connInfo, ); const cookieValue = request.getCookie("test_cookie"); assertEquals(cookieValue, "test_cookie_value"); }); await t.step("Returns undefined if the cookie does not exist", () => { const req = new Request("https://drash.land", { headers: { Accept: "application/json;text/html", Cookie: "test_cookie=test_cookie_value", credentials: "include", }, }); const request = new Drash.Request( req, new Map(), connInfo, ); const cookieValue = request.getCookie("cookie_doesnt_exist"); assertEquals(cookieValue, undefined); }); } async function bodyTests(t: Deno.TestContext) { await t.step("Can return multiple files", async () => { const formData = new FormData(); const file1 = new Blob([ new File([Deno.readFileSync("./mod.ts")], "mod.ts"), ], { type: "application/javascript", }); const file2 = new Blob([ new File([Deno.readFileSync("./mod.ts")], "mod.ts"), ], { type: "application/javascript", }); formData.append("foo[]", file1, "mod.ts"); formData.append("foo[]", file2, "mod2.ts"); const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", }, body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); // make sure that if a requets has multiple files, we can get each one eh <input type=file name=uploads[] /> const size = Deno.build.os === "windows" ? 1471 : 1433; const file = request.bodyParam<Drash.Types.BodyFile[]>("foo") ?? []; assertEquals(file[0].content, Deno.readFileSync("./mod.ts")); assertEquals(file[0].size, size); assertEquals(file[0].type, "application/javascript"); assertEquals(file[0].filename, "mod.ts"); assertEquals(file[1].content, Deno.readFileSync("./mod.ts")); assertEquals(file[1].size, size); assertEquals(file[1].type, "application/javascript"); assertEquals(file[1].filename, "mod2.ts"); }); // Reason: `this.request.getBodyParam()` didn't work for multipart/form-data requests await t.step("Returns the file object if the file exists", async () => { const formData = new FormData(); const file = new Blob([ new File([Deno.readFileSync("./logo.svg")], "logo.svg"), ], { type: "image/svg", }); formData.append("foo", file, "logo.svg"); const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", }, body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); // deno-lint-ignore no-explicit-any const bodyFile = request.bodyParam<Drash.Types.BodyFile>("foo") as any; assertEquals( bodyFile.content, Deno.readFileSync("./logo.svg"), ); assertEquals(bodyFile.type, "image/svg"); assertEquals(bodyFile.filename, "logo.svg"); assertEquals( bodyFile.size > 3000 && bodyFile.size < 3200, true, ); // Should be 3099, but on windows it 3119, so just do a basic check on size to avoid bloated test code }); await t.step( "Returns the value of a normal field for formdata requests", async () => { const formData = new FormData(); formData.append("user", "Drash"); const req = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", }, body: formData, method: "POST", }); const request = await Drash.Request.create( req, new Map(), connInfo, ); assertEquals(request.bodyParam("user"), "Drash"); }, ); await t.step("Returns undefined if the file does not exist", async () => { const formData = new FormData(); const file = new Blob([JSON.stringify({ hello: "world" }, null, 2)], { type: "application/json", }); formData.append("foo[]", file, "hello.json"); const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", }, body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); assertEquals(request.bodyParam("dontexist"), undefined); }); await t.step( "Returns the value for the parameter when the data exists for application/json", async () => { const req = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ hello: "world", }), method: "POST", }); const request = await Drash.Request.create( req, new Map(), connInfo, ); const actual = request.bodyParam("hello"); assertEquals("world", actual); }, ); await t.step( "Returns null when the data doesn't exist for application/json", async () => { const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ hello: "world", }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const actual = request.bodyParam("dont_exist"); assertEquals(undefined, actual); }, ); await t.step( "Should be consistent with falsey return values (null value returns null)", async () => { // This test case was added due to https://github.com/drashland/drash/issues/623 const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ foo: null, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const body = request.bodyAll() as { foo: null; }; assertEquals(body, { foo: null }); assertEquals(body["foo"], null); assertEquals(request.bodyParam("foo"), null); // As an edge case check, make sure bodyAll() returns the expected assertEquals( (request.bodyAll() as Partial<{ foo: unknown }>)["foo"], null, ); }, ); await t.step( "Should be consistent with falsey return values (false value returns false)", async () => { // This test case was added due to https://github.com/drashland/drash/issues/623 const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ foo: false, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const body = request.bodyAll() as Partial<{ foo: unknown; }>; assertEquals(body, { foo: false }); assertEquals(body["foo"], false); assertEquals(request.bodyParam("foo"), false); // As an edge case check, make sure bodyAll() returns the expected assertEquals( (request.bodyAll() as Partial<{ foo: unknown }>)["foo"], false, ); }, ); await t.step( "Should be consistent with falsey return values (undefined value returns undefined)", async () => { // This test case was added due to https://github.com/drashland/drash/issues/623 const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ foo: undefined, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const body = request.bodyAll() as Partial<{ foo: unknown; }>; assertEquals(body, {}); assertEquals(body["foo"], undefined); assertEquals(request.bodyParam("foo"), undefined); // As an edge case check, make sure bodyAll() returns the expected assertEquals( (request.bodyAll() as Partial<{ foo: unknown }>)["foo"], undefined, ); }, ); await t.step( "Should be consistent with falsey return values (no value returns undefined)", async () => { // This test case was added due to https://github.com/drashland/drash/issues/623 const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({}), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const body = request.bodyAll() as Partial<{ foo: unknown; }>; assertEquals(body, {}); assertEquals(body["foo"], undefined); assertEquals(request.bodyParam("foo"), undefined); // As an edge case check, make sure bodyAll() returns the expected assertEquals( (request.bodyAll() as Partial<{ foo: unknown }>)["foo"], undefined, ); }, ); await t.step( "Returns the value for the parameter when it exists and request is multipart/form-data when using generics", async () => { const formData = new FormData(); const file = new Blob([ new File([Deno.readFileSync("./logo.svg")], "logo.svg"), ], { type: "image/svg", }); formData.append("foo", file, "logo.svg"); formData.append("user", "drash"); const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", }, body: formData, method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const param = request.bodyParam<{ content: Uint8Array; filename: string; size: string; type: string; }>("foo"); assertEquals( param!.content, Deno.readFileSync("./logo.svg"), ); assertEquals(request.bodyParam("user"), "drash"); }, ); // Before the date of 5th, Oct 2020, type errors were thrown for objects because the return value of `getBodyParam` was either a string or null await t.step("Can handle when a body param is an object", async () => { const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ user: { name: "Edward", location: "UK", }, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const actual = request.bodyParam<{ name: string; location: string; }>("user")!; assertEquals({ name: "Edward", location: "UK", }, actual); const name = actual.name; // Ensuring we can access it and TS doesn't throw errors assertEquals(name, "Edward"); }); await t.step("Can handle when a body param is an array", async () => { const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ usernames: ["Edward", "John Smith", "Lord Voldemort", "Count Dankula"], }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const actual = request.bodyParam("usernames"); assertEquals( ["Edward", "John Smith", "Lord Voldemort", "Count Dankula"], actual, ); const firstName = (actual as Array<string>)[0]; assertEquals(firstName, "Edward"); }); await t.step("Can handle when a body param is a boolean", async () => { const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ authenticated: false, }), method: "POST", }); const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); const actual = request.bodyParam("authenticated"); assertEquals(actual, false); const authenticated = (actual as boolean); assertEquals(authenticated, false); }); } async function originalRequestTests(t: Deno.TestContext) { await t.step( "body is kept intact when Drash.Request body is parsed", async () => { const serverRequest = new Request("https://drash.land", { headers: { // We use `"Content-Length": "1"` to tell Drash.Request that there is // a request body. This is a hack just for unit testing. In the real // world, the Content-Length header will be defined (at least it // should be) by the client. "Content-Length": "1", "Content-Type": "application/json", }, body: JSON.stringify({ hello: "world", }), method: "POST", }); // When creating a Drash.Request object, the body is automatically parsed // and causes `Drash.Request.bodyUsed` to be `true` const request = await Drash.Request.create( serverRequest, new Map(), connInfo, ); // Check that the Drash.Request body has the `hello` param const hello = request.bodyParam("hello"); assertEquals(hello, "world"); // Check that the original request body was kept intact assertEquals(request.bodyUsed, true); assertEquals(request.original.bodyUsed, false); // Now read the original request body assertEquals(await request.original.json(), { hello: "world" }); }, ); } async function paramTests(t: Deno.TestContext) { await t.step( "Returns the value for the header param when it exists", () => { const serverRequest = new Request("https://drash.land"); const request = new Drash.Request( serverRequest, new Map().set("hello", "world"), connInfo, ); const actual = request.pathParam("hello"); assertEquals("world", actual); }, ); await t.step( "Returns null when the path param doesn't exist", () => { const serverRequest = new Request("https://drash.land"); const request = new Drash.Request( serverRequest, new Map().set("hello", "world"), connInfo, ); const actual = request.pathParam("dont-exist"); assertEquals(actual, undefined); }, ); } async function queryTests(t: Deno.TestContext) { await t.step( "Returns the value for the query param when it exists", () => { const serverRequest = new Request("https://drash.land/?hello=world"); const request = new Drash.Request( serverRequest, new Map(), connInfo, ); const actual = request.queryParam("hello"); assertEquals(actual, "world"); }, ); await t.step( "Returns null when the query data doesn't exist", () => { const serverRequest = new Request("https://drash.land/?hello=world"); const request = new Drash.Request( serverRequest, new Map(), connInfo, ); const actual = request.queryParam("dont_exist"); assertEquals(undefined, actual); }, ); }
the_stack
import { DndContext, DragOverlay, useDndContext, closestCorners, rectIntersection, closestCenter, useSensors, useSensor, PointerSensor, MouseSensor, } from '@dnd-kit/core'; import { observer, RecursionField } from '@formily/react'; import React, { useState } from 'react'; import { useContext } from 'react'; import { createContext } from 'react'; import { findPropertyByPath, getSchemaPath, useDesignable, useSchemaComponent, } from '../../components/schema-renderer'; import { Droppable, SortableItem } from '../../components/Sortable'; import { uid } from '@formily/shared'; import cls from 'classnames'; import './style.less'; import { FormilyISchema, ISchema } from '..'; import { DesignableBar } from './DesignableBar'; import { useClient } from '../../constate'; const GridRowContext = createContext<any>(null); const GridColContext = createContext<any>(null); export function isGridRowOrCol(schema: ISchema | FormilyISchema) { if (!schema) { return; } return ['Grid.Row', 'Grid.Col'].includes(schema?.['x-component']); } export const Grid: any = observer((props: any) => { const { designable, root, schema, refresh, deepRemove, deepRemoveIfEmpty, remove, ...methods } = useDesignable(); const [dragOverlayContent, setDragOverlayContent] = useState(''); const [style, setStyle] = useState({}); const [active, setActive] = useState(false); const [clientWidths, setClientWidths] = useState([0, 0]); const { addNewComponent } = props; const AddNewComponent = useSchemaComponent(addNewComponent); const { createSchema, removeSchema, updateSchema } = useClient(); // const sensors = useSensors(useSensor(MouseSensor)); const rows = Object.values(schema.properties || {}).filter((item) => { return !item['x-hidden']; }); const path = getSchemaPath(schema); return ( <div className={cls('nb-grid', { active })}> <DndContext // autoScroll // sensors={sensors} collisionDetection={rectIntersection} onDragStart={(event) => { setActive(true); const el = event?.active?.data?.current?.previewRef ?.current as HTMLElement; console.log(event, el); // setDragOverlayContent(el?.outerHTML); // setStyle({ width: el?.clientWidth, height: el?.clientHeight }); const activeType = event?.active?.data?.current?.type; if (activeType === 'col-resize') { setDragOverlayContent(''); const prev = el.previousElementSibling as HTMLDivElement; const next = el.nextElementSibling as HTMLDivElement; setClientWidths([prev.clientWidth, next.clientWidth]); } else { setDragOverlayContent('拖拽'); } }} onDragCancel={() => { setActive(false); }} onDragMove={(event) => { const activeType = event?.active?.data?.current?.type; const el = event?.active?.data?.current?.previewRef ?.current as HTMLElement; if (activeType === 'col-resize') { const prev = el.previousElementSibling as HTMLDivElement; const next = el.nextElementSibling as HTMLDivElement; prev.style.width = `calc(${clientWidths[0]}px + ${event.delta.x}px)`; next.style.width = `calc(${clientWidths[1]}px - ${event.delta.x}px)`; return; } }} onDragOver={(event) => { const activeType = event?.active?.data?.current?.type; console.log({ event }); if (activeType === 'col-resize') { return; } }} onDragEnd={async (event) => { setActive(false); const activeType = event?.active?.data?.current?.type; const sourcePath = event?.active?.data?.current?.path; const targetPath = event?.over?.data?.current?.path; const method = event?.over?.data?.current?.method; const type = event?.over?.data?.current?.type; console.log({ event, sourcePath, targetPath }); if (activeType === 'col-resize') { const parentPath = event?.active?.data?.current?.parentPath; const el = event?.active?.data?.current?.previewRef ?.current as HTMLElement; const els = el.parentElement.querySelectorAll( ':scope > .nb-grid-col', ); const size = []; const gap = el.clientWidth; els.forEach((el: HTMLDivElement) => { // const w = (100 * el.clientWidth) / el.parentElement.clientWidth; const w2 = (100 * (el.clientWidth + gap + gap / els.length)) / el.parentElement.clientWidth; size.push(w2); // el.style.width = `${w}%`; }); const parent = findPropertyByPath(root, parentPath); parent['x-component-props'] = parent['x-component-props'] || {}; parent['x-component-props']['colsize'] = size; await updateSchema({ key: parent['key'], 'x-component-props': { colsize: size, }, }); return; } if (!sourcePath || !targetPath) { return; } if (sourcePath === targetPath) { return; } let fn = methods[method]; if (!fn && type === 'block') { fn = methods.insertAfter; } console.log({ event, sourcePath, targetPath, method, type }); if (!fn) { return; } const sourceSchema = findPropertyByPath(root, sourcePath); if (!sourceSchema) { return; } if (!type) { return; } let data; if (['col-divider', 'col-resize'].includes(type)) { // if (sourceSchema?.parent?.['x-component'] === 'Grid.Col') { // // console.log('datadata', sourcePath, targetPath); // if ( // sourcePath.join('.').startsWith(targetPath.join('.')) && // Object.keys(sourceSchema?.parent?.properties).length < 2 // ) { // return; // } // } data = { type: 'void', 'x-component': 'Grid.Col', properties: { [sourceSchema.name]: sourceSchema.toJSON(), }, }; } else if (['block', 'col'].includes(type)) { data = sourceSchema.toJSON(); } else if (['row-divider', 'row'].includes(type)) { data = { type: 'void', 'x-component': 'Grid.Row', properties: { [uid()]: { type: 'void', 'x-component': 'Grid.Col', properties: { [sourceSchema.name]: sourceSchema.toJSON(), }, }, }, }; } if (data) { console.log('datadata', data, type, method); remove(sourcePath); const ppath = [...sourcePath]; ppath.pop(); const s = fn(data, targetPath); const removed = deepRemoveIfEmpty(ppath); const last = removed.pop(); if (['block', 'col'].includes(type)) { await updateSchema(s); } else { await createSchema(s); } if (isGridRowOrCol(last)) { await removeSchema(last); } } }} > <DragOverlay dropAnimation={{ duration: 20, easing: 'cubic-bezier(0.18, 0.67, 0.6, 1.22)', }} // dropAnimation={null} // style={{ whiteSpace: 'nowrap' }} style={{ width: 40, whiteSpace: 'nowrap', // ...style, // pointerEvents: 'none', }} > <div className={'nb-grid-drag-overlay'} style={{ ...style, }} dangerouslySetInnerHTML={{ __html: dragOverlayContent }} /> </DragOverlay> <Droppable id={`${schema.name}-row-divider`} className={'nb-grid-row-divider'} data={{ type: 'row-divider', method: 'prepend', path, }} /> {rows.map((property, index) => { return ( <> {index > 0 && ( <Droppable id={`${schema.name}-row-divider-${index}`} className={'nb-grid-row-divider'} data={{ type: 'row-divider', method: 'insertBefore', path: [...path, property.name], }} /> )} <RecursionField name={property.name} schema={property} /> </> ); })} <Droppable id={`${schema.name}-row-divider-last`} className={'nb-grid-row-divider'} data={{ type: 'row-divider', method: 'appendChild', path, }} /> </DndContext> {designable && AddNewComponent && <AddNewComponent />} </div> ); }); Grid.Row = observer((props: any) => { const { designable, schema } = useDesignable(); const columns = Object.values(schema.properties || {}).filter((item) => { return !item['x-hidden']; }); const columnCount = columns.length; const path = getSchemaPath(schema); let size = schema['x-component-props']?.['colsize'] || []; if (size?.length !== columnCount) { size = []; } return ( <GridRowContext.Provider value={{ columnCount }}> <Droppable id={schema.name} className={'nb-grid-row'} data={{ type: 'row', method: 'appendChild', path, }} > <Droppable id={`${schema.name}-first`} className={'nb-grid-col-divider'} data={{ type: 'col-divider', method: 'prepend', path: [...path], }} /> {columns.map((property, index) => { return ( <> {index > 0 && ( <SortableItem draggable id={`${schema.name}-${index}`} data={{ type: 'col-resize', method: 'insertBefore', parentPath: [...path], path: [...path, property.name], }} disabled={!designable} className={cls('nb-grid-col-divider', { resizable: designable, })} /> )} <GridColContext.Provider value={{ index, width: size[index] }}> <RecursionField name={property.name} schema={property} /> </GridColContext.Provider> </> ); })} <Droppable id={`${schema.name}-last`} className={'nb-grid-col-divider'} data={{ type: 'col-divider', method: 'appendChild', path: [...path], }} /> </Droppable> </GridRowContext.Provider> ); }); Grid.Col = observer((props: any) => { const { schema, designable, DesignableBar } = useDesignable(); // const { width } = props; const { columnCount } = useContext(GridRowContext); const { width } = useContext(GridColContext); return ( <Droppable id={schema.name} className={'nb-grid-col'} style={{ width: `calc(${ width || 100 / columnCount }% - 24px - 24px / ${columnCount})`, }} data={{ type: 'col', method: 'appendChild', path: getSchemaPath(schema), }} > {/* <Droppable id={`${schema.name}-divider`} className={'nb-grid-row-divider'} /> */} {props.children} {/* <Grid.Col.DesignableBar /> */} </Droppable> ); }); Grid.Col.DesignableBar = DesignableBar;
the_stack
import { Agile, CollectionPersistent, Collection, Storage, Persistent, StatePersistent, Group, Item, assignSharedStorageManager, createStorageManager, Storages, } from '../../../src'; import { LogMock } from '../../helper/logMock'; import waitForExpect from 'wait-for-expect'; describe('CollectionPersistent Tests', () => { interface ItemInterface { id: string; name: string; } let dummyAgile: Agile; let dummyCollection: Collection<ItemInterface>; let storageManager: Storages; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); dummyCollection = new Collection<ItemInterface>(dummyAgile, { key: 'dummyCollectionKey', }); // Register Storage Manager storageManager = createStorageManager(); assignSharedStorageManager(storageManager); jest.spyOn(CollectionPersistent.prototype, 'instantiatePersistent'); jest.spyOn(CollectionPersistent.prototype, 'initialLoading'); jest.clearAllMocks(); }); it('should create CollectionPersistent and should call initialLoading if Persistent is ready (default config)', () => { // Overwrite instantiatePersistent once to not call it jest .spyOn(CollectionPersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = true; }); const collectionPersistent = new CollectionPersistent(dummyCollection); expect(collectionPersistent).toBeInstanceOf(CollectionPersistent); expect(collectionPersistent.instantiatePersistent).toHaveBeenCalledWith({ key: undefined, storageKeys: [], defaultStorageKey: null, }); expect(collectionPersistent.initialLoading).toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(collectionPersistent._key).toBe(CollectionPersistent.placeHolderKey); expect(collectionPersistent.ready).toBeTruthy(); expect(collectionPersistent.isPersisted).toBeFalsy(); expect(collectionPersistent.onLoad).toBeUndefined(); expect(collectionPersistent.storageKeys).toStrictEqual([]); expect(collectionPersistent.config).toStrictEqual({ defaultStorageKey: null, // is assigned in 'instantiatePersistent' which is mocked }); }); it('should create CollectionPersistent and should call initialLoading if Persistent is ready (specific config)', () => { // Overwrite instantiatePersistent once to not call it and set ready property jest .spyOn(CollectionPersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = true; }); const collectionPersistent = new CollectionPersistent(dummyCollection, { key: 'collectionPersistentKey', storageKeys: ['test1', 'test2'], defaultStorageKey: 'test2', }); expect(collectionPersistent).toBeInstanceOf(CollectionPersistent); expect(collectionPersistent.instantiatePersistent).toHaveBeenCalledWith({ key: 'collectionPersistentKey', storageKeys: ['test1', 'test2'], defaultStorageKey: 'test2', }); expect(collectionPersistent.initialLoading).toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(collectionPersistent._key).toBe(CollectionPersistent.placeHolderKey); expect(collectionPersistent.ready).toBeTruthy(); expect(collectionPersistent.isPersisted).toBeFalsy(); expect(collectionPersistent.onLoad).toBeUndefined(); expect(collectionPersistent.storageKeys).toStrictEqual([]); expect(collectionPersistent.config).toStrictEqual({ defaultStorageKey: null, // is assigned in 'instantiatePersistent' which is mocked }); }); it("should create CollectionPersistent and shouldn't call initialLoading if Persistent isn't ready", () => { // Overwrite instantiatePersistent once to not call it and set ready property jest .spyOn(CollectionPersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = false; }); const collectionPersistent = new CollectionPersistent(dummyCollection); expect(collectionPersistent).toBeInstanceOf(CollectionPersistent); expect(collectionPersistent.collection()).toBe(dummyCollection); expect(collectionPersistent.instantiatePersistent).toHaveBeenCalledWith({ key: undefined, storageKeys: [], defaultStorageKey: null, }); expect(collectionPersistent.initialLoading).not.toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(collectionPersistent._key).toBe(CollectionPersistent.placeHolderKey); expect(collectionPersistent.ready).toBeFalsy(); expect(collectionPersistent.isPersisted).toBeFalsy(); expect(collectionPersistent.onLoad).toBeUndefined(); expect(collectionPersistent.storageKeys).toStrictEqual([]); expect(collectionPersistent.config).toStrictEqual({ defaultStorageKey: null, }); }); it("should create CollectionPersistent and shouldn't call initialLoading if Persistent is ready (config.loadValue = false)", () => { // Overwrite instantiatePersistent once to not call it and set ready property jest .spyOn(CollectionPersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = true; }); const collectionPersistent = new CollectionPersistent(dummyCollection, { loadValue: false, }); expect(collectionPersistent).toBeInstanceOf(CollectionPersistent); expect(collectionPersistent.collection()).toBe(dummyCollection); expect(collectionPersistent.instantiatePersistent).toHaveBeenCalledWith({ key: undefined, storageKeys: [], defaultStorageKey: null, }); expect(collectionPersistent.initialLoading).not.toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(collectionPersistent._key).toBe(CollectionPersistent.placeHolderKey); expect(collectionPersistent.ready).toBeTruthy(); expect(collectionPersistent.isPersisted).toBeFalsy(); expect(collectionPersistent.onLoad).toBeUndefined(); expect(collectionPersistent.storageKeys).toStrictEqual([]); expect(collectionPersistent.config).toStrictEqual({ defaultStorageKey: null, }); }); describe('CollectionPersistent Function Tests', () => { let collectionPersistent: CollectionPersistent<ItemInterface>; let dummyItem1: Item<ItemInterface>; let dummyItem2: Item<ItemInterface>; let dummyItem3: Item<ItemInterface>; let dummyItem4WithoutPersistent: Item<ItemInterface>; beforeEach(() => { collectionPersistent = new CollectionPersistent(dummyCollection, { key: 'collectionPersistentKey', storageKeys: ['dummyStorage'], }); storageManager.register( new Storage({ key: 'dummyStorage', methods: { get: jest.fn(), remove: jest.fn(), set: jest.fn(), }, }) ); dummyItem1 = new Item<ItemInterface>(dummyCollection, { id: '1', name: 'frank', }); dummyItem1.persist = jest.fn(); dummyItem1.persistent = new StatePersistent(dummyItem1); if (dummyItem1.persistent) { dummyItem1.persistent.ready = true; dummyItem1.persistent.initialLoading = jest.fn(); } dummyItem2 = new Item<ItemInterface>(dummyCollection, { id: '2', name: 'dieter', }); dummyItem2.persist = jest.fn(); dummyItem2.persistent = new StatePersistent(dummyItem2); if (dummyItem2.persistent) { dummyItem2.persistent.ready = true; dummyItem2.persistent.initialLoading = jest.fn(); } dummyItem3 = new Item<ItemInterface>(dummyCollection, { id: '3', name: 'hans', }); dummyItem3.persist = jest.fn(); dummyItem3.persistent = new StatePersistent(dummyItem3); if (dummyItem3.persistent) { dummyItem3.persistent.ready = true; dummyItem3.persistent.initialLoading = jest.fn(); } dummyItem4WithoutPersistent = new Item<ItemInterface>(dummyCollection, { id: '4', name: 'jeff', }); }); describe('initialLoading function tests', () => { beforeEach(() => { jest.spyOn(Persistent.prototype, 'initialLoading'); }); it('should call initialLoad in parent and set Collection.isPersisted to true', async () => { await collectionPersistent.initialLoading(); await waitForExpect(() => { expect(Persistent.prototype.initialLoading).toHaveBeenCalled(); expect(dummyCollection.isPersisted).toBeTruthy(); }); }); }); describe('loadPersistedValue function tests', () => { let dummyDefaultGroup: Group<ItemInterface>; let placeholderItem1: Item<ItemInterface>; let placeholderItem2: Item<ItemInterface>; let placeholderItem3: Item<ItemInterface>; beforeEach(() => { collectionPersistent.config.defaultStorageKey = 'test'; placeholderItem1 = dummyCollection.createPlaceholderItem('1'); placeholderItem1.persist = jest.fn(); placeholderItem2 = dummyCollection.createPlaceholderItem('2'); placeholderItem2.persist = jest.fn(); placeholderItem3 = dummyCollection.createPlaceholderItem('3'); placeholderItem3.persist = jest.fn(); dummyDefaultGroup = new Group(dummyCollection, ['1', '2', '3'], { key: 'default', }); dummyDefaultGroup.persist = jest.fn(); dummyDefaultGroup.persistent = new StatePersistent(dummyDefaultGroup); if (dummyDefaultGroup.persistent) { dummyDefaultGroup.persistent.ready = true; dummyDefaultGroup.persistent.initialLoading = jest.fn(); } collectionPersistent.setupSideEffects = jest.fn(); dummyCollection.getDefaultGroup = jest.fn( () => dummyDefaultGroup as any ); dummyCollection.assignItem = jest.fn(); storageManager.get = jest.fn(); }); it( 'should load default Group and apply persisted value to Items ' + 'that are already present in the Collection (persistentKey)', async () => { collectionPersistent.ready = true; dummyCollection.data = { ['3']: dummyItem3, }; storageManager.get = jest .fn() .mockReturnValueOnce(Promise.resolve(true)); dummyDefaultGroup._value = ['3']; const response = await collectionPersistent.loadPersistedValue(); expect(response).toBeTruthy(); expect(storageManager.get).toHaveBeenCalledWith( collectionPersistent._key, collectionPersistent.config.defaultStorageKey ); // Default Group expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, collectionPersistent._key ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( dummyDefaultGroup.persistent?.initialLoading ).toHaveBeenCalledTimes(1); // Dummy Item 3 expect(dummyItem3.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( '3', collectionPersistent._key ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(dummyItem3.persistent?.initialLoading).toHaveBeenCalledTimes( 1 ); expect(collectionPersistent.setupSideEffects).toHaveBeenCalledWith( collectionPersistent._key ); } ); it( 'should load default Group and create/add persisted Items ' + "that aren't present in the Collection yet (persistentKey)", async () => { collectionPersistent.ready = true; dummyCollection.data = {}; dummyCollection.size = 0; storageManager.get = jest .fn() .mockReturnValueOnce(Promise.resolve(true)); placeholderItem1.persist = jest.fn(function () { placeholderItem1.persistent = new StatePersistent(placeholderItem1); placeholderItem1.persistent.ready = true; placeholderItem1.persistent.loadPersistedValue = jest .fn() .mockReturnValueOnce(true); return null as any; }); placeholderItem2.persist = jest.fn(function () { placeholderItem2.persistent = new StatePersistent(placeholderItem2); placeholderItem2.persistent.ready = false; placeholderItem2.persistent.loadPersistedValue = jest.fn(); return null as any; }); placeholderItem3.persist = jest.fn(function () { placeholderItem3.persistent = new StatePersistent(placeholderItem3); placeholderItem3.persistent.ready = true; placeholderItem3.persistent.loadPersistedValue = jest .fn() .mockReturnValueOnce(false); return null as any; }); dummyCollection.getItemWithReference = jest .fn() .mockReturnValueOnce(placeholderItem1) .mockReturnValueOnce(placeholderItem2) .mockReturnValueOnce(placeholderItem3); dummyDefaultGroup._value = ['1', '2', '3']; const response = await collectionPersistent.loadPersistedValue(); expect(response).toBeTruthy(); expect(storageManager.get).toHaveBeenCalledWith( collectionPersistent._key, collectionPersistent.config.defaultStorageKey ); expect(dummyCollection.size).toBe(1); // Because only placeholder Item 1 was added // Default Group expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, collectionPersistent._key ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( dummyDefaultGroup.persistent?.initialLoading ).toHaveBeenCalledTimes(1); // Placeholder Item 1 expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith( '1' ); expect(placeholderItem1.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( '1', collectionPersistent._key ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( placeholderItem1?.persistent?.loadPersistedValue ).toHaveBeenCalledTimes(1); expect(dummyCollection.assignItem).toHaveBeenCalledWith( placeholderItem1, { overwrite: true, rebuildGroups: false, } ); expect(placeholderItem1.isPersisted).toBeTruthy(); // Placeholder Item 2 expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith( '2' ); expect(placeholderItem2.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( '2', collectionPersistent._key ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( placeholderItem2?.persistent?.loadPersistedValue ).not.toHaveBeenCalled(); expect(dummyCollection.assignItem).not.toHaveBeenCalledWith( placeholderItem2, { overwrite: true, rebuildGroups: false, } ); // Because Item persistent isn't ready expect(placeholderItem2.isPersisted).toBeFalsy(); // Placeholder Item 3 expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith( '3' ); expect(placeholderItem3.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( '3', collectionPersistent._key ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( placeholderItem3?.persistent?.loadPersistedValue ).toHaveBeenCalledTimes(1); expect(dummyCollection.assignItem).not.toHaveBeenCalledWith( placeholderItem3, { overwrite: true, rebuildGroups: false, } ); // Because Item persistent 'leadPersistedValue()' returned false -> Item properly doesn't exist in Storage expect(placeholderItem3.isPersisted).toBeFalsy(); expect(collectionPersistent.setupSideEffects).toHaveBeenCalledWith( collectionPersistent._key ); } ); it( 'should load default Group, ' + "create/add persisted Items that aren't present in the Collection yet " + 'and apply persisted value to Items that are already present in the Collection (specific key)', async () => { collectionPersistent.ready = true; dummyCollection.data = { ['3']: dummyItem3, }; dummyCollection.size = 1; storageManager.get = jest .fn() .mockReturnValueOnce(Promise.resolve(true)); placeholderItem1.persist = jest.fn(function () { placeholderItem1.persistent = new StatePersistent(placeholderItem1); placeholderItem1.persistent.ready = true; placeholderItem1.persistent.loadPersistedValue = jest .fn() .mockReturnValueOnce(true); return null as any; }); dummyCollection.getItemWithReference = jest .fn() .mockReturnValueOnce(placeholderItem1); dummyDefaultGroup._value = ['1', '3']; const response = await collectionPersistent.loadPersistedValue( 'dummyKey' ); expect(response).toBeTruthy(); expect(storageManager.get).toHaveBeenCalledWith( 'dummyKey', collectionPersistent.config.defaultStorageKey ); expect(dummyCollection.size).toBe(2); // Because only placeholder Item 1 was added // Default Group expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, 'dummyKey' ), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( dummyDefaultGroup.persistent?.initialLoading ).toHaveBeenCalledTimes(1); // Dummy Item 3 expect(dummyItem3.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey('3', 'dummyKey'), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(dummyItem3.persistent?.initialLoading).toHaveBeenCalledTimes( 1 ); expect(dummyCollection.getItemWithReference).not.toHaveBeenCalledWith( '3' ); // Because Item 3 is already present in the Collection expect(dummyCollection.assignItem).not.toHaveBeenCalledWith( placeholderItem3, { overwrite: true, rebuildGroups: false, } ); // Because Item 3 is already present in the Collection // Placeholder Item 1 expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith( '1' ); expect(placeholderItem1.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey('1', 'dummyKey'), loadValue: false, defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( placeholderItem1?.persistent?.loadPersistedValue ).toHaveBeenCalledTimes(1); expect(dummyCollection.assignItem).toHaveBeenCalledWith( placeholderItem1, { overwrite: true, rebuildGroups: false, } ); expect(placeholderItem1.isPersisted).toBeTruthy(); expect(collectionPersistent.setupSideEffects).toHaveBeenCalledWith( 'dummyKey' ); } ); it("shouldn't load default Group and its Items if Collection flag isn't persisted", async () => { collectionPersistent.ready = true; storageManager.get = jest .fn() .mockReturnValueOnce(Promise.resolve(undefined)); const response = await collectionPersistent.loadPersistedValue(); expect(response).toBeFalsy(); expect(storageManager.get).toHaveBeenCalledWith( collectionPersistent._key, collectionPersistent.config.defaultStorageKey ); expect(dummyCollection.getDefaultGroup).not.toHaveBeenCalled(); expect(dummyDefaultGroup.persist).not.toHaveBeenCalled(); expect(placeholderItem1.persist).not.toHaveBeenCalled(); expect(placeholderItem2.persist).not.toHaveBeenCalled(); expect(placeholderItem3.persist).not.toHaveBeenCalled(); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem2.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(collectionPersistent.setupSideEffects).not.toHaveBeenCalled(); }); it("shouldn't load default Group and its Items if Persistent isn't ready", async () => { collectionPersistent.ready = false; const response = await collectionPersistent.loadPersistedValue(); expect(response).toBeFalsy(); expect(storageManager.get).not.toHaveBeenCalled(); expect(dummyCollection.getDefaultGroup).not.toHaveBeenCalled(); expect(dummyDefaultGroup.persist).not.toHaveBeenCalled(); expect(placeholderItem1.persist).not.toHaveBeenCalled(); expect(placeholderItem2.persist).not.toHaveBeenCalled(); expect(placeholderItem3.persist).not.toHaveBeenCalled(); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem2.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(collectionPersistent.setupSideEffects).not.toHaveBeenCalled(); }); it("shouldn't load default Group and its Items if Collection has no defaultGroup", async () => { collectionPersistent.ready = true; storageManager.get = jest .fn() .mockReturnValueOnce(Promise.resolve(true)); dummyCollection.getDefaultGroup = jest.fn(() => undefined); const response = await collectionPersistent.loadPersistedValue(); expect(response).toBeFalsy(); expect(storageManager.get).toHaveBeenCalledWith( collectionPersistent._key, collectionPersistent.config.defaultStorageKey ); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).not.toHaveBeenCalled(); expect(placeholderItem1.persist).not.toHaveBeenCalled(); expect(placeholderItem2.persist).not.toHaveBeenCalled(); expect(placeholderItem3.persist).not.toHaveBeenCalled(); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem2.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(collectionPersistent.setupSideEffects).not.toHaveBeenCalled(); }); }); describe('persistValue function tests', () => { let dummyDefaultGroup: Group<ItemInterface>; beforeEach(() => { collectionPersistent.storageKeys = ['test1', 'test2']; collectionPersistent.isPersisted = undefined as any; dummyCollection.data = { ['1']: dummyItem1, ['3']: dummyItem3, }; dummyDefaultGroup = new Group(dummyCollection, ['1', '2', '3'], { key: 'default', }); dummyDefaultGroup.persist = jest.fn(); dummyItem1.persist = jest.fn(); dummyItem3.persist = jest.fn(); collectionPersistent.setupSideEffects = jest.fn(); dummyCollection.getDefaultGroup = jest.fn( () => dummyDefaultGroup as any ); storageManager.set = jest.fn(); }); it('should persist default Group and its Items (persistentKey)', async () => { collectionPersistent.ready = true; const response = await collectionPersistent.persistValue(); expect(response).toBeTruthy(); expect(storageManager.set).toHaveBeenCalledWith( collectionPersistent._key, true, collectionPersistent.storageKeys ); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, collectionPersistent._key ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(dummyItem1.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( dummyItem1._key, collectionPersistent._key ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(dummyItem3.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( dummyItem3._key, collectionPersistent._key ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(collectionPersistent.setupSideEffects).toHaveBeenCalled(); expect(collectionPersistent.isPersisted).toBeTruthy(); }); it('should persist default Group and its Items (specific key)', async () => { collectionPersistent.ready = true; const response = await collectionPersistent.persistValue('dummyKey'); expect(response).toBeTruthy(); expect(storageManager.set).toHaveBeenCalledWith( 'dummyKey', true, collectionPersistent.storageKeys ); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, 'dummyKey' ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(dummyItem1.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( dummyItem1._key, 'dummyKey' ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(dummyItem3.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( dummyItem3._key, 'dummyKey' ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect(collectionPersistent.setupSideEffects).toHaveBeenCalled(); expect(collectionPersistent.isPersisted).toBeTruthy(); }); it("shouldn't persist default Group and its Items if Persistent isn't ready", async () => { collectionPersistent.ready = false; const response = await collectionPersistent.persistValue('dummyKey'); expect(response).toBeFalsy(); expect(storageManager.set).not.toHaveBeenCalled(); expect(dummyCollection.getDefaultGroup).not.toHaveBeenCalled(); expect(dummyDefaultGroup.persist).not.toHaveBeenCalled(); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(collectionPersistent.setupSideEffects).not.toHaveBeenCalled(); expect(collectionPersistent.isPersisted).toBeUndefined(); }); it("shouldn't persist default Group and its Items if Collection has no default Group", async () => { collectionPersistent.ready = true; dummyCollection.getDefaultGroup = jest.fn(() => undefined as any); const response = await collectionPersistent.persistValue(); expect(response).toBeFalsy(); expect(storageManager.set).not.toHaveBeenCalled(); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect(dummyDefaultGroup.persist).not.toHaveBeenCalled(); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(collectionPersistent.setupSideEffects).not.toHaveBeenCalled(); expect(collectionPersistent.isPersisted).toBeUndefined(); }); }); describe('setupSideEffects function tests', () => { let dummyDefaultGroup: Group<ItemInterface>; beforeEach(() => { dummyDefaultGroup = new Group(dummyCollection, ['1', '2', '3'], { key: 'default', }); jest.spyOn(dummyDefaultGroup, 'addSideEffect'); collectionPersistent.rebuildStorageSideEffect = jest.fn(); dummyCollection.getDefaultGroup = jest.fn( () => dummyDefaultGroup as any ); }); it("shouldn't add rebuild Storage side effect to the default Group", () => { collectionPersistent.setupSideEffects(); expect( dummyDefaultGroup.addSideEffect ).toHaveBeenCalledWith( CollectionPersistent.defaultGroupSideEffectKey, expect.any(Function), { weight: 0 } ); }); it("shouldn't add rebuild Storage side effect to the default Group if the Collection has no default Group", () => { dummyCollection.getDefaultGroup = jest.fn(() => undefined as any); collectionPersistent.setupSideEffects(); expect(dummyDefaultGroup.addSideEffect).not.toHaveBeenCalled(); }); describe("test added sideEffect called 'CollectionPersistent.defaultGroupSideEffectKey'", () => { beforeEach(() => { collectionPersistent.rebuildStorageSideEffect = jest.fn(); dummyCollection.getDefaultGroup = jest.fn( () => dummyDefaultGroup as any ); }); it('should call rebuildStorageSideEffect (persistentKey)', async () => { await collectionPersistent.setupSideEffects(); dummyDefaultGroup.sideEffects[ CollectionPersistent.defaultGroupSideEffectKey ].callback(dummyDefaultGroup); expect( collectionPersistent.rebuildStorageSideEffect ).toHaveBeenCalledWith(dummyDefaultGroup, collectionPersistent._key); }); it('should call rebuildStorageSideEffect (specified key)', async () => { await collectionPersistent.setupSideEffects('dummyKey'); dummyDefaultGroup.sideEffects[ CollectionPersistent.defaultGroupSideEffectKey ].callback(dummyDefaultGroup); expect( collectionPersistent.rebuildStorageSideEffect ).toHaveBeenCalledWith(dummyDefaultGroup, 'dummyKey'); }); }); }); describe('removePersistedValue function tests', () => { let dummyDefaultGroup: Group<ItemInterface>; beforeEach(() => { collectionPersistent.storageKeys = ['test1', 'test2']; collectionPersistent.isPersisted = undefined as any; dummyCollection.data = { ['1']: dummyItem1, ['3']: dummyItem3, }; dummyDefaultGroup = new Group(dummyCollection, ['1', '2', '3']); dummyDefaultGroup.persistent = new StatePersistent(dummyDefaultGroup); dummyDefaultGroup.removeSideEffect = jest.fn(); if (dummyDefaultGroup.persistent) dummyDefaultGroup.persistent.removePersistedValue = jest.fn(); dummyCollection.getDefaultGroup = jest.fn( () => dummyDefaultGroup as any ); if (dummyItem1.persistent) dummyItem1.persistent.removePersistedValue = jest.fn(); if (dummyItem3.persistent) dummyItem3.persistent.removePersistedValue = jest.fn(); storageManager.remove = jest.fn(); }); it('should remove persisted default Group and its Items from Storage (persistentKey)', async () => { collectionPersistent.ready = true; const response = await collectionPersistent.removePersistedValue(); expect(response).toBeTruthy(); expect(storageManager.remove).toHaveBeenCalledWith( collectionPersistent._key, collectionPersistent.storageKeys ); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect( dummyDefaultGroup.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, collectionPersistent._key ) ); expect(dummyDefaultGroup.removeSideEffect).toHaveBeenCalledWith( CollectionPersistent.defaultGroupSideEffectKey ); expect( dummyItem1.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getItemStorageKey( dummyItem1._key, collectionPersistent._key ) ); expect( dummyItem3.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getItemStorageKey( dummyItem3._key, collectionPersistent._key ) ); expect(collectionPersistent.isPersisted).toBeFalsy(); }); it('should remove persisted default Group and its Items from Storage (specific key)', async () => { collectionPersistent.ready = true; const response = await collectionPersistent.removePersistedValue( 'dummyKey' ); expect(response).toBeTruthy(); expect(storageManager.remove).toHaveBeenCalledWith( 'dummyKey', collectionPersistent.storageKeys ); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect( dummyDefaultGroup.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getGroupStorageKey( dummyDefaultGroup._key, 'dummyKey' ) ); expect(dummyDefaultGroup.removeSideEffect).toHaveBeenCalledWith( CollectionPersistent.defaultGroupSideEffectKey ); expect( dummyItem1.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getItemStorageKey(dummyItem1._key, 'dummyKey') ); expect( dummyItem3.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getItemStorageKey(dummyItem3._key, 'dummyKey') ); expect(collectionPersistent.isPersisted).toBeFalsy(); }); it("shouldn't remove persisted default Group and its Items from Storage if Persistent isn't ready", async () => { collectionPersistent.ready = false; const response = await collectionPersistent.removePersistedValue(); expect(response).toBeFalsy(); expect(storageManager.remove).not.toHaveBeenCalled(); expect(dummyCollection.getDefaultGroup).not.toHaveBeenCalled(); expect( dummyDefaultGroup.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect(dummyDefaultGroup.removeSideEffect).not.toHaveBeenCalled(); expect( dummyItem1.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem3.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect(collectionPersistent.isPersisted).toBeUndefined(); }); it("shouldn't remove persisted default Group and its Items from Storage if Collection has no default Group", async () => { collectionPersistent.ready = true; dummyCollection.getDefaultGroup = jest.fn(() => undefined as any); const response = await collectionPersistent.removePersistedValue(); expect(response).toBeFalsy(); expect(storageManager.remove).not.toHaveBeenCalled(); expect(dummyCollection.getDefaultGroup).toHaveBeenCalled(); expect( dummyDefaultGroup.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect(dummyDefaultGroup.removeSideEffect).not.toHaveBeenCalled(); expect( dummyItem1.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem3.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect(collectionPersistent.isPersisted).toBeUndefined(); }); }); describe('formatKey function tests', () => { it('should return key of the Collection if no valid key was specified', () => { dummyCollection._key = 'coolKey'; const response = collectionPersistent.formatKey(undefined); expect(response).toBe('coolKey'); }); it('should return specified key', () => { dummyCollection._key = 'coolKey'; const response = collectionPersistent.formatKey('awesomeKey'); expect(response).toBe('awesomeKey'); }); it('should return and apply specified key to Collection if Collection had no own valid key before', () => { dummyCollection._key = undefined; const response = collectionPersistent.formatKey('awesomeKey'); expect(response).toBe('awesomeKey'); expect(dummyCollection._key).toBe('awesomeKey'); }); it('should return undefined if no valid key was specified and Collection has no valid key either', () => { dummyCollection._key = undefined; const response = collectionPersistent.formatKey(undefined); expect(response).toBeUndefined(); }); }); describe('rebuildStorageSideEffects function tests', () => { let dummyGroup: Group<ItemInterface>; beforeEach(() => { dummyGroup = new Group(dummyCollection); dummyCollection.data = { ['1']: dummyItem1, ['2']: dummyItem2, ['3']: dummyItem3, ['4']: dummyItem4WithoutPersistent, }; dummyCollection.persistent = collectionPersistent; dummyItem1.persist = jest.fn(); dummyItem2.persist = jest.fn(); dummyItem3.persist = jest.fn(); dummyItem4WithoutPersistent.persist = jest.fn(); if (dummyItem1.persistent) dummyItem1.persistent.removePersistedValue = jest.fn(); if (dummyItem2.persistent) dummyItem2.persistent.removePersistedValue = jest.fn(); if (dummyItem3.persistent) dummyItem3.persistent.removePersistedValue = jest.fn(); }); it('should return if no Item got added or removed', () => { dummyGroup.previousStateValue = ['1', '2', '3']; dummyGroup._value = ['1', '2', '3']; collectionPersistent.rebuildStorageSideEffect(dummyGroup); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem2.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(dummyItem4WithoutPersistent.persist).not.toHaveBeenCalled(); expect( dummyItem1.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem2.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem3.persistent?.removePersistedValue ).not.toHaveBeenCalled(); }); it('should call removePersistedValue() on Items that got removed from Group', () => { dummyGroup.previousStateValue = ['1', '2', '3']; dummyGroup._value = ['2']; collectionPersistent.rebuildStorageSideEffect(dummyGroup); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem2.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(dummyItem4WithoutPersistent.persist).not.toHaveBeenCalled(); expect( dummyItem1.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getItemStorageKey('1', collectionPersistent._key) ); expect( dummyItem2.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem3.persistent?.removePersistedValue ).toHaveBeenCalledWith( CollectionPersistent.getItemStorageKey('3', collectionPersistent._key) ); }); it("should call persist on Items that got added to Group and hasn't been persisted yet", () => { dummyGroup.previousStateValue = ['1']; dummyGroup._value = ['1', '4', '3']; collectionPersistent.rebuildStorageSideEffect(dummyGroup); expect(dummyItem1.persist).not.toHaveBeenCalled(); expect(dummyItem2.persist).not.toHaveBeenCalled(); expect(dummyItem3.persist).not.toHaveBeenCalled(); expect(dummyItem4WithoutPersistent.persist).toHaveBeenCalledWith({ key: CollectionPersistent.getItemStorageKey( '4', collectionPersistent._key ), defaultStorageKey: collectionPersistent.config.defaultStorageKey, storageKeys: collectionPersistent.storageKeys, followCollectionPersistKeyPattern: false, }); expect( dummyItem1.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem2.persistent?.removePersistedValue ).not.toHaveBeenCalled(); expect( dummyItem3.persistent?.removePersistedValue ).not.toHaveBeenCalled(); }); }); describe('getItemStorageKey function tests', () => { it('should build ItemStorageKey based on itemKey and collectionKey', () => { const response = CollectionPersistent.getItemStorageKey( 'itemKey', 'collectionKey' ); expect(response).toBe('_collectionKey_item_itemKey'); LogMock.hasNotLogged('warn'); }); it('should build ItemStorageKey based on only collectionKey with warning', () => { const response = CollectionPersistent.getItemStorageKey( undefined, 'collectionKey' ); expect(response).toBe('_collectionKey_item_unknown'); LogMock.hasLoggedCode('1A:02:00'); }); it('should build ItemStorageKey based on only itemKey with warning', () => { const response = CollectionPersistent.getItemStorageKey( 'itemKey', undefined ); expect(response).toBe('_unknown_item_itemKey'); LogMock.hasLoggedCode('1A:02:00'); }); it('should build ItemStorageKey based on nothing with warning', () => { const response = CollectionPersistent.getItemStorageKey( undefined, undefined ); expect(response).toBe('_unknown_item_unknown'); LogMock.hasLoggedCode('1A:02:00'); }); }); describe('getGroupStorageKey function tests', () => { it('should build GroupStorageKey based on groupKey and collectionKey', () => { const response = CollectionPersistent.getGroupStorageKey( 'groupKey', 'collectionKey' ); expect(response).toBe('_collectionKey_group_groupKey'); LogMock.hasNotLogged('warn'); }); it('should build GroupStorageKey based on only collectionKey with warning', () => { const response = CollectionPersistent.getGroupStorageKey( undefined, 'collectionKey' ); expect(response).toBe('_collectionKey_group_unknown'); LogMock.hasLoggedCode('1A:02:01'); }); it('should build GroupStorageKey based on only groupKey with warning', () => { const response = CollectionPersistent.getGroupStorageKey( 'groupKey', undefined ); expect(response).toBe('_unknown_group_groupKey'); LogMock.hasLoggedCode('1A:02:01'); }); it('should build GroupStorageKey based on nothing with warning', () => { const response = CollectionPersistent.getGroupStorageKey( undefined, undefined ); expect(response).toBe('_unknown_group_unknown'); LogMock.hasLoggedCode('1A:02:01'); }); }); }); });
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class RUM extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: RUM.Types.ClientConfiguration) config: Config & RUM.Types.ClientConfiguration; /** * Creates a Amazon CloudWatch RUM app monitor, which collects telemetry data from your application and sends that data to RUM. The data includes performance and reliability information such as page load time, client-side errors, and user behavior. You use this operation only to create a new app monitor. To update an existing app monitor, use UpdateAppMonitor instead. After you create an app monitor, sign in to the CloudWatch RUM console to get the JavaScript code snippet to add to your web application. For more information, see How do I find a code snippet that I've already generated? */ createAppMonitor(params: RUM.Types.CreateAppMonitorRequest, callback?: (err: AWSError, data: RUM.Types.CreateAppMonitorResponse) => void): Request<RUM.Types.CreateAppMonitorResponse, AWSError>; /** * Creates a Amazon CloudWatch RUM app monitor, which collects telemetry data from your application and sends that data to RUM. The data includes performance and reliability information such as page load time, client-side errors, and user behavior. You use this operation only to create a new app monitor. To update an existing app monitor, use UpdateAppMonitor instead. After you create an app monitor, sign in to the CloudWatch RUM console to get the JavaScript code snippet to add to your web application. For more information, see How do I find a code snippet that I've already generated? */ createAppMonitor(callback?: (err: AWSError, data: RUM.Types.CreateAppMonitorResponse) => void): Request<RUM.Types.CreateAppMonitorResponse, AWSError>; /** * Deletes an existing app monitor. This immediately stops the collection of data. */ deleteAppMonitor(params: RUM.Types.DeleteAppMonitorRequest, callback?: (err: AWSError, data: RUM.Types.DeleteAppMonitorResponse) => void): Request<RUM.Types.DeleteAppMonitorResponse, AWSError>; /** * Deletes an existing app monitor. This immediately stops the collection of data. */ deleteAppMonitor(callback?: (err: AWSError, data: RUM.Types.DeleteAppMonitorResponse) => void): Request<RUM.Types.DeleteAppMonitorResponse, AWSError>; /** * Retrieves the complete configuration information for one app monitor. */ getAppMonitor(params: RUM.Types.GetAppMonitorRequest, callback?: (err: AWSError, data: RUM.Types.GetAppMonitorResponse) => void): Request<RUM.Types.GetAppMonitorResponse, AWSError>; /** * Retrieves the complete configuration information for one app monitor. */ getAppMonitor(callback?: (err: AWSError, data: RUM.Types.GetAppMonitorResponse) => void): Request<RUM.Types.GetAppMonitorResponse, AWSError>; /** * Retrieves the raw performance events that RUM has collected from your web application, so that you can do your own processing or analysis of this data. */ getAppMonitorData(params: RUM.Types.GetAppMonitorDataRequest, callback?: (err: AWSError, data: RUM.Types.GetAppMonitorDataResponse) => void): Request<RUM.Types.GetAppMonitorDataResponse, AWSError>; /** * Retrieves the raw performance events that RUM has collected from your web application, so that you can do your own processing or analysis of this data. */ getAppMonitorData(callback?: (err: AWSError, data: RUM.Types.GetAppMonitorDataResponse) => void): Request<RUM.Types.GetAppMonitorDataResponse, AWSError>; /** * Returns a list of the Amazon CloudWatch RUM app monitors in the account. */ listAppMonitors(params: RUM.Types.ListAppMonitorsRequest, callback?: (err: AWSError, data: RUM.Types.ListAppMonitorsResponse) => void): Request<RUM.Types.ListAppMonitorsResponse, AWSError>; /** * Returns a list of the Amazon CloudWatch RUM app monitors in the account. */ listAppMonitors(callback?: (err: AWSError, data: RUM.Types.ListAppMonitorsResponse) => void): Request<RUM.Types.ListAppMonitorsResponse, AWSError>; /** * Displays the tags associated with a CloudWatch RUM resource. */ listTagsForResource(params: RUM.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: RUM.Types.ListTagsForResourceResponse) => void): Request<RUM.Types.ListTagsForResourceResponse, AWSError>; /** * Displays the tags associated with a CloudWatch RUM resource. */ listTagsForResource(callback?: (err: AWSError, data: RUM.Types.ListTagsForResourceResponse) => void): Request<RUM.Types.ListTagsForResourceResponse, AWSError>; /** * Sends telemetry events about your application performance and user behavior to CloudWatch RUM. The code snippet that RUM generates for you to add to your application includes PutRumEvents operations to send this data to RUM. Each PutRumEvents operation can send a batch of events from one user session. */ putRumEvents(params: RUM.Types.PutRumEventsRequest, callback?: (err: AWSError, data: RUM.Types.PutRumEventsResponse) => void): Request<RUM.Types.PutRumEventsResponse, AWSError>; /** * Sends telemetry events about your application performance and user behavior to CloudWatch RUM. The code snippet that RUM generates for you to add to your application includes PutRumEvents operations to send this data to RUM. Each PutRumEvents operation can send a batch of events from one user session. */ putRumEvents(callback?: (err: AWSError, data: RUM.Types.PutRumEventsResponse) => void): Request<RUM.Types.PutRumEventsResponse, AWSError>; /** * Assigns one or more tags (key-value pairs) to the specified CloudWatch RUM resource. Currently, the only resources that can be tagged app monitors. Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values. Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of characters. You can use the TagResource action with a resource that already has tags. If you specify a new tag key for the resource, this tag is appended to the list of tags associated with the alarm. If you specify a tag key that is already associated with the resource, the new tag value that you specify replaces the previous value for that tag. You can associate as many as 50 tags with a resource. For more information, see Tagging Amazon Web Services resources. */ tagResource(params: RUM.Types.TagResourceRequest, callback?: (err: AWSError, data: RUM.Types.TagResourceResponse) => void): Request<RUM.Types.TagResourceResponse, AWSError>; /** * Assigns one or more tags (key-value pairs) to the specified CloudWatch RUM resource. Currently, the only resources that can be tagged app monitors. Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values. Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of characters. You can use the TagResource action with a resource that already has tags. If you specify a new tag key for the resource, this tag is appended to the list of tags associated with the alarm. If you specify a tag key that is already associated with the resource, the new tag value that you specify replaces the previous value for that tag. You can associate as many as 50 tags with a resource. For more information, see Tagging Amazon Web Services resources. */ tagResource(callback?: (err: AWSError, data: RUM.Types.TagResourceResponse) => void): Request<RUM.Types.TagResourceResponse, AWSError>; /** * Removes one or more tags from the specified resource. */ untagResource(params: RUM.Types.UntagResourceRequest, callback?: (err: AWSError, data: RUM.Types.UntagResourceResponse) => void): Request<RUM.Types.UntagResourceResponse, AWSError>; /** * Removes one or more tags from the specified resource. */ untagResource(callback?: (err: AWSError, data: RUM.Types.UntagResourceResponse) => void): Request<RUM.Types.UntagResourceResponse, AWSError>; /** * Updates the configuration of an existing app monitor. When you use this operation, only the parts of the app monitor configuration that you specify in this operation are changed. For any parameters that you omit, the existing values are kept. You can't use this operation to change the tags of an existing app monitor. To change the tags of an existing app monitor, use TagResource. To create a new app monitor, use CreateAppMonitor. After you update an app monitor, sign in to the CloudWatch RUM console to get the updated JavaScript code snippet to add to your web application. For more information, see How do I find a code snippet that I've already generated? */ updateAppMonitor(params: RUM.Types.UpdateAppMonitorRequest, callback?: (err: AWSError, data: RUM.Types.UpdateAppMonitorResponse) => void): Request<RUM.Types.UpdateAppMonitorResponse, AWSError>; /** * Updates the configuration of an existing app monitor. When you use this operation, only the parts of the app monitor configuration that you specify in this operation are changed. For any parameters that you omit, the existing values are kept. You can't use this operation to change the tags of an existing app monitor. To change the tags of an existing app monitor, use TagResource. To create a new app monitor, use CreateAppMonitor. After you update an app monitor, sign in to the CloudWatch RUM console to get the updated JavaScript code snippet to add to your web application. For more information, see How do I find a code snippet that I've already generated? */ updateAppMonitor(callback?: (err: AWSError, data: RUM.Types.UpdateAppMonitorResponse) => void): Request<RUM.Types.UpdateAppMonitorResponse, AWSError>; } declare namespace RUM { export interface AppMonitor { /** * A structure that contains much of the configuration data for the app monitor. */ AppMonitorConfiguration?: AppMonitorConfiguration; /** * The date and time that this app monitor was created. */ Created?: ISOTimestampString; /** * A structure that contains information about whether this app monitor stores a copy of the telemetry data that RUM collects using CloudWatch Logs. */ DataStorage?: DataStorage; /** * The top-level internet domain name for which your application has administrative authority. */ Domain?: AppMonitorDomain; /** * The unique ID of this app monitor. */ Id?: AppMonitorId; /** * The date and time of the most recent changes to this app monitor's configuration. */ LastModified?: ISOTimestampString; /** * The name of the app monitor. */ Name?: AppMonitorName; /** * The current state of the app monitor. */ State?: StateEnum; /** * The list of tag keys and values associated with this app monitor. */ Tags?: TagMap; } export interface AppMonitorConfiguration { /** * If you set this to true, the RUM web client sets two cookies, a session cookie and a user cookie. The cookies allow the RUM web client to collect data relating to the number of users an application has and the behavior of the application across a sequence of events. Cookies are stored in the top-level domain of the current page. */ AllowCookies?: Boolean; /** * If you set this to true, RUM enables X-Ray tracing for the user sessions that RUM samples. RUM adds an X-Ray trace header to allowed HTTP requests. It also records an X-Ray segment for allowed HTTP requests. You can see traces and segments from these user sessions in the X-Ray console and the CloudWatch ServiceLens console. For more information, see What is X-Ray? */ EnableXRay?: Boolean; /** * A list of URLs in your website or application to exclude from RUM data collection. You can't include both ExcludedPages and IncludedPages in the same operation. */ ExcludedPages?: Pages; /** * A list of pages in the CloudWatch RUM console that are to be displayed with a "favorite" icon. */ FavoritePages?: FavoritePages; /** * The ARN of the guest IAM role that is attached to the Amazon Cognito identity pool that is used to authorize the sending of data to RUM. */ GuestRoleArn?: Arn; /** * The ID of the Amazon Cognito identity pool that is used to authorize the sending of data to RUM. */ IdentityPoolId?: IdentityPoolId; /** * If this app monitor is to collect data from only certain pages in your application, this structure lists those pages. &lt;p&gt;You can't include both &lt;code&gt;ExcludedPages&lt;/code&gt; and &lt;code&gt;IncludedPages&lt;/code&gt; in the same operation.&lt;/p&gt; */ IncludedPages?: Pages; /** * Specifies the percentage of user sessions to use for RUM data collection. Choosing a higher percentage gives you more data but also incurs more costs. The number you specify is the percentage of user sessions that will be used. If you omit this parameter, the default of 10 is used. */ SessionSampleRate?: SessionSampleRate; /** * An array that lists the types of telemetry data that this app monitor is to collect. errors indicates that RUM collects data about unhandled JavaScript errors raised by your application. performance indicates that RUM collects performance data about how your application and its resources are loaded and rendered. This includes Core Web Vitals. http indicates that RUM collects data about HTTP errors thrown by your application. */ Telemetries?: Telemetries; } export interface AppMonitorDetails { /** * The unique ID of the app monitor. */ id?: String; /** * The name of the app monitor. */ name?: String; /** * The version of the app monitor. */ version?: String; } export type AppMonitorDomain = string; export type AppMonitorId = string; export type AppMonitorName = string; export interface AppMonitorSummary { /** * The date and time that the app monitor was created. */ Created?: ISOTimestampString; /** * The unique ID of this app monitor. */ Id?: AppMonitorId; /** * The date and time of the most recent changes to this app monitor's configuration. */ LastModified?: ISOTimestampString; /** * The name of this app monitor. */ Name?: AppMonitorName; /** * The current state of this app monitor. */ State?: StateEnum; } export type AppMonitorSummaryList = AppMonitorSummary[]; export type Arn = string; export type Boolean = boolean; export interface CreateAppMonitorRequest { /** * A structure that contains much of the configuration data for the app monitor. If you are using Amazon Cognito for authorization, you must include this structure in your request, and it must include the ID of the Amazon Cognito identity pool to use for authorization. If you don't include AppMonitorConfiguration, you must set up your own authorization method. For more information, see Authorize your application to send data to Amazon Web Services. If you omit this argument, the sample rate used for RUM is set to 10% of the user sessions. */ AppMonitorConfiguration?: AppMonitorConfiguration; /** * Data collected by RUM is kept by RUM for 30 days and then deleted. This parameter specifies whether RUM sends a copy of this telemetry data to Amazon CloudWatch Logs in your account. This enables you to keep the telemetry data for more than 30 days, but it does incur Amazon CloudWatch Logs charges. If you omit this parameter, the default is false. */ CwLogEnabled?: Boolean; /** * The top-level internet domain name for which your application has administrative authority. */ Domain: AppMonitorDomain; /** * A name for the app monitor. */ Name: AppMonitorName; /** * Assigns one or more tags (key-value pairs) to the app monitor. Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values. Tags don't have any semantic meaning to Amazon Web Services and are interpreted strictly as strings of characters. &lt;p&gt;You can associate as many as 50 tags with an app monitor.&lt;/p&gt; &lt;p&gt;For more information, see &lt;a href=&quot;https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html&quot;&gt;Tagging Amazon Web Services resources&lt;/a&gt;.&lt;/p&gt; */ Tags?: TagMap; } export interface CreateAppMonitorResponse { /** * The unique ID of the new app monitor. */ Id?: AppMonitorId; } export interface CwLog { /** * Indicated whether the app monitor stores copies of the data that RUM collects in CloudWatch Logs. */ CwLogEnabled?: Boolean; /** * The name of the log group where the copies are stored. */ CwLogGroup?: String; } export interface DataStorage { /** * A structure that contains the information about whether the app monitor stores copies of the data that RUM collects in CloudWatch Logs. If it does, this structure also contains the name of the log group. */ CwLog?: CwLog; } export interface DeleteAppMonitorRequest { /** * The name of the app monitor to delete. */ Name: AppMonitorName; } export interface DeleteAppMonitorResponse { } export type EventData = string; export type EventDataList = EventData[]; export type FavoritePages = String[]; export interface GetAppMonitorDataRequest { /** * An array of structures that you can use to filter the results to those that match one or more sets of key-value pairs that you specify. */ Filters?: QueryFilters; /** * The maximum number of results to return in one operation. */ MaxResults?: MaxQueryResults; /** * The name of the app monitor that collected the data that you want to retrieve. */ Name: AppMonitorName; /** * Use the token returned by the previous operation to request the next page of results. */ NextToken?: Token; /** * A structure that defines the time range that you want to retrieve results from. */ TimeRange: TimeRange; } export interface GetAppMonitorDataResponse { /** * The events that RUM collected that match your request. */ Events?: EventDataList; /** * A token that you can use in a subsequent operation to retrieve the next set of results. */ NextToken?: Token; } export interface GetAppMonitorRequest { /** * The app monitor to retrieve information for. */ Name: AppMonitorName; } export interface GetAppMonitorResponse { /** * A structure containing all the configuration information for the app monitor. */ AppMonitor?: AppMonitor; } export type ISOTimestampString = string; export type IdentityPoolId = string; export type Integer = number; export type JsonValue = string; export interface ListAppMonitorsRequest { /** * The maximum number of results to return in one operation. */ MaxResults?: Integer; /** * Use the token returned by the previous operation to request the next page of results. */ NextToken?: String; } export interface ListAppMonitorsResponse { /** * An array of structures that contain information about the returned app monitors. */ AppMonitorSummaries?: AppMonitorSummaryList; /** * A token that you can use in a subsequent operation to retrieve the next set of results. */ NextToken?: String; } export interface ListTagsForResourceRequest { /** * The ARN of the resource that you want to see the tags of. */ ResourceArn: Arn; } export interface ListTagsForResourceResponse { /** * The ARN of the resource that you are viewing. */ ResourceArn: Arn; /** * The list of tag keys and values associated with the resource you specified. */ Tags: TagMap; } export type MaxQueryResults = number; export type Pages = Url[]; export interface PutRumEventsRequest { /** * A structure that contains information about the app monitor that collected this telemetry information. */ AppMonitorDetails: AppMonitorDetails; /** * A unique identifier for this batch of RUM event data. */ BatchId: String; /** * The ID of the app monitor that is sending this data. */ Id: AppMonitorId; /** * An array of structures that contain the telemetry event data. */ RumEvents: RumEventList; /** * A structure that contains information about the user session that this batch of events was collected from. */ UserDetails: UserDetails; } export interface PutRumEventsResponse { } export interface QueryFilter { /** * The name of a key to search for. The filter returns only the events that match the Name and Values that you specify. Valid values for Name are Browser | Device | Country | Page | OS | EventType | Invert */ Name?: QueryFilterKey; /** * The values of the Name that are to be be included in the returned results. */ Values?: QueryFilterValueList; } export type QueryFilterKey = string; export type QueryFilterValue = string; export type QueryFilterValueList = QueryFilterValue[]; export type QueryFilters = QueryFilter[]; export type QueryTimestamp = number; export interface RumEvent { /** * A string containing details about the event. */ details: JsonValue; /** * A unique ID for this event. */ id: String; /** * Metadata about this event, which contains a JSON serialization of the identity of the user for this session. The user information comes from information such as the HTTP user-agent request header and document interface. */ metadata?: JsonValue; /** * The exact time that this event occurred. */ timestamp: Timestamp; /** * The JSON schema that denotes the type of event this is, such as a page load or a new session. */ type: String; } export type RumEventList = RumEvent[]; export type SessionSampleRate = number; export type StateEnum = "CREATED"|"DELETING"|"ACTIVE"|string; export type String = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The ARN of the CloudWatch RUM resource that you're adding tags to. */ ResourceArn: Arn; /** * The list of key-value pairs to associate with the resource. */ Tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type Telemetries = Telemetry[]; export type Telemetry = "errors"|"performance"|"http"|string; export interface TimeRange { /** * The beginning of the time range to retrieve performance events from. */ After: QueryTimestamp; /** * The end of the time range to retrieve performance events from. If you omit this, the time range extends to the time that this operation is performed. */ Before?: QueryTimestamp; } export type Timestamp = Date; export type Token = string; export interface UntagResourceRequest { /** * The ARN of the CloudWatch RUM resource that you're removing tags from. */ ResourceArn: Arn; /** * The list of tag keys to remove from the resource. */ TagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateAppMonitorRequest { /** * A structure that contains much of the configuration data for the app monitor. If you are using Amazon Cognito for authorization, you must include this structure in your request, and it must include the ID of the Amazon Cognito identity pool to use for authorization. If you don't include AppMonitorConfiguration, you must set up your own authorization method. For more information, see Authorize your application to send data to Amazon Web Services. */ AppMonitorConfiguration?: AppMonitorConfiguration; /** * Data collected by RUM is kept by RUM for 30 days and then deleted. This parameter specifies whether RUM sends a copy of this telemetry data to Amazon CloudWatch Logs in your account. This enables you to keep the telemetry data for more than 30 days, but it does incur Amazon CloudWatch Logs charges. */ CwLogEnabled?: Boolean; /** * The top-level internet domain name for which your application has administrative authority. */ Domain?: AppMonitorDomain; /** * The name of the app monitor to update. */ Name: AppMonitorName; } export interface UpdateAppMonitorResponse { } export type Url = string; export interface UserDetails { /** * The session ID that the performance events are from. */ sessionId?: String; /** * The ID of the user for this user session. This ID is generated by RUM and does not include any personally identifiable information about the user. */ userId?: String; } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2018-05-10"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the RUM client. */ export import Types = RUM; } export = RUM;
the_stack
import dayjs from 'dayjs' import { kea } from 'kea' import { router } from 'kea-router' import api, { PaginatedResponse } from 'lib/api' import { errorToast, toParams } from 'lib/utils' import { ActionFilter, FilterType, ViewType, FunnelVizType, PropertyFilter, PersonType } from '~/types' import { personsModalLogicType } from './personsModalLogicType' import { preflightLogic } from 'scenes/PreflightCheck/logic' import { eventUsageLogic } from 'lib/utils/eventUsageLogic' import { cohortLogic } from 'scenes/cohorts/cohortLogic' import { TrendPeople } from 'scenes/trends/types' import { cleanFilters } from 'scenes/insights/utils/cleanFilters' import { filterTrendsClientSideParams } from 'scenes/insights/sharedUtils' import { ACTIONS_LINE_GRAPH_CUMULATIVE } from 'lib/constants' export interface PersonModalParams { action: ActionFilter | 'session' // todo, refactor this session string param out label: string // Contains the step name date_from: string | number date_to: string | number filters: Partial<FilterType> breakdown_value?: string | number saveOriginal?: boolean searchTerm?: string funnelStep?: number pathsDropoff?: boolean pointValue?: number // The y-axis value of the data point (i.e. count, unique persons, ...) } export interface PeopleParamType { action: ActionFilter | 'session' label: string date_to?: string | number date_from?: string | number breakdown_value?: string | number target_date?: number | string lifecycle_type?: string | number } export function parsePeopleParams(peopleParams: PeopleParamType, filters: Partial<FilterType>): string { const { action, date_from, date_to, breakdown_value, ...restParams } = peopleParams const params = filterTrendsClientSideParams({ ...filters, entity_id: (action !== 'session' && action.id) || filters?.events?.[0]?.id || filters?.actions?.[0]?.id, entity_type: (action !== 'session' && action.type) || filters?.events?.[0]?.type || filters?.actions?.[0]?.type, entity_math: (action !== 'session' && action.math) || undefined, breakdown_value, }) // casting here is not the best if (filters.insight === ViewType.STICKINESS) { params.stickiness_days = date_from as number } else if (params.display === ACTIONS_LINE_GRAPH_CUMULATIVE) { params.date_to = date_from as string } else if (filters.insight === ViewType.LIFECYCLE) { params.date_from = filters.date_from params.date_to = filters.date_to } else { params.date_from = date_from as string params.date_to = date_to as string } // If breakdown type is cohort, we use breakdown_value // If breakdown type is event, we just set another filter if (breakdown_value && filters.breakdown_type != 'cohort' && filters.breakdown_type != 'person') { params.properties = [ ...(params.properties || []), { key: params.breakdown, value: breakdown_value, type: 'event' } as PropertyFilter, ] } if (action !== 'session' && action.properties) { params.properties = [...(params.properties || []), ...action.properties] } return toParams({ ...params, ...restParams }) } export const personsModalLogic = kea<personsModalLogicType<PersonModalParams>>({ actions: () => ({ setSearchTerm: (term: string) => ({ term }), setCohortModalVisible: (visible: boolean) => ({ visible }), loadPeople: (peopleParams: PersonModalParams) => ({ peopleParams }), loadMorePeople: true, hidePeople: true, saveCohortWithFilters: (cohortName: string, filters: Partial<FilterType>) => ({ cohortName, filters }), setPersonsModalFilters: (searchTerm: string, people: TrendPeople, filters: Partial<FilterType>) => ({ searchTerm, people, filters, }), saveFirstLoadedPeople: (people: TrendPeople) => ({ people }), setFirstLoadedPeople: (firstLoadedPeople: TrendPeople | null) => ({ firstLoadedPeople }), savePeopleParams: (peopleParams: PersonModalParams) => ({ peopleParams }), }), reducers: () => ({ searchTerm: [ '', { setSearchTerm: (_, { term }) => term, hidePeople: () => '', }, ], cohortModalVisible: [ false, { setCohortModalVisible: (_, { visible }) => visible, }, ], people: [ null as TrendPeople | null, { loadPeople: (_, { peopleParams: { action, label, date_from, breakdown_value } }) => ({ people: [], count: 0, action, label, day: date_from, breakdown_value, }), setFilters: () => null, setFirstLoadedPeople: (_, { firstLoadedPeople }) => firstLoadedPeople, }, ], firstLoadedPeople: [ null as TrendPeople | null, { saveFirstLoadedPeople: (_, { people }) => people, }, ], loadingMorePeople: [ false, { loadMorePeople: () => true, loadMorePeopleSuccess: () => false, loadMorePeopleFailure: () => false, }, ], showingPeople: [ false, { loadPeople: () => true, hidePeople: () => false, }, ], peopleParams: [ null as PersonModalParams | null, { loadPeople: (_, { peopleParams }) => peopleParams, }, ], }), selectors: { isInitialLoad: [ (s) => [s.peopleLoading, s.loadingMorePeople], (peopleLoading, loadingMorePeople) => peopleLoading && !loadingMorePeople, ], clickhouseFeaturesEnabled: [ () => [preflightLogic.selectors.preflight], (preflight) => !!preflight?.is_clickhouse_enabled, ], }, loaders: ({ actions, values }) => ({ people: { loadPeople: async ({ peopleParams }, breakpoint) => { let people: PaginatedResponse<{ people: PersonType[]; count: number }> | null = null const { label, action, filters, date_from, date_to, breakdown_value, saveOriginal, searchTerm, funnelStep, pathsDropoff, } = peopleParams const searchTermParam = searchTerm ? `&search=${encodeURIComponent(searchTerm)}` : '' if (filters.funnel_correlation_person_entity) { const cleanedParams = cleanFilters(filters) people = await api.create(`api/person/funnel/correlation/?${searchTermParam}`, cleanedParams) } else if (filters.insight === ViewType.LIFECYCLE) { const filterParams = parsePeopleParams( { label, action, target_date: date_from, lifecycle_type: breakdown_value }, filters ) people = await api.get(`api/person/lifecycle/?${filterParams}${searchTermParam}`) } else if (filters.insight === ViewType.STICKINESS) { const filterParams = parsePeopleParams( { label, action, date_from, date_to, breakdown_value }, filters ) people = await api.get(`api/person/stickiness/?${filterParams}${searchTermParam}`) } else if (funnelStep || filters.funnel_viz_type === FunnelVizType.Trends) { let params if (filters.funnel_viz_type === FunnelVizType.Trends) { // funnel trends const entrance_period_start = dayjs(date_from).format('YYYY-MM-DD HH:mm:ss') params = { ...filters, entrance_period_start, drop_off: false } } else { // regular funnel steps params = { ...filters, funnel_step: funnelStep, ...(breakdown_value !== undefined && { funnel_step_breakdown: breakdown_value }), } } const cleanedParams = cleanFilters(params) const funnelParams = toParams(cleanedParams) people = await api.create(`api/person/funnel/?${funnelParams}${searchTermParam}`) } else if (filters.insight === ViewType.PATHS) { const cleanedParams = cleanFilters(filters) people = await api.create(`api/person/path/?${searchTermParam}`, cleanedParams) } else { people = await api.actions.getPeople( { label, action, date_from, date_to, breakdown_value }, filters, searchTerm ) } breakpoint() const peopleResult = { people: people?.results[0]?.people, count: people?.results[0]?.count || 0, action, label, day: date_from, breakdown_value, next: people?.next, funnelStep, pathsDropoff, } as TrendPeople eventUsageLogic.actions.reportPersonModalViewed(peopleParams, peopleResult.count, !!people?.next) if (saveOriginal) { actions.saveFirstLoadedPeople(peopleResult) } return peopleResult }, loadMorePeople: async ({}, breakpoint) => { if (values.people) { const { people: currPeople, count, action, label, day, breakdown_value, next, funnelStep, } = values.people if (!next) { throw new Error('URL of next page of persons is not known.') } const people = await api.get(next) breakpoint() return { people: [...currPeople, ...people.results[0]?.people], count: count + people.results[0]?.count, action, label, day, breakdown_value, next: people.next, funnelStep, } } return null }, }, }), listeners: ({ actions, values }) => ({ saveCohortWithFilters: ({ cohortName, filters }) => { if (values.people) { const { label, action, day, breakdown_value } = values.people const filterParams = parsePeopleParams( { label, action, date_from: day, date_to: day, breakdown_value }, filters ) const cohortParams = { is_static: true, name: cohortName, } cohortLogic({ cohort: { id: 'personsModalNew', groups: [], }, }).actions.saveCohort(cohortParams, filterParams) } else { errorToast(undefined, "We couldn't create your cohort:") } }, setPersonsModalFilters: async ({ searchTerm, people, filters }) => { const { label, action, day, breakdown_value, funnelStep } = people const date_from = day const date_to = day const saveOriginal = false actions.loadPeople({ action, label, date_from, date_to, filters, breakdown_value, saveOriginal, searchTerm, funnelStep, }) }, }), actionToUrl: ({ values }) => ({ loadPeople: () => { return [ router.values.location.pathname, router.values.searchParams, { ...router.values.hashParams, personModal: values.peopleParams }, ] }, hidePeople: () => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { personModal: _discard, ...otherHashParams } = router.values.hashParams return [router.values.location.pathname, router.values.searchParams, otherHashParams] }, }), urlToAction: ({ actions, values }) => ({ '/insights': (_, {}, { personModal }) => { if (personModal && !values.showingPeople) { actions.loadPeople(personModal) } if (!personModal && values.showingPeople) { actions.hidePeople() } }, }), })
the_stack
import * as assert from 'assert'; import { timeout } from 'vs/base/common/async'; import { newWriteableBufferStream, VSBuffer } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { isWeb } from 'vs/base/common/platform'; import { ConfigurationSyncStore } from 'vs/base/common/product'; import { URI } from 'vs/base/common/uri'; import { runWithFakedTimers } from 'vs/base/test/common/timeTravelScheduler'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IFileService } from 'vs/platform/files/common/files'; import { NullLogService } from 'vs/platform/log/common/log'; import product from 'vs/platform/product/common/product'; import { IProductService } from 'vs/platform/product/common/productService'; import { IRequestService } from 'vs/platform/request/common/request'; import { IUserDataSyncStore, IUserDataSyncStoreManagementService, IUserDataSyncStoreService, SyncResource, UserDataSyncErrorCode, UserDataSyncStoreError } from 'vs/platform/userDataSync/common/userDataSync'; import { RequestsSession, UserDataSyncStoreManagementService, UserDataSyncStoreService } from 'vs/platform/userDataSync/common/userDataSyncStoreService'; import { UserDataSyncClient, UserDataSyncTestServer } from 'vs/platform/userDataSync/test/common/userDataSyncClient'; suite('UserDataSyncStoreManagementService', () => { const disposableStore = new DisposableStore(); teardown(() => disposableStore.clear()); test('test sync store is read from settings', async () => { const client = disposableStore.add(new UserDataSyncClient(new UserDataSyncTestServer())); await client.setUp(); client.instantiationService.stub(IProductService, { _serviceBrand: undefined, ...product, ...{ 'configurationSync.store': undefined } }); const configuredStore: ConfigurationSyncStore = { url: 'http://configureHost:3000', stableUrl: 'http://configureHost:3000', insidersUrl: 'http://configureHost:3000', canSwitch: false, authenticationProviders: { 'configuredAuthProvider': { scopes: [] } } }; await client.instantiationService.get(IFileService).writeFile(client.instantiationService.get(IEnvironmentService).settingsResource, VSBuffer.fromString(JSON.stringify({ 'configurationSync.store': configuredStore }))); await client.instantiationService.get(IConfigurationService).reloadConfiguration(); const expected: IUserDataSyncStore = { url: URI.parse('http://configureHost:3000'), type: 'stable', defaultUrl: URI.parse('http://configureHost:3000'), stableUrl: URI.parse('http://configureHost:3000'), insidersUrl: URI.parse('http://configureHost:3000'), canSwitch: false, authenticationProviders: [{ id: 'configuredAuthProvider', scopes: [] }] }; const testObject: IUserDataSyncStoreManagementService = disposableStore.add(client.instantiationService.createInstance(UserDataSyncStoreManagementService)); assert.strictEqual(testObject.userDataSyncStore?.url.toString(), expected.url.toString()); assert.strictEqual(testObject.userDataSyncStore?.defaultUrl.toString(), expected.defaultUrl.toString()); assert.deepStrictEqual(testObject.userDataSyncStore?.authenticationProviders, expected.authenticationProviders); }); }); suite('UserDataSyncStoreService', () => { const disposableStore = new DisposableStore(); teardown(() => disposableStore.clear()); test('test read manifest for the first time', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); const productService = client.instantiationService.get(IProductService); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Client-Name'], `${productService.applicationName}${isWeb ? '-web' : ''}`); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Client-Version'], productService.version); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test read manifest for the second time when session is not yet created', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test session id header is not set in the first manifest request after session is created', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; await testObject.write(SyncResource.Settings, 'some content', null); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test session id header is set from the second manifest request after session is created', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test headers are send for write request', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); await testObject.manifest(null); target.reset(); await testObject.write(SyncResource.Settings, 'some content', null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test headers are send for read request', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); await testObject.manifest(null); target.reset(); await testObject.read(SyncResource.Settings, null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test headers are reset after session is cleared ', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); await testObject.manifest(null); await testObject.clear(); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test old headers are sent after session is changed on server ', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; const userSessionId = target.requestsWithAllHeaders[0].headers!['X-User-Session-Id']; await target.clear(); // client 2 const client2 = disposableStore.add(new UserDataSyncClient(target)); await client2.setUp(); const testObject2 = client2.instantiationService.get(IUserDataSyncStoreService); await testObject2.write(SyncResource.Settings, 'some content', null); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], userSessionId); }); test('test old headers are reset from second request after session is changed on server ', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; const userSessionId = target.requestsWithAllHeaders[0].headers!['X-User-Session-Id']; await target.clear(); // client 2 const client2 = disposableStore.add(new UserDataSyncClient(target)); await client2.setUp(); const testObject2 = client2.instantiationService.get(IUserDataSyncStoreService); await testObject2.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], userSessionId); }); test('test old headers are sent after session is cleared from another server ', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; const userSessionId = target.requestsWithAllHeaders[0].headers!['X-User-Session-Id']; // client 2 const client2 = disposableStore.add(new UserDataSyncClient(target)); await client2.setUp(); const testObject2 = client2.instantiationService.get(IUserDataSyncStoreService); await testObject2.clear(); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], userSessionId); }); test('test headers are reset after session is cleared from another server ', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; // client 2 const client2 = disposableStore.add(new UserDataSyncClient(target)); await client2.setUp(); const testObject2 = client2.instantiationService.get(IUserDataSyncStoreService); await testObject2.clear(); await testObject.manifest(null); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.strictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test headers are reset after session is cleared from another server - started syncing again', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); const machineSessionId = target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id']; const userSessionId = target.requestsWithAllHeaders[0].headers!['X-User-Session-Id']; // client 2 const client2 = disposableStore.add(new UserDataSyncClient(target)); await client2.setUp(); const testObject2 = client2.instantiationService.get(IUserDataSyncStoreService); await testObject2.clear(); await testObject.manifest(null); await testObject.write(SyncResource.Settings, 'some content', null); await testObject.manifest(null); target.reset(); await testObject.manifest(null); assert.strictEqual(target.requestsWithAllHeaders.length, 1); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], undefined); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-Machine-Session-Id'], machineSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], userSessionId); assert.notStrictEqual(target.requestsWithAllHeaders[0].headers!['X-User-Session-Id'], undefined); }); test('test rate limit on server with retry after', async () => { const target = new UserDataSyncTestServer(1, 1); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); const promise = Event.toPromise(testObject.onDidChangeDonotMakeRequestsUntil); try { await testObject.manifest(null); assert.fail('should fail'); } catch (e) { assert.ok(e instanceof UserDataSyncStoreError); assert.deepStrictEqual((<UserDataSyncStoreError>e).code, UserDataSyncErrorCode.TooManyRequestsAndRetryAfter); await promise; assert.ok(!!testObject.donotMakeRequestsUntil); } }); test('test donotMakeRequestsUntil is reset after retry time is finished', async () => { return runWithFakedTimers({ useFakeTimers: true }, async () => { const client = disposableStore.add(new UserDataSyncClient(new UserDataSyncTestServer(1, 0.25))); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); try { await testObject.manifest(null); assert.fail('should fail'); } catch (e) { } const promise = Event.toPromise(testObject.onDidChangeDonotMakeRequestsUntil); await timeout(300); await promise; assert.ok(!testObject.donotMakeRequestsUntil); }); }); test('test donotMakeRequestsUntil is retrieved', async () => { const client = disposableStore.add(new UserDataSyncClient(new UserDataSyncTestServer(1, 1))); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); try { await testObject.manifest(null); } catch (e) { } const target = disposableStore.add(client.instantiationService.createInstance(UserDataSyncStoreService)); assert.strictEqual(target.donotMakeRequestsUntil?.getTime(), testObject.donotMakeRequestsUntil?.getTime()); }); test('test donotMakeRequestsUntil is checked and reset after retreived', async () => { return runWithFakedTimers({ useFakeTimers: true }, async () => { const client = disposableStore.add(new UserDataSyncClient(new UserDataSyncTestServer(1, 0.25))); await client.setUp(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); await testObject.manifest(null); try { await testObject.manifest(null); assert.fail('should fail'); } catch (e) { } await timeout(300); const target = disposableStore.add(client.instantiationService.createInstance(UserDataSyncStoreService)); assert.ok(!target.donotMakeRequestsUntil); }); }); test('test read resource request handles 304', async () => { // Setup the client const target = new UserDataSyncTestServer(); const client = disposableStore.add(new UserDataSyncClient(target)); await client.setUp(); await client.sync(); const testObject = client.instantiationService.get(IUserDataSyncStoreService); const expected = await testObject.read(SyncResource.Settings, null); const actual = await testObject.read(SyncResource.Settings, expected); assert.strictEqual(actual, expected); }); }); suite('UserDataSyncRequestsSession', () => { const requestService: IRequestService = { _serviceBrand: undefined, async request() { return { res: { headers: {} }, stream: newWriteableBufferStream() }; }, async resolveProxy() { return undefined; } }; test('too many requests are thrown when limit exceeded', async () => { const testObject = new RequestsSession(1, 500, requestService, new NullLogService()); await testObject.request('url', {}, CancellationToken.None); try { await testObject.request('url', {}, CancellationToken.None); } catch (error) { assert.ok(error instanceof UserDataSyncStoreError); assert.strictEqual((<UserDataSyncStoreError>error).code, UserDataSyncErrorCode.LocalTooManyRequests); return; } assert.fail('Should fail with limit exceeded'); }); test('requests are handled after session is expired', async () => { const testObject = new RequestsSession(1, 100, requestService, new NullLogService()); await testObject.request('url', {}, CancellationToken.None); await timeout(125); await testObject.request('url', {}, CancellationToken.None); }); test('too many requests are thrown after session is expired', async () => { const testObject = new RequestsSession(1, 100, requestService, new NullLogService()); await testObject.request('url', {}, CancellationToken.None); await timeout(125); await testObject.request('url', {}, CancellationToken.None); try { await testObject.request('url', {}, CancellationToken.None); } catch (error) { assert.ok(error instanceof UserDataSyncStoreError); assert.strictEqual((<UserDataSyncStoreError>error).code, UserDataSyncErrorCode.LocalTooManyRequests); return; } assert.fail('Should fail with limit exceeded'); }); });
the_stack
import { ConfalPyramidsProvider } from './property'; import { ConfalPyramidsTypes as CPT } from './types'; import { OrderedSet, Segmentation } from '../../../mol-data/int'; import { Vec3 } from '../../../mol-math/linear-algebra'; import { ChainIndex, ElementIndex, ResidueIndex, Structure, StructureElement, StructureProperties, Unit } from '../../../mol-model/structure'; export namespace ConfalPyramidsUtil { type Residue = Segmentation.Segment<ResidueIndex>; export type AtomInfo = { pos: Vec3, index: ElementIndex, fakeAltId: string, }; export type FirstResidueAtoms = { O3: AtomInfo, }; export type SecondResidueAtoms = { OP1: AtomInfo, OP2: AtomInfo, O5: AtomInfo, P: AtomInfo, }; type ResidueInfo = { PDB_model_num: number, asym_id: string, auth_asym_id: string, seq_id: number, auth_seq_id: number, comp_id: string, alt_id: string, ins_code: string, }; export type Handler = (pyramid: CPT.Pyramid, first: FirstResidueAtoms, second: SecondResidueAtoms, firstLocIndex: number, secondLocIndex: number) => void; function residueInfoFromLocation(loc: StructureElement.Location): ResidueInfo { return { PDB_model_num: StructureProperties.unit.model_num(loc), asym_id: StructureProperties.chain.label_asym_id(loc), auth_asym_id: StructureProperties.chain.auth_asym_id(loc), seq_id: StructureProperties.residue.label_seq_id(loc), auth_seq_id: StructureProperties.residue.auth_seq_id(loc), comp_id: StructureProperties.atom.label_comp_id(loc), alt_id: StructureProperties.atom.label_alt_id(loc), ins_code: StructureProperties.residue.pdbx_PDB_ins_code(loc) }; } export function hasMultipleModels(unit: Unit.Atomic): boolean { const prop = ConfalPyramidsProvider.get(unit.model).value; if (prop === undefined || prop.data === undefined) throw new Error('No custom properties data'); return prop.data.hasMultipleModels; } function getPossibleAltIdsIndices(eIFirst: ElementIndex, eILast: ElementIndex, structure: Structure, unit: Unit.Atomic): string[] { const loc = StructureElement.Location.create(structure, unit, -1 as ElementIndex); const uIFirst = OrderedSet.indexOf(unit.elements, eIFirst); const uILast = OrderedSet.indexOf(unit.elements, eILast); const possibleAltIds: string[] = []; for (let uI = uIFirst; uI <= uILast; uI++) { loc.element = unit.elements[uI]; const altId = StructureProperties.atom.label_alt_id(loc); if (altId !== '' && !possibleAltIds.includes(altId)) possibleAltIds.push(altId); } return possibleAltIds; } function getPossibleAltIdsResidue(residue: Residue, structure: Structure, unit: Unit.Atomic): string[] { return getPossibleAltIdsIndices(unit.elements[residue.start], unit.elements[residue.end - 1], structure, unit); } class Utility { protected getPyramidByName(name: string): { pyramid: CPT.Pyramid | undefined, index: number } { const index = this.data.names.get(name); if (index === undefined) return { pyramid: undefined, index: -1 }; return { pyramid: this.data.pyramids[index], index }; } protected stepToName(entry_id: string, modelNum: number, locFirst: StructureElement.Location, locSecond: StructureElement.Location, fakeAltId_1: string, fakeAltId_2: string) { const first = residueInfoFromLocation(locFirst); const second = residueInfoFromLocation(locSecond); const model_id = this.hasMultipleModels ? `-m${modelNum}` : ''; const alt_id_1 = fakeAltId_1 !== '' ? `.${fakeAltId_1}` : (first.alt_id.length ? `.${first.alt_id}` : ''); const alt_id_2 = fakeAltId_2 !== '' ? `.${fakeAltId_2}` : (second.alt_id.length ? `.${second.alt_id}` : ''); const ins_code_1 = first.ins_code.length ? `.${first.ins_code}` : ''; const ins_code_2 = second.ins_code.length ? `.${second.ins_code}` : ''; return `${entry_id}${model_id}_${first.auth_asym_id}_${first.comp_id}${alt_id_1}_${first.auth_seq_id}${ins_code_1}_${second.comp_id}${alt_id_2}_${second.auth_seq_id}${ins_code_2}`; } constructor(unit: Unit.Atomic) { const prop = ConfalPyramidsProvider.get(unit.model).value; if (prop === undefined || prop.data === undefined) throw new Error('No custom properties data'); this.data = prop.data; this.hasMultipleModels = hasMultipleModels(unit); this.entryId = unit.model.entryId.toLowerCase(); this.modelNum = unit.model.modelNum; } protected readonly data: CPT.PyramidsData protected readonly hasMultipleModels: boolean; protected readonly entryId: string; protected readonly modelNum: number; } export class UnitWalker extends Utility { private getAtomIndices(names: string[], residue: Residue): ElementIndex[] { let rI = residue.start; const rILast = residue.end - 1; const indices: ElementIndex[] = []; for (; rI !== rILast; rI++) { const eI = this.unit.elements[rI]; const loc = StructureElement.Location.create(this.structure, this.unit, eI); const thisName = StructureProperties.atom.label_atom_id(loc); if (names.includes(thisName)) indices.push(eI); } if (indices.length === 0) throw new Error(`Element ${name} not found on residue ${residue.index}`); return indices; } private getAtomPositions(indices: ElementIndex[]): Vec3[] { const pos = this.unit.conformation.invariantPosition; const positions: Vec3[] = []; for (const eI of indices) { const v = Vec3.zero(); pos(eI, v); positions.push(v); } return positions; } private handleStep(firstAtoms: FirstResidueAtoms[], secondAtoms: SecondResidueAtoms[]) { const modelNum = this.hasMultipleModels ? this.modelNum : -1; let ok = false; const firstLoc = StructureElement.Location.create(this.structure, this.unit, -1 as ElementIndex); const secondLoc = StructureElement.Location.create(this.structure, this.unit, -1 as ElementIndex); for (let i = 0; i < firstAtoms.length; i++) { const first = firstAtoms[i]; for (let j = 0; j < secondAtoms.length; j++) { const second = secondAtoms[j]; firstLoc.element = first.O3.index; secondLoc.element = second.OP1.index; const name = this.stepToName(this.entryId, modelNum, firstLoc, secondLoc, first.O3.fakeAltId, second.OP1.fakeAltId); const { pyramid, index } = this.getPyramidByName(name); if (pyramid !== undefined) { const setLoc = (loc: CPT.Location, eI: ElementIndex) => { loc.element.structure = this.structure; loc.element.unit = this.unit; loc.element.element = eI; }; const locIndex = index * 2; setLoc(this.data.locations[locIndex], firstLoc.element); setLoc(this.data.locations[locIndex + 1], secondLoc.element); this.handler(pyramid, first, second, locIndex, locIndex + 1); ok = true; } } } if (!ok) throw new Error('Bogus step'); } private processFirstResidue(residue: Residue, possibleAltIds: string[]) { const indO3 = this.getAtomIndices(['O3\'', 'O3*'], residue); const posO3 = this.getAtomPositions(indO3); const altPos: FirstResidueAtoms[] = [ { O3: { pos: posO3[0], index: indO3[0], fakeAltId: '' } } ]; for (let i = 1; i < indO3.length; i++) { altPos.push({ O3: { pos: posO3[i], index: indO3[i], fakeAltId: '' } }); } if (altPos.length === 1 && possibleAltIds.length > 1) { /* We have some alternate positions on the residue but O3 does not have any - fake them */ altPos[0].O3.fakeAltId = possibleAltIds[0]; for (let i = 1; i < possibleAltIds.length; i++) altPos.push({ O3: { pos: posO3[0], index: indO3[0], fakeAltId: possibleAltIds[i] } }); } return altPos; } private processSecondResidue(residue: Residue, possibleAltIds: string[]) { const indOP1 = this.getAtomIndices(['OP1'], residue); const indOP2 = this.getAtomIndices(['OP2'], residue); const indO5 = this.getAtomIndices(['O5\'', 'O5*'], residue); const indP = this.getAtomIndices(['P'], residue); const posOP1 = this.getAtomPositions(indOP1); const posOP2 = this.getAtomPositions(indOP2); const posO5 = this.getAtomPositions(indO5); const posP = this.getAtomPositions(indP); const infoOP1: AtomInfo[] = []; /* We use OP1 as "pivotal" atom. There is no specific reason * to pick OP1, it is as good a choice as any other atom */ if (indOP1.length === 1 && possibleAltIds.length > 1) { /* No altIds on OP1, fake them */ for (const altId of possibleAltIds) infoOP1.push({ pos: posOP1[0], index: indOP1[0], fakeAltId: altId }); } else { for (let i = 0; i < indOP1.length; i++) infoOP1.push({ pos: posOP1[i], index: indOP1[i], fakeAltId: '' }); } const mkInfo = (i: number, indices: ElementIndex[], positions: Vec3[], altId: string) => { if (i >= indices.length) { const last = indices.length - 1; return { pos: positions[last], index: indices[last], fakeAltId: altId }; } return { pos: positions[i], index: indices[i], fakeAltId: altId }; }; const altPos: SecondResidueAtoms[] = []; for (let i = 0; i < infoOP1.length; i++) { const altId = infoOP1[i].fakeAltId; const OP2 = mkInfo(i, indOP2, posOP2, altId); const O5 = mkInfo(i, indO5, posO5, altId); const P = mkInfo(i, indP, posP, altId); altPos.push({ OP1: infoOP1[i], OP2, O5, P }); } return altPos; } private step(residue: Residue): { firstAtoms: FirstResidueAtoms[], secondAtoms: SecondResidueAtoms[] } { const firstPossibleAltIds = getPossibleAltIdsResidue(residue, this.structure, this.unit); const firstAtoms = this.processFirstResidue(residue, firstPossibleAltIds); residue = this.residueIt.move(); const secondPossibleAltIds = getPossibleAltIdsResidue(residue, this.structure, this.unit); const secondAtoms = this.processSecondResidue(residue, secondPossibleAltIds); return { firstAtoms, secondAtoms }; } walk() { while (this.chainIt.hasNext) { this.residueIt.setSegment(this.chainIt.move()); let residue = this.residueIt.move(); while (this.residueIt.hasNext) { try { const { firstAtoms, secondAtoms } = this.step(residue); this.handleStep(firstAtoms, secondAtoms); } catch (error) { /* Skip and move along */ residue = this.residueIt.move(); } } } } constructor(private structure: Structure, private unit: Unit.Atomic, private handler: Handler) { super(unit); this.chainIt = Segmentation.transientSegments(unit.model.atomicHierarchy.chainAtomSegments, unit.elements); this.residueIt = Segmentation.transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements); } private chainIt: Segmentation.SegmentIterator<ChainIndex>; private residueIt: Segmentation.SegmentIterator<ResidueIndex>; } }
the_stack
import omit from 'lodash/omit' import { getPreciseDefaultValue, getFilterParams, getVariableParams, getCustomOptionVariableParams } from 'app/components/Control/util' import { FieldSortTypes } from '../Widget/components/Config/Sort' import { decodeMetricName } from '../Widget/components/util' import { IDashboardItemInfo, IQueryConditions, IDataRequestParams, IDataRequestBody, IDashboardItem } from './types' import { IWidgetFormed } from '../Widget/types' import ChartTypes from '../Widget/config/chart/ChartTypes' import { IControl, IGlobalControlConditionsByItem, ILocalControlConditions, IGlobalControlConditions } from 'app/components/Control/types' import { ControlPanelTypes, ControlFieldTypes } from 'app/components/Control/constants' import { IFormedViews, IShareFormedViews, IViewQueryResponse } from '../View/types' import { IPaginationParams } from '../Widget/components/Widget' export function getInitialPagination(widget: IWidgetFormed): IPaginationParams { const { mode, selectedChart, chartStyles } = widget.config if (mode === 'chart' && selectedChart === ChartTypes.Table) { const { withPaging, pageSize } = chartStyles.table return { withPaging, pageSize: withPaging ? Number(pageSize) : 0, pageNo: withPaging ? 1 : 0, totalCount: 0 } } else { return null } } export function getInitialNativeQuery(widget: IWidgetFormed): boolean { const { mode, selectedChart, chartStyles } = widget.config if (mode === 'chart' && selectedChart === ChartTypes.Table) { return chartStyles.table.withNoAggregators } else { return false } } export function getInitialPaginationAndNativeQuery(widget: IWidgetFormed) { return { pagination: getInitialPagination(widget), nativeQuery: getInitialNativeQuery(widget) } } export function getUpdatedPagination( pagination: IPaginationParams, result: IViewQueryResponse ): IPaginationParams { if (!pagination) { return pagination } const { pageNo, pageSize, totalCount } = result return { ...pagination, pageNo: pagination.withPaging ? pageNo : 0, pageSize: pagination.withPaging ? pageSize : 0, totalCount } } export function getInitialItemInfo( widget: IWidgetFormed, formedViews: IFormedViews ): IDashboardItemInfo { return { datasource: { columns: [], pageNo: 0, pageSize: 0, totalCount: 0, resultList: [] }, loading: false, queryConditions: { linkageFilters: [], globalFilters: [], linkageVariables: [], globalVariables: [], drillpathInstance: [], ...getLocalControlInitialValues(widget.config.controls, formedViews), ...getInitialPaginationAndNativeQuery(widget) }, shareToken: '', shareLoading: false, authorizedShareToken: '', downloadCsvLoading: false, interactId: '', rendered: false, renderType: 'rerender', selectedItems: [], errorMessage: '' } } interface IGlobalControlInitialValues { [itemId: string]: IGlobalControlConditions } export function getGlobalControlInitialValues( controls: IControl[], formedViews: IFormedViews | IShareFormedViews ): IGlobalControlInitialValues { const initialValues: IGlobalControlInitialValues = {} controls.forEach((control: IControl) => { const { optionWithVariable, relatedItems, relatedViews } = control const defaultValue = getPreciseDefaultValue(control) if (defaultValue) { Object.entries(relatedItems).forEach(([itemId, config]) => { Object.entries(relatedViews).forEach(([viewId, relatedView]) => { if ( config.checked && config.viewId === Number(viewId) && formedViews[viewId] ) { const { model, variable } = formedViews[viewId] if (!initialValues[itemId]) { initialValues[itemId] = { globalFilters: [], globalVariables: [] } } if (optionWithVariable) { const filterValue = getCustomOptionVariableParams( control, Number(viewId), defaultValue, variable ) initialValues[itemId].globalVariables = initialValues[ itemId ].globalVariables.concat(filterValue) } else { if (relatedView.fieldType === ControlFieldTypes.Column) { const filterValue = getFilterParams( control, relatedView.fields, defaultValue, model ) initialValues[itemId].globalFilters = initialValues[ itemId ].globalFilters.concat(filterValue) } else { const filterValue = getVariableParams( control, relatedView.fields, defaultValue, variable ) initialValues[itemId].globalVariables = initialValues[ itemId ].globalVariables.concat(filterValue) } } } }) }) } }) return initialValues } export function getLocalControlInitialValues( controls: IControl[], formedViews: IFormedViews | IShareFormedViews ): ILocalControlConditions { const initialValues: ILocalControlConditions = { tempFilters: [], // @TODO combine widget static filters with local filters variables: [] } controls.forEach((control: IControl) => { const { optionWithVariable, relatedViews } = control const defaultValue = getPreciseDefaultValue(control) if (defaultValue) { Object.entries(relatedViews).forEach(([viewId, relatedView]) => { if (formedViews[viewId]) { const { model, variable } = formedViews[viewId] if (optionWithVariable) { const filterValue = getCustomOptionVariableParams( control, Number(viewId), defaultValue, variable ) initialValues.variables = initialValues.variables.concat( filterValue ) } else { if (relatedView.fieldType === ControlFieldTypes.Column) { const filterValue = getFilterParams( control, relatedView.fields, defaultValue, model ) initialValues.tempFilters = initialValues.tempFilters.concat( filterValue ) } else { const filterValue = getVariableParams( control, relatedView.fields, defaultValue, variable ) initialValues.variables = initialValues.variables.concat( filterValue ) } } } }) } }) return initialValues } export function getRequestParams( widget: IWidgetFormed, cachedQueryConditions: IQueryConditions, flush: boolean, inputQueryConditions?: Partial<IQueryConditions> ): IDataRequestParams { const { cols, rows, metrics, secondaryMetrics, color, label, size, xAxis, tip, limit, cache, expired } = widget.config const customOrders = cols .concat(rows) .filter(({ sort }) => sort && sort.sortType === FieldSortTypes.Custom) .map(({ name, sort }) => ({ name, list: sort[FieldSortTypes.Custom].sortList })) // @TODO combine widget static filters with local filters let tempFilters = cachedQueryConditions.tempFilters let linkageFilters = cachedQueryConditions.linkageFilters let globalFilters = cachedQueryConditions.globalFilters let paginationOrders = cachedQueryConditions.orders let variables = cachedQueryConditions.variables let linkageVariables = cachedQueryConditions.linkageVariables let globalVariables = cachedQueryConditions.globalVariables let pagination = cachedQueryConditions.pagination let nativeQuery = cachedQueryConditions.nativeQuery let drillStatus = cachedQueryConditions.drillStatus const prevDrillHistory = cachedQueryConditions.drillHistory ? cachedQueryConditions.drillHistory[ cachedQueryConditions.drillHistory.length - 1 ] : {} if (inputQueryConditions) { tempFilters = inputQueryConditions.tempFilters || tempFilters linkageFilters = inputQueryConditions.linkageFilters || linkageFilters globalFilters = inputQueryConditions.globalFilters || globalFilters paginationOrders = inputQueryConditions.orders || paginationOrders variables = inputQueryConditions.variables || variables linkageVariables = inputQueryConditions.linkageVariables || linkageVariables globalVariables = inputQueryConditions.globalVariables || globalVariables drillStatus = inputQueryConditions.drillStatus || prevDrillHistory pagination = inputQueryConditions.pagination || pagination nativeQuery = inputQueryConditions.nativeQuery !== void 0 ? inputQueryConditions.nativeQuery : nativeQuery } let groups = cols .concat(rows) .filter((g) => g.name !== '指标名称') .map((g) => g.name) let aggregators = metrics.map((m) => ({ column: decodeMetricName(m.name), func: m.agg })) let orders = widget.config.orders const filters = widget.config.filters.reduce( (a, b) => a.concat(b.config.sqlModel), [] ) if (secondaryMetrics && secondaryMetrics.length) { aggregators = aggregators.concat( secondaryMetrics.map((second) => ({ column: decodeMetricName(second.name), func: second.agg })) ) } if (color) { groups = groups.concat(color.items.map((c) => c.name)) } if (label) { groups = groups.concat( label.items.filter((l) => l.type === 'category').map((l) => l.name) ) aggregators = aggregators.concat( label.items .filter((l) => l.type === 'value') .map((l) => ({ column: decodeMetricName(l.name), func: l.agg })) ) } if (size) { aggregators = aggregators.concat( size.items.map((s) => ({ column: decodeMetricName(s.name), func: s.agg })) ) } if (xAxis) { aggregators = aggregators.concat( xAxis.items.map((x) => ({ column: decodeMetricName(x.name), func: x.agg })) ) } if (tip) { aggregators = aggregators.concat( tip.items.map((t) => ({ column: decodeMetricName(t.name), func: t.agg })) ) } if (paginationOrders) { orders = orders.concat(paginationOrders) } return { groups, aggregators, filters, tempFilters, linkageFilters, globalFilters, variables, linkageVariables, globalVariables, orders, limit, cache, expired, flush, pagination, nativeQuery, customOrders, drillStatus } } export function getRequestBody( requestParams: IDataRequestParams ): IDataRequestBody { const { filters, tempFilters, // @TODO combine widget static filters with local filters linkageFilters, globalFilters, variables, linkageVariables, globalVariables, pagination, drillStatus, groups, ...rest } = requestParams const { pageSize, pageNo } = pagination || { pageSize: 0, pageNo: 0 } let combinedFilters = filters .concat(tempFilters) .concat(linkageFilters) .concat(globalFilters) if (drillStatus && drillStatus.filters) { combinedFilters = combinedFilters.concat(drillStatus.filters) } return { ...omit(rest, 'customOrders'), groups: drillStatus && drillStatus.groups ? drillStatus.groups : groups, filters: combinedFilters, params: variables.concat(linkageVariables).concat(globalVariables), pageSize, pageNo } } export function getFormValuesRelatedItems( controls: IControl[], currentItems: IDashboardItem[], formValues: object ): number[] { return Object.keys(formValues).reduce((items, key) => { const control = controls.find((c) => c.key === key) const { relatedItems } = control const checkedItems = Object.entries(relatedItems) .filter( ([itemId, config]) => config.checked && currentItems.find((c) => c.id === Number(itemId)) ) .map(([itemId]) => itemId) return Array.from(new Set([...items, ...checkedItems])) }, []) } export function getCurrentControlValues( type: ControlPanelTypes, controls: IControl[], formedViews: IFormedViews | IShareFormedViews, allFormValues: object, changedFormValues?: object, currentItems?: IDashboardItem[] ): IGlobalControlConditionsByItem | ILocalControlConditions { const updatedFormValues = { ...allFormValues, ...changedFormValues } if (type === ControlPanelTypes.Global) { const changedFormValuesRelatedItems = getFormValuesRelatedItems( controls, currentItems, changedFormValues || allFormValues ) const conditionsByItem: IGlobalControlConditionsByItem = {} changedFormValuesRelatedItems.forEach((itemId) => { Object.entries(updatedFormValues).forEach(([key, value]) => { const control = controls.find((c) => c.key === key) if (control) { const { optionWithVariable, relatedViews, relatedItems } = control const relatedItem = relatedItems[itemId] if ( relatedItem && relatedItem.checked && relatedViews[relatedItem.viewId] && formedViews[relatedItem.viewId] ) { const relatedView = relatedViews[relatedItem.viewId] const { model, variable } = formedViews[relatedItem.viewId] if (!conditionsByItem[itemId]) { conditionsByItem[itemId] = { globalVariables: [], globalFilters: [] } } if (optionWithVariable) { const controlVariables = getCustomOptionVariableParams( control, relatedItem.viewId, value, variable ) conditionsByItem[itemId].globalVariables = conditionsByItem[ itemId ].globalVariables.concat(controlVariables) } else { if (relatedView.fieldType === ControlFieldTypes.Column) { const controlFilters = getFilterParams( control, relatedView.fields, value, model ) conditionsByItem[itemId].globalFilters = conditionsByItem[ itemId ].globalFilters.concat(controlFilters) } else { const controlVariables = getVariableParams( control, relatedView.fields, value, variable ) conditionsByItem[itemId].globalVariables = conditionsByItem[ itemId ].globalVariables.concat(controlVariables) } } } } }) }) return conditionsByItem } else { const conditions: ILocalControlConditions = { tempFilters: [], variables: [] } Object.entries(updatedFormValues).forEach(([key, value]) => { const control = controls.find((c) => c.key === key) if (control) { const [viewId, relatedView] = Object.entries(control.relatedViews)[0] if (formedViews[viewId]) { const { model, variable } = formedViews[viewId] if (control.optionWithVariable) { const controlVariables = getCustomOptionVariableParams( control, Number(viewId), value, variable ) conditions.variables = conditions.variables.concat(controlVariables) } else { if (relatedView.fieldType === ControlFieldTypes.Column) { const controlFilters = getFilterParams( control, relatedView.fields, value, model ) conditions.tempFilters = conditions.tempFilters.concat( controlFilters ) } else { const controlVariables = getVariableParams( control, relatedView.fields, value, variable ) conditions.variables = conditions.variables.concat( controlVariables ) } } } } }) return conditions } }
the_stack
import { NULL_ADDRESS } from '@celo/base/lib/address' import { assertEqualBN, assertLogMatches2, assertRevert, matchAddress, matchAny, timeTravel, } from '@celo/protocol/lib/test-utils' import { fixed1, toFixed } from '@celo/utils/lib/fixidity' import BigNumber from 'bignumber.js' import _ from 'lodash' import { SortedOraclesContract, SortedOraclesInstance } from 'types' import Web3 from 'web3' const SortedOracles: SortedOraclesContract = artifacts.require('SortedOracles') // @ts-ignore // TODO(mcortesi): Use BN.js SortedOracles.numberFormat = 'BigNumber' contract('SortedOracles', (accounts: string[]) => { let sortedOracles: SortedOraclesInstance const anOracle = accounts[9] const aToken = '0x00000000000000000000000000000000deadbeef' const aReportExpiry: number = 3600 beforeEach(async () => { sortedOracles = await SortedOracles.new(true) await sortedOracles.initialize(aReportExpiry) }) describe('#initialize()', () => { it('should have set the owner', async () => { const owner: string = await sortedOracles.owner() assert.equal(owner, accounts[0]) }) it('should have set reportExpiry', async () => { assertEqualBN(await sortedOracles.reportExpirySeconds(), aReportExpiry) }) it('should not be callable again', async () => { await assertRevert(sortedOracles.initialize(aReportExpiry)) }) }) describe('#setReportExpiry', () => { const newReportExpiry = aReportExpiry + 1 it('should update reportExpiry', async () => { await sortedOracles.setReportExpiry(newReportExpiry) assertEqualBN(await sortedOracles.reportExpirySeconds(), newReportExpiry) }) it('should emit the ReportExpirySet event', async () => { const resp = await sortedOracles.setReportExpiry(newReportExpiry) assert.equal(resp.logs.length, 1) const log = resp.logs[0] assertLogMatches2(log, { event: 'ReportExpirySet', args: { reportExpiry: new BigNumber(newReportExpiry), }, }) }) it('should revert when called by a non-owner', async () => { await assertRevert(sortedOracles.setReportExpiry(newReportExpiry, { from: accounts[1] })) }) }) describe('#setTokenReportExpiry', () => { const newReportExpiry = aReportExpiry + 1 const token = Web3.utils.toChecksumAddress(Web3.utils.randomHex(20)) it('should update reportExpiry', async () => { await sortedOracles.setTokenReportExpiry(token, newReportExpiry) assertEqualBN(await sortedOracles.tokenReportExpirySeconds(token), newReportExpiry) }) it('should emit the TokenReportExpirySet event', async () => { const resp = await sortedOracles.setTokenReportExpiry(token, newReportExpiry) assert.equal(resp.logs.length, 1) const log = resp.logs[0] assertLogMatches2(log, { event: 'TokenReportExpirySet', args: { token, reportExpiry: new BigNumber(newReportExpiry), }, }) }) it('should revert when called by a non-owner', async () => { await assertRevert(sortedOracles.setReportExpiry(newReportExpiry, { from: accounts[1] })) }) }) describe('#addOracle', () => { it('should add an Oracle', async () => { await sortedOracles.addOracle(aToken, anOracle) assert.isTrue(await sortedOracles.isOracle(aToken, anOracle)) }) it('should emit the OracleAdded event', async () => { const resp = await sortedOracles.addOracle(aToken, anOracle) assert.equal(resp.logs.length, 1) const log = resp.logs[0] assertLogMatches2(log, { event: 'OracleAdded', args: { token: matchAddress(aToken), oracleAddress: matchAddress(anOracle), }, }) }) it('should revert when token is the null address', async () => { await assertRevert(sortedOracles.addOracle(NULL_ADDRESS, anOracle)) }) it('should revert when the oracle is the null address', async () => { await assertRevert(sortedOracles.addOracle(aToken, NULL_ADDRESS)) }) it('should revert when the oracle has already been added', async () => { await sortedOracles.addOracle(aToken, anOracle) await assertRevert(sortedOracles.addOracle(aToken, anOracle)) }) it('should revert when called by anyone other than the owner', async () => { await assertRevert(sortedOracles.addOracle(aToken, anOracle, { from: accounts[1] })) }) }) describe('#getTokenReportExpirySeconds', () => { describe('when no token level expiry is set', () => { it('returns the contract level one', async () => { assert.isTrue((await sortedOracles.getTokenReportExpirySeconds(aToken)).eq(aReportExpiry)) }) }) describe('when a token level expiry is set', () => { const anotherReportExpirt = 2 * aReportExpiry beforeEach(async () => { await sortedOracles.setTokenReportExpiry(aToken, anotherReportExpirt) }) it('returns the contract level one', async () => { assert.isTrue( (await sortedOracles.getTokenReportExpirySeconds(aToken)).eq(anotherReportExpirt) ) }) }) }) describe('#removeExpiredReports', () => { beforeEach(async () => { await sortedOracles.addOracle(aToken, anOracle) }) it('should revert when no report exists', async () => { await assertRevert(sortedOracles.removeExpiredReports(aToken, 1)) }) describe('when a report has been made', () => { beforeEach(async () => { await sortedOracles.report(aToken, toFixed(1), NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) }) it('should revert when only 1 report exists', async () => { await assertRevert(sortedOracles.removeExpiredReports(aToken, 1)) }) describe('when multiple reports have been made', () => { beforeEach(async () => { await timeTravel(aReportExpiry / 2, web3) for (let i = 7; i > 3; i--) { const anotherOracle = accounts[i] await sortedOracles.addOracle(aToken, anotherOracle) await sortedOracles.report(aToken, toFixed(2), anOracle, NULL_ADDRESS, { from: anotherOracle, }) } }) it('should do nothing when oldest report is not expired', async () => { await sortedOracles.removeExpiredReports(aToken, 3) assert.equal(await sortedOracles.numTimestamps.call(aToken), 5) }) it('should remove k and stop when k<n reports are expired', async () => { await timeTravel(aReportExpiry / 2, web3) await sortedOracles.removeExpiredReports(aToken, 3) assert.equal(await sortedOracles.numTimestamps.call(aToken), 4) }) it('should revert when n>=numTimestamps', async () => { await assertRevert(sortedOracles.removeExpiredReports(aToken, 5)) }) it('should remove n when n<numTimestamps reports are expired', async () => { await timeTravel(aReportExpiry, web3) await sortedOracles.removeExpiredReports(aToken, 3) assert.equal(await sortedOracles.numTimestamps.call(aToken), 2) }) }) }) }) describe('#isOldestReportExpired', () => { beforeEach(async () => { await sortedOracles.addOracle(aToken, anOracle) }) it('should return true if there are no reports', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isTrue(isReportExpired[0]) }) describe('when a report has been made', () => { beforeEach(async () => { await sortedOracles.report(aToken, toFixed(new BigNumber(1)), NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) }) describe('using the default expiry', () => { it('should return true if report is expired', async () => { await timeTravel(aReportExpiry, web3) const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isTrue(isReportExpired[0]) }) it('should return false if report is not expired', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isFalse(isReportExpired[0]) }) }) describe('when a per token expiry is set, which is greater than the default', () => { const tokenReportExpiry = 2 * aReportExpiry beforeEach(async () => { await sortedOracles.setTokenReportExpiry(aToken, tokenReportExpiry) }) describe('and no time has passed', () => { it('it should not be expired', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isFalse(isReportExpired[0]) }) }) describe('and the default expiry time has passed', () => { beforeEach(() => timeTravel(aReportExpiry, web3)) it('should return false', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isFalse(isReportExpired[0]) }) }) describe('and the token expiry time has passed', () => { beforeEach(() => timeTravel(tokenReportExpiry, web3)) it('should return true if the report is expired', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isTrue(isReportExpired[0]) }) }) }) describe('when a per token expiry is set, which is lower than the default', () => { const tokenReportExpiry = aReportExpiry / 2 beforeEach(async () => { await sortedOracles.setTokenReportExpiry(aToken, tokenReportExpiry) }) describe('and no time has passed', () => { it('it should not be expired', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isFalse(isReportExpired[0]) }) }) describe('and the default expiry time has passed', () => { beforeEach(() => timeTravel(aReportExpiry, web3)) it('should return true', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isTrue(isReportExpired[0]) }) }) describe('and the token expiry time has passed', () => { beforeEach(() => timeTravel(tokenReportExpiry, web3)) it('should return true if the report is expired', async () => { const isReportExpired = await sortedOracles.isOldestReportExpired(aToken) assert.isTrue(isReportExpired[0]) }) }) }) }) }) describe('#removeOracle', () => { beforeEach(async () => { await sortedOracles.addOracle(aToken, anOracle) }) it('should remove an Oracle', async () => { await sortedOracles.removeOracle(aToken, anOracle, 0) assert.isFalse(await sortedOracles.isOracle(aToken, anOracle)) }) describe('when there is more than one report made', () => { const anotherOracle = accounts[6] beforeEach(async () => { await sortedOracles.report(aToken, toFixed(1), NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) await sortedOracles.addOracle(aToken, anotherOracle) await sortedOracles.report(aToken, toFixed(5), anOracle, NULL_ADDRESS, { from: anotherOracle, }) }) it('should decrease the number of rates', async () => { await sortedOracles.removeOracle(aToken, anotherOracle, 1) assert.equal((await sortedOracles.numRates(aToken)).toNumber(), 1) }) it('should decrease the number of timestamps', async () => { await sortedOracles.removeOracle(aToken, anotherOracle, 1) assert.equal((await sortedOracles.numTimestamps(aToken)).toNumber(), 1) }) it('should emit the OracleRemoved, OracleReportRemoved and MedianUpdated events', async () => { const resp = await sortedOracles.removeOracle(aToken, anotherOracle, 1) assert.equal(resp.logs.length, 3) assertLogMatches2(resp.logs[0], { event: 'OracleReportRemoved', args: { oracle: matchAddress(anotherOracle), token: matchAddress(aToken), }, }) const medianUpdatedEvent = _.find(resp.logs, { event: 'MedianUpdated', }) assert.exists(medianUpdatedEvent) assertLogMatches2(resp.logs[2], { event: 'OracleRemoved', args: { token: matchAddress(aToken), oracleAddress: matchAddress(anotherOracle), }, }) }) }) describe('when there is a single report left', () => { beforeEach(async () => { await sortedOracles.report(aToken, toFixed(10), NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) }) it('should not decrease the number of rates', async () => { await sortedOracles.removeOracle(aToken, anOracle, 0) assert.equal((await sortedOracles.numRates(aToken)).toNumber(), 1) }) it('should not reset the median rate', async () => { const [actualNumeratorBefore] = await sortedOracles.medianRate(aToken) await sortedOracles.removeOracle(aToken, anOracle, 0) const [actualNumeratorAfter] = await sortedOracles.medianRate(aToken) assert.equal(actualNumeratorBefore.toNumber(), actualNumeratorAfter.toNumber()) }) it('should not decrease the number of timestamps', async () => { await sortedOracles.removeOracle(aToken, anOracle, 0) assert.equal((await sortedOracles.numTimestamps(aToken)).toNumber(), 1) }) it('should not reset the median timestamp', async () => { const medianTimestampBefore = await sortedOracles.medianTimestamp(aToken) await sortedOracles.removeOracle(aToken, anOracle, 0) const medianTimestampAfter = await sortedOracles.medianTimestamp(aToken) assert.equal(medianTimestampBefore.toNumber(), medianTimestampAfter.toNumber()) }) it('should not emit the OracleReportRemoved and MedianUpdated events, but the OracleRemoved', async () => { const resp = await sortedOracles.removeOracle(aToken, anOracle, 0) const oracleReportRemovedEvent = _.find(resp.logs, { event: 'OracleReportRemoved', }) assert.equal(oracleReportRemovedEvent, undefined) const medianUpdatedEvent = _.find(resp.logs, { event: 'MedianUpdated', }) assert.equal(medianUpdatedEvent, undefined) assertLogMatches2(resp.logs[0], { event: 'OracleRemoved', args: { token: matchAddress(aToken), oracleAddress: matchAddress(anOracle), }, }) }) }) it('should emit the OracleRemoved event', async () => { const resp = await sortedOracles.removeOracle(aToken, anOracle, 0) assert.equal(resp.logs.length, 1) const log = resp.logs[0] assertLogMatches2(log, { event: 'OracleRemoved', args: { token: matchAddress(aToken), oracleAddress: matchAddress(anOracle), }, }) }) it('should revert when the wrong index is provided', async () => { await assertRevert(sortedOracles.removeOracle(aToken, anOracle, 1)) }) it('should revert when the wrong address is provided', async () => { await assertRevert(sortedOracles.removeOracle(aToken, accounts[0], 0)) }) it('should revert when called by anyone other than the owner', async () => { await assertRevert(sortedOracles.removeOracle(aToken, anOracle, 0, { from: accounts[1] })) }) }) describe('#report', () => { const value = toFixed(10) beforeEach(async () => { await sortedOracles.addOracle(aToken, anOracle) }) it('should increase the number of rates', async () => { await sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) assert.equal((await sortedOracles.numRates(aToken)).toNumber(), 1) }) it('should set the median rate', async () => { await sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) const [actualNumerator, actualDenominator] = await sortedOracles.medianRate(aToken) assertEqualBN(actualNumerator, value) assertEqualBN(actualDenominator, fixed1) }) it('should increase the number of timestamps', async () => { await sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) assertEqualBN(await sortedOracles.numTimestamps(aToken), 1) }) it('should set the median timestamp', async () => { await sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) const blockTimestamp = (await web3.eth.getBlock('latest')).timestamp assert.equal((await sortedOracles.medianTimestamp(aToken)).toNumber(), blockTimestamp) }) it('should emit the OracleReported and MedianUpdated events', async () => { const resp = await sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) assert.equal(resp.logs.length, 2) assertLogMatches2(resp.logs[0], { event: 'OracleReported', args: { token: matchAddress(aToken), oracle: matchAddress(anOracle), timestamp: matchAny, value, }, }) assertLogMatches2(resp.logs[1], { event: 'MedianUpdated', args: { token: matchAddress(aToken), value, }, }) }) it('should revert when called by a non-oracle', async () => { await assertRevert(sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS)) }) describe('when there exists exactly one other report, made by this oracle', () => { const newValue = toFixed(12) beforeEach(async () => { await sortedOracles.report(aToken, value, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) }) it('should reset the median rate', async () => { const [initialNumerator, initialDenominator] = await sortedOracles.medianRate(aToken) assertEqualBN(initialNumerator, value) assertEqualBN(initialDenominator, fixed1) await sortedOracles.report(aToken, newValue, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) const [actualNumerator, actualDenominator] = await sortedOracles.medianRate(aToken) assertEqualBN(actualNumerator, newValue) assertEqualBN(actualDenominator, fixed1) }) it('should not change the number of total reports', async () => { const initialNumReports = await sortedOracles.numRates(aToken) await sortedOracles.report(aToken, newValue, NULL_ADDRESS, NULL_ADDRESS, { from: anOracle, }) assertEqualBN(initialNumReports, await sortedOracles.numRates(aToken)) }) }) describe('when there are multiple reports, the most recent one done by this oracle', () => { const anotherOracle = accounts[6] const anOracleValue1 = toFixed(2) const anOracleValue2 = toFixed(3) const anotherOracleValue = toFixed(1) beforeEach(async () => { await sortedOracles.addOracle(aToken, anotherOracle) await sortedOracles.report(aToken, anotherOracleValue, NULL_ADDRESS, NULL_ADDRESS, { from: anotherOracle, }) await timeTravel(5, web3) await sortedOracles.report(aToken, anOracleValue1, anotherOracle, NULL_ADDRESS, { from: anOracle, }) await timeTravel(5, web3) // confirm the setup worked const initialRates = await sortedOracles.getRates(aToken) assertEqualBN(initialRates['1'][0], anOracleValue1) assertEqualBN(initialRates['1'][1], anotherOracleValue) }) it('updates the list of rates correctly', async () => { await sortedOracles.report(aToken, anOracleValue2, anotherOracle, NULL_ADDRESS, { from: anOracle, }) const resultRates = await sortedOracles.getRates(aToken) assertEqualBN(resultRates['1'][0], anOracleValue2) assertEqualBN(resultRates['1'][1], anotherOracleValue) }) it('updates the latest timestamp', async () => { const initialTimestamps = await sortedOracles.getTimestamps(aToken) await sortedOracles.report(aToken, anOracleValue2, anotherOracle, NULL_ADDRESS, { from: anOracle, }) const resultTimestamps = await sortedOracles.getTimestamps(aToken) // the second timestamp, belonging to anotherOracle should be unchanged assertEqualBN(initialTimestamps['1']['1'], resultTimestamps['1']['1']) // the most recent timestamp, belonging to anOracle in both cases, should change assert.isTrue(resultTimestamps['1']['0'].gt(initialTimestamps['1']['0'])) }) }) }) })
the_stack
import { afterEach, describe, expect, it } from 'vitest'; import { faker } from '../src'; import { times } from './support/times'; function degreesToRadians(degrees: number) { return degrees * (Math.PI / 180.0); } function kilometersToMiles(miles: number) { return miles * 0.621371; } // http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html const EQUATORIAL_EARTH_RADIUS = 6378.137; function haversine( latitude1: number, longitude1: number, latitude2: number, longitude2: number, isMetric: boolean ) { const distanceLatitude = degreesToRadians(latitude2 - latitude1); const distanceLongitude = degreesToRadians(longitude2 - longitude1); const a = Math.sin(distanceLatitude / 2) * Math.sin(distanceLatitude / 2) + Math.cos(degreesToRadians(latitude1)) * Math.cos(degreesToRadians(latitude2)) * Math.sin(distanceLongitude / 2) * Math.sin(distanceLongitude / 2); const distance = EQUATORIAL_EARTH_RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return isMetric ? distance : kilometersToMiles(distance); } const seededRuns = [ { seed: 42, expectations: { city: 'Port Valentine', cityPrefix: 'West', citySuffix: 'bury', cityName: 'Gulfport', streetName: 'Peyton Village', streetPrefix: 'b', streetSuffix: 'Isle', streetAddress: '7917 Metz Pine', fullStreetAddress: '7917 Metz Pine Apt. 410', secondaryAddress: 'Apt. 791', county: 'Berkshire', country: 'Haiti', countryCode: 'GY', state: 'Maine', stateAbbr: 'ME', zipCode: '79177', direction: 'South', directionNonAbbr: 'South', directionAbbr: 'S', ordinalDirection: 'Northwest', ordinalDirectionAbbr: 'NW', cardinalDirection: 'East', cardinalDirectionAbbr: 'E', timeZone: 'Europe/Amsterdam', nearbyGpsCoordinates: ['0.0814', '-0.0809'], }, }, { seed: 1337, expectations: { city: 'New Carmelo', cityPrefix: 'West', citySuffix: 'boro', cityName: 'Dubuque', streetName: 'Keith Dam', streetPrefix: 'a', streetSuffix: 'Forks', streetAddress: '51225 Alexys Haven', fullStreetAddress: '51225 Alexys Haven Apt. 552', secondaryAddress: 'Apt. 512', county: 'Bedfordshire', country: 'Equatorial Guinea', countryCode: 'EH', state: 'Indiana', stateAbbr: 'IN', zipCode: '51225', direction: 'South', directionNonAbbr: 'South', directionAbbr: 'S', ordinalDirection: 'Northwest', ordinalDirectionAbbr: 'NW', cardinalDirection: 'East', cardinalDirectionAbbr: 'E', timeZone: 'Africa/Casablanca', nearbyGpsCoordinates: ['0.0806', '-0.0061'], }, }, { seed: 1211, expectations: { city: 'La Crosse', cityPrefix: 'Fort', citySuffix: 'shire', cityName: 'Urbana', streetName: 'Koch Turnpike', streetPrefix: 'c', streetSuffix: 'Via', streetAddress: '487 Breana Wells', fullStreetAddress: '487 Breana Wells Apt. 616', secondaryAddress: 'Suite 487', county: 'Cambridgeshire', country: 'Uganda', countryCode: 'UM', state: 'Washington', stateAbbr: 'WA', zipCode: '48721-9061', direction: 'Southwest', directionNonAbbr: 'Southwest', directionAbbr: 'SW', ordinalDirection: 'Southwest', ordinalDirectionAbbr: 'SW', cardinalDirection: 'West', cardinalDirectionAbbr: 'W', timeZone: 'Asia/Magadan', nearbyGpsCoordinates: ['-0.0287', '0.0596'], }, }, ]; const NON_SEEDED_BASED_RUN = 5; const functionNames = [ 'city', 'cityPrefix', 'citySuffix', 'cityName', 'streetName', 'streetPrefix', 'streetSuffix', 'secondaryAddress', 'county', 'country', 'countryCode', 'state', 'stateAbbr', 'zipCode', 'timeZone', ]; describe('address', () => { afterEach(() => { faker.locale = 'en'; }); for (const { seed, expectations } of seededRuns) { describe(`seed: ${seed}`, () => { for (const functionName of functionNames) { it(`${functionName}()`, () => { faker.seed(seed); const actual = faker.address[functionName](); expect(actual).toBe(expectations[functionName]); }); } describe('streetAddress()', () => { it('should return street name with a building number', () => { faker.seed(seed); const address = faker.address.streetAddress(); expect(address).toStrictEqual(expectations.streetAddress); }); it('should return street name with a building number and a secondary address', () => { faker.seed(seed); const address = faker.address.streetAddress(true); expect(address).toEqual(expectations.fullStreetAddress); }); }); describe('direction()', () => { it('returns random direction', () => { faker.seed(seed); const direction = faker.address.direction(); const expected = expectations.direction; expect( direction, `The random direction should be equal to ${expected}` ).toBe(expected); }); it('should not return abbreviation when useAbbr is false', () => { faker.seed(seed); const direction = faker.address.direction(false); const expected = expectations.directionNonAbbr; expect( direction, `The abbreviation of direction when useAbbr is false should be equal ${expected}. Current is ${direction}` ).toBe(expected); }); it('returns abbreviation when useAbbr is true', () => { faker.seed(seed); const direction = faker.address.direction(true); const expected = expectations.directionAbbr; expect( direction, `The abbreviation of direction when useAbbr is true should be equal ${expected}. Current is ${direction}` ).toBe(expected); }); }); describe('ordinalDirection()', () => { it('returns random ordinal direction', () => { faker.seed(seed); const ordinalDirection = faker.address.ordinalDirection(); const expected = expectations.ordinalDirection; expect( ordinalDirection, `The ransom ordinal direction should be equal ${expected}. Current is ${ordinalDirection}` ).toBe(expected); }); it('returns abbreviation when useAbbr is true', () => { faker.seed(seed); const ordinalDirection = faker.address.ordinalDirection(true); const expected = expectations.ordinalDirectionAbbr; expect( ordinalDirection, `The ordinal direction when useAbbr is true should be equal ${expected}. Current is ${ordinalDirection}` ).toBe(expected); }); }); describe('cardinalDirection()', () => { it('returns random cardinal direction', () => { faker.seed(seed); const cardinalDirection = faker.address.cardinalDirection(); const expected = expectations.cardinalDirection; expect( cardinalDirection, `The random cardinal direction should be equal ${expected}. Current is ${cardinalDirection}` ).toBe(expected); }); it('returns abbreviation when useAbbr is true', () => { faker.seed(seed); const cardinalDirection = faker.address.cardinalDirection(true); const expected = expectations.cardinalDirectionAbbr; expect( cardinalDirection, `The cardinal direction when useAbbr is true should be equal ${expected}. Current is ${cardinalDirection}` ).toBe(expected); }); }); describe('nearbyGPSCoordinate()', () => { it('returns expected coordinates', () => { faker.seed(seed); // this input is required for all expected results for this function const coordsInput: [number, number] = [0, 0]; const coords = faker.address.nearbyGPSCoordinate(coordsInput); expect(coords).toEqual(expectations.nearbyGpsCoordinates); }); }); }); } describe(`random seeded tests for seed ${JSON.stringify( faker.seed() )}`, () => { for (let i = 1; i <= NON_SEEDED_BASED_RUN; i++) { describe('countryCode()', () => { it('returns random alpha-3 countryCode', () => { const countryCode = faker.address.countryCode('alpha-3'); expect(countryCode).toBeTruthy(); expect( countryCode.length, 'The countryCode should be 3 characters long' ).toBe(3); }); }); describe('zipCode()', () => { it('returns random zipCode - user specified format', () => { let zipCode = faker.address.zipCode('?#? #?#'); expect(zipCode).toMatch(/^[A-Za-z]\d[A-Za-z]\s\d[A-Za-z]\d$/); // try another format zipCode = faker.address.zipCode('###-###'); expect(zipCode).toMatch(/^\d{3}-\d{3}$/); }); it('returns zipCode with proper locale format', () => { // we'll use the en_CA locale.. faker.locale = 'en_CA'; const zipCode = faker.address.zipCode(); expect(zipCode).toMatch(/^[A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d$/); }); }); describe('zipCodeByState()', () => { it('returns zipCode valid for specified State', () => { faker.locale = 'en_US'; const states = ['IL', 'GA', 'WA']; const zipCode1 = +faker.address.zipCodeByState(states[0]); expect(zipCode1).toBeGreaterThanOrEqual(60001); expect(zipCode1).toBeLessThanOrEqual(62999); const zipCode2 = +faker.address.zipCodeByState(states[1]); expect(zipCode2).toBeGreaterThanOrEqual(30001); expect(zipCode2).toBeLessThanOrEqual(31999); const zipCode3 = +faker.address.zipCodeByState(states[2]); expect(zipCode3).toBeGreaterThanOrEqual(98001); expect(zipCode3).toBeLessThanOrEqual(99403); }); }); describe('latitude()', () => { it('returns random latitude', () => { for (let i = 0; i < 100; i++) { const latitude = faker.address.latitude(); expect(latitude).toBeTypeOf('string'); const latitude_float = parseFloat(latitude); expect(latitude_float).toBeGreaterThanOrEqual(-90.0); expect(latitude_float).toBeLessThanOrEqual(90.0); } }); it('returns latitude with min and max and default precision', () => { for (let i = 0; i < 100; i++) { const latitude = faker.address.latitude(5, -5); expect(latitude).toBeTypeOf('string'); expect( latitude.split('.')[1].length, 'The precision of latitude should be 4 digits' ).toBe(4); const latitude_float = parseFloat(latitude); expect(latitude_float).toBeGreaterThanOrEqual(-5); expect(latitude_float).toBeLessThanOrEqual(5); } }); it('returns random latitude with custom precision', () => { for (let i = 0; i < 100; i++) { const latitude = faker.address.latitude(undefined, undefined, 7); expect(latitude).toBeTypeOf('string'); expect( latitude.split('.')[1].length, 'The precision of latitude should be 7 digits' ).toBe(7); const latitude_float = parseFloat(latitude); expect(latitude_float).toBeGreaterThanOrEqual(-180); expect(latitude_float).toBeLessThanOrEqual(180); } }); }); describe('longitude()', () => { it('returns random longitude', () => { for (let i = 0; i < 100; i++) { const longitude = faker.address.longitude(); expect(longitude).toBeTypeOf('string'); const longitude_float = parseFloat(longitude); expect(longitude_float).toBeGreaterThanOrEqual(-180); expect(longitude_float).toBeLessThanOrEqual(180); } }); it('returns random longitude with min and max and default precision', () => { for (let i = 0; i < 100; i++) { const longitude = faker.address.longitude(100, -30); expect(longitude).toBeTypeOf('string'); expect( longitude.split('.')[1].length, 'The precision of longitude should be 4 digits' ).toBe(4); const longitude_float = parseFloat(longitude); expect(longitude_float).toBeGreaterThanOrEqual(-30); expect(longitude_float).toBeLessThanOrEqual(100); } }); it('returns random longitude with custom precision', () => { for (let i = 0; i < 100; i++) { const longitude = faker.address.longitude(undefined, undefined, 7); expect(longitude).toBeTypeOf('string'); expect( longitude.split('.')[1].length, 'The precision of longitude should be 7 digits' ).toBe(7); const longitude_float = parseFloat(longitude); expect(longitude_float).toBeGreaterThanOrEqual(-180); expect(longitude_float).toBeLessThanOrEqual(180); } }); }); describe('direction()', () => { it('returns abbreviation when useAbbr is true', () => { const direction = faker.address.direction(true); const lengthDirection = direction.length; const prefixErrorMessage = 'The abbreviation of direction when useAbbr is true should'; expect( direction, `${prefixErrorMessage} be of type string. Current is ${typeof direction}` ).toBeTypeOf('string'); expect(lengthDirection).toBeLessThanOrEqual(2); }); }); describe('ordinalDirection()', () => { it('returns abbreviation when useAbbr is true', () => { const ordinalDirection = faker.address.ordinalDirection(true); const expectedType = 'string'; const ordinalDirectionLength = ordinalDirection.length; const prefixErrorMessage = 'The ordinal direction when useAbbr is true should'; expect( ordinalDirection, `${prefixErrorMessage} be equal ${expectedType}. Current is ${typeof ordinalDirection}` ).toBeTypeOf(expectedType); expect(ordinalDirectionLength).toBeLessThanOrEqual(2); }); }); describe('cardinalDirection()', () => { it('returns abbreviation when useAbbr is true', () => { const cardinalDirection = faker.address.cardinalDirection(true); const expectedType = 'string'; const cardinalDirectionLength = cardinalDirection.length; const prefixErrorMessage = 'The cardinal direction when useAbbr is true should'; expect( cardinalDirection, `${prefixErrorMessage} be of type ${expectedType}. Current is ${typeof cardinalDirection}` ).toBeTypeOf(expectedType); expect(cardinalDirectionLength).toBeLessThanOrEqual(2); }); }); describe('nearbyGPSCoordinate()', () => { for (const isMetric of [true, false]) { for (const radius of times(100)) { it.each(times(5))( `should return random gps coordinate within a distance of another one (${JSON.stringify( { isMetric, radius } )}) (iter: %s)`, () => { const latitude1 = +faker.address.latitude(); const longitude1 = +faker.address.longitude(); const coordinate = faker.address.nearbyGPSCoordinate( [latitude1, longitude1], radius, isMetric ); expect(coordinate.length).toBe(2); expect(coordinate[0]).toBeTypeOf('string'); expect(coordinate[1]).toBeTypeOf('string'); const latitude2 = +coordinate[0]; expect(latitude2).toBeGreaterThanOrEqual(-90.0); expect(latitude2).toBeLessThanOrEqual(90.0); const longitude2 = +coordinate[1]; expect(longitude2).toBeGreaterThanOrEqual(-180.0); expect(longitude2).toBeLessThanOrEqual(180.0); const actualDistance = haversine( latitude1, longitude1, latitude2, longitude2, isMetric ); expect(actualDistance).toBeLessThanOrEqual(radius); } ); } } }); } }); });
the_stack
import { CancellationToken } from 'vscode-languageserver'; import * as AnalyzerNodeInfo from '../analyzer/analyzerNodeInfo'; import { AliasDeclaration, Declaration, DeclarationType, FunctionDeclaration, isAliasDeclaration, isFunctionDeclaration, } from '../analyzer/declaration'; import { areDeclarationsSame, createSynthesizedAliasDeclaration, getDeclarationsWithUsesLocalNameRemoved, } from '../analyzer/declarationUtils'; import { getModuleNode, getStringNodeValueRange } from '../analyzer/parseTreeUtils'; import * as ParseTreeUtils from '../analyzer/parseTreeUtils'; import { ParseTreeWalker } from '../analyzer/parseTreeWalker'; import * as ScopeUtils from '../analyzer/scopeUtils'; import { isStubFile, SourceMapper } from '../analyzer/sourceMapper'; import { TypeEvaluator } from '../analyzer/typeEvaluatorTypes'; import { isInstantiableClass, TypeCategory } from '../analyzer/types'; import { ClassMemberLookupFlags, lookUpClassMember } from '../analyzer/typeUtils'; import { throwIfCancellationRequested } from '../common/cancellationUtils'; import { appendArray } from '../common/collectionUtils'; import { assert } from '../common/debug'; import { TextRange } from '../common/textRange'; import { ImportAsNode, NameNode, ParseNode, ParseNodeType, StringNode } from '../parser/parseNodes'; export type CollectionResult = { node: NameNode | StringNode; range: TextRange; }; // This walker looks for symbols that are semantically equivalent // to the requested symbol. export class DocumentSymbolCollector extends ParseTreeWalker { static collectFromNode( node: NameNode, evaluator: TypeEvaluator, cancellationToken: CancellationToken, startingNode?: ParseNode, treatModuleInImportAndFromImportSame = false, skipUnreachableCode = true ): CollectionResult[] { const symbolName = node.value; const declarations = this.getDeclarationsForNode( node, evaluator, /* resolveLocalName */ true, cancellationToken ); startingNode = startingNode ?? getModuleNode(node); if (!startingNode) { return []; } const collector = new DocumentSymbolCollector( symbolName, declarations, evaluator, cancellationToken, startingNode, treatModuleInImportAndFromImportSame, skipUnreachableCode ); return collector.collect(); } static getDeclarationsForNode( node: NameNode, evaluator: TypeEvaluator, resolveLocalName: boolean, token: CancellationToken, sourceMapper?: SourceMapper ): Declaration[] { throwIfCancellationRequested(token); const declarations = this._getDeclarationsForNode(node, evaluator); const resolvedDeclarations: Declaration[] = []; declarations.forEach((decl) => { const resolvedDecl = evaluator.resolveAliasDeclaration(decl, resolveLocalName); if (resolvedDecl) { resolvedDeclarations.push(resolvedDecl); if (sourceMapper && isStubFile(resolvedDecl.path)) { const implDecls = sourceMapper.findDeclarations(resolvedDecl); for (const implDecl of implDecls) { if (implDecl && implDecl.path) { this._addIfUnique(resolvedDeclarations, implDecl); } } } } }); return resolvedDeclarations; } private _results: CollectionResult[] = []; private _dunderAllNameNodes = new Set<StringNode>(); constructor( private _symbolName: string, private _declarations: Declaration[], private _evaluator: TypeEvaluator, private _cancellationToken: CancellationToken, private _startingNode: ParseNode, private _treatModuleInImportAndFromImportSame = false, private _skipUnreachableCode = true ) { super(); // Don't report strings in __all__ right away, that will // break the assumption on the result ordering. this._setDunderAllNodes(this._startingNode); } collect() { this.walk(this._startingNode); return this._results; } override walk(node: ParseNode) { if (!this._skipUnreachableCode || !AnalyzerNodeInfo.isCodeUnreachable(node)) { super.walk(node); } } override visitName(node: NameNode): boolean { throwIfCancellationRequested(this._cancellationToken); // No need to do any more work if the symbol name doesn't match. if (node.value !== this._symbolName) { return false; } if (this._declarations.length > 0) { const declarations = DocumentSymbolCollector._getDeclarationsForNode( node, this._evaluator, this._skipUnreachableCode ); if (declarations && declarations.length > 0) { // Does this name share a declaration with the symbol of interest? if (declarations.some((decl) => this._resultsContainsDeclaration(decl))) { this._addResult(node); } } } else { // There were no declarations this._addResult(node); } return false; } override visitString(node: StringNode): boolean { throwIfCancellationRequested(this._cancellationToken); if (this._dunderAllNameNodes.has(node)) { this._addResult(node); } return false; } private _addResult(node: NameNode | StringNode) { const range: TextRange = node.nodeType === ParseNodeType.Name ? node : getStringNodeValueRange(node); this._results.push({ node, range }); } private _resultsContainsDeclaration(declaration: Declaration) { // Resolve the declaration. const resolvedDecl = this._evaluator.resolveAliasDeclaration(declaration, /* resolveLocalNames */ false); if (!resolvedDecl) { return false; } // The reference results declarations are already resolved, so we don't // need to call resolveAliasDeclaration on them. if ( this._declarations.some((decl) => areDeclarationsSame(decl, resolvedDecl, this._treatModuleInImportAndFromImportSame) ) ) { return true; } // We didn't find the declaration using local-only alias resolution. Attempt // it again by fully resolving the alias. const resolvedDeclNonlocal = this._getResolveAliasDeclaration(resolvedDecl); if (!resolvedDeclNonlocal || resolvedDeclNonlocal === resolvedDecl) { return false; } return this._declarations.some((decl) => areDeclarationsSame(decl, resolvedDeclNonlocal, this._treatModuleInImportAndFromImportSame) ); } private _getResolveAliasDeclaration(declaration: Declaration) { // TypeEvaluator.resolveAliasDeclaration only resolve alias in AliasDeclaration in the form of // "from x import y as [y]" but don't do thing for alias in "import x as [x]" // Here, alias should have same name as module name. if (isAliasDeclFromImportAsWithAlias(declaration)) { return getDeclarationsWithUsesLocalNameRemoved([declaration])[0]; } const resolvedDecl = this._evaluator.resolveAliasDeclaration(declaration, /* resolveLocalNames */ true); return isAliasDeclFromImportAsWithAlias(resolvedDecl) ? getDeclarationsWithUsesLocalNameRemoved([resolvedDecl])[0] : resolvedDecl; function isAliasDeclFromImportAsWithAlias(decl?: Declaration): decl is AliasDeclaration { return ( !!decl && decl.type === DeclarationType.Alias && decl.node && decl.usesLocalName && decl.node.nodeType === ParseNodeType.ImportAs ); } } private _setDunderAllNodes(node: ParseNode) { if (node.nodeType !== ParseNodeType.Module) { return; } const dunderAllInfo = AnalyzerNodeInfo.getDunderAllInfo(node); if (!dunderAllInfo) { return; } const moduleScope = ScopeUtils.getScopeForNode(node); if (!moduleScope) { return; } dunderAllInfo.stringNodes.forEach((stringNode) => { if (stringNode.value !== this._symbolName) { return; } const symbolInScope = moduleScope.lookUpSymbolRecursive(stringNode.value); if (!symbolInScope) { return; } if (!symbolInScope.symbol.getDeclarations().some((d) => this._resultsContainsDeclaration(d))) { return; } this._dunderAllNameNodes.add(stringNode); }); } private static _addIfUnique(declarations: Declaration[], itemToAdd: Declaration) { for (const def of declarations) { if (areDeclarationsSame(def, itemToAdd)) { return; } } declarations.push(itemToAdd); } private static _getDeclarationsForNode( node: NameNode, evaluator: TypeEvaluator, skipUnreachableCode = true ): Declaration[] { // This can handle symbols brought in by wildcard (import *) as long as the declarations that the symbol collector // compares against point to the actual alias declaration, not one that uses local name (ex, import alias) if (node.parent?.nodeType !== ParseNodeType.ModuleName) { return this._getDeclarationsForNonModuleNameNode(node, evaluator, skipUnreachableCode); } return this._getDeclarationsForModuleNameNode(node, evaluator); } private static _getDeclarationsForNonModuleNameNode( node: NameNode, evaluator: TypeEvaluator, skipUnreachableCode = true ): Declaration[] { assert(node.parent?.nodeType !== ParseNodeType.ModuleName); let decls = evaluator.getDeclarationsForNameNode(node, skipUnreachableCode) || []; if (node.parent?.nodeType === ParseNodeType.ImportFromAs) { // Make sure we get the decl for this specific "from import" statement decls = decls.filter((d) => d.node === node.parent); } // If we can't get decl, see whether we can get type from the node. // Some might have synthesized type for the node such as subModule in import X.Y statement. if (decls.length === 0) { const type = evaluator.getType(node); if (type?.category === TypeCategory.Module) { // Synthesize decl for the module. return [createSynthesizedAliasDeclaration(type.filePath)]; } } // We would like to make X in import X and import X.Y as Y to match, but path for // X in import X and one in import X.Y as Y might not match since path in X.Y will point // to X.Y rather than X if import statement has an alias. // so, for such case, we put synthesized one so we can treat X in both statement same. for (const aliasDecl of decls.filter((d) => isAliasDeclaration(d) && !d.loadSymbolsFromPath)) { const node = (aliasDecl as AliasDeclaration).node; if (node.nodeType === ParseNodeType.ImportFromAs) { // from ... import X case, decl in the submodule fallback has the path. continue; } decls.push(...(evaluator.getDeclarationsForNameNode(node.module.nameParts[0], skipUnreachableCode) || [])); } // For now, we only support function overriding. for (const decl of decls.filter( (d) => isFunctionDeclaration(d) && d.isMethod && d.node.name.value.length > 0 )) { const methodDecl = decl as FunctionDeclaration; const enclosingClass = ParseTreeUtils.getEnclosingClass(methodDecl.node); const classResults = enclosingClass ? evaluator.getTypeOfClass(enclosingClass) : undefined; if (!classResults) { continue; } for (const mroClass of classResults.classType.details.mro) { if (isInstantiableClass(mroClass)) { const currentMember = lookUpClassMember(mroClass, methodDecl.node.name.value); const baseMember = lookUpClassMember( mroClass, methodDecl.node.name.value, ClassMemberLookupFlags.SkipOriginalClass ); if (currentMember && !baseMember) { // Found base decl of the overridden method. Hold onto the decls. currentMember.symbol .getDeclarations() .filter((d) => isFunctionDeclaration(d) && d.isMethod) .forEach((d) => this._addIfUnique(decls, d)); } } } } return decls; } private static _getDeclarationsForModuleNameNode(node: NameNode, evaluator: TypeEvaluator): Declaration[] { assert(node.parent?.nodeType === ParseNodeType.ModuleName); // We don't have symbols corresponding to ModuleName in our system since those // are not referenceable. but in "find all reference", we want to match those // if it refers to the same module file. Code below handles different kind of // ModuleName cases. const moduleName = node.parent; if ( moduleName.parent?.nodeType === ParseNodeType.ImportAs || moduleName.parent?.nodeType === ParseNodeType.ImportFrom ) { const index = moduleName.nameParts.findIndex((n) => n === node); // Special case, first module name part. if (index === 0) { // 1. import X or from X import ... const decls: Declaration[] = []; // First, we need to put decls for module names type evaluator synthesized so that // we can match both "import X" and "from X import ..." decls.push( ...(evaluator .getDeclarationsForNameNode(moduleName.nameParts[0]) ?.filter((d) => isAliasDeclaration(d)) || []) ); if (decls.length === 0) { return decls; } // ex, import X as x const isImportAsWithAlias = moduleName.nameParts.length === 1 && moduleName.parent.nodeType === ParseNodeType.ImportAs && !!moduleName.parent.alias; // if "import" has alias, symbol is assigned to alias, not the module. const importName = isImportAsWithAlias ? (moduleName.parent as ImportAsNode).alias!.value : moduleName.nameParts[0].value; // And we also need to re-use "decls for X" binder has created // so that it matches with decls type evaluator returns for "references for X". // ex) import X or from .X import ... in init file and etc. const symbolWithScope = ScopeUtils.getScopeForNode(node)?.lookUpSymbolRecursive(importName); if (symbolWithScope && moduleName.nameParts.length === 1) { let declsFromSymbol: Declaration[] = []; appendArray( declsFromSymbol, symbolWithScope.symbol.getDeclarations().filter((d) => isAliasDeclaration(d)) ); // If symbols are re-used, then find one that belong to this import statement. if (declsFromSymbol.length > 1) { declsFromSymbol = declsFromSymbol.filter((d) => { d = d as AliasDeclaration; if (d.firstNamePart !== undefined) { // For multiple import statements with sub modules, decl can be re-used. // ex) import X.Y and import X.Z or from .X import ... in init file. // Decls for X will be reused for both import statements, and node will point // to first import statement. For those case, use firstNamePart instead to check. return d.firstNamePart === moduleName.nameParts[0].value; } return d.node === moduleName.parent; }); } // ex, import X as x // We have decls for the alias "x" not the module name "X". Convert decls for the "X" if (isImportAsWithAlias) { declsFromSymbol = getDeclarationsWithUsesLocalNameRemoved(declsFromSymbol); } decls.push(...declsFromSymbol); } return decls; } if (index > 0) { // 2. import X.Y or from X.Y import .... // For submodule "Y", we just use synthesized decls from type evaluator. // Decls for these sub module don't actually exist in the system. Instead, symbol for Y in // "import X.Y" hold onto synthesized module type (without any decl). // And "from X.Y import ..." doesn't have any symbol associated module names. // they can't be referenced in the module. return evaluator.getDeclarationsForNameNode(moduleName.nameParts[index]) || []; } return []; } return []; } }
the_stack
import * as fs from "fs"; import * as path from "path"; import * as util from "util"; import { ANTLRInputStream } from "../src/ANTLRInputStream"; import { CharStream } from "../src/CharStream"; import { CharStreams } from "../src/CharStreams"; import { CommonTokenStream } from "../src/CommonTokenStream"; import { GraphemesLexer } from "./gen/GraphemesLexer"; import { JavaLexer } from "./gen/std/JavaLexer"; import { Lexer } from "../src/Lexer"; import { Stopwatch } from "./Stopwatch"; import { TimeSpan } from "./TimeSpan"; function padStart(str: string, n: number): string { if (str.length < n) { str = " ".repeat(n - str.length) + str; } return str; } /** * Test how fast we can lex Java and some unicode graphemes using old and * new unicode stream mechanism. It also tests load time for unicode code points beyond 0xFFFF. * * Sample output on Linux with Intel Xeon E5-2600 @ 2.20 GHz (us == microseconds, 1/1000 of a millisecond): * * ``` * Java VM args: * Warming up Java compiler.... * load_legacy_java_utf8 average time 273us size 132266b over 3500 loads of 29038 symbols from Parser.java * load_legacy_java_utf8 average time 299us size 128386b over 3500 loads of 13379 symbols from udhr_hin.txt * load_new_utf8 average time 535us size 284788b over 3500 loads of 29038 symbols from Parser.java * load_new_utf8 average time 439us size 153150b over 3500 loads of 13379 symbols from udhr_hin.txt * * lex_legacy_java_utf8 average time 624us over 2000 runs of 29038 symbols * lex_legacy_java_utf8 average time 1530us over 2000 runs of 29038 symbols DFA cleared * lex_new_java_utf8 average time 672us over 2000 runs of 29038 symbols * lex_new_java_utf8 average time 1671us over 2000 runs of 29038 symbols DFA cleared * * lex_legacy_grapheme_utf8 average time 11942us over 400 runs of 6614 symbols from udhr_kor.txt * lex_legacy_grapheme_utf8 average time 12075us over 400 runs of 6614 symbols from udhr_kor.txt DFA cleared * lex_legacy_grapheme_utf8 average time 10040us over 400 runs of 13379 symbols from udhr_hin.txt * lex_legacy_grapheme_utf8 average time 10221us over 400 runs of 13379 symbols from udhr_hin.txt DFA cleared * ``` * * Sample output on OS X with 4 GHz Intel Core i7 (us == microseconds, 1/1000 of a millisecond): * * ``` * Java VM args: -Xms2G -Xmx2G * Warming up Java compiler.... * load_legacy_java_ascii_file average time 53us size 58384b over 3500 loads of 29038 symbols from Parser.java * load_legacy_java_ascii_file average time 27us size 15568b over 3500 loads of 7625 symbols from RuleContext.java * load_legacy_java_ascii average time 53us size 65584b over 3500 loads of 29038 symbols from Parser.java * load_legacy_java_ascii average time 13us size 32816b over 3500 loads of 7625 symbols from RuleContext.java * load_legacy_java_utf8 average time 54us size 65584b over 3500 loads of 29038 symbols from Parser.java * load_legacy_java_utf8 average time 118us size 32816b over 3500 loads of 13379 symbols from udhr_hin.txt * load_new_utf8 average time 232us size 131232b over 3500 loads of 29038 symbols from Parser.java * load_new_utf8 average time 69us size 32928b over 3500 loads of 7625 symbols from RuleContext.java * load_new_utf8 average time 210us size 65696b over 3500 loads of 13379 symbols from udhr_hin.txt * * lex_legacy_java_utf8 average time 342us over 2000 runs of 29038 symbols * lex_legacy_java_utf8 average time 890us over 2000 runs of 29038 symbols DFA cleared * lex_new_java_utf8 average time 439us over 2000 runs of 29038 symbols * lex_new_java_utf8 average time 969us over 2000 runs of 29038 symbols DFA cleared * * lex_legacy_grapheme_utf8 average time 3971us over 400 runs of 6614 symbols from udhr_kor.txt * lex_legacy_grapheme_utf8 average time 4084us over 400 runs of 6614 symbols from udhr_kor.txt DFA cleared * lex_legacy_grapheme_utf8 average time 7542us over 400 runs of 13379 symbols from udhr_hin.txt * lex_legacy_grapheme_utf8 average time 7666us over 400 runs of 13379 symbols from udhr_hin.txt DFA cleared * lex_new_grapheme_utf8 average time 4034us over 400 runs of 6614 symbols from udhr_kor.txt * lex_new_grapheme_utf8 average time 4173us over 400 runs of 6614 symbols from udhr_kor.txt DFA cleared * lex_new_grapheme_utf8 average time 7680us over 400 runs of 13379 symbols from udhr_hin.txt * lex_new_grapheme_utf8 average time 7946us over 400 runs of 13379 symbols from udhr_hin.txt DFA cleared * lex_new_grapheme_utf8 average time 70us over 400 runs of 85 symbols from emoji.txt * lex_new_grapheme_utf8 average time 82us over 400 runs of 85 symbols from emoji.txt DFA cleared * ``` * * I dump footprint now too (this is 64-bit HotSpot VM): * * ``` * Parser.java (29038 char): org.antlr.v4.runtime.ANTLRFileStream@6b8e0782d footprint: * COUNT AVG SUM DESCRIPTION * 2 29164 58328 [C * 1 24 24 java.lang.String * 1 32 32 org.antlr.v4.runtime.ANTLRFileStream * 4 58384 (total) * * RuleContext.java (7625 char): org.antlr.v4.runtime.ANTLRFileStream@76fb7505d footprint: * COUNT AVG SUM DESCRIPTION * 2 7756 15512 [C * 1 24 24 java.lang.String * 1 32 32 org.antlr.v4.runtime.ANTLRFileStream * 4 15568 (total) * * Parser.java (29038 char): org.antlr.v4.runtime.ANTLRInputStream@1fc1cb1d footprint: * COUNT AVG SUM DESCRIPTION * 1 65552 65552 [C * 1 32 32 org.antlr.v4.runtime.ANTLRInputStream * 2 65584 (total) * * RuleContext.java (7625 char): org.antlr.v4.runtime.ANTLRInputStream@2c6aa25dd footprint: * COUNT AVG SUM DESCRIPTION * 1 32784 32784 [C * 1 32 32 org.antlr.v4.runtime.ANTLRInputStream * 2 32816 (total) * * Parser.java (29038 char): org.antlr.v4.runtime.ANTLRInputStream@3d08db0bd footprint: * COUNT AVG SUM DESCRIPTION * 1 65552 65552 [C * 1 32 32 org.antlr.v4.runtime.ANTLRInputStream * 2 65584 (total) * * udhr_hin.txt (13379 char): org.antlr.v4.runtime.ANTLRInputStream@486dc6f3d footprint: * COUNT AVG SUM DESCRIPTION * 1 32784 32784 [C * 1 32 32 org.antlr.v4.runtime.ANTLRInputStream * 2 32816 (total) * * Parser.java (29038 char): org.antlr.v4.runtime.CodePointCharStream@798fe5a1d footprint: * COUNT AVG SUM DESCRIPTION * 1 40 40 [C * 1 131088 131088 [I * 1 24 24 java.lang.String * 1 48 48 java.nio.HeapIntBuffer * 1 32 32 org.antlr.v4.runtime.CodePointCharStream * 5 131232 (total) * * RuleContext.java (7625 char): org.antlr.v4.runtime.CodePointCharStream@29cf5a20d footprint: * COUNT AVG SUM DESCRIPTION * 1 40 40 [C * 1 32784 32784 [I * 1 24 24 java.lang.String * 1 48 48 java.nio.HeapIntBuffer * 1 32 32 org.antlr.v4.runtime.CodePointCharStream * 5 32928 (total) * * udhr_hin.txt (13379 char): org.antlr.v4.runtime.CodePointCharStream@1adb8a22d footprint: * COUNT AVG SUM DESCRIPTION * 1 40 40 [C * 1 65552 65552 [I * 1 24 24 java.lang.String * 1 48 48 java.nio.HeapIntBuffer * 1 32 32 org.antlr.v4.runtime.CodePointCharStream * 5 65696 (total) * ``` * * The "DFA cleared" indicates that the lexer was returned to initial conditions * before the tokenizing of each file. As the ALL(*) lexer encounters new input, * it records how it tokenized the chars. The next time it sees that input, * it will more quickly recognize the token. * * Lexing times have the top 20% stripped off before doing the average * to account for issues with the garbage collection and compilation pauses; * other OS tasks could also pop in randomly. * * Load times are too fast to measure with a microsecond clock using an SSD * so the average load time is computed as the overall time to load * n times divided by n (rather then summing up the individual times). * * @since 4.7 */ export class TimeLexerSpeed { // These paths are relative to /target/benchmark public static readonly Parser_java_file: string = path.resolve(__dirname, "../../reference/antlr4/runtime/Java/src/org/antlr/v4/runtime/Parser.java"); public static readonly RuleContext_java_file: string = path.resolve(__dirname, "../../reference/antlr4/runtime/Java/src/org/antlr/v4/runtime/RuleContext.java"); public static readonly PerfDir: string = path.resolve(__dirname, "../../benchmark"); public output: boolean = true; public streamFootprints: string[] = []; public static async main(...args: string[]): Promise<void> { // let runtimeMxBean: RuntimeMXBean = ManagementFactory.getRuntimeMXBean(); // let vmArgs: string[] = runtimeMxBean.getInputArguments(); // console.log("Java VM args: "); // for (let vmArg in vmArgs) { // if ( !vmArg.startsWith("-D") ) { // console.log(vmArg + " "); // } // } console.log(__dirname); console.log(path.resolve(__dirname, TimeLexerSpeed.Parser_java_file)); console.log(); // console.log(VM.current().details()); let tests: TimeLexerSpeed = new TimeLexerSpeed(); await tests.compilerWarmUp(100); let n: number = 3500; // await tests.load_legacy_java_ascii_file(TimeLexerSpeed.Parser_java_file, n); // await tests.load_legacy_java_ascii_file(TimeLexerSpeed.RuleContext_java_file, n); // await tests.load_legacy_java_ascii(TimeLexerSpeed.Parser_java_file, n); // await tests.load_legacy_java_ascii(TimeLexerSpeed.RuleContext_java_file, n); // await tests.load_legacy_java_utf8(TimeLexerSpeed.Parser_java_file, n); // await tests.load_legacy_java_utf8(path.join(TimeLexerSpeed.PerfDir, "udhr_hin.txt"), n); // await tests.load_new_utf8(TimeLexerSpeed.Parser_java_file, n); // await tests.load_new_utf8(TimeLexerSpeed.RuleContext_java_file, n); // await tests.load_new_utf8(path.join(TimeLexerSpeed.PerfDir, "udhr_hin.txt"), n); console.log(); n = 2000; tests.lex_legacy_java_utf8(n, false); await tests.lex_legacy_java_utf8(n, true); await tests.lex_new_java_utf8(n, false); await tests.lex_new_java_utf8(n, true); console.log(); n = 400; await tests.lex_legacy_grapheme_utf8("udhr_kor.txt", n, false); await tests.lex_legacy_grapheme_utf8("udhr_kor.txt", n, true); await tests.lex_legacy_grapheme_utf8("udhr_hin.txt", n, false); await tests.lex_legacy_grapheme_utf8("udhr_hin.txt", n, true); // legacy can't handle the emoji (32 bit stuff) await tests.lex_new_grapheme_utf8("udhr_kor.txt", n, false); await tests.lex_new_grapheme_utf8("udhr_kor.txt", n, true); await tests.lex_new_grapheme_utf8("udhr_hin.txt", n, false); await tests.lex_new_grapheme_utf8("udhr_hin.txt", n, true); await tests.lex_new_grapheme_utf8("emoji.txt", n, false); await tests.lex_new_grapheme_utf8("emoji.txt", n, true); for (let streamFootprint of tests.streamFootprints) { console.log(streamFootprint); } } public async compilerWarmUp(n: number): Promise<void> { console.log("Warming up runtime"); this.output = false; await this.lex_new_java_utf8(n, false); console.log("."); await this.lex_legacy_java_utf8(n, false); console.log("."); console.log("."); await this.lex_legacy_grapheme_utf8("udhr_hin.txt", n, false); console.log("."); await this.lex_new_grapheme_utf8("udhr_hin.txt", n, false); console.log(); this.output = true; } // public load_legacy_java_ascii_file(resourceName: string, n: number): void { // let sampleJavaFile = resourceName; // if (!fs.existsSync(sampleJavaFile)) { // console.error(`Can't run load_legacy_java_ascii_file (or can't find ${resourceName})`); // return; // } // let content = fs.readFileSync(sampleJavaFile, { encoding: "ascii" }); // let start: Stopwatch = Stopwatch.startNew(); // let input: CharStream[] = []; // keep refs around so we can average memory // for (let i: number = 0; i < n; i++) { // input.push(new ANTLRInputStream(content)); // } // let stop: TimeSpan = start.elapsed(); // let size: number = input[0].size; // let currentMethodName: string = "load_legacy_java_ascii_file"; // let olayout: GraphLayout = GraphLayout.parseInstance(input[0]); // let streamSize: number = olayout.totalSize(); // this.streamFootprints.push(`${TimeLexerSpeed.basename(resourceName)} (${size} char): ${olayout.toFootprint()}`); // if (this.output) { // System.out.printf("%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\n", // currentMethodName, // tus / n, // streamSize, // n, // size, // TimeLexerSpeed.basename(resourceName)); // } // } // public load_legacy_java_ascii(resourceName: string, n: number): void { // let input: CharStream[] = []; // keep refs around so we can average memory // let loader: ClassLoader = TimeLexerSpeed.class.getClassLoader(); // let streams: InputStream[] = []; // for (let i: number = 0; i < n; i++) { // streams.push(loader.getResourceAsStream(resourceName)); // } // let start: Stopwatch = Stopwatch.startNew(); // track only time to suck data out of stream // for (let i: number = 0; i < n; i++) { // let is: InputStream = streams[i]; // try { // input.push(new ANTLRInputStream(is)); // } catch (ex) { // input.push(undefined); // throw ex; // } finally { // is.close(); // } // } // let stop: TimeSpan = start.elapsed(); // let size: number = input[0].size; // let streamSize: number = GraphLayout.parseInstance(input[0]).totalSize(); // this.streamFootprints.push(`${TimeLexerSpeed.basename(resourceName)} (${size} char): ${GraphLayout.parseInstance(input[0]).toFootprint()}`); // let currentMethodName: string = "load_legacy_java_ascii"; // if (this.output) { // console.log("%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\n", // currentMethodName, // tus / n, // streamSize, // n, // size, // TimeLexerSpeed.basename(resourceName)); // } // } // public load_legacy_java_utf8(resourceName: string, n: number): void { // let input: CharStream[] = []; // keep refs around so we can average memory // let loader: ClassLoader = TimeLexerSpeed.class.getClassLoader(); // let streams: InputStream[] = []; // for (let i: number = 0; i < n; i++) { // streams.push(loader.getResourceAsStream(resourceName)); // } // let start: Stopwatch = Stopwatch.startNew(); // track only time to suck data out of stream // for (let i: number = 0; i < n; i++) { // let is: InputStream = streams[i]; // try { // let isr: InputStreamReader = new InputStreamReader(is, Charset.forName("UTF-8")); // try { // let br: BufferedReader = new BufferedReader(isr); // try { // input.push(new ANTLRInputStream(br)); // } // finally { // br.close(); // } // } // finally { // isr.close(); // } // } catch (ex) { // input.push(undefined); // } finally { // is.close(); // } // } // let stop: TimeSpan = start.elapsed(); // let size: number = input[0].size; // let streamSize: number = GraphLayout.parseInstance(input[0]).totalSize(); // this.streamFootprints.push(`${TimeLexerSpeed.basename(resourceName)} (${size} char): ${GraphLayout.parseInstance(input[0]).toFootprint()}`); // let currentMethodName: string = "load_legacy_java_utf8"; // if (this.output) { // console.log("%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\n", // currentMethodName, // tus / n, // streamSize, // n, // size, // TimeLexerSpeed.basename(resourceName)); // } // } // public async load_new_utf8(resourceName: string, n: number): Promise<void> { // let input: CharStream[] = []; // keep refs around so we can average memory // let loader: ClassLoader = TimeLexerSpeed.class.getClassLoader(); // let streams: InputStream[] = []; // for (let i: number = 0; i < n; i++) { // streams.push(loader.getResourceAsStream(resourceName)); // } // let uc: URLConnection | undefined; // let streamLength: number = await TimeLexerSpeed.getResourceSize(resourceName); // let start: Stopwatch = Stopwatch.startNew(); // track only time to suck data out of stream // for (let i: number = 0; i < n; i++) { // let is: InputStream = streams[i]; // try { // input.push(CharStreams.fromStream(is, Charset.forName("UTF-8"), resourceName, streamLength)); // } // finally { // is.close(); // } // } // let stop: TimeSpan = start.elapsed(); // let size: number = input[0].size; // let streamSize: number = GraphLayout.parseInstance(input[0]).totalSize(); // this.streamFootprints.push(`${TimeLexerSpeed.basename(resourceName)} (${size} char): ${GraphLayout.parseInstance(input[0]).toFootprint()}`); // let currentMethodName: string = "load_new_utf8"; // if (this.output) { // console.log("%27s average time %5dus size %6db over %4d loads of %5d symbols from %s\n", // currentMethodName, // tus / n, // streamSize, // n, // size, // TimeLexerSpeed.basename(resourceName)); // } // } public lex_legacy_java_utf8(n: number, clearLexerDFACache: boolean): void { let content = fs.readFileSync(TimeLexerSpeed.Parser_java_file, { encoding: "utf-8" }); // tslint:disable-next-line:deprecation let input: CharStream = new ANTLRInputStream(content); let lexer: JavaLexer = new JavaLexer(input); let avg: TimeSpan = this.tokenize(lexer, n, clearLexerDFACache); let currentMethodName: string = "lex_legacy_java_utf8"; if (this.output) { console.log(`${padStart(currentMethodName, 27)} average time ${Math.round(avg.totalMicroseconds)}us over ${n} runs of ${input.size} symbols${clearLexerDFACache ? " DFA cleared" : ""}`); } } public async lex_new_java_utf8(n: number, clearLexerDFACache: boolean): Promise<void> { let content = fs.readFileSync(TimeLexerSpeed.Parser_java_file, { encoding: "utf-8" }); let size: number = await TimeLexerSpeed.getResourceSize(TimeLexerSpeed.Parser_java_file); let input: CharStream = CharStreams.fromString(content); let lexer: JavaLexer = new JavaLexer(input); let avg: TimeSpan = this.tokenize(lexer, n, clearLexerDFACache); let currentMethodName: string = "lex_new_java_utf8"; if (this.output) { console.log(`${padStart(currentMethodName, 27)} average time ${Math.round(avg.totalMicroseconds)}us over ${n} runs of ${input.size} symbols${clearLexerDFACache ? " DFA cleared" : ""}`); } } public lex_legacy_grapheme_utf8(fileName: string, n: number, clearLexerDFACache: boolean): void { let content = fs.readFileSync(path.join(TimeLexerSpeed.PerfDir, fileName), { encoding: "utf-8" }); // tslint:disable-next-line:deprecation let input: CharStream = new ANTLRInputStream(content); let lexer: GraphemesLexer = new GraphemesLexer(input); let avg: TimeSpan = this.tokenize(lexer, n, clearLexerDFACache); let currentMethodName: string = "lex_legacy_grapheme_utf8"; if (this.output) { console.log(`${padStart(currentMethodName, 27)} average time ${Math.round(avg.totalMicroseconds)}us over ${n} runs of ${input.size} symbols from ${fileName}${clearLexerDFACache ? " DFA cleared" : ""}`); } } public async lex_new_grapheme_utf8(fileName: string, n: number, clearLexerDFACache: boolean): Promise<void> { let resourceName: string = path.join(TimeLexerSpeed.PerfDir, fileName); let content = fs.readFileSync(resourceName, { encoding: "utf-8" }); let size: number = await TimeLexerSpeed.getResourceSize(resourceName); let input: CharStream = CharStreams.fromString(content); let lexer: GraphemesLexer = new GraphemesLexer(input); let avg: TimeSpan = this.tokenize(lexer, n, clearLexerDFACache); let currentMethodName: string = "lex_new_grapheme_utf8"; if (this.output) { console.log(`${padStart(currentMethodName, 27)} average time ${Math.round(avg.totalMicroseconds)}us over ${n} runs of ${input.size} symbols from ${fileName}${clearLexerDFACache ? " DFA cleared" : ""}`); } } public tokenize(lexer: Lexer, n: number, clearLexerDFACache: boolean): TimeSpan { // always wipe the DFA before we begin tests so previous tests don't affect this run! lexer.interpreter.clearDFA(); let times: TimeSpan[] = []; for (let i: number = 0; i < n; i++) { lexer.reset(); if (clearLexerDFACache) { lexer.interpreter.clearDFA(); } let start: Stopwatch = Stopwatch.startNew(); let tokens: CommonTokenStream = new CommonTokenStream(lexer); tokens.fill(); // lex whole file. // let size: number = lexer.inputStream.size; let stop: TimeSpan = start.elapsed(); times.push(stop); // if (this.output) { // console.log(`Tokenized ${size} char in ${times[i].totalMilliseconds}ms`); // } } times.sort((a, b) => a.totalMilliseconds - b.totalMilliseconds); times = times.slice(0, times.length - (n * 0.2)); // drop highest 20% of times return this.avg(times); } public avg(values: TimeSpan[]): TimeSpan { let sum: number = 0.0; for (let v of values) { sum += v.totalMilliseconds; } return TimeSpan.fromMilliseconds(sum / values.length); } public std(mean: number, values: number[]): number { // unbiased std dev let sum: number = 0.0; for (let v of values) { sum += (v - mean) * (v - mean); } return Math.sqrt(sum / (values.length - 1)); } public static basename(fullyQualifiedFileName: string): string { return path.basename(fullyQualifiedFileName); } public static async getResourceSize(resourceName: string): Promise<number> { let stats = await util.promisify(fs.stat)(resourceName); return stats.size; } } let _ = TimeLexerSpeed.main();
the_stack
import { extent as d3Extent, max, min } from "d3-array"; import { ScaleContinuousNumeric, ScaleTime } from "d3-scale"; import * as PropTypes from "prop-types"; import * as React from "react"; import { clearCanvas, functor, head, identity, isDefined, isNotDefined, last, shallowEqual } from "./utils"; import { mouseBasedZoomAnchor, IZoomAnchorOptions } from "./zoom/zoomBehavior"; import { getChartConfigWithUpdatedYScales, getCurrentCharts, getCurrentItem, getNewChartConfig, } from "./utils/ChartDataUtil"; import { EventCapture } from "./EventCapture"; import { CanvasContainer } from "./CanvasContainer"; import evaluator from "./utils/evaluator"; const CANDIDATES_FOR_RESET = ["seriesName"]; const shouldResetChart = (thisProps: any, nextProps: any) => { return !CANDIDATES_FOR_RESET.every((key) => { const result = shallowEqual(thisProps[key], nextProps[key]); return result; }); }; const getCursorStyle = () => { const tooltipStyle = ` .react-financial-charts-grabbing-cursor { pointer-events: all; cursor: -moz-grabbing; cursor: -webkit-grabbing; cursor: grabbing; } .react-financial-charts-crosshair-cursor { pointer-events: all; cursor: crosshair; } .react-financial-charts-tooltip-hover { pointer-events: all; cursor: pointer; } .react-financial-charts-avoid-interaction { pointer-events: none; } .react-financial-charts-enable-interaction { pointer-events: all; } .react-financial-charts-tooltip { pointer-events: all; cursor: pointer; } .react-financial-charts-default-cursor { cursor: default; } .react-financial-charts-move-cursor { cursor: move; } .react-financial-charts-pointer-cursor { cursor: pointer; } .react-financial-charts-ns-resize-cursor { cursor: ns-resize; } .react-financial-charts-ew-resize-cursor { cursor: ew-resize; }`; return <style type="text/css">{tooltipStyle}</style>; }; const getDimensions = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => { const { margin, height, width } = props; return { height: height - margin.top - margin.bottom, width: width - margin.left - margin.right, }; }; const getXScaleDirection = (flipXScale?: boolean) => { return flipXScale ? -1 : 1; }; const calculateFullData = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => { const { data: fullData, plotFull, xScale, clamp, pointsPerPxThreshold, flipXScale, xAccessor, displayXAccessor, minPointsPerPxThreshold, } = props; const useWholeData = plotFull !== undefined ? plotFull : xAccessor === identity; const { filterData } = evaluator({ xScale, useWholeData, clamp, pointsPerPxThreshold, minPointsPerPxThreshold, flipXScale, }); return { xAccessor, displayXAccessor: displayXAccessor ?? xAccessor, xScale: xScale.copy(), fullData, filterData, }; }; const resetChart = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => { const state = calculateState(props); const { xAccessor, displayXAccessor, fullData, plotData: initialPlotData, xScale } = state; const { postCalculator, children } = props; const plotData = postCalculator !== undefined ? postCalculator(initialPlotData) : initialPlotData; const dimensions = getDimensions(props); const chartConfig = getChartConfigWithUpdatedYScales( getNewChartConfig(dimensions, children), { plotData, xAccessor, displayXAccessor, fullData }, xScale.domain(), ); return { ...state, xScale, plotData, chartConfig, }; }; const updateChart = ( newState: any, initialXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>, props: any, lastItemWasVisible: boolean, initialChartConfig: any, ) => { const { fullData, xScale, xAccessor, displayXAccessor, filterData } = newState; const lastItem = last(fullData); const lastXItem = xAccessor(lastItem); const [start, end] = initialXScale.domain(); const { postCalculator, children, padding, flipXScale, maintainPointsPerPixelOnResize } = props; const direction = getXScaleDirection(flipXScale); const dimensions = getDimensions(props); const updatedXScale = setXRange(xScale, dimensions, padding, direction); let initialPlotData; if (!lastItemWasVisible || end >= lastXItem) { // resize comes here... // get plotData between [start, end] and do not change the domain const [rangeStart, rangeEnd] = initialXScale.range(); const [newRangeStart, newRangeEnd] = updatedXScale.range(); const newDomainExtent = ((newRangeEnd - newRangeStart) / (rangeEnd - rangeStart)) * (end.valueOf() - start.valueOf()); const newStart = maintainPointsPerPixelOnResize ? end.valueOf() - newDomainExtent : start; const lastItemX = initialXScale(lastXItem); const response = filterData(fullData, [newStart, end], xAccessor, updatedXScale, { fallbackStart: start, fallbackEnd: { lastItem, lastItemX }, }); initialPlotData = response.plotData; updatedXScale.domain(response.domain); } else if (lastItemWasVisible && end < lastXItem) { // this is when a new item is added and last item was visible // so slide over and show the new item also // get plotData between [xAccessor(l) - (end - start), xAccessor(l)] and DO change the domain const dx = initialXScale(lastXItem) - initialXScale.range()[1]; const [newStart, newEnd] = initialXScale .range() .map((x) => x + dx) .map((x) => initialXScale.invert(x)); const response = filterData(fullData, [newStart, newEnd], xAccessor, updatedXScale); initialPlotData = response.plotData; updatedXScale.domain(response.domain); // if last item was visible, then shift } const plotData = postCalculator(initialPlotData); const chartConfig = getChartConfigWithUpdatedYScales( getNewChartConfig(dimensions, children, initialChartConfig), { plotData, xAccessor, displayXAccessor, fullData }, updatedXScale.domain(), ); return { xScale: updatedXScale, xAccessor, chartConfig, plotData, fullData, filterData, }; }; const calculateState = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => { const { xAccessor: inputXAccesor, xExtents: xExtentsProp, data, padding, flipXScale } = props; const direction = getXScaleDirection(flipXScale); const dimensions = getDimensions(props); const extent = typeof xExtentsProp === "function" ? xExtentsProp(data) : (d3Extent<number | Date>( xExtentsProp.map((d: any) => functor(d)).map((each: any) => each(data, inputXAccesor)), ) as [TXAxis, TXAxis]); const { xAccessor, displayXAccessor, xScale, fullData, filterData } = calculateFullData(props); const updatedXScale = setXRange(xScale, dimensions, padding, direction); const { plotData, domain } = filterData(fullData, extent, inputXAccesor, updatedXScale); return { plotData, xScale: updatedXScale.domain(domain), xAccessor, displayXAccessor, fullData, filterData, }; }; const setXRange = (xScale: any, dimensions: any, padding: any, direction = 1) => { if (xScale.rangeRoundPoints) { if (isNaN(padding)) { throw new Error("padding has to be a number for ordinal scale"); } xScale.rangeRoundPoints([0, dimensions.width], padding); } else if (xScale.padding) { if (isNaN(padding)) { throw new Error("padding has to be a number for ordinal scale"); } xScale.range([0, dimensions.width]); xScale.padding(padding / 2); } else { const { left, right } = isNaN(padding) ? padding : { left: padding, right: padding }; if (direction > 0) { xScale.range([left, dimensions.width - right]); } else { xScale.range([dimensions.width - right, left]); } } return xScale; }; const pinchCoordinates = (pinch: any) => { const { touch1Pos, touch2Pos } = pinch; return { topLeft: [Math.min(touch1Pos[0], touch2Pos[0]), Math.min(touch1Pos[1], touch2Pos[1])], bottomRight: [Math.max(touch1Pos[0], touch2Pos[0]), Math.max(touch1Pos[1], touch2Pos[1])], }; }; const isInteractionEnabled = ( xScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>, xAccessor: any, data: any, ) => { const interaction = !isNaN(xScale(xAccessor(head(data)))) && isDefined(xScale.invert); return interaction; }; export interface ChartCanvasProps<TXAxis extends number | Date> { readonly clamp?: | boolean | ("left" | "right" | "both") | ((domain: [number, number], items: [number, number]) => [number, number]); readonly className?: string; readonly children?: React.ReactNode; readonly data: any[]; readonly defaultFocus?: boolean; readonly disableInteraction?: boolean; readonly disablePan?: boolean; readonly disableZoom?: boolean; readonly displayXAccessor?: (data: any) => TXAxis; readonly flipXScale?: boolean; readonly height: number; readonly margin: { bottom: number; left: number; right: number; top: number; }; readonly maintainPointsPerPixelOnResize?: boolean; readonly minPointsPerPxThreshold?: number; readonly mouseMoveEvent?: boolean; /** * Called when panning left past the first data point. */ readonly onLoadAfter?: (start: TXAxis, end: TXAxis) => void; /** * Called when panning right past the last data point. */ readonly onLoadBefore?: (start: TXAxis, end: TXAxis) => void; /** * Click event handler. */ readonly onClick?: React.MouseEventHandler<HTMLDivElement>; /** * Double click event handler. */ readonly onDoubleClick?: React.MouseEventHandler<HTMLDivElement>; readonly padding?: | number | { bottom: number; left: number; right: number; top: number; }; readonly plotFull?: boolean; readonly pointsPerPxThreshold?: number; readonly postCalculator?: (plotData: any[]) => any[]; readonly ratio: number; readonly seriesName: string; readonly useCrossHairStyleCursor?: boolean; readonly width: number; readonly xAccessor: (data: any) => TXAxis; readonly xExtents: ((data: any[]) => [TXAxis, TXAxis]) | (((data: any[]) => TXAxis) | TXAxis)[]; readonly xScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>; readonly zIndex?: number; readonly zoomAnchor?: (options: IZoomAnchorOptions<any, TXAxis>) => TXAxis; readonly zoomMultiplier?: number; } interface ChartCanvasState<TXAxis extends number | Date> { xAccessor?: (data: any) => TXAxis; displayXAccessor?: any; filterData?: any; chartConfig?: any; plotData: any[]; xScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>; } export class ChartCanvas<TXAxis extends number | Date> extends React.Component< ChartCanvasProps<TXAxis>, ChartCanvasState<TXAxis> > { public static defaultProps = { clamp: false, className: "react-financial-charts", defaultFocus: true, disablePan: false, disableInteraction: false, disableZoom: false, flipXScale: false, maintainPointsPerPixelOnResize: true, margin: { top: 0, right: 40, bottom: 40, left: 0 }, minPointsPerPxThreshold: 1 / 100, mouseMoveEvent: true, postCalculator: identity, padding: 0, pointsPerPxThreshold: 2, useCrossHairStyleCursor: true, xAccessor: identity as (data: any) => any, xExtents: [min, max] as any[], zIndex: 1, zoomAnchor: mouseBasedZoomAnchor, zoomMultiplier: 1.1, }; public static childContextTypes = { plotData: PropTypes.array, fullData: PropTypes.array, chartConfig: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, origin: PropTypes.arrayOf(PropTypes.number).isRequired, padding: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ top: PropTypes.number, bottom: PropTypes.number, }), ]), yExtents: PropTypes.arrayOf(PropTypes.func), yExtentsProvider: PropTypes.func, yScale: PropTypes.func.isRequired, mouseCoordinates: PropTypes.shape({ at: PropTypes.string, format: PropTypes.func, }), width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, }), ).isRequired, xScale: PropTypes.func.isRequired, xAccessor: PropTypes.func.isRequired, displayXAccessor: PropTypes.func.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, margin: PropTypes.object.isRequired, ratio: PropTypes.number.isRequired, getCanvasContexts: PropTypes.func, xAxisZoom: PropTypes.func, yAxisZoom: PropTypes.func, amIOnTop: PropTypes.func, redraw: PropTypes.func, subscribe: PropTypes.func, unsubscribe: PropTypes.func, setCursorClass: PropTypes.func, generateSubscriptionId: PropTypes.func, getMutableState: PropTypes.func, }; private readonly canvasContainerRef = React.createRef<CanvasContainer>(); private readonly eventCaptureRef = React.createRef<EventCapture>(); private finalPinch?: boolean; private fullData: any[]; private lastSubscriptionId = 0; private mutableState = {}; private panInProgress = false; private prevMouseXY?: number[]; private subscriptions: any[] = []; private waitingForPinchZoomAnimationFrame?: boolean; private waitingForPanAnimationFrame?: boolean; private waitingForMouseMoveAnimationFrame?: boolean; // tslint:disable-next-line: variable-name private hackyWayToStopPanBeyondBounds__plotData?: any[] | null; // tslint:disable-next-line: variable-name private hackyWayToStopPanBeyondBounds__domain?: any[] | null; public constructor(props: ChartCanvasProps<TXAxis>) { super(props); const { fullData, ...state } = resetChart(props); this.state = state; this.fullData = fullData; } public getMutableState = () => { return this.mutableState; }; public getDataInfo = () => { return { ...this.state, fullData: this.fullData, }; }; public getCanvasContexts = () => { return this.canvasContainerRef.current?.getCanvasContexts(); }; public generateSubscriptionId = () => { this.lastSubscriptionId++; return this.lastSubscriptionId; }; public clearBothCanvas() { const canvases = this.getCanvasContexts(); if (canvases && canvases.axes && canvases.mouseCoord) { clearCanvas([canvases.axes, canvases.mouseCoord], this.props.ratio); } } public clearMouseCanvas() { const canvases = this.getCanvasContexts(); if (canvases && canvases.mouseCoord) { clearCanvas([canvases.mouseCoord], this.props.ratio); } } public clearThreeCanvas() { const canvases = this.getCanvasContexts(); if (canvases && canvases.axes && canvases.mouseCoord && canvases.bg) { clearCanvas([canvases.axes, canvases.mouseCoord, canvases.bg], this.props.ratio); } } public subscribe = (id: string, rest: any) => { const { getPanConditions = functor({ draggable: false, panEnabled: true, }), } = rest; this.subscriptions = this.subscriptions.concat({ id, ...rest, getPanConditions, }); }; public unsubscribe = (id: string) => { this.subscriptions = this.subscriptions.filter((each) => each.id !== id); }; public getAllPanConditions = () => { return this.subscriptions.map((each) => each.getPanConditions()); }; public setCursorClass = (className: string) => { this.eventCaptureRef.current?.setCursorClass(className); }; public amIOnTop = (id: string) => { const dragableComponents = this.subscriptions.filter((each) => each.getPanConditions().draggable); return dragableComponents.length > 0 && last(dragableComponents).id === id; }; public handleContextMenu = (mouseXY: number[], e: React.MouseEvent) => { const { xAccessor, chartConfig, plotData, xScale } = this.state; const currentCharts = getCurrentCharts(chartConfig, mouseXY); const currentItem = getCurrentItem(xScale, xAccessor, mouseXY, plotData); this.triggerEvent( "contextmenu", { mouseXY, currentItem, currentCharts, }, e, ); }; public calculateStateForDomain = (newDomain: any) => { const { xAccessor, displayXAccessor, xScale: initialXScale, chartConfig: initialChartConfig, plotData: initialPlotData, } = this.state; const { filterData } = this.state; const { fullData } = this; const { postCalculator = ChartCanvas.defaultProps.postCalculator } = this.props; const { plotData: beforePlotData, domain } = filterData(fullData, newDomain, xAccessor, initialXScale, { currentPlotData: initialPlotData, currentDomain: initialXScale!.domain(), }); const plotData = postCalculator(beforePlotData); const updatedScale = initialXScale.copy().domain(domain) as | ScaleContinuousNumeric<number, number> | ScaleTime<number, number>; const chartConfig = getChartConfigWithUpdatedYScales( initialChartConfig, { plotData, xAccessor, displayXAccessor, fullData }, updatedScale.domain(), ); return { xScale: updatedScale, plotData, chartConfig, }; }; public pinchZoomHelper = (initialPinch: any, finalPinch: any) => { const { xScale: initialPinchXScale } = initialPinch; const { xScale: initialXScale, chartConfig: initialChartConfig, plotData: initialPlotData, xAccessor, displayXAccessor, filterData, } = this.state; const { fullData } = this; const { postCalculator = ChartCanvas.defaultProps.postCalculator } = this.props; const { topLeft: iTL, bottomRight: iBR } = pinchCoordinates(initialPinch); const { topLeft: fTL, bottomRight: fBR } = pinchCoordinates(finalPinch); const e = initialPinchXScale.range()[1]; const xDash = Math.round(-(iBR[0] * fTL[0] - iTL[0] * fBR[0]) / (iTL[0] - iBR[0])); const yDash = Math.round( e + ((e - iBR[0]) * (e - fTL[0]) - (e - iTL[0]) * (e - fBR[0])) / (e - iTL[0] - (e - iBR[0])), ); const x = Math.round((-xDash * iTL[0]) / (-xDash + fTL[0])); const y = Math.round(e - ((yDash - e) * (e - iTL[0])) / (yDash + (e - fTL[0]))); const newDomain = [x, y].map(initialPinchXScale.invert); const { plotData: beforePlotData, domain } = filterData(fullData, newDomain, xAccessor, initialPinchXScale, { currentPlotData: initialPlotData, currentDomain: initialXScale!.domain(), }); const plotData = postCalculator(beforePlotData); const updatedScale = initialXScale!.copy().domain(domain) as | ScaleContinuousNumeric<number, number> | ScaleTime<number, number>; const mouseXY = finalPinch.touch1Pos; const chartConfig = getChartConfigWithUpdatedYScales( initialChartConfig, { plotData, xAccessor, displayXAccessor, fullData }, updatedScale.domain(), ); const currentItem = getCurrentItem(updatedScale, xAccessor, mouseXY, plotData); return { chartConfig, xScale: updatedScale, plotData, mouseXY, currentItem, }; }; public cancelDrag() { this.eventCaptureRef.current?.cancelDrag(); this.triggerEvent("dragcancel"); } public handlePinchZoom = (initialPinch: any, finalPinch: any, e: any) => { if (!this.waitingForPinchZoomAnimationFrame) { this.waitingForPinchZoomAnimationFrame = true; const state = this.pinchZoomHelper(initialPinch, finalPinch); this.triggerEvent("pinchzoom", state, e); this.finalPinch = finalPinch; requestAnimationFrame(() => { this.clearBothCanvas(); this.draw({ trigger: "pinchzoom" }); this.waitingForPinchZoomAnimationFrame = false; }); } }; public handlePinchZoomEnd = (initialPinch: any, e: any) => { const { xAccessor = ChartCanvas.defaultProps.xAccessor } = this.state; if (this.finalPinch) { const state = this.pinchZoomHelper(initialPinch, this.finalPinch); const { xScale } = state; this.triggerEvent("pinchzoom", state, e); this.finalPinch = undefined; this.clearThreeCanvas(); const { fullData } = this; const firstItem = head(fullData); const scale_start = head(xScale.domain()); const data_start = xAccessor(firstItem); const lastItem = last(fullData); const scale_end = last(xScale.domain()); const data_end = xAccessor(lastItem); const { onLoadAfter, onLoadBefore } = this.props; this.setState(state, () => { if (scale_start < data_start) { if (onLoadBefore !== undefined) { onLoadBefore(scale_start, data_start); } } if (data_end < scale_end) { if (onLoadAfter !== undefined) { onLoadAfter(data_end, scale_end); } } }); } }; public handleZoom = (zoomDirection: any, mouseXY: any, e: any) => { if (this.panInProgress) { return; } const { xAccessor, xScale: initialXScale, plotData: initialPlotData } = this.state; const { zoomMultiplier = ChartCanvas.defaultProps.zoomMultiplier, zoomAnchor = ChartCanvas.defaultProps.zoomAnchor, } = this.props; const { fullData } = this; const item = zoomAnchor({ xScale: initialXScale!, xAccessor: xAccessor!, mouseXY, plotData: initialPlotData, }); const cx = initialXScale(item); const c = zoomDirection > 0 ? 1 * zoomMultiplier : 1 / zoomMultiplier; const newDomain = initialXScale! .range() .map((x) => cx + (x - cx) * c) .map((x) => initialXScale.invert(x)); const { xScale, plotData, chartConfig } = this.calculateStateForDomain(newDomain); const currentItem = getCurrentItem(xScale, xAccessor, mouseXY, plotData); const currentCharts = getCurrentCharts(chartConfig, mouseXY); this.clearThreeCanvas(); const firstItem = head(fullData); const scale_start = head(xScale.domain()); const data_start = xAccessor!(firstItem); const lastItem = last(fullData); const scale_end = last(xScale.domain()); const data_end = xAccessor!(lastItem); this.mutableState = { mouseXY, currentItem, currentCharts, }; this.triggerEvent( "zoom", { xScale, plotData, chartConfig, mouseXY, currentCharts, currentItem, show: true, }, e, ); const { onLoadAfter, onLoadBefore } = this.props; this.setState( { xScale, plotData, chartConfig, }, () => { if (scale_start < data_start) { if (onLoadBefore !== undefined) { onLoadBefore(scale_start, data_start); } } if (data_end < scale_end) { if (onLoadAfter !== undefined) { onLoadAfter(data_end, scale_end); } } }, ); }; public xAxisZoom = (newDomain: any) => { const { xScale, plotData, chartConfig } = this.calculateStateForDomain(newDomain); this.clearThreeCanvas(); const { xAccessor } = this.state; const { fullData } = this; const firstItem = head(fullData); const scale_start = head(xScale.domain()); const data_start = xAccessor!(firstItem); const lastItem = last(fullData); const scale_end = last(xScale.domain()); const data_end = xAccessor!(lastItem); const { onLoadAfter, onLoadBefore } = this.props; this.setState( { xScale, plotData, chartConfig, }, () => { if (scale_start < data_start) { if (onLoadBefore !== undefined) { onLoadBefore(scale_start, data_start); } } if (data_end < scale_end) { if (onLoadAfter !== undefined) { onLoadAfter(data_end, scale_end); } } }, ); }; public yAxisZoom = (chartId: string, newDomain: any) => { this.clearThreeCanvas(); const { chartConfig: initialChartConfig } = this.state; const chartConfig = initialChartConfig.map((each: any) => { if (each.id === chartId) { const { yScale } = each; return { ...each, yScale: yScale.copy().domain(newDomain), yPanEnabled: true, }; } else { return each; } }); this.setState({ chartConfig, }); }; public triggerEvent(type: any, props?: any, e?: any) { this.subscriptions.forEach((each) => { const state = { ...this.state, fullData: this.fullData, subscriptions: this.subscriptions, }; each.listener(type, props, state, e); }); } public draw = (props: any) => { this.subscriptions.forEach((each) => { if (isDefined(each.draw)) { each.draw(props); } }); }; public redraw = () => { this.clearThreeCanvas(); this.draw({ force: true }); }; public panHelper = ( mouseXY: number[], initialXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>, { dx, dy }: { dx: number; dy: number }, chartsToPan: string[], ) => { const { xAccessor, displayXAccessor, chartConfig: initialChartConfig, filterData } = this.state; const { fullData } = this; const { postCalculator = ChartCanvas.defaultProps.postCalculator } = this.props; const newDomain = initialXScale .range() .map((x) => x - dx) .map((x) => initialXScale.invert(x)); const { plotData: beforePlotData, domain } = filterData(fullData, newDomain, xAccessor, initialXScale, { currentPlotData: this.hackyWayToStopPanBeyondBounds__plotData, currentDomain: this.hackyWayToStopPanBeyondBounds__domain, ignoreThresholds: true, }); const updatedScale = initialXScale.copy().domain(domain) as | ScaleContinuousNumeric<number, number> | ScaleTime<number, number>; const plotData = postCalculator(beforePlotData); const currentItem = getCurrentItem(updatedScale, xAccessor, mouseXY, plotData); const chartConfig = getChartConfigWithUpdatedYScales( initialChartConfig, { plotData, xAccessor, displayXAccessor, fullData }, updatedScale.domain(), dy, chartsToPan, ); const currentCharts = getCurrentCharts(chartConfig, mouseXY); return { xScale: updatedScale, plotData, chartConfig, mouseXY, currentCharts, currentItem, }; }; public handlePan = ( mousePosition: number[], panStartXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>, dxdy: { dx: number; dy: number }, chartsToPan: string[], e: React.MouseEvent, ) => { if (!this.waitingForPanAnimationFrame) { this.waitingForPanAnimationFrame = true; this.hackyWayToStopPanBeyondBounds__plotData = this.hackyWayToStopPanBeyondBounds__plotData ?? this.state.plotData; this.hackyWayToStopPanBeyondBounds__domain = this.hackyWayToStopPanBeyondBounds__domain ?? this.state.xScale!.domain(); const newState = this.panHelper(mousePosition, panStartXScale, dxdy, chartsToPan); this.hackyWayToStopPanBeyondBounds__plotData = newState.plotData; this.hackyWayToStopPanBeyondBounds__domain = newState.xScale.domain(); this.panInProgress = true; this.triggerEvent("pan", newState, e); this.mutableState = { mouseXY: newState.mouseXY, currentItem: newState.currentItem, currentCharts: newState.currentCharts, }; requestAnimationFrame(() => { this.waitingForPanAnimationFrame = false; this.clearBothCanvas(); this.draw({ trigger: "pan" }); }); } }; public handlePanEnd = ( mousePosition: number[], panStartXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>, dxdy: { dx: number; dy: number }, chartsToPan: string[], e: React.MouseEvent | React.TouchEvent, ) => { const state = this.panHelper(mousePosition, panStartXScale, dxdy, chartsToPan); this.hackyWayToStopPanBeyondBounds__plotData = null; this.hackyWayToStopPanBeyondBounds__domain = null; this.panInProgress = false; const { xScale, plotData, chartConfig } = state; this.triggerEvent("panend", state, e); requestAnimationFrame(() => { const { xAccessor } = this.state; const { fullData } = this; const firstItem = head(fullData); const scale_start = head(xScale.domain()); const data_start = xAccessor!(firstItem); const lastItem = last(fullData); const scale_end = last(xScale.domain()); const data_end = xAccessor!(lastItem); const { onLoadAfter, onLoadBefore } = this.props; this.clearThreeCanvas(); this.setState( { xScale, plotData, chartConfig, }, () => { if (scale_start < data_start) { if (onLoadBefore !== undefined) { onLoadBefore(scale_start, data_start); } } if (data_end < scale_end) { if (onLoadAfter !== undefined) { onLoadAfter(data_end, scale_end); } } }, ); }); }; public handleMouseDown = (_: number[], __: string[], e: React.MouseEvent) => { this.triggerEvent("mousedown", this.mutableState, e); }; public handleMouseEnter = (e: React.MouseEvent) => { this.triggerEvent( "mouseenter", { show: true, }, e, ); }; public handleMouseMove = (mouseXY: number[], _: string, e: any) => { if (!this.waitingForMouseMoveAnimationFrame) { this.waitingForMouseMoveAnimationFrame = true; const { chartConfig, plotData, xScale, xAccessor } = this.state; const currentCharts = getCurrentCharts(chartConfig, mouseXY); const currentItem = getCurrentItem(xScale, xAccessor, mouseXY, plotData); this.triggerEvent( "mousemove", { show: true, mouseXY, // prevMouseXY is used in interactive components prevMouseXY: this.prevMouseXY, currentItem, currentCharts, }, e, ); this.prevMouseXY = mouseXY; this.mutableState = { mouseXY, currentItem, currentCharts, }; requestAnimationFrame(() => { this.clearMouseCanvas(); this.draw({ trigger: "mousemove" }); this.waitingForMouseMoveAnimationFrame = false; }); } }; public handleMouseLeave = (e: any) => { this.triggerEvent("mouseleave", { show: false }, e); this.clearMouseCanvas(); this.draw({ trigger: "mouseleave" }); }; public handleDragStart = ({ startPos }: any, e: any) => { this.triggerEvent("dragstart", { startPos }, e); }; public handleDrag = ({ startPos, mouseXY }: { startPos: number[]; mouseXY: number[] }, e: React.MouseEvent) => { const { chartConfig, plotData, xScale, xAccessor } = this.state; const currentCharts = getCurrentCharts(chartConfig, mouseXY); const currentItem = getCurrentItem(xScale, xAccessor, mouseXY, plotData); this.triggerEvent( "drag", { startPos, mouseXY, currentItem, currentCharts, }, e, ); this.mutableState = { mouseXY, currentItem, currentCharts, }; requestAnimationFrame(() => { this.clearMouseCanvas(); this.draw({ trigger: "drag" }); }); }; public handleDragEnd = ({ mouseXY }: { mouseXY: number[] }, e: React.MouseEvent) => { this.triggerEvent("dragend", { mouseXY }, e); requestAnimationFrame(() => { this.clearMouseCanvas(); this.draw({ trigger: "dragend" }); }); }; public handleClick = (_: number[], e: React.MouseEvent) => { this.triggerEvent("click", this.mutableState, e); requestAnimationFrame(() => { this.clearMouseCanvas(); this.draw({ trigger: "click" }); }); }; public handleDoubleClick = (_: number[], e: React.MouseEvent) => { this.triggerEvent("dblclick", {}, e); }; public getChildContext() { const dimensions = getDimensions(this.props); return { fullData: this.fullData, plotData: this.state.plotData, width: dimensions.width, height: dimensions.height, chartConfig: this.state.chartConfig, xScale: this.state.xScale, xAccessor: this.state.xAccessor, displayXAccessor: this.state.displayXAccessor, margin: this.props.margin, ratio: this.props.ratio, xAxisZoom: this.xAxisZoom, yAxisZoom: this.yAxisZoom, getCanvasContexts: this.getCanvasContexts, redraw: this.redraw, subscribe: this.subscribe, unsubscribe: this.unsubscribe, generateSubscriptionId: this.generateSubscriptionId, getMutableState: this.getMutableState, amIOnTop: this.amIOnTop, setCursorClass: this.setCursorClass, }; } public UNSAFE_componentWillReceiveProps(nextProps: ChartCanvasProps<TXAxis>) { const reset = shouldResetChart(this.props, nextProps); const { chartConfig: initialChartConfig, plotData, xAccessor, xScale } = this.state; const interaction = isInteractionEnabled(xScale, xAccessor, plotData); let newState; if (!interaction || reset || !shallowEqual(this.props.xExtents, nextProps.xExtents)) { // do reset newState = resetChart(nextProps); this.mutableState = {}; } else { const [start, end] = xScale.domain(); const prevLastItem = last(this.fullData); const calculatedState = calculateFullData(nextProps); const { xAccessor } = calculatedState; const previousX = xAccessor(prevLastItem); const lastItemWasVisible = previousX <= end && previousX >= start; newState = updateChart(calculatedState, xScale, nextProps, lastItemWasVisible, initialChartConfig); } const { fullData, ...state } = newState; if (!this.panInProgress) { this.clearThreeCanvas(); this.setState(state); } this.fullData = fullData; } public resetYDomain = (chartId?: string) => { const { chartConfig } = this.state; let changed = false; const newChartConfig = chartConfig.map((each: any) => { if ( (isNotDefined(chartId) || each.id === chartId) && !shallowEqual(each.yScale.domain(), each.realYDomain) ) { changed = true; return { ...each, yScale: each.yScale.domain(each.realYDomain), yPanEnabled: false, }; } return each; }); if (changed) { this.clearThreeCanvas(); this.setState({ chartConfig: newChartConfig, }); } }; public shouldComponentUpdate() { return !this.panInProgress; } public render() { const { disableInteraction, disablePan, disableZoom, useCrossHairStyleCursor, onClick, onDoubleClick, height, width, margin = ChartCanvas.defaultProps.margin, className, zIndex = ChartCanvas.defaultProps.zIndex, defaultFocus, ratio, mouseMoveEvent, } = this.props; const { plotData, xScale, xAccessor, chartConfig } = this.state; const dimensions = getDimensions(this.props); const interaction = isInteractionEnabled(xScale, xAccessor, plotData); const cursorStyle = useCrossHairStyleCursor && interaction; const cursor = getCursorStyle(); return ( <div style={{ position: "relative", width, height }} className={className} onClick={onClick} onDoubleClick={onDoubleClick} > <CanvasContainer ref={this.canvasContainerRef} ratio={ratio} width={width} height={height} style={{ height, zIndex, width }} /> <svg className={className} width={width} height={height} style={{ position: "absolute", zIndex: zIndex + 5 }} > {cursor} <defs> <clipPath id="chart-area-clip"> <rect x="0" y="0" width={dimensions.width} height={dimensions.height} /> </clipPath> {chartConfig.map((each: any, idx: number) => ( <clipPath key={idx} id={`chart-area-clip-${each.id}`}> <rect x="0" y="0" width={each.width} height={each.height} /> </clipPath> ))} </defs> <g transform={`translate(${margin.left + 0.5}, ${margin.top + 0.5})`}> <EventCapture ref={this.eventCaptureRef} useCrossHairStyleCursor={cursorStyle} mouseMove={mouseMoveEvent && interaction} zoom={!disableZoom && interaction} pan={!disablePan && interaction} width={dimensions.width} height={dimensions.height} chartConfig={chartConfig} xScale={xScale!} xAccessor={xAccessor} focus={defaultFocus} disableInteraction={disableInteraction} getAllPanConditions={this.getAllPanConditions} onContextMenu={this.handleContextMenu} onClick={this.handleClick} onDoubleClick={this.handleDoubleClick} onMouseDown={this.handleMouseDown} onMouseMove={this.handleMouseMove} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onDragStart={this.handleDragStart} onDrag={this.handleDrag} onDragComplete={this.handleDragEnd} onZoom={this.handleZoom} onPinchZoom={this.handlePinchZoom} onPinchZoomEnd={this.handlePinchZoomEnd} onPan={this.handlePan} onPanEnd={this.handlePanEnd} /> <g className="react-financial-charts-avoid-interaction">{this.props.children}</g> </g> </svg> </div> ); } }
the_stack
import { IBufferLine } from "xterm"; import { ActiveCharPrompt, ActivePrompt, closestLeftBoundary, closestRightBoundary, collectAutocompleteCandidates, getLastToken, hasTrailingWhitespace, isIncompleteInput } from "./shell-utils"; import ShellHistory from "./shell-history"; import WasmTerminalConfig from "../wasm-terminal-config"; import WasmTty from "../wasm-tty/wasm-tty"; import CommandRunner from "../command-runner/command-runner"; /** * A shell is the primary interface that is used to start other programs. * It's purpose to handle: * - Job control (control of child processes), * - Control Sequences (CTRL+C to kill the foreground process) * - Line editing and history * - Output text to the tty -> terminal * - Interpret text within the tty to launch processes and interpret programs */ type AutoCompleteHandler = (index: number, tokens: string[]) => string[]; export default class WasmShell { wasmTerminalConfig: WasmTerminalConfig; wasmTty: WasmTty; history: ShellHistory; commandRunner?: CommandRunner; maxAutocompleteEntries: number; _autocompleteHandlers: AutoCompleteHandler[]; _active: boolean; _activePrompt?: ActivePrompt; _activeCharPrompt?: ActiveCharPrompt; constructor( wasmTerminalConfig: WasmTerminalConfig, wasmTty: WasmTty, options: { historySize: number; maxAutocompleteEntries: number } = { historySize: 10, maxAutocompleteEntries: 100 } ) { this.wasmTerminalConfig = wasmTerminalConfig; this.wasmTty = wasmTty; this.history = new ShellHistory(options.historySize); this.commandRunner = undefined; this.maxAutocompleteEntries = options.maxAutocompleteEntries; this._autocompleteHandlers = [ (index, tokens) => { return this.history.entries; } ]; this._active = false; } async prompt() { // If we are already prompting, do nothing... if (this._activePrompt) { return; } try { this._activePrompt = this.wasmTty.read("$ "); this._active = true; let line = await this._activePrompt.promise; if (this.commandRunner) { this.commandRunner.kill(); } if (line === "") { // Simply prompt again this.prompt(); return; } if (line === "!!") { // This means run the previous command if (this.history && this.history.entries.length > 0) { line = this.history.entries[this.history.entries.length - 1]; } else { throw new Error("No Previous command in History"); } } else if (this.history) { this.history.push(this.wasmTty.getInput()); } this.commandRunner = this.getCommandRunner(line); await this.commandRunner.runCommand(); } catch (e) { this.wasmTty.println(`${e.toString()}`); // tslint:disable-next-line this.prompt(); } } isPrompting() { return this._active; } /** * This function returns a command runner for the specified line */ getCommandRunner(line: string) { return new CommandRunner( this.wasmTerminalConfig, line, // Command Read Callback async () => { this._activePrompt = this.wasmTty.read(""); this._active = true; return this._activePrompt.promise; }, // Command End Callback () => { // Doing a set timeout to allow whatever killed the process to do it's thing first setTimeout(() => { // tslint:disable-next-line this.prompt(); }); }, // TTY this.wasmTty ); } /** * This function completes the current input, calls the given callback * and then re-displays the prompt. */ printAndRestartPrompt(callback: () => Promise<any> | undefined) { const cursor = this.wasmTty.getCursor(); // Complete input this.wasmTty.setCursor(this.wasmTty.getInput().length); this.wasmTty.print("\r\n"); // Prepare a function that will resume prompt const resume = () => { this.wasmTty.setCursor(this.wasmTty.getCursor()); this.wasmTty.setInput(this.wasmTty.getInput()); }; // Call the given callback to echo something, and if there is a promise // returned, wait for the resolution before resuming prompt. const ret = callback(); if (ret) { // tslint:disable-next-line ret.then(resume); } else { resume(); } } /** * Resolve a pending read operation * (Will resolve an empty string) */ resolveActiveRead() { // Abort the read if we were reading if (this._activePrompt && this._activePrompt.resolve) { this._activePrompt.resolve(""); this._activePrompt = undefined; } if (this._activeCharPrompt && this._activeCharPrompt.resolve) { this._activeCharPrompt.resolve(""); this._activeCharPrompt = undefined; } this._active = false; } /** * Abort a pending read operation */ rejectActiveRead(reason = "aborted") { if (this._activePrompt || this._activeCharPrompt) { this.wasmTty.print("\r\n"); } if (this._activePrompt && this._activePrompt.reject) { this._activePrompt.reject(new Error(reason)); this._activePrompt = undefined; } if (this._activeCharPrompt && this._activeCharPrompt.reject) { this._activeCharPrompt.reject(new Error(reason)); this._activeCharPrompt = undefined; } this._active = false; } /** * Move cursor at given direction */ handleCursorMove = (dir: number) => { if (dir > 0) { const num = Math.min( dir, this.wasmTty.getInput().length - this.wasmTty.getCursor() ); this.wasmTty.setCursorDirectly(this.wasmTty.getCursor() + num); } else if (dir < 0) { const num = Math.max(dir, -this.wasmTty.getCursor()); this.wasmTty.setCursorDirectly(this.wasmTty.getCursor() + num); } }; /** * Erase a character at cursor location */ handleCursorErase = (backspace: boolean) => { if (backspace) { if (this.wasmTty.getCursor() <= 0) return; const newInput = this.wasmTty.getInput().substr(0, this.wasmTty.getCursor() - 1) + this.wasmTty.getInput().substr(this.wasmTty.getCursor()); this.wasmTty.clearInput(); this.wasmTty.setCursorDirectly(this.wasmTty.getCursor() - 1); this.wasmTty.setInput(newInput, true); } else { const newInput = this.wasmTty.getInput().substr(0, this.wasmTty.getCursor()) + this.wasmTty.getInput().substr(this.wasmTty.getCursor() + 1); this.wasmTty.setInput(newInput); } }; /** * Insert character at cursor location */ handleCursorInsert = (data: string) => { const newInput = this.wasmTty.getInput().substr(0, this.wasmTty.getCursor()) + data + this.wasmTty.getInput().substr(this.wasmTty.getCursor()); this.wasmTty.setCursorDirectly(this.wasmTty.getCursor() + data.length); this.wasmTty.setInput(newInput); }; /** * Handle input completion */ handleReadComplete = () => { if (this._activePrompt && this._activePrompt.resolve) { this._activePrompt.resolve(this.wasmTty.getInput()); this._activePrompt = undefined; } this.wasmTty.print("\r\n"); this._active = false; }; /** * Handle terminal -> tty input */ handleTermData = (data: string) => { // Only Allow CTRL+C Through if (!this._active && data !== "\x03") { return; } if (this.wasmTty.getFirstInit() && this._activePrompt) { let line = this.wasmTty .getBuffer() .getLine( this.wasmTty.getBuffer().cursorY + this.wasmTty.getBuffer().baseY ); let promptRead = (line as IBufferLine).translateToString( false, 0, this.wasmTty.getBuffer().cursorX ); this._activePrompt.promptPrefix = promptRead; this.wasmTty.setPromptPrefix(promptRead); this.wasmTty.setFirstInit(false); } // If we have an active character prompt, satisfy it in priority if (this._activeCharPrompt && this._activeCharPrompt.resolve) { this._activeCharPrompt.resolve(data); this._activeCharPrompt = undefined; this.wasmTty.print("\r\n"); return; } // If this looks like a pasted input, expand it if (data.length > 3 && data.charCodeAt(0) !== 0x1b) { const normData = data.replace(/[\r\n]+/g, "\r"); Array.from(normData).forEach(c => this.handleData(c)); } else { this.handleData(data); } }; /** * Handle a single piece of information from the terminal -> tty. */ handleData = (data: string) => { // Only Allow CTRL+C Through if (!this._active && data !== "\x03") { return; } const ord = data.charCodeAt(0); let ofs; // Handle ANSI escape sequences if (ord === 0x1b) { switch (data.substr(1)) { case "[A": // Up arrow if (this.history) { let value = this.history.getPrevious(); if (value) { this.wasmTty.setInput(value); this.wasmTty.setCursor(value.length); } } break; case "[B": // Down arrow if (this.history) { let value = this.history.getNext(); if (!value) value = ""; this.wasmTty.setInput(value); this.wasmTty.setCursor(value.length); } break; case "[D": // Left Arrow this.handleCursorMove(-1); break; case "[C": // Right Arrow this.handleCursorMove(1); break; case "[3~": // Delete this.handleCursorErase(false); break; case "[F": // End this.wasmTty.setCursor(this.wasmTty.getInput().length); break; case "[H": // Home this.wasmTty.setCursor(0); break; // case "b": // ALT + a case "b": // ALT + LEFT ofs = closestLeftBoundary( this.wasmTty.getInput(), this.wasmTty.getCursor() ); if (ofs) this.wasmTty.setCursor(ofs); break; case "f": // ALT + RIGHT ofs = closestRightBoundary( this.wasmTty.getInput(), this.wasmTty.getCursor() ); if (ofs) this.wasmTty.setCursor(ofs); break; case "\x7F": // CTRL + BACKSPACE ofs = closestLeftBoundary( this.wasmTty.getInput(), this.wasmTty.getCursor() ); if (ofs) { this.wasmTty.setInput( this.wasmTty.getInput().substr(0, ofs) + this.wasmTty.getInput().substr(this.wasmTty.getCursor()) ); this.wasmTty.setCursor(ofs); } break; } // Handle special characters } else if (ord < 32 || ord === 0x7f) { switch (data) { case "\r": // ENTER case "\x0a": // CTRL+J case "\x0d": // CTRL+M if (isIncompleteInput(this.wasmTty.getInput())) { this.handleCursorInsert("\n"); } else { this.handleReadComplete(); } break; case "\x7F": // BACKSPACE case "\x08": // CTRL+H case "\x04": // CTRL+D this.handleCursorErase(true); break; case "\t": // TAB if (this._autocompleteHandlers.length > 0) { const inputFragment = this.wasmTty .getInput() .substr(0, this.wasmTty.getCursor()); const hasTrailingSpace = hasTrailingWhitespace(inputFragment); const candidates = collectAutocompleteCandidates( this._autocompleteHandlers, inputFragment ); // Sort candidates candidates.sort(); // Depending on the number of candidates, we are handing them in // a different way. if (candidates.length === 0) { // No candidates? Just add a space if there is none already if (!hasTrailingSpace) { this.handleCursorInsert(" "); } } else if (candidates.length === 1) { // Just a single candidate? Complete const lastToken = getLastToken(inputFragment); this.handleCursorInsert( candidates[0].substr(lastToken.length) + " " ); } else if (candidates.length <= this.maxAutocompleteEntries) { // If we are less than maximum auto-complete candidates, print // them to the user and re-start prompt this.printAndRestartPrompt(() => { this.wasmTty.printWide(candidates); return undefined; }); } else { // If we have more than maximum auto-complete candidates, print // them only if the user acknowledges a warning this.printAndRestartPrompt(() => this.wasmTty .readChar( `Display all ${candidates.length} possibilities? (y or n)` ) .promise.then((yn: string) => { if (yn === "y" || yn === "Y") { this.wasmTty.printWide(candidates); } }) ); } } else { this.handleCursorInsert(" "); } break; case "\x01": // CTRL+A this.wasmTty.setCursor(0); break; case "\x02": // CTRL+B this.handleCursorMove(-1); break; case "\x03": // CTRL+C case "\x1a": // CTRL+Z const currentInput = this.wasmTty.getInput(); this.wasmTty.setCursor(currentInput.length); this.wasmTty.setInput(""); this.wasmTty.setCursorDirectly(0); this.wasmTty.print(currentInput + "^C\r\n"); if (this.history) this.history.rewind(); // Kill the command if (this.commandRunner) { this.commandRunner.kill(); this.commandRunner = undefined; } // If we are prompting, then we want to cancel the current read this.resolveActiveRead(); break; case "\x05": // CTRL+E this.wasmTty.setCursor(this.wasmTty.getInput().length); break; case "\x06": // CTRL+F this.handleCursorMove(1); break; case "\x07": // CTRL+G if (this.history) this.history.rewind(); this.wasmTty.setInput(""); break; case "\x0b": // CTRL+K this.wasmTty.setInput( this.wasmTty.getInput().substring(0, this.wasmTty.getCursor()) ); this.wasmTty.setCursor(this.wasmTty.getInput().length); break; case "\x0c": // CTRL+L this.wasmTty.clearTty(); this.wasmTty.print(`$ ${this.wasmTty.getInput()}`); break; case "\x0e": // CTRL+N if (this.history) { let value = this.history.getNext(); if (!value) value = ""; this.wasmTty.setInput(value); this.wasmTty.setCursor(value.length); } break; case "\x10": // CTRL+P if (this.history) { let value = this.history.getPrevious(); if (value) { this.wasmTty.setInput(value); this.wasmTty.setCursor(value.length); } } break; case "\x15": // CTRL+U this.wasmTty.setInput( this.wasmTty.getInput().substring(this.wasmTty.getCursor()) ); this.wasmTty.setCursor(0); break; } // Handle visible characters } else { this.handleCursorInsert(data); } }; }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreApp } from '@services/app'; import { CoreSites } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalWarning } from '@services/ws'; import { makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { CoreCommentsOffline } from './comments-offline'; import { CoreCommentsSyncAutoSyncData, CoreCommentsSyncProvider } from './comments-sync'; const ROOT_CACHE_KEY = 'mmComments:'; declare module '@singletons/events' { /** * Augment CoreEventsData interface with events specific to this service. * * @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation */ export interface CoreEventsData { [CoreCommentsProvider.REFRESH_COMMENTS_EVENT]: CoreCommentsRefreshCommentsEventData; [CoreCommentsProvider.COMMENTS_COUNT_CHANGED_EVENT]: CoreCommentsCountChangedEventData; [CoreCommentsSyncProvider.AUTO_SYNCED]: CoreCommentsSyncAutoSyncData; } } /** * Service that provides some features regarding comments. */ @Injectable( { providedIn: 'root' }) export class CoreCommentsProvider { static readonly REFRESH_COMMENTS_EVENT = 'core_comments_refresh_comments'; static readonly COMMENTS_COUNT_CHANGED_EVENT = 'core_comments_count_changed'; static pageSize = 1; // At least it will be one. static pageSizeOK = false; // If true, the pageSize is definitive. If not, it's a temporal value to reduce WS calls. /** * Initialize the module service. */ initialize(): void { // Reset comments page size. CoreEvents.on(CoreEvents.LOGIN, () => { CoreCommentsProvider.pageSize = 1; CoreCommentsProvider.pageSizeOK = false; }); } /** * Add a comment. * * @param content Comment text. * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: true if comment was sent to server, false if stored in device. */ async addComment( content: string, contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<CoreCommentsData | false> { siteId = siteId || CoreSites.getCurrentSiteId(); // Convenience function to store a comment to be synchronized later. const storeOffline = async (): Promise<false> => { await CoreCommentsOffline.saveComment(content, contextLevel, instanceId, component, itemId, area, siteId); return false; }; if (!CoreApp.isOnline()) { // App is offline, store the comment. return storeOffline(); } // Send comment to server. try { return await this.addCommentOnline(content, contextLevel, instanceId, component, itemId, area, siteId); } catch (error) { if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the message so don't store it. throw error; } return storeOffline(); } } /** * Add a comment. It will fail if offline or cannot connect. * * @param content Comment text. * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when added, rejected otherwise. */ async addCommentOnline( content: string, contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<CoreCommentsData> { const comments: CoreCommentsCommentBasicData[] = [ { contextlevel: contextLevel, instanceid: instanceId, component: component, itemid: itemId, area: area, content: content, }, ]; const commentsResponse = await this.addCommentsOnline(comments, siteId); // A comment was added, invalidate them. await CoreUtils.ignoreErrors( this.invalidateCommentsData(contextLevel, instanceId, component, itemId, area, siteId), ); return commentsResponse![0]; } /** * Add several comments. It will fail if offline or cannot connect. * * @param comments Comments to save. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when added, rejected otherwise. Promise resolved doesn't mean that comments * have been added, the resolve param can contain errors for comments not sent. */ async addCommentsOnline( comments: CoreCommentsCommentBasicData[], siteId?: string, ): Promise<CoreCommentsAddCommentsWSResponse | undefined> { if (!comments || !comments.length) { return; } const site = await CoreSites.getSite(siteId); const data: CoreCommentsAddCommentsWSParams = { comments: comments, }; return await site.write('core_comment_add_comments', data); } /** * Check if Calendar is disabled in a certain site. * * @param site Site. If not defined, use current site. * @return Whether it's disabled. */ areCommentsDisabledInSite(site?: CoreSite): boolean { site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('NoDelegate_CoreComments'); } /** * Check if comments are disabled in a certain site. * * @param siteId Site Id. If not defined, use current site. * @return Promise resolved with true if disabled, rejected or resolved with false otherwise. */ async areCommentsDisabled(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return this.areCommentsDisabledInSite(site); } /** * Delete a comment. * * @param comment Comment object to delete. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when deleted (with true if deleted in online, false otherwise), rejected otherwise. Promise resolved * doesn't mean that comments have been deleted, the resolve param can contain errors for comments not deleted. */ async deleteComment(comment: CoreCommentsCommentBasicData, siteId?: string): Promise<boolean> { siteId = siteId || CoreSites.getCurrentSiteId(); // Offline comment, just delete it. if (!comment.id) { await CoreCommentsOffline.removeComment( comment.contextlevel, comment.instanceid, comment.component, comment.itemid, comment.area, siteId, ); return false; } // Convenience function to store the action to be synchronized later. const storeOffline = async (): Promise<boolean> => { await CoreCommentsOffline.deleteComment( comment.id!, comment.contextlevel, comment.instanceid, comment.component, comment.itemid, comment.area, siteId, ); return false; }; if (!CoreApp.isOnline()) { // App is offline, store the comment. return storeOffline(); } // Send comment to server. try { await this.deleteCommentsOnline( [comment.id], comment.contextlevel, comment.instanceid, comment.component, comment.itemid, comment.area, siteId, ); return true; } catch (error) { if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, the user cannot send the comment so don't store it. throw error; } return storeOffline(); } } /** * Delete a comment. It will fail if offline or cannot connect. * * @param commentIds Comment IDs to delete. * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when deleted, rejected otherwise. Promise resolved doesn't mean that comments * have been deleted, the resolve param can contain errors for comments not deleted. */ async deleteCommentsOnline( commentIds: number[], contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const data: CoreCommentsDeleteCommentsWSParams = { comments: commentIds, }; await site.write('core_comment_delete_comments', data); await CoreUtils.ignoreErrors( this.invalidateCommentsData(contextLevel, instanceId, component, itemId, area, siteId), ); } /** * Returns whether WS to add/delete comments are available in site. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with true if available, resolved with false or rejected otherwise. * @since 3.8 */ async isAddCommentsAvailable(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); // First check if it's disabled. if (this.areCommentsDisabledInSite(site)) { return false; } return site.wsAvailable('core_comment_add_comments'); } /** * Get cache key for get comments data WS calls. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @return Cache key. */ protected getCommentsCacheKey( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', ): string { return this.getCommentsPrefixCacheKey(contextLevel, instanceId) + ':' + component + ':' + itemId + ':' + area; } /** * Get cache key for get comments instance data WS calls. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @return Cache key. */ protected getCommentsPrefixCacheKey(contextLevel: string, instanceId: number): string { return ROOT_CACHE_KEY + 'comments:' + contextLevel + ':' + instanceId; } /** * Retrieve a list of comments. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param page Page number (0 based). Default 0. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the comments. */ async getComments( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', page: number = 0, siteId?: string, ): Promise<CoreCommentsGetCommentsWSResponse> { const site = await CoreSites.getSite(siteId); const params: CoreCommentsGetCommentsWSParams = { contextlevel: contextLevel, instanceid: instanceId, component: component, itemid: itemId, area: area, page: page, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCommentsCacheKey(contextLevel, instanceId, component, itemId, area), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, }; const response = await site.read<CoreCommentsGetCommentsWSResponse>('core_comment_get_comments', params, preSets); if (response.comments) { // Update pageSize with the greatest count at the moment. if (typeof response.count == 'undefined' && response.comments.length > CoreCommentsProvider.pageSize) { CoreCommentsProvider.pageSize = response.comments.length; } return response; } throw new CoreError('No comments returned'); } /** * Get comments count number to show on the comments component. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Comments count with plus sign if needed. */ async getCommentsCount( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<string> { siteId = siteId ? siteId : CoreSites.getCurrentSiteId(); let trueCount = false; // Convenience function to get comments number on a page. const getCommentsPageCount = async (page: number): Promise<number> => { try { const response = await this.getComments(contextLevel, instanceId, component, itemId, area, page, siteId); // Count is only available in 3.8 onwards. if (typeof response.count != 'undefined') { trueCount = true; return response.count; } if (response.comments) { return response.comments.length || 0; } return -1; } catch { return -1; } }; const count = await getCommentsPageCount(0); if (trueCount || count < CoreCommentsProvider.pageSize) { return count + ''; } else if (CoreCommentsProvider.pageSizeOK && count >= CoreCommentsProvider.pageSize) { // Page Size is ok, show + in case it reached the limit. return (CoreCommentsProvider.pageSize - 1) + '+'; } const countMore = await getCommentsPageCount(1); // Page limit was reached on the previous call. if (countMore > 0) { CoreCommentsProvider.pageSizeOK = true; return (CoreCommentsProvider.pageSize - 1) + '+'; } return count + ''; } /** * Invalidates comments data. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCommentsData( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); await CoreUtils.allPromises([ // This is done with starting with to avoid conflicts with previous keys that were including page. site.invalidateWsCacheForKeyStartingWith(this.getCommentsCacheKey( contextLevel, instanceId, component, itemId, area, ) + ':'), site.invalidateWsCacheForKey(this.getCommentsCacheKey(contextLevel, instanceId, component, itemId, area)), ]); } /** * Invalidates all comments data for an instance. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCommentsByInstance(contextLevel: string, instanceId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getCommentsPrefixCacheKey(contextLevel, instanceId)); } } export const CoreComments = makeSingleton(CoreCommentsProvider); /** * Data returned by comment_area_exporter. */ export type CoreCommentsArea = { component: string; // Component. commentarea: string; // Commentarea. itemid: number; // Itemid. courseid: number; // Courseid. contextid: number; // Contextid. cid: string; // Cid. autostart: boolean; // Autostart. canpost: boolean; // Canpost. canview: boolean; // Canview. count: number; // Count. collapsediconkey: string; // @since 3.3. Collapsediconkey. displaytotalcount: boolean; // Displaytotalcount. displaycancel: boolean; // Displaycancel. fullwidth: boolean; // Fullwidth. linktext: string; // Linktext. notoggle: boolean; // Notoggle. template: string; // Template. canpostorhascomments: boolean; // Canpostorhascomments. }; /** * Params of core_comment_add_comments WS. */ type CoreCommentsAddCommentsWSParams = { comments: CoreCommentsCommentBasicData[]; }; export type CoreCommentsCommentBasicData = { id?: number; // Comment ID. contextlevel: string; // Contextlevel system, course, user... instanceid: number; // The id of item associated with the contextlevel. component: string; // Component. content: string; // Component. itemid: number; // Associated id. area?: string; // String comment area. }; /** * Comments Data returned by WS. */ export type CoreCommentsData = { id: number; // Comment ID. content: string; // The content text formatted. format: number; // Content format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). timecreated: number; // Time created (timestamp). strftimeformat: string; // Time format. profileurl: string; // URL profile. fullname: string; // Fullname. time: string; // Time in human format. avatar: string; // HTML user picture. userid: number; // User ID. delete?: boolean; // Permission to delete=true/false. }; /** * Data returned by core_comment_add_comments WS. */ export type CoreCommentsAddCommentsWSResponse = CoreCommentsData[]; /** * Params of core_comment_delete_comments WS. */ type CoreCommentsDeleteCommentsWSParams = { comments: number[]; }; /** * Params of core_comment_get_comments WS. */ type CoreCommentsGetCommentsWSParams = { contextlevel: string; // Contextlevel system, course, user... instanceid: number; // The Instance id of item associated with the context level. component: string; // Component. itemid: number; // Associated id. area?: string; // String comment area. page?: number; // Page number (0 based). sortdirection?: string; // Sort direction: ASC or DESC. }; /** * Data returned by core_comment_get_comments WS. */ export type CoreCommentsGetCommentsWSResponse = { comments: CoreCommentsData[]; // List of comments. count?: number; // @since 3.8. Total number of comments. perpage?: number; // @since 3.8. Number of comments per page. canpost?: boolean; // Whether the user can post in this comment area. warnings?: CoreWSExternalWarning[]; }; /** * Data sent by COMMENTS_COUNT_CHANGED_EVENT event. */ export type CoreCommentsCountChangedEventData = { contextLevel: string; instanceId: number; component: string; itemId: number; area: string; countChange: number; }; /** * Data sent by REFRESH_COMMENTS_EVENT event. */ export type CoreCommentsRefreshCommentsEventData = { contextLevel?: string; instanceId?: number; component?: string; itemId?: number; area?: string; };
the_stack
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable} from 'rxjs'; import {ActionSummaryMetaData} from '../constants/actions'; import {BACKEND_BASE_URL, KeyCodes, RotateDirection, SwipeDirection} from '../constants/constants'; import {CurrentUserResponse, ExportedTestCaseData, ExportImportProjectRequest, GetUserPresetGlobalVariableResponse, ImageResponse, ImagesResponse, InitDevicesResponse, OcrDetailsResponse, PlayActionRequest, PlayActionResponse, ProjectCopyRequest, ProjectListResponse, PythonDebuggerRequest, PythonDebuggerResponse, ScaledScreenDimensionsResponse, ScreenContentSummary, UuidResponse, VersionInfoResponse} from '../constants/interfaces'; import {Bounds, Point} from '../constants/rect'; import {ValidationRequestDetails} from '../constants/screen_validation_constants'; import {Shape} from '../constants/shape'; /** Communicates to the UIConductor Java backend */ @Injectable() export class BackendManagerService { readonly OPTIONS = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }) }; constructor(private readonly http: HttpClient) {} /** Adds the given action to current workflow */ addActionByUUID(uuid: string) { return this.http.get( BACKEND_BASE_URL + '/addActionByUUID', {params: new HttpParams().set('uuidStr', uuid)}); } /** Adds action to current workflow */ addActionToWorkflow(action: ActionSummaryMetaData) { return this.http.post(BACKEND_BASE_URL + '/addActionToWorkflow', action); } /** Add validation action to current workflow */ addValidationStep(action: ValidationRequestDetails) { return this.http.post(BACKEND_BASE_URL + '/addValidationStep', action); } /** Adds drag Action */ addDragAction(pointsList: Point[]) { return this.http.get(BACKEND_BASE_URL + '/addDragAction', { params: new HttpParams() .set( 'xList', pointsList.map(p => Math.floor(p.x).toString()).join(',')) .set( 'yList', pointsList.map(p => Math.floor(p.y).toString()).join(',')) }); } /** Stops playing current workflow */ cancelCurrentWorkflow() { return this.http.get(BACKEND_BASE_URL + '/cancelCurrentWorkflow'); } /** Creates a new workspace */ createNewWorkSpace() { return this.http.get(BACKEND_BASE_URL + '/createNewWorkSpace'); } /** copy project */ copyProject(projectCopyRequest: ProjectCopyRequest) { return this.http.post( BACKEND_BASE_URL + '/copyProjectTree', projectCopyRequest, this.OPTIONS); } /** Performs double click on current device */ doubleClick(x: number, y: number) { return this.http.get(BACKEND_BASE_URL + '/doubleclick', { params: new HttpParams() .set('x', Math.floor(x).toString()) .set('y', Math.floor(y).toString()) }); } /** Performs dragMove click on current device */ dragMove(x: number, y: number) { return this.http.get(BACKEND_BASE_URL + '/dragMove', { params: new HttpParams() .set('x', Math.floor(x).toString()) .set('y', Math.floor(y).toString()) }); } /** Performs dragStart on current device */ dragStart(x: number, y: number) { return this.http.get(BACKEND_BASE_URL + '/dragStart', { params: new HttpParams() .set('x', Math.floor(x).toString()) .set('y', Math.floor(y).toString()) }); } /** Performs dragStop on current device */ dragStop(x: number, y: number) { return this.http.get(BACKEND_BASE_URL + '/dragStop', { params: new HttpParams() .set('x', Math.floor(x).toString()) .set('y', Math.floor(y).toString()) }); } /** Performs Drag with context action on current devices */ dragWithStartEndContext( startX: number, startY: number, endX: number, endY: number) { return this.http.get(BACKEND_BASE_URL + '/dragWithStartEndContext', { params: new HttpParams() .set('startX', Math.floor(startX).toString()) .set('startY', Math.floor(startY).toString()) .set('endX', Math.floor(endX).toString()) .set('endY', Math.floor(endY).toString()) }); } /** Performs Swipe with context action on current devices */ swipeWithStartEndContext( startX: number, startY: number, endX: number, endY: number) { return this.http.get(BACKEND_BASE_URL + '/swipeWithStartEndContext', { params: new HttpParams() .set('startX', Math.floor(startX).toString()) .set('startY', Math.floor(startY).toString()) .set('endX', Math.floor(endX).toString()) .set('endY', Math.floor(endY).toString()) }); } /** Returns raw json test information for given test */ exportTestCase(uuid: string): Observable<ExportedTestCaseData> { return this.http.get<ExportedTestCaseData>( BACKEND_BASE_URL + '/exportTestCase', { params: new HttpParams().set('uuidStr', uuid), }); } /** * Returns dictionary of reference image uuids to reference image in form of * base64 string */ exportRefImagesForWorkflow(uuid: string): Observable<ImagesResponse> { return this.http.get<ImagesResponse>( BACKEND_BASE_URL + '/exportRefImagesForWorkflow', { params: new HttpParams().set('uuidStr', uuid), }); } /** * Exports the given project as a zip file */ exportCurrentProject(exportImportProjectReq: ExportImportProjectRequest) { const url = BACKEND_BASE_URL + '/exportProjectToZip?' + new HttpParams() .set('projectId', exportImportProjectReq.projectId) .set('projectName', exportImportProjectReq.projectName) .toString(); window.open(url); } /** * Exports the given project as a zip file */ exportTopLevelTests(exportImportProjectReq: ExportImportProjectRequest) { const url = BACKEND_BASE_URL + '/exportTopLevelCaseOnlyToZip?' + new HttpParams() .set('projectId', exportImportProjectReq.projectId) .set('projectName', exportImportProjectReq.projectName) .toString(); window.open(url); } /** Upload zip file and import */ unzipAndImport(projectName: string, file: File): Observable<unknown> { const formData = new FormData(); formData.append('file', file, file.name); formData.append('projectName', projectName); const headers = new HttpHeaders({'Accept': 'application/zip'}); return this.http.post( BACKEND_BASE_URL + '/unzipAndImport', formData, {headers}); } /** * Gets the content details from the select area. * (DisplayText|ResourceID|checked) */ getContentFromScreen(bounds: Bounds): Observable<ScreenContentSummary> { return this.http.get<ScreenContentSummary>( BACKEND_BASE_URL + '/getContentFromScreen', { params: new HttpParams() .set('startX', Math.floor(bounds.x1).toString()) .set('startY', Math.floor(bounds.y1).toString()) .set('endX', Math.floor(bounds.x2).toString()) .set('endY', Math.floor(bounds.y2).toString()) }); } /** * Gets the global variable from backend in plain string format to make it * simple. It doesn't include the resevered internal variables (e.g. adb * path, input path output path). Expected return will be something * similar to: $uicd_var1=abc,$uicd_var2=123. */ getUserPresetGlobalVariable(): Observable<GetUserPresetGlobalVariableResponse> { return this.http.get<GetUserPresetGlobalVariableResponse>( BACKEND_BASE_URL + '/getUserPresetGlobalVariable'); } /** * Set the global variable from backend in plain string format. * simple. Expected input should be in the following format: * $uicd_var1=abc,$uicd_var2=123. */ setUserPresetGlobalVariable(globalVariableStr: string) { return this.http.post( BACKEND_BASE_URL + '/setUserPresetGlobalVariable', globalVariableStr); } /** Fetches the current XML representation of the device screen */ fetchXML(): Observable<string[]> { return this.http.get<string[]>(BACKEND_BASE_URL + '/fetchCurrentXML'); } /** Gets current workflow in json format */ getCurrentWorkflow(): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/getCurrentWorkflow'); } /** Gets action details. */ getActionDetails(uuid: string): Observable<ActionSummaryMetaData> { return this.http.get<ActionSummaryMetaData>( BACKEND_BASE_URL + '/getActionDetails', {params: new HttpParams().set('uuidStr', uuid)}); } /** Gets current user of UICD */ getCurrentUser(): Observable<CurrentUserResponse> { return this.http.get<CurrentUserResponse>( BACKEND_BASE_URL + '/getCurrentUser'); } /** Gets adb connected devices from backend */ getDevicesList() { return this.http.get(BACKEND_BASE_URL + '/getDevicesList'); } /** Gets devices that already initialized in backend */ getInitedDevices(): Observable<InitDevicesResponse> { return this.http.get<InitDevicesResponse>( BACKEND_BASE_URL + '/getInitializedDevicesDetails'); } /** Gets current play mode */ getPlayMode(): Observable<string> { return this.http.get<string>(BACKEND_BASE_URL + '/getPlayMode'); } /** Gets xmldumper version and uicd backend version */ getVersionInfo(): Observable<VersionInfoResponse> { return this.http.get<VersionInfoResponse>( BACKEND_BASE_URL + '/getVersionInfo'); } /** * Checks whether backend already initialized the device to avoid * reinitialized devices when user refresh the frontend */ hasInitializedDevices(): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/hasInitedDevices'); } /** * Initializes single device in backend, backend will start the xmldumper * server on the device * @param deviceId */ initDevice(deviceId: string): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/initDevice', { params: new HttpParams().set('deviceId', deviceId), }); } /** * Initialize device list in backend, backend will start the xmldumper * server on the device * @param deviceIdList device id list separater by comma. * @param isCleanInit whether need a clean init. */ initDevicesFromListV2(deviceIdList: string, isCleanInit: boolean): Observable<InitDevicesResponse> { return this.http.get<InitDevicesResponse>( BACKEND_BASE_URL + '/initDevicesFromListV2', { params: new HttpParams() .set('devicesIdList', deviceIdList) .set('isCleanInit', isCleanInit.toString()), }); } /** Changes the current workflow in backend. */ loadWorkflow(uuid: string) { return this.http.get(BACKEND_BASE_URL + '/loadWorkflow', { params: new HttpParams().set('uuidStr', uuid), }); } /** * Performs long click on current device */ longClick(x: number, y: number, duration: number) { return this.http.get(BACKEND_BASE_URL + '/longclick', { params: new HttpParams() .set('x', Math.floor(x).toString()) .set('y', Math.floor(y).toString()) .set('duration', duration.toString()) }); } /** * Sends given keyCode to the backend and will click the button on the * current selected device * @param keyCode which key to click. */ pressKey(keyCode: KeyCodes): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/pressKey', { params: new HttpParams().set('keyCode', keyCode.toString()), }); } /** Plays current workflow */ playCurrentWorkflow(): Observable<PlayActionResponse> { return this.http.get<PlayActionResponse>( BACKEND_BASE_URL + '/playCurrentWorkflow'); } /** Plays the current workflow starting from given action */ playCurrentWorkflowFromAction(playActionRequest: PlayActionRequest): Observable<PlayActionResponse> { return this.http.post<PlayActionResponse>( BACKEND_BASE_URL + '/playCurrentWorkflowFromAction', playActionRequest, this.OPTIONS); } /** Plays the given action. */ playAction(playActionRequest: PlayActionRequest): Observable<PlayActionResponse> { return this.http.post<PlayActionResponse>( BACKEND_BASE_URL + '/playAction', playActionRequest, this.OPTIONS); } /** Removes the action with given uuid */ removeAction(index: string) { return this.http.post(BACKEND_BASE_URL + '/removeAction', index); } /** Removes last action in current workflow */ undo() { return this.http.get(BACKEND_BASE_URL + '/undo'); } /** Removes last action in current workflow */ redo() { return this.http.get(BACKEND_BASE_URL + '/redo'); } /** * Reorders the current workflow compound's children Action based on the * actionIdList on backend */ reorderActions(actionIdList: string[]) { return this.http.post( BACKEND_BASE_URL + '/reorderActions', JSON.stringify(actionIdList), this.OPTIONS); } /** * Saves the given workflow to backend * @workflow workflow description */ saveCurrentWorkflow(workflow: ActionSummaryMetaData) { return this.http.post( BACKEND_BASE_URL + '/saveCurrentWorkflow', JSON.stringify(workflow)); } /** * Saves the current workflow to backend */ saveCurrentWorkflowWithoutMetadata() { return this.http.post( BACKEND_BASE_URL + '/saveCurrentWorkflowWithoutMetadata', null); } /** * Sets different play configurations * @param mode SINGLE|MULTI|PLAYALL */ setPlayMode(mode: string): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/setPlayMode', { params: new HttpParams().set('playMode', mode), }); } /** * Sets play speed factor * @param playSpeedFactor. >= 0.1, backend have the logic to make sure it * greater than 0.1 */ setPlaySpeedFactor(playSpeedFactor: number) { return this.http.post( BACKEND_BASE_URL + '/setPlaySpeedFactor', playSpeedFactor); } /** * Changes the current device used for test * @param deviceId serial of the device to be used in the test */ selectedDeviceChanged(deviceId: string): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/selectedDeviceChanged', { params: new HttpParams().set('deviceId', deviceId), }); } /** Restart backend spring service */ softRestart() { return this.http.get(BACKEND_BASE_URL + '/softRestart'); } /** Performs swipe action */ swipe(startX: number, startY: number, endX: number, endY: number) { return this.http.get(BACKEND_BASE_URL + '/swipe', { params: new HttpParams() .set('startX', Math.floor(startX).toString()) .set('startY', Math.floor(startY).toString()) .set('endX', Math.floor(endX).toString()) .set('endY', Math.floor(endY).toString()) }); } /** * Sends the tap command to backend, (x,y) is at frontend scale(logic * point), and backend will covert to physical point(store the logic * point). */ tap(x: number, y: number, isStrictMode: boolean) { return this.http.get(BACKEND_BASE_URL + '/tap', { params: new HttpParams() .set('x', Math.floor(x).toString()) .set('y', Math.floor(y).toString()) .set('isStrictMode', String(isStrictMode)) }); } /** Validates the backend status */ validateUicdBackendConnection() { return this.http.get(BACKEND_BASE_URL + '/validateUicdBackendConnection'); } /** Performs Zoom action on current devices */ zoom(x1: number, y1: number, x2: number, y2: number, isZoomIn: boolean) { return this.http.get(BACKEND_BASE_URL + '/zoom', { params: new HttpParams() .set('x1', Math.floor(x1).toString()) .set('y1', Math.floor(y1).toString()) .set('x2', Math.floor(x2).toString()) .set('y2', Math.floor(y2).toString()) .set('isZoomIn', String(isZoomIn)) }); } /** * Updates the workflow with the same uuid. * @param workflow new workflow description. */ updateActionMetadata(workflow: ActionSummaryMetaData) { return this.http.post( BACKEND_BASE_URL + '/updateActionMetadata', JSON.stringify(workflow)); } /** Updates the validation action. */ updateValidationAction(uuidStr: string, req: ValidationRequestDetails) { return this.http.post( BACKEND_BASE_URL + '/updateValidationAction', JSON.stringify(req), {params: new HttpParams().set('uuidStr', uuidStr)}); } /** * Performs Swipe action on current device following given direction. */ quickSwipe(direction: SwipeDirection): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/quickSwipe', { params: new HttpParams().set('dir', direction), }); } /** * Performs Swipe action on current device following given direction. */ rotateScreen(direction: RotateDirection): Observable<unknown> { return this.http.get(BACKEND_BASE_URL + '/screenRotate', { params: new HttpParams().set('dir', direction), }); } /** Takes the screenshot of the current screen of selected device */ takeScreenshot(): Observable<ImageResponse> { return this.http.get<ImageResponse>(BACKEND_BASE_URL + '/takeScreenshot'); } /** Gets the scaled dimensions of the screenshot */ getScaledScreenDimensions(): Observable<ScaledScreenDimensionsResponse> { return this.http.get<ScaledScreenDimensionsResponse>( BACKEND_BASE_URL + '/getScaledScreenDimensions'); } /** Adds Image to image database */ addImage(imgBase64Str: string): Observable<UuidResponse> { return this.http.post<UuidResponse>( BACKEND_BASE_URL + '/addImage', imgBase64Str); } /** * Gets scaled regions from the backend so that can be saved in the * action */ getScaledRegions(regionsSelected: Shape[]): Observable<Shape[]> { return this.http.post<Shape[]>( BACKEND_BASE_URL + '/getScaledRegions', JSON.stringify(regionsSelected)); } /** * Gets scaled regions from the backend so that can be saved in the * action */ deleteImage(refImgUuid: string): Observable<void> { return this.http.post<void>(`${BACKEND_BASE_URL}/deleteImage`, refImgUuid); } /** * Creates new project. */ createProject(projectName: string): Observable<ProjectListResponse> { return this.http.post<ProjectListResponse>( BACKEND_BASE_URL + '/createProject', projectName); } /** * Deletes project. */ deleteProject(projectId: string): Observable<ProjectListResponse> { return this.http.post<ProjectListResponse>( BACKEND_BASE_URL + '/deleteProjectByProjectId', projectId); } /** * Adds share with user list to current project */ addShareWithUserListToProject(userList: string): Observable<void> { return this.http.post<void>( BACKEND_BASE_URL + '/addShareWithUserListToProject', userList); } /** * Gets project list that contains all the projects of current user. */ getProjectList(): Observable<ProjectListResponse> { return this.http.get<ProjectListResponse>( BACKEND_BASE_URL + '/getProjectList'); } /** * Gets project list that contains all the projects of the given user. */ getProjectListByUsername(username: string): Observable<ProjectListResponse> { return this.http.get<ProjectListResponse>( BACKEND_BASE_URL + '/getProjectListByUsername', { params: new HttpParams().set('username', username), }); } /** * Sets current project after user selects from project list. */ setCurrentProject(projectName: string): Observable<ProjectListResponse> { return this.http.post<ProjectListResponse>( BACKEND_BASE_URL + '/setCurrentProject', projectName); } /** * Fetches the methods available in the snippet validation action for the * selected package. * @param packageName name of the package of which the methods needs to * fetched */ getAllAvailableSnippetMethods(packageName: string) { return this.http.get(BACKEND_BASE_URL + '/getAllAvailableSnippetMethods', { params: new HttpParams().set('packageName', packageName), }); } /** Fetches details information from ocr engine. */ getOcrDetails() { return this.http.get<OcrDetailsResponse>( BACKEND_BASE_URL + '/getOcrDetails'); } /** Start python debugger service */ initPdbDebuggerServer(pythonDebugger: PythonDebuggerRequest): Observable<PythonDebuggerResponse> { return this.http.post<PythonDebuggerResponse>( BACKEND_BASE_URL + '/runPdbDebugger', pythonDebugger, this.OPTIONS); } /** Set break points in pdb debugger */ pdbDebuggerBreak(breakLines: string): Observable<PythonDebuggerResponse> { return this.http.get<PythonDebuggerResponse>( BACKEND_BASE_URL + '/pdbDebuggerBreak', {params: new HttpParams().set('breakLines', breakLines)}); } /** Remove break points in pdb debugger */ pdbDebuggerClear(breakLines: string): Observable<PythonDebuggerResponse> { return this.http.get<PythonDebuggerResponse>( BACKEND_BASE_URL + '/pdbDebuggerClear', {params: new HttpParams().set('breakLines', breakLines)}); } /** Continue in pdb debugger */ pdbDebuggerContinue(): Observable<PythonDebuggerResponse> { return this.http.get<PythonDebuggerResponse>( BACKEND_BASE_URL + '/pdbDebuggerContinue'); } /** Step in in pdb debugger */ pdbDebuggerStepIn(): Observable<PythonDebuggerResponse> { return this.http.get<PythonDebuggerResponse>( BACKEND_BASE_URL + '/pdbDebuggerStepIn'); } /** Next in pdb debugger */ pdbDebuggerNext(): Observable<PythonDebuggerResponse> { return this.http.get<PythonDebuggerResponse>( BACKEND_BASE_URL + '/pdbDebuggerNext'); } /** Stop the pdb debugger */ pdbDebuggerStop(): Observable<PythonDebuggerResponse> { return this.http.get<PythonDebuggerResponse>( BACKEND_BASE_URL + '/stopPdbDebugger'); } }
the_stack
import addElOrigin, { addElAttributeValueOrigin, addElAttributeNameOrigin } from "./addElOrigin"; import { normalizeHtml, normalizeHtmlAttribute } from "./normalize"; import { consoleWarn } from "../../helperFunctions/logging"; var htmlEntityRegex = /^\&[#a-zA-Z0-9]+\;/; var whitespaceRegex = /^[\s]+/; var tagEndRegex = /^(\s+)\/?>/; // var twoQuoteSignsRegex = /^['"]{2}/; const LOG_MAPPING = true; const config = { validateHtmlMapping: true }; function tagTypeHasClosingTag(tagName) { try { return document.createElement(tagName).outerHTML.indexOf("></") !== -1; } catch (err) { // For CustomElements createElement fails sometimes return true; } } // tries to describe the relationship between an assigned innerHTML value // and the value you get back when reading el.innerHTML. // e.g. you could assign "<input type='checkbox' checked>" and get back // "<input type='checkbox' checked=''>" // essentially this function serializes the elements content and compares it to the // assigned value export default function mapInnerHTMLAssignment( el, assignedInnerHTML, actionName, initialExtraCharsValue, contentEndIndex = assignedInnerHTML[0].length, nodesToIgnore: any[] = [] ) { var serializedHtml = el.innerHTML; var forDebuggingProcessedHtml = ""; var charOffsetInSerializedHtml = 0; var charsAddedInSerializedHtml = 0; if (initialExtraCharsValue !== undefined) { charsAddedInSerializedHtml = initialExtraCharsValue; } var assignedString = assignedInnerHTML[0]; // if (contentEndIndex === 0) { // contentEndIndex = assignedString.length // } // if (nodesToIgnore === undefined) { // nodesToIgnore = []; // } var error = Error(); // used to get stack trace, rather than capturing a new one every time processNewInnerHtml(el); function getCharOffsetInAssignedHTML() { return charOffsetInSerializedHtml - charsAddedInSerializedHtml; } // get offsets by looking at how the assigned value compares to the serialized value // e.g. accounts for differeces between assigned "&" and serialized "&amp;" function getCharMappingOffsets( textAfterAssignment, charOffsetAdjustmentInAssignedHtml, tagName ) { if (charOffsetAdjustmentInAssignedHtml === undefined) { charOffsetAdjustmentInAssignedHtml = 0; } var offsets: any[] | undefined = []; var extraCharsAddedHere = 0; for (var i = 0; i < textAfterAssignment.length; i++) { offsets.push(-extraCharsAddedHere); var char = textAfterAssignment[i]; var htmlEntityMatchAfterAssignment = textAfterAssignment .substr(i, 30) .match(htmlEntityRegex); var posInAssignedString = charOffsetInSerializedHtml + i - charsAddedInSerializedHtml + charOffsetAdjustmentInAssignedHtml - extraCharsAddedHere; if (posInAssignedString >= contentEndIndex) { // http://stackoverflow.com/questions/38892536/why-do-browsers-append-extra-line-breaks-at-the-end-of-the-body-tag break; // just don't bother for now } var textIncludingAndFollowingChar = assignedString.substr( posInAssignedString, 30 ); // assuming that no html entity is longer than 30 chars if (char === "\n" && textIncludingAndFollowingChar[0] == "\r") { extraCharsAddedHere--; } var htmlEntityMatch = textIncludingAndFollowingChar.match( htmlEntityRegex ); if ( tagName === "NOSCRIPT" && htmlEntityMatchAfterAssignment !== null && htmlEntityMatch !== null ) { // NOSCRIPT assignments: "&amp;" => "&amp;amp;", "&gt;" => "&amp;gt;" // so we manually advance over the "&amp;" for (var n = 0; n < "amp;".length; n++) { i++; extraCharsAddedHere++; offsets.push(-extraCharsAddedHere); } offsets.push(-extraCharsAddedHere); } if (htmlEntityMatchAfterAssignment !== null && htmlEntityMatch === null) { // assigned a character, but now it shows up as an entity (e.g. & ==> &amp;) var entity = htmlEntityMatchAfterAssignment[0]; for (var n = 0; n < entity.length - 1; n++) { i++; extraCharsAddedHere++; offsets.push(-extraCharsAddedHere); } } if (htmlEntityMatchAfterAssignment === null && htmlEntityMatch !== null) { // assigned an html entity but now getting character back (e.g. &raquo; => ») var entity = htmlEntityMatch[0]; extraCharsAddedHere -= entity.length - 1; } } if (offsets.length === 0) { offsets = undefined; } return { offsets: offsets, extraCharsAddedHere: extraCharsAddedHere }; } function processNewInnerHtml(el) { var children; if (el.tagName === "TEMPLATE") { children = el.content.childNodes; } else { children = Array.prototype.slice.apply(el.childNodes, []); } addElOrigin(el, "replaceContents", { action: actionName, children: children }); var childNodesToProcess: any[] = [].slice.call(children); childNodesToProcess = childNodesToProcess.filter(function(childNode) { var shouldIgnore = nodesToIgnore.indexOf(childNode) !== -1; return !shouldIgnore; }); childNodesToProcess.forEach(function(child) { var isTextNode = child.nodeType === 3; var isCommentNode = child.nodeType === 8; var isElementNode = child.nodeType === 1; if (LOG_MAPPING) { console.log( "assigned_", assignedString .substr(getCharOffsetInAssignedHTML(), 100) .replace(/\n/g, "\\n") ); if (isTextNode) { console.log( "text_____", (child.textContent || "").replace(/\n/g, "\\n").slice(0, 100) ); } else if (isCommentNode) { console.log( "comment ", "<!--" + (child.textContent || "").replace(/\n/g, "\\n").slice(0, 100) + "-->" ); } else { console.log( "outerHTML", child.outerHTML && child.outerHTML.replace(/\n/g, "\\n").slice(0, 100) ); } } if (isTextNode) { var text = child.textContent; text = normalizeHtml(text, child.parentNode.tagName); var res = getCharMappingOffsets(text, 0, child.parentNode.tagName); var offsets = res.offsets; var extraCharsAddedHere = res.extraCharsAddedHere; addElOrigin(child, "textValue", { action: actionName, trackingValue: assignedInnerHTML[1], value: serializedHtml, inputValuesCharacterIndex: [charOffsetInSerializedHtml], extraCharsAdded: charsAddedInSerializedHtml, offsetAtCharIndex: offsets, error: error }); charsAddedInSerializedHtml += extraCharsAddedHere; charOffsetInSerializedHtml += text.length; forDebuggingProcessedHtml += text; } else if (isCommentNode) { addElOrigin(child, "commentStart", { action: actionName, trackingValue: assignedInnerHTML[1], inputValuesCharacterIndex: [charOffsetInSerializedHtml], value: serializedHtml }); charOffsetInSerializedHtml += "<!--".length; forDebuggingProcessedHtml += "<!--"; addElOrigin(child, "textValue", { value: serializedHtml, trackingValue: assignedInnerHTML[1], inputValuesCharacterIndex: [charOffsetInSerializedHtml], action: actionName, error: error }); charOffsetInSerializedHtml += child.textContent.length; forDebuggingProcessedHtml += child.textContent; addElOrigin(child, "commentEnd", { action: actionName, trackingValue: assignedInnerHTML[1], inputValuesCharacterIndex: [charOffsetInSerializedHtml], value: serializedHtml }); charOffsetInSerializedHtml += "-->".length; forDebuggingProcessedHtml += "-->"; } else if (isElementNode) { addElOrigin(child, "openingTagStart", { action: actionName, trackingValue: assignedInnerHTML[1], inputValuesCharacterIndex: [charOffsetInSerializedHtml], value: serializedHtml, extraCharsAdded: charsAddedInSerializedHtml, error: error }); var openingTagStart = "<" + child.tagName; charOffsetInSerializedHtml += openingTagStart.length; forDebuggingProcessedHtml += openingTagStart; for (var i = 0; i < child.attributes.length; i++) { let extraCharsAddedHere = 0; var attr = child.attributes[i]; var charOffsetInSerializedHtmlBefore = charOffsetInSerializedHtml; var whitespaceBeforeAttributeInSerializedHtml = " "; // always the same var assignedValueFromAttrStartOnwards = assignedString.substr( getCharOffsetInAssignedHTML(), 100 ); var whitespaceMatches = assignedValueFromAttrStartOnwards.match( whitespaceRegex ); var whitespaceBeforeAttributeInAssignedHtml; if (whitespaceMatches !== null) { whitespaceBeforeAttributeInAssignedHtml = whitespaceMatches[0]; } else { // something broke, but better to show a broken result than nothing at all if (config.validateHtmlMapping) { consoleWarn( "no whitespace found at start of", assignedValueFromAttrStartOnwards ); } whitespaceBeforeAttributeInAssignedHtml = ""; } var attrStr = attr.name; var textAfterAssignment: any = normalizeHtmlAttribute( attr.textContent ); attrStr += "='" + textAfterAssignment + "'"; var offsetAtCharIndex: number[] = []; var extraWhitespaceBeforeAttributeInAssignedHtml = whitespaceBeforeAttributeInAssignedHtml.length - whitespaceBeforeAttributeInSerializedHtml.length; extraCharsAddedHere -= extraWhitespaceBeforeAttributeInAssignedHtml; offsetAtCharIndex.push(-extraCharsAddedHere); // char index for " " before attr var offsetInAssigned = getCharOffsetInAssignedHTML() + whitespaceBeforeAttributeInAssignedHtml.length; // add mapping for attribute name for (var charIndex in attr.name) { offsetAtCharIndex.push(-extraCharsAddedHere); } offsetInAssigned += attr.name.length; var nextCharacters = assignedString.substr(offsetInAssigned, 50); var equalsSignIsNextNonWhitespaceCharacter = /^[\s]*=/.test( nextCharacters ); if (!equalsSignIsNextNonWhitespaceCharacter) { if (attr.textContent !== "") { consoleWarn("empty text content"); // debugger } // value of attribute is omitted in original html const eqQuoteQuote: any = '=""'; for (var charIndex in eqQuoteQuote) { extraCharsAddedHere++; offsetAtCharIndex.push(-extraCharsAddedHere); } } else { var whitespaceBeforeEqualsSign = nextCharacters.match( /^([\s]*)=/ )[1]; extraCharsAddedHere -= whitespaceBeforeEqualsSign.length; offsetInAssigned += whitespaceBeforeEqualsSign.length; // map `=` character offsetAtCharIndex.push(-extraCharsAddedHere); offsetInAssigned += "=".length; var nextCharacters = assignedString.substr(offsetInAssigned, 50); var whitespaceBeforeNonWhiteSpace = nextCharacters.match( /^([\s]*)[\S]/ )[1]; extraCharsAddedHere -= whitespaceBeforeNonWhiteSpace.length; offsetInAssigned += whitespaceBeforeNonWhiteSpace.length; // map `"` character offsetAtCharIndex.push(-extraCharsAddedHere); offsetInAssigned += '"'.length; var charOffsetAdjustmentInAssignedHtml = offsetInAssigned - getCharOffsetInAssignedHTML(); var res = getCharMappingOffsets( textAfterAssignment, charOffsetAdjustmentInAssignedHtml, child.tagName ); if (res.offsets === undefined) { // Pretty sure this can only happen if there is a bug further up, but for now // allow it to happen rather than breaking everything // specifically this was happening on StackOverflow, probably because we don't // support tables yet (turn <table> into <table><tbody>), // but once that is supported this might just fix itself consoleWarn("No offsets for attribute mapping"); for (let ii = 0; ii < textAfterAssignment.length; ii++) { offsetAtCharIndex.push(-extraCharsAddedHere); } } else { res.offsets.forEach(function(offset, i) { offsetAtCharIndex.push(offset - extraCharsAddedHere); }); extraCharsAddedHere += res.extraCharsAddedHere; } var lastOffset = offsetAtCharIndex[offsetAtCharIndex.length - 1]; offsetAtCharIndex.push(lastOffset); // map the "'" after the attribute value } addElAttributeNameOrigin(child, attr.name, { action: actionName, trackingValue: assignedInnerHTML[1], value: serializedHtml, inputValuesCharacterIndex: [charOffsetInSerializedHtmlBefore], extraCharsAdded: charsAddedInSerializedHtml, offsetAtCharIndex: offsetAtCharIndex, error: error }); addElAttributeValueOrigin(child, attr.name, { action: actionName, trackingValue: assignedInnerHTML[1], value: serializedHtml, inputValuesCharacterIndex: [ charOffsetInSerializedHtmlBefore + (" " + attr.name).length ], extraCharsAdded: charsAddedInSerializedHtml, offsetAtCharIndex: offsetAtCharIndex, error: error }); charsAddedInSerializedHtml += extraCharsAddedHere; charOffsetInSerializedHtml += whitespaceBeforeAttributeInSerializedHtml.length + attrStr.length; forDebuggingProcessedHtml += whitespaceBeforeAttributeInSerializedHtml + attrStr; } var openingTagEnd = ">"; var assignedStringFromCurrentOffset = assignedString.substr( getCharOffsetInAssignedHTML(), 200 ); if (assignedStringFromCurrentOffset === "") { // debugger; } var matches = assignedStringFromCurrentOffset.match(tagEndRegex); var whitespaceBeforeClosingAngleBracketInAssignedHTML = ""; if (matches !== null) { // something like <div > (with extra space) // this char will not show up in the re-serialized innerHTML whitespaceBeforeClosingAngleBracketInAssignedHTML = matches[1]; } charsAddedInSerializedHtml -= whitespaceBeforeClosingAngleBracketInAssignedHTML.length; if (!tagTypeHasClosingTag(child.tagName)) { if (assignedString[getCharOffsetInAssignedHTML()] === "/") { // something like <div/> // this char will not show up in the re-serialized innerHTML charsAddedInSerializedHtml -= 1; } else { var explicitClosingTag = "</" + child.tagName.toLowerCase() + ">"; var explicitClosingTagAndOpeningTagEnd = ">" + explicitClosingTag; if ( assignedString .substr( getCharOffsetInAssignedHTML(), explicitClosingTagAndOpeningTagEnd.length ) .toLowerCase() === explicitClosingTagAndOpeningTagEnd ) { // something like <div></div> // this char will not show up in the re-serialized innerHTML charsAddedInSerializedHtml -= explicitClosingTag.length; } } } addElOrigin(child, "openingTagEnd", { action: actionName, trackingValue: assignedInnerHTML[1], inputValuesCharacterIndex: [charOffsetInSerializedHtml], value: serializedHtml, extraCharsAdded: charsAddedInSerializedHtml, error: error }); charOffsetInSerializedHtml += openingTagEnd.length; forDebuggingProcessedHtml += openingTagEnd; if (child.tagName === "IFRAME") { forDebuggingProcessedHtml += child.outerHTML; charOffsetInSerializedHtml += child.outerHTML.length; } else { processNewInnerHtml(child); } if (tagTypeHasClosingTag(child.tagName)) { addElOrigin(child, "closingTag", { action: actionName, trackingValue: assignedInnerHTML[1], inputValuesCharacterIndex: [charOffsetInSerializedHtml], value: serializedHtml, extraCharsAdded: charsAddedInSerializedHtml, error: error }); var closingTag = "</" + child.tagName + ">"; charOffsetInSerializedHtml += closingTag.length; forDebuggingProcessedHtml += closingTag; let hasClosingTagButNotInAssignedHtml = assignedString.substr( getCharOffsetInAssignedHTML() - ">".length - closingTag.length, 2 ) === "/>"; if (hasClosingTagButNotInAssignedHtml) { console.log("hasClosingTagButNotInAssignedHtml"); // I don't really understand the +1, but it's needed charsAddedInSerializedHtml += closingTag.length - "/>".length + 1; } } } else { throw "not handled"; } // consoleLog("processed", forDebuggingProcessedHtml, assignedInnerHTML.toString().toLowerCase().replace(/\"/g, "'") === forDebuggingProcessedHtml.toLowerCase()) }); } }
the_stack
import { forEachProperty } from '@fluid-experimental/property-binder'; import { BaseProxifiedProperty, PropertyProxy } from '@fluid-experimental/property-proxy'; import { Workspace} from '@fluid-experimental/property-properties'; import {TypeIdHelper} from '@fluid-experimental/property-changeset'; import { BaseProperty, PropertyFactory,ReferenceArrayProperty, ReferenceProperty, ContainerProperty, MapProperty} from '@fluid-experimental/property-properties'; import memoize from 'memoize-one'; import { HashCalculator } from './HashCalculator'; import { IColumns, IExpandedMap, IInspectorRow, IInspectorSearchAbortHandler, IInspectorSearchCallback, IInspectorSearchMatch, IInspectorSearchMatchMap, IInspectorTableProps} from './InspectorTableTypes'; import { Utils } from './typeUtils'; const { isEnumProperty, isEnumArrayProperty, isInt64Property, isReferenceProperty, isUint64Property, isCollectionProperty, isReferenceArrayProperty, isReferenceCollectionTypeid, isReferenceMapProperty } = Utils; const idSeparator = '/'; interface IShowNextResultResult { /** * New rows needed to expand to show next results */ expandedRows: IExpandedMap; /** * row index of the next result. This value is used to automatically scroll in the table */ rowIdx: number; /** * Next result column index */ columnIdx: number; } /** * Generates: * @type{IShowNextResultResult} object, containing information, * required to make desired match visible and where this match is located * * Parameters: * @data List of all @type{IInspectorRow} items, which have to be displayed in the table * @param currentlyExpanded List of hashes of nodes, which are currently expanded (for example by user) * @param filteredExpanded List of hashes of nodes, which have to be expanded to make matching elements visible * @param allMatches List of @type{IInspectorSearchMatch} containing information about matching rows * @param resultIndex Index of desired matching item, starting from 0 */ export const showNextResult = ( data: IInspectorRow[], currentlyExpanded: IExpandedMap, allMatches: IInspectorSearchMatch[], resultIndex: number, childToParentMap: {[key: string]: string}) : IShowNextResultResult => { const desiredDataItem = allMatches[resultIndex]; // sanity check if (!desiredDataItem) { return {expandedRows: currentlyExpanded, rowIdx: -1, columnIdx: -1}; } // iterate through all the parents until root is reached let toBeExpandedNode = childToParentMap[desiredDataItem.rowId]; while (toBeExpandedNode) { if (!(toBeExpandedNode in currentlyExpanded)) { currentlyExpanded[toBeExpandedNode] = true; } toBeExpandedNode = childToParentMap[toBeExpandedNode]; } const rowInfo = findMatchingElementIndexInDataSet(data, currentlyExpanded, desiredDataItem); return {expandedRows: currentlyExpanded, rowIdx: rowInfo.idx, columnIdx: desiredDataItem.indexOfColumn}; }; /** * Recursive function to find index of matching element in data set * * Generates: * Object, containing information about row, containing matching element: * - index of the row * - flag whether the element was found * * Parameters: * @param data List of all @type{IInspectorRow} items of the dataset * @param currentlyExpanded List of hashes of nodes, which are currently expanded * @param matchingElement @type{IInspectorSearchMatch} object, containing information about match * @param rowCounter (default value 0) aggregation counter, used during recursive process */ function findMatchingElementIndexInDataSet(data: IInspectorRow[], currentlyExpanded: IExpandedMap, matchingElement: IInspectorSearchMatch, rowCounter = 0): {idx: number, found: boolean} { for (const row of data) { if (row.id === matchingElement.rowId) { return {idx: rowCounter, found: true}; } rowCounter++; // If current row is expanded - search recursively among its children if (row.id in currentlyExpanded) { const res = findMatchingElementIndexInDataSet(row.children!, currentlyExpanded, matchingElement, rowCounter); if (res.found) { return res; } else { rowCounter = res.idx; } } } return {idx: rowCounter, found: false}; } interface ISearchLevelState { data?: IInspectorRow[]; index: number; } export interface IInspectorSearchState { abort?: boolean; newMatchFound?: boolean; updateScheduled?: number; chunkSize?: number; expression?: string; foundMatches: IInspectorSearchMatch[]; levels?: ISearchLevelState[]; matchesMap: IInspectorSearchMatchMap; scheduled?: number; childToParentMap: {[key: string]: string}; } export interface IInspectorSearchControls { abortHandler: IInspectorSearchAbortHandler; state: IInspectorSearchState; } const abortSearch = (searchState: IInspectorSearchState) => { if (searchState.scheduled !== undefined || searchState.updateScheduled !== undefined) { clearTimeout(searchState.scheduled); clearTimeout(searchState.updateScheduled); } searchState.abort = true; }; const updateHandler = (callback: IInspectorSearchCallback, searchState: IInspectorSearchState, done: boolean) => { searchState.newMatchFound = false; searchState.updateScheduled = window.setTimeout(() => { callback(searchState.foundMatches, searchState.matchesMap, done, searchState.childToParentMap); }, 0); }; /** * This search function will recursively traverse the table rows provided as `data` in chunks of the given size. * After processing `chunksSize` amount of rows, it will return control to the main thread and queue a follow-up run if * necessary, until the whole data set has been searched through. Incomplete table rows will be filled on the fly. In * order to avoid infinite search, the function will not follow references. * @param searchExpression The term to search for. * @param data The data set to search. * @param dataGetter The data getter function that is used to determine cell values. * @param columns An array of columns to search. * @param handleUpdate A callback that will be invoked for every search result, or when the search is completed. * @param toTableRowsProps A subset of the inspector table props that is passed on to the toTableRows method. * @param toTableRowsOptions Options that influence the behaviour of the toTableRows method. * @param searchState An object storing the (intermediate) search results and information on how to proceed in * subsequent calls. Users don't need to mind this. * @param chunkSize The size of the chunk (number of rows) to search in each pass. * @param recursive A flag indicating whether the search function has been called recursively by itself. Users don't * need to mind this. * @param entryPoint A flag indicating whether this functions was the entry point of a recursive traversal. Users don't * need to mind this. * @return An object that gives access to the search state and abort handler. While the state object needs to be passed * to future search calls, the abort handler is a function that can be used to abort the search process at any time. */ export const search = ( searchExpression: string, data: IInspectorRow[], dataGetter, columns: IColumns[], handleUpdate: IInspectorSearchCallback, toTableRowsProps: IToTableRowsProps, toTableRowsOptions: IToTableRowsOptions, searchState: IInspectorSearchState = { foundMatches: [], matchesMap: {}, childToParentMap: {} }, chunkSize = 1000, recursive = false, entryPoint = true): IInspectorSearchControls => { // Check if search should be aborted. if (searchState.abort) { return { abortHandler: () => { /*noop*/ }, state: searchState, }; } let searchControls: IInspectorSearchControls | undefined; // Prepare the search state object when calling this method for the first time. if (searchState.expression === undefined) { searchState.expression = searchExpression.toLowerCase(); } if (searchState.scheduled !== undefined) { searchState.scheduled = undefined; } if (!searchState.levels) { searchState.levels = [{ data, index: 0 }]; } if (searchState.chunkSize === undefined) { searchState.chunkSize = chunkSize; } const levelState = searchState.levels[searchState.levels.length - 1]; const rows = levelState.data || data; // Iterate over all rows in a depth first traversal. let item: IInspectorRow; for (; levelState.index < rows.length; ++levelState.index) { // Check if we need to interrupt at the end of a chunk. if (searchState.chunkSize === 0 || searchState.newMatchFound) { // Schedule next iteration. We would like to do it only if nothing was found. if (searchState.chunkSize === 0 && !searchState.newMatchFound) { if (searchState.scheduled === undefined) { searchState.scheduled = window.setTimeout(() => { searchState.chunkSize = chunkSize; search(searchExpression, rows, dataGetter, columns, handleUpdate, toTableRowsProps, toTableRowsOptions, searchState, chunkSize, false, true); }, 10); } } if (entryPoint && searchState.newMatchFound) { updateHandler(handleUpdate, searchState, false); } return { abortHandler: abortSearch.bind(null, searchState), state: searchState, }; } item = rows[levelState.index]; searchState.childToParentMap[item.id] = item.parentId; // Skip data creation row. if (item.context === undefined) { continue; } // Search current row and store the result in the search state. for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) { // TODO: Not sure if we pass the correct row index to the data getter. I think it should be the overall index in // the table. That's at least what the base table seems to pass to it. const column = columns[columnIndex]; const validGetter = dataGetter && dataGetter({ column, columnIndex, columns, rowData: item, rowIndex: levelState.index }); const cell = validGetter || item[column.dataKey]; if ((cell !== undefined ? String(cell).toLowerCase() : '').includes(searchState.expression!)) { if (!searchState.matchesMap[item.id]) { searchState.matchesMap[item.id] = []; } if (!searchState.matchesMap[item.id][columnIndex]) { searchState.foundMatches.push({rowId: item.id, indexOfColumn: columnIndex}); searchState.matchesMap[item.id][columnIndex] = true; searchState.newMatchFound = true; break; } } } if (searchState.newMatchFound) { if (entryPoint) { updateHandler(handleUpdate, searchState, false); } return { abortHandler: abortSearch.bind(null, searchState), state: searchState, }; } // Recursively search through children. --searchState.chunkSize; if (item.children && !item.isReference) { if (item.children[0].context === 'd') { fillExpanded({[item.id]: true}, [item], toTableRowsProps, toTableRowsOptions); } if (item.children.length > 0) { searchState.levels.push({ data: item.children, index: 0 }); searchControls = search(searchExpression, item.children, dataGetter, columns, handleUpdate, toTableRowsProps, toTableRowsOptions, searchState, chunkSize, true, false); if (searchState.newMatchFound || (searchState.chunkSize === 0 && searchState.scheduled !== undefined)) { if (entryPoint && searchState.newMatchFound) { updateHandler(handleUpdate, searchState, false); } return searchControls; } } } } // We are done with this level. searchState.levels.pop(); if (!recursive && searchState.levels.length > 0) { // Walk up the hierarchy and continue in the parent. const parent = searchState.levels[searchState.levels.length - 1]; ++parent.index; searchControls = search(searchExpression, parent.data!, dataGetter, columns, handleUpdate, toTableRowsProps, toTableRowsOptions, searchState, chunkSize, false, false); } // If we are in the first instance of this function on the stack trace (i.e. all recursively called instances have // returned already) and have checked all rows or found a new match, we call the search result update handler. if (entryPoint && (searchState.newMatchFound || searchState.levels.length === 0)) { updateHandler(handleUpdate, searchState, searchState.levels.length === 0); } return searchControls ? searchControls : { abortHandler: abortSearch.bind(null, searchState), state: searchState, }; }; export const isPrimitive = memoize((typeid: string): boolean => { return TypeIdHelper.isPrimitiveType(typeid); }); const getTypeid = memoize((property: BaseProperty): string => { return isEnumProperty(property) || property.getContext() !== 'single' ? property.getFullTypeid() : property.getTypeid(); }); export const getCollectionTypeid = memoize((property: BaseProperty): string => { return isEnumArrayProperty(property) ? (property as any).getFullTypeid(true) : property.getTypeid(); }); export const getReferenceValue = (rowData: IInspectorRow) => { const parentProp = (rowData.parent! as ContainerProperty); let path = ''; if (Utils.isReferenceCollectionTypeid(getCollectionTypeid(parentProp))) { path = parentProp.getValue(rowData.propertyId) as string; } else { const unresolvedProperty = parentProp.get([rowData.propertyId, BaseProperty.PATH_TOKENS.REF]) as unknown as ReferenceProperty; path = unresolvedProperty.getValue() as string; } return path; }; const getShortId = (parentPath: string, childId: string | undefined = undefined): string => { const sanitizer = [ { searchFor: /[.]|[\[]/g, replaceWith: idSeparator }, { searchFor: /[\]]/g, replaceWith: '' }, { searchFor: /\/[\/]+/g, replaceWith: idSeparator }, ]; const absolutePath = childId !== undefined ? parentPath + idSeparator + childId : parentPath; const hash = new HashCalculator(); hash.pushString(sanitizePath(absolutePath, sanitizer)); return hash.getHash(); }; /** * Checks if a row is expandable. * @param data The data of the current row. * @param context The specified context of the row. Will only be used if data is primitive. * @param typeid The specified typeid of the row. * @param dataCreation Indicates if data creation is enabled */ const isExpandable = (data: any, context: string, typeid: string, dataCreation: boolean): boolean => { context = (data && data.getProperty) ? data.getProperty().getContext() : context; // If data creation is enabled everything except primitives is expandable to access the data // creation. Otherwise, make sure that properties contain at least one element. return dataCreation ? data && (context !== 'single' || !isPrimitive(typeid)) : data && ((context !== 'single' && (data.size > 0 || data.length > 0)) || (!isPrimitive(typeid) && Object.keys(data).length > 0)); }; const addAdditionalRow = (subRows, id, parentProperty) => { const undefinedRowData = { context: undefined, data: undefined, id: id + '/Add', name: '', parent: parentProperty, typeid: undefined, value: undefined, }; const isDefinedParent = parentProperty.getParent() !== undefined; const isNotUint64Property = !isUint64Property(parentProperty); const isNotInt64Property = !isInt64Property(parentProperty); const isNotEnumProperty = !isEnumProperty(parentProperty); const canAddData = (isDefinedParent || parentProperty.isRoot()) && (parentProperty.isDynamic() || isCollectionProperty(parentProperty)) && (isNotUint64Property || isNotInt64Property || isNotEnumProperty); if (canAddData) { subRows.push(undefinedRowData); } }; const compareName = (a: string, b: string) => { // ignore upper and lowercase const nameA = a.toUpperCase(); const nameB = b.toUpperCase(); if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; }; const compareNameDesc = (a: string, b: string) => { return compareName(a, b) * -1; }; interface IToTableRowsOptions { depth: number; addDummy: boolean; followReferences: boolean; ascending: boolean; parentIsConstant?: boolean; } interface IPropertyToTableRowOptions extends Partial<IToTableRowsOptions> { depth: number; dataCreation: boolean; } export const dummyChild = { children: undefined, context: 'd', data: 'd', id: 'd', isConstant: false, isReference: false, name: 'd', parentId: 'd', parentIsConstant: false, propertyId: 'd', typeid: 'd', value: 'd', }; const OPTION_DEFAULTS = { depth: 0, addDummy: true, followReferences: true, ascending: true, parentIsConstant: false }; type IToTableRowsProps = Pick<IInspectorTableProps, 'dataCreationHandler' | 'dataCreationOptionGenerationHandler' | 'childGetter' | 'nameGetter' | 'readOnly'>; export const toTableRows = ( { data, id = '', }: IInspectorRow, props: IToTableRowsProps, options: Partial<IToTableRowsOptions> = {}, pathPrefix: string = '', ): IInspectorRow[] => { const { ascending, parentIsConstant } = {...OPTION_DEFAULTS, ...options}; const dataCreation = (props.readOnly !== true) && !parentIsConstant && !!props.dataCreationHandler && !!props.dataCreationOptionGenerationHandler; const subRows: IInspectorRow[] = []; const parentProperty = data.getProperty(); const dataContext = parentProperty.getContext(); const keys = Object.keys(parentProperty.getEntriesReadOnly()); let sortedKeys = keys; if (dataContext === 'map' || dataContext === 'single') { if (ascending) { sortedKeys = keys.sort(compareName); } else { sortedKeys = keys.sort(compareNameDesc); } } switch (dataContext) { case 'single': { sortedKeys.forEach((key) => { const newRow = singlePropertyTableRow(data, key, id, props, {...OPTION_DEFAULTS, ...options, dataCreation}, pathPrefix); subRows.push(newRow); }); break; } default: { sortedKeys.forEach((key) => { const newRow = collectionChildTableRow(data, key, id, props, {...OPTION_DEFAULTS, ...options, dataCreation}, pathPrefix); subRows.push(newRow); }); break; } } if (dataCreation) { addAdditionalRow(subRows, id, parentProperty); } return subRows; }; const createInvalidReference = (parentData: BaseProxifiedProperty, propertyId: string, parentRowId: string, props: IToTableRowsProps, options: IPropertyToTableRowOptions, pathPrefix: string) => { const parentProperty = parentData.getProperty(); const newId = getShortId(pathPrefix + parentProperty.getAbsolutePath(), propertyId); const parentIsConstant = !!options.parentIsConstant; const newRow: IInspectorRow = { children: undefined, context: 'single', data: undefined, id: newId, isConstant: false, isReference: true, name: String(propertyId), parent: parentProperty, parentId: parentRowId, parentIsConstant, propertyId: String(propertyId), typeid: 'Reference', value: '', }; return newRow; }; /** * Construct a table row for an entry in a property that is not a collection. */ export const singlePropertyTableRow = (parentData: BaseProxifiedProperty, propertyId: string, parentRowId: string, props: IToTableRowsProps, options: IPropertyToTableRowOptions, pathPrefix: string) : IInspectorRow => { const { depth, addDummy, dataCreation, followReferences, ascending } = options; const parentIsConstant = !!options.parentIsConstant; const parentProperty = parentData.getProperty(); let property; // when we try to access an non-existing element of an array, the 'get' method throws which causes app crash try { property = (parentProperty as ContainerProperty).get(propertyId); } catch { return createInvalidReference(parentData, propertyId, parentRowId, props, options, pathPrefix); } const unresolvedProperty = parentData.getProperty([propertyId, BaseProperty.PATH_TOKENS.REF]); if (property === undefined || !followReferences || !property.getContext) { // This could happen if the property is ReferenceProperty that points to an invalid reference. property = unresolvedProperty; } const currentContext = property.getContext(); const currentTypeid = getTypeid(property); let determinedData = parentData[propertyId]; // Show a value only if the typeid of the property is primitive // Use the PropertyProxy's caret syntax to show the string representation of properties that support it. const determinedValue = getPropertyValue(parentData, propertyId, currentContext, currentTypeid, followReferences); if (isReferenceProperty(property) && !followReferences) { determinedData = undefined; } // Apply custom child and name getters determinedData = props.childGetter!(determinedData, propertyId, parentProperty, currentTypeid, currentContext); const name = props.nameGetter!(propertyId, parentProperty, currentTypeid, currentContext); const isPropExpandable = isExpandable(determinedData, currentContext, currentTypeid, dataCreation); const newId = getShortId(pathPrefix + parentProperty.getAbsolutePath(), propertyId); const propertyIdString = String(propertyId); const newRow: IInspectorRow = { children: undefined, context: currentContext, data: determinedData, id: newId, isConstant: property && (property as any)._isConstant, isReference: isReferenceProperty(unresolvedProperty), name: name === propertyId ? propertyIdString : name, parent: parentProperty, parentId: parentRowId, parentIsConstant, propertyId: propertyIdString, typeid: currentTypeid, value: determinedValue, }; if (isPropExpandable) { if (depth !== 0) { newRow.children = toTableRows( { ...newRow }, props, { addDummy, ascending, depth: depth - 1, followReferences, parentIsConstant: newRow.isConstant || newRow.parentIsConstant }, pathPrefix, ); } else if (addDummy) { newRow.children = [dummyChild]; } } return newRow; }; /** * Construct a table row for an entry in a collection property. */ export const collectionChildTableRow = (collectionPropertyProxy: BaseProxifiedProperty, propertyId: string, parentRowId: string, props: IToTableRowsProps, options: IPropertyToTableRowOptions, pathPrefix: string): IInspectorRow => { const collectionProperty = collectionPropertyProxy.getProperty() as ContainerProperty; let propertyProxy: BaseProxifiedProperty | undefined; let prop; // when we try to access an non-existing element of an array, the 'get' method throws which causes app crash try { prop = (collectionProperty as ContainerProperty).get(propertyId); } catch { return createInvalidReference(collectionPropertyProxy, propertyId, parentRowId, props, options, pathPrefix); } propertyProxy = (prop && PropertyFactory.instanceOf(prop, 'BaseProperty') ? PropertyProxy.proxify(prop) : prop) as BaseProxifiedProperty; const { depth, addDummy, dataCreation, followReferences, ascending } = options; const parentIsConstant = !!options.parentIsConstant; const collectionTypeid = getCollectionTypeid(collectionProperty); const isReferenceCollection = isReferenceCollectionTypeid(collectionTypeid); // Always start with the collection typeid, and fresh variables let determinedData; let determinedValue; let currentTypeid = collectionTypeid; let currentContext = 'single'; let property: BaseProperty | BaseProxifiedProperty | undefined = propertyProxy; if (!isReferenceCollection || (isReferenceCollection && followReferences)) { if (propertyProxy !== undefined && propertyProxy.getProperty && PropertyFactory.instanceOf(propertyProxy.getProperty(), 'BaseProperty')) { property = propertyProxy.getProperty() ; currentTypeid = getTypeid(property); currentContext = property.getContext(); } else if (isReferenceCollection) { // Try to obtain a property const {referencedPropertyParent, relativePathFromParent} = PropertyProxy.getParentOfReferencedProperty(collectionProperty as ReferenceArrayProperty, propertyId); if (referencedPropertyParent && relativePathFromParent) { property = (referencedPropertyParent as ContainerProperty).get(relativePathFromParent)!; if (property) { if (PropertyFactory.instanceOf(property as BaseProperty, 'BaseProperty')) { currentTypeid = getTypeid(property); currentContext = property.getContext(); } else { currentTypeid = getCollectionTypeid(referencedPropertyParent); } } } } else if (isEnumProperty(collectionProperty.get(propertyId)!) && collectionProperty.getContext() === 'map') { // TODO: Temporary fix as the full typeid of enum maps is currently wrong property = (collectionProperty as MapProperty).get(propertyId)!; currentTypeid = property.getFullTypeid(); currentContext = property.getContext(); } } // In case a set is processed there is no valid key, take the guid instead. propertyId = collectionProperty.getContext() === 'set' ? (propertyProxy as any).guid : propertyId; determinedValue = getPropertyValue(collectionPropertyProxy, propertyId, currentContext, currentTypeid, followReferences); if (propertyProxy && (followReferences || !TypeIdHelper.isReferenceTypeId(currentTypeid))) { determinedData = propertyProxy; } // Apply custom child and name getters determinedData = props.childGetter!( determinedData, propertyId, collectionProperty, currentTypeid, currentContext); const name = props.nameGetter!(propertyId, collectionProperty, currentTypeid, currentContext); const isPropExpandable = isExpandable(determinedData, currentContext, currentTypeid, dataCreation); const children = undefined; const newId = getShortId(pathPrefix + collectionProperty.getAbsolutePath(), propertyId); const propertyIdString = String(propertyId); const newRow: IInspectorRow = { children, context: currentContext, data: determinedData, id: newId, isConstant: property && (property as any)._isConstant, isReference: isReferenceCollection, name: name === propertyId ? propertyIdString : name, parent: collectionProperty, parentId: parentRowId, parentIsConstant, propertyId: propertyIdString, typeid: currentTypeid, value: determinedValue, }; if (isPropExpandable) { if (addDummy) { newRow.children = [dummyChild]; } else if (depth !== 0) { newRow.children = toTableRows({ ...newRow }, props, { addDummy, ascending, depth: depth - 1, followReferences, }, pathPrefix); } } return newRow; }; export interface ISanitizer { searchFor: RegExp; replaceWith: string; } export const sanitizePath = (inPath: string, sanitizer: ISanitizer[]) => { let outPath = inPath; sanitizer.forEach((replaceCase) => { outPath = outPath.replace(replaceCase.searchFor, replaceCase.replaceWith); }); return outPath; }; export const expandAll = (workspace: Workspace) => { const expanded: IExpandedMap = {}; const root = (workspace as any).root; forEachProperty(root, (property) => { if (!isPrimitive(property.getFullTypeid())) { const newId = getShortId(property.getAbsolutePath()); expanded[newId] = true; } return true; }); return expanded; }; export const fillExpanded = ( expanded: IExpandedMap, innerRows: IInspectorRow[], props: IToTableRowsProps, toTableRowsOptions?: IToTableRowsOptions, pathPrefix: string = '', ) => { for (const row of innerRows) { if (row.id in expanded) { const newPathPrefix = row.parent && row.isReference ? pathPrefix + row.parent.getAbsolutePath() + idSeparator + row.name : pathPrefix; if (row.children && row.children[0].context === 'd') { row.children = toTableRows( { ...row }, props, {...toTableRowsOptions, parentIsConstant: row.isConstant || row.parentIsConstant}, newPathPrefix, ); } fillExpanded(expanded, row.children!, props, toTableRowsOptions, newPathPrefix); } } }; const isPropertyProxy = (p: any): p is BaseProxifiedProperty => { return p.getProperty && PropertyFactory.instanceOf(p.getProperty(), 'BaseProperty'); }; const invalidReference = (parentProxy: BaseProxifiedProperty, id: string | number) => { return 'Invalid Reference: ' + (isReferenceMapProperty(parentProxy.getProperty()) ? (parentProxy as any).get(id + '*') : parentProxy[id + '*']); }; /** * Extracts the value from a property and returns it. * @param parent The parent of the property in question. * @param id The id of the child property that we want to extract the value from. * @return The property value. */ export const getPropertyValue = (parent: ContainerProperty | BaseProxifiedProperty, id: string, context: string, typeid: string, followReferences = true): string | number | boolean => { let parentProperty; let parentProxy; if (isPropertyProxy(parent)) { parentProxy = parent; parentProperty = parentProxy.getProperty(); } else { parentProperty = parent; parentProxy = PropertyProxy.proxify(parent); } let property; try { property = (parentProperty as ContainerProperty).get(id); } catch (e) { // Most likely failed due to some Reference mess up if (Utils.isReferenceCollectionTypeid(parentProperty.getTypeid()) || Utils.isReferenceProperty(parentProxy.getProperty([id, BaseProperty.PATH_TOKENS.REF]))) { return invalidReference(parentProxy, id); } else { throw (e); } } if (property === undefined || !followReferences) { // TODO This could happen if the property is ReferenceProperty that points to an invalid reference. property = parentProxy.getProperty([id, BaseProperty.PATH_TOKENS.REF]) as BaseProperty; } let propertyProxy = (parentProperty.getContext() === 'map' ? (parentProxy as any).get(id) : parentProxy[id]); if (parentProperty.getContext() === 'set') { propertyProxy = PropertyProxy.proxify(property); } const contextIsSingle = context === 'single'; const parentContextIsSingle = parentProperty.getContext() === 'single'; id = parentProperty.getContext() === 'set' ? (propertyProxy as any).guid : id; let determinedValue; // If the property is a reference and we don't follow them, we store the reference path string instead. if (!followReferences && TypeIdHelper.isReferenceTypeId(typeid)) { if (parentContextIsSingle || isReferenceArrayProperty(parentProperty)) { determinedValue = parentProxy[id + '*']; } else { determinedValue = (parentProxy as any).get(id + '*'); } } else if (contextIsSingle && propertyProxy !== undefined && isPrimitive(typeid)) { try { if (parentProxy[id + '^'] !== undefined) { determinedValue = parentProxy[id + '^']; } else if ((parentProxy as any).get(id + '^') !== undefined) { determinedValue = (parentProxy as any).get(id + '^'); } else { determinedValue = parentProxy; } } catch (error) { console.error(error); } } else if ( (propertyProxy === undefined && (isReferenceArrayProperty(parentProperty) || isReferenceMapProperty(parentProperty)) && !parentProperty.isReferenceValid(id as never) ) || (contextIsSingle && PropertyFactory.instanceOf(property, 'Reference') && !(property as ReferenceProperty).isReferenceValid()) ) { // Probably encountered an invalid Reference. determinedValue = invalidReference(parentProxy, id); } return determinedValue; };
the_stack
import { AxiosRequestConfig } from "axios"; import { DEFAULT_RPC, NEO_NETWORK, RPC_VERSION } from "../consts"; import logger from "../logging"; import { timeout } from "../settings"; import { BaseTransaction } from "../tx/transaction/BaseTransaction"; import { isAddress, Claims, Balance, Coin } from "../wallet"; import { RPCVMResponse } from "./parse"; import Query from "./Query"; const log = logger("rpc"); export interface Validator { publickey: string; votes: string; active: boolean; } export interface GetUnclaimedResult { available: number; unavailable: number; unclaimed: number; } /** * RPC Client model to query a NEO node. Contains built-in methods to query using RPC calls. */ export class RPCClient { public net: string; public history: Query[]; public lastSeenHeight: number; public version: string; // tslint:disable-next-line:variable-name private _latencies: number[]; /** * @param net 'MainNet' or 'TestNet' will query the default RPC address found in consts. You may provide a custom URL. * @param version Version of NEO node. Used to check if RPC methods have been implemented. it will default to DEFAULT_RPC found in CONST */ public constructor(net: string, version = RPC_VERSION) { if (net === NEO_NETWORK.MAIN) { this.net = DEFAULT_RPC.MAIN; } else if (net === NEO_NETWORK.TEST) { this.net = DEFAULT_RPC.TEST; } else { this.net = net; } this.history = []; this.lastSeenHeight = 0; this._latencies = []; this.version = version; } public get [Symbol.toStringTag](): string { return "RPC Client"; } public get latency(): number { if (this._latencies.length === 0) { return 99999; } return Math.floor( this._latencies.reduce((p, c) => p + c, 0) / this._latencies.length ); } public set latency(lat: number) { if (this._latencies.length > 4) { this._latencies.shift(); } this._latencies.push(lat); } /** * Measures the latency using getBlockCount call. Returns the current latency. For average, call this.latency */ public async ping(): Promise<number> { const timeStart = Date.now(); const query = Query.getBlockCount(); try { const response = await this.execute(query, { timeout: timeout.ping }); this.lastSeenHeight = response.result; const newPing = Date.now() - timeStart; this.latency = newPing; return newPing; } catch (err) { this.latency = timeout.ping; return timeout.ping; } } /** * Takes an Query object and executes it. Adds the Query object to history. */ public execute(query: Query, config?: AxiosRequestConfig): Promise<any> { this.history.push(query); log.info(`RPC: ${this.net} executing Query[${query.req.method}]`); return query.execute(this.net, config); } /** * Creates a query with the given req and immediately executes it. */ public query( req: Record<string, unknown>, config?: AxiosRequestConfig ): Promise<any> { const query = new Query(req); return this.execute(query, config); } /** * Gets the state of an account given an address. */ public async getAccountState(addr: string): Promise<any> { if (!isAddress(addr)) { throw new Error(`Invalid address given: ${addr}`); } const response = await this.execute(Query.getAccountState(addr)); return response.result; } /** * Gets the state of an asset given an id. */ public async getAssetState(assetId: string): Promise<any> { const response = await this.execute(Query.getAssetState(assetId)); return response.result; } /** * Gets the block at a given height or hash. */ public async getBlock( indexOrHash: string | number, verbose = 1 ): Promise<Record<string, unknown> | string> { const response = await this.execute(Query.getBlock(indexOrHash, verbose)); return response.result; } /** * Gets the block hash at a given height. */ public async getBlockHash(index: number): Promise<string> { const response = await this.execute(Query.getBlockHash(index)); return response.result; } /** * Get the latest block hash. */ public async getBestBlockHash(): Promise<string> { const response = await this.execute(Query.getBestBlockHash()); return response.result; } /** * Get the current block height. */ public async getBlockCount(): Promise<number> { const response = await this.execute(Query.getBlockCount()); return response.result; } /** * Get the system fees of a block. * @param {number} index * @return {Promise<string>} - System fees as a string. */ public async getBlockSysFee(index: number): Promise<string> { const response = await this.execute(Query.getBlockSysFee(index)); return response.result; } /** * Gets the number of peers this node is connected to. * @return {Promise<number>} */ public async getConnectionCount(): Promise<number> { const response = await this.execute(Query.getConnectionCount()); return response.result; } /** * Gets the state of the contract at the given scriptHash. */ public async getContractState( scriptHash: string ): Promise<Record<string, unknown>> { const response = await this.execute(Query.getContractState(scriptHash)); return response.result; } /** * Gets a list of all peers that this node has discovered. */ public async getPeers(): Promise<Record<string, unknown>> { const response = await this.execute(Query.getPeers()); return response.result; } /** * Gets a list of all transaction hashes waiting to be processed. */ public async getRawMemPool(): Promise<string[]> { const response = await this.execute(Query.getRawMemPool()); return response.result; } /** * Gets a transaction based on its hash. */ public async getRawTransaction(txid: string, verbose = 1): Promise<any> { const response = await this.execute(Query.getRawTransaction(txid, verbose)); return response.result; } /** * Gets the corresponding value of a key in the storage of a contract address. */ public async getStorage(scriptHash: string, key: string): Promise<string> { const response = await this.execute(Query.getStorage(scriptHash, key)); return response.result; } /** * Gets the transaction output given a transaction id and index */ public async getTxOut(txid: string, index: number): Promise<any> { const response = await this.execute(Query.getTxOut(txid, index)); return response.result; } /** * Gets the list of validators available for voting. */ public async getValidators(): Promise<Validator[]> { const response = await this.execute(Query.getValidators()); return response.result; } /** * Gets the version of the NEO node. This method will never be blocked by version. This method will also update the current Client's version to the one received. */ public async getVersion(): Promise<string> { try { const response = await this.execute(Query.getVersion()); if (response && response.result && response.result.useragent) { const useragent = response.result.useragent; const responseLength = useragent.length; const strippedResponse = useragent.substring(1, responseLength - 1); const [_header, newVersion] = strippedResponse.split(":"); this.version = newVersion; } else { throw new Error("Empty or unexpected version pattern"); } return this.version; } catch (err) { if (err.message.includes("Method not found")) { this.version = RPC_VERSION; return this.version; } else { throw err; } } } /** * Calls a smart contract with the given parameters. This method is a local invoke, results are not reflected on the blockchain. */ public async invoke( scriptHash: string, ...params: any[] ): Promise<RPCVMResponse> { const response = await this.execute(Query.invoke(scriptHash, ...params)); return response.result; } /** * Submits a contract method call with parameters for the node to run. This method is a local invoke, results are not reflected on the blockchain. */ public async invokeFunction( scriptHash: string, operation: string, ...params: any[] ): Promise<RPCVMResponse> { const response = await this.execute( Query.invokeFunction(scriptHash, operation, ...params) ); return response.result; } /** * Submits a script for the node to run. This method is a local invoke, results are not reflected on the blockchain. */ public async invokeScript(script: string): Promise<RPCVMResponse> { const response = await this.execute(Query.invokeScript(script)); return response.result; } /** * Sends a serialized transaction to the network. */ public async sendRawTransaction( transaction: BaseTransaction | string ): Promise<boolean> { const response = await this.execute(Query.sendRawTransaction(transaction)); return response.result; } /** * Submits a serialized block to the network. */ public async submitBlock(block: string): Promise<any> { const response = await this.execute(Query.submitBlock(block)); return response.result; } /** * Checks if the provided address is a valid NEO address. */ public async validateAddress(addr: string): Promise<boolean> { const response = await this.execute(Query.validateAddress(addr)); return response.result.isvalid; } /** * Get the unspent utxo for an address */ public async getUnspents(addr: string): Promise<Balance> { const response = await this.execute(Query.getUnspents(addr)); return this.parseUnspentsToBalance(response.result); } /** * Get the unclaimed gas amount for an address */ public async getUnclaimed(addr: string): Promise<GetUnclaimedResult> { const response = await this.execute(Query.getUnclaimed(addr)); return response.result; } /** * Get the claimable for an address */ public async getClaimable(addr: string): Promise<Claims> { const response = await this.execute(Query.getClaimable(addr)); return new Claims({ net: this.net, address: response.result.address, claims: response.result.claimable.map( (rawClaim: any) => new Object({ claim: rawClaim.unclaimed, txid: rawClaim.txid, index: rawClaim.n, value: rawClaim.value, start: rawClaim.start_height, end: rawClaim.end_height, }) ), }); } private parseUnspentsToBalance(getUnspentsResult: any): Balance { const bal = new Balance({ address: getUnspentsResult.address, }); for (const assetBalance of getUnspentsResult.balance) { if (assetBalance.amount === 0) { continue; } if (assetBalance.unspent.length > 0) { bal.addAsset(assetBalance.asset_symbol, { unspent: assetBalance.unspent.map( (utxo: any) => new Coin({ index: utxo.n, txid: utxo.txid, value: utxo.value, }) ), }); } else { bal.addToken(assetBalance.asset_symbol, assetBalance.amount); } } return bal; } } export default RPCClient;
the_stack
module WinJSTests { "use strict"; var Key = WinJS.Utilities.Key; var NavBarContainer = <typeof WinJS.UI.PrivateNavBarContainer> WinJS.UI.NavBarContainer; // Item sized from TestData/NavBar.css var itemMargins = 5; var itemHeight = 100; var itemHeightWithMargins = itemHeight + itemMargins + itemMargins; var itemWidth = 250; var itemWidthWithMargins = itemWidth + itemMargins + itemMargins; var marginAboveBelowItems = 30; var navUtils = NavBarUtils; var _element; function nobodyHasFocus() { return document.activeElement === null || document.activeElement === document.body; } export class NavBarContainerTests { setUp = function () { LiveUnit.LoggingCore.logComment("In setup"); var newNode = document.createElement("div"); newNode.id = "host"; document.body.appendChild(newNode); _element = newNode; }; tearDown = function () { LiveUnit.LoggingCore.logComment("In tearDown"); if (_element) { WinJS.Utilities.disposeSubTree(_element); document.body.removeChild(_element); _element = null; } }; testHiddenNavContainer = function () { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); navbarContainerEl.style.display = "none"; var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true), currentIndex: 5 }); LiveUnit.Assert.isFalse(navbarContainer._measured, "Measured is false if no width/height"); navbarContainerEl.style.display = "block"; navbarContainer.forceLayout(); LiveUnit.Assert.isTrue(navbarContainer._measured, "Measured after visible"); }; testInstantiationMarkup = function (complete) { var html = "<div id ='navcontainer' data-win-control='WinJS.UI.NavBarContainer'>" + navUtils.getNavBarCommandsMarkup(20, true, true, true, true, true, true) + "</div>"; _element.innerHTML = html; WinJS.UI.processAll(). then(function () { var navcontainer = document.getElementById('navcontainer').winControl; LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(navcontainer.element, "win-navbarcontainer"), "win-navbarcontainer class is not present"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(navcontainer.element, "win-navbarcontainer-horizontal"), "win-navbarcontainer-horizontal class is not present"); // Verify pageIndicator box var pageIndicatorBoxEl = navcontainer.element.querySelector(".win-navbarcontainer-pageindicator-box"); LiveUnit.Assert.isTrue(pageIndicatorBoxEl, "win-navbarcontainer-pageindicator-box class is not present"); // Verify current pageIndicator var pageIndicatorCurrentEl = pageIndicatorBoxEl.querySelector(".win-navbarcontainer-pageindicator-current"); LiveUnit.Assert.isTrue(pageIndicatorCurrentEl, "win-navbarcontainer-pageindicator-current class is not present"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(pageIndicatorCurrentEl, "win-navbarcontainer-pageindicator"), "win-navbarcontainer-pageindicator class is not present"); // Verify left navarrow var leftArrowEl = navcontainer.element.querySelector(".win-navbarcontainer-navleft"); LiveUnit.Assert.isTrue(leftArrowEl, "win-navbarcontainer-navleft class is not present"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(leftArrowEl, "win-navbarcontainer-navarrow"), "win-navbarcontainer-navarrow class is not present"); // Verify right navarrow var rightArrowEl = navcontainer.element.querySelector(".win-navbarcontainer-navright"); LiveUnit.Assert.isTrue(rightArrowEl, "win-navbarcontainer-navright class is not present"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(rightArrowEl, "win-navbarcontainer-navarrow"), "win-navbarcontainer-navarrow class is not present"); // Verify left and right navarrows are not the same LiveUnit.Assert.isFalse(leftArrowEl === rightArrowEl); }). done(complete); }; testCurrentIndexConstructor = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true), currentIndex: 5 }); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.columnsPerPage); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.rowsPerPage); LiveUnit.Assert.areEqual(Math.ceil(10 / (1 * 1)), navbarContainer._sizes.pages); LiveUnit.Assert.areEqual(2500, navbarContainer._scrollPosition); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var sixthNavItem = navbarContainer._surfaceEl.children[5].winControl; LiveUnit.Assert.areEqual(sixthNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(5, navbarContainer.currentIndex); complete(); }); }; testCurrentIndexAndMaxRowsConstructor = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(20, true), currentIndex: 10, maxRows: 2 }); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.columnsPerPage); LiveUnit.Assert.areEqual(2, navbarContainer._sizes.rowsPerPage); LiveUnit.Assert.areEqual(Math.ceil(20 / (1 * 2)), navbarContainer._sizes.pages); LiveUnit.Assert.areEqual(2500, navbarContainer._scrollPosition); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var navItem10 = navbarContainer._surfaceEl.children[10].winControl; LiveUnit.Assert.areEqual(navItem10._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(10, navbarContainer.currentIndex); complete(); }); }; testCurrentIndexAndMaxRows = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(20, true) }); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.columnsPerPage); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.rowsPerPage); LiveUnit.Assert.areEqual(Math.ceil(20 / (1 * 1)), navbarContainer._sizes.pages); LiveUnit.Assert.areEqual(0, navbarContainer._scrollPosition); // Wait for the control to no longer be in the construction phase WinJS.Utilities.Scheduler.schedulePromiseNormal().then(function () { navbarContainer.maxRows = 2; navbarContainer.currentIndex = 10; navbarContainer.element.focus(); // Wait for focus to move return WinJS.Promise.timeout(); }).then(function () { var navItem10 = navbarContainer._surfaceEl.children[10].winControl; LiveUnit.Assert.areEqual(navItem10._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(10, navbarContainer.currentIndex); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.columnsPerPage); LiveUnit.Assert.areEqual(2, navbarContainer._sizes.rowsPerPage); LiveUnit.Assert.areEqual(Math.ceil(20 / (1 * 2)), navbarContainer._sizes.pages); LiveUnit.Assert.areEqual(2500, navbarContainer._scrollPosition); complete(); }); }; testSizes = function () { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true) }); LiveUnit.Assert.areEqual(itemHeight, navbarContainer._sizes.itemOffsetHeight); LiveUnit.Assert.areEqual(itemWidth, navbarContainer._sizes.itemOffsetWidth); LiveUnit.Assert.areEqual(itemHeightWithMargins, navbarContainer._sizes.itemHeight); LiveUnit.Assert.areEqual(itemWidthWithMargins, navbarContainer._sizes.itemWidth); }; testMaxRows = function () { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, {}); var dataSize; for (var rows = 1; rows < 5; rows++) { dataSize = 1; navbarContainer.maxRows = rows; while (dataSize <= rows) { navbarContainer.data = navUtils.getNavBarCommandsData(dataSize, true); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.columnsPerPage); LiveUnit.Assert.areEqual(dataSize, navbarContainer._sizes.rowsPerPage); dataSize++; } navbarContainer.data = navUtils.getNavBarCommandsData(dataSize, true); LiveUnit.Assert.areEqual(2, navbarContainer._sizes.pages); } }; testConsumeMarkup = function () { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); navbarContainerEl.innerHTML = navUtils.getNavBarCommandsMarkup(10, true); var navbarContainer = new NavBarContainer(navbarContainerEl); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.columnsPerPage); LiveUnit.Assert.areEqual(1, navbarContainer._sizes.rowsPerPage); LiveUnit.Assert.areEqual(10, navbarContainer._sizes.pages); }; testConstructTwice = function () { var navbarContainerEl = document.createElement('div'); var navbarContainer = new NavBarContainer(navbarContainerEl); try { navbarContainer = new NavBarContainer(navbarContainerEl); LiveUnit.Assert.fail("Should throw"); } catch (e) { LiveUnit.Assert.areEqual("Invalid argument: Controls may only be instantiated one time for each DOM element", e.message); LiveUnit.Assert.areEqual("WinJS.UI.NavBarContainer.DuplicateConstruction", e.name); } }; testArrowKeysPressed = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); _element.style.width = "800px"; var navbarContainer = new NavBarContainer(navbarContainerEl, { maxRows: 1, data: navUtils.getNavBarCommandsData(20, true, false, false, false, false, false) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; var lastNavItem = navbarContainer._surfaceEl.children[19].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); for (var i = 0; i < 20; i++) { Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); } LiveUnit.Assert.areEqual(lastNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(19, navbarContainer.currentIndex); WinJS.Utilities._setImmediate(function () { for (var i = 0; i < 20; i++) { Helper.keydown(lastNavItem._buttonEl, Key.leftArrow); } LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); complete(); }); }); }; testKeyboardingHorizontal = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { maxRows: 2, data: navUtils.getNavBarCommandsData(100, true, false, false, false, false, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; var thirdNavItem = navbarContainer._surfaceEl.children[2].winControl; var fourthNavItem = navbarContainer._surfaceEl.children[3].winControl; var lastNavItem = navbarContainer._surfaceEl.children[99].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); LiveUnit.Assert.areEqual(firstNavItem._splitButtonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._splitButtonEl, Key.rightArrow); LiveUnit.Assert.areEqual(thirdNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); Helper.keydown(thirdNavItem._buttonEl, Key.downArrow); LiveUnit.Assert.areEqual(fourthNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(3, navbarContainer.currentIndex); Helper.keydown(fourthNavItem._buttonEl, Key.upArrow); LiveUnit.Assert.areEqual(thirdNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); Helper.keydown(thirdNavItem._buttonEl, Key.leftArrow); LiveUnit.Assert.areEqual(firstNavItem._splitButtonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._splitButtonEl, Key.end); LiveUnit.Assert.areEqual(lastNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(99, navbarContainer.currentIndex); Helper.keydown(lastNavItem._buttonEl, Key.home); LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); var columns = navbarContainer._sizes.columnsPerPage; var rows = navbarContainer._sizes.rowsPerPage; var firstItemOnFirstPageNavItem = navbarContainer._surfaceEl.children[0].winControl; var lastItemOnFirstPageNavItem = navbarContainer._surfaceEl.children[columns * rows - 1].winControl; var firstItemOnSecondPageNavItem = navbarContainer._surfaceEl.children[columns * rows].winControl; var lastItemOnSecondPageNavItem = navbarContainer._surfaceEl.children[2 * columns * rows - 1].winControl; var firstItemOnThirdPageNavItem = navbarContainer._surfaceEl.children[2 * columns * rows].winControl; var lastItemOnThirdPageNavItem = navbarContainer._surfaceEl.children[3 * columns * rows - 1].winControl; Helper.keydown(firstNavItem._buttonEl, Key.pageDown); LiveUnit.Assert.areEqual(lastItemOnFirstPageNavItem._buttonEl, document.activeElement); Helper.keydown(lastItemOnFirstPageNavItem._buttonEl, Key.pageDown); LiveUnit.Assert.areEqual(lastItemOnSecondPageNavItem._buttonEl, document.activeElement); Helper.keydown(lastItemOnSecondPageNavItem._buttonEl, Key.pageDown); LiveUnit.Assert.areEqual(lastItemOnThirdPageNavItem._buttonEl, document.activeElement); Helper.keydown(lastItemOnThirdPageNavItem._buttonEl, Key.pageUp); LiveUnit.Assert.areEqual(firstItemOnThirdPageNavItem._buttonEl, document.activeElement); Helper.keydown(firstItemOnThirdPageNavItem._buttonEl, Key.pageUp); LiveUnit.Assert.areEqual(firstItemOnSecondPageNavItem._buttonEl, document.activeElement); Helper.keydown(firstItemOnSecondPageNavItem._buttonEl, Key.pageUp); LiveUnit.Assert.areEqual(firstItemOnFirstPageNavItem._buttonEl, document.activeElement); complete(); }); }; testKeyboardingVertical = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); navbarContainerEl.className = "verticalTest"; var navbarContainer = new NavBarContainer(navbarContainerEl, { maxRows: 2, layout: WinJS.UI.Orientation.vertical, data: navUtils.getNavBarCommandsData(100, true, false, false, false, false, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; var thirdNavItem = navbarContainer._surfaceEl.children[2].winControl; var fourthNavItem = navbarContainer._surfaceEl.children[3].winControl; var fifthNavItem = navbarContainer._surfaceEl.children[4].winControl; var sixthNavItem = navbarContainer._surfaceEl.children[5].winControl; var seventhNavItem = navbarContainer._surfaceEl.children[6].winControl; var lastNavItem = navbarContainer._surfaceEl.children[99].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); LiveUnit.Assert.areEqual(firstNavItem._splitButtonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._splitButtonEl, Key.downArrow); LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); Helper.keydown(secondNavItem._buttonEl, Key.downArrow); LiveUnit.Assert.areEqual(thirdNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); Helper.keydown(thirdNavItem._buttonEl, Key.upArrow); LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); Helper.keydown(secondNavItem._buttonEl, Key.end); LiveUnit.Assert.areEqual(lastNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(99, navbarContainer.currentIndex); Helper.keydown(lastNavItem._buttonEl, Key.home); LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.pageDown); LiveUnit.Assert.areEqual(thirdNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); Helper.keydown(fourthNavItem._buttonEl, Key.pageDown); LiveUnit.Assert.areEqual(sixthNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(5, navbarContainer.currentIndex); Helper.keydown(seventhNavItem._buttonEl, Key.pageUp); LiveUnit.Assert.areEqual(fourthNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(3, navbarContainer.currentIndex); Helper.keydown(fourthNavItem._buttonEl, Key.pageUp); LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); complete(); }); }; testFocusUpdateOnDataRemove = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(3, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); // Remove the item with focus and make sure the next one gets focus. navbarContainer.data.splice(1, 1); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); // Remove the item with focus when there is no next item and make sure the previous one gets focus. navbarContainer.data.splice(1, 1); var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); // Remove the last item. navbarContainer.data.splice(0, 1); LiveUnit.Assert.isTrue(nobodyHasFocus(), "No element should have focus"); LiveUnit.Assert.areEqual(-1, navbarContainer.currentIndex); complete(); }); }; testFocusUpdateOnDataChange = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(3, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); // Replace the item navbarContainer.data.setAt(1, navUtils.getNavBarCommandData(3, true)); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); complete(); }); }; testFocusUpdateOnDataInserts = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(3, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); // Insert before the item navbarContainer.data.splice(0, 0, navUtils.getNavBarCommandData(3, true)); LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); // Insert after the item navbarContainer.data.splice(3, 0, navUtils.getNavBarCommandData(3, true)); LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); complete(); }); }; testFocusUpdateOnDataReload = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(3, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); // Reverse to cause a reload event. navbarContainer.data.reverse(); var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); complete(); }); }; testFocusUpdateOnDataMove = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(3, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); // Move the item navbarContainer.data.move(1, 2); var secondNavItem = navbarContainer._surfaceEl.children[2].winControl; LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(2, navbarContainer.currentIndex); complete(); }); }; testSplitToggle = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true, false, false, false, false, true) }); navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; var secondNavItem = navbarContainer._surfaceEl.children[1].winControl; LiveUnit.Assert.isFalse(secondNavItem.splitOpened); LiveUnit.Assert.isFalse(firstNavItem.splitOpened); // Open the first split button. LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._buttonEl, Key.rightArrow); LiveUnit.Assert.areEqual(firstNavItem._splitButtonEl, document.activeElement); LiveUnit.Assert.areEqual(0, navbarContainer.currentIndex); Helper.keydown(firstNavItem._splitButtonEl, Key.enter); LiveUnit.Assert.isTrue(firstNavItem.splitOpened); LiveUnit.Assert.isFalse(secondNavItem.splitOpened); // When we open the second split button the first one closes. Helper.keydown(firstNavItem._splitButtonEl, Key.rightArrow); LiveUnit.Assert.areEqual(secondNavItem._buttonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); Helper.keydown(secondNavItem._buttonEl, Key.rightArrow); LiveUnit.Assert.areEqual(secondNavItem._splitButtonEl, document.activeElement); LiveUnit.Assert.areEqual(1, navbarContainer.currentIndex); Helper.keydown(secondNavItem._splitButtonEl, Key.enter); LiveUnit.Assert.isTrue(secondNavItem.splitOpened); LiveUnit.Assert.isFalse(firstNavItem.splitOpened); complete(); }); }; testSplitOpenedAndSplitToggleOnPropertyUpdates = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true, false, false, false, false, true) }); var eventName = "splittoggle", splitToggleFired = false, firstNavItem; function loop(action) { firstNavItem = navbarContainer._surfaceEl.children[0].winControl; navbarContainerEl.addEventListener(eventName, function handler(e: any) { LiveUnit.Assert.areEqual(firstNavItem, e.detail.navbarCommand); splitToggleFired = true; }); firstNavItem._splitButtonEl.click(); LiveUnit.Assert.isTrue(splitToggleFired); splitToggleFired = false; LiveUnit.Assert.isTrue(firstNavItem.splitOpened); action(); LiveUnit.Assert.isTrue(splitToggleFired); splitToggleFired = false; LiveUnit.Assert.isFalse(firstNavItem.splitOpened); } var actions = []; // Update template actions.push(function () { var template: any = function template(item) { var root = document.createElement("div"); root.textContent = "New Template"; return root; } navbarContainer.template = template; }); // Update data actions.push(function () { navbarContainer.data = navUtils.getNavBarCommandsData(8, true, true, true, true, true, true); }); // Update fixedSize actions.push(function () { navbarContainer.fixedSize = true; }); // Update maxrows actions.push(function () { navbarContainer.maxRows = 2; }); // Update layout actions.push(function () { navbarContainer.layout = WinJS.UI.Orientation.vertical; }); // Update currentIndex actions.push(function () { navbarContainer.currentIndex = 3; }); actions.forEach(function (action) { loop(action); }); complete(); }; testInvokedEvent = function () { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true, false, false, false, false, true) }); var clickedIndex, navbarCmd, dataItem; navbarContainer.addEventListener(NavBarContainer._EventName.invoked, function (ev) { clickedIndex = ev.detail.index; navbarCmd = ev.detail.navbarCommand; dataItem = ev.detail.data; }); var expectedIndex = 1, expectedNavBarCmd = (<HTMLElement>navbarContainerEl.querySelectorAll(".win-navbarcommand")[expectedIndex]).winControl, expectedDataItem = navbarContainer.data.getAt(expectedIndex); navbarContainer._surfaceEl.children[expectedIndex].winControl._buttonEl.click(); LiveUnit.Assert.areEqual(expectedIndex, clickedIndex); LiveUnit.Assert.areEqual(expectedNavBarCmd, navbarCmd); LiveUnit.Assert.areEqual(expectedDataItem, dataItem); }; testSplitToggleFiresWhenSplitOpenedUpdated = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(6, true, false, false, false, false, true) }); var splitToggleFired = false; navbarContainer.addEventListener("splittoggle", function (e) { splitToggleFired = true; }); var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; LiveUnit.Assert.isFalse(firstNavItem.splitOpened); firstNavItem.splitOpened = true; LiveUnit.Assert.isTrue(splitToggleFired); splitToggleFired = false; firstNavItem.splitOpened = false; LiveUnit.Assert.isTrue(splitToggleFired); complete(); }; testSplitToggleEvent = function () { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true, false, false, false, false, true) }); var clickedIndex, opened, navbarCmd, dataItem; navbarContainer.addEventListener(NavBarContainer._EventName.splitToggle, function (ev) { clickedIndex = ev.detail.index; opened = ev.detail.opened; navbarCmd = ev.detail.navbarCommand; dataItem = ev.detail.data; }); var expectedIndex = 1, expectedNavBarCmd = (<HTMLElement>navbarContainerEl.querySelectorAll(".win-navbarcommand")[expectedIndex]).winControl, expectedDataItem = navbarContainer.data.getAt(expectedIndex); var navItem1 = navbarContainer._surfaceEl.children[expectedIndex].winControl; navItem1._splitButtonEl.click(); LiveUnit.Assert.areEqual(expectedIndex, clickedIndex); LiveUnit.Assert.isTrue(opened); LiveUnit.Assert.areEqual(expectedNavBarCmd, navbarCmd); LiveUnit.Assert.areEqual(expectedDataItem, dataItem); expectedIndex = 2; expectedNavBarCmd = (<HTMLElement>navbarContainerEl.querySelectorAll(".win-navbarcommand")[expectedIndex]).winControl; expectedDataItem = navbarContainer.data.getAt(expectedIndex); var navItem2 = navbarContainer._surfaceEl.children[expectedIndex].winControl; navItem2._splitButtonEl.click(); LiveUnit.Assert.areEqual(expectedIndex, clickedIndex); LiveUnit.Assert.isTrue(opened); LiveUnit.Assert.isFalse(navItem1.splitOpened); // Verify the previous split button is closed LiveUnit.Assert.areEqual(expectedNavBarCmd, navbarCmd); LiveUnit.Assert.areEqual(expectedDataItem, dataItem); }; testDataEdits = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var dataList = navUtils.getNavBarCommandsData(20, true, false, false, false, false, true); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: dataList }); var editsCount = 100; function performRandomEdit(i) { var editTypes = ["push", "unshift", "pop", "shift", "reverse", "setAt", "move", "sort", "length"]; var item = navUtils.getNavBarCommandData(i, true, true, true, true, true, true); // Perform data edits switch (Helper.getRandomItem(editTypes)) { case "push": LiveUnit.LoggingCore.logComment("Performing push"); dataList.push(item); break; case "unshift": LiveUnit.LoggingCore.logComment("Performing unshift"); dataList.unshift(item); break; case "pop": LiveUnit.LoggingCore.logComment("Performing pop"); if (dataList.length > 0) { dataList.pop(); } break; case "shift": LiveUnit.LoggingCore.logComment("Performing shift"); if (dataList.length > 0) { dataList.shift(); }; break; case "setAt": LiveUnit.LoggingCore.logComment("Performing setAt"); dataList.setAt(Helper.getRandomNumberUpto(dataList.length), item); break; case "move": LiveUnit.LoggingCore.logComment("Performing move"); dataList.move(0, dataList.length - 1); break; case "reverse": LiveUnit.LoggingCore.logComment("Performing reverse"); dataList.reverse(); break; case "sort": LiveUnit.LoggingCore.logComment("Performing sort"); dataList.sort(); break; case "length": LiveUnit.LoggingCore.logComment("Setting the length of the list to less than actual member"); if (dataList.length > 2) { dataList.length = 2; }; break; default: LiveUnit.Assert.fail("Unrecognized edit type"); } } function verify() { var cmds:any = navbarContainerEl.querySelectorAll(".win-navbarcommand"); LiveUnit.Assert.areEqual(dataList.length, cmds.length, "Unexpected number of items"); dataList.forEach(function (item, index) { LiveUnit.Assert.areEqual(item.label, cmds[index].winControl.label, "Incorrect label on the navbarcommand"); }); } for (var i = 0; i < editsCount; i++) { // Edit performRandomEdit(i); // Verify verify(); } complete(); }; testDispose = function () { var navbarContainer = new NavBarContainer(); LiveUnit.Assert.isFalse(navbarContainer._disposed); navbarContainer.dispose(); LiveUnit.Assert.isTrue(navbarContainer._disposed); navbarContainer.dispose(); LiveUnit.Assert.isTrue(navbarContainer._disposed); }; testForceLayoutUpdatesUI = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true, false, true, false, false, false) }); var origPageIndicatorCount = navbarContainerEl.querySelectorAll(".win-navbarcontainer-pageindicator").length; // Flip to 3rd page navbarContainer.currentIndex = 4; // Hide navbarContainerEl.style.display = "none"; // Resize _element.style.width = "700px"; WinJS.Utilities._setImmediate(function () { // Show navbarContainerEl.style.display = "block"; var currentPageIndicatorCount = navbarContainerEl.querySelectorAll(".win-navbarcontainer-pageindicator").length; // Verify LiveUnit.Assert.areEqual(origPageIndicatorCount, currentPageIndicatorCount, "Unexpected page indicator count"); // Remeasure navbarContainer.forceLayout(); // Verify currentPageIndicatorCount = navbarContainerEl.querySelectorAll(".win-navbarcontainer-pageindicator").length; origPageIndicatorCount = 5; LiveUnit.Assert.areEqual(origPageIndicatorCount, currentPageIndicatorCount, "Unexpected page indicator count"); complete(); }); } testChangeLayoutProperty = function (complete) { var navbarContainerEl = document.createElement('div'); _element.appendChild(navbarContainerEl); var navbarContainer = new NavBarContainer(navbarContainerEl, { data: navUtils.getNavBarCommandsData(10, true, false, true, false, false, false) }); // Verify pageindicators are visible var style = getComputedStyle(navbarContainerEl.querySelector(".win-navbarcontainer-pageindicator-box")); LiveUnit.Assert.areEqual("visible", style.visibility, "Page indicator are hidden"); var pageIndicatorCount = navbarContainerEl.querySelectorAll(".win-navbarcontainer-pageindicator").length; // Switch to vertical layout navbarContainer.layout = WinJS.UI.Orientation.vertical; // Verify pageindicators are hidden var style = getComputedStyle(navbarContainerEl.querySelector(".win-navbarcontainer-pageindicator-box")); LiveUnit.Assert.areEqual("hidden", style.visibility, "Page indicator are visible"); // Press end, then home navbarContainer.element.focus(); WinJS.Utilities._setImmediate(function () { var firstNavItem = navbarContainer._surfaceEl.children[0].winControl; var lastNavItem = navbarContainer._surfaceEl.children[9].winControl; LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); Helper.keydown(firstNavItem._buttonEl, Key.end); LiveUnit.Assert.areEqual(lastNavItem._buttonEl, document.activeElement); Helper.keydown(lastNavItem._buttonEl, Key.home); LiveUnit.Assert.areEqual(firstNavItem._buttonEl, document.activeElement); // Switch to horizontal layout navbarContainer.layout = WinJS.UI.Orientation.horizontal; Helper.keydown(firstNavItem._buttonEl, Key.end); // Verify pageindicators are visible var style = getComputedStyle(navbarContainerEl.querySelector(".win-navbarcontainer-pageindicator-box")); LiveUnit.Assert.areEqual("visible", style.visibility, "Page indicator are hidden"); // Verify pageindicator count is same as before var newPageIndicatorCount = navbarContainerEl.querySelectorAll(".win-navbarcontainer-pageindicator").length; LiveUnit.Assert.areEqual(pageIndicatorCount, newPageIndicatorCount, "Unexpected number of page indicators"); complete(); }); } }; } LiveUnit.registerTestClass("WinJSTests.NavBarContainerTests");
the_stack
import { IncomingMessage, ServerResponse, ClientRequest, IncomingHttpHeaders } from 'http'; import proxy from 'http-proxy-middleware'; import HttpStatus from 'http-status-codes'; import setCookieParser, { Cookie } from 'set-cookie-parser'; import zlib from 'zlib'; // node.js standard lib import { AppRenderer } from './AppRenderer'; import { ProxyConfig } from './ProxyConfig'; import { RenderResponse } from './RenderResponse'; import { RouteUrlParser } from './RouteUrlParser'; import { buildQueryString, tryParseJson } from './util'; /** * Extends IncomingMessage as it should contain these properties but they are not provided in types */ export interface ProxyIncomingMessage extends IncomingMessage { originalUrl: string; query: { [key: string]: string | number | boolean }; } /** * Extends ClientRequest as it should contain `method` but it's not provided in types */ interface ExtendedClientRequest extends ClientRequest { method: string; } // For some reason, every other response returned by Sitecore contains the 'set-cookie' header with the SC_ANALYTICS_GLOBAL_COOKIE value as an empty string. // This effectively sets the cookie to empty on the client as well, so if a user were to close their browser // after one of these 'empty value' responses, they would not be tracked as a returning visitor after re-opening their browser. // To address this, we simply parse the response cookies and if the analytics cookie is present but has an empty value, then we // remove it from the response header. This means the existing cookie in the browser remains intact. export const removeEmptyAnalyticsCookie = (proxyResponse: IncomingMessage) => { const cookies = setCookieParser.parse(proxyResponse.headers['set-cookie'] as string[]); if (cookies) { const analyticsCookieIndex = cookies.findIndex( (c: Cookie) => c.name === 'SC_ANALYTICS_GLOBAL_COOKIE' ); if (analyticsCookieIndex !== -1) { const analyticsCookie = cookies[analyticsCookieIndex]; if (analyticsCookie && analyticsCookie.value === '') { cookies.splice(analyticsCookieIndex, 1); /* eslint-disable no-param-reassign */ proxyResponse.headers['set-cookie'] = (cookies as unknown) as string[]; /* eslint-enable no-param-reassign */ } } } }; // inspired by: http://stackoverflow.com/a/22487927/9324 /** * @param {IncomingMessage} proxyResponse * @param {IncomingMessage} request * @param {ServerResponse} serverResponse * @param {AppRenderer} renderer * @param {ProxyConfig} config */ async function renderAppToResponse( proxyResponse: IncomingMessage, request: IncomingMessage, serverResponse: ServerResponse, renderer: AppRenderer, config: ProxyConfig ) { // monkey-patch FTW? const originalWriteHead = serverResponse.writeHead; const originalWrite = serverResponse.write; const originalEnd = serverResponse.end; // these lines are necessary and must happen before we do any writing to the response // otherwise the headers will have already been sent delete proxyResponse.headers['content-length']; proxyResponse.headers['content-type'] = 'text/html; charset=utf-8'; // remove IIS server header for security delete proxyResponse.headers.server; if (config.setHeaders) { config.setHeaders(request, serverResponse, proxyResponse); } const contentEncoding = proxyResponse.headers['content-encoding']; if ( contentEncoding && (contentEncoding.indexOf('gzip') !== -1 || contentEncoding.indexOf('deflate') !== -1) ) { delete proxyResponse.headers['content-encoding']; } // we are going to set our own status code if rendering fails serverResponse.writeHead = () => serverResponse; // buffer the response body as it is written for later processing let buf = Buffer.from(''); serverResponse.write = (data, encoding: unknown) => { if (Buffer.isBuffer(data)) { buf = Buffer.concat([buf, data]); // append raw buffer } else { buf = Buffer.concat([buf, Buffer.from(data, encoding as BufferEncoding)]); // append string with optional character encoding (default utf8) } // sanity check: if the response is huge, bail. // ...we don't want to let someone bring down the server by filling up all our RAM. if (buf.length > (config.maxResponseSizeBytes as number)) { throw new Error('Document too large'); } return true; }; /** * Extract layout service data from proxy response */ async function extractLayoutServiceDataFromProxyResponse() { if ( proxyResponse.statusCode === HttpStatus.OK || proxyResponse.statusCode === HttpStatus.NOT_FOUND ) { let responseString: Promise<string>; if ( contentEncoding && (contentEncoding.indexOf('gzip') !== -1 || contentEncoding.indexOf('deflate') !== -1) ) { responseString = new Promise((resolve, reject) => { if (config.debug) { console.log('Layout service response is compressed; decompressing.'); } zlib.unzip(buf, (error, result) => { if (error) { reject(error); } if (result) { resolve(result.toString('utf-8')); } }); }); } else { responseString = Promise.resolve(buf.toString('utf-8')); } return responseString.then(tryParseJson); } return Promise.resolve(null); } /** * function replies with HTTP 500 when an error occurs * @param {Error} error */ async function replyWithError(error: Error) { console.error(error); let errorResponse = { statusCode: proxyResponse.statusCode || HttpStatus.INTERNAL_SERVER_ERROR, content: proxyResponse.statusMessage || 'Internal Server Error', }; if (config.onError) { const onError = await config.onError(error, proxyResponse); errorResponse = { ...errorResponse, ...onError }; } completeProxyResponse(Buffer.from(errorResponse.content), errorResponse.statusCode, {}); } // callback handles the result of server-side rendering /** * @param {Error | null} error * @param {RenderResponse} result */ async function handleRenderingResult(error: Error | null, result: RenderResponse | null) { if (!error && !result) { return replyWithError(new Error('Render function did not return a result or an error!')); } if (error) { return replyWithError(error); } if (!result) { // should not occur, but makes TS happy return replyWithError(new Error('Render function result did not return a result.')); } if (!result.html) { return replyWithError( new Error('Render function result was returned but html property was falsy.') ); } if (config.transformSSRContent) { result.html = await config.transformSSRContent(result, request, serverResponse); } // we have to convert back to a buffer so that we can get the *byte count* (rather than character count) of the body let content = Buffer.from(result.html); // setting the content-length header is not absolutely necessary, but is recommended proxyResponse.headers['content-length'] = content.length.toString(10); // if original request was a HEAD, we should not return a response body if (request.method === 'HEAD') { if (config.debug) { console.log('DEBUG: Original request method was HEAD, clearing response body'); } content = Buffer.from([]); } if (result.redirect) { if (!result.status) { result.status = 302; } proxyResponse.headers.location = result.redirect; } const finalStatusCode = result.status || proxyResponse.statusCode || HttpStatus.OK; if (config.debug) { console.log( 'DEBUG: FINAL response headers for client', JSON.stringify(proxyResponse.headers, null, 2) ); console.log('DEBUG: FINAL status code for client', finalStatusCode); } completeProxyResponse(content, finalStatusCode); } /** * @param {Buffer | null} content * @param {number} statusCode * @param {IncomingHttpHeaders} [headers] */ function completeProxyResponse( content: Buffer | null, statusCode: number, headers?: IncomingHttpHeaders ) { if (!headers) { headers = proxyResponse.headers; } originalWriteHead.apply(serverResponse, [statusCode, headers]); if (content) originalWrite.call(serverResponse, content); originalEnd.call(serverResponse); } /** * @param {object} layoutServiceData */ async function createViewBag(layoutServiceData: { [key: string]: unknown }) { let viewBag = { statusCode: proxyResponse.statusCode, dictionary: {}, }; if (config.createViewBag) { const customViewBag = await config.createViewBag( request, serverResponse, proxyResponse, layoutServiceData ); viewBag = { ...viewBag, ...customViewBag }; } return viewBag; } // as the response is ending, we parse the current response body which is JSON, then // render the app using that JSON, but return HTML to the final response. serverResponse.end = async () => { try { const layoutServiceData = await extractLayoutServiceDataFromProxyResponse(); const viewBag = await createViewBag(layoutServiceData); if (!layoutServiceData) { throw new Error( `Received invalid response ${proxyResponse.statusCode} ${proxyResponse.statusMessage}` ); } return renderer( handleRenderingResult, // originalUrl not defined in `http-proxy-middleware` types but it exists ((request as unknown) as { [key: string]: unknown }).originalUrl as string, layoutServiceData, viewBag ); } catch (error) { return replyWithError(error); } }; } /** * @param {IncomingMessage} proxyResponse * @param {IncomingMessage} request * @param {ServerResponse} serverResponse * @param {AppRenderer} renderer * @param {ProxyConfig} config */ function handleProxyResponse( proxyResponse: IncomingMessage, request: IncomingMessage, serverResponse: ServerResponse, renderer: AppRenderer, config: ProxyConfig ) { removeEmptyAnalyticsCookie(proxyResponse); if (config.debug) { console.log('DEBUG: request url', request.url); console.log('DEBUG: request query', (request as ProxyIncomingMessage).query); console.log('DEBUG: request original url', (request as ProxyIncomingMessage).originalUrl); console.log('DEBUG: proxied request response code', proxyResponse.statusCode); console.log('DEBUG: RAW request headers', JSON.stringify(request.headers, null, 2)); console.log( 'DEBUG: RAW headers from the proxied response', JSON.stringify(proxyResponse.headers, null, 2) ); } // if the request URL contains any of the excluded rewrite routes, we assume the response does not need to be server rendered. // instead, the response should just be relayed as usual. if (isUrlIgnored((request as ProxyIncomingMessage).originalUrl, config, true)) { return Promise.resolve(undefined); } // your first thought might be: why do we need to render the app here? why not just pass the JSON response to another piece of middleware that will render the app? // the answer: the proxy middleware ends the response and does not "chain" return renderAppToResponse(proxyResponse, request, serverResponse, renderer, config); } /** * @param {string} reqPath * @param {IncomingMessage} req * @param {ProxyConfig} config * @param {RouteUrlParser} parseRouteUrl */ export function rewriteRequestPath( reqPath: string, req: IncomingMessage, config: ProxyConfig, parseRouteUrl?: RouteUrlParser ) { // the path comes in URL-encoded by default, // but we don't want that because... // 1. We need to URL-encode it before we send it out to the Layout Service, if it matches a route // 2. We don't want to force people to URL-encode ignored routes, etc (just use spaces instead of %20, etc) const decodedReqPath = decodeURIComponent(reqPath); // if the request URL contains a path/route that should not be re-written, then just pass it along as-is if (isUrlIgnored(reqPath, config)) { // we do not return the decoded URL because we're using it verbatim - should be encoded. return reqPath; } // if the request URL doesn't contain the layout service controller path, assume we need to rewrite the request URL so that it does // if this seems redundant, it is. the config.pathRewriteExcludeRoutes should contain the layout service path, but can't always assume that it will... if (decodedReqPath.indexOf(config.layoutServiceRoute) !== -1) { return reqPath; } let finalReqPath = decodedReqPath; const qsIndex = finalReqPath.indexOf('?'); let qs = ''; if (qsIndex > -1) { qs = buildQueryString((req as ProxyIncomingMessage).query); finalReqPath = finalReqPath.slice(0, qsIndex); } if (config.qsParams) { if (qs) { qs += '&'; } qs += `${config.qsParams}`; } let lang; if (parseRouteUrl) { if (config.debug) { console.log(`DEBUG: Parsing route URL using ${decodedReqPath} URL...`); } const routeParams = parseRouteUrl(finalReqPath); if (routeParams) { if (routeParams.sitecoreRoute) { finalReqPath = routeParams.sitecoreRoute; } else { finalReqPath = '/'; } if (!finalReqPath.startsWith('/')) { finalReqPath = `/${finalReqPath}`; } lang = routeParams.lang; if (routeParams.qsParams) { qs += `&${routeParams.qsParams}`; } if (config.debug) { console.log('DEBUG: parseRouteUrl() result', routeParams); } } } let path = `${config.layoutServiceRoute}?item=${encodeURIComponent(finalReqPath)}&sc_apikey=${ config.apiKey }`; if (lang) { path = `${path}&sc_lang=${lang}`; } if (qs) { path = `${path}&${qs}`; } return path; } /** * @param {string} originalUrl * @param {ProxyConfig} config * @param {boolean} noDebug */ function isUrlIgnored(originalUrl: string, config: ProxyConfig, noDebug = false): boolean { if (config.pathRewriteExcludePredicate && config.pathRewriteExcludeRoutes) { console.error( 'ERROR: pathRewriteExcludePredicate and pathRewriteExcludeRoutes were both provided in config. Provide only one.' ); process.exit(1); } let result = null; if (config.pathRewriteExcludeRoutes) { const matchRoute = decodeURIComponent(originalUrl).toUpperCase(); result = config.pathRewriteExcludeRoutes.find( (excludedRoute: string) => excludedRoute.length > 0 && matchRoute.startsWith(excludedRoute) ); if (!noDebug && config.debug) { if (!result) { console.log( `DEBUG: URL ${originalUrl} did not match the proxy exclude list, and will be treated as a layout service route to render. Excludes:`, config.pathRewriteExcludeRoutes ); } else { console.log( `DEBUG: URL ${originalUrl} matched the proxy exclude list and will be served verbatim as received. Excludes: `, config.pathRewriteExcludeRoutes ); } } return result ? true : false; } if (config.pathRewriteExcludePredicate) { result = config.pathRewriteExcludePredicate(originalUrl); if (!noDebug && config.debug) { if (!result) { console.log( `DEBUG: URL ${originalUrl} did not match the proxy exclude function, and will be treated as a layout service route to render.` ); } else { console.log( `DEBUG: URL ${originalUrl} matched the proxy exclude function and will be served verbatim as received.` ); } } return result; } return false; } /** * @param {ClientRequest} proxyReq * @param {IncomingMessage} req * @param {ServerResponse} res * @param {ProxyConfig} config * @param {Function} customOnProxyReq */ function handleProxyRequest( proxyReq: ClientRequest, req: IncomingMessage, res: ServerResponse, config: ProxyConfig, customOnProxyReq: | ((proxyReq: ClientRequest, req: IncomingMessage, res: ServerResponse) => void) | undefined ) { // if a HEAD request, we still need to issue a GET so we can return accurate headers if ( (proxyReq as ExtendedClientRequest).method === 'HEAD' && !isUrlIgnored((req as ProxyIncomingMessage).originalUrl, config, true) ) { if (config.debug) { console.log('DEBUG: Rewriting HEAD request to GET to create accurate headers'); } (proxyReq as ExtendedClientRequest).method = 'GET'; } // invoke custom onProxyReq if (customOnProxyReq) { customOnProxyReq(proxyReq, req, res); } } /** * @param {AppRenderer} renderer * @param {ProxyConfig} config * @param {RouteUrlParser} parseRouteUrl */ function createOptions( renderer: AppRenderer, config: ProxyConfig, parseRouteUrl: RouteUrlParser ): proxy.Config { if (!config.maxResponseSizeBytes) { config.maxResponseSizeBytes = 10 * 1024 * 1024; } // ensure all excludes are case insensitive if (config.pathRewriteExcludeRoutes && Array.isArray(config.pathRewriteExcludeRoutes)) { config.pathRewriteExcludeRoutes = config.pathRewriteExcludeRoutes.map((exclude) => exclude.toUpperCase() ); } if (config.debug) { console.log('DEBUG: Final proxy config', config); } const customOnProxyReq = config.proxyOptions?.onProxyReq; return { ...config.proxyOptions, target: config.apiHost, changeOrigin: true, // required otherwise need to include CORS headers ws: true, pathRewrite: (reqPath, req) => rewriteRequestPath(reqPath, req, config, parseRouteUrl), logLevel: config.debug ? 'debug' : 'info', onProxyReq: (proxyReq, req, res) => handleProxyRequest(proxyReq, req, res, config, customOnProxyReq), onProxyRes: (proxyRes, req, res) => handleProxyResponse(proxyRes, req, res, renderer, config), }; } /** * @param {AppRenderer} renderer * @param {ProxyConfig} config * @param {RouteUrlParser} parseRouteUrl */ export default function scProxy( renderer: AppRenderer, config: ProxyConfig, parseRouteUrl: RouteUrlParser ) { const options = createOptions(renderer, config, parseRouteUrl); return proxy(options); }
the_stack
import { Output, EventEmitter, Directive, Input, TemplateRef, ViewContainerRef, OnDestroy, ChangeDetectorRef } from '@angular/core'; import { PLATFORM_ID, Inject } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; import { Subscription } from 'rxjs'; import { IResponsivePattern, IResponsiveSubscriptions } from '../../@core'; import { ResponsiveState } from '../../@core/providers/responsive-state/responsive-state'; import { ResponsiveWindowDirective } from "../responsive-window/responsive-window"; import { PlatformService } from '../../@core/providers/platform-service/platform.service'; @Directive( { selector: '[responsive]' }) export class ResponsiveDirective implements OnDestroy { private _config: string | string[]; @Input() set responsive(config: string | string[]) { this._config = config; this.init_responsive(); } get config(): string | string[]{ return this._config; } // @Input() responsiveContainer: ResponsiveWindowDirective; private _responsiveContainer:ResponsiveWindowDirective; @Input() set responsiveContainer(value: ResponsiveWindowDirective) { this._responsiveContainer = value; if(this.config){ if(this._sizes_window !== null && this._sizes_window !== "window") { throw new Error('Responsive directive cannot use window AND responsiveContainer together'); } this.init_responsive(); } } get responsiveContainer(): ResponsiveWindowDirective{ return this._responsiveContainer; } @Output() changes: EventEmitter<any> = new EventEmitter(); private _windows = null; private _window = null; private _isEnabledForPlatform: boolean = null; public set_values: IResponsivePattern = { bootstrap: '', browser: '', device: '', pixelratio: '', orientation: '', standard: '', ie: '', sizes: 0 }; private set_active_subscriptions: IResponsiveSubscriptions = { bootstrap: false, browser: false, device: false, pixelratio: false, orientation: false, standard: false, ie: false, sizes: false }; private match_multiple: IResponsiveSubscriptions = { bootstrap: false, browser: false, device: false, pixelratio: false, orientation: false, standard: false, ie: false, sizes: false }; private _subscription_Bootstrap: Subscription; private _subscription_Browser: Subscription; private _subscription_Pixel_Ratio: Subscription; private _subscription_Device: Subscription; private _subscription_Orientation: Subscription; private _subscription_Standard: Subscription; private _subscription_IE_Version: Subscription; private _subscription_custom_sizes: Subscription; protected _showWhenTrue = true; private _globalNoRepeat = 0; private _noRepeatBootstrapName: string; private _bootstrapNoRepeat = 0; private _deviceNoRepeat = 0; private _standardNoRepeat = 0; private _orientationNoRepeat = 0; private _browserNoRepeat = 0; private _pixelratioNoRepeat = 0; private _ieNoRepeat = 0; private _sizesNoRepeat = 0; private _bootstrap_user_param: string[] = []; private _devices_user_param: string[] = []; private _standard_user_param: string[] = []; private _orientation_user_param: string[] = []; private _browser_user_param: string[] = []; private _pixelratio_user_param: string[] = []; private _ie_user_param: string[] = []; private _sizes_user_param: [number, number] = [0, Number.MAX_VALUE]; private _sizes_window = 'window'; // private _sizes_container = null; protected _actives: string[] = []; constructor( public templateRef: TemplateRef<Object>, private _responsiveState: ResponsiveState, private viewContainer: ViewContainerRef, private cd: ChangeDetectorRef, platformService: PlatformService ) { this._isEnabledForPlatform = platformService.isEnabledForPlatform(); } public init_responsive(): void { const config: any = this.config; if (this.isJSON(config)) { if (!!config.bootstrap && this._bootstrapNoRepeat === 0) { this._bootstrap_user_param = <string[]>(Array.isArray(config.bootstrap) ? config.bootstrap : [config.bootstrap]); this._bootstrapNoRepeat = 1; this.set_active_subscriptions.bootstrap = true; } if (!!config.device && this._deviceNoRepeat === 0) { this._devices_user_param = <string[]>(Array.isArray(config.device) ? config.device : [config.device]); this._deviceNoRepeat = 1; this.set_active_subscriptions.device = true; } if (!!config.standard && this._standardNoRepeat === 0) { this._standard_user_param = <string[]>(Array.isArray(config.standard) ? config.standard : [config.standard]); this._standardNoRepeat = 1; this.set_active_subscriptions.standard = true; } if (!!config.orientation && this._orientationNoRepeat === 0) { this._orientation_user_param = <string[]>(Array.isArray(config.orientation) ? config.orientation : [config.orientation]); this._orientationNoRepeat = 1; this.set_active_subscriptions.orientation = true; } if (!!config.browser && this._browserNoRepeat === 0) { this._browser_user_param = <string[]>(Array.isArray(config.browser) ? config.browser : [config.browser]); this._browserNoRepeat = 1; this.set_active_subscriptions.browser = true; } if (!!config.pixelratio && this._pixelratioNoRepeat === 0) { this._pixelratio_user_param = <string[]>(Array.isArray(config.pixelratio) ? config.pixelratio : [config.pixelratio]); this._pixelratioNoRepeat = 1; this.set_active_subscriptions.pixelratio = true; } if (!!config.ie && this._ieNoRepeat === 0) { this._ie_user_param = <string[]>(Array.isArray(config.ie) ? config.ie : [config.ie]); this._ieNoRepeat = 1; this.set_active_subscriptions.ie = true; } if (!!config.sizes && this._sizesNoRepeat === 0) { const _min = config.sizes.min || 0; const _max = config.sizes.max || Number.MAX_VALUE; const _win = config.sizes.window; if (_win !== undefined) { this._sizes_window = _win; } // this._sizes_container = value.sizes.container; this._sizes_user_param = [_min, _max]; this._sizesNoRepeat = 1; this.set_active_subscriptions.sizes = true; } } else if (Array.isArray(config)) { throw new Error('Responsive directive don´t work with a only array parameter'); } else if (typeof config === 'string') { throw new Error('Responsive directive don´t work with a only string parameter'); } else if (typeof config === 'number') { throw new Error('Responsive directive don´t work with a only number parameter'); } else if (typeof config === 'undefined' || config === null) { throw new Error('Responsive directive don´t work without a param'); } for (let key in this.set_active_subscriptions) { if (this.set_active_subscriptions[key]) { this._actives.push(key); } } if (this._isEnabledForPlatform) { if (this.set_active_subscriptions.bootstrap) { this._subscription_Bootstrap = this._responsiveState.elemento$.subscribe(this.updateBootstrap.bind(this)); } if (this.set_active_subscriptions.browser) { this._subscription_Browser = this._responsiveState.browser$.subscribe(this.updateBrowser.bind(this)); } if (this.set_active_subscriptions.device) { this._subscription_Device = this._responsiveState.device$.subscribe(this.updateDevice.bind(this)); } if (this.set_active_subscriptions.pixelratio) { this._subscription_Pixel_Ratio = this._responsiveState.pixel$.subscribe(this.updatePixelRatio.bind(this)); } if (this.set_active_subscriptions.orientation) { this._subscription_Orientation = this._responsiveState.orientation$.subscribe(this.updateOrientation.bind(this)); } if (this.set_active_subscriptions.standard) { this._subscription_Standard = this._responsiveState.standard$.subscribe(this.updateStandard.bind(this)); } if (this.set_active_subscriptions.ie) { this._subscription_IE_Version = this._responsiveState.ieVersion$.subscribe(this.updateIEversion.bind(this)); } if (this.set_active_subscriptions.sizes) { this._subscription_custom_sizes = this._responsiveState.ancho$.subscribe(this.updateSizes.bind(this)); } } } private updateBootstrap(value: string): void { const _update = this._ifValueChanged(this._noRepeatBootstrapName, value); if (_update) { this.set_values.bootstrap = value; } this.updateEvent(this.set_values.bootstrap, 'bootstrap'); } private updateBrowser(value: string): void { this.set_values.browser = value; this.updateEvent(this.set_values.browser, 'browser'); } private updateDevice(value: string): void { this.set_values.device = value; this.updateEvent(this.set_values.device, 'device'); } private updatePixelRatio(value: string): void { this.set_values.pixelratio = value; this.updateEvent(this.set_values.pixelratio, 'pixelratio'); } private updateOrientation(value: string): void { this.set_values.orientation = value; this.updateEvent(this.set_values.orientation, 'orientation'); } private updateStandard(value: string): void { this.set_values.standard = value; this.updateEvent(this.set_values.standard, 'standard'); } private updateIEversion(value: string): void { this.set_values.ie = value; this.updateEvent(this.set_values.ie, 'ie'); } private updateSizes(value: number): void { if(this.responsiveContainer){ this.set_values.sizes = this._isEnabledForPlatform ? this.responsiveContainer.getWidth() : 0; }else if (this._sizes_window){ this.set_values.sizes = this._responsiveState.getWidth(this._sizes_window); }else{ this.set_values.sizes = value; } this.updateEvent(this.set_values.sizes, 'sizes'); } private updateEvent(param: any, type_directive: string): void { if (!!this._showWhenTrue) { switch (type_directive) { case 'bootstrap': this.showHideOperations(this._bootstrap_user_param.indexOf(param) !== -1, type_directive); break; case 'device': this.showHideOperations(this._devices_user_param.indexOf(param) !== -1, type_directive); break; case 'standard': this.showHideOperations(this._standard_user_param.indexOf(param) !== -1, type_directive); break; case 'orientation': this.showHideOperations(this._orientation_user_param.indexOf(param) !== -1, type_directive); break; case 'browser': this.showHideOperations(this._browser_user_param.indexOf(param) !== -1, type_directive); break; case 'pixelratio': this.showHideOperations(this._pixelratio_user_param.indexOf(param) !== -1, type_directive); break; case 'ie': this.showHideOperations(this._ie_user_param.indexOf(param) !== -1, type_directive); break; case 'sizes': this.showHideOperations( ( param >= this._sizes_user_param[0] && param < this._sizes_user_param[1] ), type_directive); break; } } else { switch (type_directive) { case 'bootstrap': this.showHideOperations(!(this._bootstrap_user_param.indexOf(param)), type_directive); break; case 'device': this.showHideOperations(!(this._devices_user_param.indexOf(param)), type_directive); break; case 'standard': this.showHideOperations(!(this._standard_user_param.indexOf(param)), type_directive); break; case 'orientation': this.showHideOperations(!(this._orientation_user_param.indexOf(param)), type_directive); break; case 'browser': this.showHideOperations(!(this._browser_user_param.indexOf(param)), type_directive); break; case 'pixelratio': this.showHideOperations(!(this._pixelratio_user_param.indexOf(param)), type_directive); break; case 'ie': this.showHideOperations(!(this._ie_user_param.indexOf(param)), type_directive); break; case 'sizes': this.showHideOperations(!(( param >= this._sizes_user_param[0] && param < this._sizes_user_param[1])), type_directive); break; } } } private showHideOperations(show: boolean, type_directive: string): void { const global_state = this.matchValues(show, type_directive); if (!!global_state) { if (this._globalNoRepeat === 0) { this._globalNoRepeat = 1; this.viewContainer.createEmbeddedView(this.templateRef); this.changes.emit(true); this.cd.markForCheck(); } } else { this._globalNoRepeat = 0; this.changes.emit(false); this.viewContainer.clear(); this.cd.markForCheck(); } } private matchValues(show: boolean, type_directive: string) { let match = true; if (show) { this.match_multiple[type_directive] = true; } else { this.match_multiple[type_directive] = false; } for (let all_key in this.match_multiple) { for (let active of this._actives) { if (all_key == active && this.match_multiple[all_key] === false) return match = false; } } return match; } public ngOnDestroy(): void { if (this._isEnabledForPlatform) { if (this.set_active_subscriptions.bootstrap) { this._subscription_Bootstrap.unsubscribe(); } if (this.set_active_subscriptions.browser) { this._subscription_Browser.unsubscribe(); } if (this.set_active_subscriptions.device) { this._subscription_Device.unsubscribe(); } if (this.set_active_subscriptions.pixelratio) { this._subscription_Pixel_Ratio.unsubscribe(); } if (this.set_active_subscriptions.orientation) { this._subscription_Orientation.unsubscribe(); } if (this.set_active_subscriptions.standard) { this._subscription_Standard.unsubscribe(); } if (this.set_active_subscriptions.ie) { this._subscription_IE_Version.unsubscribe(); } if (this.set_active_subscriptions.sizes) { this._subscription_custom_sizes.unsubscribe(); } } } private _ifValueChanged(oldValue: any, newValue: any): boolean { if (oldValue === newValue) { return false; } else { this._noRepeatBootstrapName = newValue; return true; } } private isJSON(value: any): boolean { try { JSON.stringify(value); return true; } catch (ex) { return false; } } }
the_stack
import * as React from 'react'; import styled, { keyframes } from 'styled-components'; import { useState } from 'react'; // import { ipcRenderer } from 'electron'; import { Client } from 'pg'; const getTables = (client) => { return new Promise((resolve, reject) => { client.query(`SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' ORDER BY table_name ASC`, (err, result) => { if (err) reject(err); resolve(result); } ); }); }; const getForeignKeys = (client, tableName) => { return new Promise((resolve, reject) => { client.query( `SELECT tc.table_schema, tc.constraint_name, tc.table_name, kcu.column_name, ccu.table_schema AS foreign_table_schema, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = '${tableName}'`, (err, result) => { if (err) reject(err); resolve(result.rows); } ); }); }; // #TODO: add error handling when tables lack a primary key // Relational database theory dictates that every table must have a primary key. // This rule is not enforced by PostgreSQL, but it is usually best to follow it. const getColumns = (client, tableName) => { return new Promise((resolve, reject) => { client.query( `SELECT COLUMN_NAME AS ColumnName, DATA_TYPE AS DataType, CHARACTER_MAXIMUM_LENGTH AS CharacterLength, COLUMN_DEFAULT AS DefaultValue FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '${tableName}'`, (err, result) => { if (err) // #TODO: give a msg that doesn't expose structure of database reject(err); resolve(result.rows); } ); }); }; const getPrimaryKey = (client, tableName) => { return new Promise((resolve, reject) => { client.query( `SELECT column_name FROM pg_constraint, information_schema.constraint_column_usage WHERE contype = 'p' AND information_schema.constraint_column_usage.table_name = '${tableName}' AND pg_constraint.conname = information_schema.constraint_column_usage.constraint_name`, (err, result) => { if (err) reject(err); resolve(result.rows[0].column_name); } ); }); }; async function composeTableData(client) { const tablesArr = []; let tableNames: any tableNames = await getTables(client); for (const table of tableNames.rows) { table.primaryKey = await getPrimaryKey(client, table.table_name); table.foreignKeys = await getForeignKeys(client, table.table_name); table.columns = await getColumns(client, table.table_name); tablesArr.push(table); } return new Promise((resolve, reject) => { if (tablesArr.length > 0) { resolve(tablesArr); } else { // #TODO: add empty state trigger reject(new Error('database empty')); } }); } const InvisibleHeader = styled.div` height: 30px; -webkit-app-region: drag; `; const LoginPageWrapper = styled.div` margin-top: -30px; display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; `; const Title = styled.h1` font-size: 600%; font-weight: none; color: white; `; const Panel = styled.div` height: 100vh; width: 50vw; display: flex; justify-content: center; align-items: center; `; const funtimes = keyframes` 0%{background-position:0% 50%} 50%{background-position:100% 50%} 100%{background-position:0% 50%} `; const LeftPanel = styled(Panel)` background-color: white; display: flex; width: 100vw; height: 100vh; animation: ${funtimes} 8s ease infinite; background: linear-gradient(270deg, #49cefe, #c647bc); background-size: 400% 400%; `; const LoginContainer = styled.div` display: flex; flex-direction: column; align-items: center; background-color: white; border-radius: 3px; padding: 20px; `; const LoginTypeNavigation = styled.div` display: flex; flex-direction: row; align-items: center; justify-content: center; `; interface LoginTypeButtonProps { readonly selectedLoginType: string; readonly buttonType: string; } const LoginTypeButton = styled.button<LoginTypeButtonProps>` padding: 5px; font-size: 120%; margin: 10px; background-color: transparent; display: flex; border: none; border-bottom: ${({ selectedLoginType, buttonType }) => selectedLoginType === buttonType ? '3px solid #4B70FE ' : '3px solid transparent'}; transition: 0.3s; :hover { border-bottom: 3px solid #4B70FE; cursor: pointer; } :focus { outline: none; } `; const URIConnectionContainer = styled.div` display: flex; flex-direction: column; padding: 20px; transition: all 0.2s; `; const InputLabel = styled.span` font-size: 80%; letter-spacing: 2px; color: #485360; `; interface IURIInputProps { requiredError: boolean; } const URIInput = styled.textarea<IURIInputProps>` width: 200px; height: 150px; border-radius: 3px; letter-spacing: 2px; resize: none; padding: 8px; border: ${({ requiredError }) => requiredError ? '1px solid #ca333e' : '1px solid lightgrey'}; :focus { outline: none; } `; const ToggleSSL = styled.div` display: flex; justify-content: center; padding-bottom: 10px; display: flex; align-items: center; `; const LoginBtn = styled.button` padding: 8px; width: 150px; border: none; transition: 0.2s; border-radius: 3px; font-size: 120%; color: white; text-align: center; background-color: #4B70FE; transition: all 0.2s; span { cursor: pointer; display: inline-block; position: relative; transition: 0.5s; } span:after { content: ">>"; position: absolute; opacity: 0; top: 0; right: -20px; transition: 0.5s; } :hover { box-shadow: 0px 5px 10px #bdc3c7; span { padding-right: 5px; } span:after { opacity: 1; } } :focus { outline: none; } :active{ transform: translateY(3px); box-shadow: 0px 2px 10px #bdc3c7; } ` const CredentialsContainer = styled.div` display: flex; flex-direction: column; padding: 20px; transition: all 0.2s; `; const InputAndLabelWrapper = styled.div` margin: 5px 0px; display: flex; flex-direction: column; `; const CredentialsInput = styled.input<IURIInputProps>` border-radius: 3px; padding: 8px; width: 200px; letter-spacing: 2px; border: ${({ requiredError }) => requiredError ? '1px solid #ca333e' : '1px solid lightgrey'}; :focus { outline: none; } `; const ConnectionErrorMessage = styled.div` background-color: #f1c7ca; width: 200px; color: #ca333e; border-radius: 3px; padding: 5px; margin: 5px; border-left: 3px solid #ca333e; font-size: 100%; transition: all 0.2s; `; const LogoutMessage = styled.div` background-color: #d5f5e3; width: 200px; color: #26a65b; border-radius: 3px; padding: 5px; margin: 5px; border-left: 3px solid #26a65b; font-size: 100%; transition: all 0.2s; `; const RequiredWarning = styled.span` color: #ca333e; font-size: 80%; transition: all 0.2s; `; const Login = ({ setTableData, setCurrentView, pgClient, setPgClient }) => { const [loginType, setLoginType] = useState('URI'); const [host, setHost] = useState({ value: '', requiredError: false }); const [port, setPort] = useState('5432'); const [username, setUsername] = useState({ value: '', requiredError: false }); const [password, setPassword] = useState({ value: '', requiredError: false }); const [database, setDatabase] = useState({ value: '', requiredError: false }); const [URI, setURI] = useState(''); const [isSSL, setSSL] = useState(false); const [requiredError, setRequiredError] = useState(false); const [connectionError, setConnectionError] = useState(false); const [loading, setLoading] = useState(false); const [loggedOutMessage, setLoggedOutMessage] = useState(''); const sendLoginURI = (): void => { if (loggedOutMessage) setLoggedOutMessage(''); const updatedPort = !port ? '5432' : port; let updatedURI; if (loginType === 'URI') updatedURI = URI; else if (loginType === 'Credentials') updatedURI = `postgres://${username.value}:${password.value}@${host.value}:${updatedPort}/${database.value}`; if (isSSL) updatedURI += '?ssl=true'; if (!updatedURI) setRequiredError(true); if (!host.value) setHost({ value: '', requiredError: true }); if (!username.value) setUsername({ value: '', requiredError: true }); if (!password.value) setPassword({ value: '', requiredError: true }); if (!database.value) setDatabase({ value: '', requiredError: true }); if ( URI || (host.value && username.value && password.value && database.value) ) { // const client = new Client(`postgres://ltdnkwnbccooem:64ad308e565b39cc070194f7fa621ae0e925339be5a1c69480ff2a4462eab4c4@ec2-54-163-226-238.compute-1.amazonaws.com:5432/ddsu160rb5t7vq?ssl=true`) const client = new Client(updatedURI); client.connect(); setPgClient(client) composeTableData(client) .then(tableData => { setTableData(tableData) setCurrentView('homePage') }) } }; const captureURI = (e): void => { const sanitizedURI = e.target.value.replace(/\s+/g, ''); setURI(sanitizedURI); if (requiredError) setRequiredError(false); }; return ( <React.Fragment> <InvisibleHeader></InvisibleHeader> <LoginPageWrapper> <LeftPanel> <Panel> <Title>SeeQL</Title> </Panel> <Panel> <LoginContainer> {loggedOutMessage === 'inactivity' && ( <LogoutMessage> You've been logged out due to inactivity. Please re-enter your credentials to login. </LogoutMessage> )} {loggedOutMessage === 'userlogout' && ( <LogoutMessage>You have successfully logged out. Have a nice day.</LogoutMessage> )} {connectionError && ( <ConnectionErrorMessage> We were unable to connect to your database. Please try again. </ConnectionErrorMessage> )} <LoginTypeNavigation> <LoginTypeButton buttonType="URI" selectedLoginType={loginType} onClick={() => { setLoginType('URI'), setConnectionError(false); }} > URI </LoginTypeButton> <LoginTypeButton buttonType="Credentials" selectedLoginType={loginType} onClick={() => { setLoginType('Credentials'), setConnectionError(false); }} > Credentials </LoginTypeButton> </LoginTypeNavigation> {loginType === 'Credentials' && ( <CredentialsContainer> <InputAndLabelWrapper> <InputLabel>Host</InputLabel> <CredentialsInput type="text" requiredError={host.requiredError} placeholder="host" value={host.value} onChange={e => setHost({ value: e.target.value, requiredError: false }) } /> {host.requiredError && ( <RequiredWarning>host is required</RequiredWarning> )} </InputAndLabelWrapper> <InputAndLabelWrapper> <InputLabel>Port</InputLabel> <CredentialsInput type="text" requiredError={false} placeholder="port (default 5432)" value={port} onChange={e => setPort(e.target.value)} /> </InputAndLabelWrapper> <InputAndLabelWrapper> <InputLabel>Username</InputLabel> <CredentialsInput type="text" requiredError={username.requiredError} placeholder="username" value={username.value} onChange={e => setUsername({ value: e.target.value, requiredError: false }) } /> {username.requiredError && ( <RequiredWarning>username is required</RequiredWarning> )} </InputAndLabelWrapper> <InputAndLabelWrapper> <InputLabel>Password</InputLabel> <CredentialsInput type="password" requiredError={password.requiredError} placeholder="password" value={password.value} onChange={e => setPassword({ value: e.target.value, requiredError: false }) } /> {password.requiredError && ( <RequiredWarning>password is required</RequiredWarning> )} </InputAndLabelWrapper> <InputAndLabelWrapper> <InputLabel>Database</InputLabel> <CredentialsInput type="text" requiredError={database.requiredError} placeholder="database" value={database.value} onChange={e => setDatabase({ value: e.target.value, requiredError: false }) } /> {database.requiredError && ( <RequiredWarning>database is required</RequiredWarning> )} </InputAndLabelWrapper> </CredentialsContainer> )} {loginType === 'URI' && ( <URIConnectionContainer> <InputLabel>URI Connection String</InputLabel> <URIInput requiredError={requiredError} onChange={captureURI} placeholder="Enter your URI connection string..." value={URI} /> {requiredError && ( <RequiredWarning>URI is required</RequiredWarning> )} </URIConnectionContainer> )} <ToggleSSL> <input type="checkbox" onChange={e => setSSL(e.target.checked)} /> <InputLabel>ssl?</InputLabel> </ToggleSSL> {!loading && <><LoginBtn onClick={sendLoginURI}><span>Login</span></LoginBtn></>} {loading && <LoginBtn disabled>Loading...</LoginBtn>} </LoginContainer> </Panel> </LeftPanel> </LoginPageWrapper> </React.Fragment > ); }; export default Login;
the_stack
import inquirer, { Answers, InputQuestionOptions, QuestionCollection } from "inquirer"; import { createDirectoryIfNotExists, FEATURES } from "./utils"; export function chooseSubscription(subscriptionsList: AzureSubscription[]): Promise<Answers> { const questions: QuestionCollection = [ { type: "list", name: "subscription", message: "Choose a subscription:", choices: subscriptionsList.map((subscription: AzureSubscription) => { return { name: `${subscription.name}`, disabled: subscription.state !== "Enabled", value: subscription.id }; }), validate: function (value: string) { if (value.length) { return true; } else { return "Please choose a subscription."; } } } ]; return inquirer.prompt(questions); } export function chooseResourceGroup(resourceGroups: AzureResourceGroup[]): Promise<Answers> { // move resource groups created with Hexa to the top resourceGroups = resourceGroups.sort((a, _b) => (a.tags && a.tags["x-created-by"] === "hexa" ? -1 : 1)); if (process.env.HEXA_ENABLE_ADDING_NEW_RESOURCE) { resourceGroups = [ ...resourceGroups, { id: "MANUAL", location: "", tags: {}, name: "<Create a Resource Group>" } ]; } const questions: QuestionCollection = [ { type: "list", name: "resourceGroup", message: "Choose resource group:", choices: resourceGroups.map((resourceGroup: AzureResourceGroup) => { const isCreatedByHexa = resourceGroup.tags && resourceGroup.tags["x-created-by"] === "hexa"; return { name: `${resourceGroup.name} ${isCreatedByHexa ? "(hexa)" : ""}`, value: resourceGroup.id, short: resourceGroup.name }; }), validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a resource group."; } } } ]; return inquirer.prompt(questions); } export function chooseAccountStorage(storageAccounts: AzureStorage[]): Promise<inquirer.Answers> { // move storage accounts created with Hexa to the top storageAccounts = storageAccounts.sort((a, _b) => (a.tags && a.tags["x-created-by"] === "hexa" ? -1 : 1)); if (process.env.HEXA_ENABLE_ADDING_NEW_RESOURCE) { storageAccounts = [ ...storageAccounts, { id: "MANUAL", tags: {}, location: "", name: "<Create Storage Account>" } ]; } const questions: QuestionCollection = [ { type: "list", name: "storage", message: "Choose a storage account:", choices: storageAccounts.map((storageAccount: AzureStorage) => { return { name: storageAccount.name, value: storageAccount.id }; }), validate: function (value: string) { if (value.length) { return true; } else { return "Please choose a storage account."; } } } ]; return inquirer.prompt(questions); } export function askForFeatures(features: typeof FEATURES): Promise<Answers> { const questions: QuestionCollection = [ { type: "checkbox", name: "features", message: "Choose features you want to setup:", choices: features, validate: function (value: string) { if (value.length) { return true; } else { return "Please choose at least one feature."; } } } ]; return inquirer.prompt(questions); } export function askForResourceGroupDetails(regions: AzureRegion[], defaultResourceGroupName: string, defaultRegion: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "name", message: "Enter a name for the resource group:", default: defaultResourceGroupName, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a name for the resource group."; } } }, { type: "list", name: "region", message: "Choose a region:", default: defaultRegion, choices: regions.map((region: AzureRegion) => { return { name: `${region.name} (${region.displayName})`, value: region.name, short: region.displayName }; }), validate: function (value: string) { if (value.length) { return true; } else { return "Please choose a region."; } } } ]; return inquirer.prompt(questions); } export function askForStorageAccountDetails(_regions: AzureRegion[], defaultStorageName: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "name", message: "Enter a name for the storage account:", default: defaultStorageName, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a name for the storage account."; } } }, ]; return inquirer.prompt(questions); } export async function askForAzureStaticWebAppsProjectDetails(defaultGitBranch: string, defaultGitUrl: string, outputLocation: string, gitHubToken: string): Promise<Answers> { const gitUrl: InputQuestionOptions = { type: "input", name: "gitUrl", message: "Enter the URL of your GitHub project:", validate: function (value: string) { if (value.length) { return true; } else { return "Please enter an existing GitHub URL of your project"; } } }; if (defaultGitUrl) { gitUrl.default = defaultGitUrl; } const questions: QuestionCollection = [ gitUrl, { type: "input", name: "gitBranch", message: "Enter branch's name to deploy:", default: defaultGitBranch, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a name of the git branch to deploy."; } } }, { type: "input", name: "gitHubToken", message: "Enter your GitHub Personal Access Token (https://github.com/settings/tokens):", default: gitHubToken, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter your GitHub Personal Access Token."; } } }, { type: "input", name: "appLocation", message: "Enter the folder your application code.:", default: '/', validate: function (value: string) { if (value.length) { return true; } else { return "Please enter the folder of your application code."; } } }, { type: "input", name: "outputLocation", message: "Enter the folder of the build output directory to deploy:", default: outputLocation, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter the folder of the build output directory to deploy."; } } }, { type: "input", name: "apiLocation", message: "Enter the folder of your Azure Functions code (optional):", default: 'api', validate: function (value: string) { if (value.length) { return true; } else { return "Please enter the folder of your Azure Functions code."; } } } ]; return inquirer.prompt(questions); } export function askForDatabaseDetails(defaultDatabaseName: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "databaseName", message: "Enter a name for the database:", default: defaultDatabaseName, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a name for the database."; } } }, { type: "list", name: "databaseType", message: "Choose a database type:", default: 0, choices: [ { name: `Azure Table Storage`, value: "TABLE_STORAGE", short: `Table Storage` }, { name: `Azure Cosmos DB`, value: "COSMOSDB", short: `CosmosDB` } ], validate: function (value: string) { if (value.length) { return true; } else { return "Please choose a Database type."; } } } ]; return inquirer.prompt(questions); } export function askForProjectDetails(defaultProjectName: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "name", message: "Enter the project's name:", default: defaultProjectName, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a name for the project."; } } } ]; return inquirer.prompt(questions); } export function askIfOverrideProjectFile(): Promise<Answers> { const forceDelete = !!process.env.HEXA_RESET_MODE; let deletionWarning = "(File will be deleted)"; const questions: QuestionCollection = [ { type: "confirm", name: "override", message: `Configuration file found. Do you want to override it? ${forceDelete && deletionWarning}`, default: false } ]; return inquirer.prompt(questions); } export function askForHostingFolder(defaultPublicFolderName: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "folder", message: "Enter public folder (will be created if not present):", default: defaultPublicFolderName, validate: function (value: string) { if (value && value.length) { return createDirectoryIfNotExists(value); } else { return "Please enter a public folder."; } } } ]; return inquirer.prompt(questions); } export function askForFunctionsAppFolder(): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "folder", message: "Choose the functions folder (will be created if not present):", default: "functions", validate: function (value: string) { if (value && value.length) { return createDirectoryIfNotExists(value); } else { return "Please enter a folder for your Functions."; } } } ]; return inquirer.prompt(questions); } export function askForFunctionNameFolder(functionFolderName: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "confirm", name: "override", message: `Function ${functionFolderName} found. Do you want to override it?`, default: false } ]; return inquirer.prompt(questions); } export function askForKubernetesClusterDetails(defaultClusterName: string): Promise<Answers> { const questions: QuestionCollection = [ { type: "input", name: "name", message: "Enter a name for the Kubernetes cluster:", default: defaultClusterName, validate: function (value: string) { if (value.length) { return true; } else { return "Please enter a name for the Kubernetes cluster."; } } } ]; return inquirer.prompt(questions); } export function chooseKubernetesCluster(kubernetesClusters: AzureKubernetesCluster[]): Promise<inquirer.Answers> { // move clusters created with Hexa to the top kubernetesClusters = kubernetesClusters.sort((a, _b) => (a.tags && a.tags["x-created-by"] === "hexa" ? -1 : 1)); if (process.env.HEXA_ENABLE_ADDING_NEW_RESOURCE) { kubernetesClusters = [ ...kubernetesClusters, { id: "MANUAL", tags: {}, hostname: "", publicIp: {} as any, nodeResourceGroup: "", name: "<Create a Kubernetes Cluster>" } ]; } const questions: QuestionCollection = [ { type: "list", name: "cluster", message: "Choose a cluster:", choices: kubernetesClusters.map((cluster: AzureKubernetesCluster) => { return { name: cluster.name, value: cluster.id }; }), validate: function (value: string) { if (value.length) { return true; } else { return "Please choose a cluster."; } } } ]; return inquirer.prompt(questions); } export function chooseAcrAccount(AcrList: AzureContainerRegistry[]): Promise<inquirer.Answers> { // move ACR accounts created with Hexa to the top AcrList = AcrList.sort((a, _b) => (a.tags && a.tags["x-created-by"] === "hexa" ? -1 : 1)); if (process.env.HEXA_ENABLE_ADDING_NEW_RESOURCE) { AcrList = [ ...AcrList, { id: "MANUAL", tags: {}, hostname: "", name: "<Create a Container Registry>" } ]; } const questions: QuestionCollection = [ { type: "list", name: "registry", message: "Choose a container registry:", choices: AcrList.map((cluster: AzureContainerRegistry) => { return { name: cluster.name, value: cluster.id }; }), validate: function (value: string) { if (value.length) { return true; } else { return "Please choose a container registry."; } } } ]; return inquirer.prompt(questions); }
the_stack
import {Mutable, Class, AnyTiming, Timing} from "@swim/util"; import {Affinity, FastenerOwner} from "@swim/component"; import {Length} from "@swim/math"; import type {Color} from "@swim/style"; import {Look, Mood, MoodVector, ThemeMatrix, ThemeAnimator} from "@swim/theme"; import {ViewContextType, ViewContext, View, ViewRefFactory, ViewRef} from "@swim/view"; import {HtmlView} from "@swim/dom"; import {DeckSlot} from "./DeckSlot"; import type {DeckSliderObserver} from "./DeckSliderObserver"; /** @public */ export class DeckSlider extends DeckSlot { constructor(node: HTMLElement) { super(node); this.itemCount = 0; this.item = null; this.initSlider(); } initSlider(): void { this.addClass("deck-slider"); this.position.setState("relative", Affinity.Intrinsic); } override readonly observerType?: Class<DeckSliderObserver>; @ThemeAnimator({type: Number, inherits: true, updateFlags: View.NeedsLayout}) override readonly deckPhase!: ThemeAnimator<this, number | undefined>; @ThemeAnimator({type: Number, value: 0.5}) override readonly slotAlign!: ThemeAnimator<this, number>; override get colorLook(): Look<Color> { return Look.color; } /** @internal */ itemCount: number; /** @internal */ item: DeckSliderItem<this, HtmlView> | null; protected createItem(value: string): HtmlView { const itemView = HtmlView.fromTag("span"); itemView.display.setState("flex", Affinity.Intrinsic); itemView.alignItems.setState("center", Affinity.Intrinsic); itemView.whiteSpace.setState("nowrap", Affinity.Intrinsic); itemView.text(value); return itemView; } pushItem(newItemView: HtmlView | string, timing?: AnyTiming | boolean): void { if (typeof newItemView === "string") { newItemView = this.createItem(newItemView); } const oldItemCount = this.itemCount; const newItemCount = oldItemCount + 1; this.itemCount = newItemCount; const oldItemKey = "item" + oldItemCount; const oldItemRef = this.getFastener(oldItemKey, ViewRef) as DeckSliderItem<this, HtmlView> | null; const oldItemView = oldItemRef !== null ? oldItemRef.view : null; const newItemKey = "item" + newItemCount; const newItemRef = DeckSliderItemRef.create(this) as DeckSliderItem<this, HtmlView>; Object.defineProperty(newItemRef, "name", { value: newItemKey, configurable: true, }) newItemRef.itemIndex = newItemCount; this.willPushItem(newItemView, oldItemView); this.item = newItemRef; this.setFastener(newItemKey, newItemRef); newItemRef.setView(newItemView); newItemRef.insertView(); if (timing === void 0 && oldItemCount === 0) { timing = false; } else if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, Mood.navigating, false); } else { timing = Timing.fromAny(timing); } //if (this.deckPhase.superFastener === null) { // this.deckPhase.setState(newItemCount, timing); //} if (timing === false) { this.didPushItem(newItemView, oldItemView); } } protected willPushItem(newItemView: HtmlView, oldItemView: HtmlView | null): void { this.forEachObserver(function (observer: DeckSliderObserver): void { if (observer.deckSliderWillPushItem !== void 0) { observer.deckSliderWillPushItem(newItemView, oldItemView, this); } }); } protected didPushItem(newItemView: HtmlView, oldItemView: HtmlView | null): void { if (oldItemView !== null && oldItemView.parent === this) { oldItemView.remove(); } this.forEachObserver(function (observer: DeckSliderObserver): void { if (observer.deckSliderDidPushItem !== void 0) { observer.deckSliderDidPushItem(newItemView, oldItemView, this); } }); } popItem(timing?: AnyTiming | boolean): HtmlView | null { const oldItemCount = this.itemCount; const newItemCount = oldItemCount - 1; this.itemCount = newItemCount; const oldItemKey = "item" + oldItemCount; const oldItemRef = this.getFastener(oldItemKey, ViewRef) as DeckSliderItem<this, HtmlView> | null; const oldItemView = oldItemRef !== null ? oldItemRef.view : null; if (oldItemView !== null) { const newItemKey = "item" + newItemCount; const newItemRef = this.getFastener(newItemKey, ViewRef) as DeckSliderItem<this, HtmlView> | null; const newItemView = newItemRef !== null ? newItemRef.view : null; this.willPopItem(newItemView, oldItemView); this.item = newItemRef; if (newItemRef !== null) { newItemRef.insertView(); } if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, Mood.navigating, false); } else { timing = Timing.fromAny(timing); } //if (this.deckPhase.superFastener === null) { // this.deckPhase.setState(newItemCount, timing); //} if (timing === false) { this.didPopItem(newItemView, oldItemView); } } return oldItemView; } protected willPopItem(newItemView: HtmlView | null, oldItemView: HtmlView): void { this.forEachObserver(function (observer: DeckSliderObserver): void { if (observer.deckSliderWillPopItem !== void 0) { observer.deckSliderWillPopItem(newItemView, oldItemView, this); } }); } protected didPopItem(newItemView: HtmlView | null, oldItemView: HtmlView): void { const oldItemKey = oldItemView.key; oldItemView.remove(); if (oldItemKey !== void 0) { const oldItemRef = this.getFastener(oldItemKey, ViewRef) as DeckSliderItem<this, HtmlView> | null; if (oldItemRef !== null && oldItemRef.itemIndex > this.itemCount) { this.setFastener(oldItemKey, null); } } this.forEachObserver(function (observer: DeckSliderObserver): void { if (observer.deckSliderDidPopItem !== void 0) { observer.deckSliderDidPopItem(newItemView, oldItemView, this); } }); } protected override didLayout(viewContext: ViewContextType<this>): void { if (!this.deckPhase.tweening) { const deckPhase = this.deckPhase.value; if (deckPhase !== void 0) { const nextItemIndex = Math.round(deckPhase + 1); const nextItemKey = "item" + nextItemIndex; const nextItemRef = this.getFastener(nextItemKey, ViewRef) as DeckSliderItem<this, HtmlView> | null; const nextItemView = nextItemRef !== null ? nextItemRef.view : null; if (nextItemView !== null) { this.didPopItem(this.item !== null ? this.item.view : null, nextItemView); } else if (this.item !== null && this.item.view !== null && Math.round(deckPhase) > 0) { const prevItemIndex = Math.round(deckPhase - 1); const prevItemKey = "item" + prevItemIndex; const prevItemRef = this.getFastener(prevItemKey, ViewRef) as DeckSliderItem<this, HtmlView> | null; const prevItemView = prevItemRef !== null ? prevItemRef.view : null; this.didPushItem(this.item.view, prevItemView); } } } super.didLayout(viewContext); } } /** @internal */ export interface DeckSliderItem<O extends DeckSlider = DeckSlider, V extends HtmlView = HtmlView> extends ViewRef<O, V> { itemIndex: number; /** @internal */ itemWidth: Length | string | null; /** @override */ didAttachView(itemView: V): void; /** @override */ insertChild(parent: View, child: V, target: View | number | null, key: string | undefined): void; /** @protected */ viewDidApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean, itemView: V): void; viewDidLayout(viewContext: ViewContext, itemView: V): void; /** @protected */ initItem(itemView: V): void; /** @protected */ layoutItem(itemView: V): void; } /** @internal */ export const DeckSliderItem = (function (_super: typeof ViewRef) { const DeckSliderItem = _super.extend("DeckSliderItem") as ViewRefFactory<DeckSliderItem<any, any>>; DeckSliderItem.prototype.didAttachView = function (this: DeckSliderItem, itemView: HtmlView): void { this.initItem(itemView); }; DeckSliderItem.prototype.insertChild = function (this: DeckSliderItem, parent: View, child: HtmlView, target: View | number | null, key: string | undefined): void { const targetKey = "item" + (this.itemIndex + 1); target = parent.getChild(targetKey); parent.insertChild(child, target, key); }; DeckSliderItem.prototype.viewDidApplyTheme = function (this: DeckSliderItem, theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean, itemView: HtmlView): void { if (itemView.color.hasAffinity(Affinity.Intrinsic)) { itemView.color.setState(theme.getOr(this.owner.colorLook, mood, null), timing, Affinity.Intrinsic); } }; DeckSliderItem.prototype.viewDidLayout = function (this: DeckSliderItem, viewContext: ViewContext, itemView: HtmlView): void { this.layoutItem(itemView); }; DeckSliderItem.prototype.initItem = function (this: DeckSliderItem, itemView: HtmlView): void { itemView.position.setState("absolute", Affinity.Intrinsic); }; DeckSliderItem.prototype.layoutItem = function (this: DeckSliderItem, itemView: HtmlView): void { const itemIndex = this.itemIndex; const slotAlign = this.owner.slotAlign.getValue(); let slotWidth: Length | number | null = this.owner.width.state; slotWidth = slotWidth instanceof Length ? slotWidth.pxValue() : this.owner.node.offsetWidth; let slotHeight: Length | number | null = this.owner.height.state; slotHeight = slotHeight instanceof Length ? slotHeight.pxValue() : this.owner.node.offsetHeight; const deckPhase = this.owner.deckPhase.getValueOr(0); const nextIndex = Math.max(this.owner.itemCount, Math.ceil(deckPhase)); const prevIndex = nextIndex - 1; const itemPhase = deckPhase - prevIndex; let itemWidth: Length | number | null = itemView.width.state; this.itemWidth = itemWidth; if (itemWidth instanceof Length) { itemWidth = itemWidth.pxValue(slotWidth); } else { itemWidth = itemView.node.offsetWidth; // Memoize computed item width while animating // to avoid style recalculation in animation frames. if (this.owner.deckPhase.tweening) { itemView.width.setState(itemWidth, Affinity.Intrinsic); } else { itemView.width.setState(this.itemWidth, Affinity.Intrinsic); } } const slotSpace = slotWidth - itemWidth; if (itemIndex < prevIndex || itemIndex === prevIndex && itemPhase === 1) { // under itemView.left.setState(0, Affinity.Intrinsic); itemView.top.setState(0, Affinity.Intrinsic); itemView.height.setState(slotHeight, Affinity.Intrinsic); itemView.opacity.setState(0, Affinity.Intrinsic); itemView.setCulled(true); } else if (itemIndex === prevIndex) { // out itemView.left.setState(slotSpace * slotAlign * (1 - itemPhase), Affinity.Intrinsic); itemView.top.setState(0, Affinity.Intrinsic); itemView.height.setState(slotHeight, Affinity.Intrinsic); itemView.opacity.setState(1 - itemPhase, Affinity.Intrinsic); itemView.setCulled(false); } else if (itemIndex === nextIndex) { // in itemView.left.setState(slotSpace * (1 - itemPhase) + slotSpace * slotAlign * itemPhase, Affinity.Intrinsic); itemView.top.setState(0, Affinity.Intrinsic); itemView.height.setState(slotHeight, Affinity.Intrinsic); itemView.opacity.setState(itemPhase, Affinity.Intrinsic); itemView.setCulled(false); } else { // over itemView.left.setState(slotSpace, Affinity.Intrinsic); itemView.top.setState(0, Affinity.Intrinsic); itemView.height.setState(slotHeight, Affinity.Intrinsic); itemView.opacity.setState(0, Affinity.Intrinsic); itemView.setCulled(true); } }; DeckSliderItem.construct = function <F extends DeckSliderItem<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).itemIndex = 0; (fastener as Mutable<typeof fastener>).itemWidth = null; return fastener; }; return DeckSliderItem; })(ViewRef); /** @internal */ export const DeckSliderItemRef = ViewRef.define<DeckSlider, HtmlView>("DeckSliderItemRef", { extends: DeckSliderItem, key: true, type: HtmlView, observes: true, });
the_stack
import path from "path"; import fg from "fast-glob"; import yaml from "js-yaml"; import mapObj from "map-obj"; import fs from "fs-extra"; import { log } from "./log"; import { template, getTemplateStringByParentName, getRawTriggers, getTriggerWebhookBasePath, getAsyncStringFunctionResult, } from "./utils"; import multimatch from "multimatch"; import { ITriggerContext, IWorkflow, AnyObject, IWorkflowData, OutputsMode, OutcomeStatus, ConclusionStatus, } from "./interface"; import { TRIGGER_RESULT_ENV_PREFIX } from "./constans"; interface IGetWorkflowsOptions { context: ITriggerContext; cwd: string; include?: string[]; exclude?: string[]; } export const getWorkflowDoc = async ({ path: filePath, }: { path: string; }): Promise<IWorkflowData> => { let doc: IWorkflowData | string | undefined; try { doc = yaml.safeLoad(await fs.readFile(filePath, "utf8")) as IWorkflowData; } catch (e) { log.error("Load yaml file error:", filePath, e); throw e; } return doc; }; export const getWorkflow = async ({ cwd, path: filePath, context, }: { cwd: string; path: string; context: ITriggerContext; }): Promise<IWorkflow | undefined> => { const relativePath = path.relative(path.resolve(cwd, "workflows"), filePath); const doc = await getWorkflowDoc({ path: filePath }); if (doc && typeof doc === "object" && doc.on) { // handle doc on, replace variables if (doc.on && typeof doc.on === "object") { const currentEnv = doc.env || {}; // get new env actual value of doc yml const newEnv: Record<string, string> = mapObj( currentEnv as Record<string, string>, (mapKey, mapValue) => { let newMapValueString = ""; let isHandled = false; if (typeof mapValue === "string") { const theMapValue = mapValue as string; // if supported newMapValueString = template( theMapValue, { env: process.env, ...context, }, { shouldReplaceUndefinedToEmpty: true, } ); isHandled = true; } if (isHandled) { return [mapKey, newMapValueString]; } else { return [mapKey, mapValue]; } }, { deep: true, } ) as Record<string, string>; // add env to context // add metadata context const metadata: Record<string, string> = {}; const newContext = { ...context, env: { ...process.env, ...newEnv, }, metadata, }; if (doc.on) { const docOnKeys = Object.keys(doc.on); for (let i = 0; i < docOnKeys.length; i++) { const triggerName = docOnKeys[i]; if ( (doc.on as Record<string, Record<string, Record<string, string>>>)[ triggerName ] && (doc.on as Record<string, Record<string, Record<string, string>>>)[ triggerName ].config && (doc.on as Record<string, Record<string, Record<string, string>>>)[ triggerName ].config.metadata ) { // run metadata function newContext.metadata = (await getAsyncStringFunctionResult( (doc.on as Record< string, Record<string, Record<string, string>> >)[triggerName].config.metadata, newContext )) as Record<string, string>; } } } const newOn = mapObj( doc.on, (mapKey, mapValue) => { let newMapValueString = ""; let isHandled = false; if (typeof mapValue === "string") { const theMapValue = mapValue as string; // if supported newMapValueString = template(theMapValue, newContext, { shouldReplaceUndefinedToEmpty: true, }); isHandled = true; } if (isHandled) { return [mapKey as string, newMapValueString]; } else { return [mapKey as string, mapValue]; } }, { deep: true, } ) as Record<string, AnyObject>; doc.on = newOn; } return { path: filePath, relativePath: relativePath, data: doc as IWorkflowData, }; } else { log.debug("skip empty or invalid file", filePath); return undefined; } }; export const getWorkflows = async ( options: IGetWorkflowsOptions ): Promise<IWorkflow[]> => { const { context, cwd } = options; const include = options.include as string[]; const exclude = options.exclude as string[]; const workflowsPath = path.resolve(cwd, "workflows"); // check is folder const stat = await fs.lstat(workflowsPath); const isFile = stat.isFile(); let entries = []; if (isFile) { // check is exist const isExist = await fs.pathExists(workflowsPath); if (isExist) { // relative path const relativePath = path.relative( path.resolve(cwd, "workflows"), workflowsPath ); entries.push({ path: workflowsPath, relativePath, }); } } else { // get all files with json object let relativeEntries = await fg(["**/*.yml", "**/*.yaml"], { cwd: workflowsPath, dot: true, }); const patterns: string[] = arrify(include).concat(negate(exclude)); // filter if (patterns.length) { log.debug("workflows detect: ", relativeEntries); log.debug("workflows filter pattern: ", patterns); if (!include.length) { // only excludes needs to select all items first // globstar is for matching scoped packages patterns.unshift("**"); } relativeEntries = multimatch(relativeEntries, patterns); log.debug("workflows filter results: ", relativeEntries); } entries = relativeEntries.map((relativePath) => { return { relativePath, path: path.resolve(workflowsPath, relativePath), }; }); } const workflows: IWorkflow[] = []; // Get document, or throw exception on error for (let index = 0; index < entries.length; index++) { const filePath = entries[index].path; const workflow = await getWorkflow({ path: filePath, cwd: cwd, context: context, }); if (workflow) { workflows.push(workflow); } } const validWorkflows = workflows.filter((workflow) => { const rawTriggers = getRawTriggers(workflow.data); return rawTriggers.length > 0; }); return validWorkflows; }; export const getJobsDependences = ( jobs: Record<string, AnyObject> ): { lastJobs: string[]; firstJobs: string[] } => { const jobKeys = Object.keys(jobs); const jobsWhoHasNeeds: { id: string; needs: string[]; }[] = []; const jobsNoNeeds: string[] = []; jobKeys.forEach((jobKey) => { const job = jobs[jobKey] as { needs: string[] }; if (job && job.needs && job.needs.length > 0) { jobsWhoHasNeeds.push({ id: jobKey, needs: job.needs, }); } if (!job.needs || job.needs.length === 0) { jobsNoNeeds.push(jobKey); } }); let lastJobs: string[] = []; let beNeededJobs: string[] = []; jobsWhoHasNeeds.forEach((job) => { job.needs.forEach((beNeededJob) => { const isBeNeeded = jobsWhoHasNeeds.find( (item) => item.id === beNeededJob ); if (isBeNeeded) { beNeededJobs.push(beNeededJob); } }); }); beNeededJobs = [...new Set(beNeededJobs)]; jobsWhoHasNeeds.forEach((job) => { if (!beNeededJobs.includes(job.id)) { lastJobs.push(job.id); } }); if (lastJobs.length === 0) { lastJobs = jobKeys; } return { lastJobs, firstJobs: jobsNoNeeds }; }; export const renameJobsBySuffix = ( jobs: Record<string, AnyObject>, suffix: string ): Record<string, AnyObject> => { const jobKeys = Object.keys(jobs); const newJobs: Record<string, AnyObject> = {}; jobKeys.forEach((jobKey) => { const job = jobs[jobKey] as { needs: string[]; }; const newJobKey = `${jobKey}${suffix}`; if (job.needs) { job.needs = job.needs.map((item: string) => { return `${item}${suffix}`; }); } newJobs[newJobKey] = job; }); return newJobs; }; interface IBuildSingleWorkflowOptions { workflow: IWorkflow; cwd?: string; trigger: { name: string; results: AnyObject[]; outcome: OutcomeStatus; conclusion: ConclusionStatus; outputsMode?: OutputsMode; exportOutputs?: boolean; outputsDir?: string; resultsPerWorkflow?: number; }; } export const getBuiltWorkflows = async ( options: IBuildSingleWorkflowOptions ): Promise<IWorkflowData[]> => { log.trace("buildWorkflow options:", options); const { workflow, trigger } = options; const cwd = options.cwd || process.cwd(); const { outcome, conclusion, results, resultsPerWorkflow } = trigger; const outputsMode = trigger.outputsMode || "separate"; const exportOutputs = trigger.exportOutputs || false; const outputsDir = trigger.outputsDir || "dist/outputs"; const workflowData = { ...workflow.data }; // handle context expresstion const workflowDataJobs: Record< string, AnyObject > = workflowData.jobs as Record<string, AnyObject>; delete workflowData.jobs; let jobsGroups: { lastJobs: string[]; firstJobs: string[]; jobs: Record<string, AnyObject>; }[] = []; // jobs internal env let jobInternalEnvs: Record<string, string>[] = []; if (conclusion === "success") { if (outputsMode === "combine") { if (resultsPerWorkflow && results.length > resultsPerWorkflow) { const jobsGroupsCount = Math.ceil(results.length / resultsPerWorkflow); const getJobsGroupsResults = Array.from({ length: jobsGroupsCount, }).map((_, index) => { return getJobGroups({ cwd, outputs: results.slice( index * resultsPerWorkflow, (index + 1) * resultsPerWorkflow ), exportOutputs, outputsDir, outcome: outcome, conclusion: conclusion, workflowData: workflowData, workflowDataJobs: workflowDataJobs, workflowRelativePath: workflow.relativePath, triggerName: trigger.name, suffix: `${index}`, }); }); const jobsGroupsResults = await Promise.all(getJobsGroupsResults); jobsGroups = jobsGroupsResults.map((item) => item.jobsGroup); jobInternalEnvs = jobsGroupsResults.map((item) => item.jobInternalEnv); return jobsGroups.map((jobsGroup, index) => { return getWorkflowData({ jobsGroups: [jobsGroup], jobInternalEnvs: [jobInternalEnvs[index]], workflowData, }); }); } else { const jobsGroupsResult = await getJobGroups({ cwd, outputs: results, outcome: outcome, exportOutputs, outputsDir, conclusion: conclusion, workflowData: workflowData, workflowDataJobs: workflowDataJobs, workflowRelativePath: workflow.relativePath, triggerName: trigger.name, }); jobsGroups.push(jobsGroupsResult.jobsGroup); jobInternalEnvs.push(jobsGroupsResult.jobInternalEnv); } } else { const getJobsGroupsResults = results.map((result, index) => getJobGroups({ cwd, outputs: result, outcome: outcome, exportOutputs, outputsDir, conclusion: conclusion, workflowData: workflowData, workflowDataJobs: workflowDataJobs, workflowRelativePath: workflow.relativePath, triggerName: trigger.name, suffix: `${index}`, }) ); const jobsGroupsResults = await Promise.all(getJobsGroupsResults); jobsGroups = jobsGroupsResults.map((item) => item.jobsGroup); jobInternalEnvs = jobsGroupsResults.map((item) => item.jobInternalEnv); } } if (resultsPerWorkflow) { // split jobs if (jobsGroups.length > resultsPerWorkflow) { const jobsGroupsCount = Math.ceil(jobsGroups.length / resultsPerWorkflow); return Array.from({ length: jobsGroupsCount }).map((_, outputsIndex) => { const theWorkflowData = getWorkflowData({ jobsGroups: jobsGroups.slice( outputsIndex * resultsPerWorkflow, (outputsIndex + 1) * resultsPerWorkflow ), jobInternalEnvs: jobInternalEnvs.slice( outputsIndex * resultsPerWorkflow, (outputsIndex + 1) * resultsPerWorkflow ), workflowData, }); return theWorkflowData; }); } else { const newWorkflowData = getWorkflowData({ jobsGroups: jobsGroups, jobInternalEnvs: jobInternalEnvs, workflowData, }); return [newWorkflowData]; } } else { const newWorkflowData = getWorkflowData({ jobsGroups: jobsGroups, jobInternalEnvs: jobInternalEnvs, workflowData, }); return [newWorkflowData]; } }; interface IInternalGetJobGruopsOptions { outputs: AnyObject[] | AnyObject; exportOutputs: boolean; outputsDir: string; outcome: OutcomeStatus; conclusion: ConclusionStatus; workflowData: IWorkflowData; workflowDataJobs: Record<string, AnyObject>; workflowRelativePath: string; triggerName: string; cwd: string; suffix?: string; } interface IInternalGetWorkflowDataOptions { workflowData: IWorkflowData; jobsGroups: { lastJobs: string[]; firstJobs: string[]; jobs: Record<string, AnyObject>; }[]; jobInternalEnvs: Record<string, string>[]; } function getWorkflowData( options: IInternalGetWorkflowDataOptions ): IWorkflowData { const { workflowData, jobsGroups, jobInternalEnvs } = options; const finalJobs: Record<string, AnyObject> = {}; jobsGroups.forEach((jobsGroup, index) => { const jobs = jobsGroup.jobs; const jobKeys = Object.keys(jobs); if (index > 0) { jobKeys.forEach((jobKey) => { const job = jobs[jobKey]; // inject envs job.env = { ...jobInternalEnvs[index], ...(job.env as Record<string, string>), }; if (jobsGroup.firstJobs.includes(jobKey)) { if (Array.isArray(job.needs)) { job.needs = (job.needs as string[]).concat( jobsGroups[index - 1].lastJobs ); } else { job.needs = jobsGroups[index - 1].lastJobs; } finalJobs[jobKey] = job; } else { finalJobs[jobKey] = job; } }); } else { jobKeys.forEach((jobKey) => { const job = jobs[jobKey]; // inject envs job.env = { ...jobInternalEnvs[index], ...(job.env as Record<string, string>), }; finalJobs[jobKey] = job; }); } }); // finalJobs name unique for act unique name const finalJobKeys = Object.keys(finalJobs); finalJobKeys.forEach((jobKey, index) => { const job = finalJobs[jobKey]; if (job.name) { job.name = `${job.name} ${index}`; } else { job.name = `job ${index}`; } finalJobs[jobKey] = job; }); const newWorkflowData = { ...workflowData }; newWorkflowData.on = ["push"]; newWorkflowData.jobs = finalJobs; return newWorkflowData; } async function getJobGroups( options: IInternalGetJobGruopsOptions ): Promise<{ jobsGroup: { lastJobs: string[]; firstJobs: string[]; jobs: Record<string, AnyObject>; }; jobInternalEnv: Record<string, string>; }> { const { outputs, exportOutputs, outputsDir, workflowData, workflowDataJobs, triggerName, outcome, conclusion, suffix, cwd, workflowRelativePath, } = options; const jobInternalEnv: Record<string, string> = {}; const context: Record<string, AnyObject> = { on: {}, }; const rawTriggers = getRawTriggers(workflowData); // add all triggers results to env for (let i = 0; i < rawTriggers.length; i++) { const rawTrigger = rawTriggers[i]; if (triggerName === rawTrigger.name) { // check is need export if (exportOutputs) { const filePath = getTriggerWebhookBasePath( workflowRelativePath, triggerName ).slice(1); const finalOutputsPath = path.resolve( cwd, outputsDir, `${filePath}${suffix ? "_" + suffix : ""}.json` ); const finalOutputsRelativePath = path.relative(cwd, finalOutputsPath); await fs.outputJSON(finalOutputsPath, outputs, { spaces: 2, }); jobInternalEnv[ `${TRIGGER_RESULT_ENV_PREFIX}${rawTrigger.name}` ] = JSON.stringify( { outcome: outcome, conclusion: conclusion, outputs: { path: finalOutputsRelativePath, }, }, null, 2 ); } else { jobInternalEnv[ `${TRIGGER_RESULT_ENV_PREFIX}${rawTrigger.name}` ] = JSON.stringify( { outcome: outcome, conclusion: conclusion, outputs: outputs, }, null, 2 ); } } else { jobInternalEnv[ `${TRIGGER_RESULT_ENV_PREFIX}${rawTrigger.name}` ] = JSON.stringify( { outcome: "skipped", conclusion: "skipped", outputs: {}, }, null, 2 ); } context.on[ rawTrigger.name ] = `(fromJSON(env.${TRIGGER_RESULT_ENV_PREFIX}${rawTrigger.name}))`; } // handle context expresstion let newJobs = {}; try { newJobs = mapObj( workflowDataJobs as Record<string, unknown>, (key, value) => { value = value as unknown; if (typeof value === "string" && key !== "if") { // if supported value = getTemplateStringByParentName(value, "on", context); } if (key === "if" && typeof value === "string") { if (value.trim().indexOf("${{") !== 0) { value = `\${{ ${value} }}`; } value = getTemplateStringByParentName(value as string, "on", context); } return [key, value]; }, { deep: true, } ); } catch (error) { throw new Error( `An error occurred when parsing workflow file ${workflowRelativePath}: ${error.toString()}` ); } let jobs = newJobs; if (suffix) { jobs = renameJobsBySuffix( newJobs as Record<string, AnyObject>, `_${suffix}` ); } // jobs id rename for merge const jobsDependences = getJobsDependences(jobs); const jobsGroup = { lastJobs: jobsDependences.lastJobs, firstJobs: jobsDependences.firstJobs, jobs: jobs, }; return { jobsGroup, jobInternalEnv }; } function arrify(thing: string | string[]): string[] { if (!thing) { return []; } if (!Array.isArray(thing)) { return [thing]; } return thing; } function negate(patterns: string | string[]): string[] { return arrify(patterns).map((pattern) => `!${pattern}`); }
the_stack
import { Component, SimpleChange, ViewChild, OnInit, Output, EventEmitter } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { AppConfigService, setupTestBed, DataRowEvent, ObjectDataRow, DataCellEvent, ObjectDataColumn } from '@alfresco/adf-core'; import { TaskListService } from '../services/tasklist.service'; import { TaskListComponent } from './task-list.component'; import { ProcessTestingModule } from '../../testing/process.testing.module'; import { fakeGlobalTask, fakeEmptyTask, paginatedTask, fakeColumnSchema, fakeCustomSchema } from '../../mock'; import { TranslateService, TranslateModule } from '@ngx-translate/core'; import { of, Subject } from 'rxjs'; declare let jasmine: any; describe('TaskListComponent', () => { let component: TaskListComponent; let fixture: ComponentFixture<TaskListComponent>; let appConfig: AppConfigService; let taskListService: TaskListService; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessTestingModule ] }); beforeEach(() => { appConfig = TestBed.inject(AppConfigService); appConfig.config.bpmHost = 'http://localhost:9876/bpm'; fixture = TestBed.createComponent(TaskListComponent); component = fixture.componentInstance; taskListService = TestBed.inject(TaskListService); appConfig.config = Object.assign(appConfig.config, { 'adf-task-list': { 'presets': { fakeCustomSchema } } }); }); beforeEach(() => { jasmine.Ajax.install(); }); afterEach(() => { jasmine.Ajax.uninstall(); fixture.destroy(); }); it('should display loading spinner', () => { component.isLoading = true; const spinner = fixture.debugElement.query(By.css('.mat-progress-spinner')); expect(spinner).toBeDefined(); }); it('should hide loading spinner upon loading complete', async () => { component.isLoading = true; fixture.detectChanges(); await fixture.whenStable(); let spinner = fixture.debugElement.query(By.css('.mat-progress-spinner')); expect(spinner).toBeDefined(); component.isLoading = false; fixture.detectChanges(); await fixture.whenStable(); spinner = fixture.debugElement.query(By.css('.mat-progress-spinner')); expect(spinner).toBeNull(); }); it('should use the default schemaColumn as default', () => { component.ngAfterContentInit(); expect(component.columns).toBeDefined(); expect(component.columns.length).toEqual(3); }); it('should use the custom schemaColumn from app.config.json', () => { component.presetColumn = 'fakeCustomSchema'; component.ngAfterContentInit(); fixture.detectChanges(); expect(component.columns.length).toEqual(2); expect(component.columns[0]).toEqual(new ObjectDataColumn(fakeCustomSchema[0])); expect(component.columns[1]).toEqual(new ObjectDataColumn(fakeCustomSchema[1])); }); it('should fetch custom schemaColumn when the input presetColumn is defined', () => { component.presetColumn = 'fakeCustomSchema'; fixture.detectChanges(); expect(component.columns).toBeDefined(); expect(component.columns.length).toEqual(2); }); it('should return an empty task list when no input parameters are passed', () => { component.ngAfterContentInit(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).toBeTruthy(); }); it('should return the filtered task list when the input parameters are passed', (done) => { const state = new SimpleChange(null, 'open', true); const processDefinitionKey = new SimpleChange(null, null, true); const assignment = new SimpleChange(null, 'fake-assignee', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); expect(component.rows[0]['description']).toEqual('descriptionFake1'); expect(component.rows[0]['category']).toEqual('categoryFake1'); expect(component.rows[0]['assignee'].id).toEqual(2); expect(component.rows[0]['assignee'].firstName).toEqual('firstNameFake1'); expect(component.rows[0]['assignee'].lastName).toEqual('lastNameFake1'); expect(component.rows[0][('assignee')].email).toEqual('emailFake1'); expect(component.rows[0]['created'].toISOString()).toEqual('2017-03-01T12:25:17.189Z'); expect(component.rows[0]['dueDate'].toISOString()).toEqual('2017-04-02T12:25:17.189Z'); expect(component.rows[0]['endDate'].toISOString()).toEqual('2017-05-03T12:25:31.129Z'); expect(component.rows[0]['duration']).toEqual(13940); expect(component.rows[0]['priority']).toEqual(50); expect(component.rows[0]['parentTaskId']).toEqual(1); expect(component.rows[0]['parentTaskName']).toEqual('parentTaskNameFake'); expect(component.rows[0]['processInstanceId']).toEqual(2511); expect(component.rows[0]['processInstanceName']).toEqual('processInstanceNameFake'); expect(component.rows[0]['processDefinitionId']).toEqual('myprocess:1:4'); expect(component.rows[0]['processDefinitionName']).toEqual('processDefinitionNameFake'); expect(component.rows[0]['processDefinitionDescription']).toEqual('processDefinitionDescriptionFake'); expect(component.rows[0]['processDefinitionKey']).toEqual('myprocess'); expect(component.rows[0]['processDefinitionCategory']).toEqual('http://www.activiti.org/processdef'); done(); }); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'processDefinitionKey': processDefinitionKey, 'assignment': assignment }); fixture.detectChanges(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should return the filtered task list by processDefinitionKey', (done) => { const state = new SimpleChange(null, 'open', true); /* cspell:disable-next-line */ const processDefinitionKey = new SimpleChange(null, 'fakeprocess', true); const assignment = new SimpleChange(null, 'fake-assignee', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); done(); }); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'processDefinitionKey': processDefinitionKey, 'assignment': assignment }); fixture.detectChanges(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should return the filtered task list by processInstanceId', (done) => { const state = new SimpleChange(null, 'open', true); const processInstanceId = new SimpleChange(null, 'fakeprocessId', true); const assignment = new SimpleChange(null, 'fake-assignee', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); expect(component.rows[0]['processInstanceId']).toEqual(2511); done(); }); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'processInstanceId': processInstanceId, 'assignment': assignment }); fixture.detectChanges(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should return the filtered task list by processDefinitionId', (done) => { const state = new SimpleChange(null, 'open', true); const processDefinitionId = new SimpleChange(null, 'fakeprocessDefinitionId', true); const assignment = new SimpleChange(null, 'fake-assignee', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); expect(component.rows[0]['processDefinitionId']).toEqual('myprocess:1:4'); done(); }); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'processDefinitionId': processDefinitionId, 'assignment': assignment }); fixture.detectChanges(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should return the filtered task list by created date', (done) => { const state = new SimpleChange(null, 'open', true); const afterDate = new SimpleChange(null, '28-02-2017', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); expect(component.rows[0]['processDefinitionId']).toEqual('myprocess:1:4'); done(); }); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'afterDate': afterDate }); fixture.detectChanges(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should return the filtered task list for all state', (done) => { const state = new SimpleChange(null, 'all', true); /* cspell:disable-next-line */ const processInstanceId = new SimpleChange(null, 'fakeprocessId', true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); expect(component.rows[0]['processInstanceId']).toEqual(2511); expect(component.rows[0]['endDate']).toBeDefined(); expect(component.rows[1]['name']).toEqual('No name'); expect(component.rows[1]['endDate']).toBeUndefined(); done(); }); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'processInstanceId': processInstanceId }); fixture.detectChanges(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should return a currentId null when the taskList is empty', () => { component.selectTask(null); expect(component.getCurrentId()).toBeNull(); }); it('should return selected id for the selected task', () => { component.rows = [ { id: '999', name: 'Fake-name' }, { id: '888', name: 'Fake-name-888' } ]; component.selectTask('888'); expect(component.rows).toBeDefined(); expect(component.currentInstanceId).toEqual('888'); }); it('should reload tasks when reload() is called', (done) => { component.state = 'open'; component.assignment = 'fake-assignee'; component.ngAfterContentInit(); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[0]['name']).toEqual('nameFake1'); done(); }); fixture.detectChanges(); component.reload(); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should emit row click event', (done) => { const row = new ObjectDataRow({ id: '999' }); const rowEvent = new DataRowEvent(row, null); component.rowClick.subscribe((taskId) => { expect(taskId).toEqual('999'); expect(component.getCurrentId()).toEqual('999'); done(); }); component.onRowClick(rowEvent); }); describe('component changes', () => { beforeEach(() => { component.rows = fakeGlobalTask.data; fixture.detectChanges(); }); it('should NOT reload the tasks if the loadingTaskId is the same of the current task', () => { spyOn(component, 'reload').and.stub(); component.currentInstanceId = '999'; component.rows = [{ id: '999', name: 'Fake-name' }]; const landingTaskId = '999'; const change = new SimpleChange(null, landingTaskId, true); component.ngOnChanges({ 'landingTaskId': change }); expect(component.reload).not.toHaveBeenCalled(); expect(component.rows.length).toEqual(1); }); it('should reload the tasks if the loadingTaskId is different from the current task', (done) => { component.currentInstanceId = '999'; component.rows = [{ id: '999', name: 'Fake-name' }]; const landingTaskId = '888'; const change = new SimpleChange(null, landingTaskId, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.rows.length).toEqual(2); done(); }); component.ngOnChanges({ 'landingTaskId': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should NOT reload the task list when no parameters changed', () => { component.rows = null; component.ngOnChanges({}); fixture.detectChanges(); expect(component.isListEmpty()).toBeTruthy(); }); it('should reload the list when the appId parameter changes', (done) => { const appId = '1'; const change = new SimpleChange(null, appId, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[1]['name']).toEqual('No name'); done(); }); component.ngOnChanges({ 'appId': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should reload the list when the processDefinitionKey parameter changes', (done) => { const processDefinitionKey = 'fakeprocess'; const change = new SimpleChange(null, processDefinitionKey, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[1]['name']).toEqual('No name'); done(); }); component.ngOnChanges({ 'processDefinitionKey': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should reload the list when the state parameter changes', (done) => { const state = 'open'; const change = new SimpleChange(null, state, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[1]['name']).toEqual('No name'); done(); }); component.ngOnChanges({ 'state': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should reload the list when the sort parameter changes', (done) => { const sort = 'desc'; const change = new SimpleChange(null, sort, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[1]['name']).toEqual('No name'); done(); }); component.ngOnChanges({ 'sort': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should reload the process list when the name parameter changes', (done) => { const name = 'FakeTaskName'; const change = new SimpleChange(null, name, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[1]['name']).toEqual('No name'); done(); }); component.ngOnChanges({ 'name': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); it('should reload the list when the assignment parameter changes', (done) => { const assignment = 'assignee'; const change = new SimpleChange(null, assignment, true); component.success.subscribe((res) => { expect(res).toBeDefined(); expect(component.rows).toBeDefined(); expect(component.isListEmpty()).not.toBeTruthy(); expect(component.rows.length).toEqual(2); expect(component.rows[1]['name']).toEqual('No name'); done(); }); component.ngOnChanges({ 'assignment': change }); jasmine.Ajax.requests.mostRecent().respondWith({ 'status': 200, contentType: 'application/json', responseText: JSON.stringify(fakeGlobalTask) }); }); }); it('should update the columns when presetColumn schema changes', () => { appConfig.config = Object.assign(appConfig.config, { 'adf-task-list': { 'presets': fakeColumnSchema } }); component.presetColumn = 'fakeCustomSchema'; component.ngAfterContentInit(); const initialColumnSchema = component.mergeJsonAndHtmlSchema(); expect(component.columns).toEqual(initialColumnSchema); component.presetColumn = 'fakeMyTasksSchema'; const presetColumnChange = new SimpleChange(null, 'fakeMyTasksSchema', false); component.ngOnChanges({ 'presetColumn': presetColumnChange }); const newColumnSchema = component.mergeJsonAndHtmlSchema(); const expectedColumn1 = new ObjectDataColumn(fakeColumnSchema.fakeMyTasksSchema[0]); const expectedColumn2 = new ObjectDataColumn(fakeColumnSchema.fakeMyTasksSchema[1]); expect(component.columns).toEqual(newColumnSchema); expect(initialColumnSchema).not.toEqual(newColumnSchema); expect(component.columns.length).toEqual(2); expect(component.columns[0]).toEqual(expectedColumn1); expect(component.columns[1]).toEqual(expectedColumn2); }); it('should show the updated list when pagination changes', async () => { spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask), of(paginatedTask)); const state = new SimpleChange(null, 'open', true); const processDefinitionKey = new SimpleChange(null, null, true); const assignment = new SimpleChange(null, 'fake-assignee', true); component.ngAfterContentInit(); component.ngOnChanges({ 'state': state, 'processDefinitionKey': processDefinitionKey, 'assignment': assignment }); fixture.detectChanges(); await fixture.whenStable(); let rows = Array.from(fixture.debugElement.nativeElement.querySelectorAll('.adf-datatable-body adf-datatable-row')); expect(rows.length).toEqual(2); component.updatePagination({ skipCount: 0, maxItems: 5 }); fixture.detectChanges(); await fixture.whenStable(); rows = Array.from(fixture.debugElement.nativeElement.querySelectorAll('.adf-datatable-body adf-datatable-row')); expect(rows.length).toEqual(5); expect(taskListService.findTasksByState).toHaveBeenCalledTimes(2); }); it('should be able to select all tasks when multi-selection is enabled', async () => { spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask)); const state = new SimpleChange(null, 'open', true); component.multiselect = true; component.ngOnChanges({ 'sort': state }); fixture.detectChanges(); await fixture.whenStable(); const selectAllCheckbox = fixture.nativeElement.querySelector('div[class*="adf-datatable-cell-header adf-datatable-checkbox"] .mat-checkbox-inner-container'); selectAllCheckbox.click(); fixture.detectChanges(); await fixture.whenStable(); expect(component.selectedInstances.length).toBe(2); expect(component.selectedInstances[0].obj.name).toBe('nameFake1'); expect(component.selectedInstances[1].obj.description).toBe('descriptionFake2'); selectAllCheckbox.click(); fixture.detectChanges(); await fixture.whenStable(); expect(component.selectedInstances.length).toBe(0); }); it('should be able to unselect a selected tasks using the checkbox', async () => { spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask)); const state = new SimpleChange(null, 'open', true); component.multiselect = true; component.ngOnChanges({ 'sort': state }); fixture.detectChanges(); await fixture.whenStable(); const selectTask1 = fixture.nativeElement.querySelector('[data-automation-id="datatable-row-0"] .mat-checkbox-inner-container'); const selectTask2 = fixture.nativeElement.querySelector('[data-automation-id="datatable-row-1"] .mat-checkbox-inner-container'); selectTask1.click(); selectTask1.click(); selectTask2.click(); fixture.detectChanges(); await fixture.whenStable(); let selectRow1 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-0"]'); let selectRow2 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-1"]'); expect(selectRow1).toBeDefined(); expect(selectRow2).toBeDefined(); expect(component.selectedInstances.length).toBe(2); selectTask2.click(); fixture.detectChanges(); await fixture.whenStable(); expect(component.selectedInstances.length).toBe(1); selectRow1 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-0"]'); selectRow2 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-1"]'); expect(selectRow1).toBeDefined(); expect(selectRow2).toBeNull(); }); it('should not be able to select different row when selection mode is set to NONE and multiselection is enabled', async () => { spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask)); const state = new SimpleChange(null, 'open', true); component.multiselect = true; component.selectionMode = 'none'; component.ngOnChanges({ 'sort': state }); fixture.detectChanges(); await fixture.whenStable(); const selectTask1 = fixture.nativeElement.querySelector('[data-automation-id="datatable-row-0"] .mat-checkbox-inner-container'); const selectTask2 = fixture.nativeElement.querySelector('[data-automation-id="datatable-row-1"] .mat-checkbox-inner-container'); selectTask1.click(); selectTask1.click(); selectTask2.click(); fixture.detectChanges(); await fixture.whenStable(); let selectRow1 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-0"]'); let selectRow2 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-1"]'); expect(selectRow1).toBeDefined(); expect(selectRow2).toBeDefined(); expect(component.selectedInstances.length).toBe(2); selectTask2.click(); fixture.detectChanges(); await fixture.whenStable(); expect(component.selectedInstances.length).toBe(1); selectRow1 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-0"]'); selectRow2 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-1"]'); expect(selectRow1).toBeDefined(); expect(selectRow2).toBeNull(); const selectTask2Row = fixture.nativeElement.querySelector('[data-automation-id="text_No name"]'); selectTask2Row.click(); selectRow1 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-0"]'); selectRow2 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-1"]'); expect(selectRow1).toBeDefined(); expect(selectRow2).toBeNull(); }); it('should select only one row when selection mode is set to SINGLE and multiselection is enabled', fakeAsync(() => { spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask)); const state = new SimpleChange(null, 'open', true); component.multiselect = true; component.selectionMode = 'single'; component.ngOnChanges({ 'sort': state }); fixture.detectChanges(); const selectTask1 = fixture.nativeElement.querySelector('[data-automation-id="datatable-row-0"] .mat-checkbox-inner-container'); const selectTask2 = fixture.nativeElement.querySelector('[data-automation-id="datatable-row-1"] .mat-checkbox-inner-container'); selectTask1.click(); selectTask1.click(); selectTask2.click(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(component.selectedInstances.length).toBe(2); const selectTask2Row = fixture.nativeElement.querySelector('[data-automation-id="text_No name"]'); selectTask2Row.click(); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(component.selectedInstances.length).toBe(1); const selectRow1 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-0"]'); const selectRow2 = fixture.nativeElement.querySelector('[class*="adf-is-selected"][data-automation-id="datatable-row-1"]'); expect(selectRow1).toBeNull(); expect(selectRow2).toBeDefined(); }); }); })); it('should change selected row after clicking on different row', async () => { spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask)); const state = new SimpleChange(null, 'open', true); component.ngOnChanges({ 'sort': state }); fixture.detectChanges(); await fixture.whenStable(); const selectTask1 = fixture.nativeElement.querySelector('[data-automation-id="text_nameFake1"]'); const selectTask2 = fixture.nativeElement.querySelector('[data-automation-id="text_No name"]'); selectTask1.click(); fixture.detectChanges(); await fixture.whenStable(); expect(component.currentInstanceId.toString()).toBe('14'); selectTask2.click(); fixture.detectChanges(); await fixture.whenStable(); expect(component.currentInstanceId.toString()).toBe('2'); }); }); @Component({ template: ` <adf-tasklist #taskList> <data-columns> <data-column key="name" title="ADF_TASK_LIST.PROPERTIES.NAME" class="full-width name-column"></data-column> <data-column key="created" title="ADF_TASK_LIST.PROPERTIES.CREATED" class="hidden"></data-column> <data-column key="startedBy" title="ADF_TASK_LIST.PROPERTIES.CREATED" class="desktop-only dw-dt-col-3 ellipsis-cell"> <ng-template let-entry="$implicit"> <div>{{entry.row?.obj?.startedBy | fullName}}</div> </ng-template> </data-column> </data-columns> </adf-tasklist>` }) class CustomTaskListComponent { @ViewChild(TaskListComponent) taskList: TaskListComponent; } describe('CustomTaskListComponent', () => { let fixture: ComponentFixture<CustomTaskListComponent>; let component: CustomTaskListComponent; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessTestingModule ], declarations: [CustomTaskListComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CustomTaskListComponent); fixture.detectChanges(); component = fixture.componentInstance; }); afterEach(() => { fixture.destroy(); }); it('should fetch custom schemaColumn from html', () => { fixture.detectChanges(); expect(component.taskList.columnList).toBeDefined(); expect(component.taskList.columns[0]['title']).toEqual('ADF_TASK_LIST.PROPERTIES.NAME'); expect(component.taskList.columns[1]['title']).toEqual('ADF_TASK_LIST.PROPERTIES.CREATED'); expect(component.taskList.columns.length).toEqual(3); }); }); @Component({ template: ` <adf-tasklist [appId]="1"> <adf-custom-empty-content-template> <p id="custom-id">CUSTOM EMPTY</p> </adf-custom-empty-content-template> </adf-tasklist> ` }) class EmptyTemplateComponent { } describe('Task List: Custom EmptyTemplateComponent', () => { let fixture: ComponentFixture<EmptyTemplateComponent>; let translateService: TranslateService; let taskListService: TaskListService; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessTestingModule ], declarations: [EmptyTemplateComponent] }); beforeEach(() => { translateService = TestBed.inject(TranslateService); taskListService = TestBed.inject(TaskListService); spyOn(translateService, 'get').and.callFake((key) => { return of(key); }); spyOn(taskListService, 'findTasksByState').and.returnValue(of(fakeEmptyTask)); fixture = TestBed.createComponent(EmptyTemplateComponent); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); }); it('should render the custom template', (done) => { fixture.detectChanges(); fixture.whenStable().then(() => { expect(fixture.debugElement.query(By.css('#custom-id'))).not.toBeNull(); expect(fixture.debugElement.query(By.css('.adf-empty-content'))).toBeNull(); done(); }); }); }); @Component({ template: ` <adf-tasklist [showContextMenu]="true" (showRowContextMenu)="onShowRowContextMenu($event)" #taskList> <data-columns> <data-column key="name" title="ADF_TASK_LIST.PROPERTIES.NAME" class="full-width name-column"></data-column> <data-column key="created" title="ADF_TASK_LIST.PROPERTIES.CREATED" class="hidden"></data-column> <data-column key="startedBy" title="ADF_TASK_LIST.PROPERTIES.CREATED" class="desktop-only dw-dt-col-3 ellipsis-cell"> <ng-template let-entry="$implicit"> <div>{{entry.row?.obj?.startedBy | fullName}}</div> </ng-template> </data-column> </data-columns> </adf-tasklist>` }) class TaskListContextMenuComponent implements OnInit { @Output() contextAction = new EventEmitter<any>(); private performAction$ = new Subject<any>(); ngOnInit() { this.performContextActions(); } onShowRowContextMenu(event: DataCellEvent) { event.value.actions = [ { data: event.value.row['obj'], model: { key: 'taskDetails', icon: 'open', title: 'View Task Details', visible: true }, subject: this.performAction$ }, { data: event.value.row['obj'], model: { key: 'cancel', icon: 'open', title: 'Cancel Process', visible: true }, subject: this.performAction$ } ]; } performContextActions() { this.performAction$ .subscribe((action: any) => { this.contextAction.emit(action.data); }); } } describe('TaskListContextMenuComponent', () => { let fixture: ComponentFixture<TaskListContextMenuComponent>; let customComponent: TaskListContextMenuComponent; let taskListService: TaskListService; let element: HTMLElement; setupTestBed({ imports: [ TranslateModule.forRoot(), ProcessTestingModule ], declarations: [ TaskListContextMenuComponent ] }); beforeEach(() => { fixture = TestBed.createComponent(TaskListContextMenuComponent); customComponent = fixture.componentInstance; element = fixture.nativeElement; taskListService = TestBed.inject(TaskListService); spyOn(taskListService, 'findTasksByState').and.returnValues(of(fakeGlobalTask)); fixture.detectChanges(); }); afterEach(() => { const event = new KeyboardEvent('keydown', { bubbles : true, cancelable : true, key : 'Escape' }); document.querySelector('.cdk-overlay-backdrop').dispatchEvent(event); fixture.detectChanges(); }); it('Should be able to show context menu on task list', async () => { const contextMenu = element.querySelector(`[data-automation-id="text_${fakeGlobalTask.data[0].name}"]`); const contextActionSpy = spyOn(customComponent.contextAction, 'emit').and.callThrough(); contextMenu.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true })); fixture.detectChanges(); await fixture.whenStable(); const contextActions = document.querySelectorAll('.mat-menu-item'); expect(contextActions.length).toBe(2); expect(contextActions[0]['disabled']).toBe(false, 'View Task Details action not enabled'); expect(contextActions[1]['disabled']).toBe(false, 'Cancel Task action not enabled'); contextActions[0].dispatchEvent(new Event('click')); fixture.detectChanges(); expect(contextActionSpy).toHaveBeenCalled(); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/imagesMappers"; import * as Parameters from "../models/parameters"; import { ComputeManagementClientContext } from "../computeManagementClientContext"; /** Class representing a Images. */ export class Images { private readonly client: ComputeManagementClientContext; /** * Create a Images. * @param {ComputeManagementClientContext} client Reference to the service client. */ constructor(client: ComputeManagementClientContext) { this.client = client; } /** * Create or update an image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param parameters Parameters supplied to the Create Image operation. * @param [options] The optional parameters * @returns Promise<Models.ImagesCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, imageName: string, parameters: Models.Image, options?: msRest.RequestOptionsBase): Promise<Models.ImagesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(resourceGroupName,imageName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ImagesCreateOrUpdateResponse>; } /** * Update an image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param parameters Parameters supplied to the Update Image operation. * @param [options] The optional parameters * @returns Promise<Models.ImagesUpdateResponse> */ update(resourceGroupName: string, imageName: string, parameters: Models.ImageUpdate, options?: msRest.RequestOptionsBase): Promise<Models.ImagesUpdateResponse> { return this.beginUpdate(resourceGroupName,imageName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ImagesUpdateResponse>; } /** * Deletes an Image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param [options] The optional parameters * @returns Promise<Models.ImagesDeleteMethodResponse> */ deleteMethod(resourceGroupName: string, imageName: string, options?: msRest.RequestOptionsBase): Promise<Models.ImagesDeleteMethodResponse> { return this.beginDeleteMethod(resourceGroupName,imageName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ImagesDeleteMethodResponse>; } /** * Gets an image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param [options] The optional parameters * @returns Promise<Models.ImagesGetResponse> */ get(resourceGroupName: string, imageName: string, options?: Models.ImagesGetOptionalParams): Promise<Models.ImagesGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param callback The callback */ get(resourceGroupName: string, imageName: string, callback: msRest.ServiceCallback<Models.Image>): void; /** * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, imageName: string, options: Models.ImagesGetOptionalParams, callback: msRest.ServiceCallback<Models.Image>): void; get(resourceGroupName: string, imageName: string, options?: Models.ImagesGetOptionalParams | msRest.ServiceCallback<Models.Image>, callback?: msRest.ServiceCallback<Models.Image>): Promise<Models.ImagesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, imageName, options }, getOperationSpec, callback) as Promise<Models.ImagesGetResponse>; } /** * Gets the list of images under a resource group. * @param resourceGroupName The name of the resource group. * @param [options] The optional parameters * @returns Promise<Models.ImagesListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ImagesListByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ImageListResult>): void; /** * @param resourceGroupName The name of the resource group. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ImageListResult>): void; listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ImageListResult>, callback?: msRest.ServiceCallback<Models.ImageListResult>): Promise<Models.ImagesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.ImagesListByResourceGroupResponse>; } /** * Gets the list of Images in the subscription. Use nextLink property in the response to get the * next page of Images. Do this till nextLink is null to fetch all the Images. * @param [options] The optional parameters * @returns Promise<Models.ImagesListResponse> */ list(options?: msRest.RequestOptionsBase): Promise<Models.ImagesListResponse>; /** * @param callback The callback */ list(callback: msRest.ServiceCallback<Models.ImageListResult>): void; /** * @param options The optional parameters * @param callback The callback */ list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ImageListResult>): void; list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ImageListResult>, callback?: msRest.ServiceCallback<Models.ImageListResult>): Promise<Models.ImagesListResponse> { return this.client.sendOperationRequest( { options }, listOperationSpec, callback) as Promise<Models.ImagesListResponse>; } /** * Create or update an image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param parameters Parameters supplied to the Create Image operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(resourceGroupName: string, imageName: string, parameters: Models.Image, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, imageName, parameters, options }, beginCreateOrUpdateOperationSpec, options); } /** * Update an image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param parameters Parameters supplied to the Update Image operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdate(resourceGroupName: string, imageName: string, parameters: Models.ImageUpdate, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, imageName, parameters, options }, beginUpdateOperationSpec, options); } /** * Deletes an Image. * @param resourceGroupName The name of the resource group. * @param imageName The name of the image. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, imageName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, imageName, options }, beginDeleteMethodOperationSpec, options); } /** * Gets the list of images under a resource group. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ImagesListByResourceGroupNextResponse> */ listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ImagesListByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ImageListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ImageListResult>): void; listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ImageListResult>, callback?: msRest.ServiceCallback<Models.ImageListResult>): Promise<Models.ImagesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByResourceGroupNextOperationSpec, callback) as Promise<Models.ImagesListByResourceGroupNextResponse>; } /** * Gets the list of Images in the subscription. Use nextLink property in the response to get the * next page of Images. Do this till nextLink is null to fetch all the Images. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ImagesListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ImagesListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ImageListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ImageListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ImageListResult>, callback?: msRest.ServiceCallback<Models.ImageListResult>): Promise<Models.ImagesListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.ImagesListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", urlParameters: [ Parameters.resourceGroupName, Parameters.imageName, Parameters.subscriptionId ], queryParameters: [ Parameters.expand0, Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Image }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ImageListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/images", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ImageListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", urlParameters: [ Parameters.resourceGroupName, Parameters.imageName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.Image, required: true } }, responses: { 200: { bodyMapper: Mappers.Image }, 201: { bodyMapper: Mappers.Image }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", urlParameters: [ Parameters.resourceGroupName, Parameters.imageName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ImageUpdate, required: true } }, responses: { 200: { bodyMapper: Mappers.Image }, 201: { bodyMapper: Mappers.Image }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}", urlParameters: [ Parameters.resourceGroupName, Parameters.imageName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.OperationStatusResponse }, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ImageListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ImageListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
namespace egret { /** * Easing function set. Different easing functions are used to make an animation proceed according to the corresponding equation * @see http://edn.egret.com/cn/index.php/article/index/id/53 Easing effect Demo * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 缓动函数集合,使用不同的缓动函数使得动画按照对应的方程进行 * @see http://edn.egret.com/cn/index.php/article/index/id/53 缓动效果演示 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ export class Ease { /** * @version Egret 2.4 * @platform Web,Native */ constructor() { egret.$error(1014); } /** * get.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static get(amount: number) { if (amount < -1) { amount = -1; } if (amount > 1) { amount = 1; } return function (t: number) { if (amount == 0) { return t; } if (amount < 0) { return t * (t * -amount + 1 + amount); } return t * ((2 - t) * amount + (1 - amount)); } } /** * get pow in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get pow in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getPowIn(pow: number) { return function (t: number) { return Math.pow(t, pow); } } /** * get pow out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get pow out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getPowOut(pow: number) { return function (t: number) { return 1 - Math.pow(1 - t, pow); } } /** * get pow in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get pow in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getPowInOut(pow: number) { return function (t: number) { if ((t *= 2) < 1) return 0.5 * Math.pow(t, pow); return 1 - 0.5 * Math.abs(Math.pow(2 - t, pow)); } } /** * quad in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quad in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quadIn = Ease.getPowIn(2); /** * quad out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quad out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quadOut = Ease.getPowOut(2); /** * quad in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quad in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quadInOut = Ease.getPowInOut(2); /** * cubic in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * cubic in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static cubicIn = Ease.getPowIn(3); /** * cubic out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * cubic out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static cubicOut = Ease.getPowOut(3); /** * cubic in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * cubic in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static cubicInOut = Ease.getPowInOut(3); /** * quart in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quart in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quartIn = Ease.getPowIn(4); /** * quart out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quart out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quartOut = Ease.getPowOut(4); /** * quart in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quart in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quartInOut = Ease.getPowInOut(4); /** * quint in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quint in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quintIn = Ease.getPowIn(5); /** * quint out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quint out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quintOut = Ease.getPowOut(5); /** * quint in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * quint in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static quintInOut = Ease.getPowInOut(5); /** * sine in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * sine in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static sineIn(t: number) { return 1 - Math.cos(t * Math.PI / 2); } /** * sine out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * sine out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static sineOut(t: number) { return Math.sin(t * Math.PI / 2); } /** * sine in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * sine in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static sineInOut(t: number) { return -0.5 * (Math.cos(Math.PI * t) - 1) } /** * get back in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get back in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getBackIn(amount: number) { return function (t: number) { return t * t * ((amount + 1) * t - amount); } } /** * back in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * back in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static backIn = Ease.getBackIn(1.7); /** * get back out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get back out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getBackOut(amount: number) { return function (t) { return (--t * t * ((amount + 1) * t + amount) + 1); } } /** * back out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * back out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static backOut = Ease.getBackOut(1.7); /** * get back in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get back in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getBackInOut(amount: number) { amount *= 1.525; return function (t: number) { if ((t *= 2) < 1) return 0.5 * (t * t * ((amount + 1) * t - amount)); return 0.5 * ((t -= 2) * t * ((amount + 1) * t + amount) + 2); } } /** * back in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * back in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static backInOut = Ease.getBackInOut(1.7); /** * circ in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * circ in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static circIn(t: number) { return -(Math.sqrt(1 - t * t) - 1); } /** * circ out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * circ out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static circOut(t: number) { return Math.sqrt(1 - (--t) * t); } /** * circ in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * circ in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static circInOut(t: number) { if ((t *= 2) < 1) { return -0.5 * (Math.sqrt(1 - t * t) - 1); } return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); } /** * bounce in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * bounce in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static bounceIn(t: number) { return 1 - Ease.bounceOut(1 - t); } /** * bounce out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * bounce out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static bounceOut(t: number) { if (t < 1 / 2.75) { return (7.5625 * t * t); } else if (t < 2 / 2.75) { return (7.5625 * (t -= 1.5 / 2.75) * t + 0.75); } else if (t < 2.5 / 2.75) { return (7.5625 * (t -= 2.25 / 2.75) * t + 0.9375); } else { return (7.5625 * (t -= 2.625 / 2.75) * t + 0.984375); } } /** * bounce in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * bounce in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static bounceInOut(t: number) { if (t < 0.5) return Ease.bounceIn(t * 2) * .5; return Ease.bounceOut(t * 2 - 1) * 0.5 + 0.5; } /** * get elastic in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get elastic in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getElasticIn(amplitude: number, period: number) { let pi2 = Math.PI * 2; return function (t: number) { if (t == 0 || t == 1) return t; let s = period / pi2 * Math.asin(1 / amplitude); return -(amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period)); } } /** * elastic in.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * elastic in。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static elasticIn = Ease.getElasticIn(1, 0.3); /** * get elastic out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get elastic out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getElasticOut(amplitude: number, period: number) { let pi2 = Math.PI * 2; return function (t: number) { if (t == 0 || t == 1) return t; let s = period / pi2 * Math.asin(1 / amplitude); return (amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1); } } /** * elastic out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * elastic out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static elasticOut = Ease.getElasticOut(1, 0.3); /** * get elastic in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * get elastic in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static getElasticInOut(amplitude: number, period: number) { let pi2 = Math.PI * 2; return function (t: number) { let s = period / pi2 * Math.asin(1 / amplitude); if ((t *= 2) < 1) return -0.5 * (amplitude * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * pi2 / period)); return amplitude * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * pi2 / period) * 0.5 + 1; } } /** * elastic in out.See example. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * elastic in out。请查看示例 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static elasticInOut = Ease.getElasticInOut(1, 0.3 * 1.5); } }
the_stack
import { AffectedTaskOccurrence } from "../../../Enumerations/AffectedTaskOccurrence"; import { ArchiveTag } from "../../../ComplexProperties/ArchiveTag"; import { DeleteMode } from "../../../Enumerations/DeleteMode"; import { EffectiveRights } from "../../../Enumerations/EffectiveRights"; import { EwsLogging } from "../../EwsLogging"; import { ExchangeService } from "../../ExchangeService"; import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion"; import { ExtendedPropertyCollection } from "../../../ComplexProperties/ExtendedPropertyCollection"; import { ExtendedPropertyDefinition } from "../../../PropertyDefinitions/ExtendedPropertyDefinition"; import { FindFoldersResults } from "../../../Search/FindFoldersResults"; import { FindItemResponse } from "../../Responses/FindItemResponse"; import { FindItemsResults } from "../../../Search/FindItemsResults"; import { FolderId } from "../../../ComplexProperties/FolderId"; import { FolderPermissionCollection } from "../../../ComplexProperties/FolderPermissionCollection"; import { FolderView } from "../../../Search/FolderView"; import { GroupedFindItemsResults } from "../../../Search/GroupedFindItemsResults"; import { Grouping } from "../../../Search/Grouping"; import { Item } from "../Items/Item"; import { ItemView } from "../../../Search/ItemView"; import { ManagedFolderInformation } from "../../../ComplexProperties/ManagedFolderInformation"; import { PolicyTag } from "../../../ComplexProperties/PolicyTag"; import { Promise } from "../../../Promise"; import { PropertyDefinition } from "../../../PropertyDefinitions/PropertyDefinition"; import { PropertySet } from "../../PropertySet"; import { Schemas } from "../Schemas/Schemas"; import { SearchFilter } from "../../../Search/Filters/SearchFilter"; import { SendCancellationsMode } from "../../../Enumerations/SendCancellationsMode"; import { ServiceErrorHandling } from "../../../Enumerations/ServiceErrorHandling"; import { ServiceObjectSchema } from "../Schemas/ServiceObjectSchema"; import { ServiceResponse } from "../../Responses/ServiceResponse"; import { ServiceResponseCollection } from "../../Responses/ServiceResponseCollection"; import { ViewBase } from "../../../Search/ViewBase"; import { WellKnownFolderName } from "../../../Enumerations/WellKnownFolderName"; import { XmlElementNames } from "../../XmlElementNames"; import { ServiceObject } from "../ServiceObject"; export class Folder extends ServiceObject { /** * Gets the Id of the folder. * */ get Id(): FolderId { return <FolderId>this.PropertyBag._getItem(this.GetIdPropertyDefinition()); } /** * Gets the Id of this folder's parent folder. * */ get ParentFolderId(): FolderId { return <FolderId>this.PropertyBag._getItem(Schemas.FolderSchema.ParentFolderId); } /** * Gets the number of child folders this folder has. * */ get ChildFolderCount(): number { return <number>this.PropertyBag._getItem(Schemas.FolderSchema.ChildFolderCount); } /** * Gets or sets the display name of the folder. * */ get DisplayName(): string { return <string>this.PropertyBag._getItem(Schemas.FolderSchema.DisplayName); } set DisplayName(value: string) { this.PropertyBag._setItem(Schemas.FolderSchema.DisplayName, value); } /** * Gets or sets the custom class name of this folder. * */ get FolderClass(): string { return <string>this.PropertyBag._getItem(Schemas.FolderSchema.FolderClass); } set FolderClass(value: string) { this.PropertyBag._setItem(Schemas.FolderSchema.FolderClass, value); } /** * Gets the total number of items contained in the folder. * */ get TotalCount(): number { return <number>this.PropertyBag._getItem(Schemas.FolderSchema.TotalCount); } /** * Gets a list of extended properties associated with the folder. **Unstable Need testing** * */ get ExtendedProperties(): ExtendedPropertyCollection { return <ExtendedPropertyCollection>this.PropertyBag._getItem(ServiceObjectSchema.ExtendedProperties); } /** * Gets the Email Lifecycle Management (ELC) information associated with the folder. * */ get ManagedFolderInformation(): ManagedFolderInformation { return <ManagedFolderInformation>this.PropertyBag._getItem(Schemas.FolderSchema.ManagedFolderInformation); } /** * Gets a value indicating the effective rights the current authenticated user has on the folder. * */ get EffectiveRights(): EffectiveRights { return <EffectiveRights>this.PropertyBag._getItem(Schemas.FolderSchema.EffectiveRights); } /** * Gets a list of permissions for the folder. * */ get Permissions(): FolderPermissionCollection { return <FolderPermissionCollection>this.PropertyBag._getItem(Schemas.FolderSchema.Permissions); } /** * Gets the number of unread items in the folder. * */ get UnreadCount(): number { return <number>this.PropertyBag._getItem(Schemas.FolderSchema.UnreadCount); } /** * Gets or sets the policy tag. * */ get PolicyTag(): PolicyTag { return <PolicyTag>this.PropertyBag._getItem(Schemas.FolderSchema.PolicyTag); } set PolicyTag(value: PolicyTag) { this.PropertyBag._setItem(Schemas.FolderSchema.PolicyTag, value); } /** * Gets or sets the archive tag. * */ get ArchiveTag(): ArchiveTag { return <ArchiveTag>this.PropertyBag._getItem(Schemas.FolderSchema.ArchiveTag); } set ArchiveTag(value) { this.PropertyBag._setItem(Schemas.FolderSchema.ArchiveTag, value); } /** * Gets the well known name of this folder, if any, as a string. * **value** - The well known name of this folder as a string, or null if this folder isn't a well known folder. * */ get WellKnownFolderNameAsString(): string { return WellKnownFolderName[<WellKnownFolderName>this.PropertyBag._getItem(Schemas.FolderSchema.WellKnownFolderName)]; } /** * Gets the well known name of this folder, if any. * **value** - The well known name of this folder, or null if this folder isn't a well known folder. * */ get WellKnownFolderName(): WellKnownFolderName { return WellKnownFolderName[this.WellKnownFolderNameAsString] || null; } /** * _FolderTYpe -> type of folder, use to avoid folder type detection using instanceof. some cases it has circular loop in nodejs/requirejs */ //get _FolderType(): string { return XmlElementNames.Folder; } /** * Initializes an unsaved local instance of **Folder**. To bind to an existing folder, use Folder.Bind() instead. * * @param {ExchangeService} service EWS service to which this object belongs. */ constructor(service: ExchangeService) { super(service); } /** * Binds to an existing folder, whatever its actual type is, and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the folder. * @param {FolderId} id The Id of the folder to bind to. * @return {Promise<Folder>} A Folder instance representing the folder corresponding to the specified Id :Promise. */ static Bind(service: ExchangeService, id: FolderId): Promise<Folder>; /** * Binds to an existing folder, whatever its actual type is, and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the folder. * @param {WellKnownFolderName} name The name of the folder to bind to. * @return {Promise<Folder>} A Folder instance representing the folder corresponding to the specified name :Promise. */ static Bind(service: ExchangeService, name: WellKnownFolderName): Promise<Folder>; /** * Binds to an existing folder, whatever its actual type is, and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the folder. * @param {FolderId} id The Id of the folder to bind to. * @param {PropertySet} propertySet The set of properties to load. * @return {Promise<Folder>} A Folder instance representing the folder corresponding to the specified Id :Promise. */ static Bind(service: ExchangeService, id: FolderId, propertySet: PropertySet): Promise<Folder>; /** * Binds to an existing folder, whatever its actual type is, and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the folder. * @param {WellKnownFolderName} name The name of the folder to bind to. * @param {PropertySet} propertySet The set of properties to load. * @return {Promise<Folder>} A Folder instance representing the folder corresponding to the specified name :Promise. */ static Bind(service: ExchangeService, name: WellKnownFolderName, propertySet: PropertySet): Promise<Folder>; static Bind(service: ExchangeService, idOrName: FolderId | WellKnownFolderName, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<Folder> { if (idOrName instanceof FolderId) { return service.BindToFolder(idOrName, propertySet); } else if (typeof idOrName === 'number') { return service.BindToFolder(new FolderId(idOrName), propertySet); } EwsLogging.Assert(false, "Folder.Bind", "unknown paramete type"); throw new Error("unknow parameter type. this should not be reached"); } /** * Copies this folder into the specified folder. Calling this method results in a call to EWS. * * @param {WellKnownFolderName} destinationFolderName The name of the folder in which to copy this folder. * @return {Promise<Folder>} A Folder representing the copy of this folder :Promise. */ Copy(destinationFolderName: WellKnownFolderName): Promise<Folder>; /** * Copies this folder into a specific folder. Calling this method results in a call to EWS. * * @param {FolderId} destinationFolderId The Id of the folder in which to copy this folder. * @return {Promise<Folder>} A Folder representing the copy of this folder :Promise. */ Copy(destinationFolderId: FolderId): Promise<Folder>; Copy(destinationFolderIdOrName: FolderId | WellKnownFolderName): Promise<Folder> { this.ThrowIfThisIsNew(); //EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId"); if (typeof destinationFolderIdOrName === 'undefined') { EwsLogging.Assert(false, "Folder.Copy", "unknown paramete type"); throw new Error("unknow parameter type. this should not be reached"); } var folderId: FolderId = <FolderId>destinationFolderIdOrName; if (typeof destinationFolderIdOrName === 'number') folderId = new FolderId(destinationFolderIdOrName); return this.Service.CopyFolder(this.Id, folderId); } /** * Deletes the folder. Calling this method results in a call to EWS. * * @param {DeleteMode} deleteMode Deletion mode. */ Delete(deleteMode: DeleteMode): Promise<void> { return this.InternalDelete(deleteMode, null, null); } /** * Empties the folder. Calling this method results in a call to EWS. * * @param {DeleteMode} deleteMode The deletion mode. * @param {boolean} deleteSubFolders Indicates whether sub-folders should also be deleted. */ Empty(deleteMode: DeleteMode, deleteSubFolders: boolean): Promise<void> { this.ThrowIfThisIsNew(); return this.Service.EmptyFolder( this.Id, deleteMode, deleteSubFolders); } /** * Obtains a list of folders by searching the sub-folders of this folder. Calling this method results in a call to EWS. * * @param {FolderView} view The view controlling the number of folders returned. * @return {Promise<FindFoldersResults>} An object representing the results of the search operation :Promise. */ FindFolders(view: FolderView): Promise<FindFoldersResults>; /** * Obtains a list of folders by searching the sub-folders of this folder. Calling this method results in a call to EWS. * * @param {SearchFilter} searchFilter The search filter. Available search filter classes include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection * @param {FolderView} view The view controlling the number of folders returned. * @return {Promise<FindFoldersResults>} An object representing the results of the search operation :Promise. */ FindFolders(searchFilter: SearchFilter, view: FolderView): Promise<FindFoldersResults>; FindFolders(viewOrSearchFilter: FolderView | SearchFilter, view?: FolderView): Promise<FindFoldersResults> { this.ThrowIfThisIsNew(); //todo: better argument check with ewsutilities var argsLength = arguments.length; if (argsLength < 1 && argsLength > 2) { throw new Error("invalid arguments, check documentation and try again."); } if (viewOrSearchFilter instanceof FolderView) { return this.Service.FindFolders(this.Id, viewOrSearchFilter); } else if (viewOrSearchFilter instanceof SearchFilter) { if (typeof view === 'undefined' || !(view instanceof FolderView)) { throw new Error("Folder.ts - FindFolders - incorrect uses of parameters at 2nd position, must be FolderView"); } return this.Service.FindFolders(this.Id, viewOrSearchFilter, view); } else { throw new Error("Folder.ts - FindFolders - incorrect uses of parameters at 1st position, must be FolderView or SearchFilter"); } } /** * Obtains a list of items by searching the contents of this folder. Calling this method results in a call to EWS. * * @param {ItemView} view The view controlling the number of items returned. * @return {Promise<FindItemsResults<Item>>} An object representing the results of the search operation :Promise. */ FindItems(view: ItemView): Promise<FindItemsResults<Item>>; /** * Obtains a grouped list of items by searching the contents of this folder. Calling this method results in a call to EWS. * * @param {ItemView} view The view controlling the number of items returned. * @param {Grouping} groupBy The grouping criteria. * @return {Promise<GroupedFindItemsResults<Item>>} A collection of grouped items representing the contents of this folder :Promise. */ FindItems(view: ItemView, groupBy: Grouping): Promise<GroupedFindItemsResults<Item>>; /** * Obtains a list of items by searching the contents of this folder. Calling this method results in a call to EWS. * * @param {string} queryString query string to be used for indexed search * @param {ItemView} view The view controlling the number of items returned. * @return {Promise<FindItemsResults<Item>>} An object representing the results of the search operation :Promise. */ FindItems(queryString: string, view: ItemView): Promise<FindItemsResults<Item>>; /** * Obtains a list of items by searching the contents of this folder. Calling this method results in a call to EWS. * * @param {SearchFilter} searchFilter The search filter. Available search filter classes include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection * @param {ItemView} view The view controlling the number of items returned. * @return {Promise<FindItemsResults<Item>>} An object representing the results of the search operation :Promise. */ FindItems(searchFilter: SearchFilter, view: ItemView): Promise<FindItemsResults<Item>>; /** * Obtains a grouped list of items by searching the contents of this folder. Calling this method results in a call to EWS. * * @param {string} queryString Query string to be used for indexed search * @param {ItemView} view The view controlling the number of items returned. * @param {Grouping} groupBy The grouping criteria. * @return {Promise<GroupedFindItemsResults<Item>>} A collection of grouped items representing the contents of this folder :Promise. */ FindItems(queryString: string, view: ItemView, groupBy: Grouping): Promise<GroupedFindItemsResults<Item>>; /** * Obtains a grouped list of items by searching the contents of this folder. Calling this method results in a call to EWS. * * @param {SearchFilter} searchFilter The search filter. Available search filter classes include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection * @param {ItemView} view The view controlling the number of items returned. * @param {Grouping} groupBy The grouping criteria. * @return {Promise<GroupedFindItemsResults<Item>>} A collection of grouped items representing the contents of this folder :Promise. */ FindItems(searchFilter: SearchFilter, view: ItemView, groupBy: Grouping): Promise<GroupedFindItemsResults<Item>>; FindItems( viewQueryStringOrSearchFilter: string | ItemView | SearchFilter, viewOrGroupBy?: ItemView | Grouping, groupBy?: Grouping ): Promise<FindItemsResults<Item> | GroupedFindItemsResults<Item>> { var argsLength = arguments.length; if (argsLength < 1 && argsLength > 3) { throw new Error("invalid arguments, check documentation and try again."); } //todo: better argument check with ewsutilities //EwsUtilities.ValidateParam(groupBy, "groupBy"); //EwsUtilities.ValidateParamAllowNull(searchFilter, "searchFilter"); //EwsUtilities.ValidateParamAllowNull(queryString, "queryString"); //position 1 - viewQueryStringOrSearchFilter var queryString: string = null; var searchFilter: SearchFilter = null; var view: ItemView = null; if (typeof viewQueryStringOrSearchFilter === 'string') { queryString = viewQueryStringOrSearchFilter; } else if (viewQueryStringOrSearchFilter instanceof SearchFilter) { searchFilter = viewQueryStringOrSearchFilter; } else if (viewQueryStringOrSearchFilter instanceof ViewBase) { view = viewQueryStringOrSearchFilter; } else { throw new Error("Folder.ts - FindItems - incorrect uses of parameters at 1st position, must be string, Itemview or SearchFilter"); } var groupResultBy: Grouping = null; var isGroupped: boolean = false; // to resturn GroupedFindItemsResults<Item> //position 2 - viewOrGroupBy if (argsLength >= 2) { if (viewOrGroupBy instanceof Grouping) { if (!(viewQueryStringOrSearchFilter instanceof ItemView)) { throw new Error("Folder.ts - FindItems with " + argsLength + " parameters - incorrect uses of parameter at 1nd position, it must be Itemview when using Grouping at 2nd place"); } groupResultBy = viewOrGroupBy; isGroupped = true; } else if (viewOrGroupBy instanceof ItemView) { view = viewOrGroupBy; } else { throw new Error("ExchangeService.ts - FindItems with " + argsLength + " parameters - incorrect uses of parameter at 2nd position, must be Itemsview or Grouping"); } } //position 3 - groupBy if (argsLength === 3) { if (!(viewOrGroupBy instanceof ItemView)) { throw new Error("Folder.ts - FindItems with " + argsLength + " parameters - incorrect uses of parameter at 1nd position, it must be Itemview when using Grouping at 3rd place"); } groupResultBy = <Grouping>groupBy; isGroupped = true; } return this.InternalFindItems<Item>( searchFilter || queryString, view, groupResultBy /* groupBy */) .then((res) => { if (isGroupped) { return res.__thisIndexer(0).GroupedFindResults; } return res.__thisIndexer(0).Results; }); } /** * @internal Gets the element name of item in XML * * @return {string} name of elelment */ GetXmlElementName(): string { return XmlElementNames.Folder; } /** * @internal Gets the name of the change XML element. * * @return {string} XML element name, */ GetChangeXmlElementName(): string { return XmlElementNames.FolderChange; } /** * @internal Gets the name of the delete field XML element. * * @return {string} XML element name, */ GetDeleteFieldXmlElementName(): string { return XmlElementNames.DeleteFolderField; } /** * @internal Gets a list of extended properties defined on this object. * * @return {ExtendedPropertyCollection} Extended properties collection. */ GetExtendedProperties(): ExtendedPropertyCollection { return this.ExtendedProperties; } /** * @internal Get the property definition for the Id property. * * @return {PropertyDefinition} A PropertyDefinition instance. */ GetIdPropertyDefinition(): PropertyDefinition { return Schemas.FolderSchema.Id; } /** * @internal Gets the minimum required server version. * * @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported. */ GetMinimumRequiredServerVersion(): ExchangeVersion { return ExchangeVersion.Exchange2007_SP1; } /** * @internal Internal method to return the schema associated with this type of object. * * @return {ServiceObjectSchema} The schema associated with this type of object. */ GetSchema(): ServiceObjectSchema { return Schemas.FolderSchema.Instance; } /** * @internal Gets the name of the set field XML element. * * @return {string} XML element name, */ GetSetFieldXmlElementName(): string { return XmlElementNames.SetFolderField; } /** * @internal Deletes the object. * * @param {DeleteMode} deleteMode The deletion mode. * @param {SendCancellationsMode} sendCancellationsMode Indicates whether meeting cancellation messages should be sent. * @param {AffectedTaskOccurrence} affectedTaskOccurrences Indicate which occurrence of a recurring task should be deleted. */ InternalDelete(deleteMode: DeleteMode, sendCancellationsMode?: SendCancellationsMode, affectedTaskOccurrences?: AffectedTaskOccurrence): Promise<void> { this.ThrowIfThisIsNew(); return this.Service.DeleteFolder(this.Id, deleteMode); } /** * @internal Find items. * * @param {string} queryString Query string to be used for indexed search * @param {ViewBase} view The view controlling the number of items returned. * @param {Grouping} groupBy The group by. * @return {Promise<ServiceResponseCollection<FindItemResponse<TItem>>>} FindItems response collection :Promise. */ InternalFindItems<TItem extends Item>(queryString: string, view: ViewBase, groupBy: Grouping): Promise<ServiceResponseCollection<FindItemResponse<TItem>>>; /** * @internal Find items. * * @param {SearchFilter} searchFilter The search filter. Available search filter classes include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and SearchFilter.SearchFilterCollection * @param {ViewBase} view The view controlling the number of items returned. * @param {Grouping} groupBy The group by. * @return {Promise<ServiceResponseCollection<FindItemResponse<TItem>>>} FindItems response collection :Promise. */ InternalFindItems<TItem extends Item>(searchFilter: SearchFilter, view: ViewBase, groupBy: Grouping): Promise<ServiceResponseCollection<FindItemResponse<TItem>>>; /** * ### ~~*shim used internally to minimize code flow logic from calling functions*~~ */ InternalFindItems<TItem extends Item>(searchFilterOrQueryString: SearchFilter | string, view: ViewBase, groupBy: Grouping): Promise<ServiceResponseCollection<FindItemResponse<TItem>>>; InternalFindItems<TItem extends Item>(searchFilterOrQueryString: SearchFilter | string, view: ViewBase, groupBy: Grouping): Promise<ServiceResponseCollection<FindItemResponse<TItem>>> { this.ThrowIfThisIsNew(); var searchFilter: SearchFilter = null; var queryString = null; if (searchFilterOrQueryString instanceof SearchFilter) { searchFilter = searchFilterOrQueryString; } else if (typeof searchFilterOrQueryString === 'string') { queryString = searchFilterOrQueryString; } //debug: //todo: //ref: verify if querystring is null return this.Service.FindItems<TItem>( [this.Id], // FolderId[] searchFilter, /* searchFilter */ queryString, /* queryString */ view, groupBy, ServiceErrorHandling.ThrowOnError); } /** * @internal Loads the specified set of properties on the object. * * @param {PropertySet} propertySet The properties to load. */ InternalLoad(propertySet: PropertySet): Promise<void> { this.ThrowIfThisIsNew(); return this.Service.LoadPropertiesForFolder(this, propertySet); } /** * Marks all items in folder as read. Calling this method results in a call to EWS. * * @param {boolean} suppressReadReceipts If true, suppress sending read receipts for items. */ MarkAllItemsAsRead(suppressReadReceipts: boolean): Promise<void> { this.ThrowIfThisIsNew(); return this.Service.MarkAllItemsAsRead( this.Id, true, suppressReadReceipts); } /** * Marks all items in folder as read. Calling this method results in a call to EWS. * * @param {boolean} suppressReadReceipts If true, suppress sending read receipts for items. */ MarkAllItemsAsUnread(suppressReadReceipts: boolean): Promise<void> { this.ThrowIfThisIsNew(); return this.Service.MarkAllItemsAsRead( this.Id, false, suppressReadReceipts); } /** * Moves this folder to the specified folder. Calling this method results in a call to EWS. * * @param {WellKnownFolderName} destinationFolderName The name of the folder in which to move this folder. * @return {Promise<Folder>} A new folder representing this folder in its new location. After Move completes, this folder does not exist anymore :Promise. */ Move(destinationFolderName: WellKnownFolderName): Promise<Folder>; /** * Moves this folder to a specific folder. Calling this method results in a call to EWS. * * @param {FolderId} destinationFolderId The Id of the folder in which to move this folder. * @return {Promise<Folder>} A new folder representing this folder in its new location. After Move completes, this folder does not exist anymore :Promise. */ Move(destinationFolderId: FolderId): Promise<Folder>; Move(destinationFolderIdOrName: FolderId | WellKnownFolderName): Promise<Folder> { this.ThrowIfThisIsNew(); if (typeof destinationFolderIdOrName === 'undefined') { EwsLogging.Assert(false, "Folder.Move", "unknown paramete type"); throw new Error("unknow parameter type. this should not be reached"); } //EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId"); var folderId: FolderId = <FolderId>destinationFolderIdOrName; if (typeof destinationFolderIdOrName === 'number') folderId = new FolderId(destinationFolderIdOrName); return this.Service.MoveFolder(this.Id, folderId); } /** * Removes an extended property. * * @param {ExtendedPropertyDefinition} extendedPropertyDefinition The extended property definition. * @return {boolean} True if property was removed. */ RemoveExtendedProperty(extendedPropertyDefinition: ExtendedPropertyDefinition): boolean { return this.ExtendedProperties.RemoveExtendedProperty(extendedPropertyDefinition); } /** * Saves this folder in a specific folder. Calling this method results in a call to EWS. * * @param {WellKnownFolderName} parentFolderName The name of the folder in which to save this folder. */ Save(parentFolderName: WellKnownFolderName): Promise<void>; /** * Saves this folder in a specific folder. Calling this method results in a call to EWS. * * @param {FolderId} parentFolderId The Id of the folder in which to save this folder. */ Save(parentFolderId: FolderId): Promise<void>; Save(parentFolderIdOrname: FolderId | WellKnownFolderName): Promise<void> { this.ThrowIfThisIsNotNew(); if (typeof parentFolderIdOrname === 'undefined') { EwsLogging.Assert(false, "Folder.Save", "unknown paramete type"); throw new Error("unknow parameter type. this should not be reached"); } //EwsUtilities.ValidateParam(parentFolderId, "parentFolderId"); var folderId: FolderId = <FolderId>parentFolderIdOrname; if (typeof parentFolderIdOrname === 'number') folderId = new FolderId(parentFolderIdOrname); if (this.IsDirty) { return this.Service.CreateFolder(this, folderId); } else return null; } /** * Sets the extended property. * * @param {ExtendedPropertyDefinition} extendedPropertyDefinition The extended property definition. * @param {any} value The value. */ SetExtendedProperty(extendedPropertyDefinition: ExtendedPropertyDefinition, value: any): void { this.ExtendedProperties.SetExtendedProperty(extendedPropertyDefinition, value); } /** * Applies the local changes that have been made to this folder. Calling this method results in a call to EWS. * */ Update(): Promise<void> { if (this.IsDirty) { if (this.PropertyBag.GetIsUpdateCallNecessary()) { return this.Service.UpdateFolder(this); } } return undefined; } /** * @internal Validates this instance. * */ Validate(): void { super.Validate(); // Validate folder permissions if (this.PropertyBag.Contains(Schemas.FolderSchema.Permissions)) { this.Permissions.Validate(); } } }
the_stack
import { Camera, ArrayCamera, PerspectiveCamera, Vector3, Quaternion, Matrix4, Group, Mesh, RingBufferGeometry, MeshBasicMaterial, BufferGeometry, RawShaderMaterial, GreaterDepth, CircleBufferGeometry, MathUtils } from "three"; import * as createTextGeometry from "three-bmfont-text"; import * as createTextShader from "three-bmfont-text/shaders/msdf"; import { customElement, html } from "@ff/ui/CustomElement"; import "@ff/ui/Button"; import GPUPicker from "@ff/three/GPUPicker"; import AnnotationSprite, { Annotation, AnnotationElement } from "./AnnotationSprite"; import UniversalCamera from "@ff/three/UniversalCamera"; import AnnotationFactory from "./AnnotationFactory"; import CVAssetReader from "client/components/CVAssetReader"; //////////////////////////////////////////////////////////////////////////////// const _vec3a = new Vector3(); const _vec3b = new Vector3(); const _quat1 = new Quaternion(); const _mat4 = new Matrix4(); export default class CircleSprite extends AnnotationSprite { static readonly typeName: string = "Circle"; private _isExpanded = false; protected static readonly behindOpacity = 0.2; protected offset: Group; protected anchorMesh: Mesh; protected ringMesh: Mesh; protected ringGeometry: RingBufferGeometry; protected ringMaterialA: MeshBasicMaterial; protected ringMaterialB: MeshBasicMaterial; protected markerGeometry: BufferGeometry; protected markerMaterialA: RawShaderMaterial; protected markerMaterialB: RawShaderMaterial; protected markerA: Mesh; protected markerB: Mesh; // Temporary until annotation scale implementation is resolved xrScale: number = 1.0; isWebGL2: boolean = false; constructor(annotation: Annotation, assetReader: CVAssetReader) { super(annotation); this._isExpanded = annotation.data.expanded; this.offset = new Group(); this.offset.matrixAutoUpdate = false; this.add(this.offset); this.ringGeometry = new RingBufferGeometry(0.45, 0.5, 32); this.ringMaterialA = new MeshBasicMaterial(); this.ringMaterialB = new MeshBasicMaterial({ depthFunc: GreaterDepth, depthWrite: false, opacity: CircleSprite.behindOpacity, transparent: true }); this.ringMesh = new Mesh( this.ringGeometry, this.ringMaterialA, ); const ringMeshB = new Mesh( this.ringGeometry, this.ringMaterialB, ); const innerCircle = new Mesh( new CircleBufferGeometry(0.45, 32), new MeshBasicMaterial({ color: 0, opacity: 0.65, transparent: true }), ); innerCircle.matrixAutoUpdate = false; innerCircle.position.set(0, 0, 0.005); innerCircle.updateMatrix(); this.anchorMesh = new Mesh( new BufferGeometry(), new MeshBasicMaterial() ); this.anchorMesh.frustumCulled = false; this.offset.add(this.anchorMesh, this.ringMesh, ringMeshB, innerCircle); this.markerGeometry = null; this.markerA = null; this.markerB = null; assetReader.fontReader.load("fonts/Roboto-Bold").then(font => { this.markerMaterialA = new RawShaderMaterial(createTextShader.default({ map: font.texture, transparent: true, color: 0xffffff, isWebGL2: this.isWebGL2 })); this.markerMaterialB = new RawShaderMaterial(createTextShader.default({ map: font.texture, transparent: true, opacity: CircleSprite.behindOpacity, color: 0xffffff, depthFunc: GreaterDepth, depthWrite: false, isWebGL2: this.isWebGL2 })); this.markerGeometry = createTextGeometry.default({ font: font.descriptor }); this.markerA = new Mesh(this.markerGeometry, this.markerMaterialA); this.markerA.matrixAutoUpdate = false; this.markerB = new Mesh(this.markerGeometry, this.markerMaterialB); this.markerB.matrixAutoUpdate = false; // we're async here, register marker for picking manually GPUPicker.add(this.markerA, false); GPUPicker.add(this.markerB, false); this.offset.add(this.markerA, this.markerB); this.update(); }); this.update(); } dispose() { this.offset = null; this.anchorMesh = null; this.ringMesh = null; this.ringGeometry = null; this.ringMaterialA = null; this.ringMaterialB = null; this.markerGeometry = null; this.markerMaterialA = null; this.markerMaterialB = null; this.markerA = null; this.markerB = null; super.dispose(); } update() { const annotation = this.annotation.data; const c = annotation.color; this.ringMaterialA.color.setRGB(c[0], c[1], c[2]); this.ringMaterialB.color.setRGB(c[0], c[1], c[2]); //this.anchorMesh.position.set(0, 0, annotation.scale * 0.1); if (this.markerA) { const length = annotation.marker.length; const scale = length > 1 ? 0.013 : 0.016; const geometry = this.markerGeometry; (geometry as any).update(annotation.marker); geometry.computeBoundingBox(); geometry.boundingBox.getCenter(_vec3a); this.markerA.position.set(-scale * (_vec3a.x + 1), scale * _vec3a.y, 0.01); this.markerA.scale.set(scale, -scale, -1); this.markerA.updateMatrix(); this.markerB.position.set(-scale * (_vec3a.x + 1), scale * _vec3a.y, 0.01); this.markerB.scale.set(scale, -scale, -1); this.markerB.updateMatrix(); } super.update(); } renderHTMLElement(element: AnnotationElement, container: HTMLElement, camera: UniversalCamera) { const annotation = this.annotation.data; let matrixCamera : PerspectiveCamera = null; const isShowing = this.annotation.data.visible; if(camera instanceof ArrayCamera) { matrixCamera = ((camera as Camera) as ArrayCamera).cameras[0]; } // billboard rotation if(matrixCamera) { _mat4.copy(matrixCamera.matrixWorldInverse); } else { _mat4.copy(camera.matrixWorldInverse); } _mat4.multiply(this.matrixWorld); _mat4.decompose(_vec3a, _quat1, _vec3b); this.offset.quaternion.copy(_quat1.invert()); // get inverse world scale relative to user scale this.offset.parent.matrixWorld.decompose(_vec3a, _quat1, _vec3b); const invWorldScale = 1.0/_vec3b.x * (1.0/annotation.scale) * this.xrScale; // scale annotation with respect to camera distance const vpHeight = container.offsetHeight + 250; const vpScale = annotation.scale * 55 / vpHeight * invWorldScale; let scaleFactor = 1; if (camera.isPerspectiveCamera) { const distZ = -_vec3a.set(0, 0, 0).applyMatrix4(_mat4).z; const theta = camera.fov * MathUtils.DEG2RAD * 0.5; scaleFactor = Math.tan(theta) * distZ * vpScale; } else { scaleFactor = camera.size * 0.5 * vpScale; } this.offset.scale.setScalar(scaleFactor); this.offset.position.set(0, (annotation.offset + 1) * scaleFactor * 0.5, 0); this.offset.updateMatrix(); // don't show if behind the camera this.setVisible(!this.isBehindCamera(this.offset, camera) && isShowing); if(!this.getVisible()) { element.setVisible(this.getVisible()); } if (annotation.expanded) { // calculate screen position of HTML sprite element _vec3a.set(0, 0, 0).applyMatrix4(this.anchorMesh.modelViewMatrix).applyMatrix4(camera.projectionMatrix); _vec3b.set(0.6, 0.5, 0).applyMatrix4(this.anchorMesh.modelViewMatrix).applyMatrix4(camera.projectionMatrix); const centerX = (_vec3a.x + 1) * 0.5 * container.clientWidth; const centerY = (1 - _vec3a.y) * 0.5 * container.clientHeight; const offsetX = (_vec3b.x + 1) * 0.5 * container.clientWidth - centerX; const offsetY = (1 - _vec3b.y) * 0.5 * container.clientHeight - centerY; let x = centerX + offsetX; let y = centerY + offsetY; element.classList.remove("sv-align-right", "sv-align-bottom"); if (x + element.offsetWidth >= container.offsetWidth) { x = centerX - offsetX; element.classList.add("sv-align-right"); } if (y + element.offsetHeight >= container.offsetHeight) { y = centerY - offsetY; element.classList.add("sv-align-bottom"); } element.setPosition(x, y); } if(this._isExpanded !== annotation.expanded) { element.style.visibility = ""; this._isExpanded = annotation.expanded } } protected createHTMLElement() { return new CircleAnnotation(this); } protected updateHTMLElement(element: AnnotationElement) { element.setVisible(this.getVisible()); // Stops annotation box from occasionally showing before it has been positioned if(this.annotation.data.expanded && this._isExpanded !== this.annotation.data.expanded) { element.style.visibility = "hidden"; } element.requestUpdate(); } } AnnotationFactory.registerType(CircleSprite); //////////////////////////////////////////////////////////////////////////////// @customElement("sv-circle-annotation") class CircleAnnotation extends AnnotationElement { constructor(sprite: CircleSprite) { super(sprite); } setVisible(visible: boolean) { // element is visible only if the annotation is in expanded state super.setVisible(visible && this.sprite.annotation.data.expanded); } protected firstConnected() { super.firstConnected(); this.classList.add("sv-circle-annotation"); } protected render() { const annotation = this.sprite.annotation; const annotationData = annotation.data; return html`<div class="sv-title">${annotation.title}</div> <div class="sv-content"><p>${annotation.lead}</p></div> ${annotationData.articleId ? html`<ff-button inline text="Read more..." icon="document" @click=${this.onClickArticle}></ff-button>` : null}`; } protected onClickArticle(event: MouseEvent) { event.stopPropagation(); this.sprite.emitLinkEvent(this.sprite.annotation.data.articleId); } }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import convict from 'convict'; import { ipaddress, url } from 'convict-format-with-validator'; import json5 from 'json5'; import yaml from 'yaml'; import toml from 'toml'; import { cpus, networkInterfaces } from 'os'; import Logger from '../logger/Logger'; import * as userRoles from '../access/roles'; import { BYPASS_ROOM_LOCK, BYPASS_LOBBY } from '../access/access'; import { CHANGE_ROOM_LOCK, PROMOTE_PEER, MODIFY_ROLE, SEND_CHAT, MODERATE_CHAT, SHARE_AUDIO, SHARE_VIDEO, SHARE_SCREEN, EXTRA_VIDEO, SHARE_FILE, MODERATE_FILES, MODERATE_ROOM } from '../access/perms'; const logger = new Logger('config'); // add network interfaces list const ifaceWhiteListRegex = '^(eth.*)|(ens.*)|(br.*)|(wl.*)|(ww.*)'; // add parsers convict.addParser([ { extension: 'json', parse: JSON.parse }, { extension: 'json5', parse: json5.parse }, { extension: [ 'yml', 'yaml' ], parse: yaml.parse }, { extension: 'toml', parse: toml.parse } ]); // add formats function assert(assertion: Boolean, msg: string) { if (!assertion) throw new Error(msg); } // add automatic IP detection function getListenIps() { const listenIP = []; const ifaces = networkInterfaces(); Object.keys(ifaces).forEach(function(ifname) { if (ifname.match(ifaceWhiteListRegex)) { ifaces[ifname].forEach(function(iface) { if ( (iface.family !== 'IPv4' && (iface.family !== 'IPv6' || iface.scopeid !== 0)) || iface.internal !== false ) { // skip over internal (i.e. 127.0.0.1) and non-ipv4 or ipv6 non global addresses return; } listenIP.push({ ip: iface.address, announcedIp: null }); }); } }); if (listenIP.length === 0) { listenIP.push({ ip: '0.0.0.0', announcedIp: null }); } logger.info('discovered IP adresses:', JSON.stringify(listenIP, null, 4)); return listenIP; } const isFloat = { name : 'float', coerce : (v: string) => parseFloat(v), validate : (v: number) => assert(Number.isFinite(v), 'must be a number') }; convict.addFormats({ ipaddress, url, isFloat }); // config schema const configSchema = convict({ turnAPIKey : { doc : 'TURN server key for requesting a geoip-based TURN server closest to the client.', format : String, default : '' }, turnAPIURI : { doc : 'TURN server URL for requesting a geoip-based TURN server closest to the client.', format : String, default : '' }, turnAPIparams : { 'uri_schema' : { doc : 'TURN server URL schema.', format : String, default : 'turn' }, 'transport' : { doc : 'TURN server transport.', format : [ 'tcp', 'udp' ], default : 'tcp' }, 'ip_ver' : { doc : 'TURN server IP version.', format : [ 'ipv4', 'ipv6' ], default : 'ipv4' }, 'servercount' : { doc : 'TURN server count.', format : 'nat', default : 2 } }, turnAPITimeout : { doc : 'TURN server API timeout (seconds).', format : 'nat', default : 2 * 1000 }, backupTurnServers : { doc : 'Backup TURN servers if REST fails or is not configured', format : '*', default : [ { urls : [ 'turn:turn.example.com:443?transport=tcp' ], username : 'example', credential : 'example' } ] }, fileTracker : { doc : 'Bittorrent tracker.', format : String, default : 'wss://tracker.openwebtorrent.com' }, redisOptions : { host : { doc : 'Redis server host.', format : String, default : 'localhost' }, port : { doc : 'Redis server port.', format : 'port', default : 6379 }, password : { doc : 'Redis server password.', format : String, default : '' } }, cookieSecret : { doc : 'Session cookie secret.', format : String, default : 'T0P-S3cR3t_cook!e' }, cookieName : { doc : 'Session cookie name.', format : String, default : 'edumeet.sid' }, tls : { cert : { doc : 'SSL certificate path.', format : String, default : './certs/edumeet-demo-cert.pem' }, key : { doc : 'SSL key path.', format : String, default : './certs/edumeet-demo-key.pem' } }, listeningHost : { doc : 'The listening Host or IP address.', format : String, default : '0.0.0.0' }, listeningPort : { doc : 'The HTTPS listening port.', format : 'port', default : 443 }, listeningRedirectPort : { doc : 'The HTTP server listening port used for redirecting any HTTP request to HTTPS. If 0, the redirect server is disabled.', format : 'port', default : 8080 }, httpOnly : { doc : 'Listens only on HTTP on listeningPort; listeningRedirectPort disabled. Use case: load balancer backend.', format : 'Boolean', default : false }, trustProxy : { doc : 'WebServer/Express trust proxy config for httpOnly mode. More infos: [expressjs](https://expressjs.com/en/guide/behind-proxies.html), [proxy-addr](https://www.npmjs.com/package/proxy-addr)', format : String, default : '' }, staticFilesCachePeriod : { doc : 'The max-age in milliseconds for HTTP caching of static resources. This can also be a string accepted by the [ms module](https://www.npmjs.com/package/ms#readme).', format : '*', default : 0 }, activateOnHostJoin : { doc : 'When true, the room will be open to all users since there are users in the room.', format : 'Boolean', default : true }, roomsUnlocked : { doc : 'An array of rooms users can enter without waiting in the lobby.', format : Array, default : [] }, maxUsersPerRoom : { doc : 'It defines how many users can join a single room. If not set, no limit is applied.', format : 'nat', default : 0 }, routerScaleSize : { doc : 'Room size before spreading to a new router.', format : 'nat', default : 40 }, requestTimeout : { doc : 'Socket timeout value (ms).', format : 'nat', default : 20000 }, requestRetries : { doc : 'Socket retries when a timeout occurs.', format : 'nat', default : 3 }, // Mediasoup settings mediasoup : { numWorkers : { doc : 'The number of Mediasoup workers to spawn. Defaults to the available CPUs count.', format : 'nat', default : Object.keys(cpus()).length }, worker : { logLevel : { doc : 'The Mediasoup log level.', format : String, default : 'warn' }, logTags : { doc : 'The Mediasoup log tags.', format : Array, default : [ 'info', 'ice', 'dtls', 'rtp', 'srtp', 'rtcp' ] }, rtcMinPort : { doc : 'The Mediasoup start listening port number.', format : 'port', default : 40000 }, rtcMaxPort : { doc : 'The Mediasoup end listening port number.', format : 'port', default : 49999 } }, // mediasoup Router settings. router : { // Router media codecs. mediaCodecs : { doc : 'The Mediasoup codecs settings. [supportedRtpCapabilities](https://github.com/versatica/mediasoup/blob/v3/src/supportedRtpCapabilities.ts)', format : '*', default : [ { kind : 'audio', mimeType : 'audio/opus', clockRate : 48000, channels : 2 }, { kind : 'video', mimeType : 'video/VP8', clockRate : 90000, parameters : { 'x-google-start-bitrate' : 1000 } }, { kind : 'video', mimeType : 'video/VP9', clockRate : 90000, parameters : { 'profile-id' : 2, 'x-google-start-bitrate' : 1000 } }, { kind : 'video', mimeType : 'video/h264', clockRate : 90000, parameters : { 'packetization-mode' : 1, 'profile-level-id' : '4d0032', 'level-asymmetry-allowed' : 1, 'x-google-start-bitrate' : 1000 } }, { kind : 'video', mimeType : 'video/h264', clockRate : 90000, parameters : { 'packetization-mode' : 1, 'profile-level-id' : '42e01f', 'level-asymmetry-allowed' : 1, 'x-google-start-bitrate' : 1000 } } ] } }, // mediasoup WebRtcTransport settings. webRtcTransport : { listenIps : { doc : 'The Mediasoup listen IPs. [TransportListenIp](https://mediasoup.org/documentation/v3/mediasoup/api/#TransportListenIp)', format : Array, default : getListenIps() }, initialAvailableOutgoingBitrate : { doc : 'The Mediasoup initial available outgoing bitrate (in bps). [WebRtcTransportOptions](https://mediasoup.org/documentation/v3/mediasoup/api/#WebRtcTransportOptions)', format : 'nat', default : 1000000 }, maxIncomingBitrate : { doc : 'The Mediasoup maximum incoming bitrate for each transport. (in bps). [setMaxIncomingBitrate](https://mediasoup.org/documentation/v3/mediasoup/api/#transport-setMaxIncomingBitrate)', format : 'nat', default : 15000000 } } }, // Prometheus exporter prometheus : { enabled : { doc : 'Enables the Prometheus metrics exporter.', format : 'Boolean', default : false }, listen : { doc : 'Prometheus metrics exporter listening address.', format : 'String', default : 'localhost' }, port : { doc : 'The Prometheus metrics exporter listening port.', format : 'port', default : 8889 }, // default metrics options deidentify : { doc : 'De-identify IP addresses in Prometheus logs.', format : 'Boolean', default : false }, numeric : { doc : 'Show numeric IP addresses in Prometheus logs.', format : 'Boolean', default : false }, quiet : { doc : 'Include fewer labels in Prometheus metrics.', format : 'Boolean', default : false }, // aggregated metrics options period : { doc : 'The Prometheus metrics exporter update period (seconds).', format : 'nat', default : 15 }, secret : { doc : 'The Prometheus metrics exporter authorization header: `Bearer <secret>` required to allow scraping.', format : String, default : '' } }, // User roles // All users have the role "NORMAL" by default. Other roles need to be // added in the "userMapping" function. The following accesses and // permissions are arrays of roles. Roles can be changed in userRoles.js // // Example: // [ userRoles.MODERATOR, userRoles.AUTHENTICATED ] accessFromRoles : { doc : 'User roles.', format : '*', default : { // The role(s) will gain access to the room // even if it is locked (!) [BYPASS_ROOM_LOCK] : [ userRoles.ADMIN ], // The role(s) will gain access to the room without // going into the lobby. If you want to restrict access to your // server to only directly allow authenticated users, you could // add the userRoles.AUTHENTICATED to the user in the userMapping // function, and change to BYPASS_LOBBY : [ userRoles.AUTHENTICATED ] [BYPASS_LOBBY] : [ userRoles.NORMAL ] } }, permissionsFromRoles : { doc : 'User permissions from roles.', format : '*', default : { // The role(s) have permission to lock/unlock a room [CHANGE_ROOM_LOCK] : [ userRoles.MODERATOR ], // The role(s) have permission to promote a peer from the lobby [PROMOTE_PEER] : [ userRoles.NORMAL ], // The role(s) have permission to give/remove other peers roles [MODIFY_ROLE] : [ userRoles.NORMAL ], // The role(s) have permission to send chat messages [SEND_CHAT] : [ userRoles.NORMAL ], // The role(s) have permission to moderate chat [MODERATE_CHAT] : [ userRoles.MODERATOR ], // The role(s) have permission to share audio [SHARE_AUDIO] : [ userRoles.NORMAL ], // The role(s) have permission to share video [SHARE_VIDEO] : [ userRoles.NORMAL ], // The role(s) have permission to share screen [SHARE_SCREEN] : [ userRoles.NORMAL ], // The role(s) have permission to produce extra video [EXTRA_VIDEO] : [ userRoles.NORMAL ], // The role(s) have permission to share files [SHARE_FILE] : [ userRoles.NORMAL ], // The role(s) have permission to moderate files [MODERATE_FILES] : [ userRoles.MODERATOR ], // The role(s) have permission to moderate room (e.g. kick user) [MODERATE_ROOM] : [ userRoles.MODERATOR ] } }, // Array of permissions. If no peer with the permission in question // is in the room, all peers are permitted to do the action. The peers // that are allowed because of this rule will not be able to do this // action as soon as a peer with the permission joins. In this example // everyone will be able to lock/unlock room until a MODERATOR joins. allowWhenRoleMissing : { doc : 'Allow when role missing.', format : Array, default : [ CHANGE_ROOM_LOCK ] } }); /** * Formats the schema documentation, calling the same function recursively. * @param docs the documentation object to extend * @param property the root property * @param schema the config schema fragment * @returns the documentation object */ function formatDocs(docs: any, property: string | null, schema: any) { if (schema._cvtProperties) { Object.entries(schema._cvtProperties).forEach(([ name, value ]) => { formatDocs(docs, `${property ? `${property}.` : ''}${name}`, value); }); return docs; } if (property) { docs[property] = // eslint-disable-line no-param-reassign { doc : schema.doc, format : JSON.stringify(schema.format, null, 2), default : JSON.stringify(schema.default, null, 2) }; } return docs; } // format docs const configDocs = formatDocs({}, null, configSchema.getSchema()); let config: any = {}; let configError = ''; let configLoaded = false; // Load config from file for (const format of [ 'json', 'json5', 'yaml', 'yml', 'toml' ]) // eslint-disable-line no-restricted-syntax { const filepath = path.normalize(`${__dirname}/../../config/config.${format}`); if (fs.existsSync(filepath)) { try { logger.debug(`Loading config from ${filepath}`); configSchema.loadFile(filepath); configLoaded = true; break; } catch (err) { logger.debug(`Loading config from ${filepath} failed: ${err.message}`); } } } if (!configLoaded) { logger.warn(`No config file found in ${path.normalize(`${__dirname}/../../config/`)}, using defaults.`); configSchema.load({}); } // Perform validation try { configSchema.validate({ allowed: 'strict' }); config = configSchema.getProperties(); } catch (error: any) { configError = error.message; } // load additional config module (no validation is performed) const configModuleFilepath = path.normalize(`${__dirname}/../../config/config.js`); if (fs.existsSync(configModuleFilepath)) { try { logger.info(`Loading config module from ${configModuleFilepath}`); const configModule = require('../../config/config.js'); // eslint-disable-line @typescript-eslint/no-var-requires Object.assign(config, configModule); } catch (err) { logger.error(`Error loading ${configModuleFilepath} module: ${err.message}`); } } // eslint-disable-next-line logger.debug('Using config:', config); // export { configSchema, config, configError, configDocs };
the_stack
import { FramePoint, HorizontalFramePointsExceptSize, isFramePoint, isPercentPin, LayoutSystem, NormalisedFrame, valueToUseForPin, VerticalFramePointsExceptSize, VerticalFramePoints, HorizontalFramePoints, isHorizontalPoint, numberPartOfPin, } from 'utopia-api' import { FlexLayoutHelpers } from '../../core/layout/layout-helpers' import { createLayoutPropertyPath, framePointForPinnedProp, LayoutPinnedProps, LayoutProp, pinnedPropForFramePoint, LayoutPinnedProp, LayoutTargetableProp, } from '../../core/layout/layout-helpers-new' import { maybeSwitchLayoutProps, PinningAndFlexPoints, PinningAndFlexPointsExceptSize, roundJSXElementLayoutValues, roundAttributeLayoutValues, } from '../../core/layout/layout-utils' import { findElementAtPath, findJSXElementAtPath, getSimpleAttributeAtPath, MetadataUtils, } from '../../core/model/element-metadata-utils' import { isJSXElement, jsxAttributeValue, JSXElement, JSXElementChild, UtopiaJSXComponent, ElementInstanceMetadata, ElementInstanceMetadataMap, setJSXAttributesAttribute, ArbitraryJSBlock, TopLevelElement, getJSXElementNameAsString, isJSXArbitraryBlock, isJSXFragment, isUtopiaJSXComponent, SettableLayoutSystem, emptyComments, } from '../../core/shared/element-template' import { getAllUniqueUids, getUtopiaID, guaranteeUniqueUids, insertJSXElementChild, setUtopiaID, transformJSXComponentAtPath, findJSXElementChildAtPath, transformJSXComponentAtElementPath, isSceneElement, } from '../../core/model/element-template-utils' import { generateUID } from '../../core/shared/uid-utils' import { setJSXValuesAtPaths, unsetJSXValuesAtPaths, ValueAtPath, setJSXValueAtPath, jsxAttributesToProps, jsxSimpleAttributeToValue, getJSXAttributeAtPath, getAllPathsFromAttributes, } from '../../core/shared/jsx-attributes' import { Imports, isParseFailure, ParsedTextFile, ParseSuccess, RevisionsState, ElementPath, importAlias, PropertyPath, foldParsedTextFile, textFile, textFileContents, isParseSuccess, isTextFile, HighlightBoundsForUids, ExportsDetail, } from '../../core/shared/project-file-types' import { applyUtopiaJSXComponentsChanges, getOrDefaultScenes, getUtopiaJSXComponentsFromSuccess, } from '../../core/model/project-file-utils' import { lintAndParse } from '../../core/workers/parser-printer/parser-printer' import { defaultProject } from '../../sample-projects/sample-project-utils' import { eitherToMaybe, flatMapEither, foldEither, forEachRight, isRight, right, isLeft, Either, } from '../../core/shared/either' import Utils, { IndexPosition } from '../../utils/utils' import { CanvasPoint, canvasPoint, CanvasRectangle, canvasRectangle, CanvasVector, localRectangle, LocalRectangle, } from '../../core/shared/math-utils' import { insertionSubjectIsJSXElement } from '../editor/editor-modes' import { DerivedState, EditorState, getOpenUIJSFile, insertElementAtPath, modifyOpenParseSuccess, OriginalCanvasAndLocalFrame, PersistentModel, removeElementAtPath, TransientCanvasState, transientCanvasState, transientFileState, getStoryboardElementPathFromEditorState, addSceneToJSXComponents, StoryboardFilePath, modifyUnderlyingTarget, modifyParseSuccessAtPath, getOpenUIJSFileKey, withUnderlyingTargetFromEditorState, modifyUnderlyingForOpenFile, TransientFilesState, forUnderlyingTargetFromEditorState, TransientFileState, withUnderlyingTarget, transformElementAtPath, ResizeOptions, } from '../editor/store/editor-state' import * as Frame from '../frame' import { getImageSizeFromMetadata, MultipliersForImages, scaleImageDimensions } from '../images' import * as EP from '../../core/shared/element-path' import * as PP from '../../core/shared/property-path' import Canvas, { TargetSearchType } from './canvas' import { CanvasFrameAndTarget, CSSCursor, DragState, DuplicateNewUID, EdgePosition, flexResizeChange, MoveDragState, oppositeEdgePositionPart, DragStatePositions, pinFrameChange, PinOrFlexFrameChange, ResizeDragState, singleResizeChange, ResizeDragStatePropertyChange, CanvasPositions, } from './canvas-types' import { collectParentAndSiblingGuidelines, filterGuidelinesStaticAxis, oneGuidelinePerDimension, } from './controls/guideline-helpers' import { determineElementsToOperateOnForDragging, dragComponent, extendSelectedViewsForInteraction, } from './controls/select-mode/move-utils' import { cornerGuideline, Guideline, Guidelines, GuidelineWithSnappingVector, xAxisGuideline, yAxisGuideline, } from './guideline' import { addImport, mergeImports } from '../../core/workers/common/project-file-utils' import { getLayoutProperty } from '../../core/layout/getLayoutProperty' import { getStoryboardUID } from '../../core/model/scene-utils' import { forceNotNull, optionalMap } from '../../core/shared/optional-utils' import { fastForEach } from '../../core/shared/utils' import { UiJsxCanvasContextData } from './ui-jsx-canvas' import { addFileToProjectContents, contentsToTree, getContentsTreeFileFromString, ProjectContentTreeRoot, } from '../assets' import { getAllTargetsAtPoint } from './dom-lookup' import { parseCSSLengthPercent } from '../inspector/common/css-utils' import { normalisePathToUnderlyingTargetForced } from '../custom-code/code-file' import { addToMapOfArraysUnique, uniqBy } from '../../core/shared/array-utils' import { mapValues } from '../../core/shared/object-utils' import { emptySet } from '../../core/shared/set-utils' import { WindowMousePositionRaw } from '../../utils/global-positions' import { getTopLevelName, importedFromWhere } from '../editor/import-utils' import { Notice } from '../common/notice' import { createStylePostActionToast } from '../../core/layout/layout-notice' import { uniqToasts } from '../editor/actions/toast-helpers' import { LayoutTargetablePropArrayKeepDeepEquality } from '../../utils/deep-equality-instances' export function getOriginalFrames( selectedViews: Array<ElementPath>, componentMetadata: ElementInstanceMetadataMap, ): Array<OriginalCanvasAndLocalFrame> { let originalFrames: Array<OriginalCanvasAndLocalFrame> = [] function includeChildren(view: ElementPath): Array<ElementPath> { return [ view, ...MetadataUtils.getChildrenHandlingGroups(componentMetadata, view, true).map( (child) => child.elementPath, ), ] } Utils.fastForEach( extendSelectedViewsForInteraction(selectedViews, componentMetadata), (selectedView) => { const allPaths = Utils.flatMapArray(includeChildren, EP.allPathsForLastPart(selectedView)) Utils.fastForEach(allPaths, (path) => { let alreadyAdded = false Utils.fastForEach(originalFrames, (originalFrame) => { if (EP.pathsEqual(originalFrame.target, path)) { alreadyAdded = true } }) if (!alreadyAdded) { // TODO Scene Implementation - this should only be one call const localFrame = MetadataUtils.getFrame(path, componentMetadata) const globalFrame = MetadataUtils.getFrameInCanvasCoords(path, componentMetadata) if (localFrame != null && globalFrame != null) { // Remove the ancestor frames if the immediate ones are groups. let workingFrame: CanvasRectangle | null = canvasRectangle(localFrame) workingFrame = MetadataUtils.shiftGroupFrame( componentMetadata, path, workingFrame, false, ) const local = localRectangle(workingFrame) originalFrames.push({ target: path, frame: Utils.defaultIfNull<LocalRectangle | undefined>(undefined, local), canvasFrame: globalFrame, }) } } }) }, ) return originalFrames } export function getOriginalCanvasFrames( selectedViews: Array<ElementPath>, componentMetadata: ElementInstanceMetadataMap, ): Array<CanvasFrameAndTarget> { const originalFrames: Array<CanvasFrameAndTarget> = [] function includeChildren(view: ElementPath): Array<ElementPath> { return [ view, ...MetadataUtils.getChildrenHandlingGroups(componentMetadata, view, true).map( (child) => child.elementPath, ), ] } Utils.fastForEach(selectedViews, (selectedView) => { const selectedAndChildren = Utils.flatMapArray( includeChildren, EP.allPathsForLastPart(selectedView), ) const includingParents = [...selectedAndChildren, ...selectedAndChildren.map(EP.parentPath)] const allPaths = uniqBy(Utils.stripNulls(includingParents), EP.pathsEqual) Utils.fastForEach(allPaths, (path) => { let alreadyAdded = false Utils.fastForEach(originalFrames, (originalFrame) => { if (EP.pathsEqual(originalFrame.target, path)) { alreadyAdded = true } }) if (!alreadyAdded) { const frame = MetadataUtils.getFrameInCanvasCoords(path, componentMetadata) originalFrames.push({ target: path, frame: frame, }) } }) }) return originalFrames } function applyTransientFilesState( producedTransientFilesState: TransientFilesState | null, toastsToAdd: ReadonlyArray<Notice>, result: EditorState, ): EditorState { let workingState = result if (producedTransientFilesState != null) { for (const filePath of Object.keys(producedTransientFilesState)) { const producedTransientFileState = producedTransientFilesState[filePath] workingState = modifyParseSuccessAtPath(filePath, workingState, (success) => { let parseSuccessResult: ParseSuccess = { ...success, imports: producedTransientFileState.imports, topLevelElements: producedTransientFileState.topLevelElementsIncludingScenes, } return parseSuccessResult }) } } return { ...workingState, toasts: uniqToasts([...workingState.toasts, ...toastsToAdd]), } } export function clearDragState( model: EditorState, derived: DerivedState, applyChanges: boolean, ): EditorState { let result: EditorState = model if ( applyChanges && result.canvas.dragState != null && getDragStateDrag(result.canvas.dragState, result.canvas.resizeOptions) != null ) { const producedTransientCanvasState = produceCanvasTransientState( derived.canvas.transientState.selectedViews, result, false, ) const producedTransientFilesState = producedTransientCanvasState.filesState result = applyTransientFilesState( producedTransientFilesState, producedTransientCanvasState.toastsToApply, result, ) } return { ...result, canvas: { ...result.canvas, dragState: null, }, selectedViews: applyChanges ? derived.canvas.transientState.selectedViews : result.selectedViews, } } export function canvasFrameToNormalisedFrame(frame: CanvasRectangle): NormalisedFrame { const { x, y, width, height } = frame return { left: x, top: y, width, height } } function dragDeltaScaleForProp(prop: LayoutTargetableProp): number { switch (prop) { case 'PinnedRight': case 'PinnedBottom': return -1 case 'flexGrow': case 'flexShrink': return 0.01 default: return 1 } } function unsetValueWhenNegative(prop: LayoutTargetableProp): boolean { switch (prop) { case 'PinnedLeft': case 'PinnedTop': case 'PinnedRight': case 'PinnedBottom': return false default: return true } } export function updateFramesOfScenesAndComponents( editorState: EditorState, framesAndTargets: Array<PinOrFlexFrameChange>, optionalParentFrame: CanvasRectangle | null, ): EditorState { let workingEditorState: EditorState = editorState let toastsToAdd: Array<Notice> = [] Utils.fastForEach(framesAndTargets, (frameAndTarget) => { const target = frameAndTarget.target // Realign to aim at the static version, not the dynamic one. const originalTarget = target const staticTarget = EP.dynamicPathToStaticPath(target) if (staticTarget == null) { return } const element = withUnderlyingTargetFromEditorState( staticTarget, workingEditorState, null, (success, underlyingElement) => underlyingElement, ) if (element == null) { throw new Error(`Unexpected result when looking for element: ${element}`) } const staticParentPath = EP.parentPath(staticTarget) const parentElement = withUnderlyingTargetFromEditorState( staticParentPath, workingEditorState, null, (success, underlyingElement) => underlyingElement, ) const elementMetadata = MetadataUtils.findElementByElementPath(editorState.jsxMetadata, target) const isFlexContainer = frameAndTarget.type !== 'PIN_FRAME_CHANGE' && frameAndTarget.type !== 'PIN_MOVE_CHANGE' && frameAndTarget.type !== 'PIN_SIZE_CHANGE' && frameAndTarget.type !== 'SINGLE_RESIZE' // TODO since now we are trusting the frameAndTarget.type, there is no point in having two switches let propsToSet: Array<ValueAtPath> = [] let propsToSkip: Array<PropertyPath> = [] let propsToUnset: Array<PropertyPath> = [] if (isFlexContainer) { switch (frameAndTarget.type) { case 'PIN_FRAME_CHANGE': // this can never run now since frameAndTarget.type cannot be both PIN_FRAME_CHANGE and not PIN_FRAME_CHANGE case 'PIN_SIZE_CHANGE': // this can never run now since frameAndTarget.type cannot be both PIN_FRAME_CHANGE and not PIN_FRAME_CHANGE case 'PIN_MOVE_CHANGE': // this can never run now since frameAndTarget.type cannot be both PIN_FRAME_CHANGE and not PIN_FRAME_CHANGE case 'SINGLE_RESIZE': // this can never run now since frameAndTarget.type cannot be both PIN_FRAME_CHANGE and not PIN_FRAME_CHANGE throw new Error( `Attempted to make a pin change against an element in a flex container ${JSON.stringify( staticParentPath, )}.`, ) case 'FLEX_MOVE': workingEditorState = modifyUnderlyingForOpenFile( originalTarget, workingEditorState, (elem) => elem, (success, underlyingTarget) => { const components = getUtopiaJSXComponentsFromSuccess(success) if (underlyingTarget == null) { return success } else { const updatedComponents = reorderComponent( workingEditorState.projectContents, workingEditorState.canvas.openFile?.filename ?? null, components, underlyingTarget, frameAndTarget.newIndex, ) return { ...success, topLevelElements: applyUtopiaJSXComponentsChanges( success.topLevelElements, updatedComponents, ), } } }, ) break case 'FLEX_RESIZE': if (staticParentPath == null) { throw new Error(`No parent available for ${JSON.stringify(staticParentPath)}`) } else { if (parentElement == null) { throw new Error(`Unexpected result when looking for parent: ${parentElement}`) } const targetPropertyPath = createLayoutPropertyPath(frameAndTarget.targetProperty) const valueFromDOM = getObservableValueForLayoutProp( elementMetadata, frameAndTarget.targetProperty, ) const valueFromAttributes = eitherToMaybe( getSimpleAttributeAtPath(right(element.props), targetPropertyPath), ) // Defer through these in order: observable value >>> value from attribute >>> 0. const currentAttributeToChange = valueFromDOM ?? valueFromAttributes ?? 0 const scalingFactor = dragDeltaScaleForProp(frameAndTarget.targetProperty) const scaledDelta = Math.floor(frameAndTarget.delta * scalingFactor) const newAttributeNumericValue = currentAttributeToChange + scaledDelta const shouldUnsetDraggedProp = newAttributeNumericValue < 0 && unsetValueWhenNegative(frameAndTarget.targetProperty) if (shouldUnsetDraggedProp) { propsToUnset.push(targetPropertyPath) } else { const newAttributeValue = jsxAttributeValue(newAttributeNumericValue, emptyComments) propsToSet.push({ path: targetPropertyPath, value: newAttributeValue, }) } propsToSkip.push( createLayoutPropertyPath('left'), createLayoutPropertyPath('top'), createLayoutPropertyPath('right'), createLayoutPropertyPath('bottom'), createLayoutPropertyPath('Width'), createLayoutPropertyPath('Height'), createLayoutPropertyPath('minWidth'), createLayoutPropertyPath('minHeight'), createLayoutPropertyPath('maxWidth'), createLayoutPropertyPath('maxHeight'), createLayoutPropertyPath('FlexCrossBasis'), createLayoutPropertyPath('flexBasis'), createLayoutPropertyPath('flexGrow'), createLayoutPropertyPath('flexShrink'), ) } break default: const _exhaustiveCheck: never = frameAndTarget throw new Error(`Unhandled type ${JSON.stringify(frameAndTarget)}`) } } else { let parentFrame: CanvasRectangle | null = null if (optionalParentFrame == null) { const nonGroupParent = MetadataUtils.findNonGroupParent( workingEditorState.jsxMetadata, originalTarget, ) parentFrame = nonGroupParent == null ? null : MetadataUtils.getFrameInCanvasCoords(nonGroupParent, workingEditorState.jsxMetadata) } else { parentFrame = optionalParentFrame } const parentOffset = parentFrame == null ? ({ x: 0, y: 0 } as CanvasPoint) : ({ x: parentFrame.x, y: parentFrame.y } as CanvasPoint) switch (frameAndTarget.type) { case 'PIN_FRAME_CHANGE': case 'PIN_SIZE_CHANGE': if (frameAndTarget.frame != null) { const newLocalFrame = Utils.getLocalRectangleInNewParentContext( parentOffset, frameAndTarget.frame, ) const currentLocalFrame = MetadataUtils.getFrame(target, workingEditorState.jsxMetadata) const currentFullFrame = optionalMap(Frame.getFullFrame, currentLocalFrame) const fullFrame = Frame.getFullFrame(newLocalFrame) const elementProps = element.props // Pinning layout. const frameProps = LayoutPinnedProps.filter((p) => { const value = getLayoutProperty(p, right(elementProps)) return isLeft(value) || value.value != null }).map(framePointForPinnedProp) function whichPropsToUpdate() { if (frameAndTarget.type === 'PIN_SIZE_CHANGE') { // only update left, top, right or bottom if the frame is expressed as left, top, right, bottom. // otherwise try to change width and height only let verticalPoints = frameProps.filter((p) => VerticalFramePoints.includes(p)) let horizontalPoints = frameProps.filter((p) => HorizontalFramePoints.includes(p)) if (verticalPoints.length < 2) { verticalPoints.push(FramePoint.Height) } if (horizontalPoints.length < 2) { horizontalPoints.push(FramePoint.Width) } return [...horizontalPoints, ...verticalPoints] } else if ( frameAndTarget.type === 'PIN_FRAME_CHANGE' && frameAndTarget.edgePosition != null && isEdgePositionOnSide(frameAndTarget.edgePosition) ) { // if it has partial positioning points set and dragged on an edge only the dragged edge should be added while keeping the existing frame points. return extendPartialFramePointsForResize(frameProps, frameAndTarget.edgePosition) } else { // The "Old" behavior, for PIN_FRAME_CHANGE return frameProps.length == 4 ? frameProps : [FramePoint.Left, FramePoint.Top, FramePoint.Width, FramePoint.Height] } } const propsToUpdate: Array<FramePoint> = whichPropsToUpdate() Utils.fastForEach(propsToUpdate, (propToUpdate) => { const absoluteValue = fullFrame[propToUpdate] const previousValue = currentFullFrame == null ? null : currentFullFrame[propToUpdate] const pinnedPropToUpdate = pinnedPropForFramePoint(propToUpdate) const propPathToUpdate = createLayoutPropertyPath(pinnedPropToUpdate) const existingProp = getLayoutProperty(pinnedPropToUpdate, right(elementProps)) if (absoluteValue === previousValue || isLeft(existingProp)) { // Only update pins that have actually changed or aren't set via code propsToSkip.push(propPathToUpdate) } else { const pinIsPercentage = existingProp.value == null ? false : isPercentPin(existingProp.value) let valueToUse: string | number if (parentFrame == null) { valueToUse = absoluteValue } else { valueToUse = valueToUseForPin( propToUpdate, absoluteValue, pinIsPercentage, parentFrame, ) } propsToSet.push({ path: propPathToUpdate, value: jsxAttributeValue(valueToUse, emptyComments), }) } }) } break case 'PIN_MOVE_CHANGE': { let frameProps: { [k: string]: string | number | undefined } = {} // { FramePoint: value } Utils.fastForEach(LayoutPinnedProps, (p) => { const framePoint = framePointForPinnedProp(p) if (framePoint !== FramePoint.Width && framePoint !== FramePoint.Height) { const value = getLayoutProperty(p, right(element.props)) if (isLeft(value) || value.value != null) { frameProps[framePoint] = value.value propsToSkip.push(createLayoutPropertyPath(p)) } } }) let framePointsToUse: Array<FramePoint> = [...(Object.keys(frameProps) as FramePoint[])] const horizontalExistingFramePoints = framePointsToUse.filter( (p) => HorizontalFramePointsExceptSize.indexOf(p) > -1, ) if (horizontalExistingFramePoints.length === 0) { framePointsToUse.push(FramePoint.Left) } const verticalExistingFramePoints = framePointsToUse.filter( (p) => VerticalFramePointsExceptSize.indexOf(p) > -1, ) if (verticalExistingFramePoints.length === 0) { framePointsToUse.push(FramePoint.Top) } propsToSet.push( ...getPropsToSetToMoveElement( frameAndTarget.delta, framePointsToUse, frameProps, parentFrame, ), ) break } case 'SINGLE_RESIZE': let frameProps: { [k: string]: string | number | undefined } = {} // { FramePoint: value } Utils.fastForEach(LayoutPinnedProps, (p) => { const framePoint = framePointForPinnedProp(p) const value = getLayoutProperty(p, right(element.props)) if (isLeft(value) || value.value != null) { frameProps[framePoint] = value.value propsToSkip.push(createLayoutPropertyPath(p)) } }) let framePointsToUse: Array<FramePoint> = Object.keys(frameProps) as FramePoint[] if (isEdgePositionOnSide(frameAndTarget.edgePosition)) { framePointsToUse = extendPartialFramePointsForResize( framePointsToUse, frameAndTarget.edgePosition, ) } else { let verticalPoints = framePointsToUse.filter((p) => VerticalFramePoints.includes(p)) let horizontalPoints = framePointsToUse.filter((p) => HorizontalFramePoints.includes(p)) if (verticalPoints.length < 2) { if (verticalPoints.length === 0) { verticalPoints.push(FramePoint.Top) } verticalPoints.push(FramePoint.Height) } if (horizontalPoints.length < 2) { if (horizontalPoints.length === 0) { horizontalPoints.push(FramePoint.Left) } horizontalPoints.push(FramePoint.Width) } framePointsToUse = Utils.uniq([...verticalPoints, ...horizontalPoints]) } propsToSet.push( ...getPropsToSetToResizeElement( frameAndTarget.edgePosition, frameAndTarget.sizeDelta.x, frameAndTarget.sizeDelta.y, framePointsToUse, frameProps, parentFrame, ), ) break case 'FLEX_MOVE': case 'FLEX_RESIZE': throw new Error( `Attempted to make a flex change against a pinned element ${JSON.stringify( staticParentPath, )}.`, ) default: const _exhaustiveCheck: never = frameAndTarget throw new Error(`Unhandled type ${JSON.stringify(frameAndTarget)}`) } } if (propsToSet.length > 0 || propsToUnset.length > 0) { const propsToNotDelete = [...propsToSet.map((p) => p.path), ...propsToSkip] workingEditorState = modifyUnderlyingForOpenFile( originalTarget, workingEditorState, (elem) => { // Remove the pinning and flex props first... const propsToMaybeRemove = frameAndTarget.type === 'PIN_MOVE_CHANGE' ? PinningAndFlexPointsExceptSize // for PIN_MOVE_CHANGE, we don't want to remove the size props, we just keep them intact : PinningAndFlexPoints let propsToRemove: Array<PropertyPath> = [...propsToUnset] function createPropPathForProp(prop: string): PropertyPath { if (isFramePoint(prop)) { return createLayoutPropertyPath(pinnedPropForFramePoint(prop)) } else { return createLayoutPropertyPath(prop as LayoutProp) } } fastForEach(propsToMaybeRemove, (prop) => { const propPath = createPropPathForProp(prop) if (!PP.contains(propsToNotDelete, propPath)) { propsToRemove.push(propPath) } }) const layoutPropsRemoved = unsetJSXValuesAtPaths(elem.props, propsToRemove) // ...Add in the updated properties. const layoutPropsAdded = flatMapEither( (props) => setJSXValuesAtPaths(props, propsToSet), layoutPropsRemoved, ) return foldEither( (_) => elem, (updatedProps) => { toastsToAdd.push( ...createStylePostActionToast( MetadataUtils.getElementLabel(originalTarget, workingEditorState.jsxMetadata), getAllPathsFromAttributes(elem.props), getAllPathsFromAttributes(updatedProps), ), ) return { ...elem, props: updatedProps, } }, layoutPropsAdded, ) }, ) } // Round the frame details. workingEditorState = modifyUnderlyingForOpenFile( staticTarget, workingEditorState, roundJSXElementLayoutValues, ) // TODO originalFrames is never being set, so we have a regression here, meaning keepChildrenGlobalCoords // doesn't work. Once that is fixed we can re-implement keeping the children in place }) if (toastsToAdd.length > 0) { workingEditorState = { ...workingEditorState, toasts: uniqToasts([...workingEditorState.toasts, ...toastsToAdd]), } } return workingEditorState } function updateFrameValueForProp( framePoint: FramePoint, delta: number, frameProps: { [k: string]: string | number | undefined }, parentFrame: CanvasRectangle | null, ): ValueAtPath | null { if (delta !== 0) { const existingProp = frameProps[framePoint] if (existingProp == null) { return { path: createLayoutPropertyPath(pinnedPropForFramePoint(framePoint)), value: jsxAttributeValue(delta, emptyComments), } } const parsedProp = foldEither( (_) => null, (r) => r, parseCSSLengthPercent(existingProp), ) if (parsedProp != null) { const pinIsPercentage = parsedProp.unit === '%' const pinIsUnitlessOrPx = parsedProp.unit == null || parsedProp.unit === 'px' if (pinIsPercentage) { let valueToUse: string | number const percentValue = parsedProp.value if (parentFrame != null) { const referenceSize = isHorizontalPoint(framePoint) ? parentFrame.width : parentFrame.height const deltaAsPercentValue = (delta / referenceSize) * 100 valueToUse = `${percentValue + deltaAsPercentValue}%` } else { valueToUse = `${percentValue + delta}%` } return { path: createLayoutPropertyPath(pinnedPropForFramePoint(framePoint)), value: jsxAttributeValue(valueToUse, emptyComments), } } else if (pinIsUnitlessOrPx) { return { path: createLayoutPropertyPath(pinnedPropForFramePoint(framePoint)), value: jsxAttributeValue(parsedProp.value + delta, emptyComments), } } } } return null } function getPropsToSetToMoveElement( dragDelta: CanvasVector, framePoints: FramePoint[], frameProps: { [k: string]: string | number | undefined }, parentFrame: CanvasRectangle | null, ): ValueAtPath[] { let propsToSet: ValueAtPath[] = [] Utils.fastForEach(framePoints, (framePoint) => { const delta = isHorizontalPoint(framePoint) ? dragDelta.x : dragDelta.y const shouldInvertValue = framePoint === FramePoint.Right || framePoint === FramePoint.Bottom const updatedProp = updateFrameValueForProp( framePoint, shouldInvertValue ? -delta : delta, frameProps, parentFrame, ) if (updatedProp != null) { propsToSet.push(updatedProp) } }) return propsToSet } function getPropsToSetToResizeElement( edgePosition: EdgePosition, widthDelta: number, heightDelta: number, framePoints: FramePoint[], frameProps: { [k: string]: string | number | undefined }, parentFrame: CanvasRectangle | null, ): ValueAtPath[] { let propsToSet: ValueAtPath[] = [] Utils.fastForEach(framePoints, (framePoint) => { let updatedProp switch (framePoint) { case FramePoint.Left: { const targetEdgePoint = { x: 0, y: 0.5 } const delta = widthDelta * (edgePosition.x + targetEdgePoint.x - 1) if (delta !== 0) { updatedProp = updateFrameValueForProp(framePoint, delta, frameProps, parentFrame) } break } case FramePoint.Top: { const targetEdgePoint = { x: 0.5, y: 0 } const delta = heightDelta * (edgePosition.y + targetEdgePoint.y - 1) if (delta !== 0) { updatedProp = updateFrameValueForProp(framePoint, delta, frameProps, parentFrame) } break } case FramePoint.Right: { const targetEdgePoint = { x: 1, y: 0.5 } const delta = widthDelta * -(edgePosition.x + targetEdgePoint.x - 1) if (delta !== 0) { updatedProp = updateFrameValueForProp(framePoint, delta, frameProps, parentFrame) } break } case FramePoint.Bottom: { const targetEdgePoint = { x: 0.5, y: 1 } const delta = heightDelta * -(edgePosition.y + targetEdgePoint.y - 1) if (delta !== 0) { updatedProp = updateFrameValueForProp(framePoint, delta, frameProps, parentFrame) } break } case FramePoint.Width: { if (widthDelta !== 0) { updatedProp = updateFrameValueForProp(framePoint, widthDelta, frameProps, parentFrame) } break } case FramePoint.Height: { if (heightDelta !== 0) { updatedProp = updateFrameValueForProp(framePoint, heightDelta, frameProps, parentFrame) } break } case FramePoint.CenterX: { const targetEdgePoint = { x: 0.5, y: 0.5 } const delta = widthDelta * (edgePosition.x + targetEdgePoint.x - 1) if (delta !== 0) { updatedProp = updateFrameValueForProp(framePoint, delta, frameProps, parentFrame) } break } case FramePoint.CenterY: { const targetEdgePoint = { x: 0.5, y: 0.5 } const delta = heightDelta * (edgePosition.y + targetEdgePoint.y - 1) if (delta !== 0) { updatedProp = updateFrameValueForProp(framePoint, delta, frameProps, parentFrame) } break } default: { break } } if (updatedProp != null) { propsToSet.push(updatedProp) } }) return propsToSet } function extendPartialFramePointsForResize(frameProps: FramePoint[], edgePosition: EdgePosition) { // if it has partial positioning points set and dragged on an edge only the dragged edge should be added while keeping the existing frame points. let verticalPoints = frameProps.filter((p) => VerticalFramePoints.includes(p)) let horizontalPoints = frameProps.filter((p) => HorizontalFramePoints.includes(p)) let framePointsToUse = [...frameProps] if (edgePosition.x === 0.5 && verticalPoints.length < 2) { if (verticalPoints.length === 0) { if (edgePosition.y === 0) { verticalPoints.push(FramePoint.Top) verticalPoints.push(FramePoint.Height) } else { verticalPoints.push(FramePoint.Height) } } else { if (edgePosition.y === 0) { verticalPoints.push(FramePoint.Top) } else if (!verticalPoints.includes(FramePoint.Bottom)) { verticalPoints.push(FramePoint.Height) } } framePointsToUse = [...verticalPoints, ...horizontalPoints] } if (edgePosition.y === 0.5 && horizontalPoints.length < 2) { if (horizontalPoints.length === 0) { if (edgePosition.x === 0) { horizontalPoints.push(FramePoint.Left) horizontalPoints.push(FramePoint.Width) } else { horizontalPoints.push(FramePoint.Width) } } else { if (edgePosition.x === 0) { horizontalPoints.push(FramePoint.Left) } else if (!horizontalPoints.includes(FramePoint.Right)) { horizontalPoints.push(FramePoint.Width) } } framePointsToUse = [...verticalPoints, ...horizontalPoints] } return Utils.uniq(framePointsToUse) } export function getOriginalFrameInCanvasCoords( originalFrames: Array<OriginalCanvasAndLocalFrame>, target: ElementPath, ): CanvasRectangle | null { for (const originalFrame of originalFrames ?? []) { if (EP.pathsEqual(target, originalFrame.target)) { if (originalFrame.canvasFrame != null) { return originalFrame.canvasFrame } } } return null } export function pickPointOnRect(rect: CanvasRectangle, position: EdgePosition): CanvasPoint { return Utils.addVectors( Utils.rectOrigin(rect), Utils.scalePoint(Utils.rectSizeToVector(rect), position as CanvasPoint), ) } export function isEdgePositionACorner(edgePosition: EdgePosition): boolean { return ( (edgePosition.x === 0 && edgePosition.y === 0) || (edgePosition.x === 0 && edgePosition.y === 1) || (edgePosition.x === 1 && edgePosition.y === 0) || (edgePosition.x === 1 && edgePosition.y === 1) ) } export function isEdgePositionAHorizontalEdge(edgePosition: EdgePosition): boolean { return ( (edgePosition.x === 0.5 && edgePosition.y === 0) || (edgePosition.x === 0.5 && edgePosition.y === 1) ) } export function isEdgePositionAVerticalEdge(edgePosition: EdgePosition): boolean { return ( (edgePosition.x === 0 && edgePosition.y === 0.5) || (edgePosition.x === 1 && edgePosition.y === 0.5) ) } export function isEdgePositionOnSide(edgePosition: EdgePosition): boolean { return edgePosition.x === 0.5 || edgePosition.y === 0.5 } export const SnappingThreshold = 5 export function collectGuidelines( metadata: ElementInstanceMetadataMap, selectedViews: Array<ElementPath>, scale: number, draggedPoint: CanvasPoint | null, resizingFromPosition: EdgePosition | null, ): Array<GuidelineWithSnappingVector> { if (draggedPoint == null) { return [] } let guidelines: Array<Guideline> = collectParentAndSiblingGuidelines(metadata, selectedViews) // For any images create guidelines at the current multiplier setting. if (resizingFromPosition != null) { Utils.fastForEach(selectedViews, (selectedView) => { if (MetadataUtils.isPinnedAndNotAbsolutePositioned(metadata, selectedView)) { return } const instance = MetadataUtils.findElementByElementPath(metadata, selectedView) if (instance != null && MetadataUtils.isImg(instance) && instance.localFrame != null) { const frame = instance.localFrame const imageSize = getImageSizeFromMetadata(instance) Utils.fastForEach(MultipliersForImages, (multiplier) => { const imageDimension = scaleImageDimensions(imageSize, multiplier) // Calculate the guidelines around the corner/edge given. const point: CanvasPoint = { x: frame.x + frame.width * resizingFromPosition.x, y: frame.y + frame.width * resizingFromPosition.y, } as CanvasPoint const lowHalfWidth = Utils.roundTo(imageDimension.width / 2, 0) const highHalfWidth = imageDimension.width - lowHalfWidth const lowHalfHeight = Utils.roundTo(imageDimension.height / 2, 0) const highHalfHeight = imageDimension.height - lowHalfHeight if (isEdgePositionACorner(resizingFromPosition)) { // If this is a corner the guidelines will be at x +/- width and y +/- height. if (resizingFromPosition.x === 0) { if (resizingFromPosition.y === 0) { // Top-left. guidelines.push( cornerGuideline( point.x + imageDimension.width, point.y + imageDimension.height, -imageDimension.width, -imageDimension.height, ), ) } else { // Bottom-left. guidelines.push( cornerGuideline( point.x, point.y + imageDimension.height, imageDimension.width, -imageDimension.height, ), ) } } else { if (resizingFromPosition.y === 0) { // Top-right. guidelines.push( cornerGuideline( point.x + imageDimension.width, point.y, -imageDimension.width, imageDimension.height, ), ) } else { // Bottom-right. guidelines.push( cornerGuideline(point.x, point.y, imageDimension.width, imageDimension.height), ) } } } else if (isEdgePositionAVerticalEdge(resizingFromPosition)) { // If this is a side edge the guidelines will be at x +/- width and y +/- (height / 2). guidelines.push( xAxisGuideline( point.x - imageDimension.width, point.y - lowHalfHeight, point.y + highHalfHeight, ), xAxisGuideline( point.x + imageDimension.width, point.y - lowHalfHeight, point.y + highHalfHeight, ), yAxisGuideline(point.y - lowHalfHeight, point.x - imageDimension.width, point.x), yAxisGuideline(point.y - lowHalfHeight, point.x, point.x + imageDimension.width), yAxisGuideline(point.y + highHalfHeight, point.x - imageDimension.width, point.x), yAxisGuideline(point.y + highHalfHeight, point.x, point.x + imageDimension.width), ) } else if (isEdgePositionAHorizontalEdge(resizingFromPosition)) { // If this is a top/bottom edge the guidelines will be at x +/- (width / 2) and y +/- height. guidelines.push( xAxisGuideline(point.x - lowHalfWidth, point.y - imageDimension.height, point.y), xAxisGuideline(point.x - lowHalfWidth, point.y, point.y + imageDimension.height), xAxisGuideline(point.x + highHalfWidth, point.y - imageDimension.height, point.y), xAxisGuideline(point.x + highHalfWidth, point.y, point.y + imageDimension.height), yAxisGuideline( point.y - imageDimension.height, point.x - lowHalfWidth, point.x + highHalfWidth, ), yAxisGuideline( point.y + imageDimension.height, point.x - lowHalfWidth, point.x + highHalfWidth, ), ) } }) } }) } const filteredGuidelines = resizingFromPosition != null ? filterGuidelinesStaticAxis(guidelines, resizingFromPosition) : guidelines const closestGuidelines = Guidelines.getClosestGuidelinesAndOffsets( [draggedPoint.x], [draggedPoint.y], [draggedPoint], filteredGuidelines, null, SnappingThreshold, scale, ) return closestGuidelines } function innerSnapPoint( editor: EditorState, point: CanvasPoint, resizingFromPosition: EdgePosition | null, ): { point: CanvasPoint; guideline: GuidelineWithSnappingVector | null } { const guidelines = oneGuidelinePerDimension( collectGuidelines( editor.jsxMetadata, editor.selectedViews, editor.canvas.scale, point, resizingFromPosition, ), ) let snappedPoint = point let snappedGuideline: GuidelineWithSnappingVector | null = null guidelines.forEach((guideline) => { if (guideline.activateSnap) { snappedPoint = Utils.offsetPoint(snappedPoint, guideline.snappingVector) snappedGuideline = guideline } }) return { point: snappedPoint, guideline: snappedGuideline, } } export function snapPoint( editor: EditorState, pointToSnap: CanvasPoint, enableSnapping: boolean, keepAspectRatio: boolean, diagonalA: CanvasPoint, diagonalB: CanvasPoint, resizingFromPosition: EdgePosition | null, ): CanvasPoint { const elementsToTarget = determineElementsToOperateOnForDragging( editor.selectedViews, editor.jsxMetadata, true, false, ) const anythingPinnedAndNotAbsolutePositioned = elementsToTarget.some((elementToTarget) => { return MetadataUtils.isPinnedAndNotAbsolutePositioned(editor.jsxMetadata, elementToTarget) }) const shouldSnap = enableSnapping && !anythingPinnedAndNotAbsolutePositioned if (keepAspectRatio) { const closestPointOnLine = Utils.closestPointOnLine(diagonalA, diagonalB, pointToSnap) if (shouldSnap) { const { guideline } = innerSnapPoint(editor, closestPointOnLine, resizingFromPosition) if (guideline != null) { const guidelinePoints = Guidelines.convertGuidelineToPoints(guideline.guideline) // for now, because scale is not a first-class citizen, we know that CanvasVector and LocalVector have the same dimensions let snappedPoint: CanvasPoint | null = null switch (guidelinePoints.type) { case 'cornerguidelinepoint': snappedPoint = guidelinePoints.point break default: snappedPoint = Utils.lineIntersection( diagonalA, diagonalB, guidelinePoints.start, guidelinePoints.end, ) } if (snappedPoint != null) { return snappedPoint } } // fallback to regular diagonal snapping return closestPointOnLine } else { return pointToSnap } } else { const { point } = innerSnapPoint(editor, pointToSnap, resizingFromPosition) return shouldSnap ? point : pointToSnap } } function getTargetableProp(resizeOptions: ResizeOptions): LayoutTargetableProp | undefined { return resizeOptions.propertyTargetOptions[resizeOptions.propertyTargetSelectedIndex] } function findResizePropertyChange( dragState: ResizeDragState, resizeOptions: ResizeOptions, ): ResizeDragStatePropertyChange | undefined { const resizeProp: LayoutTargetableProp | undefined = getTargetableProp(resizeOptions) return dragState.properties.find((prop) => prop.targetProperty === resizeProp) } function calculateDraggedRectangle( editor: EditorState, dragState: ResizeDragState, ): CanvasRectangle { const originalSize = dragState.originalSize const resizeOptions = editor.canvas.resizeOptions const propertyChange = findResizePropertyChange(dragState, resizeOptions) if (propertyChange == null) { return originalSize } else { // for center based resize, we need to calculate with double deltas // for now, because scale is not a first-class citizen, we know that CanvasVector and LocalVector have the same dimensions // this will break with the introduction of scale into the coordinate systems const deltaScale = propertyChange.centerBasedResize ? 2 : 1 let delta: CanvasVector = canvasPoint({ x: 0, y: 0 }) const drag = getDragStateDrag(dragState, editor.canvas.resizeOptions) if (drag != null) { delta = Utils.scaleVector( Utils.scalePoint(drag, dragState.enabledDirection as CanvasVector), deltaScale, ) } const startingCorner: EdgePosition = { x: 1 - dragState.edgePosition.x, y: 1 - dragState.edgePosition.y, } as EdgePosition const startingPoint = pickPointOnRect(originalSize, startingCorner) const originalCenter = Utils.getRectCenter(originalSize) const draggedCorner = pickPointOnRect(originalSize, dragState.edgePosition) const newCorner = Utils.offsetPoint(draggedCorner, delta) const snappedNewCorner = Utils.roundPointTo( snapPoint( editor, newCorner, propertyChange.enableSnapping, propertyChange.keepAspectRatio, startingPoint, draggedCorner, startingCorner, ), 0, ) const newSizeVector = Utils.pointDifference(startingPoint, snappedNewCorner) const newRectangle = propertyChange.centerBasedResize ? Utils.rectFromPointVector(originalCenter, Utils.scaleVector(newSizeVector, 0.5), true) : Utils.rectFromPointVector(startingPoint, newSizeVector, false) return newRectangle } } export function calculateNewBounds( editor: EditorState, dragState: ResizeDragState, ): CanvasRectangle { const originalSize = dragState.originalSize const aspectRatio = originalSize.width / originalSize.height const newRectangle = calculateDraggedRectangle(editor, dragState) const resizeOptions = editor.canvas.resizeOptions const propertyChange = findResizePropertyChange(dragState, resizeOptions) if (propertyChange == null) { return originalSize } else { // In an aspect ratio locked resize if one dimension doesn't change then neither can the other. // FIXME: Replace with handling for this during drag. /* if (dragState.keepAspectRatio && oldRectangle != null) { if (newRectangle.width === oldRectangle.width || newRectangle.height === oldRectangle.height) { newRectangle.width = oldRectangle.width newRectangle.height = oldRectangle.height } } */ // At this point I do ugly things to keep side drags in line if (dragState.edgePosition.x === 0.5) { const newWidth = propertyChange.keepAspectRatio ? Utils.roundTo(newRectangle.height * aspectRatio) : originalSize.width newRectangle.x -= newWidth / 2 newRectangle.width = newWidth } if (dragState.edgePosition.y === 0.5) { const newHeight = propertyChange.keepAspectRatio ? Utils.roundTo(newRectangle.width / aspectRatio) : originalSize.height newRectangle.y -= newHeight / 2 newRectangle.height = newHeight } return newRectangle } } export function getCursorFromDragState(editorState: EditorState): CSSCursor | null { const dragState = editorState.canvas.dragState if (dragState == null) { return null } else { switch (dragState.type) { case 'MOVE_DRAG_STATE': if (dragState.drag == null) { return null } else { return CSSCursor.Move } case 'RESIZE_DRAG_STATE': if (isEdgePositionAHorizontalEdge(dragState.edgePosition)) { return CSSCursor.ResizeNS } else if (isEdgePositionAVerticalEdge(dragState.edgePosition)) { return CSSCursor.ResizeEW } else if (isEdgePositionACorner(dragState.edgePosition)) { // Slightly more complicated as we need to determine if the corner has flipped. let edgePosition: EdgePosition = dragState.edgePosition const bounds = calculateNewBounds(editorState, dragState) const leftEdgePastOldRightEdge = dragState.edgePosition.x === 0 && bounds.x === dragState.originalSize.x + dragState.originalSize.width && bounds.width > 0 const rightEdgePastOldLeftEdge = dragState.edgePosition.x === 1 && bounds.x !== dragState.originalSize.x const topEdgePastOldBottomEdge = dragState.edgePosition.y === 0 && bounds.y === dragState.originalSize.y + dragState.originalSize.height && bounds.height > 0 const bottomEdgePastOldTopEdge = dragState.edgePosition.y === 1 && bounds.y !== dragState.originalSize.y if (leftEdgePastOldRightEdge || rightEdgePastOldLeftEdge) { edgePosition = { ...edgePosition, x: oppositeEdgePositionPart(edgePosition.x), } } if (topEdgePastOldBottomEdge || bottomEdgePastOldTopEdge) { edgePosition = { ...edgePosition, y: oppositeEdgePositionPart(edgePosition.y), } } const isTopLeft = edgePosition.x === 0 && edgePosition.y === 0 const isBottomRight = edgePosition.x === 1 && edgePosition.y === 1 return isTopLeft || isBottomRight ? CSSCursor.ResizeNWSE : CSSCursor.ResizeNESW } else { return null } case 'INSERT_DRAG_STATE': return null default: const _exhaustiveCheck: never = dragState throw new Error(`Unhandled drag state type ${JSON.stringify(dragState)}`) } } } function getTransientCanvasStateFromFrameChanges( editorState: EditorState, framesAndTargets: Array<PinOrFlexFrameChange>, preventAnimations: boolean, elementsToTarget: Array<ElementPath>, ): TransientCanvasState { let workingEditorState: EditorState = editorState let successByFilename: { [filename: string]: ParseSuccess } = {} if (preventAnimations) { // We don't want animations included in the transient state, except for the case where we're about to apply that to the final state workingEditorState = preventAnimationsOnTargets(workingEditorState, elementsToTarget) } workingEditorState = updateFramesOfScenesAndComponents(workingEditorState, framesAndTargets, null) for (const frameAndTarget of framesAndTargets) { forUnderlyingTargetFromEditorState( frameAndTarget.target, workingEditorState, (success, underlyingElement, underlyingTarget, underlyingFilePath) => { successByFilename[underlyingFilePath] = success return success }, ) } return transientCanvasState( editorState.selectedViews, editorState.highlightedViews, mapValues((success) => { return transientFileState(success.topLevelElements, success.imports) }, successByFilename), workingEditorState.toasts, // TODO filter for relevant toasts ) } export function produceResizeCanvasTransientState( editorState: EditorState, dragState: ResizeDragState, preventAnimations: boolean, ): TransientCanvasState { const elementsToTarget = determineElementsToOperateOnForDragging( dragState.draggedElements, editorState.jsxMetadata, false, true, ) const newSize = calculateNewBounds(editorState, dragState) let framesAndTargets: Array<PinOrFlexFrameChange> = [] let globalFrames: Array<CanvasRectangle> = [] Utils.fastForEach(dragState.draggedElements, (selectedView) => { const frame = getOriginalFrameInCanvasCoords(dragState.originalFrames, selectedView) if (frame != null) { globalFrames.push(frame) } }) const boundingBox = Utils.boundingRectangleArray(globalFrames) if (boundingBox == null) { return transientCanvasState(dragState.draggedElements, editorState.highlightedViews, null, []) } else { Utils.fastForEach(elementsToTarget, (target) => { forUnderlyingTargetFromEditorState( target, editorState, (success, element, underlyingTarget, underlyingFilePath) => { const originalFrame = getOriginalFrameInCanvasCoords(dragState.originalFrames, target) if (originalFrame != null) { const newTargetFrame = Utils.transformFrameUsingBoundingBox( newSize, boundingBox, originalFrame, ) const roundedFrame = { x: Math.floor(newTargetFrame.x), y: Math.floor(newTargetFrame.y), width: Math.ceil(newTargetFrame.width), height: Math.ceil(newTargetFrame.height), } as CanvasRectangle const isFlexContainer = MetadataUtils.isParentYogaLayoutedContainerAndElementParticipatesInLayout( target, editorState.jsxMetadata, ) if (isFlexContainer) { for (const resizePropertyChange of dragState.properties) { if (resizePropertyChange.targetProperty != null) { if (resizePropertyChange.drag != null) { const newDelta = isTargetPropertyHorizontal(dragState.edgePosition) ? resizePropertyChange.drag.x ?? 0 : resizePropertyChange.drag.y ?? 0 framesAndTargets.push( flexResizeChange(target, resizePropertyChange.targetProperty, newDelta), ) } } } } else { framesAndTargets.push( pinFrameChange(underlyingTarget, roundedFrame, dragState.edgePosition), ) } } }, ) }) return getTransientCanvasStateFromFrameChanges( editorState, framesAndTargets, preventAnimations, elementsToTarget, ) } } export function isTargetPropertyHorizontal(edgePosition: EdgePosition): boolean { return edgePosition.x !== 0.5 } export function produceResizeSingleSelectCanvasTransientState( editorState: EditorState, dragState: ResizeDragState, preventAnimations: boolean, ): TransientCanvasState { const elementsToTarget = determineElementsToOperateOnForDragging( dragState.draggedElements, editorState.jsxMetadata, false, true, ) if (elementsToTarget.length !== 1) { return transientCanvasState(editorState.selectedViews, editorState.highlightedViews, null, []) } const elementToTarget = elementsToTarget[0] const newSize = calculateNewBounds(editorState, dragState) let framesAndTargets: Array<PinOrFlexFrameChange> = [] let globalFrame = getOriginalFrameInCanvasCoords(dragState.originalFrames, elementToTarget) const originalFrame = getOriginalFrameInCanvasCoords(dragState.originalFrames, elementToTarget) if (originalFrame != null && globalFrame != null) { const nonNullGlobalFrame = globalFrame forUnderlyingTargetFromEditorState( elementToTarget, editorState, (success, element, underlyingTarget, underlyingFilePath) => { const newTargetFrame = Utils.transformFrameUsingBoundingBox( newSize, nonNullGlobalFrame, originalFrame, ) const roundedFrame = { x: Math.floor(newTargetFrame.x), y: Math.floor(newTargetFrame.y), width: Math.ceil(newTargetFrame.width), height: Math.ceil(newTargetFrame.height), } as CanvasRectangle const isFlexContainer = MetadataUtils.isParentYogaLayoutedContainerAndElementParticipatesInLayout( elementToTarget, editorState.jsxMetadata, ) for (const propertyChange of dragState.properties) { if ( isFlexContainer || dragState.edgePosition.x === 0.5 || dragState.edgePosition.y === 0.5 ) { if (propertyChange.targetProperty != null) { if (propertyChange.drag != null) { const newDelta = isTargetPropertyHorizontal(dragState.edgePosition) ? propertyChange.drag.x ?? 0 : propertyChange.drag.y ?? 0 framesAndTargets.push( flexResizeChange(elementToTarget, propertyChange.targetProperty, newDelta), ) } } } else { const edgePosition = propertyChange.centerBasedResize ? ({ x: 0.5, y: 0.5 } as EdgePosition) : dragState.edgePosition const sizeChange = { x: roundedFrame.width - originalFrame.width, y: roundedFrame.height - originalFrame.height, } as CanvasVector framesAndTargets.push(singleResizeChange(elementToTarget, edgePosition, sizeChange)) } } }, ) } return getTransientCanvasStateFromFrameChanges( editorState, framesAndTargets, preventAnimations, elementsToTarget, ) } export function produceCanvasTransientState( previousCanvasTransientSelectedViews: Array<ElementPath>, editorState: EditorState, preventAnimations: boolean, ): TransientCanvasState { const currentOpenFile = editorState.canvas.openFile?.filename let transientState: TransientCanvasState | null = null if (currentOpenFile != null) { const editorMode = editorState.mode switch (editorMode.type) { case 'insert': if (insertionSubjectIsJSXElement(editorMode.subject) && editorMode.insertionStarted) { const insertionElement = editorMode.subject.element const importsToAdd = editorMode.subject.importsToAdd const insertionParent = editorMode.subject.parent?.target ?? null // Not actually modifying the underlying target, but we'll exploit the functionality. modifyUnderlyingTarget( insertionParent, currentOpenFile, editorState, (element) => element, (parseSuccess, underlying, underlyingFilePath) => { const openComponents = getUtopiaJSXComponentsFromSuccess(parseSuccess) const updatedComponents = insertJSXElementChild( editorState.projectContents, currentOpenFile, underlying, insertionElement, openComponents, { type: 'front', }, ) const updatedImports: Imports = mergeImports( underlyingFilePath, parseSuccess.imports, importsToAdd, ) // Sync these back up. const topLevelElements = applyUtopiaJSXComponentsChanges( parseSuccess.topLevelElements, updatedComponents, ) transientState = transientCanvasState( editorState.selectedViews, editorState.highlightedViews, { [underlyingFilePath]: transientFileState(topLevelElements, updatedImports), }, [], ) return parseSuccess }, ) } break case 'select': if ( editorState.canvas.dragState != null && anyDragStarted(editorState.canvas.dragState) && anyDragMovement(editorState.canvas.dragState) ) { const dragState = editorState.canvas.dragState switch (dragState.type) { case 'MOVE_DRAG_STATE': transientState = produceMoveTransientCanvasState( previousCanvasTransientSelectedViews, editorState, dragState, preventAnimations, ) break case 'RESIZE_DRAG_STATE': if (dragState.isMultiSelect) { transientState = produceResizeCanvasTransientState( editorState, dragState, preventAnimations, ) } else { transientState = produceResizeSingleSelectCanvasTransientState( editorState, dragState, preventAnimations, ) } break case 'INSERT_DRAG_STATE': throw new Error(`Unable to use insert drag state in select mode.`) default: const _exhaustiveCheck: never = dragState throw new Error(`Unhandled drag state type ${JSON.stringify(dragState)}`) } } break } if (transientState == null && editorState.canvas.transientProperties != null) { transientState = createCanvasTransientStateFromProperties(editorState) } } if (transientState == null) { return transientCanvasState(editorState.selectedViews, editorState.highlightedViews, null, []) } else { return transientState } } export function createDuplicationNewUIDsFromEditorState( editorState: EditorState, ): Array<DuplicateNewUID> { return createDuplicationNewUIDs( editorState.selectedViews, editorState.jsxMetadata, editorState.projectContents, ) } export function createDuplicationNewUIDs( selectedViews: Array<ElementPath>, componentMetadata: ElementInstanceMetadataMap, projectContents: ProjectContentTreeRoot, ): Array<DuplicateNewUID> { const targetViews = determineElementsToOperateOnForDragging( selectedViews, componentMetadata, true, false, ) let existingIDs = getAllUniqueUids(projectContents) let result: Array<DuplicateNewUID> = [] Utils.fastForEach(targetViews, (targetView) => { const newUID = generateUID(existingIDs) existingIDs.push(newUID) result.push({ originalPath: targetView, newUID: newUID, }) }) return result } export const SkipFrameChange = 'skipFrameChange' function getReparentTargetAtPosition( componentMeta: ElementInstanceMetadataMap, selectedViews: Array<ElementPath>, hiddenInstances: Array<ElementPath>, canvasScale: number, canvasOffset: CanvasVector, ): ElementPath | undefined { const allTargets = getAllTargetsAtPoint( componentMeta, selectedViews, hiddenInstances, 'no-filter', WindowMousePositionRaw, canvasScale, canvasOffset, ) // filtering for non-selected views from alltargets return allTargets.find((target) => selectedViews.every((view) => !EP.pathsEqual(view, target))) } export function getReparentTarget( selectedViews: Array<ElementPath>, editorState: EditorState, toReparent: Array<ElementPath>, position: CanvasPoint, ): { shouldReparent: boolean newParent: ElementPath | null } { const result = getReparentTargetAtPosition( editorState.jsxMetadata, selectedViews, editorState.hiddenInstances, editorState.canvas.scale, editorState.canvas.realCanvasOffset, ) const possibleNewParent = result == undefined ? null : result const currentParents = Utils.stripNulls( toReparent.map((view) => MetadataUtils.getParent(editorState.jsxMetadata, view)), ) let parentSupportsChild = true if (possibleNewParent != null) { parentSupportsChild = MetadataUtils.targetSupportsChildren( editorState.jsxMetadata, possibleNewParent, ) } else { // a null template path means Canvas, let's translate that to the storyboard component const storyboardComponent = getStoryboardElementPathFromEditorState(editorState) return { shouldReparent: storyboardComponent != null, newParent: storyboardComponent, } } if ( parentSupportsChild && ((currentParents.length === 0 && possibleNewParent != null) || (currentParents.length > 0 && currentParents.every((parent) => !EP.pathsEqual(possibleNewParent, parent.elementPath)))) ) { return { shouldReparent: true, newParent: possibleNewParent, } } else { return { shouldReparent: false, newParent: null, } } } export interface MoveTemplateResult { updatedEditorState: EditorState newPath: ElementPath | null } export function getFrameChange( target: ElementPath, newFrame: CanvasRectangle, isParentFlex: boolean, ): PinOrFlexFrameChange { if (isParentFlex) { return flexResizeChange(target, 'flexBasis', 0) // KILLME } else { return pinFrameChange(target, newFrame, null) } } function editorReparentNoStyleChange( target: ElementPath, indexPosition: IndexPosition, newParentPath: ElementPath, editor: EditorState, ): EditorState { // this code structure with the two withUnderlyingTargetFromEditorStates is copied verbatim from canvas-utils.ts@moveTemplate return withUnderlyingTargetFromEditorState( target, editor, editor, (underlyingElementSuccess, underlyingElement, underlyingTarget, underlyingFilePath) => { return withUnderlyingTargetFromEditorState( newParentPath, editor, editor, ( newParentSuccess, underlyingNewParentElement, underlyingNewParentPath, underlyingNewParentFilePath, ) => { const utopiaComponentsIncludingScenes = getUtopiaJSXComponentsFromSuccess( newParentSuccess, ) const updatedUnderlyingElement = findElementAtPath( underlyingTarget, utopiaComponentsIncludingScenes, ) if (updatedUnderlyingElement == null) { return editor } // Remove and then insert again at the new location. return modifyParseSuccessAtPath(underlyingNewParentFilePath, editor, (workingSuccess) => { let updatedUtopiaComponents: UtopiaJSXComponent[] = [] updatedUtopiaComponents = removeElementAtPath( underlyingTarget, utopiaComponentsIncludingScenes, ) updatedUtopiaComponents = insertElementAtPath( editor.projectContents, editor.canvas.openFile?.filename ?? null, underlyingNewParentPath, updatedUnderlyingElement, updatedUtopiaComponents, indexPosition, ) return { ...workingSuccess, topLevelElements: applyUtopiaJSXComponentsChanges( workingSuccess.topLevelElements, updatedUtopiaComponents, ), } }) }, ) }, ) } export function editorMultiselectReparentNoStyleChange( targets: ElementPath[], indexPosition: IndexPosition, newParentPath: ElementPath, editor: EditorState, ): EditorState { return targets.reduce<EditorState>((workingEditor, target) => { return editorReparentNoStyleChange(target, indexPosition, newParentPath, workingEditor) }, editor) } export function moveTemplate( target: ElementPath, originalPath: ElementPath, newFrame: CanvasRectangle | typeof SkipFrameChange | null, indexPosition: IndexPosition, newParentPath: ElementPath | null, parentFrame: CanvasRectangle | null, editorState: EditorState, componentMetadata: ElementInstanceMetadataMap, selectedViews: Array<ElementPath>, highlightedViews: Array<ElementPath>, newParentLayoutSystem: SettableLayoutSystem | null, newParentMainAxis: 'horizontal' | 'vertical' | null, ): MoveTemplateResult { function noChanges(): MoveTemplateResult { return { updatedEditorState: editorState, newPath: target, } } let newIndex: number = 0 let newPath: ElementPath | null = null let flexContextChanged: boolean = false const targetID = EP.toUid(target) if (newParentPath == null) { // TODO Scene Implementation return noChanges() } else { return withUnderlyingTargetFromEditorState( target, editorState, noChanges(), (underlyingElementSuccess, underlyingElement, underlyingTarget, underlyingFilePath) => { return withUnderlyingTargetFromEditorState( newParentPath, editorState, noChanges(), ( newParentSuccess, underlyingNewParentElement, underlyingNewParentPath, underlyingNewParentFilePath, ) => { const utopiaComponentsIncludingScenes = getUtopiaJSXComponentsFromSuccess( newParentSuccess, ) const { components: withLayoutUpdatedForNewContext, componentMetadata: withMetadataUpdatedForNewContext, didSwitch, toast, } = maybeSwitchLayoutProps( target, originalPath, newParentPath, componentMetadata, componentMetadata, utopiaComponentsIncludingScenes, parentFrame, newParentLayoutSystem, newParentMainAxis, ) const updatedUnderlyingElement = findElementAtPath( underlyingTarget, withLayoutUpdatedForNewContext, ) if (updatedUnderlyingElement == null) { return noChanges() } else { let workingEditorState: EditorState = editorState let updatedUtopiaComponents: Array<UtopiaJSXComponent> = withLayoutUpdatedForNewContext flexContextChanged = flexContextChanged || didSwitch // Remove and then insert again at the new location. workingEditorState = modifyParseSuccessAtPath( underlyingNewParentFilePath, workingEditorState, (workingSuccess) => { updatedUtopiaComponents = removeElementAtPath( underlyingTarget, updatedUtopiaComponents, ) updatedUtopiaComponents = insertElementAtPath( workingEditorState.projectContents, workingEditorState.canvas.openFile?.filename ?? null, underlyingNewParentPath, updatedUnderlyingElement, updatedUtopiaComponents, indexPosition, ) return { ...workingSuccess, topLevelElements: applyUtopiaJSXComponentsChanges( workingSuccess.topLevelElements, updatedUtopiaComponents, ), } }, ) // Validate the result of the re-insertion. if (newParentPath == null) { newIndex = updatedUtopiaComponents.findIndex( (exported) => exported.rootElement === updatedUnderlyingElement, ) if (newIndex === -1) { throw new Error('Invalid root element index.') } } else { // Can't rely on underlyingNewParentElement as that will now be out of date. const updatedUnderlyingNewParentElement = forceNotNull( 'Element should exist', findJSXElementAtPath(underlyingNewParentPath, updatedUtopiaComponents), ) newIndex = updatedUnderlyingNewParentElement.children.indexOf( updatedUnderlyingElement, ) if (newIndex === -1) { throw new Error('Invalid child element index.') } } newPath = EP.appendToPath(newParentPath, targetID) let updatedComponentMetadata: ElementInstanceMetadataMap = withMetadataUpdatedForNewContext // Need to make these changes ahead of updating the frame. const elementMetadata = MetadataUtils.findElementByElementPath( updatedComponentMetadata, target, ) if (elementMetadata != null) { const elementMetadataWithNewPath: ElementInstanceMetadata = { ...elementMetadata, elementPath: newPath, } updatedComponentMetadata = MetadataUtils.removeElementMetadataChild( target, updatedComponentMetadata, ) updatedComponentMetadata = MetadataUtils.insertElementMetadataChild( newParentPath, elementMetadataWithNewPath, updatedComponentMetadata, ) } workingEditorState.jsxMetadata = updatedComponentMetadata if ( newFrame !== SkipFrameChange && newFrame != null && newPath != null && !flexContextChanged ) { const isParentFlex = MetadataUtils.isParentYogaLayoutedContainerAndElementParticipatesInLayout( originalPath, componentMetadata, ) const frameChanges: Array<PinOrFlexFrameChange> = [ getFrameChange(newPath, newFrame, isParentFlex), ] workingEditorState = updateFramesOfScenesAndComponents( workingEditorState, frameChanges, parentFrame, ) } const newSelectedViews = selectedViews.map((v) => { if (EP.pathsEqual(v, target)) { return newPath } else { return v } }) const newHighlightedViews = newParentPath == null ? highlightedViews.map((t) => (EP.pathsEqual(t, target) ? newPath : t)) : [newParentPath] const updatedEditorState: EditorState = { ...workingEditorState, selectedViews: Utils.stripNulls(newSelectedViews), highlightedViews: Utils.stripNulls(newHighlightedViews), toasts: uniqToasts([...workingEditorState.toasts, ...toast]), } return { updatedEditorState: updatedEditorState, newPath: newPath, } } }, ) }, ) } } function preventAnimationsOnTargets(editorState: EditorState, targets: ElementPath[]): EditorState { let workingEditorState = editorState Utils.fastForEach(targets, (target) => { const staticPath = EP.dynamicPathToStaticPath(target) if (staticPath != null) { workingEditorState = modifyUnderlyingForOpenFile( staticPath, editorState, (underlyingElement) => { const styleUpdated = setJSXValuesAtPaths(underlyingElement.props, [ { path: PP.create(['style', 'transition']), value: jsxAttributeValue('none', emptyComments), }, ]) return foldEither( () => underlyingElement, (updatedProps) => { return { ...underlyingElement, props: updatedProps, } }, styleUpdated, ) }, ) } }) return workingEditorState } function produceMoveTransientCanvasState( previousCanvasTransientSelectedViews: Array<ElementPath>, editorState: EditorState, dragState: MoveDragState, preventAnimations: boolean, ): TransientCanvasState { let selectedViews: Array<ElementPath> = dragState.draggedElements let originalFrames: Array<CanvasFrameAndTarget> = dragState.originalFrames let elementsToTarget = determineElementsToOperateOnForDragging( selectedViews, editorState.jsxMetadata, true, false, ) let workingEditorState: EditorState = editorState if (preventAnimations) { // We don't want animations included in the transient state, except for the case where we're about to apply that to the final state workingEditorState = preventAnimationsOnTargets(workingEditorState, elementsToTarget) } if (dragState.reparent) { const reparentTarget = getReparentTarget( previousCanvasTransientSelectedViews, workingEditorState, elementsToTarget, dragState.canvasPosition, ) if (reparentTarget.shouldReparent) { elementsToTarget = elementsToTarget.map((target) => { const frame = originalFrames.find((originalFrameAndTarget) => { return EP.pathsEqual(originalFrameAndTarget.target, target) })?.frame const reparentResult = moveTemplate( target, target, frame ?? null, { type: 'front' }, reparentTarget.newParent, null, workingEditorState, workingEditorState.jsxMetadata, selectedViews, workingEditorState.highlightedViews, null, null, ) selectedViews = reparentResult.updatedEditorState.selectedViews // As it has moved, we need to synchronise the paths. originalFrames = originalFrames.map((originalFrame) => { if (reparentResult.newPath != null && EP.pathsEqual(originalFrame.target, target)) { return { ...originalFrame, target: reparentResult.newPath, } } else { return originalFrame } }) workingEditorState = reparentResult.updatedEditorState return reparentResult.newPath ?? target }) } } else if (dragState.duplicate) { const parentTarget = MetadataUtils.getDuplicationParentTargets(selectedViews) const duplicateResult = duplicate(elementsToTarget, parentTarget, workingEditorState) if (duplicateResult != null) { workingEditorState = duplicateResult.updatedEditorState selectedViews = duplicateResult.updatedEditorState.selectedViews if (duplicateResult.originalFrames != null) { originalFrames = duplicateResult.originalFrames } } } const moveGuidelines = collectParentAndSiblingGuidelines( workingEditorState.jsxMetadata, selectedViews, ) const framesAndTargets = dragComponent( workingEditorState.jsxMetadata, selectedViews, originalFrames, moveGuidelines, dragState.dragSelectionBoundingBox, dragState.drag, Utils.defaultIfNull(Utils.zeroPoint as CanvasPoint, dragState.drag), dragState.enableSnapping, dragState.constrainDragAxis, workingEditorState.canvas.scale, ) workingEditorState = updateFramesOfScenesAndComponents(workingEditorState, framesAndTargets, null) let transientFilesState: TransientFilesState = {} for (const elementToTarget of elementsToTarget) { forUnderlyingTargetFromEditorState( elementToTarget, workingEditorState, (success, underlyingElement, underlyingTarget, underlyingFilePath) => { transientFilesState[underlyingFilePath] = { topLevelElementsIncludingScenes: success.topLevelElements, imports: success.imports, } return success }, ) } return transientCanvasState( selectedViews, workingEditorState.highlightedViews, transientFilesState, workingEditorState.toasts, // TODO Filter for relevant toasts ) } export function getCanvasOffset( previousOffset: CanvasPoint, previousScale: number, scale: number, componentMetadata: ElementInstanceMetadataMap, selectedViews: ElementPath[], focusPoint: CanvasPoint | null, isFirstLoad: boolean, ): CanvasPoint { // TODO HACK getting the canvas element's size here, this should probably go away once we manage the size of the panes const canvasDiv = document.getElementById('canvas-root') const pinFocusPointOnScreen = focusPoint != null const canvasDivSize = canvasDiv == null ? null : canvasDiv.getBoundingClientRect() if (canvasDivSize != null && canvasDivSize.width !== 0 && canvasDivSize.height !== 0) { const zoomFocusPoint = focusPoint ?? focusPointForZoom( selectedViews, scale, previousScale, componentMetadata, previousOffset, canvasDivSize, ) const centerOffset = Utils.scaleVector( { x: canvasDivSize.width / 2, y: canvasDivSize.height / 2, } as CanvasPoint, 1 / scale, ) const offsetFocusPoint = Utils.pointDifference(centerOffset, zoomFocusPoint) if (!pinFocusPointOnScreen) { return Utils.negate(offsetFocusPoint) } else { // we need to shift the new offset by the distance of the new canvas center and the focus point const currentVisibleCenter = Utils.offsetPoint( Utils.scaleVector( { x: canvasDivSize.width / 2, y: canvasDivSize.height / 2, } as CanvasPoint, 1 / previousScale, ), Utils.negate(previousOffset), ) const focusPointFromVisibleCenter = Utils.pointDifference( currentVisibleCenter, zoomFocusPoint, ) const differenceVectorInNewScale = Utils.scaleVector( focusPointFromVisibleCenter, previousScale / scale, ) return Utils.negate(Utils.pointDifference(differenceVectorInNewScale, offsetFocusPoint)) } } else { if (isFirstLoad) { // Attempt to focus on something to prevent the user opening up a barren wasteland of a canvas const defaultOffset = { x: 20, y: 60 } const selectedView = selectedViews[0] if (selectedView == null) { return defaultOffset as CanvasPoint } else { const frame = MetadataUtils.getFrameInCanvasCoords(selectedView, componentMetadata) if (frame == null) { return defaultOffset as CanvasPoint } else { return { x: frame.x + defaultOffset.x, y: frame.y + defaultOffset.y, } as CanvasPoint } } } else { return previousOffset } } } export function focusPointForZoom( selectedViews: Array<ElementPath>, scale: number, previousScale: number, componentMetadata: ElementInstanceMetadataMap, canvasOffset: CanvasPoint, canvasDivSize: ClientRect, ): CanvasPoint { if (selectedViews.length > 0) { const accumulatedPoint = selectedViews.reduce((working, selectedView) => { const frame = MetadataUtils.getFrameInCanvasCoords(selectedView, componentMetadata) if (frame == null) { return working } else { return { x: working.x + (frame.x + frame.width / 2), y: working.y + (frame.y + frame.height / 2), } } }, Utils.zeroPoint) return { x: accumulatedPoint.x / selectedViews.length, y: accumulatedPoint.y / selectedViews.length, } as CanvasPoint } else { return { x: ((canvasDivSize.width / 2) * 1) / previousScale - canvasOffset.x, y: ((canvasDivSize.height / 2) * 1) / previousScale - canvasOffset.y, } as CanvasPoint } } export interface DuplicateResult { updatedEditorState: EditorState originalFrames: Array<CanvasFrameAndTarget> | null } export function duplicate( paths: Array<ElementPath>, newParentPath: ElementPath | null, editor: EditorState, ): DuplicateResult | null { let duplicateNewUIDs: Array<DuplicateNewUID> = [] let newOriginalFrames: Array<CanvasFrameAndTarget> | null = null if ( editor.canvas.dragState != null && editor.canvas.dragState.type === 'MOVE_DRAG_STATE' && editor.canvas.dragState.duplicateNewUIDs != null ) { duplicateNewUIDs = editor.canvas.dragState.duplicateNewUIDs newOriginalFrames = editor.canvas.dragState.originalFrames } let newSelectedViews: Array<ElementPath> = [] let workingEditorState: EditorState = editor const existingIDs = getAllUniqueUids(editor.projectContents) for (const path of paths) { let metadataUpdate: (metadata: ElementInstanceMetadataMap) => ElementInstanceMetadataMap = ( metadata, ) => metadata workingEditorState = modifyUnderlyingForOpenFile( path, workingEditorState, (elem) => elem, (success, underlyingInstancePath, underlyingFilePath) => { let utopiaComponents = getUtopiaJSXComponentsFromSuccess(success) let newElement: JSXElementChild | null = null let jsxElement: JSXElementChild | null = findElementAtPath( underlyingInstancePath, utopiaComponents, ) let uid: string if (jsxElement == null) { console.warn(`Could not find element ${EP.toVarSafeComponentId(path)}`) return success } else { const duplicateNewUID: DuplicateNewUID | undefined = duplicateNewUIDs.find((entry) => EP.pathsEqual(entry.originalPath, path), ) if (duplicateNewUID === undefined) { newElement = guaranteeUniqueUids([jsxElement], existingIDs)[0] uid = getUtopiaID(newElement) } else { // Helps to keep the model consistent because otherwise the dom walker // goes into a frenzy. newElement = setUtopiaID(jsxElement, duplicateNewUID.newUID) if (isJSXElement(newElement)) { newElement = { ...newElement, children: guaranteeUniqueUids(newElement.children, [ ...existingIDs, duplicateNewUID.newUID, ]), } } uid = duplicateNewUID.newUID } let newPath: ElementPath if (newParentPath == null) { const storyboardUID = Utils.forceNotNull( 'Could not find storyboard element', getStoryboardUID(utopiaComponents), ) newPath = EP.elementPath([[storyboardUID, uid]]) } else { newPath = EP.appendToPath(newParentPath, uid) } // Update the original frames to be the duplicate ones. if (newOriginalFrames != null && newPath != null) { newOriginalFrames = newOriginalFrames.map((originalFrame) => { if (EP.pathsEqual(originalFrame.target, path)) { return { frame: originalFrame.frame, target: newPath as ElementPath, } } else { return originalFrame } }) } utopiaComponents = insertElementAtPath( workingEditorState.projectContents, workingEditorState.canvas.openFile?.filename ?? null, newParentPath, newElement, utopiaComponents, null, ) if (newElement == null) { console.warn(`Could not duplicate ${EP.toVarSafeComponentId(path)}`) return success } else { newSelectedViews.push(newPath) // duplicating and inserting the metadata to ensure we're not working with stale metadata // this is used for drag + duplicate on the canvas const nonNullNewElement: JSXElementChild = newElement metadataUpdate = (metadata) => MetadataUtils.duplicateElementMetadataAtPath( path, newPath, right(nonNullNewElement), metadata, ) return { ...success, topLevelElements: applyUtopiaJSXComponentsChanges( success.topLevelElements, utopiaComponents, ), } } } }, ) workingEditorState = { ...workingEditorState, jsxMetadata: metadataUpdate(workingEditorState.jsxMetadata), } } return { updatedEditorState: { ...workingEditorState, selectedViews: newSelectedViews, }, originalFrames: newOriginalFrames, } } export function reorderComponent( projectContents: ProjectContentTreeRoot, openFile: string | null, components: Array<UtopiaJSXComponent>, target: ElementPath, newIndex: number, ): Array<UtopiaJSXComponent> { let workingComponents = [...components] const parentPath = EP.parentPath(target) const jsxElement = findElementAtPath(target, workingComponents) if (jsxElement != null) { const newPosition: IndexPosition = { type: 'absolute', index: newIndex, } workingComponents = removeElementAtPath(target, workingComponents) workingComponents = insertElementAtPath( projectContents, openFile, parentPath, jsxElement, workingComponents, newPosition, ) } return workingComponents } export interface GetParseSuccessOrTransientResult { topLevelElements: Array<TopLevelElement> imports: Imports jsxFactoryFunction: string | null combinedTopLevelArbitraryBlock: ArbitraryJSBlock | null highlightBounds: HighlightBoundsForUids | null exportsDetail: ExportsDetail } const EmptyResult: GetParseSuccessOrTransientResult = { topLevelElements: [], imports: {}, jsxFactoryFunction: null, combinedTopLevelArbitraryBlock: null, highlightBounds: null, exportsDetail: [], } export function getParseSuccessOrTransientForFilePath( filePath: string, projectContents: ProjectContentTreeRoot, transientFilesState: TransientFilesState | null, ): GetParseSuccessOrTransientResult { const projectFile = getContentsTreeFileFromString(projectContents, filePath) if (isTextFile(projectFile) && isParseSuccess(projectFile.fileContents.parsed)) { const parseSuccess = projectFile.fileContents.parsed const targetTransientFileState: TransientFileState | null = transientFilesState == null ? null : transientFilesState[filePath] ?? null if (targetTransientFileState == null) { return { topLevelElements: parseSuccess.topLevelElements, imports: parseSuccess.imports, jsxFactoryFunction: parseSuccess.jsxFactoryFunction, combinedTopLevelArbitraryBlock: parseSuccess.combinedTopLevelArbitraryBlock, highlightBounds: parseSuccess.highlightBounds, exportsDetail: parseSuccess.exportsDetail, } } else { return { topLevelElements: targetTransientFileState.topLevelElementsIncludingScenes, imports: targetTransientFileState.imports, jsxFactoryFunction: parseSuccess.jsxFactoryFunction, combinedTopLevelArbitraryBlock: parseSuccess.combinedTopLevelArbitraryBlock, highlightBounds: parseSuccess.highlightBounds, exportsDetail: parseSuccess.exportsDetail, } } } else { return EmptyResult } } export function getValidElementPaths( focusedElementPath: ElementPath | null, topLevelElementName: string, instancePath: ElementPath, projectContents: ProjectContentTreeRoot, filePath: string, transientFilesState: TransientFilesState | null, resolve: (importOrigin: string, toImport: string) => Either<string, string>, ): Array<ElementPath> { const { topLevelElements, imports } = getParseSuccessOrTransientForFilePath( filePath, projectContents, transientFilesState, ) const importSource = importedFromWhere(filePath, topLevelElementName, topLevelElements, imports) if (importSource != null) { let originTopLevelName = getTopLevelName(importSource, topLevelElementName) const resolvedImportSource = resolve(filePath, importSource.filePath) if (isRight(resolvedImportSource)) { const resolvedFilePath = resolvedImportSource.value const { topLevelElements: resolvedTopLevelElements, exportsDetail, } = getParseSuccessOrTransientForFilePath( resolvedFilePath, projectContents, transientFilesState, ) // Handle default exports as they may actually be named. if (originTopLevelName == null) { for (const exportDetail of exportsDetail) { if (exportDetail.type === 'EXPORT_DEFAULT_FUNCTION_OR_CLASS') { originTopLevelName = exportDetail.name } } } const topLevelElement = resolvedTopLevelElements.find( (element): element is UtopiaJSXComponent => { return isUtopiaJSXComponent(element) && element.name === originTopLevelName }, ) if (topLevelElement != null) { return getValidElementPathsFromElement( focusedElementPath, topLevelElement.rootElement, instancePath, projectContents, resolvedFilePath, false, true, transientFilesState, resolve, ) } } } return [] } export function getValidElementPathsFromElement( focusedElementPath: ElementPath | null, element: JSXElementChild, parentPath: ElementPath, projectContents: ProjectContentTreeRoot, filePath: string, parentIsScene: boolean, parentIsInstance: boolean, transientFilesState: TransientFilesState | null, resolve: (importOrigin: string, toImport: string) => Either<string, string>, ): Array<ElementPath> { if (isJSXElement(element)) { const isScene = isSceneElement(element, filePath, projectContents) const uid = getUtopiaID(element) const path = parentIsInstance ? EP.appendNewElementPath(parentPath, uid) : EP.appendToPath(parentPath, uid) let paths = [path] fastForEach(element.children, (c) => paths.push( ...getValidElementPathsFromElement( focusedElementPath, c, path, projectContents, filePath, isScene, false, transientFilesState, resolve, ), ), ) const name = getJSXElementNameAsString(element.name) const lastElementPathPart = EP.lastElementPathForPath(path) const matchingFocusedPathPart = focusedElementPath == null || lastElementPathPart == null ? null : EP.pathUpToElementPath(focusedElementPath, lastElementPathPart, 'static-path') const isFocused = parentIsScene || matchingFocusedPathPart != null if (isFocused) { paths = [ ...paths, ...getValidElementPaths( focusedElementPath, name, matchingFocusedPathPart ?? path, projectContents, filePath, transientFilesState, resolve, ), ] } return paths } else if (isJSXArbitraryBlock(element)) { // FIXME: From investigation of https://github.com/concrete-utopia/utopia/issues/1137 // The paths this will generate will only be correct if the elements from `elementsWithin` // are used at the same level at which they're defined. // This will work fine: // export var SameFileApp = (props) => { // const AppAsVariable = App // return <AppAsVariable /> // } // This will not: // export var SameFileApp = (props) => { // const AppAsVariable = App // return <div data-uid='same-file-app-div' style={{ position: 'relative', width: '100%', height: '100%', backgroundColor: '#FFFFFF' }}> // <AppAsVariable /> // </div> // } let paths: Array<ElementPath> = [] fastForEach(Object.values(element.elementsWithin), (e) => paths.push( ...getValidElementPathsFromElement( focusedElementPath, e, parentPath, projectContents, filePath, parentIsScene, parentIsInstance, transientFilesState, resolve, ), ), ) return paths } else if (isJSXFragment(element)) { let paths: Array<ElementPath> = [] fastForEach(Object.values(element.children), (e) => paths.push( ...getValidElementPathsFromElement( focusedElementPath, e, parentPath, projectContents, filePath, parentIsScene, parentIsInstance, transientFilesState, resolve, ), ), ) return paths } else { return [] } } function createCanvasTransientStateFromProperties( editor: EditorState, ): TransientCanvasState | null { if (editor.canvas.transientProperties == null) { return null } else { const updatedEditor = Object.values(editor.canvas.transientProperties).reduce( (working, currentProp) => { return modifyUnderlyingTarget( currentProp.elementPath, Utils.forceNotNull('No open file found', getOpenUIJSFileKey(editor)), working, (element: JSXElement) => { const valuesAtPath = Object.keys(currentProp.attributesToUpdate).map((key) => { return { path: PP.fromString(key), value: currentProp.attributesToUpdate[key], } }) let updatedAttributes = setJSXValuesAtPaths(element.props, valuesAtPath) return foldEither( (_) => element, (updatedProps) => { return { ...element, props: updatedProps, } }, updatedAttributes, ) }, ) }, editor, ) let transientFilesState: TransientFilesState = {} fastForEach(Object.values(editor.canvas.transientProperties) ?? [], (prop) => { forUnderlyingTargetFromEditorState( prop.elementPath, updatedEditor, (success, underlyingElement, underlyingTarget, underlyingFilePath) => { transientFilesState[underlyingFilePath] = { topLevelElementsIncludingScenes: success.topLevelElements, imports: success.imports, } return success }, ) }) return transientCanvasState( updatedEditor.selectedViews, updatedEditor.highlightedViews, transientFilesState, [], ) } } export function getDragStatePositions( dragState: DragState | null, resizeOptions: ResizeOptions, ): DragStatePositions | null { if (dragState == null) { return null } else { switch (dragState.type) { case 'MOVE_DRAG_STATE': case 'INSERT_DRAG_STATE': return dragState case 'RESIZE_DRAG_STATE': return findResizePropertyChange(dragState, resizeOptions) ?? null default: const _exhaustiveCheck: never = dragState throw new Error(`Unhandled drag state type ${JSON.stringify(dragState)}`) } } } export function getDragStateDrag( dragState: DragState | null, resizeOptions: ResizeOptions, ): CanvasPoint | null { return optionalMap((positions) => positions.drag, getDragStatePositions(dragState, resizeOptions)) } export function getDragStateStart( dragState: DragState | null, resizeOptions: ResizeOptions, ): CanvasPoint | null { return optionalMap( (positions) => positions.start, getDragStatePositions(dragState, resizeOptions), ) } export function anyDragStarted(dragState: DragState | null): boolean { if (dragState == null) { return false } else { switch (dragState.type) { case 'MOVE_DRAG_STATE': case 'INSERT_DRAG_STATE': return dragState.start != null case 'RESIZE_DRAG_STATE': return dragState.properties.some((prop) => prop.start != null) default: const _exhaustiveCheck: never = dragState throw new Error(`Unhandled drag state type ${JSON.stringify(dragState)}`) } } } export function anyDragMovement(dragState: DragState | null): boolean { if (dragState == null) { return false } else { switch (dragState.type) { case 'MOVE_DRAG_STATE': case 'INSERT_DRAG_STATE': return dragState.drag != null case 'RESIZE_DRAG_STATE': return dragState.properties.some((prop) => prop.drag != null) default: const _exhaustiveCheck: never = dragState throw new Error(`Unhandled drag state type ${JSON.stringify(dragState)}`) } } } export function getResizeOptions( layoutSystem: 'flex-horizontal' | 'flex-vertical' | 'absolute' | null, controlDirection: 'horizontal' | 'vertical', edge: 'before' | 'after', ): Array<LayoutTargetableProp> { switch (layoutSystem) { case 'flex-horizontal': switch (controlDirection) { case 'horizontal': return ['Height', 'minHeight', 'maxHeight'] case 'vertical': return ['flexBasis', 'flexGrow', 'flexShrink', 'minWidth', 'maxWidth'] default: const _exhaustiveCheck: never = controlDirection throw new Error(`Unhandled control direction ${JSON.stringify(controlDirection)}`) } case 'flex-vertical': switch (controlDirection) { case 'horizontal': return ['flexBasis', 'flexGrow', 'flexShrink', 'minHeight', 'maxHeight'] case 'vertical': return ['Width', 'minWidth', 'maxWidth'] default: const _exhaustiveCheck: never = controlDirection throw new Error(`Unhandled control direction ${JSON.stringify(controlDirection)}`) } case 'absolute': switch (controlDirection) { case 'horizontal': switch (edge) { case 'before': return ['PinnedTop', 'Height', 'marginTop', 'minHeight', 'maxHeight'] case 'after': return ['PinnedBottom', 'Height', 'marginBottom', 'minHeight', 'maxHeight'] default: const _exhaustiveCheck: never = edge throw new Error(`Unhandled control edge ${JSON.stringify(edge)}`) } case 'vertical': switch (edge) { case 'before': return ['PinnedLeft', 'Width', 'marginLeft', 'minWidth', 'maxWidth'] case 'after': return ['PinnedRight', 'Width', 'marginRight', 'minWidth', 'maxWidth'] default: const _exhaustiveCheck: never = edge throw new Error(`Unhandled control edge ${JSON.stringify(edge)}`) } default: const _exhaustiveCheck: never = controlDirection throw new Error(`Unhandled control direction ${JSON.stringify(controlDirection)}`) } case null: switch (controlDirection) { case 'horizontal': switch (edge) { case 'before': return ['Height', 'marginTop', 'minHeight', 'maxHeight'] case 'after': return ['Height', 'marginBottom', 'minHeight', 'maxHeight'] default: const _exhaustiveCheck: never = edge throw new Error(`Unhandled control edge ${JSON.stringify(edge)}`) } case 'vertical': switch (edge) { case 'before': return ['Width', 'marginLeft', 'minWidth', 'maxWidth'] case 'after': return ['Width', 'marginRight', 'minWidth', 'maxWidth'] default: const _exhaustiveCheck: never = edge throw new Error(`Unhandled control edge ${JSON.stringify(edge)}`) } default: const _exhaustiveCheck: never = controlDirection throw new Error(`Unhandled control direction ${JSON.stringify(controlDirection)}`) } default: const _exhaustiveCheck: never = layoutSystem throw new Error(`Unhandled flex direction ${JSON.stringify(layoutSystem)}`) } } export const MoveIntoDragThreshold = 3 export function dragExceededThreshold( canvasPosition: CanvasPoint, dragStart: CanvasPoint, ): boolean { const xDiff = Math.abs(canvasPosition.x - dragStart.x) const yDiff = Math.abs(canvasPosition.y - dragStart.y) return xDiff > MoveIntoDragThreshold || yDiff > MoveIntoDragThreshold } export function getObservableValueForLayoutProp( elementMetadata: ElementInstanceMetadata | null, layoutProp: LayoutTargetableProp, ): unknown { if (elementMetadata == null) { return null } else { switch (layoutProp) { case 'Width': case 'minWidth': case 'maxWidth': return elementMetadata.localFrame?.width case 'Height': case 'minHeight': case 'maxHeight': return elementMetadata.localFrame?.height case 'flexBasis': case 'FlexCrossBasis': case 'flexGrow': case 'flexShrink': const path = createLayoutPropertyPath(layoutProp) return Utils.pathOr(null, PP.getElements(path), elementMetadata.props) case 'marginTop': return elementMetadata.specialSizeMeasurements.margin.top case 'marginBottom': return elementMetadata.specialSizeMeasurements.margin.bottom case 'marginLeft': return elementMetadata.specialSizeMeasurements.margin.left case 'marginRight': return elementMetadata.specialSizeMeasurements.margin.right case 'PinnedLeft': return elementMetadata.localFrame?.x case 'PinnedTop': return elementMetadata.localFrame?.y case 'PinnedRight': return elementMetadata.localFrame == null || elementMetadata.specialSizeMeasurements.coordinateSystemBounds == null ? null : elementMetadata.specialSizeMeasurements.coordinateSystemBounds.width - (elementMetadata.localFrame.width + elementMetadata.localFrame.x) case 'PinnedBottom': return elementMetadata.localFrame == null || elementMetadata.specialSizeMeasurements.coordinateSystemBounds == null ? null : elementMetadata.specialSizeMeasurements.coordinateSystemBounds.height - (elementMetadata.localFrame.height + elementMetadata.localFrame.y) default: const _exhaustiveCheck: never = layoutProp throw new Error(`Unhandled prop ${JSON.stringify(layoutProp)}`) } } }
the_stack
import * as fs from "fs-extra"; import path from "path"; import micromatch from "micromatch"; import { ValidationError } from "@changesets/errors"; import { warn } from "@changesets/logger"; import { Packages } from "@manypkg/get-packages"; import { Config, WrittenConfig, Linked } from "@changesets/types"; import packageJson from "../package.json"; import { getDependentsGraph } from "@changesets/get-dependents-graph"; export let defaultWrittenConfig = { $schema: `https://unpkg.com/@changesets/config@${packageJson.version}/schema.json`, changelog: "@changesets/cli/changelog", commit: false, linked: [] as Linked, access: "restricted", baseBranch: "master", updateInternalDependencies: "patch", ignore: [] as ReadonlyArray<string> } as const; function getNormalisedChangelogOption( thing: false | readonly [string, any] | string ): Config["changelog"] { if (thing === false) { return false; } if (typeof thing === "string") { return [thing, null]; } return thing; } function normalizePackageNames( listOfPackageNamesOrGlob: readonly string[], pkgNames: readonly string[] ): [string[], string[]] { const matchingPackages = micromatch(pkgNames, listOfPackageNamesOrGlob); // Go through the list of given package globs (again) in order to find out // which packages didn't match so that we can show a validation message. const nonExistingPackages = listOfPackageNamesOrGlob.filter( pkgNameOrGlob => !pkgNames.some(pkgName => micromatch.isMatch(pkgName, pkgNameOrGlob)) ); // Since the validation happens in subsequent steps, we need to return a tuple // with the list of non-existing packages. // TODO: refactor the validation logic to exit early when something is not valid. return [matchingPackages, nonExistingPackages]; } // TODO: replace usage with Array.isArray when TS 4.1 gets released // source: https://github.com/microsoft/TypeScript/pull/39258/files#diff-a6b488d9bd802977827b535a3011c1f3R1379 function isArray<T>( arg: T | {} ): arg is T extends readonly any[] ? unknown extends T ? never : readonly any[] : any[] { return Array.isArray(arg); } export let read = async (cwd: string, packages: Packages) => { let json = await fs.readJSON(path.join(cwd, ".changeset", "config.json")); return parse(json, packages); }; export let parse = (json: WrittenConfig, packages: Packages): Config => { let messages = []; let pkgNames: readonly string[] = packages.packages.map( ({ packageJson }) => packageJson.name ); if ( json.changelog !== undefined && json.changelog !== false && typeof json.changelog !== "string" && !( isArray(json.changelog) && json.changelog.length === 2 && typeof json.changelog[0] === "string" ) ) { messages.push( `The \`changelog\` option is set as ${JSON.stringify( json.changelog, null, 2 )} when the only valid values are undefined, a module path(e.g. "@changesets/cli/changelog" or "./some-module") or a tuple with a module path and config for the changelog generator(e.g. ["@changesets/cli/changelog", { someOption: true }])` ); } let normalizedAccess: WrittenConfig["access"] = json.access; if ((json.access as string) === "private") { normalizedAccess = "restricted"; warn( 'The `access` option is set as "private", but this is actually not a valid value - the correct form is "restricted".' ); } if ( normalizedAccess !== undefined && normalizedAccess !== "restricted" && normalizedAccess !== "public" ) { messages.push( `The \`access\` option is set as ${JSON.stringify( normalizedAccess, null, 2 )} when the only valid values are undefined, "public" or "restricted"` ); } if (json.commit !== undefined && typeof json.commit !== "boolean") { messages.push( `The \`commit\` option is set as ${JSON.stringify( json.commit, null, 2 )} when the only valid values are undefined or a boolean` ); } if (json.baseBranch !== undefined && typeof json.baseBranch !== "string") { messages.push( `The \`baseBranch\` option is set as ${JSON.stringify( json.baseBranch, null, 2 )} but the \`baseBranch\` option can only be set as a string` ); } if (json.linked !== undefined) { if ( !( isArray(json.linked) && json.linked.every( arr => Array.isArray(arr) && arr.every(pkgName => typeof pkgName === "string") ) ) ) { messages.push( `The \`linked\` option is set as ${JSON.stringify( json.linked, null, 2 )} when the only valid values are undefined or an array of arrays of package names` ); } else { let foundPkgNames = new Set<string>(); let duplicatedPkgNames = new Set<string>(); for (let linkedGroup of json.linked) { let [ normalizedLinkedGroup, nonExistingPackages ] = normalizePackageNames(linkedGroup, pkgNames); for (let linkedPkgName of normalizedLinkedGroup) { if (foundPkgNames.has(linkedPkgName)) { duplicatedPkgNames.add(linkedPkgName); } foundPkgNames.add(linkedPkgName); } // Show validation message for each non-existing package if (nonExistingPackages.length > 0) { nonExistingPackages.forEach(nonExistingPkgName => { messages.push( `The package or glob expression "${nonExistingPkgName}" specified in the \`linked\` option does not match any package in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.` ); }); } } if (duplicatedPkgNames.size) { duplicatedPkgNames.forEach(pkgName => { messages.push( `The package "${pkgName}" is defined in multiple sets of linked packages. Packages can only be defined in a single set of linked packages. If you are using glob expressions, make sure that they are valid according to https://www.npmjs.com/package/micromatch.` ); }); } } } if ( json.updateInternalDependencies !== undefined && !["patch", "minor"].includes(json.updateInternalDependencies) ) { messages.push( `The \`updateInternalDependencies\` option is set as ${JSON.stringify( json.updateInternalDependencies, null, 2 )} but can only be 'patch' or 'minor'` ); } if (json.ignore) { if ( !( isArray(json.ignore) && json.ignore.every(pkgName => typeof pkgName === "string") ) ) { messages.push( `The \`ignore\` option is set as ${JSON.stringify( json.ignore, null, 2 )} when the only valid values are undefined or an array of package names` ); } else { let [, nonExistingPackages] = normalizePackageNames( json.ignore, pkgNames ); if (nonExistingPackages.length > 0) { nonExistingPackages.forEach(nonExistingPkgName => { messages.push( `The package or glob expression "${nonExistingPkgName}" is specified in the \`ignore\` option but it is not found in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.` ); }); } // Validate that all dependents of ignored packages are listed in the ignore list const dependentsGraph = getDependentsGraph(packages); for (const ignoredPackage of json.ignore) { const dependents = dependentsGraph.get(ignoredPackage) || []; for (const dependent of dependents) { if (!json.ignore.includes(dependent)) { messages.push( `The package "${dependent}" depends on the ignored package "${ignoredPackage}", but "${dependent}" is not being ignored. Please add "${dependent}" to the \`ignore\` option.` ); } } } } } if (json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH !== undefined) { const { onlyUpdatePeerDependentsWhenOutOfRange, updateInternalDependents, useCalculatedVersionForSnapshots } = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH; if ( onlyUpdatePeerDependentsWhenOutOfRange !== undefined && typeof onlyUpdatePeerDependentsWhenOutOfRange !== "boolean" ) { messages.push( `The \`onlyUpdatePeerDependentsWhenOutOfRange\` option is set as ${JSON.stringify( onlyUpdatePeerDependentsWhenOutOfRange, null, 2 )} when the only valid values are undefined or a boolean` ); } if ( updateInternalDependents !== undefined && !["always", "out-of-range"].includes(updateInternalDependents) ) { messages.push( `The \`updateInternalDependents\` option is set as ${JSON.stringify( updateInternalDependents, null, 2 )} but can only be 'always' or 'out-of-range'` ); } if ( useCalculatedVersionForSnapshots !== undefined && typeof useCalculatedVersionForSnapshots !== "boolean" ) { messages.push( `The \`useCalculatedVersionForSnapshots\` option is set as ${JSON.stringify( useCalculatedVersionForSnapshots, null, 2 )} when the only valid values are undefined or a boolean` ); } } if (messages.length) { throw new ValidationError( `Some errors occurred when validating the changesets config:\n` + messages.join("\n") ); } let config: Config = { changelog: getNormalisedChangelogOption( json.changelog === undefined ? defaultWrittenConfig.changelog : json.changelog ), access: normalizedAccess === undefined ? defaultWrittenConfig.access : normalizedAccess, commit: json.commit === undefined ? defaultWrittenConfig.commit : json.commit, linked: json.linked === undefined ? defaultWrittenConfig.linked : json.linked.map( linkedGroup => normalizePackageNames(linkedGroup, pkgNames)[0] ), baseBranch: json.baseBranch === undefined ? defaultWrittenConfig.baseBranch : json.baseBranch, updateInternalDependencies: json.updateInternalDependencies === undefined ? defaultWrittenConfig.updateInternalDependencies : json.updateInternalDependencies, ignore: json.ignore === undefined ? defaultWrittenConfig.ignore : normalizePackageNames(json.ignore, pkgNames)[0], bumpVersionsWithWorkspaceProtocolOnly: json.bumpVersionsWithWorkspaceProtocolOnly === true, ___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH: { onlyUpdatePeerDependentsWhenOutOfRange: json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH === undefined || json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH .onlyUpdatePeerDependentsWhenOutOfRange === undefined ? false : json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH .onlyUpdatePeerDependentsWhenOutOfRange, updateInternalDependents: json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH ?.updateInternalDependents ?? "out-of-range", useCalculatedVersionForSnapshots: json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH === undefined || json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH .useCalculatedVersionForSnapshots === undefined ? false : json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH .useCalculatedVersionForSnapshots } }; return config; }; let fakePackage = { dir: "", packageJson: { name: "", version: "" } }; export let defaultConfig = parse(defaultWrittenConfig, { root: fakePackage, tool: "root", packages: [fakePackage] });
the_stack
'use strict'; import { illegalArgument } from 'vs/base/common/errors'; import * as instantiation from './instantiation'; export class AbstractDescriptor<T> { constructor(private _staticArguments: any[]) { // empty } public appendStaticArguments(more: any[]): void { this._staticArguments.push.apply(this._staticArguments, more); } public staticArguments(): any[]; public staticArguments(nth: number): any; public staticArguments(nth?: number): any[] { if (isNaN(nth)) { return this._staticArguments.slice(0); } else { return this._staticArguments[nth]; } } _validate(type: T): void { if (!type) { throw illegalArgument('can not be falsy'); } } } export class SyncDescriptor<T> extends AbstractDescriptor<T> { constructor(private _ctor: any, ...staticArguments: any[]) { super(staticArguments); } public get ctor(): any { return this._ctor; } protected bind(...moreStaticArguments): SyncDescriptor<T> { let allArgs = []; allArgs = allArgs.concat(this.staticArguments()); allArgs = allArgs.concat(moreStaticArguments); return new SyncDescriptor<T>(this._ctor, ...allArgs); } } export interface CreateSyncFunc { <T>(ctor: instantiation.IConstructorSignature0<T>): SyncDescriptor0<T>; <A1, T>(ctor: instantiation.IConstructorSignature1<A1, T>): SyncDescriptor1<A1, T>; <A1, T>(ctor: instantiation.IConstructorSignature1<A1, T>, a1: A1): SyncDescriptor0<T>; <A1, A2, T>(ctor: instantiation.IConstructorSignature2<A1, A2, T>): SyncDescriptor2<A1, A2, T>; <A1, A2, T>(ctor: instantiation.IConstructorSignature2<A1, A2, T>, a1: A1): SyncDescriptor1<A2, T>; <A1, A2, T>(ctor: instantiation.IConstructorSignature2<A1, A2, T>, a1: A1, a2: A2): SyncDescriptor0<T>; <A1, A2, A3, T>(ctor: instantiation.IConstructorSignature3<A1, A2, A3, T>): SyncDescriptor3<A1, A2, A3, T>; <A1, A2, A3, T>(ctor: instantiation.IConstructorSignature3<A1, A2, A3, T>, a1: A1): SyncDescriptor2<A2, A3, T>; <A1, A2, A3, T>(ctor: instantiation.IConstructorSignature3<A1, A2, A3, T>, a1: A1, a2: A2): SyncDescriptor1<A3, T>; <A1, A2, A3, T>(ctor: instantiation.IConstructorSignature3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): SyncDescriptor0<T>; <A1, A2, A3, A4, T>(ctor: instantiation.IConstructorSignature4<A1, A2, A3, A4, T>): SyncDescriptor4<A1, A2, A3, A4, T>; <A1, A2, A3, A4, T>(ctor: instantiation.IConstructorSignature4<A1, A2, A3, A4, T>, a1: A1): SyncDescriptor3<A2, A3, A4, T>; <A1, A2, A3, A4, T>(ctor: instantiation.IConstructorSignature4<A1, A2, A3, A4, T>, a1: A1, a2: A2): SyncDescriptor2<A3, A4, T>; <A1, A2, A3, A4, T>(ctor: instantiation.IConstructorSignature4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3): SyncDescriptor1<A4, T>; <A1, A2, A3, A4, T>(ctor: instantiation.IConstructorSignature4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor0<T>; <A1, A2, A3, A4, A5, T>(ctor: instantiation.IConstructorSignature5<A1, A2, A3, A4, A5, T>): SyncDescriptor5<A1, A2, A3, A4, A5, T>; <A1, A2, A3, A4, A5, T>(ctor: instantiation.IConstructorSignature5<A1, A2, A3, A4, A5, T>, a1: A1): SyncDescriptor4<A2, A3, A4, A5, T>; <A1, A2, A3, A4, A5, T>(ctor: instantiation.IConstructorSignature5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2): SyncDescriptor3<A3, A4, A5, T>; <A1, A2, A3, A4, A5, T>(ctor: instantiation.IConstructorSignature5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3): SyncDescriptor2<A4, A5, T>; <A1, A2, A3, A4, A5, T>(ctor: instantiation.IConstructorSignature5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor1<A5, T>; <A1, A2, A3, A4, A5, T>(ctor: instantiation.IConstructorSignature5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor0<T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>): SyncDescriptor6<A1, A2, A3, A4, A5, A6, T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, a1: A1): SyncDescriptor5<A2, A3, A4, A5, A6, T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2): SyncDescriptor4<A3, A4, A5, A6, T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3): SyncDescriptor3<A4, A5, A6, T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor2<A5, A6, T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor1<A6, T>; <A1, A2, A3, A4, A5, A6, T>(ctor: instantiation.IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): SyncDescriptor0<T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>): SyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1): SyncDescriptor6<A2, A3, A4, A5, A6, A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2): SyncDescriptor5<A3, A4, A5, A6, A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3): SyncDescriptor4<A4, A5, A6, A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor3<A5, A6, A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor2<A6, A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): SyncDescriptor1<A7, T>; <A1, A2, A3, A4, A5, A6, A7, T>(ctor: instantiation.IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): SyncDescriptor0<T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>): SyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1): SyncDescriptor7<A2, A3, A4, A5, A6, A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2): SyncDescriptor6<A3, A4, A5, A6, A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3): SyncDescriptor5<A4, A5, A6, A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor4<A5, A6, A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor3<A6, A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): SyncDescriptor2<A7, A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): SyncDescriptor1<A8, T>; <A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: instantiation.IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): SyncDescriptor0<T>; } export const createSyncDescriptor: CreateSyncFunc = <T>(ctor: any, ...staticArguments: any[]): any => { return new SyncDescriptor<T>(ctor, ...staticArguments); }; export interface SyncDescriptor0<T> { ctor: any; bind(): SyncDescriptor0<T>; } export interface SyncDescriptor1<A1, T> { ctor: any; bind(a1: A1): SyncDescriptor0<T>; } export interface SyncDescriptor2<A1, A2, T> { ctor: any; bind(a1: A1): SyncDescriptor1<A2, T>; bind(a1: A1, a2: A2): SyncDescriptor0<T>; } export interface SyncDescriptor3<A1, A2, A3, T> { ctor: any; bind(a1: A1): SyncDescriptor2<A2, A3, T>; bind(a1: A1, a2: A2): SyncDescriptor1<A3, T>; bind(a1: A1, a2: A2, a3: A3): SyncDescriptor0<T>; } export interface SyncDescriptor4<A1, A2, A3, A4, T> { ctor: any; bind(a1: A1): SyncDescriptor3<A2, A3, A4, T>; bind(a1: A1, a2: A2): SyncDescriptor2<A3, A4, T>; bind(a1: A1, a2: A2, a3: A3): SyncDescriptor1<A4, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor0<T>; } export interface SyncDescriptor5<A1, A2, A3, A4, A5, T> { ctor: any; bind(a1: A1): SyncDescriptor4<A2, A3, A4, A5, T>; bind(a1: A1, a2: A2): SyncDescriptor3<A3, A4, A5, T>; bind(a1: A1, a2: A2, a3: A3): SyncDescriptor2<A4, A5, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor1<A5, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor0<T>; } export interface SyncDescriptor6<A1, A2, A3, A4, A5, A6, T> { ctor: any; bind(a1: A1): SyncDescriptor5<A2, A3, A4, A5, A6, T>; bind(a1: A1, a2: A2): SyncDescriptor4<A3, A4, A5, A6, T>; bind(a1: A1, a2: A2, a3: A3): SyncDescriptor3<A4, A5, A6, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor2<A5, A6, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor1<A6, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): SyncDescriptor0<T>; } export interface SyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T> { ctor: any; bind(a1: A1): SyncDescriptor6<A2, A3, A4, A5, A6, A7, T>; bind(a1: A1, a2: A2): SyncDescriptor5<A3, A4, A5, A6, A7, T>; bind(a1: A1, a2: A2, a3: A3): SyncDescriptor4<A4, A5, A6, A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor3<A5, A6, A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor2<A6, A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): SyncDescriptor1<A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): SyncDescriptor0<T>; } export interface SyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T> { ctor: any; bind(a1: A1): SyncDescriptor7<A2, A3, A4, A5, A6, A7, A8, T>; bind(a1: A1, a2: A2): SyncDescriptor6<A3, A4, A5, A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3): SyncDescriptor5<A4, A5, A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): SyncDescriptor4<A5, A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): SyncDescriptor3<A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): SyncDescriptor2<A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): SyncDescriptor1<A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): SyncDescriptor0<T>; } export class AsyncDescriptor<T> extends AbstractDescriptor<T> implements AsyncDescriptor0<T> { public static create<T>(moduleName: string, ctorName: string): AsyncDescriptor<T> { return new AsyncDescriptor<T>(moduleName, ctorName); } constructor(private _moduleName: string, private _ctorName?: string, ...staticArguments: any[]) { super(staticArguments); if (typeof _moduleName !== 'string') { throw new Error('Invalid AsyncDescriptor arguments, expected `moduleName` to be a string!'); } } public get moduleName(): string { return this._moduleName; } public get ctorName(): string { return this._ctorName; } bind(...moreStaticArguments): AsyncDescriptor<T> { let allArgs = []; allArgs = allArgs.concat(this.staticArguments()); allArgs = allArgs.concat(moreStaticArguments); return new AsyncDescriptor<T>(this.moduleName, this.ctorName, ...allArgs); } } export interface AsyncDescriptor0<T> { moduleName: string; bind(): AsyncDescriptor0<T>; } export interface AsyncDescriptor1<A1, T> { moduleName: string; bind(a1: A1): AsyncDescriptor0<T>; } export interface AsyncDescriptor2<A1, A2, T> { moduleName: string; bind(a1: A1): AsyncDescriptor1<A2, T>; bind(a1: A1, a2: A2): AsyncDescriptor0<T>; } export interface AsyncDescriptor3<A1, A2, A3, T> { moduleName: string; bind(a1: A1): AsyncDescriptor2<A2, A3, T>; bind(a1: A1, a2: A2): AsyncDescriptor1<A3, T>; bind(a1: A1, a2: A2, a3: A3): AsyncDescriptor0<T>; } export interface AsyncDescriptor4<A1, A2, A3, A4, T> { moduleName: string; bind(a1: A1): AsyncDescriptor3<A2, A3, A4, T>; bind(a1: A1, a2: A2): AsyncDescriptor2<A3, A4, T>; bind(a1: A1, a2: A2, a3: A3): AsyncDescriptor1<A4, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): AsyncDescriptor0<T>; } export interface AsyncDescriptor5<A1, A2, A3, A4, A5, T> { moduleName: string; bind(a1: A1): AsyncDescriptor4<A2, A3, A4, A5, T>; bind(a1: A1, a2: A2): AsyncDescriptor3<A3, A4, A5, T>; bind(a1: A1, a2: A2, a3: A3): AsyncDescriptor2<A4, A5, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): AsyncDescriptor1<A5, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): AsyncDescriptor0<T>; } export interface AsyncDescriptor6<A1, A2, A3, A4, A5, A6, T> { moduleName: string; bind(a1: A1): AsyncDescriptor5<A2, A3, A4, A5, A6, T>; bind(a1: A1, a2: A2): AsyncDescriptor4<A3, A4, A5, A6, T>; bind(a1: A1, a2: A2, a3: A3): AsyncDescriptor3<A4, A5, A6, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): AsyncDescriptor2<A5, A6, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): AsyncDescriptor1<A6, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): AsyncDescriptor0<T>; } export interface AsyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T> { moduleName: string; bind(a1: A1): AsyncDescriptor6<A2, A3, A4, A5, A6, A7, T>; bind(a1: A1, a2: A2): AsyncDescriptor5<A3, A4, A5, A6, A7, T>; bind(a1: A1, a2: A2, a3: A3): AsyncDescriptor4<A4, A5, A6, A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): AsyncDescriptor3<A5, A6, A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): AsyncDescriptor2<A6, A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): AsyncDescriptor1<A7, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): AsyncDescriptor0<T>; } export interface AsyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T> { moduleName: string; bind(a1: A1): AsyncDescriptor7<A2, A3, A4, A5, A6, A7, A8, T>; bind(a1: A1, a2: A2): AsyncDescriptor6<A3, A4, A5, A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3): AsyncDescriptor5<A4, A5, A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4): AsyncDescriptor4<A5, A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): AsyncDescriptor3<A6, A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): AsyncDescriptor2<A7, A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): AsyncDescriptor1<A8, T>; bind(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): AsyncDescriptor0<T>; }
the_stack
import deepEqual from 'deep-equal'; import * as fs from 'fs'; import { getElementCategory, getSignatureDoc, printStats } from './common'; // -------------------------------------------------- // Main Logic // -------------------------------------------------- const oldApiFile = process.argv[2]; const newApiFile = process.argv[3]; const newApiData = JSON.parse(fs.readFileSync(newApiFile, 'utf-8')); const oldApiData = JSON.parse(fs.readFileSync(oldApiFile, 'utf-8')); console.log(`Comparing public API between:`); console.log(`old: ${oldApiFile}, ${oldApiData.length} entries`); console.log(`new: ${newApiFile}, ${newApiData.length} entries`); const breakingChanges: any[] = []; oldApiData.forEach((oldApiElement: any) => { const newApiElementMatch = findElementInApi(newApiData, oldApiElement); if (newApiElementMatch) { // compare elements for more possible differences const elementBreakingChanges = compareElements( oldApiElement, newApiElementMatch ); if (elementBreakingChanges?.length > 0) { addBreakingChanges(oldApiElement, elementBreakingChanges); breakingChanges.push(oldApiElement); } } else { // Old Element is not in new api // Was it moved? const newApiElementMoved = findMovedElementInApi(newApiData, oldApiElement); if (newApiElementMoved) { // element was moved oldApiElement.isMoved = true; oldApiElement.newName = ''; oldApiElement.newEntryPoint = newApiElementMoved.entryPoint; (oldApiElement.newNamespace = newApiElementMoved.namespace ?? ''), addBreakingChanges(oldApiElement, [ { ...getChangeDesc(oldApiElement, 'MOVED'), to: { entryPoint: newApiElementMoved.entryPoint, namespace: newApiElementMoved.namespace ?? '', }, }, ]); const elementBreakingChanges = compareElements( oldApiElement, newApiElementMoved ); if (elementBreakingChanges?.length > 0) { addBreakingChanges(oldApiElement, elementBreakingChanges); } } else { // it is removed oldApiElement.isDeleted = true; oldApiElement.deletedComment = `${oldApiElement.kind} ${ oldApiElement.namespace ? oldApiElement.namespace + '.' : '' }${ oldApiElement.name } has been removed and is no longer part of the public API.`; oldApiElement.migrationComment = ''; addBreakingChanges(oldApiElement, [ { ...getChangeDesc(oldApiElement, 'DELETED'), }, ]); } breakingChanges.push(oldApiElement); } }); printStats(breakingChanges); fs.writeFileSync(`data/breaking-changes.json`, JSON.stringify(breakingChanges)); // -------------------------------------------------- // Functions // -------------------------------------------------- function findElementInApi(apiData: Array<any>, elementToFind: any): any { return apiData.find((apiDataElement) => { return ( apiDataElement.name === elementToFind.name && apiDataElement.kind === elementToFind.kind && apiDataElement.entryPoint === elementToFind.entryPoint && apiDataElement.namespace === elementToFind.namespace ); }); } function findMovedElementInApi(apiData: Array<any>, elementToFind: any): any { return apiData.find((apiDataElement) => { return ( apiDataElement.name === elementToFind.name && apiDataElement.kind === elementToFind.kind && // This logic could be case by case. // With cart-lib epic, we have multiple classes that // moved to both entry points and namespace // However, we don't want to have false moves with // the model interfaces that have no namespace, but // all have a counterpart in the 'Occ' namespace. (elementToFind.namespace ? true : apiDataElement.namespace === elementToFind.namespace) ); }); } function compareElements(oldElement: any, newElement: any): any[] { switch (oldElement.kind) { case 'Interface': case 'Class': { return getMembersBreakingChange(oldElement, newElement); } case 'Enum': { return getEnumBreakingChange(oldElement, newElement); } case 'TypeAlias': { return getTypeAliasBreakingChange(oldElement, newElement); } case 'Variable': { return getVariableBreakingChange(oldElement, newElement); } case 'Function': { return getFunctionBreakingChange(oldElement, newElement); } case 'Namespace': { return []; } default: { throw Error(`Compare unsupported for element kind ${oldElement.kind}.`); } } } function getVariableBreakingChange(oldElement: any, newElement: any): any[] { if (oldElement.type !== newElement.type) { return [ { ...getChangeDesc(oldElement, 'CHANGED'), oldType: oldElement.type, newType: newElement.type, previousStateDoc: `${oldElement.name}: ${oldElement.type}`, currentStateDoc: `${newElement.name}: ${newElement.type}`, }, ]; } else { return []; } } function getTypeAliasBreakingChange(oldElement: any, newElement: any): any[] { if (!deepEqual(oldElement.members, newElement.members)) { return [ { ...getChangeDesc(oldElement, 'CHANGED'), previousStateDoc: oldElement.members.join(',\n'), currentStateDoc: newElement.members.join(',\n'), new: newElement.members, }, ]; } else { return []; } } function getFunctionBreakingChange(oldElement: any, newElement: any): any[] { const paramBreakingChanges = getParametersBreakingChange( oldElement, newElement ); const returnTypeChanged = oldElement.returnType !== newElement.returnType; if (paramBreakingChanges.length > 0 || returnTypeChanged) { const oldElementCopy = { ...oldElement }; delete oldElementCopy.breakingChanges; // avoid circular references const newElementCopy = { ...newElement }; delete newElementCopy.breakingChanges; // avoid circular references return [ { ...getChangeDesc(oldElement, 'CHANGED'), previousStateDoc: getSignatureDoc(oldElement), currentStateDoc: getSignatureDoc(newElement), oldElement: oldElementCopy, newElement: newElementCopy, }, ]; } else { return []; } } function getMembersBreakingChange( oldApiElement: any, newApiElementMatch: any ): any[] { const breakingChanges = []; oldApiElement.members.forEach((oldMember: any) => { let newMember = findMatchingMember(newApiElementMatch, oldMember); if (!newMember && oldMember.kind === 'Constructor') { newMember = getConstructorIfUnique(newApiElementMatch); } if (!newMember) { breakingChanges.push({ ...getChangeDesc(oldMember, 'DELETED'), isDeletedMember: true, deletedMember: oldMember, apiElementName: oldApiElement.name, apiElementKind: oldApiElement.kind, entryPoint: oldApiElement.entryPoint, deletedComment: `// TODO:Spartacus - ${oldMember.kind} '${oldMember.name}' was removed from ${oldApiElement.kind} '${oldApiElement.name}'.`, migrationComment: '', }); } else { breakingChanges.push(...getMemberBreakingChange(oldMember, newMember)); } }); return breakingChanges; } function getConstructorIfUnique(newApiElement: any): any { const constructors = newApiElement.members.filter( (member: any) => member.kind === 'Constructor' ); if (constructors?.length === 1) { return constructors[0]; } else { return undefined; } } function getMemberBreakingChange(oldMember: any, newMember: any): any[] { switch (oldMember.kind) { case 'Constructor': { return getParametersBreakingChange(oldMember, newMember); } case 'IndexSignature': case 'MethodSignature': case 'Method': { return getFunctionBreakingChange(oldMember, newMember); } case 'PropertySignature': case 'Property': { return getVariableBreakingChange(oldMember, newMember); } default: { throw Error( `Unsupported member kind for compare ${oldMember.kind} in ${oldMember.name}` ); } } } function getParametersBreakingChange(oldMember: any, newMember: any): any[] { if (!oldMember?.parameters && !newMember?.parameters) { return []; } const parametersHaveBreakingChange = isParametersBreakingChangeDetected( oldMember.parameters, newMember.parameters ); if (parametersHaveBreakingChange) { const removedParams: any[] = paramDiff(oldMember, newMember); const addedParams: any[] = paramDiff(newMember, oldMember); return [ { ...getChangeDesc(oldMember, 'CHANGED'), previousStateDoc: getSignatureDoc(oldMember), currentStateDoc: getSignatureDoc(newMember), details: { kind: oldMember.kind, name: oldMember.name, oldParams: oldMember.parameters, newParams: newMember.parameters, removedParams, addedParams, }, }, ]; } else { return []; } } function isParametersBreakingChangeDetected( oldParameters: any[], newParameters: any[] ): boolean { // Removed params is a breaking change if (oldParameters.length > newParameters.length) { return true; } // Were parameter(s) added? // If they are not optional, it's a breaking change if (oldParameters.length < newParameters.length) { const extraParams = newParameters.slice(oldParameters.length); if (!extraParams.every((param: any) => param.isOptional)) { return true; } } // Detect changes in the existing parameters. for (let index = 0; index < oldParameters.length; index++) { if (!isSameTypeParameter(oldParameters[index], newParameters[index])) { return true; } } return false; } function paramDiff(oldMember: any, newMember: any): any[] { return oldMember.parameters.filter( (oldParameter: any) => !newMember.parameters.find((newParameter: any) => isIdenticalParams(oldParameter, newParameter) ) ); } function isIdenticalParams(oldParam: any, newParam: any) { return oldParam.name === newParam?.name && oldParam.type === newParam?.type; } function isSameTypeParameter(oldParam: any, newParam: any) { return oldParam.type === newParam?.type; } function addBreakingChanges(element: any, breakingChanges: any[]) { if (!breakingChanges) { return; } if (breakingChanges.length === 0) { return; } if (!element.breakingChanges) { element.breakingChanges = []; } breakingChanges = addBreakingChangeContext(element, breakingChanges); element.breakingChanges.push(...breakingChanges); } function addBreakingChangeContext(apiElement: any, breakingChanges: any[]) { return breakingChanges.map((breakingChange: any) => { breakingChange.topLevelApiElementName = apiElement.name; breakingChange.entryPoint = apiElement.entryPoint; return breakingChange; }); } function findMatchingMember(newApiElement: any, oldMember: any) { return newApiElement.members.find( (member: any) => member.name === oldMember.name && member.kind === oldMember.kind && member?.overloadIndex === oldMember?.overloadIndex ); } function getEnumBreakingChange(oldElement: any, newElement: any): any[] { if (isEnumValueRemoved(oldElement.members, newElement.members)) { return [ { ...getChangeDesc(oldElement, 'CHANGED'), previousStateDoc: oldElement.members.join(',\n'), currentStateDoc: newElement.members.join(',\n'), old: oldElement.members, new: newElement.members, }, ]; } else { return []; } } function isEnumValueRemoved(oldMembers: any[], newMembers: any[]): boolean { return !oldMembers.every((oldMember: any) => { return newMembers.some((newMember: any) => newMember === oldMember); }); } function getChangeName(elementKind: string, changeType: string) { return `${elementKind.toUpperCase()}_${changeType}`; } function getChangeDesc(element: any, changeType: string): any { return { change: getChangeName(element.kind, changeType), changeType, changeKind: element.kind, changeLabel: getChangeLabel(changeType), changeElementName: element.name, changeElementCategory: getElementCategory(element), }; } function getChangeLabel(changeType: string): string { let label = changeType.toLowerCase(); return label.replace(/_/g, ' '); }
the_stack
export enum QueryType { Single = 1, KV = 2, AllKV = 3, Range = 4, StaticRange = 5, } export enum ResultType { // Raw = 0, Single = 1, KV = 2, Range = 4, } // export type QueryType = 'single' | 'allkv' | 'kv' | 'range' | 'static range' // export type ResultType = 'single' | 'kv' | 'range' export type Version = Uint8Array export type Source = string export type Key = string // TODO: Relax this restriction. export type KVPair<Val> = [Key, Val] export type KVQuery = Set<Key> // In the context of a store's sources (the first result matches the first of // the stores' listed sources in storeinfo). export type FullVersion = (Version | null)[] export type VersionRange = {from: Version, to: Version} // In the context of a store's sources export type FullVersionRange = (VersionRange | null)[] export type StaticKeySelector = { k: Key, isAfter: boolean, // is the key itself included } export type KeySelector = StaticKeySelector & { offset: number, // walk + or - from the specified key } export type StaticRange = { low: StaticKeySelector, high: StaticKeySelector, // If true, results will be returned in reverse lexicographical // order beginning with range.high. reverse?: boolean, // default false. } export type Range = { low: KeySelector, high: KeySelector, reverse?: boolean, // as above, default false. // If non-zero, limits the number of documents returned. TODO: Add marker in // results somehow showing that there are more results after the limit. limit?: number, // default 0. } export type RangeQuery = Range[] export type StaticRangeQuery = StaticRange[] // Outside in we have: // 1. List of ranges // 2. Document item in the list // 3. Key / Value pair export type RangeResult<Val> = [Key, Val][][] // Wrapping single and allkv like this is sort of dumb, but it works better // with TS type checks. export type Query = {type: QueryType.Single | QueryType.AllKV, q: boolean} | { type: QueryType.KV, q: KVQuery, } | { type: QueryType.Range, q: RangeQuery, } | { type: QueryType.StaticRange, q: StaticRangeQuery, } // This is an internal type. Its sort of gross that it exists. I think // eventually I'd like to move to using a single "empty" query type that // completed queries end up at. export type QueryData = boolean | KVQuery | StaticRangeQuery | RangeQuery export type ResultData<Val> = any | Map<Key, Val> | RangeResult<Val> // For now this is just used for snapshot replacements. It'll probably need work. export type ReplaceQuery = {type: QueryType.Single | QueryType.AllKV, q: boolean} | { type: QueryType.KV, q: KVQuery, } | { type: QueryType.StaticRange, q: StaticRangeQuery[], // !! } // TODO: What should this be for full range queries? export type ReplaceQueryData = boolean | KVQuery | StaticRangeQuery[] export type ReplaceData<Val> = any | Map<Key, Val> | RangeResult<Val>[] // export type Result = { // type: 'single', // d: any // } | { // type: 'kv', // d: Map<Key, Val> // } export type SingleOp<Val> = { readonly type: string, readonly data?: any, // Optional. Used when supportedTypes doesn't match. readonly newval?: Val, } export type Metadata = { uid?: string, // unique ID ts?: number, // timestamp } // Only a list if the op type doesn't support compose. (Both set and rm support compose.) export type Op<Val> = SingleOp<Val> | SingleOp<Val>[] export type SingleTxn<Val> = Op<Val> export type KVTxn<Val> = Map<Key, Op<Val>> // Ideally this would be a sparse list. Not a big deal in practice though. export type RangeTxn<Val> = [Key, Op<Val>][][] // But which one? For stores which implement KV + Range, they'll (obviously) // end up propogating a KVTxn through onTxn. Right now RangeTxn is only used // for range subscriptions. export type Txn<Val> = SingleTxn<Val> | KVTxn<Val> | RangeTxn<Val> export type TxnWithMeta<Val> = { versions: FullVersion, // Version after txn applied (nulls for parts unchanged) txn: Txn<Val>, meta: Metadata, // Unique ID generated by the client. } /** * Fetch options. These options can be passed to `store.fetch()`. * * TODO: Note that not all stores currently support all options. Add tests & * documentation for this. */ export type FetchOpts = { /** * Don't actually return values in returned data. Useful for figuring out the * version. If unspecified, defaults to `false`. */ readonly noDocs?: boolean, /** * Request that results are returned at a version >= the version specified. If * the store does not have data at the specified version yet, it should wait * for results to be available before returning. */ readonly minVersion?: FullVersion /** * Request that the results are returned at the exact specified version. * Stores should return VersionTooOldError if the version is too far in the * past. This could take a version range instead, but I'm not sure * what the stores would do with the full range information. * * TODO: This isn't currently tested or supported by most stores. * TODO: Figure out how this should interact with minVersion. */ readonly atVersion?: FullVersion, // Results already known at specified version. Return nothing in this case. // readonly knownAtVersions?: FullVersion, // TODO: knownDocs? } /** * This describes the data returned by calls to `store.fetch()`. */ export type FetchResults<Val, R = ResultData<Val>> = { /** * The results returned by executing the query against the database */ results: R, /** * The range across which the result set is valid. See description of * store.fetch for details. */ versions: FullVersionRange, /** * Optional. This is returned so implementors can bake out the query into a * static query. Eg, a range query (with limits and offsets) will be baked out * to a static range query with none of thatß, and returned alongside the data * itself. This is currently only created & returned for range queries, but * this may become useful for KV queries if limits can be specified in the * fetch options. * * You should generally ignore this. */ bakedQuery?: Query, // TODO: Maybe return a JSON-friendly opaque cursor structure here, which // can be passed back to the store to continue the fetch results when limits // are sent & applied. } /** * This describes options supported by calls to GetOps. */ export type GetOpsOptions = { /** * Supported client-side operation types. */ readonly supportedTypes?: Set<string>, // Ignore supportedTypes, just send full received ops. (default false) // readonly raw?: boolean, /** * If we can't get all the requested operations, don't abort with an error but * return what we can. */ readonly bestEffort?: boolean, // Options NYI: // - limitBytes: Limit on the amount of data to read & return. Advisory // only. Will always try to make progress (that is, return at least one // operation). There is no limitDocs equivalent because you can just // shrink the requested range if thats what you're after. NYI // - limitOps: Limit the number of operations returned. NYI /** Limit the number of ops returned. Default: No limit. */ readonly limitOps?: number, } export type GetOpsResult<Val> = { /** * The operations returned by getOps. */ ops: TxnWithMeta<Val>[], /** * The range (from, to] of the returned set for each source, across which the * results are valid. This will be the same as the input if all ops are * available and included in the query, and there are no limits. */ versions: FullVersionRange, } // If the to version in a version range is empty, fetch the open range (from..] // export type GetOpsFn<Val> = (q: Query, versions: FullVersionRange, opts?: GetOpsOptions) => Promise<GetOpsResult<Val>> export type CatchupData<Val> = { // This is more complicated than I'd like, but I'm reasonably happy with it. // The problem is that catchup isn't always possible, so sometimes you just // gotta send a diff with new documents in it; and you have no idea how you // got there. /** Replace the results in q with this result set, if it exists */ replace?: { // This is a bit of a hack. If the query here contains more keys / ranges // than the original request, they should be added to the active known // set. // // Queries are currently only expanded, so this works but a QueryDelta // would be better. // // Its awkward for ranges. For now the query contains a list of query // parts matching the original query. Each part is either a noop or its a // range query extension. (And then `with` is a standard KV[][]). q: ReplaceQuery, with: ReplaceData<Val>, // This is the max version for each source of the replacement data. This // becomes from:X if ingesting into a FullVersonRange. versions: FullVersion, }, txns: TxnWithMeta<Val>[], // ... then apply txns. // This is the known upper end of the valid version range of the data // returned by catchup. For subscriptions this is a diff from what has been // reported previously, and usually it will just replay the max versions // listen in txns. But when calling alwaysNotify, this will keep updating as // the validity of the versions of the known data grows. This becomes to:X // when ingesting into a FullVersionRange. All sources here must have either // been passed in to subscribe / catchup or listed in a replace. toVersion: FullVersion, // Having received this update chunk, is the client now up-to-date? caughtUp: boolean, } // The updates argument here could either work as // {txn, v:fullrange}[] // or // {txn, source, v:version}[] like in getOps. // Its inconsistent how it is now, but this also makes it much more convenient // to aggregate. export type CatchupOpts = { // TODO: Probably more stuff needs to go in here. readonly supportedTypes?: Set<string>, readonly raw?: boolean, readonly aggregate?: 'yes' | 'prefer no' | 'no', readonly bestEffort?: boolean, readonly limitDocs?: number, readonly limitBytes?: number, } // export type CatchupFn<Val> = (q: Query, fromVersion: FullVersion, opts: CatchupOpts) => Promise<CatchupData<Val>> export type SubscribeOpts = { // Supported client-side operation types. Also forwarded to getOps. readonly supportedTypes?: Set<string>, // I'd like to get rid of this. If this is set, the subscription will // track the value itself to support filtering by supported types. // This should be an internal implementation detail. readonly trackValues?: boolean, // Ignore supportedTypes, just send full received ops. (default false) readonly raw?: boolean, // Can the store aggregate old updates into replacement data instead of // sending the full operation set? This will not always be possible - for // example, the backend server might have paged out / deleted old // operations. // // If never is passed, the server should error if the full operation log is // not available. readonly aggregate?: 'yes' | 'prefer no' | 'no', // bestEffort: if we can't get all the requested operations, don't error // but return what we can. Passed through to catchup & getOps. readonly bestEffort?: boolean, // Always notify about version bumps even if the query results are empty? // (default false) readonly alwaysNotify?: boolean, // Just subscribe to whatever's there, from the current version. If this is // passed, fromVersion is ignored and you just get all operations as they're // streamed live. // Functionally equivalent to calling subscribe(q, (await fetch(q, {noDocs:true})).version)). // readonly fromCurrent?: boolean, // Subscribe from the specified version. If this is passed, we'll send ops // TODO: Maybe rename current -> 'raw' ? fromVersion?: FullVersion | 'current', // NYI: // - Follow symlinks? (NYI) // - When we poll, how much data should we fetch? (opts.limitDocs, opts.limitBytes) // - Stop the query after a certain number of operations (opts.limitOps) (NYI) // readonly limitBytes: number, } export type AsyncIterableIteratorWithRet<T> = AsyncIterableIterator<T> & { // AsyncIterableIterator declares the return function to be optional. // Having a return function is compulsory - its how the subscription is closed. // The value passed to return is ignored. return(value?: any): Promise<IteratorResult<T>>, } export type Subscription<Val> = AsyncIterableIteratorWithRet<CatchupData<Val>> export type MutateOptions = { conflictKeys?: Key[], // TODO: Add conflict ranges. meta?: Metadata, } // TODO: Consider wrapping ResultType + txn in an object like I did with Query. // Also the TxnWithMeta is made from txn, versions and opts.meta. Might be better to just pass a TxnWithMeta straight in. // export type MutateFn<Val> = (type: ResultType, txn: Txn<Val>, versions?: FullVersion, opts?: MutateOptions) => Promise<FullVersion> export type OpsSupport = 'none' | 'partial' | 'all' // TODO export type Capabilities = { // TODO: Add a way to mark if we can subscribe over ranges or just static // ranges // These are bitsets. readonly queryTypes: number, readonly mutationTypes: number, readonly ops?: OpsSupport, // TODO } export type StoreInfo = { readonly uid: string, // Ideally, string or byte array or something. // Unique and lexographically sorted. readonly sources: Source[], // Same length as the source list. This is kinda ugly, but its very infrequently used so,. readonly sourceIsMonotonic: boolean[], readonly capabilities: Capabilities, // And ideally, recursive querying support. [k: string]: any } export type TxnListener<Val> = ( source: Source, fromV: Version, toV: Version, type: ResultType, txn: Txn<Val>, meta: Metadata ) => void /** * Stores are the beating heart of statecraft. Stores are a semantic wrapper * around: * * - Some data (A single value or a set of key-value pairs) * - A monotonically increasing version number (or multiple version numbers). * * The store interface is intended to be like studs on a lego brick - a * composable, interoperable API for interacting with data that changes over * time. * * The store interface is designed to be a generic way to access: * * - Databases * - Files on disk * - Values in memory * - Computed views (computed lazily or eagerly) * - Event sources * - Any other API for remote data * * Most statecraft stores will not store data directly, but instead wrap or * delegate the data storage to another store in turn. * * Note that store is an interface and not a class. Any javascript object which * conforms to the store specification (below) is considered to be a store, and * can be used in any place that stores are used. This includes throughout the * core statecraft library. * * See other documentation for more high level details on stores. */ export interface Store<Val> { /** * Information about the store. This describes the store's unique identifier, * list of root sources and supported query types. * * Exported GraphQL schemas will be added here too. */ readonly storeInfo: StoreInfo, // TODO: Should this be a promise? /** * Fetch data from the store based on the passed query. * * This is one of two normal functions for reading data from a store. * * @param query A description of the data to be fetched. For example, * `{type:'kv', q:new Set(['a','b','c'])}`. See query documentation for * details on query types. The valid query types for a given store are listed * in the `storeInfo.capabilities.queryTypes` bitfield. * * @param opts Fetch options. * * @returns A promise to the corresponding result set, along with a version * range at which that resulting data is valid. * * For example, imagine a query requests key `a`. In the database, `a` was * last modified at version 100. The database is currently at version 200. The * result set will contain the value of key `a` (well, a `Map` from `a` to its * corresponding value). The returned version range will be from version 100 * to version 200. * * Some stores do not store all historical versions. In the example above, if * the store only remembers versions 190-200, the returned version range is * allowed to only specify that smaller version range. */ fetch(q: Query, opts?: FetchOpts): Promise<FetchResults<Val>> /** * Get all historical operations within the specified version range. The * operations returned should be trimmed to values in the requested query set. * * Note that some stores will simply wrap an event log (like kafka). In this * case, the store should only advertise supporting query types `AllKV` or * `Single`, and the query itself may be ignored completely. * * @param versions `[{from, to}]` pairs for each source, or `null` if you * don't care about operations of the named source. The data returned will be * in the range of (from, to]. You can think of the results as the operations * moving from a snapshot at version `from` to a snapshot at version version * `to`. Pass `to:<Empty buffer>` to get all available operations from version * `from` to the current point in time. * * @param opts Optional getOps options object. See GetOpsOptions for details. */ getOps(q: Query, versions: FullVersionRange, opts?: GetOpsOptions): Promise<GetOpsResult<Val>> // For reconnecting, you can specify knownDocs, knownAtVersions // - ... And something to specify the catchup mode (fast vs full) // - opts.getFullHistortForDocs - or something like it. // These options should usually appear together. /** * A subscription is a stream of catchup operations. These operations can be * applied in order to observe the state of some data changing over time. * * There are 3 modes a subscription can run in, depending on the existance and * value of `opts.fromVersion`: * * 1. *Fetch and subscribe*: This is the default if you don't pass any * options, or don't specify `opts.fromVersion`. The first update from the * subscription will contain a `replace: {...}` object with results as if * you fetched the query directly. After the initial catchup object, the * subscription is identical to a subscribe only query (below). * 2. *Subscribe only*: Subscribe only queries are used when consuming * application already has a snapshot of the data at some known version. * Subscriptions run in subscribe only mode if you pass in * `fromVersion:[...]` in the query options, specifying the version from * which the client has operations. The store won't do any initial fetch, * but instead will attempt to catch the client up from the specified * version. Use `opts.aggregate` to control whether the server is allowed * to aggregate the initial catchup. Note that some stores only store * historical operations for a certain amount of time, or not at all. If * the requested version is too old, the store may simply give the client * application a fresh snapshot as the first update regardless of the state * of the `fromVersion` option. * 3. *Raw subscribe*: If you pass `fromVersion: 'current'`, you get all * operations as they come in from whatever version the store thinks its * at. No catchup is performed at all in this mode. Most applications will * never use raw subscriptions. * * The subscription itself is an async iterator. This means you can read from * the stream of operations with a `for await` loop: * * ``` * const sub = store.subscribe({type: QueryType.Single, q:true}) * for await (const catchup of sub) { * // ... * } * ``` * * However, the catchup objects themselves are quite complex, and they're * awkward to consume directly. Almost all applications should use the * standard catchup state machine to consume subscription catchup objects: * * ``` * const sub = store.subscribe({type: QueryType.KV, q:new Set([...])}) * for await (const data of statecraft.subValues(ResultType.KV, sub)) { * console.log('query result set is now', data) * } * ``` * * The state machine can also be driven manually: * * ``` * const sub = store.subscribe({type: QueryType.StaticRange, q:[ * {low: sel('a/x', true), high: sel('z')} * ]}) * const machine = catchupStateMachine(ResultType.Range) * ;(async () => { * for await (const catchup of sub) { * const {results, versions} = machine(catchup) * console.log('query result set is now', results, 'at version', versions) * } * })() * ``` * * @param q A query defining the data that the consumer is interested in. Just * like `fetch`, the query type must be listed in `storeInfo.capabilities.queryTypes`. * * @returns The subscription object. Note that this subscription is returned * syncronously (immediately). But resulting data will only be available with * the first update. */ subscribe(q: Query, opts?: SubscribeOpts): AsyncIterableIteratorWithRet<CatchupData<Val>> /** * Modify the db by applying the specified transaction. All database writes * happen through this function. * * `mutate` is atomic. Stores guarantee that the transaction is either applied * in its entirity or not applied at all. * * Calling mutate directly is not always recommended. * - For simple writes, consider using the helper functions `setSingle`, * `rmKV` or `setKV`. * - For writes involving more complex logic and automatic retries in case of * conflicts, consider using a `transaction`. This mirrors the API you use * when interacting with more traditional databases. * * Ultimately however, all of these tools wrap calls to `mutate`. * * @param type The expected result type of the store. Most stores will only * have one result type (`ResultType.Single` or `ResultType.KV`). The * transaction's format must match the type passed here. Stores advertise * their list of allowed result types via * * @param txn A transaction describing desired modifications to the database. * The format of this object changes depending on the type of data in the * store. * * - For single value stores, this is usually `{type:'set', data}` or * `{type:'rm'}`. * - For KV stores, this is a map from key to operation. For example, `new * Map([['a',{type:'set',123}],['b',{type:'rm'}]])`. * * Other types can be registered via `statecraft.registerType`. This is useful * for collaborative editing via OT or CRDT, or for custom complex data update * functions like you would use for a multiplayer game. * * @param versions (*optional*): The version of the database at which this * transaction is valid. If this transaction writes to any keys which have * been modified more recently than the specified version, the transaction is * considered to be in conflict and will be aborted. The transaction can also * specify additional conflict keys via `opts.conflictKeys`. * * Note that if versions is not specified, the transaction will be applied * some arbitrary current version. This means that you may overwrite changes * from other users. * * @returns A promise to the resulting version of the store after the mutation * has been applied. */ mutate(type: ResultType, txn: Txn<Val>, versions?: FullVersion, opts?: MutateOptions): Promise<FullVersion> /** * Close the store. This should free any resources allocated on behalf of the * store, closing outgoing network sockets and associated file handles. * * This function is often a no-op. * * Stores should only recursively call `close()` on other stores created and * owned locally. * * Likewise, store consumers should call `close()` on all stores created * locally, even if those stores are only made as part of a data pipeline. */ close(): void, /** * Catchup is an optional method that can be added to stores to make * subscription catchup faster (eg when a subscription is created from a * specified version - which happens when a client reconnects). * * **This is rarely used**. Most stores will not implement catchup, and most * applications will not call catchup. * * If this method is missing, catchup happens by calling `getOps` or `fetch`. */ catchup?(q: Query, fromVersion: FullVersion, opts: CatchupOpts): Promise<CatchupData<Val>> // And potentially other helper methods and stuff. // [k: string]: any } // We'll peel & export the function types back out of store to make it easy to refer to // these types separately from stores. export type FetchFn<Val> = Store<Val>['fetch'] export type CatchupFn<Val> = NonNullable<Store<Val>['catchup']> export type GetOpsFn<Val> = Store<Val>['getOps'] export type SubscribeFn<Val> = Store<Val>['subscribe'] export type MutateFn<Val> = Store<Val>['mutate'] // This is a pretty standard OT type. export interface Type<Snap, Op> { name: string, create(data?: any): Snap apply(snapshot: Snap, op: Op): Snap applyMut?(snapshot: Snap, op: Op): void checkOp?(op: Op, snapshot: Snap): void // Check the op is valid and can apply to the given snapshot // For core OT types: // Not sure if transform should be optional. TODO. transform?(op1: Op, op2: Op, side: 'left' | 'right'): Op, // And transform cursor and stuff. compose?(op1: Op, op2: Op): Op, snapToJSON?(data: Snap): any, snapFromJSON?(data: any): Snap, opToJSON?(data: Op): any, opFromJSON?(data: any): Op, [p: string]: any } export type AnyOTType = Type<any, any> // Basically, the replace section of catchup data. export type CatchupReplace<Val, Q extends ReplaceQuery, R extends ReplaceData<Val>> = {q: Q, with: R} export interface QueryOps<Q> { // I want Val to be an associated type. I've been spoiled with rust... type: QueryType // createEmpty(q?: Q): Q toJSON(q: Q): any fromJSON(data: any): Q mapKeys?(q: Q, fn: (k: Key, i: number) => Key | null): Q /** * Adapt the specified transaction (of the expected type) to the passed in * query. If the transaction doesn't match any part of the query, returns * null. */ adaptTxn<Val>(txn: Txn<Val>, query: QueryData): Txn<Val> | null // a must be after b. Consumes a and b. Returns result. composeCR<Val>(a: CatchupReplace<Val, any, any>, b: CatchupReplace<Val, any, any>): CatchupReplace<Val, any, any> // Convert a fetch into a catchup replace object. fetchToReplace<Val>(q: Q, data: ResultData<Val>): CatchupReplace<Val, any, any> // Consumes q and snapshot updateQuery(q: Q | null, op: ReplaceQueryData): Q resultType: ResultOps<any, any, any> // For some reason ResultOps<any, Txn<any>> errors } // This would be nicer with Rust's associated types. export interface ResultOps<Val, R, T> extends Type<R, T> { type?: ResultType // name: ResultType compose(op1: T, op2: T): T composeMut?(op1: T, op2: T): void // Compose two consecutive result objects. Returns dest composeResultsMut(dest: R, src: R): R // Copy all items from src into dest. Returns dest. copyInto?(dest: R, src: R): R // Ughhhh the order of arguments here is so awkward. mapEntries<Val>(snap: R, fn: (k: Key | null, v: Val) => [Key | null, Val] | null): R mapEntriesAsync<Val>(snap: R, fn: (k: Key | null, v: Val) => Promise<[Key | null, Val] | null>): Promise<R> map<In, Out>(snap: R, fn: (v: In, k: Key | null) => Out): R mapAsync<In, Out>(snap: R, fn: (v: In, k: Key | null) => Promise<Out>): Promise<R> mapTxn<In, Out>(op: Txn<In>, fn: (v: Op<In>, k: Key | null) => Op<Out>): Txn<Out> mapTxnAsync<In, Out>(op: Txn<In>, fn: (v: Op<In>, k: Key | null) => Promise<Op<Out>>): Promise<Txn<Out>> // TODO: Add another generic parameter for snap here. Its a ReplaceData object. mapReplace<In, Out>(snap: any, fn: (v: In, k: Key | null) => Out): any // These are compulsory. snapToJSON(data: R): any snapFromJSON(data: any): R opToJSON(data: T): any opFromJSON(data: any): T // from(type: ResultType, snap: ResultData): R getCorrespondingQuery(snap: R): Query // Replace fancy types with {set} if they're not supported. filterSupportedOps(T: T, values: R, supportedTypes: Set<string>): T updateResults<Val>(snapshot: ResultData<Val>, q: ReplaceQuery, data: ReplaceData<Val>): ResultData<Val> // TODO: replace. }
the_stack
import { assert, expect } from 'chai'; import 'mocha'; import { Index } from '../lib/index'; import { DataFrame } from '../lib/dataframe'; import { ArrayIterable } from '../lib/iterables/array-iterable'; describe('DataFrame constructor', () => { it('create dataframe from array of values', () => { const df = new DataFrame([ { A: 10 }, { A: 20 }, { A: 30 }, ]); expect(df.toArray()).to.eql([ { A: 10 }, { A: 20 }, { A: 30 }, ]); }); it('dataframe automatically determines column names from objects', () => { const df = new DataFrame([ { A: 10, B: 100 }, { A: 20, B: 200 }, { A: 30, B: 300 }, ]); expect(df.getColumnNames()).to.eql(["A", "B"]); }); it('create dataframe from empty array', () => { expect(new DataFrame([]).toArray()).to.eql([]); }); it('empty dataframe from empty array has no columns', () => { expect(new DataFrame([]).getColumnNames()).to.eql([]); }); it('create empty dataframe with no params', () => { expect(new DataFrame().toArray()).to.eql([]); }); it('empty dataframe with no params has no columns', () => { expect(new DataFrame().getColumnNames()).to.eql([]); }); it('create empty dataframe from empty config', () => { expect(new DataFrame({}).toArray()).to.eql([]); }); it('empty dataframe with emptu config has no columns', () => { expect(new DataFrame({}).getColumnNames()).to.eql([]); }); it('create empty dataframe from config with no values, although index is set.', () => { expect(new DataFrame({ index: [100, 200, 300] }).toArray()).to.eql([]); }); it('create dataframe from array of values in config', () => { const dataFrame = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ], }); expect(dataFrame.toArray()).to.eql([ { A: 10 }, { A: 20 }, { A: 30 }, ]); }); it('create dataframe from empty array in config', () => { expect(new DataFrame({ values: [] }).toArray()).to.eql([]); }); it('create dataframe with values iterable', () => { var dataframe = new DataFrame({ values: new ArrayIterable([ { A: 10 }, { A: 20 }, { A: 30 }, ]) }); expect(dataframe.toArray()).to.eql([ { A: 10 }, { A: 20 }, { A: 30 }, ]); }); it('passing something other than an array or iterable for values is an error', () => { // This isn't possible in TypeScript, but is in JavaScript. expect(() => new DataFrame({ values: <any>3 })).to.throw(); }) it('index is set by default when values are passed in by array', () => { const dataFrame = new DataFrame([ { A: 10 }, { A: 20 }, { A: 30 }, ]); expect(dataFrame.toPairs()).to.eql([ [0, { A: 10 }], [1, { A: 20 }], [2, { A: 30 }], ]); }); it('index is set by default when values are passed in by config', () => { var dataframe = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ] }); expect(dataframe.toPairs()).to.eql([ [0, { A: 10 }], [1, { A: 20 }], [2, { A: 30 }], ]); }); it('can set index via array passed to constructor', () => { var dataframe = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ], index: [100, 200, 300] }); expect(dataframe.toPairs()).to.eql([ [100, { A: 10 }], [200, { A: 20 }], [300, { A: 30 }], ]); }); it('can create dataframe with values array and index iterable', () => { var dataframe = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ], index: new ArrayIterable([100, 200, 300]) }); expect(dataframe.toPairs()).to.eql([ [100, { A: 10 }], [200, { A: 20 }], [300, { A: 30 }], ]); }); it('can create dataframe with values iterable and index iterable', () => { var dataframe = new DataFrame({ values: new ArrayIterable([ { A: 10 }, { A: 20 }, { A: 30 }, ]), index: new ArrayIterable([100, 200, 300]) }); expect(dataframe.toPairs()).to.eql([ [100, { A: 10 }], [200, { A: 20 }], [300, { A: 30 }], ]); }); it('passing something other than an array or iterable for index is an error', () => { // This isn't possible in TypeScript, but is in JavaScript. expect(() => new DataFrame({ values: [10, 20, 30], index: <any>3 })).to.throw(); }); it('can create dataframe with index from another dataframe', () => { var dataframe = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ], index: new DataFrame([100, 200, 300]) }); expect(dataframe.toPairs()).to.eql([ [100, { A: 10 }], [200, { A: 20 }], [300, { A: 30 }], ]); }); it ('can get index from dataframe', () => { var dataframe = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ], index: [100, 200, 300] }); expect(dataframe.getIndex().toArray()).to.eql([ 100, 200, 300, ]); }); it('can create dataframe with index from another index', () => { var dataframe = new DataFrame({ values: [ { A: 10 }, { A: 20 }, { A: 30 }, ], index: new Index([100, 200, 300]) }); expect(dataframe.toPairs()).to.eql([ [100, { A: 10 }], [200, { A: 20 }], [300, { A: 30 }], ]); }); it('can create dataframe from pairs', () => { var dataframe = new DataFrame({ pairs: [ [100, 10], [200, 20], [300, 30], ], }); expect(dataframe.getIndex().toArray()).to.eql([100, 200, 300]); expect(dataframe.toArray()).to.eql([10, 20, 30]); }); it('can create dataframe from values and pairs', () => { var dataframe = new DataFrame({ values: new ArrayIterable([ 5, 4, 6, // Bit of a trick here, using different values to the pairs. ]), pairs: new ArrayIterable([ [100, 10], [200, 20], [300, 30], ]), }); expect(dataframe.getIndex().toArray()).to.eql([100, 200, 300]); expect(dataframe.toPairs()).to.eql([[100, 10], [200, 20], [300, 30]]); expect(dataframe.toArray()).to.eql([5, 4, 6]); // Different values! A hack to test. }); it('can create dataframe from index and pairs', () => { var dataframe = new DataFrame({ index: new ArrayIterable([ 15, 16, 17 // Trick. Separate index values. ]), pairs: new ArrayIterable([ [100, 10], [200, 20], [300, 30], ]), }); expect(dataframe.getIndex().toArray()).to.eql([15, 16, 17]); // Different values! expect(dataframe.toPairs()).to.eql([[100, 10], [200, 20], [300, 30]]); expect(dataframe.toArray()).to.eql([10, 20, 30]); }); it('can create dataframe from values, index and pairs', () => { var dataframe = new DataFrame({ values: new ArrayIterable([ 5, 4, 6, // Bit of a trick here, using different values to the pairs. ]), index: new ArrayIterable([ 15, 16, 17 // Trick. Separate index values. ]), pairs: new ArrayIterable([ [100, 10], [200, 20], [300, 30], ]), }); expect(dataframe.getIndex().toArray()).to.eql([15, 16, 17]); // Different values! expect(dataframe.toPairs()).to.eql([[100, 10], [200, 20], [300, 30]]); expect(dataframe.toArray()).to.eql([5, 4, 6]); // Different values! A hack to test. }); it('can create from rows', function () { var columnNames = ["c1", "c2"]; var dataFrame = new DataFrame({ columnNames: columnNames, rows: [ [1, 2], [3, 4], ], }); expect(dataFrame.getColumnNames()).to.eql(columnNames); expect(dataFrame.toArray()).to.eql([ { c1: 1, c2: 2 }, { c1: 3, c2: 4 }, ]); }); it('can create from rows with index', function () { var columnNames = ["c1", "c2"]; var dataFrame = new DataFrame({ columnNames: columnNames, rows: [ [1, 2], [3, 4], ], index: [10, 11], }); expect(dataFrame.getColumnNames()).to.eql(columnNames); expect(dataFrame.toPairs()).to.eql([ [10, { c1: 1, c2: 2 }], [11, { c1: 3, c2: 4 }], ]); }); it("can handle undefined row", function () { var d = new DataFrame({ columnNames: ["c1", "c2"], rows: <any[][]> [ // Cast is here to allow this in TypeScript. Normally this is not allowed, but it can be done in JavaScript so I want to handle it. [1, 2], undefined, [5, 2] ], }); expect(function () { d.toArray(); }).to.throw(); }); it("can handle null row", function () { var d = new DataFrame({ columnNames: ["c1", "c2"], rows: <any[][]> [ // Cast is here to allow this in TypeScript. Normally this is not allowed, but it can be done in JavaScript so I want to handle it. [1, 2], null, [5, 2] ], }); expect(function () { d.toArray(); }).to.throw(); }); it('can get rows from dataframe', () => { const dataFrame = new DataFrame([ { A: 10, B: 100 }, { A: 20, B: 200 }, { A: 30, B: 300 }, ]); expect(dataFrame.toRows()).to.eql([ [10, 100], [20, 200], [30, 300], ]); }); it('can initialize from array of objects with different fields', () => { var dataFrame = new DataFrame({ values: [ { Col1: 1, Col2: 'hello', }, { Col3: 10, Col4: 'computer', } ], considerAllRows: true, }); expect(dataFrame.getColumnNames()).to.eql(["Col1", "Col2", "Col3", "Col4"]); expect(dataFrame.toRows()).to.eql([ [1, 'hello', undefined, undefined], [undefined, undefined, 10, 'computer'], ]); var columns = dataFrame.getColumns(); expect(columns.count()).to.eql(4); expect(columns.at(0)!.name).to.eql("Col1"); expect(columns.at(0)!.series.toArray()).to.eql([1]); expect(columns.at(1)!.name).to.eql("Col2"); expect(columns.at(1)!.series.toArray()).to.eql(["hello"]); expect(columns.at(2)!.name).to.eql("Col3"); expect(columns.at(2)!.series.toArray()).to.eql([10]); expect(columns.at(3)!.name).to.eql("Col4"); expect(columns.at(3)!.series.toArray()).to.eql(["computer"]); }); it('can initialize from array of objects with zero fields', () => { var dataFrame = new DataFrame({ values: [ {}, {} ] }); expect(dataFrame.getColumnNames()).to.eql([]); expect(dataFrame.getColumns().count()).to.eql(0); expect(dataFrame.toRows()).to.eql([[], []]); }); });
the_stack
import { format, IConnection } from "mysql"; import { AccessKeyQueries, UserAuthProviderQueries, UserQueries } from "../queries"; import BaseDAO from "./BaseDAO"; import { UserDTO } from "../dto"; import Encryptor from "../Encryptor"; import { difference, forOwn, omit, pick } from "lodash"; export default class UserDAO extends BaseDAO { public static async createUser(connection: IConnection, user: UserDTO): Promise<UserDTO> { const userResult = await UserDAO.getUserByEmail(connection, user.email); if (userResult && userResult.length > 0) { throw new Error("User with email [" + user.email + "] already exists."); } else { await UserDAO.beginTransaction(connection); const insertResult = await UserDAO.insertUser(connection, user); const userId = insertResult.insertId; const userMatches = await UserDAO.getUserById(connection, userId); const outgoing = new UserDTO(); outgoing.id = userId; outgoing.email = userMatches[0].email; outgoing.createdTime = userMatches[0].created_time; outgoing.name = userMatches[0].name; Encryptor.instance.decryptDTO(outgoing); if (user.linkedProviders) { outgoing.linkedProviders = await UserDAO.createLinkedProviders(connection, userId, user.linkedProviders); } if (user.accessKeys) { outgoing.accessKeys = await UserDAO.createAccessKeys(connection, userId, user.accessKeys); } await UserDAO.commit(connection); return outgoing; } } public static async userByEmail(connection: IConnection, email: string): Promise<UserDTO> { const userResult = await UserDAO.getUserByEmail(connection, email); if (!userResult || userResult.length === 0) { throw new Error("No user found with email [" + email + "]"); } return await UserDAO.generateOutgoingUser(connection, userResult); } public static async userByAccessKey(connection: IConnection, accessKey: string): Promise<UserDTO> { const userResult = await UserDAO.getUserByAccessKey(connection, accessKey); if (!userResult || userResult.length === 0) { throw new Error("No user found with access key [" + accessKey + "]"); } return await UserDAO.generateOutgoingUser(connection, userResult); } public static async userById(connection: IConnection, userId: number): Promise<UserDTO> { const userResult = await UserDAO.getUserById(connection, userId); if (!userResult || userResult.length === 0) { throw new Error("No user found with id [" + userId + "]"); } return await UserDAO.generateOutgoingUser(connection, userResult); } public static async updateUser(connection: IConnection, currentEmail: string, updateInfo: UserDTO): Promise<UserDTO> { /* This function is used to - add a new access key - delete an access key - update the last access time of an access key - update the friendly name and/or expiration time of an access key - add a new auth provider */ if (!updateInfo.accessKeys) { throw new Error("incoming accessKeys property must be provided."); } const userDTO = await UserDAO.userByEmail(connection, currentEmail); const existingAccessKeys = userDTO.accessKeys; const updatedAccessKeys = updateInfo.accessKeys; // check if there's a new access key const newAccessKeyNames = difference(Object.keys(updatedAccessKeys), Object.keys(existingAccessKeys)); if (newAccessKeyNames && newAccessKeyNames.length > 0) { const newAccessKeys = pick(updatedAccessKeys, newAccessKeyNames); // this creates the new ones and then fetches all of them userDTO.accessKeys = await UserDAO.createAccessKeys(connection, userDTO.id as number, newAccessKeys); return userDTO; } // check if there's a deleted key const remAccessKeyNames = difference(Object.keys(existingAccessKeys), Object.keys(updatedAccessKeys)); if (remAccessKeyNames && remAccessKeyNames.length > 0) { const removeAccessKeys = pick(existingAccessKeys, remAccessKeyNames); await UserDAO.beginTransaction(connection); await UserDAO.removeAccessKeys(connection, removeAccessKeys); await UserDAO.commit(connection); return await UserDAO.userByEmail(connection, currentEmail); } // check if data in existing access keys changed const accessKeysToUpdate: any[] = []; forOwn(existingAccessKeys, (existingKey, existingKeyName) => { const updatedKey = updatedAccessKeys[existingKeyName]; let updated = false; updatedKey.id = existingKey.id; if (updatedKey.friendlyName && (!existingKey.friendlyName || (updatedKey.friendlyName !== existingKey.friendlyName))) { updated = true; } else if (!updatedKey.friendlyName) { updatedKey.friendlyName = existingKey.friendlyName; } if (updatedKey.lastAccess && (!existingKey.lastAccess || (updatedKey.lastAccess !== existingKey.lastAccess.getTime()))) { updated = true; } else if (!updatedKey.lastAccess) { updatedKey.lastAccess = existingKey.lastAccess; } if (updatedKey.expires && (!existingKey.expires || (updatedKey.expires !== existingKey.expires.getTime()))) { updated = true; } else if (!updatedKey.expires) { updatedKey.expires = existingKey.expires; } if (updated) { accessKeysToUpdate.push(updatedKey); } }); if (accessKeysToUpdate.length > 0) { userDTO.accessKeys = await UserDAO.updateAccessKeys(connection, userDTO.id as number, accessKeysToUpdate); return userDTO; } // check if new auth provider(s) const newAuthProviders = difference(updateInfo.linkedProviders, userDTO.linkedProviders); if (newAuthProviders && newAuthProviders.length > 0) { userDTO.linkedProviders = await UserDAO.createLinkedProviders(connection, userDTO.id as number, newAuthProviders); } return userDTO; } private static async generateOutgoingUser(connection: IConnection, userResult: any): Promise<UserDTO> { const userId = userResult[0].id; const outgoing = new UserDTO(); outgoing.id = userResult[0].id; outgoing.email = userResult[0].email; outgoing.createdTime = userResult[0].created_time; outgoing.name = userResult[0].name; Encryptor.instance.decryptDTO(outgoing); outgoing.accessKeys = await UserDAO.getAccessKeysByUserId(connection, userId) .then(UserDAO.transformOutgoingAccessKeys); outgoing.linkedProviders = await UserDAO.getLinkedProvidersForUser(connection, userId) .then(UserDAO.transformOutgoingLinkedProviders); return outgoing; } private static async getUserByEmail(connection: IConnection, email: string): Promise<any> { return UserDAO.query(connection, UserQueries.getUserByEmail, [Encryptor.instance.encrypt("user.email", email)]); } private static async insertUser(connection: IConnection, user: UserDTO): Promise<any> { const user_email = Encryptor.instance.encrypt("user.email", user.email); const user_name = Encryptor.instance.encrypt("user.name", user.name); return UserDAO.query(connection, UserQueries.insertUser, [user_email, user_name]); } private static async getUserById(connection: IConnection, id: number): Promise<any> { return UserDAO.query(connection, UserQueries.getUserById, [id]); } private static async getUserByAccessKey(connection: IConnection, accessKey: string): Promise<any> { return UserDAO.query(connection, UserQueries.getUserByAccessKey, [accessKey]); } private static async createAccessKeys(connection: IConnection, userId: number, accessKeys: any): Promise<any> { // accessKeys is an object with property names being the key // and the values being the metadata about the key; this is // mapping the keys to an array of insert statement promises return Promise.all(Object.keys(accessKeys).map((keyName) => { return UserDAO.insertAccessKey(connection, userId, accessKeys[keyName]); })).then(() => { // once all the inserts are done, query the db; // we should get back an array of access key metadata; this // reduces the array back to its original object format return UserDAO.getAccessKeysByUserId(connection, userId).then(UserDAO.transformOutgoingAccessKeys); }); } private static async updateAccessKeys(connection: IConnection, userId: number, accessKeys: any[]): Promise<any> { return Promise.all(accessKeys.map((accessKey) => { return UserDAO.updateAccessKey(connection, accessKey); })).then(() => { return UserDAO.getAccessKeysByUserId(connection, userId).then(UserDAO.transformOutgoingAccessKeys); }); } private static async removeAccessKeys(connection: IConnection, accessKeys: any): Promise<any> { return Promise.all(Object.keys(accessKeys).map((keyName) => { return UserDAO.deleteAccessKey(connection, accessKeys[keyName]); })); } private static async insertAccessKey(connection: IConnection, userId: number, accessKey: any): Promise<any> { const expires = (typeof accessKey.expires === "number") ? new Date(accessKey.expires) : accessKey.expires; const friendly_name = Encryptor.instance.encrypt("access_key.friendly_name", accessKey.friendlyName); const description = Encryptor.instance.encrypt("access_key.description", accessKey.description); return UserDAO.query(connection, AccessKeyQueries.insertAccessKey, [userId, accessKey.name, accessKey.createdBy, expires, friendly_name, description]); } private static async updateAccessKey(connection: IConnection, accessKey: any): Promise<any> { const expires = (typeof accessKey.expires === "number") ? new Date(accessKey.expires) : accessKey.expires; const lastAccess = (typeof accessKey.lastAccess === "number") ? new Date(accessKey.lastAccess) : accessKey.lastAccess; const friendly_name = Encryptor.instance.encrypt("access_key.friendly_name", accessKey.friendlyName); return UserDAO.query(connection, AccessKeyQueries.updateAccessKey, [lastAccess, friendly_name, expires, accessKey.id]); } private static async getAccessKeysByUserId(connection: IConnection, userId: number): Promise<any> { return UserDAO.query(connection, AccessKeyQueries.getAccessKeysByUserId, [userId]); } private static async deleteAccessKey(connection: IConnection, accessKey: any): Promise<any> { return UserDAO.query(connection, AccessKeyQueries.deleteAccessKeyById, [accessKey.id]); } private static transformOutgoingAccessKeys(accessKeys: any[]): any { return accessKeys.reduce((obj: any, accessKey: any) => { const friendlyName = Encryptor.instance.decrypt("access_key.friendly_name", accessKey.friendly_name); const description = Encryptor.instance.decrypt("access_key.description", accessKey.description); obj[accessKey.name] = { createdTime: accessKey.created_time, description, email: accessKey.email, expires: accessKey.expires, friendlyName, id: accessKey.id, lastAccess: accessKey.last_access, name: accessKey.name, }; return obj; }, {}); } private static async createLinkedProviders(connection: IConnection, userId: number, providers: any): Promise<any> { // insert them in the db return Promise.all(providers.map((provider: string) => { return UserDAO.insertLinkedProvider(connection, userId, provider); })).then(() => { // after they are all inserted, retrieve them and build an array of the provider names return UserDAO.getLinkedProvidersForUser(connection, userId).then(UserDAO.transformOutgoingLinkedProviders); }); } private static async insertLinkedProvider(connection: IConnection, userId: number, provider: string): Promise<any> { return UserDAO.query(connection, UserAuthProviderQueries.insertAuthProvider, [userId, provider]); } private static async getLinkedProvidersForUser(connection: IConnection, userId: number): Promise<any> { return UserDAO.query(connection, UserAuthProviderQueries.getAuthProvidersForUserId, [userId]); } private static transformOutgoingLinkedProviders(providers: any[]): string[] { return providers.map((provider: any) => { return provider.provider; }); } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of the author nor the names of the program's contributors may 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 AUTHORS OF THE SOFTWARE 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. */ /** * @fileoverview Manages fetching and exposing the server's configuration. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.serverConfigUrl = VRS.globalOptions.serverConfigUrl || 'ServerConfig.json'; // The URL to fetch the server configuration from. VRS.globalOptions.serverConfigDataType = VRS.globalOptions.serverConfigDataType || 'json'; // The type of call to make when fetching the server configuration. VRS.globalOptions.serverConfigTimeout = VRS.globalOptions.serverConfigTimeout || 10000; // The number of milliseconds to wait before timing out a fetch of server configuration. VRS.globalOptions.serverConfigRetryInterval = VRS.globalOptions.serverConfigRetryInterval || 5000; // The number of milliseconds to wait before retrying a fetch of server configuration. VRS.globalOptions.serverConfigOverwrite = VRS.globalOptions.serverConfigOverwrite !== undefined ? VRS.globalOptions.serverConfigOverwrite : false; // Whether to overwrite the existing configuration with the configuration stored on the server. VRS.globalOptions.serverConfigResetBeforeImport = VRS.globalOptions.serverConfigResetBeforeImport !== undefined ? VRS.globalOptions.serverConfigResetBeforeImport : false; // Whether to erase the existing configuration before importing the configuration stored on the server. VRS.globalOptions.serverConfigIgnoreSplitters = VRS.globalOptions.serverConfigIgnoreSplitters !== undefined ? VRS.globalOptions.serverConfigIgnoreSplitters : false; // Whether to ignore the splitter settings when importing the configuration stored on the server. VRS.globalOptions.serverConfigIgnoreLanguage = VRS.globalOptions.serverConfigIgnoreLanguage !== undefined ? VRS.globalOptions.serverConfigIgnoreLanguage : true; // Whether to ignore the language settings when importing the configuration stored on the server. VRS.globalOptions.serverConfigIgnoreRequestFeedId = VRS.globalOptions.serverConfigIgnoreRequestFeedId !== undefined ? VRS.globalOptions.serverConfigIgnoreRequestFeedId : true; // Whether to ignore the feed ID to fetch when importing the configuration stored on the server. export interface IServerConfig { VrsVersion: string; IsMono: boolean; UseMarkerLabels: boolean; UseSvgGraphicsOnDesktop: boolean; UseSvgGraphicsOnMobile: boolean; UseSvgGraphicsOnReports: boolean; Receivers: IServerConfigReceiver[]; IsLocalAddress: boolean; IsAudioEnabled: boolean; MinimumRefreshSeconds: number; RefreshSeconds: number; GoogleMapsApiKey: string; InitialSettings: string; InitialLatitude: number; InitialLongitude: number; InitialMapType: string; // VRS.MapType InitialZoom: number; InitialDistanceUnit: string; // VRS.Distance InitialHeightUnit: string; // VRS.Height InitialSpeedUnit: string; // VRS.Speed InternetClientCanRunReports: boolean; InternetClientCanShowPinText: boolean; InternetClientTimeoutMinutes: number; InternetClientsCanPlayAudio: boolean; InternetClientsCanSubmitRoutes: boolean; InternetClientsCanSeeAircraftPictures: boolean; InternetClientsCanSeePolarPlots: boolean; TileServerSettings: ITileServerSettings; TileServerLayers: ITileServerSettings[]; } export interface ITileServerSettings { Name: string; Url: string; Subdomains: string; Version: string; MinZoom: number; MaxZoom: number; ZoomOffset: number; MinNativeZoom: number; MaxNativeZoom: number; ZoomReverse: boolean; DetectRetina: boolean; ClassName: string; Attribution: string; ErrorTileUrl: string; IsTms: boolean; IsLayer: boolean; DefaultBrightness: number; DefaultOpacity: number; ExpandoOptions: ITileServerSettingExpandoOption[]; } export interface ITileServerSettingExpandoOption { Option: string; Value: string; } export interface IServerConfigReceiver { UniqueId: number; Name: string; } export class ServerConfiguration { private _ServerConfig: IServerConfig = null; /** * Gets the current configuration on the server. */ get() : IServerConfig { return this._ServerConfig; } /** * Returns true if the configuration allows for the playing of audio. */ audioEnabled() : boolean { return this._ServerConfig && !this._ServerConfig.IsMono && this._ServerConfig.IsAudioEnabled && (this._ServerConfig.IsLocalAddress || this._ServerConfig.InternetClientsCanPlayAudio); } /** * Returns true if the configuration allows for the viewing of aircraft pictures. */ picturesEnabled() : boolean { return this._ServerConfig && (this._ServerConfig.IsLocalAddress || this._ServerConfig.InternetClientsCanSeeAircraftPictures); } /** * Returns true if the configuration allows for the display of pin text on aircraft markers. */ pinTextEnabled() : boolean { return this._ServerConfig && (this._ServerConfig.IsLocalAddress || this._ServerConfig.InternetClientCanShowPinText); } /** * Returns true if the configuration allows for the running of reports. */ reportsEnabled() : boolean { return this._ServerConfig && (this._ServerConfig.IsLocalAddress || this._ServerConfig.InternetClientCanRunReports); } /** * Returns true if the configuration allows for the submission of routes. */ routeSubmissionEnabled() : boolean { return this._ServerConfig && (this._ServerConfig.IsLocalAddress || this._ServerConfig.InternetClientsCanSubmitRoutes); } /** * Returns true if the configuration allows for the display of polar plots. */ polarPlotsEnabled() : boolean { return this._ServerConfig && (this._ServerConfig.IsLocalAddress || this._ServerConfig.InternetClientsCanSeePolarPlots); } /** * Fetches the configuration from the server. If this fails then it will retry perpetually. Once it finally * receives a reply it calls the callback passed across. The callback is mandatory. */ fetch(successCallback: () => void) { var self = this; if(!successCallback) throw 'You must supply a method to call once the configuration has been fetched'; $.ajax({ url: VRS.globalOptions.serverConfigUrl, dataType: VRS.globalOptions.serverConfigDataType, timeout: VRS.globalOptions.serverConfigTimeout, success: function(data) { self._ServerConfig = data; if(self._ServerConfig.InitialSettings && VRS.configStorage && !VRS.configStorage.getHasSettings()) { VRS.configStorage.importSettings(self._ServerConfig.InitialSettings, { overwrite: VRS.globalOptions.serverConfigOverwrite, resetBeforeImport: VRS.globalOptions.serverConfigResetBeforeImport, ignoreSplitters: VRS.globalOptions.serverConfigIgnoreSplitters, ignoreLanguage: VRS.globalOptions.serverConfigIgnoreLanguage, ignoreRequestFeedId: VRS.globalOptions.serverConfigIgnoreRequestFeedId }); } VRS.globalDispatch.raise(VRS.globalEvent.serverConfigChanged, [ self._ServerConfig ]); successCallback(); }, error: function(jqXHR, textStatus, errorThrown) { self.fetchFailed(successCallback); } }); } /** * Called when the fetch fails. Waits for a bit and then tries again. */ private fetchFailed(successCallback: () => void) { var self = this; setTimeout(function() { self.fetch(successCallback); }, VRS.globalOptions.serverConfigRetryInterval); } } /* * Prebuilts */ export var serverConfig = new VRS.ServerConfiguration(); }
the_stack
import * as path from "path"; import { ConfigurationTarget, extensions, ProgressLocation, TextDocument, Uri, window, workspace, WorkspaceConfiguration } from "vscode"; import { Component, ComponentsByName, ComponentsByUri, COMPONENT_EXT, COMPONENT_FILE_GLOB, parseComponent } from "../entities/component"; import { GlobalFunction, GlobalFunctions, GlobalTag, GlobalTags } from "../entities/globals"; import { Scope } from "../entities/scope"; import { ComponentFunctions, UserFunction, UserFunctionByUri, UserFunctionsByName } from "../entities/userFunction"; import { parseVariableAssignments, Variable, VariablesByUri } from "../entities/variable"; import { CFDocsDefinitionInfo } from "../utils/cfdocs/definitionInfo"; import { MyMap, SearchMode } from "../utils/collections"; import { APPLICATION_CFM_GLOB } from "../utils/contextUtil"; import { DocumentStateContext, getDocumentStateContext } from "../utils/documentUtil"; import { resolveCustomMappingPaths, resolveRelativePath, resolveRootPath } from "../utils/fileUtil"; import { ITrie } from "../typings/trie-prefix-tree"; import trie = require("trie-prefix-tree"); let allGlobalEntityDefinitions = new MyMap<string, CFDocsDefinitionInfo>(); let allGlobalFunctions: GlobalFunctions = {}; let allGlobalTags: GlobalTags = {}; // let allMemberFunctions: MemberFunctionsByType = new MyMap<DataType, Set<MemberFunction>>(); let allComponentsByUri: ComponentsByUri = {}; let allComponentsByName: ComponentsByName = {}; // let allUserFunctionsByUri: UserFunctionsByUri = {}; let allUserFunctionsByName: UserFunctionsByName = {}; let allComponentNames: ITrie = trie([]); let allFunctionNames: ITrie = trie([]); let allServerVariables: VariablesByUri = new VariablesByUri(); let allApplicationVariables: VariablesByUri = new VariablesByUri(); /** * Checks whether the given identifier is a cached global function * @param name The identifier to check */ export function isGlobalFunction(name: string): boolean { return allGlobalFunctions.hasOwnProperty(name.toLowerCase()); } /** * Checks whether the given identifier is a cached global tag * @param name The identifier to check */ export function isGlobalTag(name: string): boolean { return allGlobalTags.hasOwnProperty(name.toLowerCase()); } /** * Checks whether the given identifier is a cached global entity * @param name The identifier to check */ export function isGlobalEntity(name: string): boolean { return allGlobalTags.hasOwnProperty(name.toLowerCase()) || allGlobalFunctions.hasOwnProperty(name.toLowerCase()); } /** * Sets the given global function object into cache * @param functionDefinition The global function object to cache */ export function setGlobalFunction(functionDefinition: GlobalFunction): void { allGlobalFunctions[functionDefinition.name.toLowerCase()] = functionDefinition; } /** * Retrieves the cached global function identified by the given function name * @param functionName The name of the global function to be retrieved */ export function getGlobalFunction(functionName: string): GlobalFunction { return allGlobalFunctions[functionName.toLowerCase()]; } /** * Returns all of the cached global functions */ export function getAllGlobalFunctions(): GlobalFunctions { return allGlobalFunctions; } /** * Clears all of the cached global functions */ export function clearAllGlobalFunctions(): void { allGlobalFunctions = {}; } /** * Sets the given global tag object into cache * @param tagDefinition The global tag object to cache */ export function setGlobalTag(tagDefinition: GlobalTag): void { allGlobalTags[tagDefinition.name.toLowerCase()] = tagDefinition; } /** * Retrieves the cached global tag identified by the given tag name * @param tagName The name of the global tag to be retrieved */ export function getGlobalTag(tagName: string): GlobalTag { return allGlobalTags[tagName.toLowerCase()]; } /** * Returns all of the cached global tags */ export function getAllGlobalTags(): GlobalTags { return allGlobalTags; } /** * Clears all of the cached global tags */ export function clearAllGlobalTags(): void { allGlobalTags = {}; } /** * Sets the given global definition object into cache * @param definition The global definition object to cache */ export function setGlobalEntityDefinition(definition: CFDocsDefinitionInfo): void { allGlobalEntityDefinitions.set(definition.name.toLowerCase(), definition); } /** * Retrieves the cached global tag identified by the given tag name * @param name The name of the global definition to be retrieved */ export function getGlobalEntityDefinition(name: string): CFDocsDefinitionInfo { return allGlobalEntityDefinitions.get(name.toLowerCase()); } /** * Returns all of the cached global entity definitions */ export function getAllGlobalEntityDefinitions(): MyMap<string, CFDocsDefinitionInfo> { return allGlobalEntityDefinitions; } /** * Clears all of the cached global entity definitions */ export function clearAllGlobalEntityDefinitions(): void { allGlobalEntityDefinitions = new MyMap<string, CFDocsDefinitionInfo>(); } /** * Sets the given component object into cache * @param comp The component to cache */ function setComponent(comp: Component): void { allComponentsByUri[comp.uri.toString()] = comp; const componentKey: string = path.basename(comp.uri.fsPath, COMPONENT_EXT).toLowerCase(); if (!allComponentsByName[componentKey]) { allComponentsByName[componentKey] = {}; } allComponentsByName[componentKey][comp.uri.toString()] = comp; try { allComponentNames.addWord(componentKey); } catch (ex) { console.error(ex); console.error(`Unable to add ${componentKey} to trie`); } } /** * Retrieves the cached component identified by the given URI * @param uri The URI of the component to be retrieved */ export function getComponent(uri: Uri): Component { if (!hasComponent(uri)) { /* TODO: If not already cached, attempt to read, parse and cache. Tricky since read is async */ } return allComponentsByUri[uri.toString()]; } /** * Checks if the cached component with the given URI exists * @param uri The URI of the component to be checked */ export function hasComponent(uri: Uri): boolean { return allComponentsByUri.hasOwnProperty(uri.toString()); } /** * Retrieves all cached components matched by the given query * @param query Some query text used to search for cached components */ export function searchAllComponentNames(query: string): Component[] { let components: Component[] = []; allComponentNames.getPrefix(query.toLowerCase()).forEach((compKey: string) => { components = components.concat(Object.values(allComponentsByName[compKey])); }); return components; } /** * Sets the given user function object into cache * @param userFunction The user function to cache */ function setUserFunction(userFunction: UserFunction): void { const functionKey: string = userFunction.name.toLowerCase(); if (!allUserFunctionsByName[functionKey]) { allUserFunctionsByName[functionKey] = {}; } allUserFunctionsByName[functionKey][userFunction.location.uri.toString()] = userFunction; try { allFunctionNames.addWord(functionKey); } catch (ex) { console.error(ex); console.error(`Unable to add ${functionKey} to trie`); } } /** * Retrieves all cached user functions matched by the given query * @param query Some query text used to search for cached user functions * @param searchMode How the query will be searched for */ export function searchAllFunctionNames(query: string, searchMode: SearchMode = SearchMode.StartsWith): UserFunction[] { let functions: UserFunction[] = []; const lowerQuery = query.toLowerCase(); if (searchMode === SearchMode.StartsWith) { allFunctionNames.getPrefix(lowerQuery).forEach((funcKey: string) => { functions = functions.concat(Object.values(allUserFunctionsByName[funcKey])); }); } else if (searchMode === SearchMode.Contains) { for (const name in allUserFunctionsByName) { if (name.includes(lowerQuery)) { functions = functions.concat(Object.values(allUserFunctionsByName[name])); } } } else if (searchMode === SearchMode.EqualTo) { if (allUserFunctionsByName.hasOwnProperty(lowerQuery)) { functions = Object.values(allUserFunctionsByName[lowerQuery]); } } return functions; } /** * Resolves a component in dot-path notation to a URI * @param dotPath A string for a component in dot-path notation * @param baseUri The URI from which the component path will be resolved */ export function componentPathToUri(dotPath: string, baseUri: Uri): Uri | undefined { if (!dotPath) { return undefined; } const normalizedPath: string = dotPath.replace(/\./g, path.sep) + COMPONENT_EXT; // relative to local directory const localPath: string = resolveRelativePath(baseUri, normalizedPath); const localFile: Uri = Uri.file(localPath); if (allComponentsByUri[localFile.toString()]) { return localFile; } // relative to web root const rootPath: string = resolveRootPath(baseUri, normalizedPath); if (rootPath) { const rootFile: Uri = Uri.file(rootPath); if (allComponentsByUri[rootFile.toString()]) { return rootFile; } } // custom mappings const customMappingPaths: string[] = resolveCustomMappingPaths(baseUri, normalizedPath); for (const mappedPath of customMappingPaths) { const mappedFile: Uri = Uri.file(mappedPath); if (allComponentsByUri[mappedFile.toString()]) { return mappedFile; } } return undefined; } /** * Caches given component and its contents * @param component The component to cache * @param documentStateContext Contextual information for a given document's state */ export function cacheComponent(component: Component, documentStateContext: DocumentStateContext): void { clearCachedComponent(component.uri); setComponent(component); component.functions.forEach((funcObj: UserFunction) => { setUserFunction(funcObj); }); const componentUri: Uri = component.uri; const fileName: string = path.basename(componentUri.fsPath); if (fileName === "Application.cfc") { const thisApplicationVariables: Variable[] = parseVariableAssignments(documentStateContext, documentStateContext.docIsScript); const thisApplicationFilteredVariables: Variable[] = thisApplicationVariables.filter((variable: Variable) => { return [Scope.Application, Scope.Session, Scope.Request].includes(variable.scope); }); setApplicationVariables(componentUri, thisApplicationFilteredVariables); } else if (fileName === "Server.cfc") { const thisServerVariables: Variable[] = parseVariableAssignments(documentStateContext, documentStateContext.docIsScript).filter((variable: Variable) => { return variable.scope === Scope.Server; }); allServerVariables.set(componentUri.toString(), thisServerVariables); } } /** * Reads and parses all cfc files in the current workspace and caches their definitions */ export async function cacheAllComponents(): Promise<void> { clearAllCachedComponents(); return workspace.findFiles(COMPONENT_FILE_GLOB).then( async (componentUris: Uri[]) => { // TODO: Remove cflint setting update for workspace state when CFLint checks it. Remove workspace state when CFLint can get list of open editors. const cflintExt = extensions.getExtension("KamasamaK.vscode-cflint"); if (cflintExt) { const cflintSettings: WorkspaceConfiguration = workspace.getConfiguration("cflint", null); const runModes: {} = cflintSettings.get<{}>("runModes"); if (runModes && runModes.hasOwnProperty("onOpen") && runModes["onOpen"]) { const cflintEnabledValues = cflintSettings.inspect<boolean>("enabled"); const cflintEnabledPrevWSValue: boolean = cflintEnabledValues.workspaceValue; cflintSettings.update("enabled", false, ConfigurationTarget.Workspace).then(async () => { await cacheGivenComponents(componentUris); await cacheAllApplicationCfms(); cflintSettings.update("enabled", cflintEnabledPrevWSValue, ConfigurationTarget.Workspace); }); } else { cacheGivenComponents(componentUris); cacheAllApplicationCfms(); } } else { cacheGivenComponents(componentUris); cacheAllApplicationCfms(); } }, (reason) => { console.error(reason); } ); } /** * Reads and parses given cfc files and caches their definitions * @param componentUris List of URIs to read, parse, and cache */ async function cacheGivenComponents(componentUris: Uri[]): Promise<void> { await window.withProgress( { location: ProgressLocation.Notification, title: "Caching components", cancellable: true }, async (progress, token) => { const componentCount = componentUris.length; let i = 0; for (const componentUri of componentUris) { if (token.isCancellationRequested) { break; } try { const document: TextDocument = await workspace.openTextDocument(componentUri); cacheComponentFromDocument(document, true); } catch (ex) { console.error(`Cannot parse document at ${componentUri}`); } finally { i++; progress.report({ message: `${i} / ${componentCount}`, increment: (100 / componentCount) }); } } } ); } /** * Parses given document and caches its definitions * @param document The text document to parse and cache * @param fast Whether to use the faster, but less accurate parsing */ export function cacheComponentFromDocument(document: TextDocument, fast: boolean = false): boolean { const documentStateContext: DocumentStateContext = getDocumentStateContext(document, fast); const parsedComponent: Component | undefined = parseComponent(documentStateContext); if (!parsedComponent) { return false; } cacheComponent(parsedComponent, documentStateContext); return true; } /** * Removes all cached references to the given component * @param componentUri The URI of the component to be removed from cache */ export function clearCachedComponent(componentUri: Uri): void { const componentByUri: Component = allComponentsByUri[componentUri.toString()]; if (componentByUri) { delete allComponentsByUri[componentUri.toString()]; } const componentKey: string = path.basename(componentUri.fsPath, COMPONENT_EXT).toLowerCase(); const componentsByName: ComponentsByUri = allComponentsByName[componentKey]; if (componentsByName) { const componentsByNameLen: number = Object.keys(componentsByName).length; if (componentsByName[componentUri.toString()]) { const prevCompFunctions: ComponentFunctions = componentsByName[componentUri.toString()].functions; if (componentsByNameLen === 1) { delete allComponentsByName[componentKey]; allComponentNames.removeWord(componentKey); } else { delete componentsByName[componentUri.toString()]; } if (prevCompFunctions) { for (const funcName of prevCompFunctions.keys()) { const userFunctions: UserFunctionByUri = allUserFunctionsByName[funcName]; if (userFunctions) { const userFunctionsLen: number = Object.keys(userFunctions).length; if (userFunctions[componentUri.toString()]) { if (userFunctionsLen === 1) { delete allUserFunctionsByName[funcName]; allFunctionNames.removeWord(funcName); } else { delete userFunctions[componentUri.toString()]; } } } } } } } } /** * Clears all cached references to components and their contents */ function clearAllCachedComponents(): void { allComponentsByUri = {}; allComponentsByName = {}; allComponentNames = trie([]); allUserFunctionsByName = {}; allFunctionNames = trie([]); } /** * Reads and parses all Application.cfm files in the current workspace and caches their definitions */ export async function cacheAllApplicationCfms(): Promise<void> { return workspace.findFiles(APPLICATION_CFM_GLOB).then( cacheGivenApplicationCfms, (reason) => { console.error(reason); } ); } /** * Reads and parses given Application.cfm files and caches their definitions * @param applicationUris List of URIs to parse and cache */ async function cacheGivenApplicationCfms(applicationUris: Uri[]): Promise<void> { applicationUris.forEach(async (applicationUri: Uri) => { try { const document: TextDocument = await workspace.openTextDocument(applicationUri); const documentStateContext: DocumentStateContext = getDocumentStateContext(document); const thisApplicationVariables: Variable[] = parseVariableAssignments(documentStateContext, documentStateContext.docIsScript); const thisApplicationFilteredVariables: Variable[] = thisApplicationVariables.filter((variable: Variable) => { return [Scope.Application, Scope.Session, Scope.Request].includes(variable.scope); }); setApplicationVariables(applicationUri, thisApplicationFilteredVariables); } catch (ex) { console.error(`Cannot parse document at ${applicationUri}`); } }); } /** * Retrieves the cached application variables identified by the given URI * @param uri The URI of the application file */ export function getApplicationVariables(uri: Uri): Variable[] { return allApplicationVariables.get(uri.toString()); } /** * Sets the cached application variables for the given URI * @param uri The URI of the application file * @param applicationVariables The application variables to set */ export function setApplicationVariables(uri: Uri, applicationVariables: Variable[]): void { allApplicationVariables.set(uri.toString(), applicationVariables); } /** * Removes the cached application variables identified by the given URI * @param uri The URI of the application file to remove */ export function removeApplicationVariables(uri: Uri): boolean { return allApplicationVariables.delete(uri.toString()); } /** * Retrieves the cached server variables identified by the given URI * @param uri The URI of the component to be check */ export function getServerVariables(uri: Uri): Variable[] { return allServerVariables.get(uri.toString()); }
the_stack
import PlayerComponent from '../interfaces/component'; import EventsList from '../interfaces/events-list'; import Level from '../interfaces/level'; import SettingsItem from '../interfaces/settings/item'; import SettingsSubItem from '../interfaces/settings/subitem'; import Player from '../player'; import { EVENT_OPTIONS, IS_ANDROID, IS_IOS, NAV } from '../utils/constants'; import { addEvent } from '../utils/events'; import { hasClass, removeElement } from '../utils/general'; import { isDashSource, isHlsSource } from '../utils/media'; /** * Levels element. * * @description * @class Levels * @implements PlayerComponent */ class Levels implements PlayerComponent { /** * Instance of OpenPlayer. * * @private * @type Player * @memberof Levels */ #player: Player; /** * Button to toggle captions. * * @private * @type HTMLButtonElement * @memberof Levels */ #button: HTMLButtonElement; /** * Container to display Levels options if `detachMenus` is set as `true`. * * @private * @type HTMLDivElement * @memberof Levels */ #menu: HTMLDivElement; /** * Events that will be triggered: * - button (to display menu of Levels if detached menus are active) * - global (to dispatch click on the subitems on the menu settings) * - media (to check the available levels) * * @private * @type EventsList * @memberof Levels */ #events: EventsList = { button: {}, global: {}, media: {}, }; /** * Determine if a submenu must be created with the CC button, instead of using the Settings menu. * * @private * @type boolean * @memberof Levels */ #detachMenu: boolean; /** * Default labels from player's config * * @private * @type object * @memberof Levels */ #labels: any; #levels: Level[] = []; /** * Initial level to be used as a default value in the `Settings` component. * * @see [[Levels.addSettings]] * @private * @type string * @memberof Levels */ #default = ''; /** * Position of the button to be indicated as part of its class name * * @private * @type {string} * @memberof Levels */ #position: string; /** * Layer where the control item will be placed * * @private * @type {string} * @memberof Captions */ #layer: string; /** * Create an instance of Captions. * * @param {Player} player * @memberof Levels * @returns {Levels} */ constructor(player: Player, position: string, layer: string) { this.#player = player; this.#labels = player.getOptions().labels; this.#detachMenu = player.getOptions().detachMenus; this.#position = position; this.#layer = layer; return this; } /** * Create a button and a container to display levels (if any). * * @inheritDoc * @memberof Levels */ public create(): void { const initialLevel = this.#player.getOptions().defaultLevel !== null ? parseInt(this.#player.getOptions().defaultLevel, 10) : this.#player.getMedia().level; this.#default = `${initialLevel}`; const menuItems = this._formatMenuItems(); const defaultLevel = menuItems.length ? menuItems.find((items: any) => items.key === this.#default) : null; const defaultLabel = defaultLevel ? defaultLevel.label : this.#labels.auto; let levelSet = false; this.#button = document.createElement('button'); this.#button.className = `op-controls__levels op-control__${this.#position}`; this.#button.tabIndex = 0; this.#button.title = this.#labels.mediaLevels; this.#button.setAttribute('aria-controls', this.#player.id); this.#button.setAttribute('aria-label', this.#labels.mediaLevels); this.#button.setAttribute('data-active-level', this.#default); this.#button.innerHTML = `<span>${defaultLabel}</span>`; const loadLevelsEvent = () => { if (!this.#levels.length) { this._gatherLevels(); setTimeout(() => { this.#player.getMedia().level = initialLevel; const e = addEvent('controlschanged'); this.#player.getElement().dispatchEvent(e); }, 0); } else if (!levelSet) { this.#player.getMedia().level = initialLevel; levelSet = true; } }; this.#events.media.loadedmetadata = loadLevelsEvent.bind(this); this.#events.media.manifestLoaded = loadLevelsEvent.bind(this); this.#events.media.hlsManifestParsed = loadLevelsEvent.bind(this); if (this.#detachMenu) { this._buildMenu(); this.#events.button.click = () => { if (this.#detachMenu) { const menus = this.#player.getContainer().querySelectorAll('.op-settings'); for (let i = 0, total = menus.length; i < total; ++i) { if (menus[i] !== this.#menu) { menus[i].setAttribute('aria-hidden', 'true'); } } if (this.#menu.getAttribute('aria-hidden') === 'true') { this.#menu.setAttribute('aria-hidden', 'false'); } else { this.#menu.setAttribute('aria-hidden', 'true'); } } }; this.#events.button.mouseover = () => { if (!IS_IOS && !IS_ANDROID) { const menus = this.#player.getContainer().querySelectorAll('.op-settings'); for (let i = 0, total = menus.length; i < total; ++i) { if (menus[i] !== this.#menu) { menus[i].setAttribute('aria-hidden', 'true'); } } if (this.#menu.getAttribute('aria-hidden') === 'true') { this.#menu.setAttribute('aria-hidden', 'false'); } } }; this.#events.button.mouseout = () => { if (!IS_IOS && !IS_ANDROID) { const menus = this.#player.getContainer().querySelectorAll('.op-settings'); for (let i = 0, total = menus.length; i < total; ++i) { menus[i].setAttribute('aria-hidden', 'true'); } if (this.#menu.getAttribute('aria-hidden') === 'false') { this.#menu.setAttribute('aria-hidden', 'true'); } } }; this.#button.addEventListener('click', this.#events.button.click, EVENT_OPTIONS); this.#button.addEventListener('mouseover', this.#events.button.mouseover, EVENT_OPTIONS); this.#menu.addEventListener('mouseover', this.#events.button.mouseover, EVENT_OPTIONS); this.#menu.addEventListener('mouseout', this.#events.button.mouseout, EVENT_OPTIONS); this.#player.getElement().addEventListener('controlshidden', this.#events.button.mouseout, EVENT_OPTIONS); } this.#events.global.click = (e: Event) => { const option = (e.target as HTMLElement); const currentTime = this.#player.getMedia().currentTime; const isPaused = this.#player.getMedia().paused; if (option.closest(`#${this.#player.id}`) && hasClass(option, 'op-levels__option')) { const levelVal = option.getAttribute('data-value'); const level = parseInt(levelVal ? levelVal.replace('levels-', '') : '-1', 10); this.#default = `${level}`; if (this.#detachMenu) { this.#button.setAttribute('data-active-level', `${level}`); this.#button.innerHTML = `<span>${option.innerText}</span>`; const levels = option.parentElement && option.parentElement.parentElement ? option.parentElement.parentElement.querySelectorAll('.op-settings__submenu-item') : []; for (let i = 0, total = levels.length; i < total; ++i) { levels[i].setAttribute('aria-checked', 'false'); } if (option.parentElement) { option.parentElement.setAttribute('aria-checked', 'true'); } this.#menu.setAttribute('aria-hidden', 'false'); } this.#player.getMedia().level = level; this.#player.getMedia().currentTime = currentTime; if (!isPaused) { this.#player.play(); } const event = addEvent('levelchanged', { detail: { label: option.innerText.trim(), level, }, }); this.#player.getElement().dispatchEvent(event); e.preventDefault(); e.stopPropagation(); } }; const connection = NAV.connection || NAV.mozConnection || NAV.webkitConnection; this.#events.global.connection = () => { // Check connectivity to switch levels (only HTML5 since HLS and Dash can use adaptive streaming) const media = this.#player.getMedia().current; if (!isDashSource(media) && !isHlsSource(media)) { let type = connection.effectiveType; const levels = this.#levels.map(item => ({ ...item, resolution: parseInt(item.label.replace('p', ''), 10), })); let level = levels.find(item => item.resolution < 360); if (type === '4g') { level = levels.find(item => item.resolution >= 720); } else if (type === '3g') { level = levels.find(item => item.resolution >= 360 && item.resolution < 720); } if (level) { this.#player.pause(); this.#player.getMedia().level = level.id; this.#player.play(); } type = connection.effectiveType; } }; Object.keys(this.#events.media).forEach(event => { this.#player.getElement().addEventListener(event, this.#events.media[event], EVENT_OPTIONS); }); document.addEventListener('click', this.#events.global.click, EVENT_OPTIONS); if (connection) { connection.addEventListener('change', this.#events.global.connection, EVENT_OPTIONS); } } public destroy(): void { const connection = NAV.connection || NAV.mozConnection || NAV.webkitConnection; Object.keys(this.#events.media).forEach(event => { this.#player.getElement().removeEventListener(event, this.#events.media[event]); }); document.removeEventListener('click', this.#events.global.click); if (connection) { connection.removeEventListener('change', this.#events.global.connection); } if (this.#detachMenu) { this.#button.removeEventListener('click', this.#events.button.click); removeElement(this.#button); this.#button.removeEventListener('mouseover', this.#events.button.mouseover); this.#menu.removeEventListener('mouseover', this.#events.button.mouseover); this.#menu.removeEventListener('mouseout', this.#events.button.mouseout); this.#player.getElement().removeEventListener('controlshidden', this.#events.button.mouseout); removeElement(this.#menu); } } /** * Add list of available captions in the `Settings` menu. * * @see [[Settings.addSettings]] * @returns {SettingsItem|object} * @memberof Captions */ public addSettings(): SettingsItem | unknown { if (this.#detachMenu) { return {}; } const subitems = this._formatMenuItems(); // Avoid implementing submenu for levels if only 2 options were available return subitems.length > 2 ? { className: 'op-levels__option', default: this.#default || '-1', key: 'levels', name: this.#labels.levels, subitems, } : {}; } private _formatMenuItems(): SettingsSubItem[] { const levels = this._gatherLevels(); const total = levels.length; let items = total ? [{ key: '-1', label: this.#labels.auto }] : []; for (let i = 0; i < total; i++) { const level = levels[i]; items = items.filter(el => el.key !== level.id); items.push({ key: level.id, label: level.label }); } // Remove duplicated labels items = items.reduce((acc: SettingsSubItem[], current) => { const duplicate = acc.find(item => item.label === current.label); if (!duplicate) { return acc.concat([current]); } return acc; }, []).sort((a, b) => (parseInt(a.label, 10) > parseInt(b.label, 10) ? 1 : -1)); return items; } /** * Get the standard label of level depending of media's height. * * @see https://en.wikipedia.org/wiki/Computer_display_standard#Standards * @private * @returns {string} * @memberof Levels */ private _getResolutionsLabel(height: number): string { if (height >= 4320) { return '8K'; } if (height >= 2160) { return '4K'; } if (height >= 1440) { return '1440p'; } if (height >= 1080) { return '1080p'; } if (height >= 720) { return '720p'; } if (height >= 480) { return '480p'; } if (height >= 360) { return '360p'; } if (height >= 240) { return '240p'; } if (height >= 144) { return '144p'; } return this.#labels.auto; } private _gatherLevels() { if (!this.#levels.length) { this.#player.getMedia().levels.forEach((level: Level) => { this.#levels.push({ ...level, label: level.label || this._getResolutionsLabel(level.height) }); }); } return this.#levels; } private _buildMenu() { // Build menu if detachMenu is `true` if (this.#detachMenu) { this.#button.classList.add('op-control--no-hover'); this.#menu = document.createElement('div'); this.#menu.className = 'op-settings op-levels__menu'; this.#menu.setAttribute('aria-hidden', 'true'); const className = 'op-levels__option'; const options = this._formatMenuItems(); // Store the submenu to reach all options for current menu item const menu = `<div class="op-settings__menu" role="menu" id="menu-item-levels"> ${options.map(item => ` <div class="op-settings__submenu-item" tabindex="0" role="menuitemradio" aria-checked="${this.#default === item.key ? 'true' : 'false'}"> <div class="op-settings__submenu-label ${className || ''}" data-value="levels-${item.key}">${item.label}</div> </div>`).join('')} </div>`; this.#menu.innerHTML = menu; const itemContainer = document.createElement('div'); itemContainer.className = `op-controls__container op-control__${this.#position}`; itemContainer.appendChild(this.#button); itemContainer.appendChild(this.#menu); this.#player.getControls().getLayer(this.#layer).appendChild(itemContainer); } } } export default Levels;
the_stack