text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/modulesMappers"; import * as Parameters from "../models/parameters"; import { IotHubGatewayServiceAPIsContext } from "../iotHubGatewayServiceAPIsContext"; /** Class representing a Modules. */ export class Modules { private readonly client: IotHubGatewayServiceAPIsContext; /** * Create a Modules. * @param {IotHubGatewayServiceAPIsContext} client Reference to the service client. */ constructor(client: IotHubGatewayServiceAPIsContext) { this.client = client; } /** * Gets the module twin. See https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins * for more information. * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param [options] The optional parameters * @returns Promise<Models.ModulesGetTwinResponse> */ getTwin(id: string, mid: string, options?: msRest.RequestOptionsBase): Promise<Models.ModulesGetTwinResponse>; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param callback The callback */ getTwin(id: string, mid: string, callback: msRest.ServiceCallback<Models.Twin>): void; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param options The optional parameters * @param callback The callback */ getTwin(id: string, mid: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Twin>): void; getTwin(id: string, mid: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Twin>, callback?: msRest.ServiceCallback<Models.Twin>): Promise<Models.ModulesGetTwinResponse> { return this.client.sendOperationRequest( { id, mid, options }, getTwinOperationSpec, callback) as Promise<Models.ModulesGetTwinResponse>; } /** * Replaces the tags and desired properties of a module twin. See * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param deviceTwinInfo The module twin info that will replace the existing info. * @param [options] The optional parameters * @returns Promise<Models.ModulesReplaceTwinResponse> */ replaceTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, options?: Models.ModulesReplaceTwinOptionalParams): Promise<Models.ModulesReplaceTwinResponse>; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param deviceTwinInfo The module twin info that will replace the existing info. * @param callback The callback */ replaceTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, callback: msRest.ServiceCallback<Models.Twin>): void; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param deviceTwinInfo The module twin info that will replace the existing info. * @param options The optional parameters * @param callback The callback */ replaceTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, options: Models.ModulesReplaceTwinOptionalParams, callback: msRest.ServiceCallback<Models.Twin>): void; replaceTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, options?: Models.ModulesReplaceTwinOptionalParams | msRest.ServiceCallback<Models.Twin>, callback?: msRest.ServiceCallback<Models.Twin>): Promise<Models.ModulesReplaceTwinResponse> { return this.client.sendOperationRequest( { id, mid, deviceTwinInfo, options }, replaceTwinOperationSpec, callback) as Promise<Models.ModulesReplaceTwinResponse>; } /** * Updates the tags and desired properties of a module twin. See * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-device-twins for more information. * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param deviceTwinInfo The module twin info containing the tags and desired properties to be * updated. * @param [options] The optional parameters * @returns Promise<Models.ModulesUpdateTwinResponse> */ updateTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, options?: Models.ModulesUpdateTwinOptionalParams): Promise<Models.ModulesUpdateTwinResponse>; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param deviceTwinInfo The module twin info containing the tags and desired properties to be * updated. * @param callback The callback */ updateTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, callback: msRest.ServiceCallback<Models.Twin>): void; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param deviceTwinInfo The module twin info containing the tags and desired properties to be * updated. * @param options The optional parameters * @param callback The callback */ updateTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, options: Models.ModulesUpdateTwinOptionalParams, callback: msRest.ServiceCallback<Models.Twin>): void; updateTwin(id: string, mid: string, deviceTwinInfo: Models.Twin, options?: Models.ModulesUpdateTwinOptionalParams | msRest.ServiceCallback<Models.Twin>, callback?: msRest.ServiceCallback<Models.Twin>): Promise<Models.ModulesUpdateTwinResponse> { return this.client.sendOperationRequest( { id, mid, deviceTwinInfo, options }, updateTwinOperationSpec, callback) as Promise<Models.ModulesUpdateTwinResponse>; } /** * Gets all the module identities on the device. * @param id The unique identifier of the device. * @param [options] The optional parameters * @returns Promise<Models.ModulesGetModulesOnDeviceResponse> */ getModulesOnDevice(id: string, options?: msRest.RequestOptionsBase): Promise<Models.ModulesGetModulesOnDeviceResponse>; /** * @param id The unique identifier of the device. * @param callback The callback */ getModulesOnDevice(id: string, callback: msRest.ServiceCallback<Models.Module[]>): void; /** * @param id The unique identifier of the device. * @param options The optional parameters * @param callback The callback */ getModulesOnDevice(id: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Module[]>): void; getModulesOnDevice(id: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Module[]>, callback?: msRest.ServiceCallback<Models.Module[]>): Promise<Models.ModulesGetModulesOnDeviceResponse> { return this.client.sendOperationRequest( { id, options }, getModulesOnDeviceOperationSpec, callback) as Promise<Models.ModulesGetModulesOnDeviceResponse>; } /** * Gets a module identity on the device. * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param [options] The optional parameters * @returns Promise<Models.ModulesGetIdentityResponse> */ getIdentity(id: string, mid: string, options?: msRest.RequestOptionsBase): Promise<Models.ModulesGetIdentityResponse>; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param callback The callback */ getIdentity(id: string, mid: string, callback: msRest.ServiceCallback<Models.Module>): void; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param options The optional parameters * @param callback The callback */ getIdentity(id: string, mid: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Module>): void; getIdentity(id: string, mid: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Module>, callback?: msRest.ServiceCallback<Models.Module>): Promise<Models.ModulesGetIdentityResponse> { return this.client.sendOperationRequest( { id, mid, options }, getIdentityOperationSpec, callback) as Promise<Models.ModulesGetIdentityResponse>; } /** * Creates or updates the module identity for a device in the IoT Hub. The moduleId and * generationId cannot be updated by the user. * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param module The module identity. * @param [options] The optional parameters * @returns Promise<Models.ModulesCreateOrUpdateIdentityResponse> */ createOrUpdateIdentity(id: string, mid: string, module: Models.Module, options?: Models.ModulesCreateOrUpdateIdentityOptionalParams): Promise<Models.ModulesCreateOrUpdateIdentityResponse>; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param module The module identity. * @param callback The callback */ createOrUpdateIdentity(id: string, mid: string, module: Models.Module, callback: msRest.ServiceCallback<Models.Module>): void; /** * @param id The unique identifier of the device. * @param mid The unique identifier of the module. * @param module The module identity. * @param options The optional parameters * @param callback The callback */ createOrUpdateIdentity(id: string, mid: string, module: Models.Module, options: Models.ModulesCreateOrUpdateIdentityOptionalParams, callback: msRest.ServiceCallback<Models.Module>): void; createOrUpdateIdentity(id: string, mid: string, module: Models.Module, options?: Models.ModulesCreateOrUpdateIdentityOptionalParams | msRest.ServiceCallback<Models.Module>, callback?: msRest.ServiceCallback<Models.Module>): Promise<Models.ModulesCreateOrUpdateIdentityResponse> { return this.client.sendOperationRequest( { id, mid, module, options }, createOrUpdateIdentityOperationSpec, callback) as Promise<Models.ModulesCreateOrUpdateIdentityResponse>; } /** * Deletes the module identity for a device in the IoT Hub. * @param id The unique identifier of the deivce. * @param mid The unique identifier of the module. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteIdentity(id: string, mid: string, options?: Models.ModulesDeleteIdentityOptionalParams): Promise<msRest.RestResponse>; /** * @param id The unique identifier of the deivce. * @param mid The unique identifier of the module. * @param callback The callback */ deleteIdentity(id: string, mid: string, callback: msRest.ServiceCallback<void>): void; /** * @param id The unique identifier of the deivce. * @param mid The unique identifier of the module. * @param options The optional parameters * @param callback The callback */ deleteIdentity(id: string, mid: string, options: Models.ModulesDeleteIdentityOptionalParams, callback: msRest.ServiceCallback<void>): void; deleteIdentity(id: string, mid: string, options?: Models.ModulesDeleteIdentityOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { id, mid, options }, deleteIdentityOperationSpec, callback); } /** * Invokes a direct method on a module of a device. See * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-direct-methods for more information. * @param deviceId The unique identifier of the device. * @param moduleId The unique identifier of the module. * @param directMethodRequest The parameters to execute a direct method on the module. * @param [options] The optional parameters * @returns Promise<Models.ModulesInvokeMethodResponse> */ invokeMethod(deviceId: string, moduleId: string, directMethodRequest: Models.CloudToDeviceMethod, options?: msRest.RequestOptionsBase): Promise<Models.ModulesInvokeMethodResponse>; /** * @param deviceId The unique identifier of the device. * @param moduleId The unique identifier of the module. * @param directMethodRequest The parameters to execute a direct method on the module. * @param callback The callback */ invokeMethod(deviceId: string, moduleId: string, directMethodRequest: Models.CloudToDeviceMethod, callback: msRest.ServiceCallback<Models.CloudToDeviceMethodResult>): void; /** * @param deviceId The unique identifier of the device. * @param moduleId The unique identifier of the module. * @param directMethodRequest The parameters to execute a direct method on the module. * @param options The optional parameters * @param callback The callback */ invokeMethod(deviceId: string, moduleId: string, directMethodRequest: Models.CloudToDeviceMethod, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CloudToDeviceMethodResult>): void; invokeMethod(deviceId: string, moduleId: string, directMethodRequest: Models.CloudToDeviceMethod, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CloudToDeviceMethodResult>, callback?: msRest.ServiceCallback<Models.CloudToDeviceMethodResult>): Promise<Models.ModulesInvokeMethodResponse> { return this.client.sendOperationRequest( { deviceId, moduleId, directMethodRequest, options }, invokeMethodOperationSpec, callback) as Promise<Models.ModulesInvokeMethodResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getTwinOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "twins/{id}/modules/{mid}", urlParameters: [ Parameters.id, Parameters.mid ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.Twin }, default: {} }, serializer }; const replaceTwinOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "twins/{id}/modules/{mid}", urlParameters: [ Parameters.id, Parameters.mid ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch ], requestBody: { parameterPath: "deviceTwinInfo", mapper: { ...Mappers.Twin, required: true } }, responses: { 200: { bodyMapper: Mappers.Twin }, default: {} }, serializer }; const updateTwinOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "twins/{id}/modules/{mid}", urlParameters: [ Parameters.id, Parameters.mid ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch ], requestBody: { parameterPath: "deviceTwinInfo", mapper: { ...Mappers.Twin, required: true } }, responses: { 200: { bodyMapper: Mappers.Twin }, default: {} }, serializer }; const getModulesOnDeviceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "devices/{id}/modules", urlParameters: [ Parameters.id ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "Module" } } } } }, default: {} }, serializer }; const getIdentityOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "devices/{id}/modules/{mid}", urlParameters: [ Parameters.id, Parameters.mid ], queryParameters: [ Parameters.apiVersion ], responses: { 200: { bodyMapper: Mappers.Module }, default: {} }, serializer }; const createOrUpdateIdentityOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "devices/{id}/modules/{mid}", urlParameters: [ Parameters.id, Parameters.mid ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch ], requestBody: { parameterPath: "module", mapper: { ...Mappers.Module, required: true } }, responses: { 200: { bodyMapper: Mappers.Module }, 201: { bodyMapper: Mappers.Module }, default: {} }, serializer }; const deleteIdentityOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "devices/{id}/modules/{mid}", urlParameters: [ Parameters.id, Parameters.mid ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.ifMatch ], responses: { 204: {}, default: {} }, serializer }; const invokeMethodOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "twins/{deviceId}/modules/{moduleId}/methods", urlParameters: [ Parameters.deviceId, Parameters.moduleId ], queryParameters: [ Parameters.apiVersion ], requestBody: { parameterPath: "directMethodRequest", mapper: { ...Mappers.CloudToDeviceMethod, required: true } }, responses: { 200: { bodyMapper: Mappers.CloudToDeviceMethodResult }, default: {} }, serializer };
the_stack
* @group integration/delegation */ import type { ICType, IDelegationNode, KeyringPair } from '@kiltprotocol/types' import { Permission } from '@kiltprotocol/types' import { BlockchainUtils } from '@kiltprotocol/chain-helpers' import { createOnChainDidFromSeed, DemoKeystore, FullDidDetails, } from '@kiltprotocol/did' import { randomAsHex } from '@polkadot/util-crypto' import { BN } from '@polkadot/util' import { Attestation } from '../attestation/Attestation' import { Claim } from '../claim/Claim' import { RequestForAttestation } from '../requestforattestation/RequestForAttestation' import { Credential } from '..' import { disconnect, init } from '../kilt' import { DelegationNode } from '../delegation/DelegationNode' import { CtypeOnChain, DriversLicense, devFaucet, WS_ADDRESS, devBob, } from './utils' import { getAttestationHashes } from '../delegation/DelegationNode.chain' let paymentAccount: KeyringPair let signer: DemoKeystore let root: FullDidDetails let claimer: FullDidDetails let attester: FullDidDetails async function writeHierarchy( delegator: FullDidDetails, ctypeHash: ICType['hash'] ): Promise<DelegationNode> { const rootNode = DelegationNode.newRoot({ account: delegator.did, permissions: [Permission.DELEGATE], cTypeHash: ctypeHash, }) await rootNode .store() .then((tx) => delegator.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) return rootNode } async function addDelegation( hierarchyId: IDelegationNode['id'], parentId: DelegationNode['id'], delegator: FullDidDetails, delegee: FullDidDetails, permissions: Permission[] = [Permission.ATTEST, Permission.DELEGATE] ): Promise<DelegationNode> { const delegationNode = DelegationNode.newNode({ hierarchyId, parentId, account: delegee.did, permissions, }) const signature = await delegationNode.delegeeSign(delegee, signer) await delegationNode .store(signature) .then((tx) => delegator.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) return delegationNode } beforeAll(async () => { await init({ address: WS_ADDRESS }) paymentAccount = devFaucet signer = new DemoKeystore() ;[attester, root, claimer] = await Promise.all([ createOnChainDidFromSeed(paymentAccount, signer, randomAsHex()), createOnChainDidFromSeed(paymentAccount, signer, randomAsHex()), createOnChainDidFromSeed(paymentAccount, signer, randomAsHex()), ]) if (!(await CtypeOnChain(DriversLicense))) { await DriversLicense.store() .then((tx) => attester.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) } }, 30_000) beforeEach(async () => { await Promise.all([attester, root, claimer].map((i) => i.refreshTxIndex())) }) it('fetches the correct deposit amount', async () => { const depositAmount = await DelegationNode.queryDepositAmount() expect(depositAmount.toString()).toStrictEqual( new BN(1000000000000000).toString() ) }) it('should be possible to delegate attestation rights', async () => { const rootNode = await writeHierarchy(root, DriversLicense.hash) const delegatedNode = await addDelegation( rootNode.id, rootNode.id, root, attester ) await Promise.all([ expect(rootNode.verify()).resolves.toBeTruthy(), expect(delegatedNode.verify()).resolves.toBeTruthy(), ]) }, 60_000) describe('and attestation rights have been delegated', () => { let rootNode: DelegationNode let delegatedNode: DelegationNode beforeAll(async () => { rootNode = await writeHierarchy(root, DriversLicense.hash) delegatedNode = await addDelegation( rootNode.id, rootNode.id, root, attester ) await Promise.all([ expect(rootNode.verify()).resolves.toBeTruthy(), expect(delegatedNode.verify()).resolves.toBeTruthy(), ]) }, 75_000) it("should be possible to attest a claim in the root's name and revoke it by the root", async () => { const content = { name: 'Ralph', age: 12, } const claim = Claim.fromCTypeAndClaimContents( DriversLicense, content, claimer.did ) const request = RequestForAttestation.fromClaim(claim, { delegationId: delegatedNode.id, }) await request.signWithDid(signer, claimer) expect(request.verifyData()).toBeTruthy() await expect(request.verifySignature()).resolves.toBeTruthy() const attestation = Attestation.fromRequestAndDid(request, attester.did) await attestation .store() .then((tx) => attester.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) const credential = Credential.fromRequestAndAttestation( request, attestation ) expect(credential.verifyData()).toBeTruthy() await expect(credential.verify()).resolves.toBeTruthy() // revoke attestation through root await credential.attestation .revoke(1) .then((tx) => root.authorizeExtrinsic(tx, signer, paymentAccount.address)) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) await expect(credential.verify()).resolves.toBeFalsy() }, 75_000) }) describe('revocation', () => { let delegator = root let firstDelegee = attester let secondDelegee = claimer beforeAll(() => { delegator = root firstDelegee = attester secondDelegee = claimer }) it('delegator can revoke and remove delegation', async () => { const rootNode = await writeHierarchy(delegator, DriversLicense.hash) const delegationA = await addDelegation( rootNode.id, rootNode.id, delegator, firstDelegee ) // Test revocation await expect( delegationA .revoke(delegator.did) .then((tx) => delegator.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) ).resolves.not.toThrow() await expect(delegationA.verify()).resolves.toBe(false) // Test removal with deposit payer's account. await expect( delegationA .remove() .then((tx) => delegator.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) ).resolves.not.toThrow() // Check that delegation fails to verify and that it is not stored on the blockchain anymore. await expect(DelegationNode.query(delegationA.id)).resolves.toBeNull() await expect(delegationA.verify()).resolves.toBe(false) }, 60_000) it('delegee cannot revoke root but can revoke own delegation', async () => { const delegationRoot = await writeHierarchy(delegator, DriversLicense.hash) const delegationA = await addDelegation( delegationRoot.id, delegationRoot.id, delegator, firstDelegee ) await expect( delegationRoot .revoke(firstDelegee.did) .then((tx) => firstDelegee.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) ).rejects.toThrow() await expect(delegationRoot.verify()).resolves.toBe(true) await expect( delegationA .revoke(firstDelegee.did) .then((tx) => firstDelegee.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) ).resolves.not.toThrow() await expect(delegationA.verify()).resolves.toBe(false) }, 60_000) it('delegator can revoke root, revoking all delegations in tree', async () => { let delegationRoot = await writeHierarchy(delegator, DriversLicense.hash) const delegationA = await addDelegation( delegationRoot.id, delegationRoot.id, delegator, firstDelegee ) const delegationB = await addDelegation( delegationRoot.id, delegationA.id, firstDelegee, secondDelegee ) delegationRoot = await delegationRoot.getLatestState() await expect( delegationRoot .revoke(delegator.did) .then((tx) => delegator.authorizeExtrinsic(tx, signer, paymentAccount.address) ) .then((tx) => BlockchainUtils.signAndSubmitTx(tx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, reSign: true, }) ) ).resolves.not.toThrow() await Promise.all([ expect(delegationRoot.verify()).resolves.toBe(false), expect(delegationA.verify()).resolves.toBe(false), expect(delegationB.verify()).resolves.toBe(false), ]) }, 60_000) }) describe('Deposit claiming', () => { it('deposit payer should be able to claim back its own deposit and delete any children', async () => { // Delegation nodes are written on the chain using `paymentAccount`. const rootNode = await writeHierarchy(root, DriversLicense.hash) const delegatedNode = await addDelegation( rootNode.id, rootNode.id, root, root ) const subDelegatedNode = await addDelegation( rootNode.id, delegatedNode.id, root, root ) await expect(DelegationNode.query(delegatedNode.id)).resolves.not.toBeNull() await expect( DelegationNode.query(subDelegatedNode.id) ).resolves.not.toBeNull() const depositClaimTx = await delegatedNode.reclaimDeposit() // Test removal failure with an account that is not the deposit payer. await expect( BlockchainUtils.signAndSubmitTx(depositClaimTx, devBob, { resolveOn: BlockchainUtils.IS_IN_BLOCK, }) ).rejects.toThrow() // Test removal success with the right account. await BlockchainUtils.signAndSubmitTx(depositClaimTx, paymentAccount, { resolveOn: BlockchainUtils.IS_IN_BLOCK, }) await expect(DelegationNode.query(delegatedNode.id)).resolves.toBeNull() await expect(DelegationNode.query(subDelegatedNode.id)).resolves.toBeNull() }, 60_000) }) describe('handling queries to data not on chain', () => { it('DelegationNode query on empty', async () => { return expect(DelegationNode.query(randomAsHex(32))).resolves.toBeNull() }) it('getAttestationHashes on empty', async () => { return expect(getAttestationHashes(randomAsHex(32))).resolves.toEqual([]) }) }) describe('hierarchyDetails', () => { it('can fetch hierarchyDetails', async () => { const rootNode = await writeHierarchy(root, DriversLicense.hash) const delegatedNode = await addDelegation( rootNode.id, rootNode.id, root, attester ) const details = await delegatedNode.getHierarchyDetails() expect(details.cTypeHash).toBe(DriversLicense.hash) expect(details.id).toBe(rootNode.id) }, 60_000) }) afterAll(() => { disconnect() })
the_stack
import { existsSync, mkdirSync } from 'fs'; import { config as Dotenv } from 'dotenv'; import { DatabaseEngine, MomentUnit, EnvAccessToken, EnvOauth, EnvMemoryCache, EnvSSL, EnvTypeorm, EnvLog, EnvUpload, EnvImageScaling, EnvRefreshToken } from '@types'; import { DATABASE_ENGINE, ENVIRONMENT, ARCHIVE_MIME_TYPE, AUDIO_MIME_TYPE, DOCUMENT_MIME_TYPE, IMAGE_MIME_TYPE, VIDEO_MIME_TYPE, CONTENT_TYPE as CONTENT_TYPE_ENUM } from '@enums'; import { list } from '@utils/enum.util'; /** * * @dependency dotenv * * @see https://www.npmjs.com/package/dotenv * */ export class Environment { /** * @description Environment instance */ private static instance: Environment; /** * @description Current root dir */ base = 'dist'; /** * @description Cluster with aggregated data */ cluster: Record<string,unknown>; /** * @description Current environment */ environment: string = ENVIRONMENT.development; /** * @description Errors staged on current environment */ errors: string[] = []; /** * @description Env variables */ variables: Record<string,unknown>; /** * @description Files directories */ readonly dirs: string[] = [ 'archives', 'documents', 'images', 'images/master-copy', 'images/rescale', 'audios', 'videos' ]; private constructor() {} /** * @description Environment singleton getter */ static get(): Environment { if (!Environment.instance) { Environment.instance = new Environment(); } return Environment.instance; } /** * @description Env variables exhaustive key list */ get keys(): string[] { return [ 'ACCESS_TOKEN_SECRET', 'ACCESS_TOKEN_DURATION', 'API_VERSION', 'AUTHORIZED', 'CDN', 'CONTENT_TYPE', 'DOMAIN', 'FACEBOOK_CONSUMER_ID', 'FACEBOOK_CONSUMER_SECRET', 'GITHUB_CONSUMER_ID', 'GITHUB_CONSUMER_SECRET', 'GOOGLE_CONSUMER_ID', 'GOOGLE_CONSUMER_SECRET', 'LINKEDIN_CONSUMER_ID', 'LINKEDIN_CONSUMER_SECRET', 'LOGS_PATH', 'LOGS_TOKEN', 'MEMORY_CACHE', 'MEMORY_CACHE_DURATION', 'PORT', 'REFRESH_TOKEN_DURATION', 'REFRESH_TOKEN_SECRET', 'REFRESH_TOKEN_UNIT', 'RESIZE_IS_ACTIVE', 'RESIZE_PATH_MASTER', 'RESIZE_PATH_SCALE', 'RESIZE_SIZE_LG', 'RESIZE_SIZE_MD', 'RESIZE_SIZE_SM', 'RESIZE_SIZE_XL', 'RESIZE_SIZE_XS', 'SSL_CERT', 'SSL_KEY', 'TYPEORM_DB', 'TYPEORM_CACHE', 'TYPEORM_CACHE_DURATION', 'TYPEORM_HOST', 'TYPEORM_LOG', 'TYPEORM_NAME', 'TYPEORM_PORT', 'TYPEORM_PWD', 'TYPEORM_SYNC', 'TYPEORM_TYPE', 'TYPEORM_USER', 'UPLOAD_MAX_FILE_SIZE', 'UPLOAD_MAX_FILES', 'UPLOAD_PATH', 'UPLOAD_WILDCARDS', 'URL' ] } /** * @description Embeded validation rules for env variables */ get rules(): Record<string,any> { return { /** * @description Access token secret phrase */ ACCESS_TOKEN_SECRET: (value: string): string => { if (!value) { this.errors.push('ACCESS_TOKEN_SECRET not found: please fill an access token secret value in your .env file to strengthen the encryption.'); } if (value && value.toString().length < 32) { this.errors.push('ACCESS_TOKEN_SECRET bad value: please fill an access token secret which have a length >= 32.'); } return value ? value.toString() : null; }, /** * @description Access token duration in minutes * * @default 60 */ ACCESS_TOKEN_DURATION: (value: string): number => { if (value && isNaN( parseInt(value, 10) )) { this.errors.push('ACCESS_TOKEN_DURATION bad value: please fill a duration expressed as a number'); } return parseInt(value, 10) || 60; }, /** * @description Current api version * * @default v1 */ API_VERSION: (value: string): string => { return value ? value.trim().toLowerCase() : 'v1'; }, /** * @description Authorized remote(s) host(s) * * @default null */ AUTHORIZED: (value: string): string => { const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}(:[0-9]{1,5})|\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/; if (!value) { this.errors.push('AUTHORIZED not found: please fill a single host as string or multiple hosts separated by coma (ie: http://my-domain.com or http://my-domain-1.com,http://my-domain-2.com, ...'); } if ( value && value.lastIndexOf(',') === -1 && !regex.test(value)) { this.errors.push('AUTHORIZED bad value: please fill a single host as string or multiple hosts separated by coma (ie: http://my-domain.com or http://my-domain-1.com,http://my-domain-2.com, ...'); } if ( value && value.lastIndexOf(',') !== -1 && value.split(',').some(v => !regex.test(v) )) { this.errors.push('AUTHORIZED bad value: please fill a single host as string or multiple hosts separated by coma (ie: http://my-domain.com or http://my-domain-1.com,http://my-domain-2.com, ...'); } return value ? value.trim().toLowerCase() : null; }, /** * @description Content delivery network location * * @default null */ CDN: (value: string) => { const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}(:[0-9]{1,5})|\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/; if (value && regex.test(value) === false) { this.errors.push('CDN bad value: please fill a valid CDN url'); } return value || null; }, /** * @description Content-Type * * @default application/json */ CONTENT_TYPE: (value: string) => { if (value && !CONTENT_TYPE_ENUM[value]) { this.errors.push(`CONTENT_TYPE bad value: please fill a supported Content-Type must be one of ${list(CONTENT_TYPE_ENUM).join(',')}`); } return value || CONTENT_TYPE_ENUM['application/json']; }, /** * @description Domain of the application in current environment * * @default localhost */ DOMAIN: (value: string): string => { return value ? value.trim().toLowerCase() : 'localhost'; }, /** * @description Facebook application id * * @default null */ FACEBOOK_CONSUMER_ID: (value: string): string => { if (value && /[0-9]{15}/.test(value) === false) { this.errors.push('FACEBOOK_CONSUMER_ID bad value: check your Facebook app settings to fill a correct value.'); } return value || null; }, /** * @description Facebook application secret * * @default null */ FACEBOOK_CONSUMER_SECRET: (value: string): string => { if (value && /[0-9-abcdef]{32}/.test(value) === false) { this.errors.push('FACEBOOK_CONSUMER_SECRET bad value: check your Facebook app settings to fill a correct value.') } return value || null; }, /** * @description Github application id * * @default null */ GITHUB_CONSUMER_ID: (value: string): string => { if (value && /[0-9-a-z-A-Z]{20}/.test(value) === false) { this.errors.push('GITHUB_CONSUMER_ID bad value: check your Github app settings to fill a correct value.'); } return value || null; }, /** * @description Github application secret * * @default null */ GITHUB_CONSUMER_SECRET: (value: string): string => { if (value && /[0-9-A-Z-a-z-_]{40}/.test(value) === false) { this.errors.push('GITHUB_CONSUMER_SECRET bad value: check your Github app and fill a correct value in your .env file.') } return value || null; }, /** * @description Google application id * * @default null */ GOOGLE_CONSUMER_ID: (value: string): string => { if (value && /[0-9]{12}-[0-9-a-z]{32}.apps.googleusercontent.com/.test(value) === false) { this.errors.push('GOOGLE_CONSUMER_ID bad value: check your Google app settings to fill a correct value.'); } return value || null; }, /** * @description Google application secret * * @default null */ GOOGLE_CONSUMER_SECRET: (value: string): string => { if (value && /[0-9-A-Z-a-z-_]{24}/.test(value) === false) { this.errors.push('GOOGLE_CONSUMER_SECRET bad value: check your Google app and fill a correct value in your .env file.') } return value || null; }, /** * @description Linkedin application id * * @default null */ LINKEDIN_CONSUMER_ID: (value: string): string => { if (value && /[0-9-a-z-A-Z]{20}/.test(value) === false) { this.errors.push('LINKEDIN_CONSUMER_ID bad value: check your Linkedin app settings to fill a correct value.'); } return value || null; }, /** * @description Linkedin application secret * * @default null */ LINKEDIN_CONSUMER_SECRET: (value: string): string => { if (value && /[0-9-A-Z-a-z-_]{40}/.test(value) === false) { this.errors.push('LINKEDIN_CONSUMER_SECRET bad value: check your Linkedin app and fill a correct value in your .env file.') } return value || null; }, /** * @description Logs token configuration used by Morgan for output pattern * * @default dev */ LOGS_TOKEN: (value: string): string => { return this.environment === 'production' ? 'combined' : value || 'dev' }, /** * @description Logs path root directory * * @default logs */ LOGS_PATH: (value: string): string => { return `${process.cwd()}/${this.base}/${value || 'logs'}` }, /** * @description Memory cache activated * * @default false */ MEMORY_CACHE: (value: string): boolean => { return !!parseInt(value, 10) || false }, /** * @description Memory cache lifetime duration * * @default 5000 */ MEMORY_CACHE_DURATION: (value: string): number => { return parseInt(value, 10) || 5000 }, /** * @description Listened port. Default 8101 * * @default 8101 */ PORT: (value: string): number => { if (value && ( isNaN(parseInt(value,10)) || parseInt(value,10) > 65535)) { this.errors.push('PORT bad value: please fill a valid TCP port number'); } return parseInt(value,10) || 8101; }, /** * @description Refresh token duration * * @default 30 */ REFRESH_TOKEN_DURATION: (value: string): number => { if (value && isNaN(parseInt(value, 10))) { this.errors.push('REFRESH_TOKEN_DURATION bad value: duration must be a number expressed in minutes.'); } return parseInt(value, 10) || 30; }, /** * @description Refresh token secret phrase */ REFRESH_TOKEN_SECRET: (value: string): string => { if (!value) { this.errors.push('REFRESH_TOKEN_SECRET not found: please fill a refresh token secret value in your .env file to strengthen the encryption.'); } if (value && value.toString().length < 32) { this.errors.push('REFRESH_TOKEN_SECRET bad value: please fill a refresh token secret which have a length >= 32.'); } return value ? value.toString() : null; }, /** * @description Refresh token unit of duration (hours|days|weeks|months) * * @default 30 */ REFRESH_TOKEN_UNIT: (value: string): MomentUnit => { if(value && !['hours', 'days', 'weeks', 'months'].includes(value) ) { this.errors.push('REFRESH_TOKEN_UNIT bad value: unit must be one of hours, days, weeks, months.'); } return (value || 'days') as MomentUnit }, /** * @description Image resizing activated * * @default true */ RESIZE_IS_ACTIVE: (value: string): boolean => { return !!parseInt(value, 10) || true }, /** * @description Directory name for original copy (required) * * @default master-copy */ RESIZE_PATH_MASTER: (value: string): string => { return value || 'master-copy' }, /** * @description Directory name for resizes * * @default rescale */ RESIZE_PATH_SCALE: (value: string): string => { return value || 'rescale' }, /** * @description * * @default 1024 */ RESIZE_SIZE_LG: (value: string): number => { return parseInt(value, 10) || 1024 }, /** * @description * * @default 768 */ RESIZE_SIZE_MD: (value: string): number => { return parseInt(value, 10) || 768 }, /** * @description * * @default 320 */ RESIZE_SIZE_SM: (value: string): number => { return parseInt(value, 10) || 320 }, /** * @description * * @default 1366 */ RESIZE_SIZE_XL: (value: string): number => { return parseInt(value, 10) || 1366 }, /** * @description * * @default 280 */ RESIZE_SIZE_XS: (value: string): number => { return parseInt(value, 10) || 280 }, /** * @description SSL certificate location * * @default null */ SSL_CERT: (value: string): string => { if (value && !existsSync(value)) { this.errors.push('SSL_CERT bad value or SSL certificate not found. Please check path and/or file access rights.') } return value || null }, /** * @description SSL key location * * @default null */ SSL_KEY: (value: string): string => { if (value && !existsSync(value)) { this.errors.push('SSL_KEY bad value or SSL key not found. Please check path and/or file access rights.') } return value || null }, /** * @description * * @default null */ TYPEORM_DB: (value: string): string => { if(!value) { this.errors.push('TYPEORM_DB not found: please define the targeted database.'); } if (value && /^[0-9a-zA-Z_]{3,}$/.test(value) === false) { this.errors.push('TYPEORM_DB bad value: please check the name of your database according [0-9a-zA-Z_].'); } return value || null }, /** * @description * * @default false */ TYPEORM_CACHE: (value: string): boolean => { if(value && isNaN(parseInt(value, 10))) { this.errors.push('TYPEORM_CACHE bad value: please use 0 or 1 to define activation of the db cache'); } return !!parseInt(value, 10) || false }, /** * @description * * @default 5000 */ TYPEORM_CACHE_DURATION: (value: string): number => { if(value && isNaN(parseInt(value,10))) { this.errors.push('TYPEORM_CACHE_DURATION bad value: please fill it with a duration expressed in ms.'); } return parseInt(value,10) || 5000 }, /** * @description * * @default localhost */ TYPEORM_HOST: (value: string): string => { if(!value) { this.errors.push('TYPEORM_HOST not found: please define the database server host.'); } if(value && value !== 'localhost' && /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/.test(value) === false) { this.errors.push('TYPEORM_HOST bad value: please fill it with a valid database server host.'); } return value || 'localhost' }, /** * @description * * @default false */ TYPEORM_LOG: (value: string): boolean => { return !!parseInt(value, 10) || false }, /** * @description * * @default default */ TYPEORM_NAME: (value: string): string => { return value || 'default' }, /** * @description * * @default 3306 */ TYPEORM_PORT: (value: string): number => { if(!value) { this.errors.push('TYPEORM_PORT not found: please define the database server port.'); } return parseInt(value,10) || 3306; }, /** * @description * * @default null */ TYPEORM_PWD: (value: string): string => { if(!value && ![ENVIRONMENT.test, ENVIRONMENT.development].includes(this.environment as ENVIRONMENT)) { this.errors.push('TYPEORM_PWD not found: please define the database user password.'); } return value || null }, /** * @description * * @default false */ TYPEORM_SYNC: (value: string): boolean => { return this.environment === ENVIRONMENT.production ? false : this.environment === ENVIRONMENT.test ? true : !!parseInt(value, 10) || false }, /** * @description * * @default mysql */ TYPEORM_TYPE: (value: string): DatabaseEngine => { if(!value) { this.errors.push('TYPEORM_TYPE not found: please define the database engine type.'); } if(value && !DATABASE_ENGINE[value]) { this.errors.push(`TYPEORM_TYPE bad value: database engine must be one of following: ${list(DATABASE_ENGINE).join(',')}.`); } return (value || 'mysql') as DatabaseEngine }, /** * @description * * @default null */ TYPEORM_USER: (value: string): string => { if(!value) { this.errors.push('TYPEORM_USER not found: please define one user for your database.'); } return value || null }, /** * @description Max upload file size * * @default 2000000 */ UPLOAD_MAX_FILE_SIZE: (value: string): number => { if(value && isNaN(parseInt(value, 10))) { this.errors.push('UPLOAD_MAX_FILE_SIZE bad value: please fill it with an integer.'); } return parseInt(value, 10) || 2000000 }, /** * @description Max number of uploaded files by request * * @default 5 */ UPLOAD_MAX_FILES: (value: string): number => { if(value && isNaN(parseInt(value, 10))) { this.errors.push('UPLOAD_MAX_FILES bad value: please fill it with an integer.'); } return parseInt(value, 10) || 5 }, /** * @description Upload directory path * * @default public */ UPLOAD_PATH: (value: string): string => { return `${process.cwd()}/${this.base}/${value || 'public'}` }, /** * @description Accepted mime-type * * @default AUDIO|ARCHIVE|DOCUMENT|IMAGE|VIDEO */ UPLOAD_WILDCARDS: (value: string): string[] => { const mimes = { AUDIO: AUDIO_MIME_TYPE, ARCHIVE: ARCHIVE_MIME_TYPE, DOCUMENT: DOCUMENT_MIME_TYPE, IMAGE: IMAGE_MIME_TYPE, VIDEO: VIDEO_MIME_TYPE }; const input = value ? value.toString().split(',') : Object.keys(mimes); const keys = Object.keys(mimes).map(k => k.toLowerCase()); if (value && value.toString().split(',').some(key => !keys.includes(key)) ) { this.errors.push(`UPLOAD_WILDCARDS bad value: please fill it with an accepted value (${keys.join(',')}) with coma separation`); } return input .filter(key => mimes[key]) .map(key => mimes[key] as Record<string,unknown> ) .reduce((acc,current) => { return [...acc as string[], ...list(current)] as string[]; }, []) as string[]; }, /** * @description API main URL * * @default http://localhost:8101 */ URL: (value: string): string => { const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}(\.[a-zA-Z0-9()]{1,})?(:[0-9]{1,5})?/; if (value && regex.test(value) === false) { this.errors.push('URL bad value. Please fill a local or remote URL'); } return value || 'http://localhost:8101' } } } /** * @description Set env according to args, and load .env file */ loads(nodeVersion: string): Environment { const [major, minor] = nodeVersion.split('.').map( parseFloat ) if(major < 14 || major === 14 && minor < 16) { this.exit('The node version of the server is too low. Please consider at least v14.16.0.'); } if ( ( process.argv && process.argv.indexOf('--env') !== -1 ) ) { this.environment = ENVIRONMENT[process.argv[process.argv.indexOf('--env') + 1]] as string || ENVIRONMENT.development; } else if ( process.env.RUNNER ) { this.environment = ENVIRONMENT.test; } else if ( process.env.NODE_ENV ) { this.environment = ENVIRONMENT[process.env.NODE_ENV as ENVIRONMENT]; } const path = `${process.cwd()}/${this.base}/env/${this.environment}.env`; if (!existsSync(path)) { this.exit(`Environment file not found at ${path}`); } Dotenv({path}); return this; } /** * @description Extract variables from process.env * * @param args Environment variables */ extracts(args: Record<string,unknown>): Environment { this.variables = this.keys.reduce( (acc, current) => { acc[current] = args[current]; return acc; }, {}); return this; } /** * @description Parse allowed env variables, validate it and returns safe current or default value */ validates(): Environment { this.keys.forEach( (key: string) => { this.variables[key] = this.rules[key](this.variables[key]) }); return this } /** * @description Aggregates some data for easy use */ aggregates(): Environment { this.cluster = { ACCESS_TOKEN: { SECRET: this.variables.ACCESS_TOKEN_SECRET, DURATION: this.variables.ACCESS_TOKEN_DURATION }, API_VERSION: this.variables.API_VERSION, AUTHORIZED: this.variables.AUTHORIZED, CDN: this.variables.CDN, CONTENT_TYPE: this.variables.CONTENT_TYPE, DOMAIN: this.variables.DOMAIN, ENV: this.environment, FACEBOOK: { KEY: 'facebook', IS_ACTIVE: this.variables.FACEBOOK_CONSUMER_ID !== null && this.variables.FACEBOOK_CONSUMER_SECRET !== null, ID: this.variables.FACEBOOK_CONSUMER_ID, SECRET: this.variables.FACEBOOK_CONSUMER_SECRET, CALLBACK_URL: `${this.variables.URL as string}/api/${this.variables.API_VERSION as string}/auth/facebook/callback` }, GITHUB: { KEY: 'github', IS_ACTIVE: this.variables.GITHUB_CONSUMER_ID !== null && this.variables.GITHUB_CONSUMER_SECRET !== null, ID: this.variables.GITHUB_CONSUMER_ID, SECRET: this.variables.GITHUB_CONSUMER_SECRET, CALLBACK_URL: `${this.variables.URL as string}/api/${this.variables.API_VERSION as string}/auth/github/callback` }, GOOGLE: { KEY: 'google', IS_ACTIVE: this.variables.GOOGLE_CONSUMER_ID !== null && this.variables.GOOGLE_CONSUMER_SECRET !== null, ID: this.variables.GOOGLE_CONSUMER_ID, SECRET: this.variables.GOOGLE_CONSUMER_SECRET, CALLBACK_URL: `${this.variables.URL as string}/api/${this.variables.API_VERSION as string}/auth/google/callback` }, LINKEDIN: { KEY: 'linkedin', IS_ACTIVE: this.variables.LINKEDIN_CONSUMER_ID !== null && this.variables.LINKEDIN_CONSUMER_SECRET !== null, ID: this.variables.LINKEDIN_CONSUMER_ID, SECRET: this.variables.LINKEDIN_CONSUMER_SECRET, CALLBACK_URL: `${this.variables.URL as string}/api/${this.variables.API_VERSION as string}/auth/linkedin/callback` }, LOGS: { PATH: this.variables.LOGS_PATH, TOKEN: this.variables.LOGS_TOKEN }, MEMORY_CACHE: { IS_ACTIVE: this.variables.MEMORY_CACHE, DURATION: this.variables.MEMORY_CACHE_DURATION }, PORT: this.variables.PORT, REFRESH_TOKEN: { DURATION: this.variables.REFRESH_TOKEN_DURATION, SECRET: this.variables.REFRESH_TOKEN_SECRET, UNIT: this.variables.REFRESH_TOKEN_UNIT }, SCALING: { IS_ACTIVE: this.variables.RESIZE_IS_ACTIVE, PATH_MASTER: this.variables.RESIZE_PATH_MASTER, PATH_SCALE: this.variables.RESIZE_PATH_SCALE, SIZES: { XS: this.variables.RESIZE_SIZE_XS, SM: this.variables.RESIZE_SIZE_SM, MD: this.variables.RESIZE_SIZE_MD, LG: this.variables.RESIZE_SIZE_LG, XL: this.variables.RESIZE_SIZE_XL } }, SSL: { IS_ACTIVE: this.variables.SSL_CERT !== null && this.variables.SSL_KEY !== null, CERT: this.variables.SSL_CERT, KEY: this.variables.SSL_KEY }, TYPEORM: { DB: this.variables.TYPEORM_DB, NAME: this.variables.TYPEORM_NAME, TYPE: this.variables.TYPEORM_TYPE, HOST: this.variables.TYPEORM_HOST, PORT: this.variables.TYPEORM_PORT, PWD: this.variables.TYPEORM_PWD, USER: this.variables.TYPEORM_USER, SYNC: this.variables.TYPEORM_SYNC, LOG: this.variables.TYPEORM_LOG, CACHE: !this.variables.MEMORY_CACHE && this.variables.TYPEORM_CACHE, CACHE_DURATION: !this.variables.MEMORY_CACHE && this.variables.TYPEORM_CACHE ? this.variables.TYPEORM_CACHE_DURATION : 0, ENTITIES: [ `${process.cwd()}/${this.base}/api/core/models/**/*.model.js`, `${process.cwd()}/${this.base}/api/resources/**/*.model.js` ], MIGRATIONS: `${process.cwd()}/${this.base}/migrations/**/*.js`, SUBSCRIBERS: [ `${process.cwd()}/${this.base}/api/core/subscribers/**/*.subscriber.js`, `${process.cwd()}/${this.base}/api/resources/**/*.subscriber.js` ] }, UPLOAD: { MAX_FILE_SIZE: this.variables.UPLOAD_MAX_FILE_SIZE, MAX_FILES: this.variables.UPLOAD_MAX_FILES, PATH: this.variables.UPLOAD_PATH, WILDCARDS: this.variables.UPLOAD_WILDCARDS }, URL: this.variables.URL }; return this; } /** * @description Creates files directories if not exists */ directories(): Environment { const log = this.cluster.LOGS as { PATH: string }; if ( !existsSync(log.PATH) ) { mkdirSync(log.PATH); } const upload = this.cluster.UPLOAD as { PATH: string }; if ( !existsSync(upload.PATH) ) { mkdirSync(upload.PATH); } this.dirs.forEach(dir => { const path = `${upload.PATH}/${dir}`; if ( !existsSync(path) ) { mkdirSync(path); } }); return this; } /** * @description Say if current environment is valid or not */ isValid(): boolean { return this.errors.length === 0; } /** * @description Exit of current process with error messages * * @param messages */ exit(messages: string|string[]): void { process.stdout.write('\n\x1b[41m[ERROR]\x1b[40m\n\n'); process.stdout.write([].concat(messages).join('\n')); process.exit(0); } } const environment = Environment .get() .loads(process.versions.node) .extracts(process.env) .validates() .aggregates() .directories(); if (!environment.isValid()) environment.exit(environment.errors); const ACCESS_TOKEN = environment.cluster.ACCESS_TOKEN as EnvAccessToken; const API_VERSION = environment.cluster.API_VERSION as string; const AUTHORIZED = environment.cluster.AUTHORIZED as string; const CDN = environment.cluster.CDN as string; const CONTENT_TYPE = environment.cluster.CONTENT_TYPE as string; const DOMAIN = environment.cluster.DOMAINE as string; const ENV = environment.cluster.ENV as string; const FACEBOOK = environment.cluster.FACEBOOK as EnvOauth; const GITHUB = environment.cluster.GITHUB as EnvOauth; const GOOGLE = environment.cluster.GOOGLE as EnvOauth; const LINKEDIN = environment.cluster.LINKEDIN as EnvOauth; const LOGS = environment.cluster.LOGS as EnvLog; const MEMORY_CACHE = environment.cluster.MEMORY_CACHE as EnvMemoryCache; const PORT = environment.cluster.PORT as number; const REFRESH_TOKEN = environment.cluster.REFRESH_TOKEN as EnvRefreshToken; const SCALING = environment.cluster.SCALING as EnvImageScaling; const SSL = environment.cluster.SSL as EnvSSL; const TYPEORM = environment.cluster.TYPEORM as EnvTypeorm; const UPLOAD = environment.cluster.UPLOAD as EnvUpload; const URL = environment.cluster.URL as string; export { ACCESS_TOKEN, API_VERSION, AUTHORIZED, CDN, CONTENT_TYPE, DOMAIN, ENV, FACEBOOK, GITHUB, GOOGLE, LINKEDIN, LOGS, MEMORY_CACHE, PORT, REFRESH_TOKEN, SCALING, SSL, TYPEORM, UPLOAD, URL }
the_stack
import { Template, Choice, ContractId } from "@daml/types"; import Ledger, {CreateEvent} from "./index"; import {assert} from "./index"; import { Event } from "./index"; import * as jtv from "@mojotech/json-type-validation"; import type { EventEmitter } from 'events'; import mockConsole from "jest-mock-console"; const mockLive = jest.fn(); const mockChange = jest.fn(); const mockConstructor = jest.fn(); const mockSend = jest.fn(); const mockClose = jest.fn(); const mockFunctions = [mockLive, mockChange, mockConstructor, mockSend, mockClose]; type Foo = {key: string}; const fooKey = 'fooKey'; type Message = | { events: Event<Foo>[]; offset?: string | null } | { warnings: string[] } | { errors: string[] } | string //for unexpected messages interface MockWebSocket { serverOpen(): void; serverSend(message: Message): void; serverClose(event: {code: number; reason: string}): void; } let mockInstance = undefined as unknown as MockWebSocket; jest.mock('isomorphic-ws', () => class { private eventEmitter: EventEmitter; constructor(...args: unknown[]) { mockConstructor(...args); mockInstance = this; // eslint-disable-next-line @typescript-eslint/no-var-requires const {EventEmitter} = require('events'); this.eventEmitter = new EventEmitter(); } addEventListener(event: string, handler: (...args: unknown[]) => void): void { this.eventEmitter.on(event, handler); } send(message: string): void { mockSend(JSON.parse(message)); } close(): void { mockClose(); } serverOpen(): void { this.eventEmitter.emit('open'); } serverSend(message: Message): void { this.eventEmitter.emit('message', {data: JSON.stringify(message)}); } serverClose(event: {code: number; reason: string}): void { this.eventEmitter.emit('close', event); } }); const Foo: Template<Foo, string, "foo-id"> = { sdkVersion: '0.0.0-SDKVERSION', templateId: "foo-id", keyDecoder: jtv.string(), keyEncode: (s: string): unknown => s, decoder: jtv.object({key: jtv.string()}), encode: (o) => o, Archive: {} as unknown as Choice<Foo, {}, {}, string>, }; const fooCreateEvent = ( coid: number, key?: string, ): CreateEvent<Foo, string, "foo-id"> => { return { templateId: "foo-id", contractId: coid.toString() as ContractId<Foo>, signatories: [], observers: [], agreementText: "fooAgreement", key: key || fooKey, payload: {key: fooKey}, }; }; const fooEvent = (coid: number): Event<Foo, string, "foo-id"> => { return { created: fooCreateEvent(coid) }; }; const fooArchiveEvent = (coid: number): Event<Foo, string, "foo-id"> => { return { archived: { templateId: "foo-id", contractId: coid.toString() as ContractId<Foo>, }, }; }; const mockOptions = { token: "dummyToken", httpBaseUrl: "http://localhost:5000/", wsBaseUrl: "ws://localhost:4000/", }; beforeEach(() => { mockFunctions.forEach(f => f.mockClear()); }); describe("internals", () => { test("assert throws as expected", () => { assert(true, "not thrown"); expect(() => assert(false, "throws")).toThrow(); }); }); describe("streamSubmit", () => { test("receive unknown message", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); expect(mockConstructor).toHaveBeenCalledTimes(1); expect(mockConstructor).toHaveBeenLastCalledWith( 'ws://localhost:4000/v1/stream/query', ['jwt.token.dummyToken', 'daml.ws.auth'], ); stream.on("change", mockChange); mockInstance.serverOpen(); expect(mockSend).toHaveBeenCalledTimes(1); expect(mockSend).toHaveBeenLastCalledWith([{templateIds: [Foo.templateId]}]); const restoreConsole = mockConsole(); mockInstance.serverSend('mickey mouse'); expect(console.error).toHaveBeenCalledWith("Ledger.streamQuery unknown message", "mickey mouse"); restoreConsole(); }); test("receive warnings", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQueries(Foo, []); stream.on("change", mockChange); const restoreConsole = mockConsole(); mockInstance.serverSend({ warnings: ["oh oh"] }); expect(console.warn).toHaveBeenCalledWith("Ledger.streamQueries warnings", {"warnings": ["oh oh"]}); restoreConsole(); }); test("receive errors", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKey(Foo, fooKey); stream.on("change", mockChange); const restoreConsole = mockConsole(); mockInstance.serverSend({ errors: ["not good!"] }); expect(console.error).toHaveBeenCalledWith("Ledger.streamFetchByKey errors", { errors: ["not good!"] }); restoreConsole(); }); test("receive null offset", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); stream.on("live", mockLive); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [], offset: null }); expect(mockLive).toHaveBeenCalledTimes(1); expect(mockLive).toHaveBeenLastCalledWith([]); expect(mockChange).not.toHaveBeenCalled(); }); test("reconnect on server close", async () => { const reconnectThreshold = 200; const ledger = new Ledger({...mockOptions, reconnectThreshold: reconnectThreshold}); const stream = ledger.streamQuery(Foo); stream.on("live", mockLive); stream.on("close", mockClose); mockInstance.serverSend({events: [], offset: '3'}); await new Promise(resolve => setTimeout(resolve, reconnectThreshold * 2)); mockConstructor.mockClear(); mockInstance.serverClose({code: 1, reason: 'test close'}); expect(mockConstructor).toHaveBeenCalled(); mockInstance.serverOpen(); expect(mockSend).toHaveBeenNthCalledWith(1, {offset: "3"}); expect(mockSend).toHaveBeenNthCalledWith(2, [{"templateIds": ["foo-id"]}]); mockSend.mockClear(); mockConstructor.mockClear(); // check that the client doesn't try to reconnect again. it should only reconnect if it // received an event confirming the stream is live again, i.e. {events: [], offset: '3'} mockInstance.serverClose({code: 1, reason: 'test close'}); expect(mockConstructor).not.toHaveBeenCalled(); }); test("do not reconnect on client close", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); expect(mockConstructor).toHaveBeenCalled(); mockConstructor.mockClear(); stream.close(); expect(mockConstructor).not.toHaveBeenCalled(); }); test("receive empty events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [] }); expect(mockChange).toHaveBeenCalledTimes(0); }); test("stop listening to a stream", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); const count1 = jest.fn(); const count2 = jest.fn(); stream.on("change", count1); stream.on("change", count2); mockInstance.serverSend({ events: [1, 2, 3].map(fooEvent) }); expect(count1).toHaveBeenCalledTimes(1); expect(count2).toHaveBeenCalledTimes(1); stream.off("change", count1) mockInstance.serverSend({ events: [1, 2, 3].map(fooEvent) }); expect(count1).toHaveBeenCalledTimes(1); expect(count2).toHaveBeenCalledTimes(2); }); }); describe("streamQuery", () => { test("receive live event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); stream.on("live", mockLive); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)], offset: '3' }); expect(mockLive).toHaveBeenCalledTimes(1); expect(mockLive).toHaveBeenLastCalledWith([fooCreateEvent(1)]); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenLastCalledWith([fooCreateEvent(1)]) }); test("receive one event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenLastCalledWith([fooCreateEvent(1)]); }); test("receive several events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [1, 2, 3].map(fooEvent) }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([1, 2, 3].map(cid => fooCreateEvent(cid))); }); test("drop matching created and archived events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQuery(Foo); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1), fooEvent(2)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(1), fooCreateEvent(2)]); mockChange.mockClear(); mockInstance.serverSend({ events: [fooArchiveEvent(1)]}); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(2)]); }); }); describe("streamQueries", () => { test("receive live event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQueries(Foo, []); stream.on("live", mockLive); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)], offset: '3' }); expect(mockLive).toHaveBeenCalledTimes(1); expect(mockLive).toHaveBeenLastCalledWith([fooCreateEvent(1)]); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenLastCalledWith([fooCreateEvent(1)]) }); test("receive one event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQueries(Foo, []); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenLastCalledWith([fooCreateEvent(1)]); }); test("receive several events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQueries(Foo, []); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [1, 2, 3].map(fooEvent) }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([1, 2, 3].map(cid => fooCreateEvent(cid))); }); test("drop matching created and archived events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamQueries(Foo, []); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1), fooEvent(2)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(1), fooCreateEvent(2)]); mockChange.mockClear(); mockInstance.serverSend({ events: [fooArchiveEvent(1)]}); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(2)]); }); }); describe("streamFetchByKey", () => { test("receive no event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKey(Foo, 'badKey'); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [] }); expect(mockChange).toHaveBeenCalledTimes(0); }); test("receive one event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKey(Foo, fooKey); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith(fooCreateEvent(1)); }); test("receive several events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKey(Foo, fooKey); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1), fooEvent(2), fooEvent(3)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith(fooCreateEvent(3)); }); test("drop matching created and archived events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKey(Foo, fooKey); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith(fooCreateEvent(1)); mockChange.mockClear(); mockInstance.serverSend({ events: [fooArchiveEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith(null); }); }); describe("streamFetchByKeys", () => { test("receive one event", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKeys(Foo, [fooKey]); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(1)]); }); test("receive several events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKeys(Foo, [fooKey]); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1), fooEvent(2), fooEvent(3)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(3)]); }); test("drop matching created and archived events", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKeys(Foo, [fooKey]); stream.on("change", state => mockChange(state)); mockInstance.serverSend({ events: [fooEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([fooCreateEvent(1)]); mockChange.mockClear(); mockInstance.serverSend({ events: [fooArchiveEvent(1)] }); expect(mockChange).toHaveBeenCalledTimes(1); expect(mockChange).toHaveBeenCalledWith([null]); }); test("watch multiple keys", () => { const create = (cid: number, key: string): Event<Foo> => ({created: fooCreateEvent(cid, key)}); const archive = fooArchiveEvent; const send = (events: Event<Foo>[]): void => mockInstance.serverSend({events}); const expectCids = (expected: (number | null)[]): void => expect(mockChange) .toHaveBeenCalledWith( expected.map((cid: number | null, idx) => cid ? fooCreateEvent(cid, 'key' + (idx + 1)) : null)); const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKeys(Foo, ['key1', 'key2']); stream.on("change", state => mockChange(state)); send([create(1, 'key1')]); expectCids([1, null]); send([create(2, 'key2')]); expectCids([1, 2]); send([archive(1), create(3, 'key1')]); expectCids([3, 2]); send([archive(2), archive(3), create(4, 'key2')]); expectCids([null, 4]); }); test("watch zero keys", () => { const ledger = new Ledger(mockOptions); const stream = ledger.streamFetchByKeys(Foo, []); stream.close(); const change = jest.fn(); stream.on("change", state => change(state)); expect(change).toHaveBeenCalledTimes(1); expect(change).toHaveBeenCalledWith([]); mockInstance.serverSend({ events: [1, 2, 3].map(fooEvent) }); expect(change).toHaveBeenCalledWith([]); expect(change).toHaveBeenCalledTimes(1); }); });
the_stack
import { ChannelType, Internal, snowflake } from '.' /** https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-structure */ export interface ApplicationCommand { /** unique id of the command */ id: snowflake /** the type of command, defaults 1 if not set */ type?: ApplicationCommandType /** unique id of the parent application */ application_id: snowflake /** guild id of the command, if not global */ guild_id?: snowflake /** 1-32 character name */ name: string /** 1-100 character description for CHAT_INPUT commands, empty string for USER and MESSAGE commands */ description: string /** the parameters for the command, max 25 */ options?: ApplicationCommandOption[] /** whether the command is enabled by default when the app is added to a guild */ default_permission?: boolean /** autoincrementing version identifier updated during substantial record changes */ version: snowflake } /** https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-types */ export enum ApplicationCommandType { /** Slash commands; a text-based command that shows up when a user types / */ CHAT_INPUT = 1, /** A UI-based command that shows up when you right click or tap on a user */ USER = 2, /** A UI-based command that shows up when you right click or tap on a message */ MESSAGE = 3, } /** https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure */ export interface ApplicationCommandOption { /** the type of option */ type: ApplicationCommandOptionType /** 1-32 character name */ name: string /** 1-100 character description */ description: string /** if the parameter is required or optional--default false */ required?: boolean /** choices for STRING, INTEGER, and NUMBER types for the user to pick from, max 25 */ choices?: ApplicationCommandOptionChoice[] /** if the option is a subcommand or subcommand group type, this nested options will be the parameters */ options?: ApplicationCommandOption[] /** if the option is a channel type, the channels shown will be restricted to these types */ channel_types?: ChannelType[] } /** https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type */ export enum ApplicationCommandOptionType { SUB_COMMAND = 1, SUB_COMMAND_GROUP = 2, STRING = 3, /** Any integer between -2^53 and 2^53 */ INTEGER = 4, BOOLEAN = 5, USER = 6, /** Includes all channel types + categories */ CHANNEL = 7, ROLE = 8, /** Includes users and roles */ MENTIONABLE = 9, /** Any double between -2^53 and 2^53 */ NUMBER = 10, } /** https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-choice-structure */ export interface ApplicationCommandOptionChoice { /** 1-100 character choice name */ name: string /** value of the choice, up to 100 characters if string */ value: string | number } /** https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-interaction-data-option-structure */ export interface ApplicationCommandInteractionDataOption { /** the name of the parameter */ name: string /** value of application command option type */ type: ApplicationCommandOptionType /** the value of the pair */ value?: ApplicationCommandOptionType /** present if this option is a group or subcommand */ options?: ApplicationCommandInteractionDataOption[] } /** https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-guild-application-command-permissions-structure */ export interface GuildApplicationCommandPermissions { /** the id of the command */ id: snowflake /** the id of the application the command belongs to */ application_id: snowflake /** the id of the guild */ guild_id: snowflake /** the permissions for the command in the guild */ permissions: ApplicationCommandPermissions[] } /** https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permissions-structure */ export interface ApplicationCommandPermissions { /** the id of the role or user */ id: snowflake /** role or user */ type: ApplicationCommandPermissionType /** true to allow, false, to disallow */ permission: boolean } /** https://discord.com/developers/docs/interactions/application-commands#application-command-permissions-object-application-command-permission-type */ export enum ApplicationCommandPermissionType { ROLE = 1, USER = 2, } declare module './internal' { interface Internal { /** https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands */ getGlobalApplicationCommands(application_id: snowflake): Promise<ApplicationCommand[]> /** https://discord.com/developers/docs/interactions/application-commands#create-global-application-command */ createGlobalApplicationCommand(application_id: snowflake, command: Partial<ApplicationCommand>): Promise<ApplicationCommand> /** https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands */ bulkOverwriteGlobalApplicationCommands(application_id: snowflake): Promise<ApplicationCommand[]> /** https://discord.com/developers/docs/interactions/application-commands#get-global-application-command */ getGlobalApplicationCommand(application_id: snowflake, command_id: snowflake): Promise<ApplicationCommand> /** https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command */ editGlobalApplicationCommand(application_id: snowflake, command_id: snowflake, command: Partial<ApplicationCommand>): Promise<ApplicationCommand> /** https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command */ deleteGlobalApplicationCommand(application_id: snowflake, command_id: snowflake): Promise<void> /** https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands */ getGuildApplicationCommands(application_id: snowflake, guild_id: snowflake): Promise<ApplicationCommand[]> /** https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command */ createGuildApplicationCommand(application_id: snowflake, guild_id: snowflake, command: Partial<ApplicationCommand>): Promise<ApplicationCommand> /** https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands */ bulkOverwriteGuildApplicationCommands(application_id: snowflake, guild_id: snowflake): Promise<void> /** https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command-permissions */ getGuildApplicationCommandPermissions(application_id: snowflake, guild_id: snowflake): Promise<GuildApplicationCommandPermissions[]> /** https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions */ batchEditApplicationCommandPermissions(application_id: snowflake, guild_id: snowflake, permissions: Partial<GuildApplicationCommandPermissions>[]): Promise<void> /** https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command */ getGuildApplicationCommand(application_id: snowflake, guild_id: snowflake, command_id: snowflake): Promise<ApplicationCommand> /** https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command */ editGuildApplicationCommand(application_id: snowflake, guild_id: snowflake, command_id: snowflake, command: Partial<ApplicationCommand>): Promise<ApplicationCommand> /** https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command */ deleteGuildApplicationCommand(application_id: snowflake, guild_id: snowflake, command_id: snowflake): Promise<void> /** https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions */ getApplicationCommandPermissions(application_id: snowflake, guild_id: snowflake, command_id: snowflake): Promise<GuildApplicationCommandPermissions> /** https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions */ editApplicationCommandPermissions(application_id: snowflake, guild_id: snowflake, command_id: snowflake, permissions: ApplicationCommandPermissions[]): Promise<GuildApplicationCommandPermissions> } } Internal.define({ '/applications/{application.id}/commands': { GET: 'getGlobalApplicationCommands', POST: 'createGlobalApplicationCommand', PUT: 'bulkOverwriteGlobalApplicationCommands', }, '/applications/{application.id}/commands/{command.id}': { GET: 'getGlobalApplicationCommand', PATCH: 'editGlobalApplicationCommand', DELETE: 'deleteGlobalApplicationCommand', }, '/applications/{application.id}/guilds/{guild.id}/commands': { GET: 'getGuildApplicationCommands', POST: 'createGuildApplicationCommand', PUT: 'bulkOverwriteGuildApplicationCommands', }, '/applications/{application.id}/guilds/{guild.id}/commands/{command.id}': { GET: 'getGuildApplicationCommand', PATCH: 'editGuildApplicationCommand', DELETE: 'deleteGuildApplicationCommand', }, '/applications/{application.id}/guilds/{guild.id}/commands/permissions': { GET: 'getGuildApplicationCommandPermissions', PUT: 'batchEditApplicationCommandPermissions', }, '/applications/{application.id}/guilds/{guild.id}/commands/{command.id}/permissions': { GET: 'getApplicationCommandPermissions', PUT: 'editApplicationCommandPermissions', }, })
the_stack
import './index'; import fetchMock, { MockRequest, MockResponse } from 'fetch-mock'; import { assert } from 'chai'; import { childShaderArraysDiffer, childShadersAreDifferent, defaultChildShaderScrapHashOrName, defaultImageURL, defaultScrapBody, numPredefinedUniforms, ShaderNode, } from './index'; import { CanvasKit, CanvasKitInit as CKInit } from '../../build/canvaskit/canvaskit'; import { ChildShader, ScrapBody, ScrapID } from '../json'; // It is assumed that canvaskit.js has been loaded and this symbol is available globally. declare const CanvasKitInit: typeof CKInit; let canvasKit: CanvasKit | null = null; const getCanvasKit = async (): Promise<CanvasKit> => { if (canvasKit) { return canvasKit; } canvasKit = await CanvasKitInit({ locateFile: (file: string) => `/canvaskit_assets/${file}` }); if (!canvasKit) { throw new Error('Could not load CanvasKit'); } return canvasKit; }; const createShaderNode = async (): Promise<ShaderNode> => { const ck = await getCanvasKit(); const node = new ShaderNode(ck); await node.setScrap(defaultScrapBody); return node; }; const createShaderNodeWithChildShader = async (): Promise<ShaderNode> => { const ck = await getCanvasKit(); const node = new ShaderNode(ck); const childScrapBody: ScrapBody = { Body: `half4 main(vec2 fragcoord) { return half4(0, 1, 0, 1); }`, Type: 'sksl', SKSLMetaData: { Children: [], ImageURL: '', Uniforms: [], }, }; fetchMock.get(`/_/load/${defaultChildShaderScrapHashOrName}`, childScrapBody); const scrapBodyWithChild: ScrapBody = { Body: `half4 main(vec2 fragcoord) { return half4(0, 1, 0, 1); }`, Type: 'sksl', SKSLMetaData: { Children: [{ UniformName: 'childShader', ScrapHashOrName: defaultChildShaderScrapHashOrName, }, ], ImageURL: '', Uniforms: [], }, }; await node.setScrap(scrapBodyWithChild); await fetchMock.flush(); fetchMock.restore(); return node; }; describe('ShaderNode', async () => { it('constructor builds with a default shader', async () => { const node = await createShaderNode(); node.compile(); // Confirm that all the post-compile pre-calculations are done correctly. assert.equal(node.getUniformCount(), numPredefinedUniforms, 'The default shader doesn\'t have any user uniforms.'); assert.equal(node.getUniform(0).name, 'iResolution', 'Confirm the predefined shaders show up in the uniforms.'); assert.equal(node.getUniformFloatCount(), node.numPredefinedUniformValues, 'These are equal because the default shader has 0 user uniforms.'); assert.isNotNull(node['uniformsMallocObj'], "We Malloc'd"); assert.equal(node.numPredefinedUniformValues, 11, 'The number of predefined uniform values is calculated after compile() is called. This value will change if predefinedUniforms is changed.'); assert.deepEqual(node.compileErrorLineNumbers, []); assert.equal(node.compileErrorMessage, ''); }); it('updates all values when a new shader is compiled.', async () => { const node = await createShaderNode(); node.compile(); assert.isNotNull(node.getShader([])); // Check our starting values. assert.equal(node.getUniformCount(), numPredefinedUniforms, 'The default shader doesn\'t have any user uniforms.'); assert.equal(node.getUniform(0).name, 'iResolution', 'Confirm the predefined shaders show up in the uniforms.'); assert.equal(node.getUniformFloatCount(), node.numPredefinedUniformValues, 'These are equal because the default shader has 0 user uniforms.'); // Set code that has a user uniform, in this case with 4 floats. await node.setScrap({ Type: 'sksl', Body: `uniform float4 iColorWithAlpha; half4 main(float2 fragCoord) { return half4(iColorWithAlpha); } `, SKSLMetaData: { Children: [], ImageURL: '', Uniforms: [1, 0, 1, 0], }, }); node.compile(); assert.isNotNull(node.getShader([0, 0, 0, 0])); // Confirm that all the post-compile pre-calculations are done correctly for the new shader. assert.equal(node.getUniformCount(), numPredefinedUniforms + 1, 'The new shader has 1 user uniform.'); assert.equal(node.getUniform(0).name, 'iResolution', 'Confirm the predefined shaders show up in the uniforms.'); assert.equal(node.getUniformFloatCount(), node.numPredefinedUniformValues + 4, 'The user uniform contributes 4 floats to the total.'); }); it('correctly indicates when run() needs to be called.', async () => { const node = await createShaderNode(); node.compile(); assert.isFalse(node.needsCompile(), 'Should not need a run immediately after a call to compile().'); const originalCode = node.shaderCode; node.shaderCode += '\n'; assert.isTrue(node.needsCompile(), 'Needs compile when code has changed.'); node.shaderCode = originalCode; assert.isFalse(node.needsCompile(), 'No longer needs a compile when change is undone.'); }); it('correctly indicates when save() needs to be called.', async () => { const node = await createShaderNode(); node.compile(); const startingUniformValues = [1, 0, 1, 0]; const modifiedUniformValues = [1, 1, 1, 1]; // Set code that has a user uniform, in this case with 4 floats, because // saving is not only indicated when the code changes, but when the user // uniforms change. await node.setScrap({ Type: 'sksl', Body: `uniform float4 iColorWithAlpha; half4 main(float2 fragCoord) { return half4(iColorWithAlpha); } `, SKSLMetaData: { Children: [], ImageURL: '', Uniforms: startingUniformValues, }, }); node.compile(); const originalCode = node.shaderCode; assert.isFalse(node.needsSave(), 'No need to save at the start.'); // Changing the code means we need to save. node.shaderCode += '\n'; assert.isTrue(node.needsSave(), 'Needs save if code changed.'); node.shaderCode = originalCode; assert.isFalse(node.needsSave(), "Doesn't need save when code restored."); // Also changing the user uniform values means we need to save. node.currentUserUniformValues = modifiedUniformValues; assert.isTrue(node.needsSave(), 'Needs save if uniform values changed.'); node.currentUserUniformValues = startingUniformValues; assert.isFalse(node.needsSave(), "Doesn't need save if uniform values restored."); }); it('reports compiler errors', async () => { const node = await createShaderNode(); node.compile(); await node.setScrap({ Type: 'sksl', Body: `uniform float4 iColorWithAlpha; half4 main(float2 fragCoord) { return half4(iColorWithAlpha) // Missing trailing semicolon. } `, SKSLMetaData: { Children: [], ImageURL: '', Uniforms: [1, 0, 1, 0], }, }); node.compile(); assert.deepEqual(node.compileErrorLineNumbers, [5]); node.compileErrorMessage.startsWith("error: 5: expected ';', but found '}'"); }); it('makes a copy of the ScrapBody', async () => { const node = await createShaderNode(); const startScrap = node.getScrap(); assert.isNotEmpty(startScrap.Body); startScrap.Body = ''; // Confirm we haven't changed the original scrap. assert.isNotEmpty(node['body']!.Body); }); it('always starts with non-null input image', async () => { const node = await createShaderNode(); assert.isNotNull(node.inputImageElement); }); it('protects against unsafe URLs', async () => { const node = await createShaderNode(); node['currentImageURL'] = 'data:foo'; assert.equal(node.getCurrentImageURL(), 'data:foo'); assert.equal(node.getSafeImageURL(), defaultImageURL); }); it('reverts to empty image URL if image fails to load.', async () => { const node = await createShaderNode(); await node.setCurrentImageURL('/dist/some-unknown-image.png'); assert.equal(node.getCurrentImageURL(), ''); }); describe('child shader', () => { it('is created on loadScrap', async () => { const node = await createShaderNodeWithChildShader(); assert.equal(1, node.children.length); assert.equal(defaultChildShaderScrapHashOrName, node.children[0]['scrapID']); assert.equal(node.getChildShader(0).UniformName, 'childShader'); }); it('can be removed', async () => { const node = await createShaderNodeWithChildShader(); node.removeChildShader(0); assert.equal(0, node.children.length); }); it('throws on out of bounds when removing shader', async () => { const node = await createShaderNodeWithChildShader(); assert.throws(() => { node.removeChildShader(2); }); }); it('throws on out of bounds when accessing child shader', async () => { const node = await createShaderNodeWithChildShader(); assert.throws(() => { node.getChildShader(2); }); }); it('can be appended', async () => { const node = await createShaderNode(); const childScrapBody: ScrapBody = { Body: `half4 main(vec2 fragcoord) { return half4(0, 1, 0, 1); }`, Type: 'sksl', SKSLMetaData: { Children: [], ImageURL: '', Uniforms: [], }, }; fetchMock.get(`/_/load/${defaultChildShaderScrapHashOrName}`, childScrapBody); await node.appendNewChildShader(); assert.equal(1, node.children.length); assert.equal(defaultChildShaderScrapHashOrName, node.children[0]['scrapID']); await fetchMock.flush(); assert.isTrue(fetchMock.done()); fetchMock.restore(); }); it('has a name', async () => { const node = await createShaderNodeWithChildShader(); assert.equal(node.getChildShaderUniformName(0), 'childShader'); }); it('has uniform declarations', async () => { const node = await createShaderNodeWithChildShader(); assert.equal(node.getChildShaderUniforms(), 'uniform shader childShader;'); }); it('has a name that can be changed', async () => { const node = await createShaderNodeWithChildShader(); const newUniformName = 'someNewName'; const childScrapBody: ScrapBody = { Body: `half4 main(vec2 fragcoord) { return half4(0, 1, 0, 1); }`, Type: 'sksl', SKSLMetaData: { Children: [], ImageURL: '', Uniforms: [], }, }; fetchMock.get(`/_/load/${defaultChildShaderScrapHashOrName}`, childScrapBody); await node.setChildShaderUniformName(0, newUniformName); assert.equal(node.getChildShaderUniformName(0), newUniformName); await fetchMock.flush(); assert.isTrue(fetchMock.done()); fetchMock.restore(); }); it('raises on invalid child shader names', async () => { const node = await createShaderNodeWithChildShader(); await node.setChildShaderUniformName(0, 'this is an invalid uniform name because it contains spaces') .then(() => assert.fail()) .catch((err: Error) => assert.match(err.message, /Invalid uniform name/)); }); it('raises on out of bounds', async () => { const node = await createShaderNodeWithChildShader(); await node.setChildShaderUniformName(1, 'aNewName') .then(() => assert.fail()) .catch((err: Error) => assert.match(err.message, /does not exist/)); }); it('saves depth first', async () => { const parentNodeSavedID = 'parentNodeSavedID'; const childNodeSavedID = 'childNodeSavedID'; const node = await createShaderNodeWithChildShader(); // The save endpoint should be called twice, the first time from the child // node, and the second time from the parent node. const callOrder = [childNodeSavedID, parentNodeSavedID]; const bodiesSent = [ '{"Body":"half4 main(vec2 fragcoord) {\\n return half4(0, 1, 0, 1);\\n }","Type":"sksl","SKSLMetaData":{"Uniforms":[],"ImageURL":"","Children":[]}}', '{"Body":"half4 main(vec2 fragcoord) {\\n return half4(0, 1, 0, 1);\\n }","Type":"sksl","SKSLMetaData":{"Uniforms":[],"ImageURL":"","Children":[{"UniformName":"childShader","ScrapHashOrName":"childNodeSavedID"}]}}', ]; let call = 0; fetchMock.post('/_/save/', (url: string, opts: MockRequest): MockResponse => { const { body } = opts; assert.equal(body, bodiesSent[call]); const resp: ScrapID = { Hash: callOrder[call], }; call++; return resp; }, { sendAsJson: true, }); const newID = await node.saveScrap(); await fetchMock.flush(); assert.isTrue(fetchMock.done()); fetchMock.restore(); assert.equal(newID, parentNodeSavedID); }); }); describe('childShadersAreDifferent', () => { it('detects differences', () => { const a: ChildShader = { UniformName: 'foo', ScrapHashOrName: '@someName', }; const b: ChildShader = { UniformName: 'bar', ScrapHashOrName: '@someName', }; const c: ChildShader = { UniformName: 'foo', ScrapHashOrName: '@someDifferentName', }; assert.isTrue(childShadersAreDifferent(a, b)); assert.isTrue(childShadersAreDifferent(b, c)); assert.isTrue(childShadersAreDifferent(a, c)); assert.isFalse(childShadersAreDifferent(a, a)); }); }); describe('childShaderArraysDiffer', () => { it('handles empty arrays', () => { assert.isFalse(childShaderArraysDiffer([], [])); }); it('handles different sized arrays', () => { const a: ChildShader = { UniformName: 'foo', ScrapHashOrName: '@someName', }; assert.isTrue(childShaderArraysDiffer([], [a])); assert.isTrue(childShaderArraysDiffer([a], [])); assert.isTrue(childShaderArraysDiffer([a], [a, a])); assert.isFalse(childShaderArraysDiffer([a], [a])); }); }); });
the_stack
import { Location } from '@angular/common'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { Component } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { ActivatedRoute, Data } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import { AccountService } from 'app/core/auth/account.service'; import { Course } from 'app/entities/course.model'; import { Exam } from 'app/entities/exam.model'; import { ExamChecklistCheckComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist-check/exam-checklist-check.component'; import { ExamChecklistExerciseGroupTableComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist-exercisegroup-table/exam-checklist-exercisegroup-table.component'; import { ExamChecklistComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist.component'; import { ExamDetailComponent } from 'app/exam/manage/exams/exam-detail.component'; import { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive'; import { ProgressBarComponent } from 'app/shared/dashboards/tutor-participation-graph/progress-bar/progress-bar.component'; import { ArtemisMarkdownService } from 'app/shared/markdown.service'; import { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe'; import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe'; import { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks'; import { CourseExamArchiveButtonComponent } from 'app/shared/components/course-exam-archive-button/course-exam-archive-button.component'; import { TranslateDirective } from 'app/shared/language/translate.directive'; import { ExamManagementService } from 'app/exam/manage/exam-management.service'; import { HttpResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive'; import { MockAccountService } from '../../../../helpers/mocks/service/mock-account.service'; @Component({ template: '', }) class DummyComponent {} describe('ExamDetailComponent', () => { let examDetailComponentFixture: ComponentFixture<ExamDetailComponent>; let examDetailComponent: ExamDetailComponent; let service: ExamManagementService; const exampleHTML = '<h1>Sample Markdown</h1>'; const exam = new Exam(); beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes([ { path: 'course-management/:courseId/exams/:examId/edit', component: DummyComponent }, { path: 'course-management/:courseId/exams/:examId/exercise-groups', component: DummyComponent }, { path: 'course-management/:courseId/exams/:examId/assessment-dashboard', component: DummyComponent }, { path: 'course-management/:courseId/exams/:examId/scores', component: DummyComponent }, { path: 'course-management/:courseId/exams/:examId/student-exams', component: DummyComponent }, { path: 'course-management/:courseId/exams/:examId/test-runs', component: DummyComponent }, { path: 'course-management/:courseId/exams/:examId/students', component: DummyComponent }, { path: 'course-management/:courseId/exams', component: DummyComponent }, ]), HttpClientTestingModule, ], declarations: [ ExamDetailComponent, DummyComponent, MockPipe(ArtemisTranslatePipe), MockPipe(ArtemisDatePipe), MockComponent(FaIconComponent), MockDirective(TranslateDirective), MockDirective(HasAnyAuthorityDirective), ExamChecklistComponent, ExamChecklistCheckComponent, ExamChecklistExerciseGroupTableComponent, ProgressBarComponent, MockDirective(NgbTooltip), MockComponent(CourseExamArchiveButtonComponent), MockDirective(DeleteButtonDirective), ], providers: [ { provide: ActivatedRoute, useValue: { data: { subscribe: (fn: (value: Data) => void) => fn({ exam, }), }, snapshot: {}, }, }, { provide: AccountService, useClass: MockAccountService }, MockProvider(ArtemisMarkdownService, { safeHtmlForMarkdown: () => exampleHTML, }), ], schemas: [], }) .compileComponents() .then(() => { examDetailComponentFixture = TestBed.createComponent(ExamDetailComponent); examDetailComponent = examDetailComponentFixture.componentInstance; service = TestBed.inject(ExamManagementService); }); }); beforeEach(function () { // reset exam exam.id = 1; exam.course = new Course(); exam.course.isAtLeastInstructor = true; exam.course.isAtLeastEditor = true; exam.course.id = 1; exam.title = 'Example Exam'; exam.numberOfRegisteredUsers = 3; exam.maxPoints = 100; exam.exerciseGroups = []; examDetailComponent.exam = exam; }); afterEach(() => { jest.restoreAllMocks(); }); it('should load exam from route and display it to user', () => { examDetailComponentFixture.detectChanges(); expect(examDetailComponent).not.toBeNull(); // stand in for other properties too who are simply loaded from the exam and displayed in spans const titleSpan = examDetailComponentFixture.debugElement.query(By.css('#examTitle')).nativeElement; expect(titleSpan).not.toBeNull(); expect(titleSpan.innerHTML).toEqual(exam.title); }); it('should correctly route to edit subpage', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const editButton = examDetailComponentFixture.debugElement.query(By.css('#editButton')).nativeElement; editButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/edit'); }); })); it('should correctly route to student exams subpage', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const studentExamsButton = examDetailComponentFixture.debugElement.query(By.css('#studentExamsButton')).nativeElement; studentExamsButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/student-exams'); }); })); it('should correctly route to dashboard', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const dashboardButton = examDetailComponentFixture.debugElement.query(By.css('#assessment-dashboard-button')).nativeElement; dashboardButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/assessment-dashboard'); }); })); it('should correctly route to exercise groups', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const dashboardButton = examDetailComponentFixture.debugElement.query(By.css('#exercises-button-groups')).nativeElement; dashboardButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/exercise-groups'); }); })); it('should correctly route to scores', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const scoresButton = examDetailComponentFixture.debugElement.query(By.css('#scores-button')).nativeElement; scoresButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/scores'); }); })); it('should correctly route to students', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const studentsButton = examDetailComponentFixture.debugElement.query(By.css('#students-button')).nativeElement; studentsButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/students'); }); })); it('should correctly route to test runs', fakeAsync(() => { const location = examDetailComponentFixture.debugElement.injector.get(Location); examDetailComponentFixture.detectChanges(); const studentsButton = examDetailComponentFixture.debugElement.query(By.css('#testrun-button')).nativeElement; studentsButton.click(); examDetailComponentFixture.whenStable().then(() => { expect(location.path()).toEqual('/course-management/1/exams/1/test-runs'); }); })); it('should return general routes correctly', () => { const route = examDetailComponent.getExamRoutesByIdentifier('edit'); expect(JSON.stringify(route)).toEqual(JSON.stringify(['/course-management', exam.course!.id, 'exams', exam.id, 'edit'])); }); it('Should reset an exam when reset exam is called', () => { // GIVEN examDetailComponent.exam = { ...exam, studentExams: [{ id: 1 }] }; const responseFakeReset = { body: exam } as HttpResponse<Exam>; jest.spyOn(service, 'reset').mockReturnValue(of(responseFakeReset)); jest.spyOn(service, 'reset').mockReturnValue(of(responseFakeReset)); // WHEN examDetailComponent.resetExam(); // THEN expect(service.reset).toHaveBeenCalledOnce(); expect(examDetailComponent.exam).toEqual(exam); }); it('should delete an exam when delete exam is called', () => { // GIVEN examDetailComponent.exam = exam; const responseFakeDelete = {} as HttpResponse<any[]>; const responseFakeEmptyExamArray = { body: [exam] } as HttpResponse<Exam[]>; jest.spyOn(service, 'delete').mockReturnValue(of(responseFakeDelete)); jest.spyOn(service, 'findAllExamsForCourse').mockReturnValue(of(responseFakeEmptyExamArray)); // WHEN examDetailComponent.deleteExam(exam.id!); // THEN expect(service.delete).toHaveBeenCalledOnce(); }); });
the_stack
import { Ripemd160, Secp256k1, Sha1, Sha256 } from '../../../crypto/crypto'; import { InstructionSet } from '../../virtual-machine'; import { conditionallyEvaluate, incrementOperationCount, mapOverOperations, } from '../common/combinators'; import { applyError, AuthenticationErrorCommon, checkLimitsCommon, cloneAuthenticationProgramStateCommon, cloneStack, commonOperations, ConsensusCommon, createAuthenticationProgramStateCommon, createTransactionContextCommon, stackItemIsTruthy, undefinedOperation, } from '../common/common'; import { AuthenticationInstruction } from '../instruction-sets-types'; import { authenticationInstructionsAreMalformed, parseBytecode, } from '../instruction-sets-utils'; import { AuthenticationErrorBCH } from './bch-errors'; import { OpcodesBCH } from './bch-opcodes'; import { bitcoinCashOperations } from './bch-operations'; import { AuthenticationProgramBCH, AuthenticationProgramStateBCH, } from './bch-types'; export { OpcodesBCH }; const enum PayToScriptHash { length = 3, lastElement = 2, } export const isPayToScriptHash = <Opcodes>( verificationInstructions: readonly AuthenticationInstruction<Opcodes>[] ) => verificationInstructions.length === PayToScriptHash.length && ((verificationInstructions[0].opcode as unknown) as number) === OpcodesBCH.OP_HASH160 && ((verificationInstructions[1].opcode as unknown) as number) === OpcodesBCH.OP_PUSHBYTES_20 && ((verificationInstructions[PayToScriptHash.lastElement] .opcode as unknown) as number) === OpcodesBCH.OP_EQUAL; const enum SegWit { minimumLength = 4, maximumLength = 42, OP_0 = 0, OP_1 = 81, OP_16 = 96, versionAndLengthBytes = 2, } /** * Test a stack item for the SegWit Recovery Rules activated in `BCH_2019_05`. * * @param bytecode - the stack item to test */ // eslint-disable-next-line complexity export const isWitnessProgram = (bytecode: Uint8Array) => { const correctLength = bytecode.length >= SegWit.minimumLength && bytecode.length <= SegWit.maximumLength; const validVersionPush = bytecode[0] === SegWit.OP_0 || (bytecode[0] >= SegWit.OP_1 && bytecode[0] <= SegWit.OP_16); const correctLengthByte = bytecode[1] + SegWit.versionAndLengthBytes === bytecode.length; return correctLength && validVersionPush && correctLengthByte; }; /** * From C++ implementation: * Note that IsPushOnly() *does* consider OP_RESERVED to be a push-type * opcode, however execution of OP_RESERVED fails, so it's not relevant to * P2SH/BIP62 as the scriptSig would fail prior to the P2SH special * validation code being executed. */ const isPushOperation = (opcode: number) => opcode < OpcodesBCH.OP_16; /** * This library's supported versions of the BCH virtual machine. "Strict" * versions (A.K.A. `isStandard` from the C++ implementations) enable additional * validation which is commonly used on the P2P network before relaying * transactions. Transactions which fail these rules are often called * "non-standard" – the transactions can technically be included by miners in * valid blocks, but most network nodes will refuse to relay them. * * BCH instruction sets marked `SPEC` ("specification") have not yet been * deployed on the main network and are subject to change. After deployment, the * `SPEC` suffix is removed. This change only effects the name of the TypeScript * enum member – the value remains the same. E.g. * `InstructionSetBCH.BCH_2020_05_SPEC` became `InstructionSetBCH.BCH_2020_05`, * but the value remained `BCH_2020_05`. * * This allows consumers to select an upgrade policy: when a version of Libauth * is released in which compatibility with a deployed virtual machine is * confirmed, this change can help to identify downstream code which requires * review. * - Consumers which prefer to upgrade manually should specify a `SPEC` type, * e.g. `InstructionSetBCH.BCH_2020_05_SPEC`. * - Consumers which prefer full compatibility between Libauth version should * specify a precise instruction set value (e.g. `BCH_2020_05`) or use the * dedicated "current" value: `instructionSetBCHCurrentStrict`. */ export enum InstructionSetBCH { BCH_2019_05 = 'BCH_2019_05', BCH_2019_05_STRICT = 'BCH_2019_05_STRICT', BCH_2019_11 = 'BCH_2019_11', BCH_2019_11_STRICT = 'BCH_2019_11_STRICT', BCH_2020_05 = 'BCH_2020_05', BCH_2020_05_STRICT = 'BCH_2020_05_STRICT', BCH_2020_11_SPEC = 'BCH_2020_11', BCH_2020_11_STRICT_SPEC = 'BCH_2020_11_STRICT', BCH_2021_05_SPEC = 'BCH_2021_05', BCH_2021_05_STRICT_SPEC = 'BCH_2021_05_STRICT', BCH_2021_11_SPEC = 'BCH_2021_11', BCH_2021_11_STRICT_SPEC = 'BCH_2021_11_STRICT', BCH_2022_05_SPEC = 'BCH_2022_05', BCH_2022_05_STRICT_SPEC = 'BCH_2022_05_STRICT', BCH_2022_11_SPEC = 'BCH_2022_11', BCH_2022_11_STRICT_SPEC = 'BCH_2022_11_STRICT', } /** * The current strict virtual machine version used by the Bitcoin Cash (BCH) * network. */ export const instructionSetBCHCurrentStrict = InstructionSetBCH.BCH_2020_05_STRICT; // eslint-disable-next-line complexity export const getFlagsForInstructionSetBCH = ( instructionSet: InstructionSetBCH ) => { switch (instructionSet) { case InstructionSetBCH.BCH_2019_05: return { disallowUpgradableNops: false, opReverseBytes: false, requireBugValueZero: false, requireMinimalEncoding: false, requireNullSignatureFailures: true, }; case InstructionSetBCH.BCH_2019_05_STRICT: return { disallowUpgradableNops: true, opReverseBytes: false, requireBugValueZero: false, requireMinimalEncoding: true, requireNullSignatureFailures: true, }; case InstructionSetBCH.BCH_2019_11: return { disallowUpgradableNops: false, opReverseBytes: false, requireBugValueZero: true, requireMinimalEncoding: true, requireNullSignatureFailures: true, }; case InstructionSetBCH.BCH_2019_11_STRICT: return { disallowUpgradableNops: true, opReverseBytes: false, requireBugValueZero: true, requireMinimalEncoding: true, requireNullSignatureFailures: true, }; case InstructionSetBCH.BCH_2020_05: return { disallowUpgradableNops: false, opReverseBytes: true, requireBugValueZero: false, requireMinimalEncoding: false, requireNullSignatureFailures: true, }; case InstructionSetBCH.BCH_2020_05_STRICT: return { disallowUpgradableNops: true, opReverseBytes: true, requireBugValueZero: true, requireMinimalEncoding: true, requireNullSignatureFailures: true, }; default: return new Error( `${instructionSet as string} is not a known instruction set.` ) as never; } }; /** * Initialize a new instruction set for the BCH virtual machine. * * @param flags - an object configuring the flags for this vm (see * `getFlagsForInstructionSetBCH`) * @param sha1 - a Sha1 implementation * @param sha256 - a Sha256 implementation * @param ripemd160 - a Ripemd160 implementation * @param secp256k1 - a Secp256k1 implementation */ export const createInstructionSetBCH = ({ flags, ripemd160, secp256k1, sha1, sha256, }: { flags: { readonly disallowUpgradableNops: boolean; readonly opReverseBytes: boolean; readonly requireBugValueZero: boolean; readonly requireMinimalEncoding: boolean; readonly requireNullSignatureFailures: boolean; }; sha1: { hash: Sha1['hash'] }; sha256: { hash: Sha256['hash'] }; ripemd160: { hash: Ripemd160['hash'] }; secp256k1: { verifySignatureSchnorr: Secp256k1['verifySignatureSchnorr']; verifySignatureDERLowS: Secp256k1['verifySignatureDERLowS']; }; }): InstructionSet< AuthenticationProgramBCH, AuthenticationProgramStateBCH > => ({ clone: cloneAuthenticationProgramStateCommon, continue: (state: AuthenticationProgramStateBCH) => state.error === undefined && state.ip < state.instructions.length, // eslint-disable-next-line complexity evaluate: (program, stateEvaluate) => { const { unlockingBytecode } = program.spendingTransaction.inputs[ program.inputIndex ]; const { lockingBytecode } = program.sourceOutput; const unlockingInstructions = parseBytecode<OpcodesBCH>(unlockingBytecode); const lockingInstructions = parseBytecode<OpcodesBCH>(lockingBytecode); const externalState = createTransactionContextCommon(program); const initialState = createAuthenticationProgramStateCommon< OpcodesBCH, AuthenticationErrorBCH >({ instructions: unlockingInstructions, stack: [], transactionContext: externalState, }); const unlockingResult = unlockingBytecode.length > ConsensusCommon.maximumBytecodeLength ? applyError<AuthenticationProgramStateBCH, AuthenticationErrorBCH>( AuthenticationErrorCommon.exceededMaximumBytecodeLengthUnlocking, initialState ) : authenticationInstructionsAreMalformed(unlockingInstructions) ? applyError<AuthenticationProgramStateBCH, AuthenticationErrorBCH>( AuthenticationErrorCommon.malformedUnlockingBytecode, initialState ) : lockingBytecode.length > ConsensusCommon.maximumBytecodeLength ? applyError<AuthenticationProgramStateBCH, AuthenticationErrorBCH>( AuthenticationErrorCommon.exceededMaximumBytecodeLengthLocking, initialState ) : authenticationInstructionsAreMalformed(lockingInstructions) ? applyError<AuthenticationProgramStateBCH, AuthenticationErrorBCH>( AuthenticationErrorCommon.malformedLockingBytecode, initialState ) : initialState.instructions.every((instruction) => isPushOperation((instruction.opcode as unknown) as number) ) ? stateEvaluate(initialState) : applyError<AuthenticationProgramStateBCH, AuthenticationErrorBCH>( AuthenticationErrorBCH.requiresPushOnly, initialState ); if (unlockingResult.error !== undefined) { return unlockingResult; } const lockingResult = stateEvaluate( createAuthenticationProgramStateCommon< OpcodesBCH, AuthenticationErrorBCH >({ instructions: lockingInstructions, stack: unlockingResult.stack, transactionContext: externalState, }) ); if (!isPayToScriptHash(lockingInstructions)) { return lockingResult; } const p2shStack = cloneStack(unlockingResult.stack); // eslint-disable-next-line functional/immutable-data const p2shScript = p2shStack.pop() ?? Uint8Array.of(); if (p2shStack.length === 0 && isWitnessProgram(p2shScript)) { return lockingResult; } const p2shInstructions = parseBytecode<OpcodesBCH>(p2shScript); return authenticationInstructionsAreMalformed(p2shInstructions) ? { ...lockingResult, error: AuthenticationErrorBCH.malformedP2shBytecode, } : stateEvaluate( createAuthenticationProgramStateCommon< OpcodesBCH, AuthenticationErrorBCH >({ instructions: p2shInstructions, stack: p2shStack, transactionContext: externalState, }) ); }, operations: { ...commonOperations< OpcodesBCH, AuthenticationProgramStateBCH, AuthenticationErrorBCH >({ flags, ripemd160, secp256k1, sha1, sha256 }), ...mapOverOperations<AuthenticationProgramStateBCH>( bitcoinCashOperations<OpcodesBCH, AuthenticationProgramStateBCH>({ flags, secp256k1, sha256, }), conditionallyEvaluate, incrementOperationCount, checkLimitsCommon ), }, ...undefinedOperation(), verify: (state: AuthenticationProgramStateBCH) => { if (state.error !== undefined) { return state.error; } if (state.executionStack.length !== 0) { return AuthenticationErrorCommon.nonEmptyExecutionStack; } if (state.stack.length !== 1) { return AuthenticationErrorCommon.requiresCleanStack; } if (!stackItemIsTruthy(state.stack[0])) { return AuthenticationErrorCommon.unsuccessfulEvaluation; } return true; }, });
the_stack
import { VerticalTextAlignment, verticalTextAlignmentProperty } from '@nativescript-community/text'; import { themer } from '@nativescript-community/ui-material-core'; import { buttonColorProperty, counterMaxLengthProperty, digitsProperty, errorColorProperty, errorProperty, floatingColorProperty, floatingInactiveColorProperty, floatingProperty, helperColorProperty, helperProperty, strokeColorProperty, strokeDisabledColorProperty, strokeInactiveColorProperty } from '@nativescript-community/ui-material-core/textbase/cssproperties'; import { Background, Color, Font, Style, Utils, _updateCharactersInRangeReplacementString, backgroundInternalProperty, editableProperty, fontInternalProperty, paddingBottomProperty, paddingLeftProperty, paddingRightProperty, paddingTopProperty, placeholderColorProperty } from '@nativescript/core'; import { textProperty } from '@nativescript/core/ui/text-base'; import { layout } from '@nativescript/core/utils'; import { TextFieldBase } from './textfield.common'; @NativeClass class TextInputControllerUnderlineImpl extends MDCTextInputControllerUnderline { _owner: WeakRef<TextField>; public static initWithOwner(owner: TextField) { const delegate = TextInputControllerUnderlineImpl.new() as TextInputControllerUnderlineImpl; delegate._owner = new WeakRef(owner); return delegate; } textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint) { let result = super.textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint); const owner = this._owner ? this._owner.get() : null; if (owner) { result = owner._getTextInsetsForBounds(result); } return result; } } @NativeClass class TextInputControllerImpl extends MDCTextInputControllerBase { _owner: WeakRef<TextField>; public static initWithOwner(owner: TextField) { const delegate = TextInputControllerImpl.new() as TextInputControllerImpl; delegate._owner = new WeakRef(owner); return delegate; } textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint) { let result = super.textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint); const owner = this._owner ? this._owner.get() : null; if (owner) { result = owner._getTextInsetsForBounds(result); } return result; } } @NativeClass class TextInputControllerOutlinedImpl extends MDCTextInputControllerOutlined { _owner: WeakRef<TextField>; public static initWithOwner(owner: TextField) { const delegate = TextInputControllerOutlinedImpl.new() as TextInputControllerOutlinedImpl; delegate._owner = new WeakRef(owner); return delegate; } textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint) { let result = super.textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint); const owner = this._owner ? this._owner.get() : null; if (owner) { result = owner._getTextInsetsForBounds(result); } return result; } } @NativeClass class TextInputControllerFilledImpl extends MDCTextInputControllerFilled { _owner: WeakRef<TextField>; public static initWithOwner(owner: TextField) { const delegate = TextInputControllerFilledImpl.new() as TextInputControllerFilledImpl; delegate._owner = new WeakRef(owner); return delegate; } textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint) { let result = super.textInsetsWithSizeThatFitsWidthHint(defaultValue, widthHint); const owner = this._owner ? this._owner.get() : null; if (owner) { result = owner._getTextInsetsForBounds(result); } return result; } } declare module '@nativescript/core/ui/text-field' { interface TextField { textFieldShouldChangeCharactersInRangeReplacementString(textField: UITextField, range: NSRange, replacementString: string): boolean; } } export class TextField extends TextFieldBase { nativeViewProtected: MDCTextField; nativeTextViewProtected: MDCTextField; private _controller: MDCTextInputControllerBase; public readonly style: Style & { variant: 'outline' | 'underline' | 'filled' }; public nsdigits?: NSCharacterSet; firstEdit: boolean; public clearFocus() { this.dismissSoftInput(); } public requestFocus() { this.focus(); } textFieldShouldChangeCharactersInRangeReplacementString(textField: UITextField, range: NSRange, replacementString: string): boolean { // ignore if not in our alllowed digits if (this.nsdigits && replacementString.length > 0 && NSString.stringWithString(replacementString).rangeOfCharacterFromSet(this.nsdigits).location === NSNotFound) { return false; } if (this.secureWithoutAutofill && !textField.secureTextEntry) { /** * Helps avoid iOS 12+ autofill strong password suggestion prompt * Discussed in several circles but for example: * https://github.com/expo/expo/issues/2571#issuecomment-473347380 */ textField.secureTextEntry = true; } // we need to override this from N as in MDC case the range is 0 // if (range.length > 0) { const delta = replacementString.length - range.length; if (delta > 0) { if (textField.text.length + delta > this.maxLength) { return false; } } // } if (this.updateTextTrigger === 'textChanged') { if (textField.secureTextEntry && this.firstEdit) { textProperty.nativeValueChange(this, replacementString); } else { if (range.location <= textField.text.length) { const newText = NSString.stringWithString(textField.text).stringByReplacingCharactersInRangeWithString(range, replacementString); textProperty.nativeValueChange(this, newText); } } } if (this.formattedText) { _updateCharactersInRangeReplacementString(this.formattedText, range.location, range.length, replacementString); } this.firstEdit = false; if (this.mCanAutoSize) { // if the textfield is in auto size we need to request a layout to take the new text width into account this.requestLayout(); } return true; // return super.textFieldShouldChangeCharactersInRangeReplacementString(textField, range, replacementString); } private mCanAutoSize = false; public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void { const widthMode = layout.getMeasureSpecMode(widthMeasureSpec); this.mCanAutoSize = widthMode !== layout.EXACTLY; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } _getTextInsetsForBounds(insets: UIEdgeInsets): UIEdgeInsets { const style = this.style; if (this.variant === 'underline' && this._controller.underlineHeightNormal === 0) { // if no underline/custom background, remove all insets like on android insets.top = 0; insets.bottom = 0; } if (paddingTopProperty.isSet(style)) { insets.top = Utils.layout.toDeviceIndependentPixels(this.effectivePaddingTop); } if (paddingRightProperty.isSet(style)) { insets.right = Utils.layout.toDeviceIndependentPixels(this.effectivePaddingRight); } if (paddingBottomProperty.isSet(style)) { insets.bottom = Utils.layout.toDeviceIndependentPixels(this.effectivePaddingBottom); } if (paddingLeftProperty.isSet(style)) { insets.left = Utils.layout.toDeviceIndependentPixels(this.effectivePaddingLeft); } return insets; } // variant = 'underline'; public createNativeView() { // const view = MDCTextFieldImpl.initWithOwner(new WeakRef(this)); const view = MDCTextField.new(); // disable it for now view.clearButtonMode = UITextFieldViewMode.Never; const scheme = MDCContainerScheme.new(); scheme.colorScheme = themer.getAppColorScheme(); if (this.style.variant === 'filled') { this._controller = TextInputControllerFilledImpl.initWithOwner(this); } else if (this.style.variant === 'outline') { this._controller = TextInputControllerOutlinedImpl.initWithOwner(this); } else if (this.style.variant === 'underline') { this._controller = TextInputControllerUnderlineImpl.initWithOwner(this); } else { this._controller = TextInputControllerImpl.initWithOwner(this); this._controller.floatingEnabled = false; // (this._controller as TextInputControllerImpl).applyThemeWithScheme(scheme); } this._controller.textInput = view; //theme needs to be applied after setting the textInput if (this.style.variant === 'filled') { (this._controller as TextInputControllerFilledImpl).applyThemeWithScheme(scheme); } else if (this.style.variant === 'outline') { (this._controller as TextInputControllerOutlinedImpl).applyThemeWithScheme(scheme); } else if (this.style.variant === 'underline') { (this._controller as TextInputControllerUnderlineImpl).applyThemeWithScheme(scheme); } else { this._controller.underlineHeightActive = 0; this._controller.underlineHeightNormal = 0; } view.textInsetsMode = MDCTextInputTextInsetsMode.IfContent; // this._controller. // if (colorScheme) { // MDCTextFieldColorThemer.applySemanticColorSchemeToTextInput(colorScheme, view); // MDCTextFieldColorThemer.applySemanticColorSchemeToTextInputController(colorScheme, this._controller); // } return view; } // TODO: check why i was checking for isFirstResponder // with it the blur event is not fired anymore // public dismissSoftInput() { // if (this.nativeViewProtected.isFirstResponder) { // super.dismissSoftInput(); // } // } blur() { this.dismissSoftInput(); } public setSelection(start: number, stop?: number) { const view = this.nativeTextViewProtected; if (stop !== undefined) { const begin = view.beginningOfDocument; view.selectedTextRange = view.textRangeFromPositionToPosition(view.positionFromPositionOffset(begin, start), view.positionFromPositionOffset(begin, stop)); } else { const begin = view.beginningOfDocument; const pos = view.positionFromPositionOffset(begin, start); view.selectedTextRange = view.textRangeFromPositionToPosition(pos, pos); } } [editableProperty.setNative](value: boolean) { this.clearFocus(); // this.nativeTextViewProtected.enabled = value; } [floatingColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.floatingPlaceholderActiveColor = color; this._updateAttributedPlaceholder(); } [floatingInactiveColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; // this._controller.inlinePlaceholderColor = color; this._controller.floatingPlaceholderNormalColor = color; this._updateAttributedPlaceholder(); } [placeholderColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.inlinePlaceholderColor = color; if (!this.floatingColor) { this._controller.floatingPlaceholderActiveColor = color; } this._updateAttributedPlaceholder(); } [errorColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.errorColor = color; } [strokeColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.activeColor = color; } [strokeInactiveColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.normalColor = color; } [strokeDisabledColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.disabledColor = color; } [buttonColorProperty.setNative](value: Color) { const color = value instanceof Color ? value.ios : value; this._controller.textInputClearButtonTintColor = color; } [helperProperty.setNative](value: string) { this._controller.helperText = value; } [helperColorProperty.setNative](value: string | Color) { const temp = typeof value === 'string' ? new Color(value) : value; const color: UIColor = temp.ios; this._controller.leadingUnderlineLabelTextColor = color; } [counterMaxLengthProperty.setNative](value: number) { this._controller.characterCountMax = value; } [floatingProperty.setNative](value: boolean) { this._controller.floatingEnabled = value; } [errorProperty.setNative](value: string) { this._controller.setErrorTextErrorAccessibilityValue(value, value); } [digitsProperty.setNative](value: string) { if (value && value.length > 0) { this.nsdigits = NSCharacterSet.characterSetWithCharactersInString(value); } else { this.nsdigits = null; } } [backgroundInternalProperty.setNative](value: Background) { switch (this.variant) { case 'none': super[backgroundInternalProperty.setNative](value); break; case 'outline': case 'filled': case 'underline': { if (value.color) { this._controller.borderFillColor = value.color.ios; } if (value.borderTopColor) { this._controller.activeColor = value.borderTopColor.ios; } break; } } } [fontInternalProperty.setNative](value: Font | UIFont) { super[fontInternalProperty.setNative](value); const font = value instanceof Font ? value.getUIFont(this._controller.inlinePlaceholderFont) : value; this._controller.inlinePlaceholderFont = font; } [verticalTextAlignmentProperty.setNative](value: VerticalTextAlignment) { // TODO: not working for now const view = this.nativeTextViewProtected; view.backgroundColor = UIColor.redColor; switch (value) { case 'initial': case 'top': view.contentVerticalAlignment = UIControlContentVerticalAlignment.Top; break; case 'middle': view.contentVerticalAlignment = UIControlContentVerticalAlignment.Center; break; case 'bottom': view.contentVerticalAlignment = UIControlContentVerticalAlignment.Bottom; break; } } }
the_stack
import { createServer } from "http"; import { Server } from "socket.io"; import { io as ioc } from "socket.io-client"; import expect = require("expect.js"); import { createAdapter } from ".."; import type { AddressInfo } from "net"; import { createClient } from "redis"; import "./util"; const ioredis = require("ioredis").createClient; let namespace1, namespace2, namespace3; let client1, client2, client3; let socket1, socket2, socket3; [ { name: "socket.io-redis", createRedisClient: createClient, }, { name: "socket.io-redis with ioredis", createRedisClient: ioredis, }, ].forEach((suite) => { const name = suite.name; describe(name, () => { beforeEach(init(suite.createRedisClient)); afterEach(cleanup); it("broadcasts", (done) => { client1.on("woot", (a, b, c, d) => { expect(a).to.eql([]); expect(b).to.eql({ a: "b" }); expect(Buffer.isBuffer(c) && c.equals(buf)).to.be(true); expect(Buffer.isBuffer(d) && d.equals(Buffer.from(array))).to.be(true); // converted to Buffer on the client-side done(); }); var buf = Buffer.from("asdfasdf", "utf8"); var array = Uint8Array.of(1, 2, 3, 4); socket2.broadcast.emit("woot", [], { a: "b" }, buf, array); }); it("broadcasts to rooms", (done) => { socket1.join("woot"); client2.emit("do broadcast"); // does not join, performs broadcast socket2.on("do broadcast", () => { socket2.broadcast.to("woot").emit("broadcast"); }); client1.on("broadcast", () => { setTimeout(done, 100); }); client2.on("broadcast", () => { throw new Error("Not in room"); }); client3.on("broadcast", () => { throw new Error("Not in room"); }); }); it("uses a namespace to broadcast to rooms", (done) => { socket1.join("woot"); client2.emit("do broadcast"); socket2.on("do broadcast", () => { namespace2.to("woot").emit("broadcast"); }); client1.on("broadcast", () => { setTimeout(done, 100); }); client2.on("broadcast", () => { throw new Error("Not in room"); }); client3.on("broadcast", () => { throw new Error("Not in room"); }); }); it("broadcasts to multiple rooms at a time", (done) => { function test() { client2.emit("do broadcast"); } socket1.join(["foo", "bar"]); client2.emit("do broadcast"); socket2.on("do broadcast", () => { socket2.broadcast.to("foo").to("bar").emit("broadcast"); }); let called = false; client1.on("broadcast", () => { if (called) return done(new Error("Called more than once")); called = true; setTimeout(done, 100); }); client2.on("broadcast", () => { throw new Error("Not in room"); }); client3.on("broadcast", () => { throw new Error("Not in room"); }); }); it("doesn't broadcast when using the local flag", (done) => { socket1.join("woot"); socket2.join("woot"); client2.emit("do broadcast"); socket2.on("do broadcast", () => { namespace2.local.to("woot").emit("local broadcast"); }); client1.on("local broadcast", () => { throw new Error("Not in local server"); }); client2.on("local broadcast", () => { setTimeout(done, 100); }); client3.on("local broadcast", () => { throw new Error("Not in local server"); }); }); it("doesn't broadcast to left rooms", (done) => { socket1.join("woot"); socket1.leave("woot"); socket2.on("do broadcast", () => { socket2.broadcast.to("woot").emit("broadcast"); setTimeout(done, 100); }); client2.emit("do broadcast"); client1.on("broadcast", () => { throw new Error("Not in room"); }); }); it("deletes rooms upon disconnection", (done) => { socket1.join("woot"); socket1.on("disconnect", () => { expect(socket1.adapter.sids[socket1.id]).to.be(undefined); expect(socket1.adapter.rooms).to.be.empty(); client1.disconnect(); done(); }); socket1.disconnect(); }); it("returns sockets in the same room", async () => { socket1.join("woot"); socket2.join("woot"); const sockets = await namespace1.adapter.sockets(new Set(["woot"])); expect(sockets.size).to.eql(2); expect(sockets.has(socket1.id)).to.be(true); expect(sockets.has(socket2.id)).to.be(true); expect(namespace1.adapter.requests.size).to.eql(0); }); it("ignores messages from unknown channels", (done) => { namespace1.adapter.subClient.psubscribe("f?o", () => { namespace3.adapter.pubClient.publish("foo", "bar"); }); namespace1.adapter.subClient.on("pmessageBuffer", () => { setTimeout(done, 50); }); }); it("ignores messages from unknown channels (2)", (done) => { namespace1.adapter.subClient.subscribe("woot", () => { namespace3.adapter.pubClient.publish("woot", "toow"); }); namespace1.adapter.subClient.on("messageBuffer", () => { setTimeout(done, 50); }); }); describe("requests", () => { afterEach(() => { expect(namespace1.adapter.requests.size).to.eql(0); }); it("returns all rooms across several nodes", async () => { socket1.join("woot1"); const rooms = await namespace1.adapter.allRooms(); expect(rooms).to.be.a(Set); expect(rooms.size).to.eql(4); expect(rooms.has(socket1.id)).to.be(true); expect(rooms.has(socket2.id)).to.be(true); expect(rooms.has(socket3.id)).to.be(true); expect(rooms.has("woot1")).to.be(true); }); it("makes a given socket join a room", async () => { await namespace3.adapter.remoteJoin(socket1.id, "woot3"); expect(socket1.rooms.size).to.eql(2); expect(socket1.rooms.has("woot3")).to.be(true); }); it("makes a given socket leave a room", async () => { socket1.join("woot3"); await namespace3.adapter.remoteLeave(socket1.id, "woot3"); expect(socket1.rooms.size).to.eql(1); expect(socket1.rooms.has("woot3")).to.be(false); }); it("makes a given socket disconnect", (done) => { client1.on("disconnect", (err) => { expect(err).to.be("io server disconnect"); done(); }); namespace2.adapter.remoteDisconnect(socket1.id, false); }); describe("socketsJoin", () => { it("makes all socket instances join the specified room", (done) => { namespace1.socketsJoin("room1"); setTimeout(() => { expect(socket1.rooms).to.contain("room1"); expect(socket2.rooms).to.contain("room1"); expect(socket3.rooms).to.contain("room1"); done(); }, 100); }); it("makes the matching socket instances join the specified room", (done) => { socket1.join("room1"); socket3.join("room1"); namespace1.in("room1").socketsJoin("room2"); setTimeout(() => { expect(socket1.rooms).to.contain("room2"); expect(socket2.rooms).to.not.contain("room2"); expect(socket3.rooms).to.contain("room2"); done(); }, 100); }); it("makes the given socket instance join the specified room", (done) => { namespace1.in(socket2.id).socketsJoin("room3"); setTimeout(() => { expect(socket1.rooms).to.not.contain("room3"); expect(socket2.rooms).to.contain("room3"); expect(socket3.rooms).to.not.contain("room3"); done(); }, 100); }); }); describe("socketsLeave", () => { it("makes all socket instances leave the specified room", (done) => { socket2.join("room1"); socket3.join("room1"); namespace1.socketsLeave("room1"); setTimeout(() => { expect(socket1.rooms).to.not.contain("room1"); expect(socket2.rooms).to.not.contain("room1"); expect(socket3.rooms).to.not.contain("room1"); done(); }, 100); }); it("makes the matching socket instances leave the specified room", (done) => { socket1.join(["room1", "room2"]); socket2.join(["room1", "room2"]); socket3.join(["room2"]); namespace1.in("room1").socketsLeave("room2"); setTimeout(() => { expect(socket1.rooms).to.not.contain("room2"); expect(socket2.rooms).to.not.contain("room2"); expect(socket3.rooms).to.contain("room2"); done(); }, 100); }); it("makes the given socket instance leave the specified room", (done) => { socket1.join("room3"); socket2.join("room3"); socket3.join("room3"); namespace1.in(socket2.id).socketsLeave("room3"); setTimeout(() => { expect(socket1.rooms).to.contain("room3"); expect(socket2.rooms).to.not.contain("room3"); expect(socket3.rooms).to.contain("room3"); done(); }, 100); }); }); describe("fetchSockets", () => { it("returns all socket instances", async () => { socket2.data = "test"; const sockets = await namespace1.fetchSockets(); expect(sockets).to.be.an(Array); expect(sockets).to.have.length(3); const remoteSocket1 = sockets.find( (socket) => socket.id === socket1.id ); expect(remoteSocket1 === socket1).to.be(true); const remoteSocket2 = sockets.find( (socket) => socket.id === socket2.id ); expect(remoteSocket2 === socket2).to.be(false); expect(remoteSocket2.handshake).to.eql(socket2.handshake); expect(remoteSocket2.data).to.eql("test"); expect(remoteSocket2.rooms.size).to.eql(1); expect(remoteSocket2.rooms).to.contain(socket2.id); }); it("returns the matching socket instances", async () => { socket1.join("room1"); socket3.join("room1"); const sockets = await namespace1.in("room1").fetchSockets(); expect(sockets).to.be.an(Array); expect(sockets).to.have.length(2); }); }); describe("serverSideEmit", () => { it("sends an event to other server instances", (done) => { let total = 2; namespace1.serverSideEmit("hello", "world", 1, "2"); namespace1.on("hello", () => { done(new Error("should not happen")); }); namespace2.on("hello", (arg1, arg2, arg3) => { expect(arg1).to.eql("world"); expect(arg2).to.eql(1); expect(arg3).to.eql("2"); --total && done(); }); namespace3.on("hello", () => { --total && done(); }); }); it("sends an event and receives a response from the other server instances", (done) => { namespace1.serverSideEmit("hello", (err, response) => { expect(err).to.be(null); expect(response).to.be.an(Array); expect(response).to.contain(2); expect(response).to.contain("3"); done(); }); namespace1.on("hello", () => { done(new Error("should not happen")); }); namespace2.on("hello", (cb) => { cb(2); }); namespace3.on("hello", (cb) => { cb("3"); }); }); it("sends an event but timeout if one server does not respond", (done) => { namespace1.adapter.requestsTimeout = 100; namespace1.serverSideEmit("hello", (err, response) => { expect(err.message).to.be( "timeout reached: only 1 responses received out of 2" ); expect(response).to.be.an(Array); expect(response).to.contain(2); done(); }); namespace1.on("hello", () => { done(new Error("should not happen")); }); namespace2.on("hello", (cb) => { cb(2); }); namespace3.on("hello", () => { // do nothing }); }); }); }); }); }); function _create(createRedisClient) { return (nsp, fn?) => { const httpServer = createServer(); const sio = new Server(httpServer); // @ts-ignore sio.adapter(createAdapter(createRedisClient(), createRedisClient())); httpServer.listen((err) => { if (err) throw err; // abort tests if ("function" == typeof nsp) { fn = nsp; nsp = ""; } nsp = nsp || "/"; const addr = httpServer.address() as AddressInfo; const url = "http://localhost:" + addr.port + nsp; const namespace = sio.of(nsp); const client = ioc(url, { reconnection: false }); namespace.on("connection", (socket) => { fn(namespace, client, socket); }); }); }; } function init(options) { const create = _create(options); return (done) => { create((_namespace1, _client1, _socket1) => { create((_namespace2, _client2, _socket2) => { create((_namespace3, _client3, _socket3) => { namespace1 = _namespace1; namespace2 = _namespace2; namespace3 = _namespace3; client1 = _client1; client2 = _client2; client3 = _client3; socket1 = _socket1; socket2 = _socket2; socket3 = _socket3; setTimeout(done, 100); }); }); }); }; } function noop() {} function cleanup(done) { namespace1.server.close(); namespace2.server.close(); namespace3.server.close(); // handle 'Connection is closed' errors namespace1.adapter.on("error", noop); namespace2.adapter.on("error", noop); namespace3.adapter.on("error", noop); namespace1.adapter.subClient.quit(); namespace2.adapter.subClient.quit(); namespace3.adapter.subClient.quit(); done(); }
the_stack
import { createSpan } from "../tracing"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PipelineOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as coreTracing from "@azure/core-tracing"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ArtifactsClientContext } from "../artifactsClientContext"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { PipelineResource, PipelineGetPipelinesByWorkspaceNextOptionalParams, PipelineGetPipelinesByWorkspaceOptionalParams, PipelineGetPipelinesByWorkspaceResponse, PipelineCreateOrUpdatePipelineOptionalParams, PipelineCreateOrUpdatePipelineResponse, PipelineGetPipelineOptionalParams, PipelineGetPipelineResponse, PipelineDeletePipelineOptionalParams, ArtifactRenameRequest, PipelineRenamePipelineOptionalParams, PipelineCreatePipelineRunOptionalParams, PipelineCreatePipelineRunResponse, PipelineGetPipelinesByWorkspaceNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing PipelineOperations operations. */ export class PipelineOperationsImpl implements PipelineOperations { private readonly client: ArtifactsClientContext; /** * Initialize a new instance of the class PipelineOperations class. * @param client Reference to the service client */ constructor(client: ArtifactsClientContext) { this.client = client; } /** * Lists pipelines. * @param options The options parameters. */ public listPipelinesByWorkspace( options?: PipelineGetPipelinesByWorkspaceOptionalParams ): PagedAsyncIterableIterator<PipelineResource> { const iter = this.getPipelinesByWorkspacePagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getPipelinesByWorkspacePagingPage(options); } }; } private async *getPipelinesByWorkspacePagingPage( options?: PipelineGetPipelinesByWorkspaceOptionalParams ): AsyncIterableIterator<PipelineResource[]> { let result = await this._getPipelinesByWorkspace(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getPipelinesByWorkspaceNext( continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *getPipelinesByWorkspacePagingAll( options?: PipelineGetPipelinesByWorkspaceOptionalParams ): AsyncIterableIterator<PipelineResource> { for await (const page of this.getPipelinesByWorkspacePagingPage(options)) { yield* page; } } /** * Lists pipelines. * @param options The options parameters. */ private async _getPipelinesByWorkspace( options?: PipelineGetPipelinesByWorkspaceOptionalParams ): Promise<PipelineGetPipelinesByWorkspaceResponse> { const { span } = createSpan( "ArtifactsClient-_getPipelinesByWorkspace", options || {} ); try { const result = await this.client.sendOperationRequest( { options }, getPipelinesByWorkspaceOperationSpec ); return result as PipelineGetPipelinesByWorkspaceResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } } /** * Creates or updates a pipeline. * @param pipelineName The pipeline name. * @param pipeline Pipeline resource definition. * @param options The options parameters. */ async beginCreateOrUpdatePipeline( pipelineName: string, pipeline: PipelineResource, options?: PipelineCreateOrUpdatePipelineOptionalParams ): Promise< PollerLike< PollOperationState<PipelineCreateOrUpdatePipelineResponse>, PipelineCreateOrUpdatePipelineResponse > > { const { span } = createSpan( "ArtifactsClient-beginCreateOrUpdatePipeline", options || {} ); const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<PipelineCreateOrUpdatePipelineResponse> => { try { const result = await this.client.sendOperationRequest(args, spec); return result as PipelineCreateOrUpdatePipelineResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { pipelineName, pipeline, options }, createOrUpdatePipelineOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Creates or updates a pipeline. * @param pipelineName The pipeline name. * @param pipeline Pipeline resource definition. * @param options The options parameters. */ async beginCreateOrUpdatePipelineAndWait( pipelineName: string, pipeline: PipelineResource, options?: PipelineCreateOrUpdatePipelineOptionalParams ): Promise<PipelineCreateOrUpdatePipelineResponse> { const poller = await this.beginCreateOrUpdatePipeline( pipelineName, pipeline, options ); return poller.pollUntilDone(); } /** * Gets a pipeline. * @param pipelineName The pipeline name. * @param options The options parameters. */ async getPipeline( pipelineName: string, options?: PipelineGetPipelineOptionalParams ): Promise<PipelineGetPipelineResponse> { const { span } = createSpan("ArtifactsClient-getPipeline", options || {}); try { const result = await this.client.sendOperationRequest( { pipelineName, options }, getPipelineOperationSpec ); return result as PipelineGetPipelineResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } } /** * Deletes a pipeline. * @param pipelineName The pipeline name. * @param options The options parameters. */ async beginDeletePipeline( pipelineName: string, options?: PipelineDeletePipelineOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const { span } = createSpan( "ArtifactsClient-beginDeletePipeline", options || {} ); const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { try { const result = await this.client.sendOperationRequest(args, spec); return result as void; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { pipelineName, options }, deletePipelineOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Deletes a pipeline. * @param pipelineName The pipeline name. * @param options The options parameters. */ async beginDeletePipelineAndWait( pipelineName: string, options?: PipelineDeletePipelineOptionalParams ): Promise<void> { const poller = await this.beginDeletePipeline(pipelineName, options); return poller.pollUntilDone(); } /** * Renames a pipeline. * @param pipelineName The pipeline name. * @param request proposed new name. * @param options The options parameters. */ async beginRenamePipeline( pipelineName: string, request: ArtifactRenameRequest, options?: PipelineRenamePipelineOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const { span } = createSpan( "ArtifactsClient-beginRenamePipeline", options || {} ); const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { try { const result = await this.client.sendOperationRequest(args, spec); return result as void; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { pipelineName, request, options }, renamePipelineOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Renames a pipeline. * @param pipelineName The pipeline name. * @param request proposed new name. * @param options The options parameters. */ async beginRenamePipelineAndWait( pipelineName: string, request: ArtifactRenameRequest, options?: PipelineRenamePipelineOptionalParams ): Promise<void> { const poller = await this.beginRenamePipeline( pipelineName, request, options ); return poller.pollUntilDone(); } /** * Creates a run of a pipeline. * @param pipelineName The pipeline name. * @param options The options parameters. */ async createPipelineRun( pipelineName: string, options?: PipelineCreatePipelineRunOptionalParams ): Promise<PipelineCreatePipelineRunResponse> { const { span } = createSpan( "ArtifactsClient-createPipelineRun", options || {} ); try { const result = await this.client.sendOperationRequest( { pipelineName, options }, createPipelineRunOperationSpec ); return result as PipelineCreatePipelineRunResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } } /** * GetPipelinesByWorkspaceNext * @param nextLink The nextLink from the previous successful call to the GetPipelinesByWorkspace * method. * @param options The options parameters. */ private async _getPipelinesByWorkspaceNext( nextLink: string, options?: PipelineGetPipelinesByWorkspaceNextOptionalParams ): Promise<PipelineGetPipelinesByWorkspaceNextResponse> { const { span } = createSpan( "ArtifactsClient-_getPipelinesByWorkspaceNext", options || {} ); try { const result = await this.client.sendOperationRequest( { nextLink, options }, getPipelinesByWorkspaceNextOperationSpec ); return result as PipelineGetPipelinesByWorkspaceNextResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getPipelinesByWorkspaceOperationSpec: coreClient.OperationSpec = { path: "/pipelines", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PipelineListResponse }, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, queryParameters: [Parameters.apiVersion2], urlParameters: [Parameters.endpoint], headerParameters: [Parameters.accept], serializer }; const createOrUpdatePipelineOperationSpec: coreClient.OperationSpec = { path: "/pipelines/{pipelineName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.PipelineResource }, 201: { bodyMapper: Mappers.PipelineResource }, 202: { bodyMapper: Mappers.PipelineResource }, 204: { bodyMapper: Mappers.PipelineResource }, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, requestBody: Parameters.pipeline, queryParameters: [Parameters.apiVersion2], urlParameters: [Parameters.endpoint, Parameters.pipelineName], headerParameters: [ Parameters.accept, Parameters.contentType, Parameters.ifMatch ], mediaType: "json", serializer }; const getPipelineOperationSpec: coreClient.OperationSpec = { path: "/pipelines/{pipelineName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PipelineResource }, 304: {}, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, queryParameters: [Parameters.apiVersion2], urlParameters: [Parameters.endpoint, Parameters.pipelineName], headerParameters: [Parameters.accept, Parameters.ifNoneMatch], serializer }; const deletePipelineOperationSpec: coreClient.OperationSpec = { path: "/pipelines/{pipelineName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, queryParameters: [Parameters.apiVersion2], urlParameters: [Parameters.endpoint, Parameters.pipelineName], headerParameters: [Parameters.accept], serializer }; const renamePipelineOperationSpec: coreClient.OperationSpec = { path: "/pipelines/{pipelineName}/rename", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, requestBody: Parameters.request, queryParameters: [Parameters.apiVersion2], urlParameters: [Parameters.endpoint, Parameters.pipelineName], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createPipelineRunOperationSpec: coreClient.OperationSpec = { path: "/pipelines/{pipelineName}/createRun", httpMethod: "POST", responses: { 202: { bodyMapper: Mappers.CreateRunResponse }, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, requestBody: Parameters.parameters, queryParameters: [ Parameters.apiVersion2, Parameters.referencePipelineRunId, Parameters.isRecovery, Parameters.startActivityName ], urlParameters: [Parameters.endpoint, Parameters.pipelineName], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getPipelinesByWorkspaceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.PipelineListResponse }, default: { bodyMapper: Mappers.CloudErrorAutoGenerated } }, queryParameters: [Parameters.apiVersion2], urlParameters: [Parameters.endpoint, Parameters.nextLink], headerParameters: [Parameters.accept], serializer };
the_stack
import { AfterContentChecked, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ElementRef, EventEmitter, Host, Input, OnChanges, OnDestroy, OnInit, Optional, Output, QueryList, SimpleChanges, TemplateRef, ViewChildren, ViewEncapsulation } from '@angular/core'; import { forkJoin, Observable, ReplaySubject, Subject, Subscription } from 'rxjs'; import { finalize, take, takeUntil } from 'rxjs/operators'; import { buildGraph } from 'dagre-compound'; import { NzNoAnimationDirective } from 'ng-zorro-antd/core/no-animation'; import { cancelRequestAnimationFrame } from 'ng-zorro-antd/core/polyfill'; import { BooleanInput, NzSafeAny } from 'ng-zorro-antd/core/types'; import { InputBoolean } from 'ng-zorro-antd/core/util'; import { calculateTransform } from './core/utils'; import { NzGraphData } from './data-source/graph-data-source'; import { NzGraphEdgeDirective } from './graph-edge.directive'; import { NzGraphGroupNodeDirective } from './graph-group-node.directive'; import { NzGraphNodeComponent } from './graph-node.component'; import { NzGraphNodeDirective } from './graph-node.directive'; import { NzGraphZoomDirective } from './graph-zoom.directive'; import { NzGraphDataDef, NzGraphEdge, NzGraphEdgeDef, NzGraphGroupNode, NzGraphLayoutConfig, NzGraphNode, NzGraphNodeDef, NzGraphOption, NzLayoutSetting, NzRankDirection, nzTypeDefinition, NZ_GRAPH_LAYOUT_SETTING } from './interface'; /** Checks whether an object is a data source. */ export function isDataSource(value: NzSafeAny): value is NzGraphData { // Check if the value is a DataSource by observing if it has a connect function. Cannot // be checked as an `instanceof DataSource` since people could create their own sources // that match the interface, but don't extend DataSource. return value && typeof value.connect === 'function'; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, selector: 'nz-graph', exportAs: 'nzGraph', template: ` <ng-content></ng-content> <svg width="100%" height="100%"> <svg:defs nz-graph-defs></svg:defs> <svg:g [attr.transform]="transformStyle"> <ng-container [ngTemplateOutlet]="groupTemplate" [ngTemplateOutletContext]="{ renderNode: renderInfo, type: 'root' }" ></ng-container> </svg:g> </svg> <ng-template #groupTemplate let-renderNode="renderNode" let-type="type"> <svg:g [attr.transform]="type === 'sub' ? subGraphTransform(renderNode) : null"> <svg:g class="core" [attr.transform]="coreTransform(renderNode)"> <svg:g class="nz-graph-edges"> <ng-container *ngFor="let edge of $asNzGraphEdges(renderNode.edges); trackBy: edgeTrackByFun"> <g class="nz-graph-edge" nz-graph-edge [edge]="edge" [edgeType]="nzGraphLayoutConfig?.defaultEdge?.type" [customTemplate]="customGraphEdgeTemplate" ></g> </ng-container> </svg:g> <svg:g class="nz-graph-nodes"> <ng-container *ngFor="let node of typedNodes(renderNode.nodes); trackBy: nodeTrackByFun"> <g *ngIf="node.type === 1" class="nz-graph-node" nz-graph-node [node]="node" [customTemplate]="nodeTemplate" (nodeClick)="clickNode($event)" ></g> <g *ngIf="node.type === 0" class="nz-graph-node" nz-graph-node [node]="node" [customTemplate]="groupNodeTemplate" (nodeClick)="clickNode($event)" ></g> <ng-container *ngIf="node.expanded" [ngTemplateOutlet]="groupTemplate" [ngTemplateOutletContext]="{ renderNode: node, type: 'sub' }" ></ng-container> </ng-container> </svg:g> </svg:g> </svg:g> </ng-template> `, host: { '[class.nz-graph]': 'true', '[class.nz-graph-auto-size]': 'nzAutoSize' } }) export class NzGraphComponent implements OnInit, OnChanges, AfterContentChecked, OnDestroy { static ngAcceptInputType_nzAutoSize: BooleanInput; @ViewChildren(NzGraphNodeComponent, { read: ElementRef }) listOfNodeElement!: QueryList<ElementRef>; @ViewChildren(NzGraphNodeComponent) listOfNodeComponent!: QueryList<NzGraphNodeComponent>; @ContentChild(NzGraphNodeDirective, { static: true, read: TemplateRef }) nodeTemplate?: TemplateRef<{ $implicit: NzGraphNode; }>; @ContentChild(NzGraphGroupNodeDirective, { static: true, read: TemplateRef }) groupNodeTemplate?: TemplateRef<{ $implicit: NzGraphGroupNode; }>; @ContentChild(NzGraphEdgeDirective, { static: true, read: TemplateRef }) customGraphEdgeTemplate?: TemplateRef<{ $implicit: NzGraphEdge; }>; /** * Provides a stream containing the latest data array to render. * Data source can be an observable of NzGraphData, or a NzGraphData to render. */ @Input() nzGraphData!: NzGraphData; @Input() nzRankDirection: NzRankDirection = 'LR'; @Input() nzGraphLayoutConfig?: NzGraphLayoutConfig; @Input() @InputBoolean() nzAutoSize = false; @Output() readonly nzGraphInitialized = new EventEmitter<NzGraphComponent>(); @Output() readonly nzGraphRendered = new EventEmitter<NzGraphComponent>(); @Output() readonly nzNodeClick: EventEmitter<NzGraphNode | NzGraphGroupNode> = new EventEmitter(); requestId: number = -1; transformStyle = ''; graphRenderedSubject$ = new ReplaySubject<void>(1); renderInfo: NzGraphGroupNode = { labelHeight: 0 } as NzGraphGroupNode; mapOfNodeAttr: { [key: string]: NzGraphNodeDef } = {}; mapOfEdgeAttr: { [key: string]: NzGraphEdgeDef } = {}; zoom = 1; public readonly typedNodes = nzTypeDefinition<Array<NzGraphNode | NzGraphGroupNode>>(); private dataSource?: NzGraphData; private layoutSetting: NzLayoutSetting = NZ_GRAPH_LAYOUT_SETTING; /** Data subscription */ private _dataSubscription?: Subscription | null; private destroy$ = new Subject<void>(); nodeTrackByFun = (_: number, node: NzGraphNode | NzGraphGroupNode) => node.name; edgeTrackByFun = (_: number, edge: NzGraphEdge) => `${edge.v}-${edge.w}`; subGraphTransform = (node: NzGraphGroupNode) => { const x = node.x - node.coreBox.width / 2.0; const y = node.y - node.height / 2.0 + node.paddingTop; return `translate(${x}, ${y})`; }; $asNzGraphEdges = (data: unknown) => data as NzGraphEdge[]; coreTransform = (node: NzGraphGroupNode) => `translate(0, ${node.parentNodeName ? node.labelHeight : 0})`; constructor( private cdr: ChangeDetectorRef, private elementRef: ElementRef, @Host() @Optional() public noAnimation?: NzNoAnimationDirective, @Optional() public nzGraphZoom?: NzGraphZoomDirective ) {} ngOnInit(): void { this.graphRenderedSubject$.pipe(take(1), takeUntil(this.destroy$)).subscribe(() => { // Only zooming is not set, move graph to center if (!this.nzGraphZoom) { this.fitCenter(); } this.nzGraphInitialized.emit(this); }); } ngOnChanges(changes: SimpleChanges): void { const { nzAutoFit, nzRankDirection, nzGraphData, nzGraphLayoutConfig } = changes; if (nzGraphLayoutConfig) { this.layoutSetting = this.mergeConfig(nzGraphLayoutConfig.currentValue); } if (nzGraphData) { if (this.dataSource !== this.nzGraphData) { this._switchDataSource(this.nzGraphData); } } if ((nzAutoFit && !nzAutoFit.firstChange) || (nzRankDirection && !nzRankDirection.firstChange)) { // Render graph if (this.dataSource!.dataSource) { this.drawGraph(this.dataSource!.dataSource, { rankDirection: this.nzRankDirection, expanded: this.dataSource!.expansionModel.selected || [] }).then(() => { this.cdr.markForCheck(); }); } } this.cdr.markForCheck(); } ngAfterContentChecked(): void { if (this.dataSource && !this._dataSubscription) { this.observeRenderChanges(); } } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); if (this.dataSource && typeof this.dataSource.disconnect === 'function') { this.dataSource.disconnect(); } if (this._dataSubscription) { this._dataSubscription.unsubscribe(); this._dataSubscription = null; } cancelRequestAnimationFrame(this.requestId); } /** * Emit event */ clickNode(node: NzGraphNode | NzGraphGroupNode): void { this.nzNodeClick.emit(node); } /** * Move graph to center and scale automatically */ fitCenter(): void { const { x, y, k } = calculateTransform( this.elementRef.nativeElement.querySelector('svg'), this.elementRef.nativeElement.querySelector('svg > g') )!; if (k) { this.zoom = k; this.transformStyle = `translate(${x}, ${y})scale(${k})`; } this.cdr.markForCheck(); } /** * re-Draw graph * * @param data * @param options * @param needResize */ drawGraph(data: NzGraphDataDef, options: NzGraphOption, needResize: boolean = false): Promise<void> { return new Promise(resolve => { this.requestId = requestAnimationFrame(() => { const renderInfo = this.buildGraphInfo(data, options); // TODO // Need better performance this.renderInfo = renderInfo; this.cdr.markForCheck(); this.requestId = requestAnimationFrame(() => { this.drawNodes(!this.noAnimation?.nzNoAnimation).then(() => { // Update element this.cdr.markForCheck(); if (needResize) { this.resizeNodeSize().then(() => { const dataSource: NzGraphDataDef = this.dataSource!.dataSource!; this.drawGraph(dataSource, options, false).then(() => resolve()); }); } else { this.graphRenderedSubject$.next(); this.nzGraphRendered.emit(this); resolve(); } }); }); }); this.cdr.markForCheck(); }); } /** * Redraw all nodes * * @param animate */ drawNodes(animate: boolean = true): Promise<void> { return new Promise(resolve => { if (animate) { this.makeNodesAnimation().subscribe(() => { resolve(); }); } else { this.listOfNodeComponent.map(node => { node.makeNoAnimation(); }); resolve(); } }); } private resizeNodeSize(): Promise<void> { return new Promise(resolve => { const dataSource: NzGraphDataDef = this.dataSource!.dataSource!; let scale = this.nzGraphZoom?.nzZoom || this.zoom || 1; this.listOfNodeElement.forEach(nodeEle => { const contentEle = nodeEle.nativeElement; if (contentEle) { let width: number; let height: number; // Check if foreignObject is set const clientRect = contentEle.querySelector('foreignObject > :first-child')?.getBoundingClientRect(); if (clientRect) { width = clientRect.width; height = clientRect.height; } else { const bBoxRect = contentEle.getBBox(); width = bBoxRect.width; height = bBoxRect.height; // getBBox will return actual value scale = 1; } // Element id type is string const node = dataSource.nodes.find(n => `${n.id}` === nodeEle.nativeElement.id); if (node && width && height) { node.height = height / scale; node.width = width / scale; } } }); resolve(); }); } /** * Switch to the provided data source by resetting the data and unsubscribing from the current * render change subscription if one exists. If the data source is null, interpret this by * clearing the node outlet. Otherwise start listening for new data. */ private _switchDataSource(dataSource: NzGraphData): void { if (this.dataSource && typeof this.dataSource.disconnect === 'function') { this.nzGraphData.disconnect(); } if (this._dataSubscription) { this._dataSubscription.unsubscribe(); this._dataSubscription = null; } this.dataSource = dataSource; this.observeRenderChanges(); } /** Set up a subscription for the data provided by the data source. */ private observeRenderChanges(): void { let dataStream: Observable<NzGraphDataDef> | undefined; let graphOptions: NzGraphOption = { rankDirection: this.nzRankDirection }; if (isDataSource(this.dataSource)) { dataStream = this.dataSource.connect(); } if (dataStream) { this._dataSubscription = dataStream.pipe(takeUntil(this.destroy$)).subscribe(data => { graphOptions = { rankDirection: this.nzRankDirection, expanded: this.nzGraphData.expansionModel.selected }; this.drawGraph(data, graphOptions, this.nzAutoSize).then(() => { this.cdr.detectChanges(); }); }); } else { throw Error(`A valid data source must be provided.`); } } /** * Get renderInfo and prepare some data * * @param data * @param options * @private */ private buildGraphInfo(data: NzGraphDataDef, options: NzGraphOption): NzGraphGroupNode { this.parseInfo(data); const renderInfo = buildGraph(data, options, this.layoutSetting) as NzGraphGroupNode; const dig = (nodes: Array<NzGraphNode | NzGraphGroupNode>): void => { nodes.forEach(node => { const { x, y } = node; node.xOffset = x; node.yOffset = y; if (node.type === 1 && this.mapOfNodeAttr.hasOwnProperty(node.name)) { Object.assign(node, this.mapOfNodeAttr[node.name]); } else if (node.type === 0) { (node as NzGraphGroupNode).edges.forEach(edge => { if (this.mapOfEdgeAttr.hasOwnProperty(`${edge.v}-${edge.w}`)) { Object.assign(edge, this.mapOfEdgeAttr[`${edge.v}-${edge.w}`]); } }); dig(node.nodes); } }); }; dig(renderInfo.nodes); // Assign data to edges of root graph renderInfo.edges.forEach(edge => { if (this.mapOfEdgeAttr.hasOwnProperty(`${edge.v}-${edge.w}`)) { Object.assign(edge, this.mapOfEdgeAttr[`${edge.v}-${edge.w}`]); } }); return renderInfo; } /** * Play with animation * * @private */ private makeNodesAnimation(): Observable<void> { return forkJoin(...this.listOfNodeComponent.map(node => node.makeAnimation())).pipe( finalize(() => { this.cdr.detectChanges(); }) ); } private parseInfo(data: NzGraphDataDef): void { data.nodes.forEach(n => { this.mapOfNodeAttr[n.id] = n; }); data.edges.forEach(e => { this.mapOfEdgeAttr[`${e.v}-${e.w}`] = e; }); } /** * Merge config with user inputs * * @param config * @private */ private mergeConfig(config: NzGraphLayoutConfig): NzLayoutSetting { const graphMeta = config?.layout || {}; const subSceneMeta = config?.subScene || {}; const defaultNodeMeta = config?.defaultNode || {}; const defaultCompoundNodeMeta = config?.defaultCompoundNode || {}; const bridge = NZ_GRAPH_LAYOUT_SETTING.nodeSize.bridge; const graph: NzLayoutSetting['graph'] = { meta: { ...NZ_GRAPH_LAYOUT_SETTING.graph.meta, ...graphMeta } }; const subScene: NzLayoutSetting['subScene'] = { meta: { ...NZ_GRAPH_LAYOUT_SETTING.subScene.meta, ...subSceneMeta } }; const nodeSize: NzLayoutSetting['nodeSize'] = { meta: { ...NZ_GRAPH_LAYOUT_SETTING.nodeSize.meta, ...defaultCompoundNodeMeta }, node: { ...NZ_GRAPH_LAYOUT_SETTING.nodeSize.node, ...defaultNodeMeta }, bridge }; return { graph, subScene, nodeSize }; } }
the_stack
import express from 'express'; import * as ThingTalk from 'thingtalk'; import * as db from '../util/db'; import * as user from '../util/user'; import * as model from '../model/schema'; import * as exampleModel from '../model/example'; import * as iv from '../util/input_validation'; import { NotFoundError } from '../util/errors'; import * as I18n from '../util/i18n'; import ThingpediaClient from '../util/thingpedia-client'; import * as DatasetUtils from '../util/dataset'; import * as Validation from '../util/validation'; import * as Importer from '../util/import_device'; import { BadRequestError } from '../util/errors'; const router = express.Router(); router.get('/', (req, res) => { res.render('thingpedia_translate_portal', { page_title: req._("Translate Thingpedia") }); }); // TODO precise type annotations function makeTranslationPairs(english : any, translated : any) { // we need to translate canonicals, confirmations, slot-filling questions, // argument names (in canonical form) and const out : any = { actions: {}, queries: {} }; for (const what of ['actions', 'queries']) { if (!translated[what]) translated[what] = {}; for (const name in english[what]) { if (!translated[what][name]) { translated[what][name] = { canonical: '', confirmation: '', formatted: [], questions: [], argcanonicals: [] }; } out[what][name] = { canonical: { english: english[what][name].canonical, translated: translated[what][name].canonical }, confirmation: { english: english[what][name].confirmation, translated: translated[what][name].confirmation }, formatted: [], args: [], }; for (let i = 0; i < english[what][name].formatted.length; i++) { let englishformat = english[what][name].formatted[i]; let translatedformat = translated[what][name].formatted[i] || {}; if (typeof englishformat === 'string') englishformat = { type: 'text', text: englishformat }; if (typeof translatedformat === 'string') translatedformat = { type: 'text', text: translatedformat }; const doubleformat : any = { type: englishformat.type, }; for (const key in englishformat) { if (key === 'type') continue; doubleformat[key] = { english: englishformat[key], translated: translatedformat[key] }; } out[what][name].formatted.push(doubleformat); } english[what][name].args.forEach((argname : string, i : number) => { out[what][name].args.push({ name: argname, argcanonical: { english: english[what][name].argcanonicals[i], translated: translated[what][name].argcanonicals[i] }, question: { english: english[what][name].questions[i], translated: translated[what][name].questions[i] } }); }); } } return out; } router.get('/by-id/:kind', user.requireLogIn, iv.validateGET({ fromVersion: '?integer', }), (req, res, next) => { const language = I18n.localeToLanguage(req.locale); if (language === 'en') { res.status(403).render('error', { page_title: req._("Thingpedia - Error"), message: req._("Translations for English cannot be contributed.") }); return; } db.withTransaction(async (dbClient) => { let fromVersion = req.query.fromVersion ? parseInt(req.query.fromVersion) : null; const englishinfo = await model.getByKind(dbClient, req.params.kind); const englishrows = await model.getMetasByKinds(dbClient, [req.params.kind], req.user!.developer_org, 'en'); let maxVersion; if (englishinfo.owner === req.user!.developer_org || (req.user!.roles & user.Role.THINGPEDIA_ADMIN) === 0) maxVersion = englishinfo.developer_version; else maxVersion = englishinfo.approved_version; if (maxVersion === null) // pretend the device does not exist if it is not visible throw new NotFoundError(); if (fromVersion !== null) fromVersion = Math.min(fromVersion, maxVersion); else fromVersion = maxVersion; const translatedrows = await model.getMetasByKindAtVersion(dbClient, req.params.kind, fromVersion, language); const english = englishrows[0]; const translated = translatedrows[0] || {}; const translatedExamples = await exampleModel.getBaseBySchema(dbClient, englishinfo.id, language); let dataset; if (translatedExamples.length > 0) { dataset = await DatasetUtils.examplesToDataset(req.params.kind, language, translatedExamples, { editMode: true }); } else { const englishExamples = await exampleModel.getBaseBySchema(dbClient, englishinfo.id, 'en'); dataset = await DatasetUtils.examplesToDataset(req.params.kind, language, englishExamples, { editMode: true, skipId: true }); } const { actions, queries } = makeTranslationPairs(english, translated); res.render('thingpedia_translate_schema', { page_title: req._("Thingpedia - Translate Device"), kind: req.params.kind, language, fromVersion, actions, queries, dataset, }); }, 'serializable', 'read only').catch(next); }); async function validateDataset(req : express.Request, dbClient : db.Client) { const tpClient = new ThingpediaClient(req.user!.developer_key, req.user!.locale, undefined, dbClient); const schemaRetriever = new ThingTalk.SchemaRetriever(tpClient, null, true); const parsed = await ThingTalk.Syntax.parse(req.body.dataset, ThingTalk.Syntax.SyntaxType.Normal, { locale: req.user!.locale, timezone: req.user!.timezone, }).typecheck(schemaRetriever, false); if (!(parsed instanceof ThingTalk.Ast.Library) || parsed.datasets.length !== 1 || parsed.datasets[0].name !== '@' + req.params.kind || parsed.datasets[0].language !== req.body.language) throw new Validation.ValidationError("Invalid dataset file: must contain exactly one dataset, with the same identifier as the class and the correct language"); const dataset = parsed.datasets[0]; await Validation.tokenizeDataset(dataset); await Validation.validateDataset(dataset); return dataset; } interface PrimitiveTypes { string : string; number : number; null : null; undefined : undefined; object : object; } function safeGet(obj : any, expect : undefined, ...args : string[]) : unknown; function safeGet<T extends 'string'|'number'|'null'|'undefined'|'object'>(obj : any, expect : T, ...args : string[]) : PrimitiveTypes[T]; function safeGet(obj : any, expect : string|undefined, ...args : string[]) : unknown { for (let i = 0; i < args.length - 1; i++) { const key = args[i]; if (typeof obj[key] !== 'object') throw new BadRequestError(`Invalid type for parameter [${args.join('][')}]`); obj = obj[key]; } const lastKey = args[args.length-1]; if (expect !== undefined && typeof obj[lastKey] !== expect) throw new BadRequestError(`Invalid type for parameter [${args.join('][')}]`); return obj[lastKey]; } function computeTranslations(req : express.Request, english : any) { const translations : any = {}; for (const what of ['actions', 'queries']) { for (const name in english[what]) { const canonical = safeGet(req.body, 'string', 'canonical', name); if (!canonical) throw new Validation.ValidationError(`Missing canonical for ${what} ${name}`); const confirmation = safeGet(req.body, 'string', 'confirmation', name); if (!confirmation) throw new Validation.ValidationError(`Missing confirmation for ${what} ${name}`); let formatted : any = safeGet(req.body, undefined, 'formatted', name); if (formatted !== undefined && !Array.isArray(formatted)) throw new BadRequestError(`Invalid type for parameter [formatted][${name}]`); if (formatted === undefined) formatted = []; for (let i = 0; i < formatted.length; i++) { const formatel = formatted[i]; if (typeof formatel !== 'object' || typeof formatel.type !== 'string' || !(formatel.type !== 'text' || typeof formatel.text === 'string')) throw new BadRequestError(`Invalid type for parameter [formatted][${name}]`); if (formatel.type === 'text') formatted[i] = formatel.text; } const questions = []; const argcanonicals = []; for (let i = 0; i < english[what][name].args.length; i++) { const argname = english[what][name].args[i]; const argcanonical = safeGet(req.body, 'string', 'argcanonical', name, argname); if (!argcanonical) throw new Validation.ValidationError(`Missing argument name for ${argname} in ${what} ${name}`); argcanonicals.push(argcanonical); if (english[what][name].questions[i]) { const question = safeGet(req.body, 'string', 'question', name, argname); if (!question) throw new Validation.ValidationError(`Missing slot-filling question for ${argname} in ${what} ${name}`); questions.push(question); } else { questions.push(''); } } translations[name] = { canonical, confirmation, formatted, questions, argcanonicals, }; } } return translations; } router.post('/by-id/:kind', user.requireLogIn, iv.validatePOST({ language: 'string', dataset: 'string' }), (req, res, next) => { const language = req.body.language; if (language === 'en') { res.status(403).render('error', { page_title: req._("Thingpedia - Error"), message: req._("Translations for English cannot be contributed.") }); return; } if (!I18n.get(language, false)) { res.status(400).render('error', { page_title: req._("Thingpedia - Error"), message: req._("Invalid language identifier %s.").format(language) }); return; } db.withTransaction(async (dbClient) => { const englishinfo = await model.getByKind(dbClient, req.params.kind); const englishrows = await model.getMetasByKinds(dbClient, [req.params.kind], req.user!.developer_org, 'en'); if (englishrows.length === 0) throw new NotFoundError(); const english = englishrows[0]; let dataset, translations; try { dataset = await validateDataset(req, dbClient); translations = computeTranslations(req, english); } catch(e) { console.error(e); if (!(e instanceof Validation.ValidationError)) throw e; res.status(400).render('error', { page_title: req._("Thingpedia - Error"), message: e }); return; } await model.insertTranslations(dbClient, englishinfo.id, englishinfo.developer_version, language, translations); await Importer.ensureDataset(dbClient, englishinfo.id, null, dataset); res.redirect(303, '/thingpedia/classes/by-id/' + req.params.kind); }).catch(next); }); export default router;
the_stack
import { OnInit, OnDestroy, ComponentFactoryResolver, ComponentFactory, ComponentRef, ViewChild, ViewContainerRef, ElementRef, Input, } from '@angular/core'; import { ArmObj } from '../../../../shared/models/arm/arm-obj'; import { Site } from '../../../../shared/models/arm/site'; import { Subscription } from 'rxjs/Subscription'; import { ConsoleService } from './../services/console.service'; import { KeyCodes, ConsoleConstants } from '../../../../shared/models/constants'; import { ErrorComponent } from './error.component'; import { MessageComponent } from './message.component'; import { PromptComponent } from './prompt.component'; import { Headers } from '@angular/http'; import { PortalService } from '../../../../shared/services/portal.service'; import { Subject } from 'rxjs/Subject'; export abstract class AbstractConsoleComponent implements OnInit, OnDestroy { public resourceId: string; public consoleType: number; public isFocused = false; public commandInParts = { leftCmd: '', middleCmd: ' ', rightCmd: '' }; // commands to left, right and on the pointer public dir: string; public initialized = false; public cleared = false; protected enterPressed = false; protected site: ArmObj<Site>; protected siteSubscription: Subscription; protected publishingCredSubscription: Subscription; /*** Variables for Tab-key ***/ protected listOfDir: string[] = []; protected dirIndex = -1; protected lastAPICall: Subscription = undefined; protected tabKeyPointer: number; /*** Variables for Command + Dir @Input ***/ protected command = ''; protected ptrPosition = 0; protected commandHistory: string[] = ['']; protected commandHistoryIndex = 1; protected currentPrompt: ComponentRef<any> = null; private _lastKeyPressed = -1; private _promptComponent: ComponentFactory<any>; private _messageComponent: ComponentFactory<any>; private _errorComponent: ComponentFactory<any>; private _msgComponents: ComponentRef<any>[] = []; private _ngUnsubscribe = new Subject(); private _armToken: string; @Input() public appName: string; /** * UI Elements */ @ViewChild('prompt', { read: ViewContainerRef }) private _prompt: ViewContainerRef; @ViewChild('consoleText') private _consoleText: ElementRef; constructor( private _componentFactoryResolver: ComponentFactoryResolver, private _consoleService: ConsoleService, private _portalService: PortalService ) {} ngOnInit() { this._portalService .getStartupInfo() .takeUntil(this._ngUnsubscribe) .subscribe(info => { this._armToken = info.token; if (!this.initialized) { this.initializeConsole(); this.initialized = true; this.addPromptComponent(); this.focusConsole(); } }); this._consoleService .getResourceId() .takeUntil(this._ngUnsubscribe) .subscribe(resourceId => { this.resourceId = resourceId; }); } ngOnDestroy() { this._ngUnsubscribe.next(); this.siteSubscription.unsubscribe(); if (this.lastAPICall && !this.lastAPICall.closed) { this.lastAPICall.unsubscribe(); } } /** * Intialize console specific variables like dir */ protected abstract initializeConsole(); /** * Mouse Press outside the console, * i.e. the console no longer in focus */ unFocusConsole() { this.isFocused = false; this._renderPromptVariables(); } /** * Unfocus console manually */ unFocusConsoleManually() { this._consoleText.nativeElement.blur(); } /** * Console brought to focus when textarea comes into focus */ focusConsoleOnTabPress() { this.isFocused = true; this._renderPromptVariables(); } /** * Mouse press inside the console, i.e. console comes into focus. * If already in focus, the console remains to be in focus. */ focusConsole() { this.isFocused = true; this._renderPromptVariables(); this._consoleText.nativeElement.focus(); } /** * Handle the paste event when in focus * @param event: KeyEvent (paste in particular) */ handlePaste(event) { const text = event.clipboardData.getData('text/plain'); this.command += text; this.ptrPosition = this.command.length; this.divideCommandForPtr(); } /** * Handle the right mouse click * @param event: MouseEvent, particularly right-click */ handleRightMouseClick(event): boolean { return false; } /** * Handle the copy event when in focus * @param event: Keyevent (copy in particular) */ handleCopy(event) { if (!this.lastAPICall || this.lastAPICall.closed) { this._removePrompt(); this.addMessageComponent(); } else if (!this.lastAPICall.closed) { this.lastAPICall.unsubscribe(); } this._resetCommand(); this.addPromptComponent(); } /** * Handles the key event of the keyboard, * is called only when the console is in focus. * @param event: KeyEvent */ keyEvent(event) { if (!this._isKeyEventValid(event.which)) { return; } /** * Switch case on the key number */ switch (event.which) { case KeyCodes.backspace: { this._backspaceKeyEvent(); break; } case KeyCodes.tab: { event.preventDefault(); this.tabKeyEvent(); return; } case KeyCodes.enter: { this._enterKeyEvent(); break; } case KeyCodes.escape: { this._resetCommand(); break; } case KeyCodes.space: { this._appendToCommand(ConsoleConstants.whitespace); break; } case KeyCodes.arrowLeft: { this._leftArrowKeyEvent(); break; } case KeyCodes.arrowUp: { this._topArrowKeyEvent(); break; } case KeyCodes.arrowRight: { this._rightArrowKeyEvent(); break; } case KeyCodes.arrowDown: { this._downArrowKeyEvent(); break; } default: { this._appendToCommand(event.key, event.which); break; } } this._lastKeyPressed = event.which; this._renderPromptVariables(); this._refreshTabFunctionElements(); } /** * Get the delimeter according to the app type */ protected abstract getMessageDelimeter(): string; /** * Get the command to list all the directories for the specific console-type */ protected abstract getTabKeyCommand(): string; /** * perform action on key pressed. */ protected abstract performAction(cmd?: string): boolean; /** * Handle the tab-pressed event */ protected abstract tabKeyEvent(); /** * Get Kudu API URL */ protected abstract getKuduUri(): string; /** * Get the left-hand-side text for the console */ protected abstract getConsoleLeft(); /** * Connect to the kudu API and display the response; * both incase of an error or a valid response */ protected abstract connectToKudu(); /** * Get the header to connect to the KUDU API. */ protected getHeader(): Headers { const headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Accept', 'application/json'); headers.append('Authorization', `Bearer ${this._armToken}`); return headers; } /** * Remove all the message history */ protected removeMsgComponents() { let len = this._msgComponents.length; while (len > 0) { --len; this._msgComponents.pop().destroy(); } } /** * Add a message component, this is usually called after user presses enter * and we have a response from the Kudu API(might be an error). * @param message: String, represents a message to be passed to be shown */ protected addMessageComponent(message?: string) { if (!this._messageComponent) { this._messageComponent = this._componentFactoryResolver.resolveComponentFactory(MessageComponent); } const msgComponent = this._prompt.createComponent(this._messageComponent); msgComponent.instance.isCommand = message ? false : true; msgComponent.instance.loading = message ? false : true; msgComponent.instance.message = message ? message : this.getConsoleLeft() + this.command; this._msgComponents.push(msgComponent); this._updateConsoleScroll(); } /** * Creates a new prompt box, * created everytime a command is entered by the user and * some response is generated from the server, or 'cls', 'exit' */ protected addPromptComponent() { if (!this._promptComponent) { this._promptComponent = this._componentFactoryResolver.resolveComponentFactory(PromptComponent); } this.currentPrompt = this._prompt.createComponent(this._promptComponent); this.currentPrompt.instance.dir = this.getConsoleLeft(); this.currentPrompt.instance.consoleType = this.consoleType; // hide the loader on the last 2 msg-components if (this._msgComponents.length > 0) { // check required if 'clear' command is entered. this._msgComponents[this._msgComponents.length - 1].instance.loading = false; } if (this._msgComponents.length > 1) { this._msgComponents[this._msgComponents.length - 2].instance.loading = false; } this._updateConsoleScroll(); } /** * Create a error message * @param error : String, represents the error message to be shown */ protected addErrorComponent(error: string) { if (!this._errorComponent) { this._errorComponent = this._componentFactoryResolver.resolveComponentFactory(ErrorComponent); } const errorComponent = this._prompt.createComponent(this._errorComponent); this._msgComponents.push(errorComponent); errorComponent.instance.message = error; this._updateConsoleScroll(); } /** * Divide the commands into left, current and right */ protected divideCommandForPtr() { if (this.ptrPosition < 0 || this.ptrPosition > this.command.length) { return; } if (this.ptrPosition === this.command.length) { this.commandInParts.leftCmd = this.command; this.commandInParts.middleCmd = ConsoleConstants.whitespace; this.commandInParts.rightCmd = ''; return; } this.commandInParts.leftCmd = this.command.substring(0, this.ptrPosition); this.commandInParts.middleCmd = this.command.substring(this.ptrPosition, this.ptrPosition + 1); this.commandInParts.rightCmd = this.command.substring(this.ptrPosition + 1, this.command.length); } /** * Change the command on tab-key event */ protected setCommandOnTabKeyEvent() { this.dirIndex = (this.dirIndex + 1) % this.listOfDir.length; this.command = this.command.substring(0, this.tabKeyPointer + 1); this.command += this.listOfDir[this.dirIndex].trim(); } /** * Replace a part of the command with the file-name in the current directory */ protected replaceWithFileName() { this.setCommandOnTabKeyEvent(); this.ptrPosition = this.command.length; this.divideCommandForPtr(); } /** * Scroll to the latest test in the console */ private _updateConsoleScroll() { window.setTimeout(() => { const el = document.getElementById('console-body'); if (el) { el.scrollTop = el.scrollHeight; } }); } private _isKeyEventValid(key: number) { if (key === KeyCodes.unknown) { // block all unknown key inputs return false; } if (this.enterPressed && key !== KeyCodes.ctrl && key !== KeyCodes.c) { // command already in progress return false; } return true; } /** * Left Arrow key pressed */ private _leftArrowKeyEvent() { if (this.ptrPosition >= 1) { --this.ptrPosition; this.divideCommandForPtr(); } } /** * Right Arrow key pressed */ private _rightArrowKeyEvent() { if (this.ptrPosition < this.command.length) { ++this.ptrPosition; this.divideCommandForPtr(); } } /** * Down Arrow key pressed */ private _downArrowKeyEvent() { if (this.commandHistory.length > 0 && this.commandHistoryIndex < this.commandHistory.length - 1) { this.commandHistoryIndex = (this.commandHistoryIndex + 1) % this.commandHistory.length; this.command = this.commandHistory[this.commandHistoryIndex]; this.ptrPosition = this.command.length; this.divideCommandForPtr(); } } /** * Top Arrow key pressed */ private _topArrowKeyEvent() { if (this.commandHistoryIndex > 0) { this.command = this.commandHistory[this.commandHistoryIndex - 1]; this.commandHistoryIndex = this.commandHistoryIndex === 1 ? 0 : --this.commandHistoryIndex; this.ptrPosition = this.command.length; this.divideCommandForPtr(); } } /** * Backspace pressed by the user */ private _backspaceKeyEvent() { if (this.ptrPosition < 1) { return; } this.commandInParts.leftCmd = this.commandInParts.leftCmd.slice(0, -1); if (this.ptrPosition === this.command.length) { this.command = this.commandInParts.leftCmd; --this.ptrPosition; return; } this.command = this.commandInParts.leftCmd + this.commandInParts.middleCmd + this.commandInParts.rightCmd; --this.ptrPosition; this.divideCommandForPtr(); } /** * Handle the Enter key pressed operation */ private _enterKeyEvent() { this.enterPressed = true; const flag = this.performAction(); this._removePrompt(); this.commandHistory.push(this.command); this.commandHistoryIndex = this.commandHistory.length; if (flag) { this.addMessageComponent(); this.connectToKudu(); } else { this.addPromptComponent(); this.enterPressed = false; } this._resetCommand(); } /** * Remove the current prompt from the console */ private _removePrompt() { const oldPrompt = document.getElementById('prompt'); if (oldPrompt) { oldPrompt.parentNode.removeChild(oldPrompt); } } /** * Refresh the tab elements, * i.e. the list of files/folder and the current dir index */ private _refreshTabFunctionElements() { this.listOfDir.length = 0; this.dirIndex = -1; } /** * Reset the command */ private _resetCommand() { this.command = ''; this.commandInParts.rightCmd = ''; this.commandInParts.leftCmd = ''; this.commandInParts.middleCmd = ConsoleConstants.whitespace; this.ptrPosition = 0; } /** * Add the text to the current command * @param cmd :String */ private _appendToCommand(cmd: string, key?: number) { if ( key && ((key > KeyCodes.backspace && key <= KeyCodes.delete) || (key >= KeyCodes.leftWindow && key <= KeyCodes.select) || (key >= KeyCodes.f1 && key < KeyCodes.scrollLock)) ) { // key-strokes not allowed, for e.g F1-F12 return; } if (key && (key === KeyCodes.c || key === KeyCodes.v) && this._lastKeyPressed === KeyCodes.ctrl) { // Ctrl + C or Ctrl + V pressed, should not append c/v to the current command return; } this.commandHistoryIndex = this.commandHistory.length; // reset the command-index to the last command if (this.ptrPosition === this.command.length) { this.commandInParts.leftCmd += cmd; this.command = this.commandInParts.leftCmd; ++this.ptrPosition; return; } this.commandInParts.leftCmd += cmd; this.command = this.commandInParts.leftCmd + this.commandInParts.middleCmd + this.commandInParts.rightCmd; ++this.ptrPosition; } /** * Render the dynamically loaded prompt box, * i.e. pass in the updated command the inFocus value to the PromptComponent. */ private _renderPromptVariables() { if (this.currentPrompt) { this.currentPrompt.instance.command = this.command; this.currentPrompt.instance.commandInParts = this.commandInParts; this.currentPrompt.instance.isFocused = this.isFocused; } } }
the_stack
import crypto from "crypto"; import { FiatTokenV2Instance } from "../../../@types/generated"; import { Approval } from "../../../@types/generated/FiatTokenV2"; import { ACCOUNTS_AND_KEYS, MAX_UINT256, ZERO_ADDRESS, } from "../../helpers/constants"; import { expectRevert, hexStringFromBuffer } from "../../helpers"; import { signPermit, TestParams, signTransferAuthorization, permitTypeHash, } from "./helpers"; export function testPermit({ getFiatToken, getDomainSeparator, fiatTokenOwner, accounts, }: TestParams): void { describe("permit", () => { let fiatToken: FiatTokenV2Instance; let domainSeparator: string; const [alice, bob] = ACCOUNTS_AND_KEYS; const charlie = accounts[1]; const initialBalance = 10e6; const permitParams = { owner: alice.address, spender: bob.address, value: 7e6, nonce: 0, deadline: MAX_UINT256, }; beforeEach(async () => { fiatToken = getFiatToken(); domainSeparator = getDomainSeparator(); await fiatToken.configureMinter(fiatTokenOwner, 1000000e6, { from: fiatTokenOwner, }); await fiatToken.mint(permitParams.owner, initialBalance, { from: fiatTokenOwner, }); }); it("has the expected type hash", async () => { expect(await fiatToken.PERMIT_TYPEHASH()).to.equal(permitTypeHash); }); it("grants allowance when a valid permit is given", async () => { const { owner, spender, deadline } = permitParams; let { value } = permitParams; // create a signed permit to grant Bob permission to spend Alice's funds // on behalf, and sign with Alice's key let nonce = 0; let { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // check that the allowance is initially zero expect((await fiatToken.allowance(owner, spender)).toNumber()).to.equal( 0 ); // check that the next nonce expected is zero expect((await fiatToken.nonces(owner)).toNumber()).to.equal(0); // a third-party, Charlie (not Alice) submits the permit let result = await fiatToken.permit( owner, spender, value, deadline, v, r, s, { from: charlie } ); // check that allowance is updated expect((await fiatToken.allowance(owner, spender)).toNumber()).to.equal( value ); // check that Approval event is emitted let log = result.logs[0] as Truffle.TransactionLog<Approval>; expect(log.event).to.equal("Approval"); expect(log.args[0]).to.equal(owner); expect(log.args[1]).to.equal(spender); expect(log.args[2].toNumber()).to.equal(value); // check that the next nonce expected is now 1 expect((await fiatToken.nonces(owner)).toNumber()).to.equal(1); // increment nonce nonce = 1; value = 1e6; ({ v, r, s } = signPermit( owner, spender, 1e6, nonce, deadline, domainSeparator, alice.key )); // submit the permit result = await fiatToken.permit( owner, spender, value, deadline, v, r, s, { from: charlie } ); // check that allowance is updated expect((await fiatToken.allowance(owner, spender)).toNumber()).to.equal( 1e6 ); // check that Approval event is emitted log = result.logs[0] as Truffle.TransactionLog<Approval>; expect(log.event).to.equal("Approval"); expect(log.args[0]).to.equal(owner); expect(log.args[1]).to.equal(spender); expect(log.args[2].toNumber()).to.equal(1e6); }); it("reverts if the signature does not match given parameters", async () => { const { owner, spender, value, nonce, deadline } = permitParams; // create a signed permit const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // try to cheat by claiming the approved amount is double await expectRevert( fiatToken.permit( owner, spender, value * 2, // pass incorrect value deadline, v, r, s, { from: charlie } ), "invalid signature" ); }); it("reverts if the signature is not signed with the right key", async () => { const { owner, spender, value, nonce, deadline } = permitParams; // create a signed permit to grant Bob permission to spend // Alice's funds on behalf, but sign with Bob's key instead of Alice's const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, bob.key ); // try to cheat by submitting the permit that is signed by a // wrong person await expectRevert( fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }), "invalid signature" ); }); it("reverts if the permit is expired", async () => { const { owner, spender, value, nonce } = permitParams; // create a signed permit that won't be valid until 10 seconds // later const deadline = Math.floor(Date.now() / 1000) - 1; const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // try to submit the permit that is expired await expectRevert( fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }), "permit is expired" ); }); it("reverts if the nonce given does not match the next nonce expected", async () => { const { owner, spender, value, deadline } = permitParams; const nonce = 1; // create a signed permit const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // check that the next nonce expected is 0, not 1 expect((await fiatToken.nonces(owner)).toNumber()).to.equal(0); // try to submit the permit await expectRevert( fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }), "invalid signature" ); }); it("reverts if the permit has already been used", async () => { const { owner, spender, value, nonce, deadline } = permitParams; // create a signed permit const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // submit the permit await fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }); // try to submit the permit again await expectRevert( fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }), "invalid signature" ); }); it("reverts if the permit has a nonce that has already been used by the signer", async () => { const { owner, spender, value, nonce, deadline } = permitParams; // create a signed permit const permit = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // submit the permit await fiatToken.permit( owner, spender, value, deadline, permit.v, permit.r, permit.s, { from: charlie } ); // create another signed permit with the same nonce, but // with different parameters const permit2 = signPermit( owner, spender, 1e6, nonce, deadline, domainSeparator, alice.key ); // try to submit the permit again await expectRevert( fiatToken.permit( owner, spender, 1e6, deadline, permit2.v, permit2.r, permit2.s, { from: charlie } ), "invalid signature" ); }); it("reverts if the permit includes invalid approval parameters", async () => { const { owner, value, nonce, deadline } = permitParams; // create a signed permit that attempts to grant allowance to the // zero address const spender = ZERO_ADDRESS; const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // try to submit the permit with invalid approval parameters await expectRevert( fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }), "approve to the zero address" ); }); it("reverts if the permit is not for an approval", async () => { const { owner: from, spender: to, value, deadline: validBefore, } = permitParams; // create a signed permit for a transfer const validAfter = 0; const nonce = hexStringFromBuffer(crypto.randomBytes(32)); const { v, r, s } = signTransferAuthorization( from, to, value, validAfter, validBefore, nonce, domainSeparator, alice.key ); // try to submit the transfer permit await expectRevert( fiatToken.permit(from, to, value, validBefore, v, r, s, { from: charlie, }), "invalid signature" ); }); it("reverts if the contract is paused", async () => { const { owner, spender, value, nonce, deadline } = permitParams; // create a signed permit const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // pause the contract await fiatToken.pause({ from: fiatTokenOwner }); // try to submit the permit await expectRevert( fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }), "paused" ); }); it("reverts if the owner or the spender is blacklisted", async () => { const { owner, spender, value, nonce, deadline } = permitParams; // create a signed permit const { v, r, s } = signPermit( owner, spender, value, nonce, deadline, domainSeparator, alice.key ); // owner is blacklisted await fiatToken.blacklist(owner, { from: fiatTokenOwner }); const submitTx = () => fiatToken.permit(owner, spender, value, deadline, v, r, s, { from: charlie, }); // try to submit the permit await expectRevert(submitTx(), "account is blacklisted"); // spender is blacklisted await fiatToken.unBlacklist(owner, { from: fiatTokenOwner }); await fiatToken.blacklist(spender, { from: fiatTokenOwner }); // try to submit the permit await expectRevert(submitTx(), "account is blacklisted"); }); }); }
the_stack
import { expect } from 'chai'; import { delay } from '../../common/promiseUtil'; import Dap from '../../dap/api'; import { itIntegrates } from '../testIntegrationUtils'; describe('evaluate', () => { itIntegrates('default', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); await p.logger.evaluateAndLog(`42`); p.log(''); await p.logger.evaluateAndLog(`'foo'`); p.log(''); await p.logger.evaluateAndLog(`1234567890n`); p.log(''); await p.logger.evaluateAndLog(`throw new Error('foo')`); p.log(''); await p.logger.evaluateAndLog(`throw {foo: 3, bar: 'baz'};`); p.log(''); await p.logger.evaluateAndLog(`throw 42;`); p.log(''); await p.logger.evaluateAndLog(`{foo: 3}`); p.log(''); await p.logger.evaluateAndLog(`baz();`); p.log(''); await p.logger.evaluateAndLog(`new Uint8Array([1, 2, 3]);`); p.log(''); await p.logger.evaluateAndLog(`new Uint8Array([1, 2, 3]).buffer;`); p.log(''); await p.logger.evaluateAndLog(`new Proxy({ a: 1 }, { get: () => 2 });`); p.log(''); // prototype-free objs just to avoid adding prototype noise to tests: await p.logger.evaluateAndLog(`Object.create({ set foo(x) {} })`, { depth: 2 }); p.log(''); await p.logger.evaluateAndLog(`Object.create({ get foo() { return 42 } })`, { depth: 2 }); p.log(''); await p.logger.evaluateAndLog(`Object.create({ get foo() { throw 'wat'; } })`, { depth: 2 }); p.log(''); p.evaluate(`setTimeout(() => { throw new Error('bar')}, 0)`); await p.logger.logOutput(await p.dap.once('output')); p.log(''); p.dap.evaluate({ expression: `setTimeout(() => { throw new Error('baz')}, 0)` }); await p.logger.logOutput(await p.dap.once('output')); p.log(''); await p.addScriptTag('browserify/bundle.js'); await p.logger.evaluateAndLog(`window.throwError('error1')`); p.log(''); await p.logger.evaluateAndLog(`window.throwValue({foo: 3, bar: 'baz'})`); p.log(''); p.dap.evaluate({ expression: `setTimeout(() => { window.throwError('error2')}, 0)` }); await p.logger.logOutput(await p.dap.once('output')); p.log(''); p.assertLog(); }); itIntegrates('repl', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); await p.logger.evaluateAndLog('42', undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`'foo'`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`1234567890n`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`throw new Error('foo')`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`throw {foo: 3, bar: 'baz'};`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`throw 42;`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`{foo: 3}`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`baz();`, undefined, 'repl'); p.log(''); // #490 await p.logger.evaluateAndLog( `new Map([['hello', function() { return 'world' }]])`, undefined, 'repl', ); p.log(''); const [, e1] = await Promise.all([ p.logger.evaluateAndLog( `setTimeout(() => { throw new Error('bar')}, 0); 42`, undefined, 'repl', ), p.dap.once('output'), ]); await p.logger.logOutput(e1); p.log(''); const [, e2] = await Promise.all([ p.logger.evaluateAndLog( `setTimeout(() => { throw new Error('baz')}, 0); 42`, undefined, 'repl', ), p.dap.once('output'), ]); await p.logger.logOutput(e2); p.log(''); await p.addScriptTag('browserify/bundle.js'); await p.logger.evaluateAndLog(`window.throwError('error1')`, undefined, 'repl'); p.log(''); await p.logger.evaluateAndLog(`window.throwValue({foo: 3, bar: 'baz'})`, undefined, 'repl'); p.log(''); const [, e3] = await Promise.all([ p.logger.evaluateAndLog( `setTimeout(() => { window.throwError('error2')}, 0); 42`, undefined, 'repl', ), p.dap.once('output'), ]); await p.logger.logOutput(e3); p.log(''); p.assertLog(); }); const copyExpressions: { [expr: string]: string } = { '123n': '123n', NaN: 'NaN', '{foo: "bar", baz: { a: [1, 2, 3, 4, 5, 6, 7, 8, 9], b: 123n, "complex key": true }}': `{ foo: "bar", baz: { a: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, ], b: 123n, "complex key": true, }, }`, [`{ double(x) { return x * 2; }, triple: x => { return x * 3 } }`]: `{ double: function(x) { return x * 2; }, triple: x => { return x * 3 }, }`, 'function hello() { return "world" }': 'function hello() { return "world" }', '(() => { const n = { foo: true }; n.recurse = n; return n })()': `{ foo: true, recurse: [Circular], }`, '1n << 100n': '1267650600228229401496703205376n', '(() => { const node = document.createElement("div"); node.innerText = "hi"; return node })()': `<div>hi</div>`, }; itIntegrates('copy via function', async ({ r }) => { const p = await r.launchAndLoad('blank'); p.dap.evaluate({ expression: 'var x = "hello"; copy(x)' }); expect((await p.dap.once('copyRequested')).text).to.equal('hello'); for (const [expression, expected] of Object.entries(copyExpressions)) { p.dap.evaluate({ expression: `copy(${expression})` }); const actual = await p.dap.once('copyRequested'); expect(actual.text).to.equal(expected, expression); } }); itIntegrates('copy via evaluate context', async ({ r }) => { const p = await r.launchAndLoad('blank'); for (const [expression, expected] of Object.entries(copyExpressions)) { const actual = await p.dap.evaluate({ expression, context: 'clipboard' }); expect(actual.result).to.equal(expected, expression); } }); itIntegrates('inspect', async ({ r }) => { const p = await r.launchAndLoad('blank'); p.dap.evaluate({ expression: 'function foo() {}; inspect(foo)\n//# sourceURL=test.js' }); p.log(await p.dap.once('revealLocationRequested')); p.assertLog(); }); itIntegrates('queryObjects', async ({ r }) => { const p = await r.launchAndLoad('blank'); await p.dap.evaluate({ expression: ` class Foo { constructor(value) { this.value = value; } } var foo1 = new Foo(1); var foo2 = new Foo(2); `, }); p.dap.evaluate({ expression: 'queryObjects(Foo)' }); await p.logger.logOutput(await p.dap.once('output')); p.assertLog(); }); itIntegrates('topLevelAwait', async ({ r }) => { const p = await r.launchAndLoad(` <script> function foo(x) { return x; } function koo() { return Promise.resolve(4); } </script> `); const exprs = [ 'await Promise.resolve(1)', '{a:await Promise.resolve(1)}', '$_', 'let {a,b} = await Promise.resolve({a: 1, b:2}), f = 5;', 'a', 'b', 'let c = await Promise.resolve(2)', 'c', 'let d;', 'd', 'let [i,{abc:{k}}] = [0,{abc:{k:1}}];', 'i', 'k', 'var l = await Promise.resolve(2);', 'l', 'foo(await koo());', '$_', 'const m = foo(await koo());', 'm', 'const n = foo(await\nkoo());', 'n', '`status: ${(await Promise.resolve({status:200})).status}`', 'for (let i = 0; i < 2; ++i) await i', 'for (let i = 0; i < 2; ++i) { await i }', 'await 0', 'await 0;function foo(){}', 'foo', 'class Foo{}; await 1;', 'Foo', 'await 0;function* gen(){}', 'for (var i = 0; i < 10; ++i) { await i; }', 'i', 'for (let j = 0; j < 5; ++j) { await j; }', 'j', 'gen', 'await 5; return 42;', 'let o = await 1, p', 'p', 'let q = 1, s = await 2', 's', 'await {...{foo: 42}}', ]; for (const expression of exprs) { p.log(`Evaluating: '${expression}'`); p.logger.logEvaluateResult(await p.dap.evaluate({ expression, context: 'repl' }), { depth: 0, }); } p.assertLog(); }); itIntegrates('escapes strings', async ({ r }) => { const p = await r.launchAndLoad('blank'); for (const context of ['watch', 'hover', 'repl'] as const) { p.log(`context=${context}`); await p.logger.evaluateAndLog(JSON.stringify('1\n2\r3\t\\4'), { depth: 0 }, context); } p.assertLog({ customAssert: str => expect(str).to.equal( [ 'context=watch', "result: '1\\n2\\r3\\t\\\\4'", 'context=hover', "result: '1\\n2\\r3\\t\\\\4'", 'context=repl', "\nresult: '1\n2\r3\t\\4'", '', ].join('\n'), ), }); }); itIntegrates.skip('output slots', async ({ r }) => { const p = await r.launchAndLoad('blank'); const empty = await p.dap.evaluate({ expression: 'let i = 0; console.log(++i); ++i', context: 'repl', }); const console = await p.dap.once('output'); const result = await p.dap.once('output'); await p.logger.logEvaluateResult(empty); await p.logger.logOutput(console); await p.logger.logOutput(result); p.assertLog(); }); itIntegrates.skip('output slots 2', async ({ r }) => { const p = await r.launchAndLoad('blank'); const empty = await p.dap.evaluate({ expression: ` let i = 0; setTimeout(() => { console.log(++i); throw {foo: ++i}; }, 0); ++i `, context: 'repl', }); const result = await p.dap.once('output'); const console = await p.dap.once('output'); const exception = await p.dap.once('output'); await p.logger.logEvaluateResult(empty); await p.logger.logOutput(result); await p.logger.logOutput(console); await p.logger.logOutput(exception); p.assertLog(); }); itIntegrates('selected context', async ({ r }) => { const p = await r.launchUrlAndLoad('worker.html'); p.log('--- Evaluating in page'); p.log('Pausing...'); p.dap.evaluate({ expression: `window.w.postMessage('pause');`, context: 'repl' }); const { threadId: pageThreadId } = await p.dap.once('stopped'); p.log('Paused'); const { id: pageFrameId } = ( await p.dap.stackTrace({ threadId: pageThreadId!, }) ).stackFrames[0]; await p.logger.logEvaluateResult( await p.dap.evaluate({ expression: 'isWorker', frameId: pageFrameId }), { depth: 0 }, ); p.dap.continue({ threadId: pageThreadId! }); await p.dap.once('continued'); p.log('Resumed'); p.log('--- Evaluating in worker'); p.dap.evaluate({ expression: `window.w.postMessage('pauseWorker');`, context: 'repl' }); const worker = await r.worker(); const { threadId: workerThreadId } = await worker.dap.once('stopped'); p.log('Paused'); const { id: workerFrameId } = ( await worker.dap.stackTrace({ threadId: workerThreadId!, }) ).stackFrames[0]; await worker.logger.logEvaluateResult( await worker.dap.evaluate({ expression: 'isWorker', frameId: workerFrameId }), { depth: 0 }, ); worker.dap.continue({ threadId: workerThreadId! }); await worker.dap.once('continued'); p.log('Resumed'); p.assertLog(); }); itIntegrates('cd', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html'); async function logCompletions(params: Dap.CompletionsParams) { const completions = await p.dap.completions(params); const text = params.text.substring(0, params.column - 1) + '|' + params.text.substring(params.column - 1); p.log( completions.targets.filter(c => c.label.startsWith('cd')), `"${text}": `, ); } await delay(50); // todo(connor4312): there's some race here on the first resolution await logCompletions({ line: 1, column: 1, text: '' }); await logCompletions({ line: 1, column: 3, text: 'cd' }); await logCompletions({ line: 1, column: 4, text: 'cd ' }); await logCompletions({ line: 1, column: 5, text: 'cd t' }); await logCompletions({ line: 1, column: 5, text: 'cd h' }); await logCompletions({ line: 1, column: 2, text: 'cd' }); await logCompletions({ line: 1, column: 3, text: 'co' }); p.assertLog(); }); itIntegrates('returnValue', async ({ r }) => { const p = await r.launchAndLoad('blank'); const evaluateAtReturn = async (returnValue: string, expression = '$returnValue') => { p.dap.evaluate({ expression: `(function () { debugger; return ${returnValue}; })();`, }); const { threadId } = await p.dap.once('stopped'); await p.dap.next({ threadId: threadId! }); // step past debugger; await p.dap.once('stopped'); await p.dap.next({ threadId: threadId! }); // step past return; await p.dap.once('stopped'); const frameId = ( await p.dap.stackTrace({ threadId: threadId!, }) ).stackFrames[0].id; p.log(`return ${returnValue}:\n`); await p.logger.evaluateAndLog(expression, { params: { frameId } }); await p.dap.continue({ threadId: threadId! }); }; await evaluateAtReturn('42'); await evaluateAtReturn('{ a: { b: true } }'); await evaluateAtReturn('undefined'); r.assertLog(); }); itIntegrates('auto expands getter (#447)', async ({ r }) => { const p = await r.launchUrlAndLoad('index.html', { __autoExpandGetters: true }); // prototype-free objs just to avoid adding prototype noise to tests: await p.logger.evaluateAndLog(`Object.create({ set foo(x) {} })`, { depth: 2 }); p.log(''); await p.logger.evaluateAndLog(`Object.create({ get foo() { return 42 } })`, { depth: 2 }); p.log(''); await p.logger.evaluateAndLog(`Object.create({ get foo() { throw 'wat'; } })`, { depth: 2 }); p.log(''); await p.logger.evaluateAndLog(`Object.create({ normalObject: true })`, { depth: 2 }); p.log(''); p.assertLog(); }); });
the_stack
import { codec } from '@liskhq/lisk-codec'; import { SCServerSocket } from 'socketcluster-server'; import { Peer } from '../../../src/peer'; import { DEFAULT_REPUTATION_SCORE, FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON, DEFAULT_RANDOM_SECRET, DEFAULT_PRODUCTIVITY_RESET_INTERVAL, DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY, DEFAULT_WS_MAX_MESSAGE_RATE, DEFAULT_RATE_CALCULATION_INTERVAL, DEFAULT_MESSAGE_ENCODING_FORMAT, } from '../../../src/constants'; import { EVENT_BAN_PEER, REMOTE_SC_EVENT_MESSAGE, REMOTE_SC_EVENT_RPC_REQUEST, EVENT_FAILED_TO_FETCH_PEERS, REMOTE_EVENT_RPC_GET_PEERS_LIST, EVENT_DISCOVERED_PEER, EVENT_UPDATED_PEER_INFO, EVENT_FAILED_PEER_INFO_UPDATE, EVENT_FAILED_TO_FETCH_PEER_INFO, PROTOCOL_EVENTS_TO_RATE_LIMIT, } from '../../../src/events'; import { RPCResponseError } from '../../../src/errors'; import { getNetgroup, constructPeerId } from '../../../src/utils'; import { p2pTypes } from '../../../src'; import { defaultRPCSchemas } from '../../../src/schema'; import { PeerConfig, P2PMessagePacketBufferData, P2PRequestPacketBufferData, } from '../../../src/types'; // eslint-disable-next-line @typescript-eslint/consistent-type-assertions const createSocketStubInstance = () => <SCServerSocket>({ emit: jest.fn(), destroy: jest.fn(), } as any); describe('peer/base', () => { let defaultPeerInfo: p2pTypes.P2PPeerInfo; let peerConfig: PeerConfig; let p2pDiscoveredPeerInfo: p2pTypes.P2PPeerInfo; let defaultPeer: Peer; beforeEach(() => { jest.useFakeTimers(); defaultPeerInfo = { peerId: constructPeerId('12.12.12.12', 5001), ipAddress: '12.12.12.12', port: 5001, sharedState: { networkVersion: '1.1', networkIdentifier: 'networkId', nonce: 'nonce', options: {}, }, }; peerConfig = { hostPort: 6001, rateCalculationInterval: DEFAULT_RATE_CALCULATION_INTERVAL, wsMaxMessageRate: DEFAULT_WS_MAX_MESSAGE_RATE, wsMaxMessageRatePenalty: DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY, secret: DEFAULT_RANDOM_SECRET, maxPeerInfoSize: 10000, maxPeerDiscoveryResponseLength: 1000, peerStatusMessageRate: 4, serverNodeInfo: { networkIdentifier: 'networkId', networkVersion: '1.2', nonce: 'nonce', advertiseAddress: true, options: {}, }, rpcSchemas: { ...defaultRPCSchemas, }, }; p2pDiscoveredPeerInfo = { peerId: constructPeerId(defaultPeerInfo.ipAddress, defaultPeerInfo.port), ipAddress: defaultPeerInfo.ipAddress, port: defaultPeerInfo.port, sharedState: { networkVersion: '1.3', networkIdentifier: 'networkId', nonce: 'nonce', options: {}, }, internalState: undefined, }; defaultPeer = new Peer(defaultPeerInfo, peerConfig); }); afterEach(() => { jest.clearAllTimers(); jest.restoreAllMocks(); defaultPeer.disconnect(); }); describe('#constructor', () => { it('should be an instance of Peer class', () => expect(defaultPeer).toBeInstanceOf(Peer)); it('should have a function named _handleRawRPC', () => { expect((defaultPeer as any)._handleRawRPC).toEqual(expect.any(Function)); }); it('should have a function named _handleWSMessage', () => { expect((defaultPeer as any)._handleWSMessage).toEqual(expect.any(Function)); }); it('should have a function named _handleRawMessage', () => { expect((defaultPeer as any)._handleRawMessage).toEqual(expect.any(Function)); }); }); describe('#id', () => { it('should get id property', () => expect(defaultPeer.id).toEqual(defaultPeerInfo.peerId)); }); describe('#ipAddress', () => { it('should get ipAddress property', () => expect(defaultPeer.ipAddress).toEqual(defaultPeerInfo.ipAddress)); }); describe('#port', () => { it('should get port property', () => expect(defaultPeer.port).toEqual(defaultPeerInfo.port)); }); describe('#netgroup', () => { it('should get netgroup property', () => expect(defaultPeer.internalState.netgroup).toEqual( getNetgroup(defaultPeerInfo.ipAddress, peerConfig.secret), )); }); describe('#reputation', () => { it('should get reputation property', () => expect(defaultPeer.internalState.reputation).toEqual(DEFAULT_REPUTATION_SCORE)); }); describe('#latency', () => { it('should get latency property', () => expect(defaultPeer.internalState.latency).toEqual(0)); }); describe('#connectTime', () => { it('should get connectTime property', () => expect(defaultPeer.internalState.connectTime).toBeGreaterThanOrEqual(0)); }); describe('#responseRate', () => { it('should get responseRate property', () => expect(defaultPeer.internalState.productivity.responseRate).toEqual(0)); }); describe('#productivity', () => { it('should get productivity property', () => { const productivity = { requestCounter: 0, responseCounter: 0, responseRate: 0, lastResponded: 0, }; expect(defaultPeer.internalState.productivity).toEqual(productivity); }); }); describe('#wsMessageRate', () => { it('should get wsMessageRate property', () => expect(defaultPeer.internalState.wsMessageRate).toEqual(0)); }); describe('#state', () => { it('should get state property', () => expect(defaultPeer.state).toEqual('closed')); }); describe('#peerInfo', () => { it('should get peerInfo property', () => expect(defaultPeer.peerInfo.sharedState).toEqual(defaultPeerInfo.sharedState)); }); describe('#updatePeerInfo', () => { it('should update peer info', () => { defaultPeer.updatePeerInfo(p2pDiscoveredPeerInfo); expect(defaultPeer.peerInfo.sharedState).toEqual(p2pDiscoveredPeerInfo.sharedState); }); }); describe('#connect', () => { it('should throw error if socket does not exist', () => { defaultPeer.disconnect(); expect(() => { defaultPeer.connect(); }).toThrow('Peer socket does not exist'); }); it('should not throw error if socket exists', () => { (defaultPeer as any)._socket = createSocketStubInstance(); defaultPeer.connect(); expect((defaultPeer as any)._socket).toBeDefined(); }); }); describe('#disconnect', () => { it('should clear _counterResetInterval', () => { const _resetCounters = jest.spyOn(defaultPeer as any, '_resetCounters'); defaultPeer.disconnect(); jest.advanceTimersByTime(peerConfig.rateCalculationInterval + 1); expect(_resetCounters).not.toHaveBeenCalled(); }); it('should clear _productivityResetInterval', () => { const _resetProductivity = jest.spyOn(defaultPeer as any, '_resetProductivity'); defaultPeer.disconnect(); jest.advanceTimersByTime(DEFAULT_PRODUCTIVITY_RESET_INTERVAL + 1); expect(_resetProductivity).not.toHaveBeenCalled(); }); it('should destroy socket if it exists', () => { (defaultPeer as any)._socket = createSocketStubInstance(); defaultPeer.disconnect(); expect((defaultPeer as any)._socket.destroy).toHaveBeenCalledWith(1000, undefined); }); }); describe('#send', () => { // Arrange let p2pPacket: P2PMessagePacketBufferData; beforeEach(() => { p2pPacket = { data: Buffer.from('myData'), event: 'myEvent', }; }); it('should throw error if socket does not exists', () => { expect(() => { defaultPeer.send(p2pPacket); }).toThrow('Peer socket does not exist'); }); it(`should emit for event ${REMOTE_SC_EVENT_MESSAGE}`, () => { (defaultPeer as any)._socket = createSocketStubInstance(); // Act defaultPeer.send(p2pPacket); // Assert expect((defaultPeer as any)._socket.emit).toHaveBeenCalledWith(REMOTE_SC_EVENT_MESSAGE, { event: p2pPacket.event, data: p2pPacket.data?.toString(DEFAULT_MESSAGE_ENCODING_FORMAT), }); }); }); describe('#request', () => { // Arrange let p2pPacket: P2PRequestPacketBufferData; beforeEach(() => { p2pPacket = { data: Buffer.from('myData'), procedure: 'myProcedure', }; }); it('should throw error if socket does not exists', async () => { return expect(defaultPeer.request(p2pPacket)).rejects.toThrow('Peer socket does not exist'); }); it('should emit if socket exists', () => { (defaultPeer as any)._socket = createSocketStubInstance(); // Act // eslint-disable-next-line @typescript-eslint/no-floating-promises defaultPeer.request(p2pPacket); // Assert expect((defaultPeer as any)._socket.emit).toHaveBeenCalledTimes(1); expect((defaultPeer as any)._socket.emit).toHaveBeenCalledWith( REMOTE_SC_EVENT_RPC_REQUEST, { procedure: p2pPacket.procedure, data: p2pPacket.data?.toString(DEFAULT_MESSAGE_ENCODING_FORMAT), }, expect.any(Function), ); }); }); describe('#fetchPeers', () => { it('should call request', async () => { const peerRequest = jest.spyOn(defaultPeer as any, 'request').mockResolvedValue({ data: { success: true, peers: [], }, }); await defaultPeer.fetchPeers(); expect(peerRequest).toHaveBeenCalledTimes(1); expect(peerRequest).toHaveBeenCalledWith({ procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST, }); }); describe('when request() fails', () => { beforeEach(() => { jest.spyOn(defaultPeer, 'request').mockRejectedValue(EVENT_FAILED_TO_FETCH_PEERS); (defaultPeer as any).emit = jest.fn(); }); it(`should emit ${EVENT_FAILED_TO_FETCH_PEERS} event`, async () => { try { // Act await defaultPeer.fetchPeers(); expect('never').toBe('called'); } catch (e) { // Assert // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.emit).toHaveBeenCalledTimes(1); // eslint-disable-next-line jest/no-try-expect expect((defaultPeer as any).emit).toHaveBeenCalledWith( EVENT_FAILED_TO_FETCH_PEERS, EVENT_FAILED_TO_FETCH_PEERS, ); } }); it('should throw an error', async () => { return expect(defaultPeer.fetchPeers()).rejects.toThrow(RPCResponseError); }); }); describe('when request() succeeds', () => { beforeEach(() => { jest.spyOn(defaultPeer, 'applyPenalty'); }); it('should return a sanitized peer list', async () => { const peers = [ { peerId: constructPeerId('1.1.1.1', 1111), ipAddress: '1.1.1.1', sourceAddress: '12.12.12.12', port: 1111, sharedState: {}, }, { peerId: constructPeerId('2.2.2.2', 2222), ipAddress: '2.2.2.2', sourceAddress: '12.12.12.12', port: 2222, sharedState: {}, }, ]; const sanitizedPeers = [ { peerId: constructPeerId('1.1.1.1', 1111), ipAddress: '1.1.1.1', sourceAddress: '12.12.12.12', port: 1111, sharedState: {}, }, { peerId: constructPeerId('2.2.2.2', 2222), ipAddress: '2.2.2.2', sourceAddress: '12.12.12.12', port: 2222, sharedState: {}, }, ]; codec.addSchema(defaultRPCSchemas.peerInfo); codec.addSchema(defaultRPCSchemas.peerRequestResponse); const encodedPeers = peers.map(peer => codec.encode(defaultRPCSchemas.peerInfo, { ipAddress: peer.ipAddress, port: peer.port, }), ); const data = codec.encode(defaultRPCSchemas.peerRequestResponse, { peers: encodedPeers, }); jest.spyOn(defaultPeer as any, 'request').mockResolvedValue({ data }); const response = await defaultPeer.fetchPeers(); expect(response).toEqual(sanitizedPeers); }); it('should throw apply penalty on malformed Peer list', async () => { const malformedPeerList = [...new Array(1001).keys()].map(index => ({ peerId: `'1.1.1.1:${1 + index}`, ipAddress: '1.1.1.1', port: 1 + index, sharedState: {}, })); const encodedMalformedPeersList = malformedPeerList.map(peer => codec.encode(defaultRPCSchemas.peerInfo, { ipAddress: peer.ipAddress, port: peer.port, }), ); const data = codec.encode(defaultRPCSchemas.peerRequestResponse, { peers: encodedMalformedPeersList, }); jest.spyOn(defaultPeer as any, 'request').mockResolvedValue({ data }); try { await defaultPeer.fetchPeers(); } catch (e) { // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.applyPenalty).toHaveBeenCalledTimes(1); // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.applyPenalty).toHaveBeenCalledWith(100); } }); it('should throw apply penalty on malformed Peer', async () => { const malformedPeerList = [ { peerId: "'1.1.1.1:5000", ipAddress: '1.1.1.1', port: 1111, sharedState: { version: '1.1.1', junkData: [...new Array(10000).keys()].map(() => 'a'), }, }, ]; const encodedMalformedPeersList = malformedPeerList.map(peer => codec.encode(defaultRPCSchemas.peerInfo, { ipAddress: peer.ipAddress, port: peer.port, }), ); const data = codec.encode(defaultRPCSchemas.peerRequestResponse, { peers: encodedMalformedPeersList, }); jest.spyOn(defaultPeer as any, 'request').mockResolvedValue({ data }); try { await defaultPeer.fetchPeers(); } catch (e) { // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.applyPenalty).toHaveBeenCalledTimes(1); // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.applyPenalty).toHaveBeenCalledWith(100); } }); }); }); describe('#discoverPeers', () => { let discoveredPeers: ReadonlyArray<p2pTypes.P2PPeerInfo>; beforeEach(() => { discoveredPeers = [ { peerId: constructPeerId('1.1.1.1', 1111), ipAddress: '1.1.1.1', port: 1111, sharedState: { networkIdentifier: 'networkId', nonce: 'nonce', networkVersion: '', options: {}, }, }, { peerId: constructPeerId('2.2.2.2', 2222), ipAddress: '2.2.2.2', port: 2222, sharedState: { networkIdentifier: 'networkId', nonce: 'nonce', networkVersion: '', options: {}, }, }, ]; jest.spyOn(defaultPeer as any, 'fetchPeers').mockResolvedValue(discoveredPeers); jest.spyOn(defaultPeer, 'emit'); }); it('should call fetchPeers', async () => { await defaultPeer.discoverPeers(); expect(defaultPeer.fetchPeers).toHaveBeenCalledTimes(1); }); it(`should emit ${EVENT_DISCOVERED_PEER} event 2 times`, async () => { await defaultPeer.discoverPeers(); expect((defaultPeer as any).emit).toHaveBeenCalledTimes(2); }); it(`should emit ${EVENT_DISCOVERED_PEER} event with every peer info`, async () => { await defaultPeer.discoverPeers(); expect(Object.keys(discoveredPeers)).not.toHaveLength(0); discoveredPeers.forEach(discoveredPeer => { expect((defaultPeer as any).emit).toHaveBeenCalledWith( EVENT_DISCOVERED_PEER, discoveredPeer, ); }); }); it('should return discoveredPeerInfoList', async () => { const discoveredPeerInfoList = await defaultPeer.discoverPeers(); expect(discoveredPeerInfoList).toEqual(discoveredPeers); }); }); describe('#fetchAndUpdateStatus', () => { describe('when request() fails', () => { beforeEach(() => { jest.spyOn(defaultPeer, 'request').mockRejectedValue(EVENT_FAILED_TO_FETCH_PEER_INFO); jest.spyOn(defaultPeer, 'emit'); }); it(`should emit ${EVENT_FAILED_TO_FETCH_PEER_INFO} event with error`, async () => { try { await defaultPeer.fetchAndUpdateStatus(); expect('never').toBe('called'); } catch (e) { // eslint-disable-next-line jest/no-try-expect expect((defaultPeer as any).emit).toHaveBeenCalledTimes(1); // eslint-disable-next-line jest/no-try-expect expect((defaultPeer as any).emit).toHaveBeenCalledWith( EVENT_FAILED_TO_FETCH_PEER_INFO, EVENT_FAILED_TO_FETCH_PEER_INFO, ); } }); it('should throw error', async () => { return expect(defaultPeer.fetchAndUpdateStatus()).rejects.toThrow(RPCResponseError); }); }); describe('when request() succeeds', () => { describe('when nodeInfo contains malformed information', () => { const invalidData = { data: '0b4bfc826a027f228c21da9e4ce2eef156f0742719b6b2466ec706b15441025f638f748b22adfab873561587be7285be3e3888cd9acdce226e342cf196fbc2c5', }; beforeEach(() => { jest.spyOn(defaultPeer as any, 'request').mockResolvedValue(invalidData); jest.spyOn(defaultPeer, 'emit'); jest.spyOn(defaultPeer, 'applyPenalty'); }); it('should apply penalty', async () => { expect.assertions(2); try { await defaultPeer.fetchAndUpdateStatus(); } catch (error) { // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.applyPenalty).toHaveBeenCalledTimes(1); // eslint-disable-next-line jest/no-try-expect expect(defaultPeer.applyPenalty).toHaveBeenCalledWith(100); } }); it('should throw error', async () => { return expect(defaultPeer.fetchAndUpdateStatus()).rejects.toThrow(RPCResponseError); }); }); describe('when _updateFromProtocolPeerInfo() fails', () => { const nodeInfo = { ipAddress: '1.1.1.1', port: 1111, networkVersion: '9.2', networkIdentifier: 'networkId', }; beforeEach(() => { const encodedResponse = codec.encode(defaultRPCSchemas.nodeInfo, nodeInfo); jest.spyOn(defaultPeer as any, 'request').mockResolvedValue({ data: encodedResponse }); jest.spyOn(defaultPeer, 'emit'); }); it(`should emit ${EVENT_FAILED_PEER_INFO_UPDATE} event with error`, async () => { try { await defaultPeer.fetchAndUpdateStatus(); expect('never').toBe('called'); } catch (error) { // eslint-disable-next-line jest/no-try-expect expect((defaultPeer as any).emit).toHaveBeenCalledTimes(1); // eslint-disable-next-line jest/no-try-expect expect((defaultPeer as any).emit).toHaveBeenCalledWith( EVENT_FAILED_PEER_INFO_UPDATE, expect.any(Error), ); } }); it('should throw error', async () => { return expect(defaultPeer.fetchAndUpdateStatus()).rejects.toThrow(RPCResponseError); }); }); describe('when _updateFromProtocolPeerInfo() succeeds', () => { const peerSharedState = { ipAddress: '1.1.1.1', port: 1111, networkVersion: '1.2', networkIdentifier: 'networkId', }; beforeEach(() => { codec.addSchema(defaultRPCSchemas.peerInfo); codec.addSchema(defaultRPCSchemas.peerRequestResponse); const encodedResponse = codec.encode(defaultRPCSchemas.nodeInfo, peerSharedState); jest.spyOn(defaultPeer as any, 'request').mockResolvedValue({ data: encodedResponse }); jest.spyOn(defaultPeer, 'updatePeerInfo'); jest.spyOn(defaultPeer, 'emit'); }); it('should call updatePeerInfo()', async () => { // Arrange const defaultProtocolPeerInfo = { peerId: constructPeerId(defaultPeerInfo.ipAddress, defaultPeerInfo.port), ipAddress: defaultPeerInfo.ipAddress, port: defaultPeerInfo.port, sharedState: { advertiseAddress: false, networkVersion: '1.2', networkIdentifier: 'networkId', nonce: '', }, }; // Act await defaultPeer.fetchAndUpdateStatus(); // Assert expect(defaultPeer.updatePeerInfo).toHaveBeenCalledWith(defaultProtocolPeerInfo); }); it(`should emit ${EVENT_UPDATED_PEER_INFO} event with fetched peer info`, async () => { const peerInfo = await defaultPeer.fetchAndUpdateStatus(); expect((defaultPeer as any).emit).toHaveBeenCalledWith(EVENT_UPDATED_PEER_INFO, peerInfo); }); it('should return fetched peer info', async () => { const peerInfo = await defaultPeer.fetchAndUpdateStatus(); expect(peerInfo.sharedState).toMatchObject({ networkIdentifier: 'networkId', networkVersion: '1.2', }); }); }); }); }); describe('#applyPenalty', () => { describe('when reputation does not go below 0', () => { it('should apply penalty', () => { const { reputation } = defaultPeer.internalState; const penalty = DEFAULT_REPUTATION_SCORE / 10; defaultPeer.applyPenalty(penalty); expect(defaultPeer.internalState.reputation).toEqual(reputation - penalty); }); it('should not ban peer', () => { const penalty = DEFAULT_REPUTATION_SCORE / 10; const banPeerSpy = jest.spyOn(defaultPeer as any, '_banPeer'); defaultPeer.applyPenalty(penalty); expect(banPeerSpy).not.toHaveBeenCalled(); }); }); describe('when reputation goes below 0', () => { beforeEach(() => { jest.spyOn(defaultPeer, 'disconnect'); jest.spyOn(defaultPeer, 'emit'); }); it('should apply penalty', () => { const { reputation } = defaultPeer.internalState; const penalty = DEFAULT_REPUTATION_SCORE; defaultPeer.applyPenalty(penalty); expect(defaultPeer.internalState.reputation).toEqual(reputation - penalty); }); it(`should emit ${EVENT_BAN_PEER} event`, () => { const penalty = DEFAULT_REPUTATION_SCORE; defaultPeer.applyPenalty(penalty); expect((defaultPeer as any).emit).toHaveBeenCalledWith(EVENT_BAN_PEER, defaultPeer.id); }); it('should disconnect peer', () => { const penalty = DEFAULT_REPUTATION_SCORE; defaultPeer.applyPenalty(penalty); expect(defaultPeer.disconnect).toHaveBeenCalledWith( FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON, ); }); }); }); describe('MessageRate and limiters', () => { describe('when protocol messages limit exceed', () => { beforeEach(() => { jest.spyOn(defaultPeer, 'applyPenalty'); jest.spyOn(defaultPeer, 'emit'); }); it('should not apply penalty inside rate limit', () => { // Arrange const { reputation } = defaultPeer.peerInfo.internalState; // Act [...PROTOCOL_EVENTS_TO_RATE_LIMIT.keys()].forEach(procedure => { // eslint-disable-next-line @typescript-eslint/no-empty-function (defaultPeer as any)._handleRawRPC({ procedure }, () => {}); }); jest.advanceTimersByTime(peerConfig.rateCalculationInterval + 1); // Assert expect(defaultPeer.peerInfo.internalState.reputation).toBe(reputation); }); it('should apply penalty for getPeers flood', () => { // Arrange const rawMessageRPC = { procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST, }; const { reputation } = defaultPeer.peerInfo.internalState; const requestCount = 9; // Act for (let i = 0; i < requestCount; i += 1) { // eslint-disable-next-line @typescript-eslint/no-empty-function (defaultPeer as any)._handleRawRPC(rawMessageRPC, () => {}); } jest.advanceTimersByTime(peerConfig.rateCalculationInterval + 1); // Assert // ((requestCount - 1) * 10) is the penalty added for every getPeers RPC request after the first request expect(defaultPeer.peerInfo.internalState.reputation).toBe( reputation - DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY - (requestCount - 1) * 10, ); }); it('should not apply any penalty for second getPeers after 10 secs', () => { // Arrange const rawMessageRPC = { procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST, }; // Act // eslint-disable-next-line @typescript-eslint/no-empty-function (defaultPeer as any)._handleRawRPC(rawMessageRPC, () => {}); // Assert expect(defaultPeer['_discoveryMessageCounter'].getPeers).toBe(1); expect(defaultPeer.peerInfo.internalState.reputation).toBe(100); // Act jest.advanceTimersByTime(10000); // eslint-disable-next-line @typescript-eslint/no-empty-function (defaultPeer as any)._handleRawRPC(rawMessageRPC, () => {}); // Assert expect(defaultPeer['_discoveryMessageCounter'].getPeers).toBe(1); expect(defaultPeer.peerInfo.internalState.reputation).toBe(100); }); it('should silent the request events after limit exceed', () => { // Arrange const rawMessageRPC = { procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST, }; const requestCount = 10; // Act for (let i = 0; i < requestCount; i += 1) { // eslint-disable-next-line @typescript-eslint/no-empty-function (defaultPeer as any)._handleRawRPC(rawMessageRPC, () => {}); } // Assert expect((defaultPeer as any).emit).toHaveBeenCalledTimes(1); }); }); describe('when messagesRate limit exceed', () => { beforeEach(() => { jest.spyOn(defaultPeer as any, 'applyPenalty'); }); it('should apply penalty for messagesRate exceeded', () => { // Arrange const { reputation } = defaultPeer.peerInfo.internalState; const messageCount = 101; // Act for (let i = 0; i < messageCount; i += 1) { (defaultPeer as any)._handleWSMessage(); } jest.advanceTimersByTime(peerConfig.rateCalculationInterval + 1); // Assert expect(defaultPeer.peerInfo.internalState.reputation).toBe( reputation - DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY, ); }); it('should increase penalty based on rate limit exceeded', () => { // Arrange const { reputation } = defaultPeer.peerInfo.internalState; const messageCount = 201; const expectedPenalty = DEFAULT_WS_MAX_MESSAGE_RATE_PENALTY * Math.floor(messageCount / DEFAULT_WS_MAX_MESSAGE_RATE); // Act for (let i = 0; i < messageCount; i += 1) { (defaultPeer as any)._handleWSMessage(); } jest.advanceTimersByTime(peerConfig.rateCalculationInterval + 1); // Assert expect(defaultPeer.peerInfo.internalState.reputation).toBe(reputation - expectedPenalty); }); }); }); });
the_stack
"use strict" import { getVisibleFileStates, isSingleState } from "../model/files/files.helper" import { CodeChartaStorage } from "./codeChartaStorage" import { CodeMapNode, NodeType, State } from "../codeCharta.model" import { isStandalone } from "./envDetector" import { isActionOfType } from "./reduxHelper" import { AreaMetricActions } from "../state/store/dynamicSettings/areaMetric/areaMetric.actions" import { HeightMetricActions } from "../state/store/dynamicSettings/heightMetric/heightMetric.actions" import { ColorMetricActions } from "../state/store/dynamicSettings/colorMetric/colorMetric.actions" import { BlacklistActions } from "../state/store/fileSettings/blacklist/blacklist.actions" import { FocusedNodePathActions } from "../state/store/dynamicSettings/focusedNodePath/focusedNodePath.actions" import md5 from "md5" import { APIVersions } from "../codeCharta.api.model" import { getAsApiVersion } from "./fileValidator" import { hierarchy } from "d3-hierarchy" import { getMedian, pushSorted } from "./nodeDecorator" import { RangeSliderController } from "../ui/rangeSlider/rangeSlider.component" import { ColorRangeActions } from "../state/store/dynamicSettings/colorRange/colorRange.actions" interface MetaDataTrackingItem { mapId: string codeChartaApiVersion: string creationTime: number exportedFileSizeInBytes: number statisticsPerLanguage: StatisticsPerLanguage repoCreationDate: string } interface StatisticsPerLanguage { [languageName: string]: LanguageStatistics } interface LanguageStatistics { numberOfFiles: number maxFilePathDepth: number avgFilePathDepth: number metrics: { [metricName: string]: MetricStatistics } } interface MetricStatistics { min: number firstQuantile: number median: number thirdQuantile: number max: number outliers: number[] variance: number standardDeviation: number variationCoefficient: number totalSum: number numberOfFiles: number avg: number metricValues: number[] } function isTrackingAllowed(state: State) { const singleFileStates = getVisibleFileStates(state.files) if (!isStandalone() || !isSingleState(state.files) || singleFileStates.length > 1) { return false } const fileApiVersion = getAsApiVersion(singleFileStates[0].file.fileMeta.apiVersion) const supportedApiVersion = getAsApiVersion(APIVersions.ONE_POINT_ZERO) return ( fileApiVersion.major > supportedApiVersion.major || (fileApiVersion.major === supportedApiVersion.major && fileApiVersion.minor >= supportedApiVersion.minor) ) } export function trackMapMetaData(state: State) { if (!isTrackingAllowed(state)) { return } const singleFileStates = getVisibleFileStates(state.files) const fileNodes: CodeMapNode[] = getFileNodes(singleFileStates[0].file.map) const fileMeta = singleFileStates[0].file.fileMeta const trackingDataItem: MetaDataTrackingItem = { mapId: fileMeta.fileChecksum, codeChartaApiVersion: fileMeta.apiVersion, creationTime: Date.now(), exportedFileSizeInBytes: fileMeta.exportedFileSize, statisticsPerLanguage: mapStatisticsPerLanguage(fileNodes), repoCreationDate: fileMeta.repoCreationDate } const fileStorage = new CodeChartaStorage() // Make sure that only files within usageData can be read const fileChecksum = trackingDataItem.mapId.replace(/\//g, "") try { fileStorage.setItem(`usageData/${fileChecksum}-meta`, JSON.stringify(trackingDataItem)) } catch { // ignore it } } function getFileNodes(node: CodeMapNode): CodeMapNode[] { const fileNodes: CodeMapNode[] = [] for (const { data } of hierarchy(node)) { if (data.type === NodeType.FILE) { fileNodes.push(data) } } return fileNodes } function mapStatisticsPerLanguage(fileNodes: CodeMapNode[]): StatisticsPerLanguage { const statisticsPerLanguage: StatisticsPerLanguage = {} const sumOfFilePathDepths: { [languageName: string]: number } = {} const metricValues: { [languageName: string]: { [metricName: string]: number[] } } = {} const unsortedMetricValues: { [languageName: string]: { [metricName: string]: number[] } } = {} for (const fileNode of fileNodes) { const fileLanguage = getFileExtension(fileNode.name) if (fileLanguage === null) { continue } //TODO: How to initialize automatically? if (metricValues[fileLanguage] === undefined) { metricValues[fileLanguage] = {} } if (unsortedMetricValues[fileLanguage] === undefined) { unsortedMetricValues[fileLanguage] = {} } if (sumOfFilePathDepths[fileLanguage] === undefined) { sumOfFilePathDepths[fileLanguage] = 0 } // Initialize statistics object for unseen metric of language if (!Object.prototype.hasOwnProperty.call(statisticsPerLanguage, fileLanguage)) { initializeLanguageStatistics(fileNode, statisticsPerLanguage, fileLanguage) } const currentLanguageStats = statisticsPerLanguage[fileLanguage] currentLanguageStats.numberOfFiles += 1 const currentPathDepth = getPathDepth(fileNode.path) sumOfFilePathDepths[fileLanguage] += currentPathDepth currentLanguageStats.maxFilePathDepth = Math.max(currentLanguageStats.maxFilePathDepth, currentPathDepth) currentLanguageStats.avgFilePathDepth = sumOfFilePathDepths[fileLanguage] / currentLanguageStats.numberOfFiles for (const metricName of Object.keys(fileNode.attributes)) { const metricStatistics: MetricStatistics = currentLanguageStats.metrics[metricName] if (metricStatistics === undefined) { // Skip if file has different set of metrics compared to other files of the same language continue } if (metricValues[fileLanguage][metricName] === undefined) { metricValues[fileLanguage][metricName] = [] } if (unsortedMetricValues[fileLanguage][metricName] === undefined) { unsortedMetricValues[fileLanguage][metricName] = [] } const valuesOfMetric = metricValues[fileLanguage][metricName] const unsortedValuesOfMetric = unsortedMetricValues[fileLanguage][metricName] const currentMetricValue = fileNode.attributes[metricName] pushSorted(valuesOfMetric, currentMetricValue) unsortedValuesOfMetric.push(currentMetricValue) metricStatistics.median = getMedian(valuesOfMetric) metricStatistics.max = Math.max(metricStatistics.max, currentMetricValue) metricStatistics.min = Math.min(metricStatistics.min, currentMetricValue) metricStatistics.numberOfFiles += 1 metricStatistics.totalSum += currentMetricValue metricStatistics.avg = metricStatistics.totalSum / metricStatistics.numberOfFiles metricStatistics.variance = getVariance(valuesOfMetric) metricStatistics.standardDeviation = Math.sqrt(metricStatistics.variance) metricStatistics.variationCoefficient = metricStatistics.standardDeviation / metricStatistics.avg metricStatistics.metricValues = unsortedValuesOfMetric let valuesFirstHalf: number[] let valuesSecondHalf: number[] if (valuesOfMetric.length % 2 === 0) { valuesFirstHalf = valuesOfMetric.slice(0, valuesOfMetric.length / 2) valuesSecondHalf = valuesOfMetric.slice(valuesOfMetric.length / 2, valuesOfMetric.length) } else { valuesFirstHalf = valuesOfMetric.slice(0, valuesOfMetric.length / 2) valuesSecondHalf = valuesOfMetric.slice(valuesOfMetric.length / 2 + 1, valuesOfMetric.length) } metricStatistics.firstQuantile = getMedian(valuesFirstHalf) metricStatistics.thirdQuantile = getMedian(valuesSecondHalf) const interQuartileRange = metricStatistics.thirdQuantile - metricStatistics.firstQuantile const upperOutlierBound = metricStatistics.thirdQuantile + 1.5 * interQuartileRange metricStatistics.outliers = valuesOfMetric.filter(function (value) { return value > upperOutlierBound }) } } return statisticsPerLanguage } function getVariance(array) { const n = array.length const mean = array.reduce((a, b) => a + b) / n return array.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n } function initializeLanguageStatistics(fileNode: CodeMapNode, statisticsPerLanguage: StatisticsPerLanguage, fileLanguage: string) { const initialPathDepth = getPathDepth(fileNode.path) const statisticsCurrentLanguage = (statisticsPerLanguage[fileLanguage] = { metrics: {}, numberOfFiles: 0, maxFilePathDepth: initialPathDepth, avgFilePathDepth: initialPathDepth }) for (const metricName of Object.keys(fileNode.attributes)) { statisticsCurrentLanguage.metrics[metricName] = { avg: 0, max: fileNode.attributes[metricName], median: 0, min: fileNode.attributes[metricName], numberOfFiles: 0, totalSum: 0, firstQuantile: 0, thirdQuantile: 0, variance: 0, standardDeviation: 0, variationCoefficient: 0, outliers: [] } } } function getPathDepth(path: string): number { return path.split("/").length } function getFileExtension(filePath: string): string { const lastDotPosition = filePath.lastIndexOf(".") return lastDotPosition !== -1 ? filePath.slice(lastDotPosition + 1) : null } interface SettingChangedEventPayload { eventName: string newValue: unknown } interface NodeInteractionEventPayload { eventName: string id: string type?: string nodeType?: string attributes?: MetricStatistics } interface EventTrackingItem { mapId: string eventType: string eventTime: number payload: SettingChangedEventPayload | NodeInteractionEventPayload } export function trackEventUsageData(actionType: string, state: State, payload?: any) { if ( !isTrackingAllowed(state) || (!isActionOfType(actionType, AreaMetricActions) && !isActionOfType(actionType, HeightMetricActions) && !isActionOfType(actionType, ColorMetricActions) && !isActionOfType(actionType, ColorRangeActions) && !isActionOfType(actionType, BlacklistActions) && !isActionOfType(actionType, FocusedNodePathActions) && ![RangeSliderController.COLOR_RANGE_FROM_UPDATED, RangeSliderController.COLOR_RANGE_TO_UPDATED].includes(actionType)) ) { return } const singleFileStates = getVisibleFileStates(state.files) const fileMeta = singleFileStates[0].file.fileMeta const eventTrackingItem = buildEventTrackingItem(fileMeta.fileChecksum, actionType, payload) if (eventTrackingItem === null) { return } // Make sure that only files within usageData can be read const fileChecksum = getVisibleFileStates(state.files)[0].file.fileMeta.fileChecksum.replace(/\//g, "") const fileStorage = new CodeChartaStorage() let appendedEvents = "" try { appendedEvents = fileStorage.getItem(`usageData/${fileChecksum}-events`) } catch { // ignore, it no events item exists } try { if (appendedEvents.length > 0) { appendedEvents += "\n" } fileStorage.setItem(`usageData/${fileChecksum}-events`, appendedEvents + JSON.stringify(eventTrackingItem)) } catch { // ignore tracking errors } } function buildEventTrackingItem( mapId: string, actionType: string, payload?: string & Record<string, string & MetricStatistics> ): EventTrackingItem | null { if (isSettingChangedEvent(actionType)) { return { mapId, eventType: "setting_changed", eventTime: Date.now(), payload: { eventName: actionType, newValue: payload } } } if (actionType === BlacklistActions.ADD_BLACKLIST_ITEM || actionType === BlacklistActions.REMOVE_BLACKLIST_ITEM) { return { mapId, eventType: "node_interaction", eventTime: Date.now(), payload: { eventName: actionType, id: md5(payload.path), type: payload.type, nodeType: payload.nodeType, attributes: payload.attributes } } } if (isActionOfType(actionType, FocusedNodePathActions) && payload !== "") { return { mapId, eventType: "node_interaction", eventTime: Date.now(), payload: { eventName: actionType, id: md5(payload) } } } return null } function isSettingChangedEvent(actionType: string) { return ( isActionOfType(actionType, AreaMetricActions) || isActionOfType(actionType, HeightMetricActions) || isActionOfType(actionType, ColorMetricActions) || isActionOfType(actionType, ColorRangeActions) || actionType === BlacklistActions.SET_BLACKLIST ) }
the_stack
import { ethers } from 'hardhat' import { BigNumberish, BigNumber } from '@ethersproject/bignumber' import { BytesLike } from '@ethersproject/bytes' import { ContractTransaction } from '@ethersproject/contracts' import { BridgeMock, Challenge, ChallengeTester, SequencerInbox, } from '../../build/types' import { Assertion, challengeRestHash, challengeHash, assertionExecutionHash, ExecutionState, assertionGasUsed, } from './rolluplib' export interface ChallengeSegment { Start: BigNumberish Length: BigNumberish } export interface Bisection { ChallengedSegment: ChallengeSegment Cuts: BytesLike[] } class SequencerBatchItem { constructor( public lastSeqNum: BigNumberish, public accumulator: BytesLike, public totalDelayedCount: BigNumberish, public sequencerMessage: BytesLike ) {} } interface ChainTime { BlockNum: BigNumberish Timestamp: BigNumberish } export interface Message { Kind: number Sender: string InboxSeqNum: BigNumberish GasPrice: BigNumberish Data: BytesLike ChainTime: ChainTime } function messageToBytes(msg: Message): BytesLike { return ethers.utils.solidityPack( ['uint8', 'address', 'uint256', 'uint256', 'uint256', 'uint256', 'bytes'], [ msg.Kind, msg.Sender, msg.ChainTime.BlockNum, msg.ChainTime.Timestamp, msg.InboxSeqNum, msg.GasPrice, msg.Data, ] ) } export function newSequencerItem( totalDelayedCount: BigNumberish, msg: Message, prevAcc: BytesLike ): SequencerBatchItem { const inner = ethers.utils.solidityKeccak256( ['address', 'uint256', 'uint256'], [msg.Sender, msg.ChainTime.BlockNum, msg.ChainTime.Timestamp] ) const acc = ethers.utils.solidityKeccak256( ['bytes32', 'uint256', 'bytes32', 'bytes32'], [prevAcc, msg.InboxSeqNum, inner, ethers.utils.keccak256(msg.Data)] ) return new SequencerBatchItem( msg.InboxSeqNum, acc, totalDelayedCount, messageToBytes(msg) ) } export function newDelayedItem( lastSeqNum: BigNumberish, totalDelayedCount: BigNumberish, prevAcc: BytesLike, prevDelayedCount: BigNumberish, delayedAcc: BytesLike ): SequencerBatchItem { const firstSeqNum = BigNumber.from(1) .add(lastSeqNum) .add(prevDelayedCount) .sub(totalDelayedCount) const acc = ethers.utils.solidityKeccak256( ['string', 'bytes32', 'uint256', 'uint256', 'uint256', 'bytes32'], [ 'Delayed messages:', prevAcc, firstSeqNum, prevDelayedCount, totalDelayedCount, delayedAcc, ] ) return new SequencerBatchItem(lastSeqNum, acc, totalDelayedCount, '0x') } function bisectionChunkCount( segmentIndex: BigNumberish, segmentCount: BigNumberish, totalLength: BigNumberish ): BigNumber { const total = BigNumber.from(totalLength) let size = total.div(segmentCount) if (BigNumber.from(segmentIndex).eq(0)) { size = size.add(total.mod(segmentCount)) } return size } function bisectionChunkHash( segmentStart: BigNumberish, segmentLength: BigNumberish, startHash: BytesLike, endHash: BytesLike ): BytesLike { return ethers.utils.solidityKeccak256( ['uint256', 'uint256', 'bytes32', 'bytes32'], [segmentStart, segmentLength, startHash, endHash] ) } function buildMerkleTree(chunks: BytesLike[]): BytesLike[][] { const layers: BytesLike[][] = [] layers.push(chunks) while (layers[layers.length - 1].length > 1) { const elements = layers[layers.length - 1] const nextLayer: BytesLike[] = [] for (let i = 0; i < elements.length; i++) { if (i % 2 == 1) { continue } if (i + 1 >= elements.length) { nextLayer.push(elements[i]) } else { const data = ethers.utils.solidityKeccak256( ['bytes32', 'bytes32'], [elements[i], elements[i + 1]] ) nextLayer.push(data) } } layers.push(nextLayer) } return layers } function pathToInt(path: boolean[]): BigNumber { let route = BigNumber.from(0) for (const entry of path) { route = route.mul(2) if (entry) { route = route.add(1) } } return route } function merkleProof( layers: BytesLike[][], index: number ): { proof: BytesLike[]; path: BigNumber } { if (index == 0 && layers.length == 1) { return { proof: [], path: BigNumber.from(0) } } const proof: BytesLike[] = [] let path: boolean[] = [] for (const layer of layers) { const pairIndex = index % 2 == 0 ? index + 1 : index - 1 if (pairIndex < layer.length) { path.push(index % 2 == 0) proof.push(layer[pairIndex]) } index = Math.floor(index / 2) } path = path.reverse() return { proof, path: pathToInt(path) } } function calculateBisectionTree(bisection: Bisection): BytesLike[][] { const segmentCount = bisection.Cuts.length - 1 let segmentStart = BigNumber.from(bisection.ChallengedSegment.Start) const chunks: BytesLike[] = [] for (let i = 0; i < segmentCount; i++) { const segmentLength = bisectionChunkCount( i, segmentCount, bisection.ChallengedSegment.Length ) const chunkHash = bisectionChunkHash( segmentStart, segmentLength, bisection.Cuts[i], bisection.Cuts[i + 1] ) chunks.push(chunkHash) segmentStart = segmentStart.add(segmentLength) } return buildMerkleTree(chunks) } export function executeBisectMove( challenge: Challenge, move: BisectMove ): Promise<ContractTransaction> { const prevTree = calculateBisectionTree(move.PrevBisection) const { proof, path } = merkleProof(prevTree, move.SegmentToChallenge) return challenge.bisectExecution( proof, path, move.InconsistentSegment.Start, move.InconsistentSegment.Length, move.PrevBisection.Cuts[move.SegmentToChallenge + 1], move.StartState.gasUsed, challengeRestHash(move.StartState), move.SubCuts ) } function getProver(opcode: number): number { if ((opcode >= 0xa1 && opcode <= 0xa6) || opcode == 0x70) { return 1 } else if (opcode >= 0x20 && opcode <= 0x24) { return 2 } else { return 0 } } export function executeProveContinuedMove( challenge: Challenge, move: ProveContinuedMove ): Promise<ContractTransaction> { const prevTree = calculateBisectionTree(move.PrevBisection) const { proof, path } = merkleProof(prevTree, move.SegmentToChallenge) return challenge.proveContinuedExecution( proof, path, move.ChallengedSegment.Start, move.ChallengedSegment.Length, move.PrevBisection.Cuts[move.SegmentToChallenge + 1], move.PreviousCut.gasUsed, challengeRestHash(move.PreviousCut) ) } export function executeOneStepProofMove( challenge: Challenge, move: OneStepProofMove ): Promise<ContractTransaction> { const prevTree = calculateBisectionTree(move.PrevBisection) const { proof, path } = merkleProof(prevTree, move.SegmentToChallenge) const prover = getProver(ethers.utils.arrayify(move.ProofData)[0]) return challenge.oneStepProveExecution( proof, path, move.ChallengedSegment.Start, move.ChallengedSegment.Length, move.PrevBisection.Cuts[move.SegmentToChallenge + 1], move.PreviousCut.inboxCount, [move.PreviousCut.sendAcc, move.PreviousCut.logAcc], [ move.PreviousCut.gasUsed, move.PreviousCut.sendCount, move.PreviousCut.logCount, ], move.ProofData, move.BufferProofData, prover ) } export async function executeMove( challenge: Challenge, move: Move ): Promise<ContractTransaction | undefined> { if (move === null) { await ethers.provider.send('evm_mine', []) return } switch (move.Kind) { case 'Bisect': { return executeBisectMove(challenge, move) } case 'OneStepProof': { return executeOneStepProofMove(challenge, move) } case 'ProveContinuedExecution': { return executeProveContinuedMove(challenge, move) } case 'Timeout': { return challenge.timeout() } } } export interface BisectMove { Kind: 'Bisect' PrevBisection: Bisection StartState: ExecutionState SegmentToChallenge: number InconsistentSegment: ChallengeSegment SubCuts: BytesLike[] } export interface ProveContinuedMove { Kind: 'ProveContinuedExecution' Assertion: Assertion PrevBisection: Bisection SegmentToChallenge: number ChallengedSegment: ChallengeSegment PreviousCut: ExecutionState } export interface OneStepProofMove { Kind: 'OneStepProof' Assertion: Assertion PrevBisection: Bisection SegmentToChallenge: number ChallengedSegment: ChallengeSegment PreviousCut: ExecutionState ProofData: BytesLike BufferProofData: BytesLike } export interface TimeoutMove { Kind: 'Timeout' } export type Move = | BisectMove | ProveContinuedMove | OneStepProofMove | TimeoutMove | null export class ChallengeDeployment { constructor( public challengeTester: ChallengeTester, public bridge: BridgeMock, public sequencerInbox: SequencerInbox ) {} async startChallenge( challengedAssertion: Assertion, asserter: string, challenger: string, asserterTimeLeft: BigNumberish, challengerTimeLeft: BigNumberish ): Promise<Challenge> { await this.challengeTester.startChallenge( assertionExecutionHash(challengedAssertion), challengedAssertion.afterState.inboxCount, asserter, challenger, asserterTimeLeft, challengerTimeLeft, this.sequencerInbox.address, this.bridge.address ) const challengeAddress = await this.challengeTester.challenge() const Challenge = await ethers.getContractFactory('Challenge') return Challenge.attach(challengeAddress) } } export async function setupChallengeTest( owner: string ): Promise<ChallengeDeployment> { const OneStepProof = await ethers.getContractFactory('OneStepProof') const osp = await OneStepProof.deploy() await osp.deployed() const OneStepProof2 = await ethers.getContractFactory('OneStepProof2') const osp2 = await OneStepProof2.deploy() await osp2.deployed() const OneStepProof3 = await ethers.getContractFactory('OneStepProofHash') const osp3 = await OneStepProof3.deploy() await osp3.deployed() const ChallengeTester = await ethers.getContractFactory('ChallengeTester') const challengeTester = await ChallengeTester.deploy([ osp.address, osp2.address, osp3.address, ]) await challengeTester.deployed() const Bridge = await ethers.getContractFactory('BridgeMock') const bridge = await Bridge.deploy() await bridge.deployed() await bridge.initialize() const SequencerInbox = await ethers.getContractFactory('SequencerInbox') const sequencerInbox = await SequencerInbox.deploy() await sequencerInbox.deployed() await sequencerInbox.initialize(bridge.address, owner, owner) await sequencerInbox.setMaxDelay(100000000, 10000000000) return new ChallengeDeployment(challengeTester, bridge, sequencerInbox) } export async function bisectExecution( challenge: Challenge, merkleNodes: BytesLike[], merkleRoute: BigNumberish, assertion: Assertion, chainHashes: BytesLike[] ): Promise<ContractTransaction> { return await challenge.bisectExecution( merkleNodes, merkleRoute, assertion.beforeState.gasUsed, assertionGasUsed(assertion), challengeHash(assertion.afterState), assertion.beforeState.gasUsed, challengeRestHash(assertion.beforeState), chainHashes ) }
the_stack
import { Datatypes, ConfigurationGroup, RelationTypes, GroupLayoutVariants, ConfigurationProperty, PropertyTypes, ExperienceRecommendations, PluginMetadata, CreatedByValues, SchemaInput, Attribute, } from "../../index"; import { gitHubApiOption, twitterApiOption, facebookApiOption, foursquareApiOption, instagramApiOption, last_fmApiOption, linkedinApiOption, steamApiOption, stripeApiOption, paypalApiOption, twilioApiOption, tumblrApiOption, web_scrapingApiOption, clockwork_smsApiOption, aviaryApiOption, lobApiOption, pinterestApiOption, google_mapsApiOption, chartjsApiOption, } from "./configuration-properties"; import { syntaxHighlighting } from "./documentation"; import { attributeAddons } from "./addon-property"; import { PropertyPreviewLayoutVariant } from "../../property-preview"; import { PropertyLayoutVariants } from "../../configuration-property"; // // // // // CHORE - clean up test state module, growing impossible to work with export const ComponentBuilderConfigurationProperty: ConfigurationProperty = { identifier: "components", content: { label: "Component", description: "Define the component data", documentation: "", icon: "https://res.cloudinary.com/codotype/image/upload/v1558931014/product-logos/twitter-512.png", }, type: PropertyTypes.COLLECTION, defaultValue: [], enabledByDefault: true, required: false, allowDisable: false, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, properties: [ { identifier: "componentName", content: { label: "Component Name", description: "Name of the component", icon: "", documentation: "", }, type: PropertyTypes.STRING, defaultValue: "", enabledByDefault: true, required: false, allowDisable: false, properties: [], selectOptions: [], unique: false, layoutVariant: PropertyLayoutVariants.COL_12, transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, { identifier: "componentSlug", content: { label: "Component Slug", description: "Slug of the component", documentation: "", icon: "", }, type: PropertyTypes.STRING, defaultValue: "", enabledByDefault: true, required: false, allowDisable: false, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, properties: [], selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, { identifier: "props", content: { label: "Props", description: "", documentation: "", icon: "", }, selectOptions: [], type: PropertyTypes.COLLECTION, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: false, transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, properties: [ { identifier: "type", content: { label: "Type", description: "", documentation: "", icon: "", }, type: PropertyTypes.DROPDOWN, defaultValue: "", enabledByDefault: true, required: false, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, allowDisable: false, selectOptions: [{ label: "String", value: "string" }], properties: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, { identifier: "name", content: { label: "Name", description: "", documentation: "", icon: "", }, type: PropertyTypes.STRING, defaultValue: "", enabledByDefault: true, required: false, allowDisable: false, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, selectOptions: [], properties: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, { identifier: "desc", content: { label: "Desc", description: "", documentation: "", icon: "", }, type: PropertyTypes.STRING, defaultValue: "", enabledByDefault: true, required: false, allowDisable: false, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, selectOptions: [], properties: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, ], }, { identifier: "tests", content: { label: "Tests", description: "", documentation: "", icon: "", }, type: PropertyTypes.INSTANCE, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: true, selectOptions: [], transformations: [], validations: [], properties: [ { identifier: "testType", content: { label: "Test Type", description: "", documentation: "", icon: "", }, type: PropertyTypes.DROPDOWN, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: false, selectOptions: [ { value: "table", label: "Table Test" }, { value: "snapshot", label: "Snapshot Test" }, ], properties: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, ], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, ], }; export const ComponentBuilderConfigurationPropertySingleText: ConfigurationProperty = { content: { label: "Component Name", description: "Name of the component", documentation: "", icon: "", }, identifier: "componentName", type: PropertyTypes.STRING, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: false, properties: [], selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }; export const ComponentBuilderConfigurationPropertySingleDropdown: ConfigurationProperty = { content: { label: "Dropdown Test", description: "Dropdown Testing", documentation: "", icon: "https://res.cloudinary.com/codotype/image/upload/v1558931014/product-logos/twitter-512.png", }, identifier: "dropdownTest", type: PropertyTypes.DROPDOWN, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: false, properties: [], transformations: [], validations: [], selectOptions: [ { value: "OPTION_01", label: "One", }, { value: "OPTION_02", label: "Two" }, ], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }; export const ComponentBuilderConfigurationPropertySingleNumber: ConfigurationProperty = { content: { label: "Number Test", description: "This is a number for testing. Don't overthink it. It's just a number. I'll should pull some configuration options from an existing plugin to populate this placeholder.", documentation: "", icon: "", }, identifier: "numberTest", type: PropertyTypes.NUMBER, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: false, properties: [], selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }; export const ComponentBuilderConfigurationPropertyWithInstance01: ConfigurationProperty = { identifier: "random_instance", content: { label: "RandomInstanceTest", description: "", documentation: "", icon: "", }, type: PropertyTypes.INSTANCE, defaultValue: "", enabledByDefault: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, required: false, allowDisable: true, transformations: [], validations: [], selectOptions: [], properties: [ComponentBuilderConfigurationPropertySingleDropdown], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }; export const ComponentBuilderConfigurationPropertyWithInstance: ConfigurationProperty = { identifier: "tests", content: { label: "Tests", icon: "https://res.cloudinary.com/codotype/image/upload/v1558931014/product-logos/twitter-512.png", description: "", documentation: "", }, type: PropertyTypes.INSTANCE, defaultValue: "", enabledByDefault: true, required: false, allowDisable: true, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, properties: [ ComponentBuilderConfigurationPropertySingleDropdown, ComponentBuilderConfigurationPropertySingleText, { identifier: "nested_instance", content: { label: "Nested Instance", description: "", documentation: "", icon: "", }, type: PropertyTypes.INSTANCE, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, defaultValue: "", enabledByDefault: true, required: false, allowDisable: true, selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, properties: [ ComponentBuilderConfigurationPropertySingleText, ComponentBuilderConfigurationPropertySingleDropdown, ComponentBuilderConfigurationPropertyWithInstance01, ], }, ], }; // // // // // ConfigurationGroups export const ComponentBuilderConfigurationGroup: ConfigurationGroup = { identifier: "components_group", content: { label: "Component plugin", description: "Generate React components", documentation: "Generate React components", icon: "", }, enabledByDefault: true, allowDisable: false, layoutVariant: GroupLayoutVariants.TABS, sections: [], properties: [ ComponentBuilderConfigurationPropertySingleText, ComponentBuilderConfigurationPropertySingleNumber, ComponentBuilderConfigurationPropertySingleDropdown, ComponentBuilderConfigurationPropertyWithInstance, // ComponentBuilderConfigurationProperty, ], }; // // // // export const LambdaBuilderNameProperty: ConfigurationProperty = { identifier: "lambdaName", content: { label: "Lambda Name", description: "How the Lambda function will be namd in the AWS dashboard", documentation: "", icon: "", }, type: PropertyTypes.STRING, defaultValue: "", enabledByDefault: true, required: false, unique: false, layoutVariant: PropertyLayoutVariants.COL_12, allowDisable: false, properties: [], selectOptions: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }; export const LambdaLanguageProperty: ConfigurationProperty = { identifier: "language", content: { label: "Language", description: "The programming language used to build the Lambda", documentation: "", icon: "", }, type: PropertyTypes.DROPDOWN, defaultValue: "", unique: false, layoutVariant: PropertyLayoutVariants.COL_12, enabledByDefault: true, required: false, allowDisable: false, properties: [], transformations: [], validations: [], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, selectOptions: [ { label: "TypeScript", value: "typescript", }, { label: "JavaScript", value: "javascrtip", }, ], }; export const LambdaBuilderConfigurationGroup: ConfigurationGroup = { identifier: "lambda_builder", content: { label: "Lambda Builder", description: "Generate AWS Lambdas", documentation: syntaxHighlighting, icon: "", }, enabledByDefault: true, allowDisable: false, layoutVariant: GroupLayoutVariants.LIST, sections: [], properties: [ { identifier: "lambda_collection", content: { label: "Lambdas", description: "", documentation: "", icon: "", }, type: PropertyTypes.COLLECTION, defaultValue: [], unique: false, layoutVariant: PropertyLayoutVariants.COL_12, enabledByDefault: true, required: false, allowDisable: true, selectOptions: [], transformations: [], validations: [], properties: [LambdaBuilderNameProperty, LambdaLanguageProperty], preview: { rules: [], variant: PropertyPreviewLayoutVariant.CODE_DARK, }, }, ], }; // // // // export const ApiExamplesConfigurationGroup: ConfigurationGroup = { identifier: "api_examples", content: { label: "API Examples", description: "Configurate API examples for the Application", documentation: syntaxHighlighting, icon: "", }, enabledByDefault: true, allowDisable: false, layoutVariant: GroupLayoutVariants.LIST, sections: [], properties: [twitterApiOption], }; export const SideBySideConfigurationGroup: ConfigurationGroup = { ...ComponentBuilderConfigurationGroup, content: { label: "Architecture Configuration", description: "Configure the server architecture of your application", documentation: syntaxHighlighting, icon: "", }, identifier: "component_builder_side_by_side", layoutVariant: GroupLayoutVariants.DOCS_4x8, properties: [twitterApiOption], }; // // // // // // // // PluginMetadata export const cdkPluginMeta: PluginMetadata = { identifier: "aws_cdk_starter", // unique ID for the plugin content: { label: "AWS CDK Starter", // short label for the plugin description: "A Codotype plugin for AWS CDK", // brief description of the plugin documentation: "", icon: "https://res.cloudinary.com/codotype/image/upload/v1553197653/tech-logos/nodejs.png", // URL to the plugin's icon. Must be at least 200x200px }, homepage: "https://codotype.org", // the "homepage" for this plugin version: "0.1.0", // the current version of the plugin codotypeVersion: "0.1.0", createdBy: { name: "Codotype", contact: { website: "https://codotype.io", }, }, techTags: ["AWS", "React", "TypeScript", "CDK", "Lambda", "DynamoDB", "S3"], // an array of strings describing the tech used in the plugin typeTags: ["Full-stack", "Infrastructure"], // describes the type of codebase produced by this plugin experience: ExperienceRecommendations.beginner, // an optional tag detailing the level of experience required to use the code produced by the plugin project_path: "output", // the name of the directory for the plugin's output schemaEditorConfiguration: { configurationGroups: [], supportedDatatypes: [], // The datatypes supported by this plugin.Only an array of DATATYPE_ * identifiers that correspond to values defined in @codotype/core are accepted. supportedRelationTypes: [], // The relation types supported by this plugin.Only an array of RELATION_TYPE_ * identifiers that correspond to values defined in @codotype/core are accepted. defaultSchemas: [], newSchemaDefaults: { attributes: [], relations: [], }, defaultRelations: [], attributeAddons: [], relationAddons: [], }, configurationGroups: [ LambdaBuilderConfigurationGroup, { ...ComponentBuilderConfigurationGroup, identifier: "api_examples", content: { ...ComponentBuilderConfigurationGroup.content, label: "API Examples", }, properties: [twitterApiOption], }, ComponentBuilderConfigurationGroup, SideBySideConfigurationGroup, ], // an array of OptionGroup objects that expose additional configuration provided by the plugin exampleProjects: [], }; // // // // // Schemas export const userSchema: SchemaInput = { id: "12345", identifiers: { singular: { title: "User", snake: "user", camel: "user", pascal: "User", kebab: "user", }, plural: { title: "Users", snake: "users", camel: "users", pascal: "Users", kebab: "users", }, }, attributes: [], internalNote: "", locked: false, removable: false, createdBy: CreatedByValues.user, configuration: {}, }; export const emailAttribute: Attribute = { id: "email-attr", datatype: Datatypes.STRING, identifiers: { title: "Email", snake: "email", camel: "email", pascal: "Email", kebab: "email", }, internalNote: "the email of the user", locked: false, createdBy: CreatedByValues.user, addons: { required: true, }, }; export const movieSchema: SchemaInput = { id: "45678", identifiers: { singular: { title: "Movie", snake: "movie", camel: "movie", pascal: "Movie", kebab: "movie", }, plural: { title: "Movies", snake: "movies", camel: "movies", pascal: "Movies", kebab: "movies", }, }, internalNote: "", attributes: [ { id: "name-attr", datatype: Datatypes.STRING, identifiers: { title: "Name", snake: "name", camel: "name", pascal: "Name", kebab: "name", }, internalNote: "the name of the user", locked: false, createdBy: CreatedByValues.user, addons: { required: true, }, }, { ...emailAttribute, }, ], // relations: [ // { // id: "relation-example-01", // type: RelationType.belongsTo, // required: false, // destinationSchemaId: userSchema.id, // source: SchemaCreators.user, // sourceSchemaAlias: "Directed Movie", // destinationSchemaAlias: "Director", // }, // ], locked: false, removable: false, createdBy: CreatedByValues.user, configuration: {}, }; CreatedByValues; // // // // // // export const dummyPluginMetadata: PluginMetadata = { identifier: "chrome_extension_plugin", // unique ID for the plugin content: { label: "Chrome Extension plugin", // short label for the plugin description: "A Codotype plugin", // brief description of the plugin documentation: "A Codotype plugin", // Detailed description of the plugin icon: "https://res.cloudinary.com/codotype/image/upload/v1553197653/tech-logos/nodejs.png", // URL to the plugin's icon. Must be at least 200x200px }, homepage: "https://codotype.org", // the "homepage" for this plugin version: "0.1.0", // the current version of the plugin codotypeVersion: "0.1.0", createdBy: { name: "Codotype", contact: {}, }, techTags: ["React", "TypeScript", "Bootstrap"], // an array of strings describing the tech used in the plugin typeTags: ["Chrome Extension", "Infrastructure"], // describes the type of codebase produced by this plugin experience: ExperienceRecommendations.beginner, // an optional tag detailing the level of experience required to use the code produced by the plugin project_path: "output", // the name of the directory for the plugin's output exampleProjects: [], schemaEditorConfiguration: { configurationGroups: [], defaultSchemas: [], supportedDatatypes: [ Datatypes.STRING, Datatypes.TEXT, Datatypes.NUMBER, Datatypes.TIMESTAMP, ], // The datatypes supported by this plugin.Only an array of DATATYPE_ * identifiers that correspond to values defined in @codotype/core are accepted. supportedRelationTypes: [RelationTypes.TO_ONE, RelationTypes.TO_MANY], // The relation types supported by this plugin.Only an array of RELATION_TYPE_ * identifiers that correspond to values defined in @codotype/core are accepted. newSchemaDefaults: { attributes: [ { id: "UUID-Attribute", identifiers: { title: "ID", snake: "id", camel: "id", pascal: "Id", kebab: "id", }, addons: { [attributeAddons.primaryKey.property.identifier]: true, }, datatype: Datatypes.UUID, locked: true, createdBy: CreatedByValues.plugin, internalNote: "", }, ], relations: [], }, defaultRelations: [], attributeAddons: [], relationAddons: [], }, configurationGroups: [ { ...ComponentBuilderConfigurationGroup, identifier: "api_examples", content: { ...ComponentBuilderConfigurationGroup.content, label: "API Examples", }, properties: [ gitHubApiOption, twitterApiOption, facebookApiOption, foursquareApiOption, instagramApiOption, last_fmApiOption, linkedinApiOption, steamApiOption, stripeApiOption, paypalApiOption, twilioApiOption, tumblrApiOption, web_scrapingApiOption, clockwork_smsApiOption, aviaryApiOption, lobApiOption, pinterestApiOption, google_mapsApiOption, chartjsApiOption, ], }, { ...ComponentBuilderConfigurationGroup, identifier: "component_builder_side_by_side", content: { label: "Architecture Configuration", description: "Configure the server architecture of your application", documentation: syntaxHighlighting, icon: "", }, layoutVariant: GroupLayoutVariants.DOCS_6x6, properties: [twitterApiOption], }, ComponentBuilderConfigurationGroup, ], // an array of OptionGroup objects that expose additional configuration provided by the plugin };
the_stack
import { Component, createInstance } from './component'; import { createDomElement, updateDomProperties } from './dom-utils'; import { Effect, IdleDeadline, IdleRequestCallback, IFiber, ITag, IUpdate, IVNode } from './interface'; declare var requestIdleCallback: (fn: IdleRequestCallback) => number; // 毫秒,检测 deadline.timeRemaining() 是否有足够空余时间。 const ENOUGH_TIME = 1; // 追踪/缓存 pending updates,空闲时执行这些更新 const updateQueue: IUpdate[] = []; let nextUnitOfWork: IFiber | null | undefined = null; let pendingCommit: IFiber | null = null; /** * 把 virtual DOM tree(可以是数组)渲染到对应的容器 DOM * @param elements VNode elements to render * @param containerDom container dom element */ export function render(elements: any, containerDom: HTMLElement) { // 把 update 压入 updateQueue updateQueue.push({ from: ITag.HOST_ROOT, dom: containerDom, newProps: { children: elements }, }); requestIdleCallback(performWork); } /** * 安排更新,通常是由 setState 调用。 * @param instance 组件实例 * @param partialState state,通常是对象 */ export function scheduleUpdate(instance: Component, partialState: any) { // 把 update 压入 updateQueue updateQueue.push({ // scheduleUpdate 只被 setState 调用,所以来源一定是 CLASS_COMPONENT from: ITag.CLASS_COMPONENT, // 相应组件实例 instance, // setState 传来的参数 partialState, }); // 下次空闲时开始更新 requestIdleCallback(performWork); } /** * 执行渲染/更新工作 * @param {IdleDeadline} deadline requestIdleCallback 传来,用于检测空闲时间 */ function performWork(deadline: IdleDeadline) { workLoop(deadline); if (nextUnitOfWork || updateQueue.length > 0) { requestIdleCallback(performWork); } } /** * 核心功能,把更新工作分片处理(可打断);处理结束后进入提交阶段(不可打断)。 * * 1. 通过 deadline 去查看剩余可执行时间,时间不够时暂停处理; * 2. 把 wip fiber tree 的创建工作分片处理(可分片/暂停,因为没有操作DOM); * 3. 一旦 wip fiber tree 创建完毕,同步执行 DOM 更新。 * @param {IdleDeadline} deadline requestIdleCallback() 的参数 */ function workLoop(deadline: IdleDeadline) { // 如果 nextUnitOfWork 为空,则重新开始分片工作。 if (!nextUnitOfWork) { resetNextUnitOfWork(); } // 如果 nextUnitOfWork 非空,且剩余空闲时间足够,继续 reconcile // 实质上是在构造新的 work-in-progress fiber tree while (nextUnitOfWork && deadline.timeRemaining() > ENOUGH_TIME) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } if (pendingCommit) { commitAllWork(pendingCommit); } } /** * 重新开始分片工作 (next unit of work),设置reconciler的起点。 */ function resetNextUnitOfWork() { // 从 updateQueue 从取出最早的 update,如果没有,说明无更新要做,结束。 const update = updateQueue.shift(); if (!update) { return; } // 如果有 partialState (说明一定是 setState,一定是 Class Componnet) // 则把 partialState 存到对应的(old)fiber 上。 if (update.partialState) { ((update.instance as Component).__fiber as IFiber).partialState = update.partialState; } // 获取 root fiber // 1. 如果是 Tag.HOST_ROOT,说明是 React.render() ,直接拿 update.dom._rootContainerFiber; // 2. 否则是 Class Componnet,从 update.instance.__fiber 一路往上拿到 root fiber。 const root = update.from === ITag.HOST_ROOT ? (update.dom as any)._rootContainerFiber : getRoot((update.instance as Component).__fiber as IFiber); // nextUnitOfWork (reconciler的起点)被设置为一个 fiber, // 这个 fiber 是一个全新的 work-in-progress fiber tree 的 root nextUnitOfWork = { tag: ITag.HOST_ROOT, // 标记为 root // 1. 如果之前没有 old tree(即是 React.render),则设为传来的参数 DOM; // 2. 否则复用之前的 root.stateNode。 stateNode: update.dom || root.stateNode, // 1. 如果之前没有 old tree(即是 React.render),则props 是 newProps; // 2. 否则共享原来的 props。 // 如果使用 newProps,我们知道,children 是什么将无法保证。 props: update.newProps || root.props, // 对应的 old fiber tree(React.render 时为 null) alternate: root, }; } /** * 对当前 fiber 取 root (通过 fiber 的 parent 属性) * @param {IFiber} fiber fiber 对象 */ function getRoot(fiber: IFiber): IFiber { let node = fiber; while (node.parent) { node = node.parent; } return node; } /** * 迭代创建 work-in-progress fiber * @param wipFiber work-in-progress fiber */ function performUnitOfWork(wipFiber: IFiber) { // 为 wipFiber 创建 children fibers beginWork(wipFiber); // 如果有 children fibers,返回第一个 child 作为 nextUnitOfWork if (wipFiber.child) { return wipFiber.child; } // 没有 child,我们调用 completeWork 直到我们找到一个 sibling 作为 nextUnitOfWork。 // 如果没有 sibling 的话,向上找 parent。 let uow: IFiber | null | undefined = wipFiber; while (uow) { completeWork(uow); // 如果有 sibling,设置 sibling 作为 nextUnitOfWork,重新开始。 if (uow.sibling) { // Sibling needs to beginWork return uow.sibling; } // 否则,向上找到 parent (children已处理完毕)开始 completeWork。 uow = uow.parent; } } /** * 为 fiber 创建 children fibers * * 1. 创建 stateNode 如果 wipFiber 没有的话; * 2. 对 wipFiber 的 children 执行 reconcileChildrenArray。 * @param {IFiber} wipFiber 当前 work-in-progress fiber */ function beginWork(wipFiber: IFiber) { if (wipFiber.tag === ITag.CLASS_COMPONENT) { updateClassComponent(wipFiber); } else { updateHostComponent(wipFiber); } } /** * 处理 host component 和 root component(即都 host/原生 组件)。 * @param wipFiber 当前 work-in-progress fiber */ function updateHostComponent(wipFiber: IFiber) { // 如果没有 stateNode (比如 React.render),创建 stateNode。 // ⚠️不会为 child 创建 DOM,也不会把 DOM 添加到 document。 if (!wipFiber.stateNode) { wipFiber.stateNode = createDomElement(wipFiber) as Element; } // 从 wipFiber 的 props.children 获取 children 来创建 children fibers。 const newChildElements = wipFiber.props.children; reconcileChildrenArray(wipFiber, newChildElements); } /** * 处理 class component(即用户自定义的组件)。 * @param wipFiber 当前 work-in-progress fiber */ function updateClassComponent(wipFiber: IFiber) { let instance = wipFiber.stateNode as Component; // 如果 instance 不存在,调用 constructor 来创建实例。 if (instance == null) { instance = wipFiber.stateNode = createInstance(wipFiber); } // 否则,如果 props 没变,且不存在更新了 state,则不需要做更新。 // 复制上次的 children 即可。 else if (wipFiber.props === instance.props && !wipFiber.partialState) { cloneChildFibers(wipFiber); return; } // 更新 props,state,用于调用 render,获取虚拟 vnode tree。 instance.props = wipFiber.props; instance.state = Object.assign({}, instance.state, wipFiber.partialState); wipFiber.partialState = null; // 同样,我们得到了 child elements 来创建 children fibers; // ⚠️由于 reconcileChildrenArray 支持数组,所以现在 render 可以返回数组了! const newChildElements = instance.render(); reconcileChildrenArray(wipFiber, newChildElements); } function arrify(val: any) { return val == null ? [] : Array.isArray(val) ? val : [val]; } /** * 核心函数,逐步创建 work-in-progress tree,决定提交阶段 (commit phase)需要 * 做的 DOM 操作(怎么更新 DOM)。 * 这里主要是比较 alternate 的 children filbers 和 newChildElements (virtual nodes)。 * @param wipFiber work-in-progress fiber * @param newChildElements 要处理的 virtual dom tree(s),用于创建 children fibers。 */ function reconcileChildrenArray(wipFiber: IFiber, newChildElements: any) { // newChildElements 无法保证是数组,可能是单个 element,也可能是 null。 const elements = arrify(newChildElements) as IVNode[]; let index = 0; let oldFiber = wipFiber.alternate ? wipFiber.alternate.child : null; let newFiber: IFiber | null = null; while (index < elements.length || oldFiber != null) { // 记录 prevFiber (开始时是 null),用于后面更新 sibling 属性 const prevFiber = newFiber; const element = index < elements.length && elements[index]; const sameType = oldFiber && element && element.type === oldFiber.type; // 如果是相同类型(肯定已满足:element 和 oldFiber 都存在) // 说明只需要执行更新就好 if (sameType) { newFiber = { // 和 oldFiber 共享相同的 type/tag/stateNode type: (oldFiber as IFiber).type, tag: (oldFiber as IFiber).tag, stateNode: (oldFiber as IFiber).stateNode, // 设置 parent 和 alternate parent: wipFiber, alternate: oldFiber, // 设置 props 和 partialState props: (element as IVNode).props, partialState: (oldFiber as IFiber).partialState, // 设置为 UPDATE effectTag: Effect.UPDATE, }; } // 如果类型不同(可能是添加/删除/替换) else { // 如果 element 存在,则需要添加/替换为 element 代表的新 DOM if (element) { newFiber = { // 设置 type 和 tag,stateNode 为空,稍后处理 type: element.type, tag: typeof element.type === 'string' ? ITag.HOST_COMPONENT : ITag.CLASS_COMPONENT, props: element.props, parent: wipFiber, // 设置为 PLACEMENT effectTag: Effect.PLACEMENT, }; } // 如果有 oldFiber,则要删除 oldFiber 对应的 DOM,这里通过 parent fiber 记录删除操作 // ⚠️ 本质是因为 oldFiber 不在 wip fiber tree 内了,在 completeWork 时无法被 // 遍历到,只能先放到 parent fiber 的 effects 中。 if (oldFiber) { oldFiber.effectTag = Effect.DELETION; wipFiber.effects = wipFiber.effects || []; wipFiber.effects.push(oldFiber); } } // 更新 oldFiber 为 oldFiber 的 sibling,继续处理过程 if (oldFiber) { oldFiber = oldFiber.sibling; } // 如果 index 为 0,说明是处理的第一个 child fiber,则 // 需要设置父 fiber 的 child 属性 if (index === 0) { wipFiber.child = newFiber; } // 否则如果 elelment 存在,更新 prevFiber 的 sibling 属性 // 通过这两步操作,建立 wip fiber tree。 else if (prevFiber && element) { prevFiber.sibling = newFiber; } // 继续处理下一个 element index++; // 可以看到,reconciliation 过程中没有使用 key,所以不知道来 child 是否有被移动位置过。 } } /** * 直接复制对应 old fiber 的 children fibers 到 work-in-progress fiber * 由于我们确信没有更新,所以只需要复制就好。 * @param parentFiber work-in-progress fiber */ function cloneChildFibers(parentFiber: IFiber) { const oldFiber = parentFiber.alternate as IFiber; if (!oldFiber.child) { return; } let oldChild: IFiber | null | undefined = oldFiber.child; let prevChild: IFiber | null = null; // 通过 sibling 属性递归复制所有children fibers while (oldChild) { // 确保不共享 fiber,直接复制 old fiber的每个属性。 const newChild = { type: oldChild.type, tag: oldChild.tag, stateNode: oldChild.stateNode, props: oldChild.props, partialState: oldChild.partialState, alternate: oldChild, parent: parentFiber, }; if (prevChild) { prevChild.sibling = newChild; } else { parentFiber.child = newChild; } prevChild = newChild; oldChild = oldChild.sibling; } } /** * 设置 CLASS_COMPONENT fiber 的 __fiber,为 parent fiber 建立 effects。 * @param fiber 叶子fiber(没有children)或者子fiber已执行过 completework 的fiber */ function completeWork(fiber: IFiber) { // 此时 fiber 是叶子fiber(没有children)或者子fiber已执行过 completework 的fiber。 // 如果 fiber 对应的组件是 CLASS_COMPONENT,设置 __fiber,用于之后 // resetNextUnitOfWork 时找到 root fiber。 if (fiber.tag === ITag.CLASS_COMPONENT) { (fiber.stateNode as Component).__fiber = fiber; } // 如果 fiber 有 parent,则把 fiber 自身的 effects (以及子 fiber 的 effects) // 合并到 parent 的 effects。 // 这其实是在 root fiber 的 effects 中收集了所有 fiber (该 fiber 有 effectTag)。 if (fiber.parent) { const childEffects = fiber.effects || []; const thisEffect = fiber.effectTag != null ? [fiber] : []; const parentEffects = fiber.parent.effects || []; fiber.parent.effects = parentEffects.concat(childEffects, thisEffect); } // 没有 parent,说明已经处理到 root fiber,处理结束,开始 commit 阶段。 // 把 pendingCommit 设为 root fiber。 else { pendingCommit = fiber; } } /** * 遍历root fiber的 effects (通过 completeWork 已收集所有变更),执行更新。 * @param fiber root fiber */ function commitAllWork(fiber: IFiber) { (fiber.effects as IFiber[]).forEach((f) => { commitWork(f); }); // 在container DOM 上设置 _rootContainerFiber, // 用于之后resetNextUnitOfWork 时找到 root fiber。 (fiber.stateNode as any)._rootContainerFiber = fiber; // 重置 nextUnitOfWork 和 pendingCommit,等待下一次更新触发(setState/render)。 nextUnitOfWork = null; pendingCommit = null; } /** * 检查 fiber 的 effectTag 并做对应的更新。 * @param fiber 需要处理的 fiber */ function commitWork(fiber: IFiber) { // HOST_ROOT 无需处理 if (fiber.tag === ITag.HOST_ROOT) { return; } let domParentFiber: IFiber = fiber.parent as IFiber; // 对于 CLASS_COMPONENT 套 CLASS_COMPONENT 的情况,向上找到非 CLASS_COMPONENT // 的 fiber,从而取到对应的真正的 DOM while (domParentFiber.tag === ITag.CLASS_COMPONENT) { domParentFiber = domParentFiber.parent as IFiber; } const domParent = domParentFiber.stateNode as Element; // 如果是 PLACEMENT 且 fiber 对应 HOST_COMPONENT,添加 stateNode 到 domParent if (fiber.effectTag === Effect.PLACEMENT && fiber.tag === ITag.HOST_COMPONENT) { domParent.appendChild(fiber.stateNode as Element); } // 如果是 UPDATE,更新属性即可。 else if (fiber.effectTag === Effect.UPDATE) { updateDomProperties(fiber.stateNode as HTMLElement, (fiber.alternate as IFiber).props, fiber.props); } // 如果是 DELETION,删除即可。 else if (fiber.effectTag === Effect.DELETION) { commitDeletion(fiber, domParent); } } /** * 删除 fiber 对应的 DOM。 * @param fiber 要执行删除的目标 fiber * @param domParent fiber 所包含的 DOM 的 parent DOM */ function commitDeletion(fiber: IFiber, domParent: Element) { let node = fiber; while (true) { // 如果 node 是 CLASS_COMPONENT,则取其 child if (node.tag === ITag.CLASS_COMPONENT) { node = node.child as IFiber; continue; } // BEGIN: 删除 node 对应的 DOM元素(stateNode) domParent.removeChild(node.stateNode as Element); /// 在 BEGIN 和 END 之间: // node 不是 fiber 且 node 没有 sibling,则向上取 parent。 // 为什么有这种操作?可以看到前面在 node 是 CLASS_COMPONENT 时,我们向下取 child 了。 // 当我们删除了 child 之后,我们需要向上返回,并删除 node 的 sibling。 // 这种向上返回的过程结束于 2 种情况: // 1. node 有 sibling,则我们要 break 下来删除这个 sibling(后面从这个 sibling 向上返回); // 2. node 已经是 fiber,此时整个删除过程已经结束。 while (node !== fiber && !node.sibling) { node = node.parent as IFiber; } // 如果 node 是 fiber,结束删除过程。 // ⚠️(删除 fiber 的 sibling显然是错误的,我们要删除的是 fiber 对应的 DOM) if (node === fiber) { return; } // END: 取 node 的 sibling,并继续删除。 node = node.sibling as IFiber; } }
the_stack
import { LocalMicroEnvironmentManager } from '../../../extension/fabric/environments/LocalMicroEnvironmentManager'; import { TestUtil } from '../../TestUtil'; import { FabricEnvironmentConnection } from 'ibm-blockchain-platform-environment-v1'; import { FabricConnectionFactory } from '../../../extension/fabric/FabricConnectionFactory'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as vscode from 'vscode'; import { SettingConfigurations } from '../../../extension/configurations'; import { FabricEnvironmentRegistryEntry, FabricRuntimeUtil, FabricEnvironmentRegistry, FabricGatewayRegistry, EnvironmentType } from 'ibm-blockchain-platform-common'; import { EnvironmentFactory } from '../../../extension/fabric/environments/EnvironmentFactory'; import { LocalMicroEnvironment } from '../../../extension/fabric/environments/LocalMicroEnvironment'; import { UserInputUtil } from '../../../extension/commands/UserInputUtil'; chai.should(); // tslint:disable no-unused-expression describe('LocalMicroEnvironmentManager', () => { const connectionRegistry: FabricGatewayRegistry = FabricGatewayRegistry.instance(); const runtimeManager: LocalMicroEnvironmentManager = LocalMicroEnvironmentManager.instance(); let mockConnection: sinon.SinonStubbedInstance<FabricEnvironmentConnection>; let sandbox: sinon.SinonSandbox; let findFreePortStub: sinon.SinonStub; let backupRuntime: LocalMicroEnvironment; let originalRuntime: LocalMicroEnvironment; before(async () => { await TestUtil.setupTests(sandbox); backupRuntime = new LocalMicroEnvironment(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V2_0); }); beforeEach(async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); await FabricEnvironmentRegistry.instance().clear(); await TestUtil.setupLocalFabric(); originalRuntime = backupRuntime; sandbox = sinon.createSandbox(); await connectionRegistry.clear(); runtimeManager['connection'] = runtimeManager['connectingPromise'] = undefined; runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].set(FabricRuntimeUtil.LOCAL_FABRIC, originalRuntime); mockConnection = sandbox.createStubInstance(FabricEnvironmentConnection); sandbox.stub(FabricConnectionFactory, 'createFabricEnvironmentConnection').returns(mockConnection); findFreePortStub = sandbox.stub().resolves([8080, 8081, 8082]); sandbox.stub(LocalMicroEnvironmentManager, 'findFreePort').value(findFreePortStub); }); afterEach(async () => { sandbox.restore(); runtimeManager['connection'] = runtimeManager['connectingPromise'] = undefined; runtimeManager['runtimes'] = new Map(); await connectionRegistry.clear(); await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); }); describe('#getRuntime', () => { it('should return the runtime', () => { runtimeManager.getRuntime(FabricRuntimeUtil.LOCAL_FABRIC).should.deep.equal(originalRuntime); }); }); describe('#updateRuntime', () => { it('should return the runtime', async () => { runtimeManager['runtimes'].size.should.equal(1); const newEnv: LocalMicroEnvironment = new LocalMicroEnvironment(FabricRuntimeUtil.LOCAL_FABRIC, 9080, 1, UserInputUtil.V2_0); runtimeManager.updateRuntime(FabricRuntimeUtil.LOCAL_FABRIC, newEnv); runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC).should.deep.equal(newEnv); runtimeManager['runtimes'].size.should.equal(1); }); }); describe('#ensureRuntime', () => { it('should get runtime if it already exists', async () => { runtimeManager['runtimes'].size.should.equal(1); const runtime: LocalMicroEnvironment = await runtimeManager.ensureRuntime(FabricRuntimeUtil.LOCAL_FABRIC); runtime.should.deep.equal(originalRuntime); runtimeManager['runtimes'].size.should.equal(1); }); it(`should create and add runtime if it doesn't exist already`, async () => { runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); const runtime: LocalMicroEnvironment = await runtimeManager.ensureRuntime(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1); runtimeManager['runtimes'].size.should.equal(1); runtime['dockerName'].should.equal(originalRuntime['dockerName']); runtime['name'].should.equal(originalRuntime['name']); runtime['numberOfOrgs'].should.equal(originalRuntime['numberOfOrgs']); runtime['path'].should.equal(originalRuntime['path']); runtime['port'].should.equal(originalRuntime['port']); runtime['url'].should.equal(originalRuntime['url']); }); }); describe('#addRuntime', () => { beforeEach(async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); }); it(`should add runtime when ports and orgs are passed in`, async () => { runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); const runtime: LocalMicroEnvironment = await runtimeManager.addRuntime(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1); runtime['dockerName'].should.equal(originalRuntime['dockerName']); runtime['name'].should.equal(originalRuntime['name']); runtime['numberOfOrgs'].should.equal(originalRuntime['numberOfOrgs']); runtime['path'].should.equal(originalRuntime['path']); runtime['port'].should.equal(originalRuntime['port']); runtime['url'].should.equal(originalRuntime['url']); runtimeManager['runtimes'].size.should.equal(1); }); it(`should add runtime when orgs are passed in and ports exist in settings`, async () => { const settings: any = {}; settings[FabricRuntimeUtil.LOCAL_FABRIC] = 8080; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, settings, vscode.ConfigurationTarget.Global); runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); const runtime: LocalMicroEnvironment = await runtimeManager.addRuntime(FabricRuntimeUtil.LOCAL_FABRIC, undefined, 1); runtime['dockerName'].should.equal(originalRuntime['dockerName']); runtime['name'].should.equal(originalRuntime['name']); runtime['numberOfOrgs'].should.equal(originalRuntime['numberOfOrgs']); runtime['path'].should.equal(originalRuntime['path']); runtime['port'].should.equal(originalRuntime['port']); runtime['url'].should.equal(originalRuntime['url']); runtimeManager['runtimes'].size.should.equal(1); }); it(`should add runtime when orgs are passed in and ports don't exist in settings`, async () => { const settings: any = {}; // settings[FabricRuntimeUtil.LOCAL_FABRIC] = undefined; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, settings, vscode.ConfigurationTarget.Global); runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); const runtime: LocalMicroEnvironment = await runtimeManager.addRuntime(FabricRuntimeUtil.LOCAL_FABRIC, undefined, 1); runtime['dockerName'].should.equal(originalRuntime['dockerName']); runtime['name'].should.equal(originalRuntime['name']); runtime['numberOfOrgs'].should.equal(originalRuntime['numberOfOrgs']); runtime['path'].should.equal(originalRuntime['path']); runtime['port'].should.equal(originalRuntime['port']); runtime['url'].should.equal(originalRuntime['url']); runtimeManager['runtimes'].size.should.equal(1); }); it(`should add runtime when ports are passed in but orgs aren't`, async () => { runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); const runtime: LocalMicroEnvironment = await runtimeManager.addRuntime(FabricRuntimeUtil.LOCAL_FABRIC, 8080); runtime['dockerName'].should.equal(originalRuntime['dockerName']); runtime['name'].should.equal(originalRuntime['name']); runtime['numberOfOrgs'].should.equal(originalRuntime['numberOfOrgs']); runtime['path'].should.equal(originalRuntime['path']); runtime['port'].should.equal(originalRuntime['port']); runtime['url'].should.equal(originalRuntime['url']); runtimeManager['runtimes'].size.should.equal(1); }); it(`should throw an error when runtime with ports are passed in but orgs aren't, and environment doesn't exist`, async () => { runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); await FabricEnvironmentRegistry.instance().clear(); try { await runtimeManager.addRuntime(FabricRuntimeUtil.LOCAL_FABRIC, 8080); } catch (error) { error.message.should.deep.equal(`Unable to add runtime as environment '${FabricRuntimeUtil.LOCAL_FABRIC}' does not exist.`); } runtimeManager['runtimes'].size.should.equal(0); }); it(`should throw an error when runtime with ports are passed in but orgs aren't, and environment doesn't have 'numberOfOrgs' property`, async () => { runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); await FabricEnvironmentRegistry.instance().clear(); await FabricEnvironmentRegistry.instance().add({name: FabricRuntimeUtil.LOCAL_FABRIC, environmentType: EnvironmentType.LOCAL_ENVIRONMENT, managedRuntime: true}); try { await runtimeManager.addRuntime(FabricRuntimeUtil.LOCAL_FABRIC, 8080); } catch (error) { error.message.should.deep.equal(`Unable to add runtime as environment '${FabricRuntimeUtil.LOCAL_FABRIC}' does not have 'numberOfOrgs' property.`); } runtimeManager['runtimes'].size.should.equal(0); }); }); describe('#removeRuntime', () => { it('should remove runtime from manager if it exists', async () => { runtimeManager['runtimes'].size.should.equal(1); runtimeManager.removeRuntime(FabricRuntimeUtil.LOCAL_FABRIC); runtimeManager['runtimes'].size.should.equal(0); }); it(`should not do anything (or error) if the runtime doesn't exist to delete`, async () => { runtimeManager['runtimes'] = new Map(); runtimeManager['runtimes'].size.should.equal(0); ((): void => { runtimeManager.removeRuntime(FabricRuntimeUtil.LOCAL_FABRIC); }).should.not.throw; runtimeManager['runtimes'].size.should.equal(0); }); }); describe('#initialize', () => { let isCreatedStub: sinon.SinonStub; let updateUserSettingsStub: sinon.SinonStub; let createStub: sinon.SinonStub; let teardownStub: sinon.SinonStub; let addRuntimeSpy: sinon.SinonSpy; beforeEach(async () => { const registryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); const getEnvironmentStub: sinon.SinonStub = sandbox.stub(EnvironmentFactory, 'getEnvironment'); getEnvironmentStub.callThrough(); getEnvironmentStub.withArgs(registryEntry).returns(originalRuntime); isCreatedStub = sandbox.stub(LocalMicroEnvironment.prototype, 'isCreated').resolves(true); updateUserSettingsStub = sandbox.stub(LocalMicroEnvironment.prototype, 'updateUserSettings').resolves(); // these need to be on the runtime we retrieve createStub = sandbox.stub(LocalMicroEnvironment.prototype, 'create').resolves(); teardownStub = sandbox.stub(LocalMicroEnvironment.prototype, 'teardown').resolves(); addRuntimeSpy = sandbox.spy(LocalMicroEnvironmentManager.prototype, 'addRuntime'); }); it('should use existing configuration and import all wallets/identities', async () => { sandbox.stub(LocalMicroEnvironmentManager.instance(), 'ensureRuntime').returns(originalRuntime); await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, { '1 Org Local Fabric': 8080 }, vscode.ConfigurationTarget.Global); await runtimeManager.initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1); const runtime: LocalMicroEnvironment = runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC); runtime.port.should.equal(8080); addRuntimeSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V2_0); updateUserSettingsStub.should.not.have.been.called; }); it('should generate new configuration', async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); findFreePortStub.resolves([8080, 8081]); await runtimeManager.initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1); const runtime: LocalMicroEnvironment = runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC); runtime.port.should.equal(8080); addRuntimeSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V2_0); updateUserSettingsStub.should.have.been.calledOnce; }); it('should be able to initalize a V1 capability network', async () => { await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); findFreePortStub.resolves([8080, 8081]); await runtimeManager.initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1, UserInputUtil.V1_4_2); const runtime: LocalMicroEnvironment = runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC); runtime.port.should.equal(8080); addRuntimeSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V1_4_2); updateUserSettingsStub.should.have.been.calledOnce; }); it('create the runtime if it is not already created', async () => { isCreatedStub.resolves(false); await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); findFreePortStub.resolves([8080, 8081]); await runtimeManager.initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1); const runtime: LocalMicroEnvironment = runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC); runtime.port.should.equal(8080); updateUserSettingsStub.should.have.been.calledOnce; addRuntimeSpy.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, 8080, 1, UserInputUtil.V2_0); createStub.should.have.been.calledOnce; }); it('create the runtime on ports not already used in the settings', async () => { isCreatedStub.resolves(false); const runtimes: any = { localRuntime1: 8080, localRuntime2: 8081, localRuntime3: 8082 }; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, runtimes, vscode.ConfigurationTarget.Global); findFreePortStub.resolves([8083, 8084]); await runtimeManager.initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1); findFreePortStub.should.have.been.calledOnceWithExactly(8083, null, null, 20); const runtime: LocalMicroEnvironment = runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC); runtime.port.should.equal(8083); updateUserSettingsStub.should.have.been.calledOnce; createStub.should.have.been.calledOnce; }); it('should teardown if entry url is out of date', async () => { isCreatedStub.resolves(true); await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global); findFreePortStub.resolves([8080, 8081]); const getEnvironmentEntryStub: sinon.SinonStub = sandbox.stub(FabricEnvironmentRegistry.instance(), 'get'); getEnvironmentEntryStub.callThrough(); getEnvironmentEntryStub.withArgs(FabricRuntimeUtil.LOCAL_FABRIC).resolves({ url: 'http://localhost:9000' }); await runtimeManager.initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1); const runtime: LocalMicroEnvironment = runtimeManager['runtimes'].get(FabricRuntimeUtil.LOCAL_FABRIC); runtime.port.should.equal(8080); updateUserSettingsStub.should.have.been.calledOnce; createStub.should.not.have.been.called; teardownStub.should.have.been.calledOnce; }); }); });
the_stack
/// <reference types="jquery" /> import IGetListRequest from "./interfaces/IGetListRequest"; import ISavePageWidgetRequest from "./interfaces/ISavePageWidgetRequest"; declare namespace Akumina { class BaseWidget { constructor(); Properties: any; GetPropertyValue(requestIn: any, key: string, defaultValue: any): any; RefreshWidget(newProps: any): void; BindTemplate(templateUri: string, data: any, targetDiv: string): void; } class Expression { And(expression: any): Expression; Or(expression: any): Expression; EqualTo(expression: any): Expression; In(expression: any): Expression; NotEqualTo(expression: any): Expression; GreaterThan(expression: any): Expression; GreaterThanOrEqualTo(expression: any): Expression; LessThan(expression: any): Expression; LessThanOrEqualTo(expression: any): Expression; Contains(expression: any): Expression; } class PropertyExpression extends Expression { constructor(param?: any); } // class OrExpression extends Expression { } // class EqualExpression extends Expression { } // class InExpression extends Expression { } // class NotEqualExpression extends Expression { } // class GreaterThanExpression extends Expression { } // class GreaterThanOrEqualExpression extends Expression { } // class LessThanExpression extends Expression { } // class LessThanOrEqualExpression extends Expression { } // class ContainsExpression extends Expression { } class SortDirection { static Descending: string; } namespace AppParts { class Banner { constructor(options: any); } class Traffic { constructor(options: any); } class Calendar { constructor(options: any); } class CompanyCalendar { constructor(options: any); } } namespace Digispace { class ConfigurationContext { /** HTML template for Loading */ static LoadingTemplateHtml: string; /** Template Folder name */ static TemplateFolderName: string; /** Is Site multilingual */ static IsMultiLingualEnabled: boolean; /** Loing URL for login to interchange */ static InterchangeLoginURL: string; /** URL to Interchange */ static InterchangeURL: string; static InterchangeQueryKey: string; /** All confguratoin constants */ static CONSTANTS: IConstants; /** Is user loggied into app manager */ static IsAppManagerLoggedIn: boolean; /* Added */ /** Is site using AzureAD ID */ static EnableAzureAD: boolean; /* Added */ /** All personas */ static Personas: any[]; /** All container layouts objects */ static ContainerLayouts: any[]; /** All premade page layout objects */ static PageLayouts: any[]; /** settings object */ static Settings: any; static TemplateCoreFolderName: string; static GraphClientId: string; static GraphSubscriptionId: string; /** JSON string */ static SiteLogoObj: string; static SiteImageObj: string; /** Caching strategy time */ static CachingStrategyInterval: number; /** Associative Array of objects */ static DepartmentSiteMap: any[]; static GoogleMapKey: string; static ApplicationInsightsKey: string; static SkypeApiKey: string; static SkypeApiKeyCC: string; static TenantUrl: string; /** Is in Debug mode */ static EnableDebugMode: boolean; /** Current Theme */ static Theme: string; /** Pages to be excluded in search */ static SearchPageExclusionList: string[]; /** Language neutral Listsname */ static LanguageNeutralLists: any; /** SP Lists with persona enabled */ static PersonaEnabledLists: any; static TemplateURLPrefix: string; /** Site URL */ static ConfigurationSiteUrl: string; /** Widget Instance URL */ static WidgetInstanceSiteUrl: string; /** Dashboard Instance Site URL */ static DashboardInstanceSiteUrl: string; static RemoteListSiteUrl: string; static GraphRedirectUrl: string; static DefaultLanguage: string; static SiteVisibleLanguages: any; static GroupTagsExtension: any; static GroupTypeExtension: any; /** Is workspace is enabled or not */ static IsWorkspacesEnabled: boolean; static NotFoundPage: string; static IsNotFoundPage: boolean; static AkTokenDuration: number; /** Time to wait for script loading */ static ScriptTimeout: number; static InstanceRowLimit: number; /** * #MARK - It is comming as Undefined */ static ErrorRedirectUrl: string; static PageWidgetDefaultSize: string; static DashboardWidgetDefaultSize: string; static DashboardGridWidth: string; static DashboardGridHeight: string; static DashboardZoneIds: string; static DashboardEnableEditMode: boolean; static DashboardView: string[]; static WorkspaceThemesAvailable: string[]; /** Internal widget dependency map */ static InternalWidgetDependencyMap: any[]; static WidgetDependencyMap: any[]; /** Currently Active languages {LanguageID, ID, FallBack, Name, Code, etc...} */ static ActiveLanguages: any[]; static EnableReusableContent: boolean; static ReusableContentList: string; static PageBuilderDefaultLayoutId: number; /** Instance Ids for widgets */ static InternalWidgetInstanceIds: any; static AppManagerLoggedInTime: any; static UseEncryption: boolean; static PersonaSelectionMode: string; static PageRouteInfo: any; /** Contains Array of pageTypes object */ static PageTypes: any[]; /** * @param isLoggedIn * @param loggedInTime */ static setAppManagerLogin(isLoggedIn: boolean, loggedInTime: any): void; /** * Set configuration from digispace object passed. * @param digispaceConfiguration */ static setDigispaceConfiguration(digispaceConfiguration: any): void; static PopulateTemplateURLPrefix(): void; /** * Load Active Languages * @param activeLanguages */ static LoadActiveLanguages(activeLanguages: any): void; static clearCache(): void; /** * GetCacheKey * @param attribute */ static getCacheKey(attribute: string): string; /** * Get Language Neutral cache key * @param key */ static getCacheKeyLanguageNeutral(key: string): string; /** * Returns currect caching strategy * @param cachingStrategy */ static ResolveCachingStrategy(cachingStrategy: any): number; /** * Map department objects to associative array * @param sitedepartments * @returns Associative array. */ static MapDepartmentSites(sitedepartments: any): any[]; static loadDigispaceConfiguration(): JQueryDeferred<any>; static GetAdditionalLoaderConfigurations(): void; /** * Set default language * @param defaultLanguage */ static SetDefaultLanguage(defaultLanguage: any): void; static GetDefaultLanguage(): any; /** * Set Site visible Languages. * @param languages */ static SetSiteVisibleLanguages(languages: any): any; /** * Get site visible languages * @param languages */ static GetSiteVisibleLanguages(languages: any): any; } class UserContext { static LanguageCode: string; static LanguageId: number; static FallbackLanguageId: number; static SetLanguage(obj: any): void; static UserId: string; static City: string; static State: string; static PostalCode: string; static Department: string; static UserLoginName: string; static LoginName: string; } class SiteContext { static IsLoaderComplete: boolean; /** Check if current page is a workspace page */ static IsWorkspacePage: boolean; /** WorkspaceDetails page absolute URL */ static WorkspaceDetailsUrl: string; /** Check if current page is a VPC */ static IsVirtualPage: boolean; static IsSPAPage: boolean; /** * Check if in design mode. */ static IsInDesignMode(): string; static FrameworkLoadTime: number; static TotalLoadTime: number; static TotalConnectTime: number; static TotalRenderTime: number; /** SiteID with {} */ static SiteId: string; /** Root Site URL */ static SiteAbsoluteUrl: string; /** Relative URL for root site */ static SiteServerRelativeUrl: string; /** Current Site relative URL */ static WebServerRelativeUrl: string; /** Current site Absolute URL */ static WebAbsoluteUrl: string; /** Check if Current user is site Admin */ static IsSiteAdmin: boolean; /** Stores current language ID */ static CurrentLanguage: number; static ListPermissionsMask: any; /** Relative URL to current page */ static ServerRequestPath: string; static IsLogoutPage: boolean; static IsDashBoardPage: boolean; static IsSandboxPage: boolean; static IsPageBuilderPage: boolean; /** Relative URL to Employee Details page */ static EmployeeDetailUrl: string; /** Absolute URL to Workspace page */ static WorkspaceListingUrl: string; /** Web ID (Root Site ID) */ static WebId: string; static IsExternalUser: boolean; /** check if page not found */ static PageNotFound: boolean; static UniqueId: string; /** #MARK - it is not used as of now */ static IsWidgetJSLoaded: boolean; /** #MARK - not used as of now. */ static LoadedWidgets: any[]; static RootSiteId: string; static RootSiteUrl: string; static IsHeadlessMode: boolean; /** @return Resolves with Language ID */ static GetSiteLocaleId(): JQueryDeferred<any>; static IsModernPage: boolean; /** Lists queired till now */ static QueriedLists: string[]; /** Lists of template views in use */ static ViewsInUse: string[]; } class PageContext { static EditMode: boolean; static PageId: string; static MapPageUrl(pageUrl: string): string; static PageRouteInfo: { email: string }; } class Utilities { /** * Shows confirmation popup if all permissions are set as NA * It is called from add page tab and page properties update * @param isPagePropertisPopUp true if called from page properties. */ static AllPermissionsNA(isPagePropertisPopUp: boolean | null): void; /** * Called to show confirmation pop up while exiting edit page mode. */ static AttemptReset(): void; /** * Check if iser is logged into appmanager and set the flag accordingly */ static CheckAppManagerIsLoggedIn(): void; /** Takes string or any value as input & can return it as boolean or JSON * @param value Any value * @param dataType Required retrun type "bool", "boolean", "json" */ static ConvertValue(value: any, dataType: string): boolean | JSON; /** * Removes duplicate entries from an array * @param array Array to be filter */ static DeDupArray(array: any): any; /** * @param result * @param isCurrent * @returns Returns value of key ListID or SiteTitle(in case of isCurrent true) */ static FindSearchResultCategory(result: any[], isCurrent: boolean): string; /** Convert date string to jsformat date string * Acceptable formats "mm/dd/yy", "dd/mm/yy", "dd-mm-yy", "mm/dd/yyyy", "dd/mm/yyyy", "dd-mm-yyyy" * @param format * @param date * @returns Converted date string in format "dd/mm/yy" or "mm/dd/yyyy" */ static FormatDateStringToJSFormat(format: string, date: string): string; /** Returns an object with pageId property */ static GetCurrentPageId(): any; static GetDashboardGridByInstance(instanceId: string): string[]; /**Returns a deffered which will resolve with site specific date format object * @returns deffered resolved with object type: { "dateformat": "mm/dd/yy", "momentformat": "MM/DD/YY", "displayformat": "MM/DD/YYYY", "languagecode": "en-US" } */ static GetDateFormatForSiteLocaleId(): JQueryDeferred<any>; /* Added */ /** * Resolves with Employee Detail Url * @param id UserId */ static GetEmployeeDetailUrl(id: string): JQueryDeferred<any>; /** * Get new GUID */ static GetGuid(): string; static GetLinkForResult(itemUrl: string): string; static GetLinkParameter(itemUrl: string, paramToRetrieve: string, defaultValue: string): string; /** * relative path for manager script */ static GetManagerUrl(): string; /** * Returns Page Grid for workspace widget Instancce Id's * @param instanceId Widget Instance ID */ static GetPageGridByInstance(instanceId: string): string[]; static GetPropertyValue(requestIn: any, key: string, defaultValue: string, dataType: string): boolean | JSON; /** Retrive search parameter value from results */ static GetSearchParameter(itemResults: any[], paramToRetrieve: string, defaultValue: string): string; /** * @returns element of sharepoint bar */ static GetSharepointBarElement(): any; /** * @returns object with URL parameters */ static GetUrlParameters(): any; static HandleSharepointBar(args: any): void; /** * Hide sharepoint bar * @param setCookie boolean */ static HideSharepointBar(setCookie: boolean): void; static IsAppManagerLaguageCompatible(): JQueryDeferred<any>; /** Convert object keys to lowercase * @param data JSON String of Array of objects * @returns Array of JSON objects with all keys in lowercase */ static JsonArrayKeyToLower(data: string): any[]; /** * Open interchange in new tab */ static OpenInterchange(): void; static PageBindCloseWidgets(args: any, grid: any): void; static PageResizeWidgets(args: any): void; /** * Open link in new window/tab. * @param link Link to open */ static PopUpLink(link: string): void; /** This method will show confirmation pop-up if user try to exit page edit mode */ static PromptExitEditMode(): void; /** Register timer to check if user is logged into appmanager every minute */ static RegisterAppManagerLoggedInCheckHandler(): void; /** * To show message in alert box * @param message Message text to show * @param options Custome options {width} * @param actioncallback Method to be called when user click ok */ static ShowAlertPopup(message: string, options: any, actioncallback?: any): void; /** * Show sharepoint bar * @param setCookie boolean */ static ShowSharepointBar(setCookie: boolean): void; /** * Toggle Debugger panel */ static ToggleDebugger(): void; static ToggleExistPageBuilderManager(): void; /** Toggle Impersonator mode */ static ToggleImpersonator(): void; /** Toggle Widget properties edit mode */ static ToggleItemManager(): void; /** Toggle live preview mode */ static ToggleLiveMode(): void; /** Toggle page builder (Add new page) */ static TogglePageBuilderManager(): void; /** Toggle page edit mode */ static TogglePageManager(): void; /** Toggle widget edit mode */ static ToggleWidgetManager(): void; } class Language { static TryGetText(Token: string): string; /* Added */ static GetText(Token: string): string; /* Added */ } class WorkspaceContext { static groupId: boolean; static IsCurrentGraphUserWorkspaceOwner: boolean; } class PageBuilderManager { GetDataForAddWidget(): JQueryDeferred<any>; } class ScriptManager { GetManagerScript(callback: () => void): JQueryDeferred<any>; GetWidgetLegacyScript(callback: () => void): JQueryDeferred<any>; GetLanguageMappingsScript(callback: () => void): JQueryDeferred<any>; GetBabelScript(callback: () => void): JQueryDeferred<any>; LoadPageBuilderCSS(): JQueryDeferred<any>; } class PerfLogger { /** Add LoaderMark and mark it start * @param mark String Name of mark to be added as Start * @param type String */ static AddLoaderStartMark(mark: string, type: string): void; /** Mark Stop of a LoaderMark * @param mark String Name of mark to be marked as Stop */ static AddLoaderStopMark(mark: string): void; /** To add a new mark * @param mark String name of mark */ static AddMark(mark: string): void; /** Get a mark object by mark name * @param mark string name of mark * @returns object of mark {name: "string", startTime: decimal} */ static GetMark(mark: string): any; /** Get List of marks added * @returns Array of mark objects [{name: "string", startTime: decimal}] */ static GetMarks(): any[]; /** Get list of all Loader Marks * @returns Array of Loader marks object */ static GetLoaderMarks(): any[]; /** Measure Performance between two marks * @param mark1 Name of mark to compare * @param mark2 Name of mark to compare * @returns PerformanceMeasure Object */ static CompareMarks(mark1: string, mark2: string): any; /** Gets color from time * @param time time in ms * @param type short,medium,long * @returns yellow green or red */ static GetColor(time: number, type: string): string; } class WidgetPropertyViews { static AddViewForProperty(widgetName: string, propName: string, value: string): void; } namespace AppPart { class Eventing { constructor(); static Subscribe(e: string, func: any, caller?: any): void; /* Updated */ static Publish(t: string, data?: any): void; /* Updated */ } class Data { Templates: Templates; } } namespace WidgetManager { class Menu { constructor(p: any); Open(parent: any): any; } } namespace Utilities { /* Added */ class DateTimeManager { static LocalToUtc(data: any): Date; static UtcToLocal(Date: Date, format: string): string; } } namespace Data { class LanguageManager { GetDefaultLanguage(): any; } class WidgetManager { InitializeChildWidgetsWithOverride(widgetIds: string[], pageId: string, widgetProps: any[], view: string): any; // RenderWidget(data: any, pageId: string, widgetProps: string, view: string): any; /* Added in Alphabatical order */ /** Check if widgetinstances are Dashboard Container widgets */ AreDashboardContainerWidgets(widgetInstanceIds: any[]): JQueryDeferred<any>; /** Add dashboard widget instance */ AddDashboardWidgetInstance(dashboardWidgetTitle: string, widgetInstance: any): JQueryDeferred<any>; /** Copy Widget Instance */ CopyWidgetInstance(widgetInstanceId: string): JQueryDeferred<any>; GetManualDependencyMap(widgetName: string): any[]; /** Resolves with next AkId */ GetNextAkId(): JQueryDeferred<any>; /** Resolves with siteId */ GetSiteId(): JQueryDeferred<any>; /** * @returns Resolves with Array with object of all the widget Instances */ GetWidgetInstances(): JQueryDeferred<any>; /** * @returns def Resolves in success with Object with authorized user groups */ GetWidgetManagerAppAuthorization(): JQueryDeferred<any>; /** * @returns def Resolves in success with Widget Manager Instance ID */ GetWidgetManagerApp(): JQueryDeferred<any>; /** * @param widgetType WidgetType * @returns def Resolves in success with array of objects of widget view of widgetType passed */ GetWidgetViews(widgetType: string): JQueryDeferred<any>; /** * #MARK - dataType correction * @param widgetInstanceIds Array of widget Instance Ids */ GetWidgetPropertiesForInstances(widgetInstanceIds: string[] | null): JQueryDeferred<any>; /** * Get js file list for dependent widgets * @param widgetName * @param widgetToDeps * @param depJsFiles */ GetWidgetJSArrayFromWidget(widgetName: string, widgetToDeps: any[], depJsFiles: any[]): any[]; GetWidgetJSFromDependency(widgets: any[]): JQueryDeferred<any>; /** * Retrives all the widget instances ID on the current page. * @returns object with ids: string[] & rel: Array<> */ GetWidgetInstancesOnPage(): any; /** * Get list of widget on current page. * @param widgets */ GetWidgetObjsOnPage(widgets: any[]): any[]; /** Initialize widget passed */ InitWidget(item: any): void; /** Initialize widgets passed in array */ InitializeWidgets(widgets: any[]): JQueryDeferred<any>; GetAndInitWidgetsPerJSFile(item: any, widgetDepJsArray: any[]): void; PopulateAutoDependencyMap(widgetsWithPropsArray: any[], widgetArray: any[]): any[]; /** * Render Child Widgets * @param selector * @param pageId * @param mode */ RenderChildWidgets(selector: string, pageId: string | null, mode: string): void; } class DataFactory { constructor(legacyMode?: boolean); /** * #MARK - Not currently used. * @param implementation */ SetImpl(implementation: string): void; /** * Get list from SharePoint * @param request */ GetList(request: IGetListRequest): Promise<any>; /** * Get widgets for page * @param pageId * @param legacy */ GetWidgetsForPage(pageId: string, legacy?: boolean): JQueryDeferred<any>; /** * Get saved layout from Sharepoint * @param layoutName Layout Name */ GetSavedLayout(layoutName: string): JQueryDeferred<any>; /** * Save custom layout * @param layoutObject JSON object having layout details */ ProvisionSavedLayout(layoutObject: any): JQueryDeferred<any>; /** * Returns List of permissions for current user for passed list * @param listName Name of list * @param useRootWeb Boolean flag */ CanUserSetItemPermissions(listName: string, useRootWeb: boolean): JQueryDeferred<any>; /** * Get matching pages from Page Url List * @param searchText Text to search existing pages */ GetPagesFromPageUrlList(searchText: string): JQueryDeferred<any>; /** * Get permissions set for list item * @param listName Name of list * @param itemId List Item id */ GetPermissionForListItem(listName: string, itemId: string): JQueryDeferred<any>; /** * Set personas for list item * @param listName ListName of which item belongs * @param itemId ID of item to set persona. * @param personaList Semicolon seprated List of persona to set for item * @param columnName column Name for persona */ SetPersonasForItem(listName: string, itemId: number, personaList: any, columnName?: string): JQueryDeferred<any>; /** * Set Tags for list item * @param listName List Name * @param itemId Item Id * @param columnName Coloumn Name for tags * @param tagList semicolon seprated list of tags */ SetTagsForItem(listName: string, itemId: string, columnName: string, tagList: any): JQueryDeferred<any>; /** * Set permissions for list item * @param listName * @param itemId * @param editgroup Array User groups for edit permission * @param readgroup Array User groups for read permission * @param useRootWeb */ SetPermissionsForListItem(listName: string, itemId: string, editgroup: any, readgroup: any, useRootWeb: boolean): JQueryDeferred<any>; /** * Get All lists from the site. By default it fetechs from root site * @param useRoot */ GetAllList(useRoot: boolean | undefined): JQueryDeferred<any>; /** Get List position */ GetListPosition(): JQueryDeferred<any>; /** * Search in sharepoint list based on request * @param request */ Search(request: any): JQueryDeferred<any>; /** * Get Site Properties * @param request */ GetSiteProperties(request: any): JQueryDeferred<any>; /** * Update page object Items * @param pageObject */ UpdatePageObjectsItem(pageTypeList: string, pageObject: any, pageId: string): JQueryDeferred<any>; /** * Add new page to list * @param pageObject JSON object with properties for page */ ProvisionPageObject(pageObject: any): JQueryDeferred<any>; /** * Add/Save new widgets to page * @param widgetName * @param pageId * @param pageWidgets */ ProvisionPageWidgets(widgetName: string, pageId: string, pageWidgets: any[]): JQueryDeferred<any>; UpdatePageUrlsItem(pageObject: any, pageId: string, pageTypeList?: string): JQueryDeferred<any>; LoadTermSet(termSetName?: string | null, columnName?: string | null, columnValue?: string | null): JQueryDeferred<any>; LoadTermSetByColumnName(request: IGetListRequest, columnName: string, columnValue?: string | null): JQueryDeferred<any>; /** * Create new list * @param siteUrl * @param siteTitle * @param templateType * @param fieldsList */ CreateList(siteUrl: string, siteTitle: string, templateType: string, fieldsList: any[]): JQueryDeferred<any>; GetItemsFromListByTitle(listName: string, searchTerm: string, isroot: boolean): JQueryDeferred<any>; /** * Get all user groups for site * @param searchUniqueValue * @param currentPage * @param pageLimit */ GetGroupsForSite(searchUniqueValue: any, currentPage: number, pageLimit: number): any; /** * Check user permission on list item * @param pageTypeList listName to which item belongs * @param pageId */ UserPermissionsForListItem(pageTypeList: string, pageId: string): JQueryDeferred<any>; /** * Check if user have edit permission on list item. * @param pageReferenceList * @param pageId * @returns Resolves with {ReadPermission: bool, EditPermission: bool} */ // tslint:disable-next-line unified-signatures UserPermissionsForListItem(pageReferenceList: any, pageId: string): JQueryDeferred<any>; /** *Updates list item * @param listName listName to which item belongs * @param itemid * @param queryParams data that needs to updated as an object */ UpdateListItem(listName: string, itemid: string, queryParams: any): JQueryDeferred<any>; /** *Delete list item * @param listName listName to which item belongs * @param itemid */ DeleteListItem(listName: string, itemid: string): JQueryDeferred<any>; /** *Get Permissin on list for current user * @param listName listName to fetch permission of */ GetListEffectiveBasePermissions(listName: string): JQueryDeferred<{}>; } class RestSharepoint {} class SharePoint { /* Added */ LoadTermSet(termSetName: string, columnName: string | null, columnValue: string | null): JQueryDeferred<any>; LoadTermSetById(termSetId: string, columnName: string, columnValue?: string | null): JQueryDeferred<any>; /** * Update Page object item * @param pageTypeList List Name * @param pageObject Page object to be updated * @param pageId Item Id of page list item */ UpdatePageObjectsItem(pageTypeList: string, pageObject: any, pageId: string): JQueryDeferred<any>; /** * @param pageObject * @param pageId * @param pageTypeList */ UpdatePageUrlsItem(pageObject: any, pageId: string, pageTypeList?: string): JQueryDeferred<any>; /** * Create new list item * @param createItemRequest */ CreateItem(createItemRequest: any): JQueryDeferred<any>; /** * Create new list * @param siteUrl * @param siteTitle * @param templateType * @param fieldsList */ CreateList(siteUrl: string, siteTitle: string, templateType: string, fieldsList: any[]): JQueryDeferred<any>; GetAppInstances(successCallback: any, errorCallback: any): void; /** * Get SiteID of current site */ GetCurrentSiteId(): JQueryDeferred<any>; GetList(request: any): JQueryDeferred<any>; /** * @param siteUrl Absolute path */ GetSiteIdByUrl(siteUrl: string, useRootWeb: boolean): JQueryDeferred<any>; /** * Get all SP user groups * @returns Resolves with array of {id, displayName, type, description} */ GetSiteSPGroups(): JQueryDeferred<any>; /** * Get list of users under user groups * @param authorizationGroups List of authorization Groups */ GetSPGroupUsersByGroupName(authorizationGroups: any[]): JQueryDeferred<any>; /** * Get User Groups current user belongs to */ GetSPUserGroups(): JQueryDeferred<any>; // LoadTermSet(termSetName: string, columnName: string, columnValue: string): JQueryDeferred<any>; } class PersonaManager { /** Does List reuire persona check * @param listName */ IsPersonaCheckRequiredForList(listName: string): JQueryDeferred<any>; /** Get array of Lists with persona enabled */ GetPersonaEnabledLists(): string[]; /** * Returns object setting filterByPersona property. Or default object * @param request */ IsPersonaFilteringOn(request?: any): any; } class Interchange { /** * Get Configuration object */ GetConfiguration(): any; /** * Get Users Data List * @param currentUserName * @param filters * @param pageSize * @param pageNumber * @param orderByField * @param sortDirection */ GetUsersData(currentUserName: string, filters: any, pageSize: number, pageNumber: number, orderByField: string, sortDirection: string): any; GetMenuApps(): any; /* Added */ // CanUserSetItemPermissions(referenceList: string): JQueryDeferred<any>; // GetPermissionForListItem(referenceList: string, itemId: string): JQueryDeferred<any>; AppPart(referenceList: string, itemId: string): any; /** * Update Page properties * @param referenceList * @param itemId * @param data */ UpdatePageProperties(referenceList: string, itemId: string, data: any): JQueryDeferred<any>; /** * Get page object from pageURL * @param relativePageUrl */ GetPageObjectForPageUrl(relativePageUrl: string): JQueryDeferred<any>; /** * Update Page object Cache * @param pageObjects */ UpdatePageObjectsCache(pageObjects: any): JQueryDeferred<any>; /** * Get sharepoint lists associated with the passed content type * @param contenttype */ GetListsForContentType(contenttype: string): JQueryDeferred<any>; /** * @param listName SharePoint List name ex. GenericPages_AK * @param itemId Item Id for which permissions need to be checked */ GetPermissionForListItemForCurrentUser(listName: string, itemId: string): JQueryDeferred<any>; /** * Check if user is logged into appManager */ IsLoggedIntoAppManager(): JQueryDeferred<any>; /** * To get personas assigned to a user * @param userId * @returns deferred resolves with array of presonas string */ GetUserPersonas(userId: string): JQueryDeferred<any>; /** * Get list of apps available for user * @param listName String */ GetApps(listName: string): JQueryDeferred<any>; /** * Get groups the current user is added to. * @returns def resolves in success with Array of names of User Groups of current user. */ GetUserGroupsFromAppManager(): JQueryDeferred<any>; /** * Filter user accessible apps from list of apps. * @param groups User Groups #MARK currently not used. * @param appsData List of apps */ GetUserAccessibleApps(groups: null, appsData: any[]): JQueryDeferred<any>; /** * Get UserGroup list based of type of authoristion * @param authorization */ GetSPGroupUsersAndUserGroupsList(authorization: any): JQueryDeferred<any>; /** * Get myapps cache key for the current user * @param attribute */ GetMyAppsCacheKey(attribute: string): JQueryDeferred<any>; /** * Get Facets from interchange * @param facetObj List of facets object */ GetFacets(facetObj: any[]): JQueryDeferred<any>; /** * Marks workspace as deleted * @param workspaceId workspace id */ MarkWorkspaceAsDeleted(workspaceId: string): JQueryDeferred<any>; /** * Check if workspace is marked for delete * @param workspaceId string */ IsWorkspaceMarkedAsDeleted(workspaceId: string): JQueryDeferred<any>; /** * Check licenses assigned to members * @param memberids string */ CheckAssignedLicenses(memberids: string): JQueryDeferred<any>; /** * Get activated Features on site. * @returns Resolves in success with JSON object */ GetActivatedFeatures(): JQueryDeferred<any>; /** * Updates widget instance cache * @param widgetInstanceId Optional */ UpdateWidgetInstanceCache(widgetInstanceId?: string): JQueryDeferred<any>; /** * @returns resolves with array of widget objects */ GetDashboardWidgets(): JQueryDeferred<any>; /** * Resolves with siteID * @param selectedSiteId */ PerformChangeSite(selectedSiteId: string): JQueryDeferred<any>; /** * @returns Resolves in success with boolean value */ ValidateAkToken(): JQueryDeferred<any>; /** * @returns Resolves in success with boolean value */ RefreshAkToken(): JQueryDeferred<any>; /** * Fetches widgets js * @param widgets Array of widget objects * @param widgetNames Array of widget names */ GetWidgetJS(widgets: any[], widgetNames: string[]): JQueryDeferred<any>; /** * Get user groups * @param model */ GetUserGroups(model: any): JQueryDeferred<any>; /** * @returns Resolves with language ID {number} */ GetAppManagerLanguageId(): JQueryDeferred<any>; /** * @returns Def Resolves in success with Version Object {FileVersion: string, ProductVersion: string} */ GetAppManagerVersion(): JQueryDeferred<any>; /** * Send data to encrypt * @param data */ EncryptData(data: string): JQueryDeferred<any>; /** * Send data to decrypt * @param data */ DecryptData(data: string): JQueryDeferred<any>; /** * Save page widgets * @param pageId */ ProvisionPageWidgets(pageWidgetsRequest: ISavePageWidgetRequest): JQueryDeferred<any>; } class PageManager { /** * Get default page layouts * @return Array of page layout object * {displayOrder:, layoutId:, layoutImage:, layoutTemplate:, layoutTitle:, selectedLayout:, spPageLayoutId: } */ GetPageLayouts(): any[]; /** * Get page object from pageURL * @param relativePageurl relative page URL */ GetPageObjectForPageUrl(relativePageurl: string): JQueryDeferred<any>; GetPageObject(): JQueryDeferred<any>; /** * Get saved layout from Sharepoint * @param Title Layout Name */ GetSavedLayout(Title?: string): JQueryDeferred<any>; /** * Save custom layout * @param layoutObject JSON object having layout details */ ProvisionSavedLayout(data: any): JQueryDeferred<any>; /** * Get widgets for page * @param pageId * @param legacy */ GetWidgetsForPage(pageId: string, legacy?: boolean): JQueryDeferred<any>; /** * Save page contents(widgets) * @param pageId * @param pageWidgets */ SetPageContents(pageId: string, data: any): JQueryDeferred<any>; /** * Get matching pages from Page Url List * @param searchText Text to search existing pages */ GetPagesFromPageUrlList(searchText: string): JQueryDeferred<any>; /** * Returns List of permissions for current user for passed list * @param listName Name of list * @param useRootWeb Boolean flag */ CanUserSetPagePermissions(listName: string, useRootWeb: boolean): JQueryDeferred<any>; /** * Get permissions for Page * @param listName Name of list * @param itemId Page Id */ GetPermissionForPage(listName: string, itemId: string): JQueryDeferred<any>; /** * Set personas for page * @param listName ListName of which item belongs * @param itemId ID of item to set persona. * @param personaList Semicolon seprated List of persona to set for item * @param columnName Coloumn Name */ SetPersonasForPage(listName: string, itemId: string, personaList: any, columnName?: string): JQueryDeferred<any>; /** * Set Tags for Page * @param listName List Name * @param itemId Item Id of page * @param columnName Coloumn Name to be updated for tags * @param list semicolon seprated list of tags */ SetTagsForPage(listName: string, itemId: string, columnName: string, list: any): JQueryDeferred<any>; /** * Returns true if widget type passed is either Dashboard, PageWidget or Container Type * @param widgetType string of widget Type */ IsDashboardOrPageWidgetOrContainerType(widgetType: any): boolean; /** * Returns page type information * @param pageTypeParam Page Type */ GetPageTypeInfo(pageTypeParam: string): JQueryDeferred<any>; /** * Set permissions for Page * @param listName * @param itemId Page item Id * @param editgroup Array User groups for edit permission * @param readgroup Array User groups for read permission * @param useRootWeb */ SetPermissionsForPage(listName: string, itemId: string, editgroup: string[], readgroup: string[], useRootWeb: boolean): JQueryDeferred<any>; /** * Resolves with all the page widgets */ GetPageWidgets(): JQueryDeferred<any>; /** * Loads a new page * @param pageRouteInfo JSON object with page routing information */ LoadNewPage(pageRouteInfo: any): void; /** * Get Dashboard widgets * @param pageId */ GetDashboardWidgetsViaAppManager(pageId: string): JQueryDeferred<any>; /** * Retrive page widget * @param pageId */ GetPageWidget(pageId: string): JQueryDeferred<any>; /** * Get Dashboard Page for User * @param userId * @returns resolves with dashboard page for user {title, userId, pageId} */ GetDashboardPageForUser(userId: string): JQueryDeferred<any>; /** * Save dashboard page for user * @param userId */ ProvisionDashboardPageForUser(userId: string): JQueryDeferred<any>; /** * Retrives available page views * @param pageId */ GetPageAvailableViews(pageId: string): JQueryDeferred<any>; /** * Get Page Active View * @param pageId */ GetPageActiveView(pageId: string): JQueryDeferred<any>; /** * Get containers for view * @param viewTemplateUrl */ GetContainersForView(viewTemplateUrl: string): JQueryDeferred<any>; /** * Get Page Child widgets * @param pageId */ GetPageChildWidgets(pageId: string): JQueryDeferred<any>; /** * Get Layouts For ToolBar * @param pageId */ GetLayoutsForToolBar(pageId: string): JQueryDeferred<any>; /** * Get Widgets For Toolbar */ GetWidgetsForToolbar(): JQueryDeferred<any>; /** * Save update page objects * @param pageObject */ ProvisionPageObject(pageObject: any): JQueryDeferred<any>; /** * Save page widgets * @param widgetName * @param pageId * @param pageWidgets */ ProvisionPageWidgets(widgetName: string, pageId: string, pageWidgets: any[]): JQueryDeferred<any>; SavePage(pageId: string): JQueryDeferred<any>; /** * Provide grid details */ getGrid(): any[]; /** * Save dashboard page * @param pageId */ SaveDashboardPage(pageId: string): JQueryDeferred<any>; /** * Add Page for groups * @param pageModel */ AddPageForGroup(pageModel: any): JQueryDeferred<any>; /** * Get Available Workspace Types * @param groupType */ GetAvailableWorkspaceTypes(groupType: string): JQueryDeferred<any>; /** * Check if group type is custom * @param type */ IsGroupTypeCustom(type: string): boolean; /** * Add pages for group * @param model */ AddPagesForGroup(model: any): JQueryDeferred<any>; /** * Returns true if widget instance is either Dashboard, PageWidget or Container * @param widgetInstances string of widget Type */ IsDashBoardOrPageWidgetOrContainer(widgetInstances: any): boolean; /** * Remove pages for group * @param groupId */ RemovePagesForGroup(groupId: string): JQueryDeferred<any>; /** * Remmove group page mapping * @param groupId */ RemoveGroupPageMapping(groupId: string): JQueryDeferred<any>; /** * Remove Group Page * @param pageIds */ RemoveGroupPage(pageIds: string[]): JQueryDeferred<any>; /** * Remove Group WIdget properties * @param widgetInstanceIds */ RemoveGroupWidgetProperties(widgetInstanceIds: string[]): JQueryDeferred<any>; /** * Execute Share point query * @param clientContext * @param collListItem * @param def * @param idArray * @param columnName */ ExecuteAsyncQuery(clientContext: any, collListItem: any, def: JQueryDeferred<any>, idArray: any[], columnName: string): JQueryDeferred<any>; } class CacheManager { cachedScript(Token: string): any; } class Groups { GetGraphDataWithFullUrl(url: string, param: any): Promise<any>; GetGroupForPage(pageId: string): JQueryDeferred<any>; GetGraphUrl(prefix: string, query: string, filterQuery: string, cacheKey: string): string; } class WidgetFactory { UpdatePageWidgetInstancesCache(model: any): any; } class Graph { GetProfilePicture(email: string, flag: boolean): Promise<any>; } } } namespace AddIn { class Utilities { static getEditMode(): boolean; static IsNullOrEmpty(value: string): boolean; static GetFriendlyUrl(url: string): string; static getQueryStringParameter(url: string): string; static substring(str: string, maxChar: number): string; static ItemExpired(date: string): boolean; static TryParseInt(val: any, defaultValue: any): number | null; static GetIcon(iconName: string): string; static isInDST(date: Date): boolean; static addRecurringEvents(data: any, month: number, year: number): any; static isInMonth(item: any, month: number, year: number): any; static setDateValues(data: any, startDate: Date, endDate: Date): any; } class Logger { static WriteInfoLog(m: any): void; static WriteErrorLog(m: any): void; static StartTraceLog(m: string): void; static StopTraceLog(m: string): void; static logConnectorCall(m: string): void; static logSPCall(m: string): void; } class Cache { static Get(m: string): any; static Set(m: string, object: any, interval: number): void; static Remove(m: string): void; } class Constants { static MIN_CACHE_EXPIRATION: number; static SHORT_CACHE_EXPIRATION: number; static CACHE_EXPIRATION: number; static HOUR_CACHE_EXPIRATION: number; static TWOHOUR_CACHE_EXPIRATION: number; static FOURHOUR_CACHE_EXPIRATION: number; static LONG_CACHE_EXPIRATION: number; static DAY_CACHE_EXPIRATION: number; } class Configuration { static containsInExcludeField(field: string): boolean; static getSelectFields(widget: string): string[]; } class Alignment {} class Location {} class Icons { static None: string; } class GenericListPaging {} class Instructions { executeAsync(widget: any, instructionSet: string, propName: string): Promise<any>; } } } declare class Templates { GetViewPrefix(): void; ParseTemplate(url: string, data: any): Promise<any>; RequestTemplateFromServer(url: string): Promise<any>; GetCoreTemplate(htmlFile: string): string; GetVirtualMasterTemplate(): string; GetErrorTemplate(data: object): Promise<any>; /** * Bind error templates for widgets * @param errorObj */ BindErrorTemplateForWidgets(errorObj: any): void; } // tslint:disable-next-line interface-name interface IConstants { LOADER_STEPS_ENABLE_AUTOCLEAR: boolean; LOADER_STEPS_ENABLE_FETCHCONFIGCONTEXT: boolean; LOADER_STEPS_ENABLE_DETECTMULTIPLEVISIBLELANGS: boolean; LOADER_STEPS_ENABLE_LOADUSERLANGSETTINGS: boolean; LOADER_STEPS_ENABLE_GETADDITIONALMARKUP: boolean; LOADER_STEPS_ENABLE_DISPLAYLOADER: boolean; LOADER_STEPS_ENABLE_EVENTSUBSCRIPTION: boolean; LOADER_STEPS_ENABLE_SETSITETHEME: boolean; LOADER_STEPS_ENABLE_VALIDATEINTERCHANGEKEY: boolean; LOADER_STEPS_ENABLE_GETLOADINGTEMPLATE: boolean; LOADER_STEPS_ENABLE_INDEXPAGEDATA: boolean; LOADER_STEPS_ENABLE_GETINTERCHANGELOGINURL: boolean; LOADER_STEPS_ENABLE_GETGRAPHTOKEN: boolean; LOADER_STEPS_ENABLE_FETCHUSERPROPERTIES: boolean; LOADER_STEPS_ENABLE_FETCHPAGEPERMISSIONS: boolean; LOADER_STEPS_ENABLE_LOADWIDGETSTYPES: boolean; LOADER_STEPS_ENABLE_LOADWIDGETSINSTANCES: boolean; LOADER_STEPS_ENABLE_INITWIDGETS: boolean; LOADER_STEPS_ENABLE_INITSNIPPETS: boolean; LOADER_STEPS_ENABLE_LOADDASHBOARDWIDGETS: boolean; LOADER_STEPS_ENABLE_DISPLAYSHAREPOINTBAR: boolean; LOADER_STEPS_ENABLE_DEBUGINFO: boolean; LOADER_STEPS_ENABLE_TRAYMENU: boolean; LOADER_STEPS_ENABLE_RESUMEMAINWINDOWLOADER: boolean; LOADER_STEPS_ENABLE_FETCHLANGUAGENEUTRALLISTS: boolean; LOADER_STEPS_ENABLE_FETCHLANGUAGES: boolean; WIDGET_OPTIONS_LOADFROMAPPMANAGER: boolean; LOADER_STEPS_ENABLE_FETCHSPGROUPS: boolean; LOADER_STEPS_ENABLE_FETCHADGROUPS: boolean; FORCETEMPLATEURL: boolean; LOADER_STEPS_ENABLE_VALIDATEWORKSPACECONFIG: boolean; LOADER_STEPS_ENABLE_FETCHWORKSPACECONTEXT: boolean; LOADER_STEPS_ENABLE_PROVISIONDASHBOARD: boolean; LOADER_STEPS_ENABLE_AUTOLOGINTOAPPMANAGER: boolean; LOADER_STEPS_ENABLE_REFRESHAKTOKEN: boolean; LOADER_STEPS_ENABLE_GETWIDGETJS: boolean; LOADER_STEPS_ENABLE_GETINDIVIDUALWIDGETSJS: boolean; REDIRECTONERROR: boolean; LOG_LEVEL: number; } // tslint:disable-next-line export-just-namespace export = Akumina;
the_stack
import BN from 'bn.js'; import { assertTruth, validatorGenerator, objectToErrorString } from './utils'; import { validators as messages } from './messages'; import { PATH, MATCH, UNDEFINED, SPLITTER } from './constants'; /** * Validate a derivation path passed in as a string * * @method derivationPathValidator * * @param {string} derivationPath The derivation path to check * * @return {boolean} It only returns true if the derivation path is correct, * otherwise an Error will be thrown and this will not finish execution. */ export const derivationPathValidator = (derivationPath: string): boolean => { const { derivationPath: derivationPathMessages } = messages; const { COIN_MAINNET, COIN_TESTNET } = PATH; let deSerializedDerivationPath: Array<string>; let coinType: number; try { /* * Because assignments get bubbled to the top of the method, we need to wrap * this inside a try/catch block. * * Otherwise, this will fail before we have a change to assert it. */ deSerializedDerivationPath = derivationPath.split(PATH.DELIMITER); coinType = parseInt(deSerializedDerivationPath[1], 10); } catch (caughtError) { throw new Error( `${derivationPathMessages.notString}: ${derivationPath || UNDEFINED}`, ); } /* * We need to assert this in a separate step, otherwise, if the size of the split * chunks is not correct the `match()` method call will fail before the * validator generator sequence will actually start. */ assertTruth({ /* * It should be composed of (at least) four parts * (purpouse, coin, account, change and/or index) */ expression: deSerializedDerivationPath.length === 4, message: [ `${derivationPathMessages.notValidParts}: [`, ...deSerializedDerivationPath, ']', ], level: 'high', }); const validationSequence = [ { /* * It should have the correct Header Key (the letter 'm') */ expression: deSerializedDerivationPath[0].split(SPLITTER)[0].toLowerCase() === PATH.HEADER_KEY, message: [ `${derivationPathMessages.notValidHeaderKey}:`, deSerializedDerivationPath[0] || UNDEFINED, ], }, { /* * It should have the Ethereum reserved Purpouse (44) */ expression: parseInt(deSerializedDerivationPath[0].split(SPLITTER)[1], 10) === PATH.PURPOSE, message: [ `${derivationPathMessages.notValidPurpouse}:`, deSerializedDerivationPath[0] || UNDEFINED, ], }, { /* * It should have the correct Coin type */ expression: coinType === COIN_MAINNET || coinType === COIN_TESTNET, message: [ `${derivationPathMessages.notValidCoin}:`, deSerializedDerivationPath[1] || UNDEFINED, ], }, { /* * It should have the correct Account format (eg: a number) */ expression: !!deSerializedDerivationPath[2].match(MATCH.DIGITS), message: [ `${derivationPathMessages.notValidAccount}:`, deSerializedDerivationPath[2] || UNDEFINED, ], }, { /* * It should have the correct Change and/or Account Index format (eg: a number) */ expression: deSerializedDerivationPath[3] .split(SPLITTER) .map((value) => !!value.match(MATCH.DIGITS)) .every((truth) => truth !== false), message: [ `${derivationPathMessages.notValidChangeIndex}:`, deSerializedDerivationPath[3] || UNDEFINED, ], }, { /* * It should have the correct amount of Account Indexed (just one) */ expression: deSerializedDerivationPath[3].split(SPLITTER).length <= 2, message: [ `${derivationPathMessages.notValidAccountIndex}:`, deSerializedDerivationPath[3] || UNDEFINED, ], }, ]; return validatorGenerator( validationSequence, `${derivationPathMessages.genericError}: ${derivationPath || UNDEFINED}`, ); }; /** * Validate an integer passed in to make sure is safe (< 9007199254740991) and positive * * @method safeIntegerValidator * * @param {number} integer The integer to validate * * @return {boolean} It only returns true if the integer is safe and positive, * otherwise an Error will be thrown and this will not finish execution. */ export const safeIntegerValidator = (integer: number): boolean => { const { safeInteger: safeIntegerMessages } = messages; const validationSequence = [ { /* * It should be a number primitive */ expression: typeof integer === 'number', message: `${safeIntegerMessages.notNumber}: ${integer}`, }, { /* * It should be a positive number * This is a little less trutfull as integers can also be negative */ expression: integer >= 0, message: `${safeIntegerMessages.notPositive}: ${integer}`, }, { /* * It should be under the safe integer limit: ± 9007199254740991 * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger */ expression: Number.isSafeInteger(integer), message: `${safeIntegerMessages.notSafe}: ${integer}`, }, ]; return validatorGenerator( validationSequence, `${safeIntegerMessages.genericError}: ${integer}`, ); }; /** * Validate a Big Number instance object that was passed in * * @method bigNumberValidator * * @param {any} bigNumber The big number instance to check * * @return {boolean} It only returns true if the object is an instance of Big Number, * otherwise an Error will be thrown and this will not finish execution. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export const bigNumberValidator = (bigNumber: any): boolean => { const { bigNumber: bigNumberMessages } = messages; const validationSequence = [ { /* * It should be an instance of the BN Class */ expression: BN.isBN(bigNumber), message: `${bigNumberMessages.notBigNumber}: ${objectToErrorString( bigNumber, )}`, }, ]; return validatorGenerator( validationSequence, `${bigNumberMessages.genericError}: ${objectToErrorString(bigNumber)}`, ); }; /** * Validate a BIP32 Ethereum Address * * @TODO Validate the checksum of the address. * * @method addressValidator * * @param {string} address The 'hex' address to check * * @return {boolean} It only returns true if the string is a valid address format, * otherwise an Error will be thrown and this will not finish execution. */ export const addressValidator = (address: string): boolean => { const { address: addressMessages } = messages; let addressLength = 0; try { /* * Because length checking is bubbled to the top, we need to to wrap this inside * a separate try-catch block, otherwise the whole thing will fail before the * validation sequence will even start. */ addressLength = address.length; } catch (caughtError) { throw new Error(`${addressMessages.notStringSequence}: ${UNDEFINED}`); } const validationSequence = [ { /* * It should be a string */ expression: typeof address === 'string', message: `${addressMessages.notStringSequence}: ${ objectToErrorString({ address, }) || UNDEFINED }`, }, { /* * It should be the correct length. Either 40 or 42 (with prefix) */ expression: addressLength === 40 || addressLength === 42, message: `${addressMessages.notLength}: ${address || UNDEFINED}`, }, { /* * It should be in the correct format (hex string of length 40 with or * with out the `0x` prefix) */ expression: !!address.match(MATCH.ADDRESS), message: `${addressMessages.notFormat}: ${address || UNDEFINED}`, }, ]; return validatorGenerator( validationSequence, `${addressMessages.genericError}: ${address || UNDEFINED}`, ); }; /** * Validate a hex string * * @method hexSequenceValidator * * @param {string} hexSequence The `hex` string to check * * @return {boolean} It only returns true if the string is a valid hex format, * otherwise an Error will be thrown and this will not finish execution. */ export const hexSequenceValidator = (hexSequence: string): boolean => { const { hexSequence: hexSequenceMessages } = messages; const validationSequence = [ { /* * It should be a string */ expression: typeof hexSequence === 'string', message: `${hexSequenceMessages.notStringSequence}: ${ objectToErrorString({ hexSequence }) || UNDEFINED }`, }, { /* * It should be in the correct format (hex string with or with out the `0x` prefix) */ expression: !!hexSequence.match(MATCH.HEX_STRING), message: `${hexSequenceMessages.notFormat}: ${hexSequence || UNDEFINED}`, }, ]; return validatorGenerator( validationSequence, `${hexSequenceMessages.genericError}: ${hexSequence || UNDEFINED}`, ); }; /** * Validate a hex string * * @method messageValidator * * @param {str} string The big number instance to check * * @return {boolean} It only returns true if the string is a valid format, * otherwise an Error will be thrown and this will not finish execution. */ export const messageValidator = (str: string): boolean => { /* * Real creative naming there, huh...? */ const { message: messageMessages } = messages; const validationSequence = [ { /* * It should be a string */ expression: typeof str === 'string', message: `${messageMessages.notString}: ${ objectToErrorString({ str }) || UNDEFINED }`, }, { /* * It should be under (or equal to) 1024 Bytes in size */ expression: str.length <= 1024, message: `${messageMessages.tooBig}: ${str || UNDEFINED}`, }, ]; return validatorGenerator( validationSequence, `${messageMessages.genericError}: ${str || UNDEFINED}`, ); }; /** * Validate a hex string * * @method messageDataValidator * * @param {any} data The messageData to check * * @return {boolean} It only returns true if the data is a valid format, * otherwise an Error will be thrown and this will not finish execution. */ export const messageDataValidator = (data: string | Uint8Array): boolean => { const { message: messageMessages } = messages; const validationSequence = [ { /* * It should be a hex string or UInt8Array */ expression: (typeof data === 'string' && hexSequenceValidator(data)) || data.constructor === Uint8Array, message: `${messageMessages.notString}: ${ objectToErrorString({ data }) || UNDEFINED }`, }, ]; return validatorGenerator( validationSequence, `${messageMessages.genericError}: ${data || UNDEFINED}`, ); };
the_stack
import * as numbers from "../magic_numbers"; import {range_360} from "../utils"; import {GoldenSun} from "../GoldenSun"; import {Button} from "../XGamepad"; import {PlayerInfo} from "./Battle"; import {battle_actions, battle_positions, PlayerSprite} from "./PlayerSprite"; import {BattleAnimation} from "./BattleAnimation"; import {BattleCursorManager} from "./BattleCursorManager"; const SCALE_FACTOR = 0.8334; const BG_X = 0; export const BG_Y = 17; const BG_WIDTH = 256; export const BG_HEIGHT = 120; const CENTER_X = numbers.GAME_WIDTH >> 1; const CENTER_Y = numbers.GAME_HEIGHT - 35; const CAMERA_SPEED = 0.009 * Math.PI; const BG_SPEED = 2.4; const BG_SPIN_SPEED = 0.4; const SPACE_BETWEEN_CHARS = 35; export const SEMI_MAJOR_AXIS = numbers.GAME_WIDTH / 2 - 50; export const SEMI_MINOR_AXIS = numbers.GAME_HEIGHT / 50; export const DEFAULT_POS_ANGLE = 0.7551327; const INITIAL_POS_ANGLE = -2.120575; const INITIAL_SCALE = 1.2; const BG_DEFAULT_SCALE = 1.0; const ACTION_POS_BG_SCALE = 2; const ACTION_POS_ALLY_X = 88; const ACTION_POS_ENEMY_CENTER_X = 106; const ACTION_ALLY_Y = 160; const ACTION_ENEMY_Y = 98; const ACTION_POS_SPACE_BETWEEN = 40; const ACTION_POS_SCALE_ADD = 0.2; export const CHOOSE_TARGET_ENEMY_SHIFT = 15; export const CHOOSE_TARGET_ALLY_SHIFT = -3; const INIT_TIME = 1500; export type CameraAngle = { rad: number; update: Function; }; export type Target = { magnitude: number; target: PlayerInfo; }; export class BattleStage { private game: Phaser.Game; private data: GoldenSun; private _cursor_manager: BattleCursorManager; private _camera_angle: CameraAngle; private background_key: string; private old_camera_angle: number; private _battle_group: Phaser.Group; private crop_group: Phaser.Group; private _group_enemies: Phaser.Group; private _group_allies: Phaser.Group; private _allies_info: PlayerInfo[]; private _enemies_info: PlayerInfo[]; private _allies_count: number; private _enemies_count: number; private shift_from_middle_enemy: number; private shift_from_middle_ally: number; private _sprites: PlayerSprite[]; private x: number; private y: number; public choosing_actions: boolean; public pause_update: boolean; public pause_players_update: boolean; private black_bg: Phaser.Graphics; private _battle_bg: Phaser.TileSprite; private _battle_bg2: Phaser.TileSprite; private upper_rect: Phaser.Graphics; private lower_rect: Phaser.Graphics; private first_ally_char: Phaser.Sprite; private last_ally_char: Phaser.Sprite; private first_enemy_char: Phaser.Sprite; private last_enemy_char: Phaser.Sprite; private bg_height: number; private pos_update_factor: { factor: number; }; constructor( game: Phaser.Game, data: GoldenSun, background_key: string, allies_info: PlayerInfo[], enemies_info: PlayerInfo[] ) { this.game = game; this.data = data; this._cursor_manager = new BattleCursorManager(this.game, this.data, this); this._camera_angle = { rad: INITIAL_POS_ANGLE, update: this.update_sprite_properties.bind(this), }; this.background_key = background_key; this.old_camera_angle = this.camera_angle.rad; this._battle_group = this.game.add.group(); this.crop_group = this.game.add.group(); this._group_enemies = this.game.add.group(); this._group_allies = this.game.add.group(); this._allies_info = allies_info; this._enemies_info = enemies_info; this._allies_count = allies_info.length; this._enemies_count = enemies_info.length; this.shift_from_middle_enemy = SPACE_BETWEEN_CHARS * this.enemies_count * 0.5; this.shift_from_middle_ally = SPACE_BETWEEN_CHARS * this.allies_count * 0.5; this._sprites = []; this.x = this.game.camera.x; this.y = this.game.camera.y; this.battle_group.x = this.x; this.battle_group.y = this.y; this.battle_group.scale.setTo(INITIAL_SCALE, INITIAL_SCALE); this.crop_group.x = this.x; this.crop_group.y = this.y; this.pause_update = false; this.pause_players_update = false; this.pos_update_factor = {factor: 0}; } get cursor_manager() { return this._cursor_manager; } get sprites() { return this._sprites; } get group_allies() { return this._group_allies; } get group_enemies() { return this._group_enemies; } get allies_info() { return this._allies_info; } get enemies_info() { return this._enemies_info; } get allies_count() { return this._allies_count; } get enemies_count() { return this._enemies_count; } get battle_group() { return this._battle_group; } get camera_angle() { return this._camera_angle; } get battle_bg() { return this._battle_bg; } get battle_bg2() { return this._battle_bg2; } initialize_sprites() { this.black_bg = this.game.add.graphics(0, 0); this.battle_group.add(this.black_bg); this.black_bg.beginFill(0x0, 1); this.black_bg.drawRect(0, 0, numbers.GAME_WIDTH, numbers.GAME_HEIGHT); this.black_bg.endFill(); this._battle_bg = this.game.add.tileSprite( BG_X, BG_Y, BG_WIDTH, BG_HEIGHT, "battle_backgrounds", this.background_key ); this._battle_bg2 = this.game.add.tileSprite( BG_X, BG_Y, BG_WIDTH, BG_HEIGHT, "battle_backgrounds", this.background_key ); const bg_filter = this.game.add.filter("ColorFilters"); this.battle_bg.filters = [bg_filter]; this.battle_bg2.filters = [bg_filter]; this.bg_height = this.battle_bg.height; this.battle_bg.scale.setTo(BG_DEFAULT_SCALE, BG_DEFAULT_SCALE); this.battle_bg2.scale.setTo(BG_DEFAULT_SCALE, BG_DEFAULT_SCALE); this.allies_info.forEach(info => { const sprite_base = this.data.info.main_char_list[info.instance.key_name].sprite_base; const player_sprite = new PlayerSprite( this.game, this.data, this.group_allies, info, sprite_base, true, battle_actions.IDLE, battle_positions.BACK ); player_sprite.initialize_player(); info.sprite = player_sprite; this.sprites.push(player_sprite); }); this.enemies_info.forEach(info => { const sprite_base = this.data.info.enemies_list[info.instance.key_name].sprite_base; const player_sprite = new PlayerSprite( this.game, this.data, this.group_enemies, info, sprite_base, false, battle_actions.IDLE, battle_positions.FRONT ); player_sprite.initialize_player(); info.sprite = player_sprite; this.sprites.push(player_sprite); }); this.first_ally_char = this.group_allies.children[0] as Phaser.Sprite; this.last_ally_char = this.group_allies.children[this.allies_count - 1] as Phaser.Sprite; this.first_enemy_char = this.group_enemies.children[0] as Phaser.Sprite; this.last_enemy_char = this.group_enemies.children[this.enemies_count - 1] as Phaser.Sprite; } intialize_crop_rectangles() { const upper_x = 0; const upper_y = 0; this.upper_rect = this.game.add.graphics(upper_x, upper_y); this.crop_group.add(this.upper_rect); this.upper_rect.beginFill(0x0, 1); this.upper_rect.drawRect(0, 0, numbers.GAME_WIDTH, numbers.GAME_HEIGHT >> 1); this.upper_rect.endFill(); const lower_x = 0; const lower_y = BG_Y + (this.bg_height >> 1) + 2; this.lower_rect = this.game.add.graphics(lower_x, lower_y); this.crop_group.add(this.lower_rect); this.lower_rect.beginFill(0x0, 1); this.lower_rect.drawRect(0, 0, numbers.GAME_WIDTH, (numbers.GAME_HEIGHT >> 1) + 2); this.lower_rect.endFill(); } initialize_stage(callback) { this.choosing_actions = false; this.initialize_sprites(); this.intialize_crop_rectangles(); this.data.game.camera.resetFX(); this.battle_group.add(this.battle_bg); this.battle_group.add(this.battle_bg2); this.battle_group.add(this.group_enemies); this.battle_group.add(this.group_allies); this.game.add.tween(this.upper_rect).to( { height: BG_Y, }, INIT_TIME, Phaser.Easing.Linear.None, true ); this.game.add.tween(this.lower_rect).to( { y: BG_Y + this.bg_height - 1, height: numbers.GAME_HEIGHT - this.bg_height - BG_Y + 1, }, INIT_TIME, Phaser.Easing.Linear.None, true ); this.game.add .tween(this.camera_angle) .to( { rad: DEFAULT_POS_ANGLE, }, INIT_TIME, Phaser.Easing.Linear.None, true ) .onComplete.addOnce(() => { if (callback) { callback(); } }); this.game.add.tween(this.battle_group.scale).to( { x: 1, y: 1, }, INIT_TIME, Phaser.Easing.Linear.None, true ); } set_update_factor(factor: number) { this.pos_update_factor.factor = factor; } async reset_chars_position() { for (let i = 0; i < this.sprites.length; ++i) { const player = this.sprites[i]; if (player.player_instance.is_paralyzed(true, true)) { player.set_action(battle_actions.DOWNED); } else { player.set_action(battle_actions.IDLE); } player.ellipses_semi_major = SEMI_MAJOR_AXIS; player.ellipses_semi_minor = SEMI_MINOR_AXIS; } let promise_resolve; const promise = new Promise(resolve => (promise_resolve = resolve)); this.game.add .tween(this.pos_update_factor) .to( { factor: 0, }, 300, Phaser.Easing.Quadratic.Out, true ) .onComplete.addOnce(promise_resolve); await promise; } async set_stage_default_position() { let promise_resolve: Function; const promise = new Promise(resolve => { promise_resolve = resolve; }); this.camera_angle.rad = range_360(this.camera_angle.rad); const dest_angle = BattleAnimation.get_angle_by_direction( this.camera_angle.rad, DEFAULT_POS_ANGLE, "closest", true ); this.game.add .tween(this.camera_angle) .to( { rad: dest_angle, }, 500, Phaser.Easing.Quadratic.Out, true ) .onComplete.addOnce(promise_resolve); await promise; } private get_player_position_in_stage(sprite_index: number, target_angle?: number) { const player_sprite = this.sprites[sprite_index]; target_angle = target_angle ?? this.camera_angle.rad; const relative_angle = player_sprite.is_ally ? target_angle : target_angle + Math.PI; player_sprite.stage_angle = BattleStage.get_angle(relative_angle); const ellipse_pos_x = BattleStage.ellipse_position(player_sprite, player_sprite.stage_angle, true); const ellipse_pos_y = BattleStage.ellipse_position(player_sprite, player_sprite.stage_angle, false); const shift_from_middle = player_sprite.is_ally ? this.shift_from_middle_ally : this.shift_from_middle_enemy; const index_shifted = player_sprite.is_ally ? sprite_index : sprite_index - this.allies_count; const pos_x = ellipse_pos_x + (SPACE_BETWEEN_CHARS * index_shifted - shift_from_middle + (SPACE_BETWEEN_CHARS >> 1)) * Math.sin(relative_angle); //shift party players from base point const pos_y = ellipse_pos_y; return {x: pos_x, y: pos_y}; } set_choosing_action_position() { this.choosing_actions = true; this.battle_bg2.x = 0; this.battle_bg2.scale.setTo(ACTION_POS_BG_SCALE, ACTION_POS_BG_SCALE); this.battle_bg2.y = -this.battle_bg.height * (ACTION_POS_BG_SCALE - 1) + BG_Y - CHOOSE_TARGET_ALLY_SHIFT; for (let i = 0; i < this.sprites.length; ++i) { const player_prite = this.sprites[i]; const index_shifted = player_prite.is_ally ? i : this.enemies_count - 1 - (i - this.allies_count); const x_shift = player_prite.is_ally ? ACTION_POS_ALLY_X : ACTION_POS_ENEMY_CENTER_X - (this.enemies_count >> 1) * ACTION_POS_SPACE_BETWEEN; const pos_x = x_shift + index_shifted * ACTION_POS_SPACE_BETWEEN; const pos_y = player_prite.is_ally ? ACTION_ALLY_Y : ACTION_ENEMY_Y; player_prite.x = pos_x; player_prite.y = pos_y; const this_scale_x = player_prite.scale.x + Math.sign(player_prite.scale.x) * ACTION_POS_SCALE_ADD; const this_scale_y = player_prite.scale.y + Math.sign(player_prite.scale.y) * ACTION_POS_SCALE_ADD; player_prite.scale.setTo(this_scale_x, this_scale_y); } } reset_positions() { this.battle_bg2.scale.setTo(BG_DEFAULT_SCALE, BG_DEFAULT_SCALE); this.battle_bg2.y = BG_Y; for (let i = 0; i < this.sprites.length; ++i) { const sprite = this.sprites[i]; const this_scale_x = sprite.scale.x - Math.sign(sprite.scale.x) * ACTION_POS_SCALE_ADD; const this_scale_y = sprite.scale.y - Math.sign(sprite.scale.y) * ACTION_POS_SCALE_ADD; sprite.scale.setTo(this_scale_x, this_scale_y); } } prevent_camera_angle_overflow() { this.camera_angle.rad = range_360(this.camera_angle.rad); } update_stage() { if (this.choosing_actions || this.pause_update) return; this.update_stage_rotation(); this.update_sprite_properties(); } update_stage_rotation() { if (this.data.gamepad.is_down(Button.DEBUG_CAM_MINUS) && !this.data.gamepad.is_down(Button.DEBUG_CAM_PLUS)) { this.camera_angle.rad -= CAMERA_SPEED; this.battle_bg.x -= BG_SPEED; } else if ( this.data.gamepad.is_down(Button.DEBUG_CAM_PLUS) && !this.data.gamepad.is_down(Button.DEBUG_CAM_MINUS) ) { this.camera_angle.rad += CAMERA_SPEED; this.battle_bg.x += BG_SPEED; } else { const delta = range_360(this.camera_angle.rad) - range_360(this.old_camera_angle); this.battle_bg.x += BG_SPIN_SPEED * this.battle_bg.width * delta; //tie bg x position with camera angle when spining } if (this.battle_bg.x > this.battle_bg.width || this.battle_bg.x < -this.battle_bg.width) { //check bg x position surplus this.battle_bg.x = this.battle_bg2.x; } if (this.battle_bg.x > 0) { //make bg2 follow default bg this.battle_bg2.x = this.battle_bg.x - this.battle_bg.width; } else if (this.battle_bg.x < 0) { this.battle_bg2.x = this.battle_bg.x + this.battle_bg.width; } if (this.old_camera_angle === this.camera_angle.rad) return; this.old_camera_angle = this.camera_angle.rad; if ( Math.sin(this.camera_angle.rad) > 0 && this.battle_group.getChildIndex(this.group_allies) < this.battle_group.getChildIndex(this.group_enemies) ) { //check party and enemy z index this.battle_group.swapChildren(this.group_enemies, this.group_allies); } else if ( Math.sin(this.camera_angle.rad) < 0 && this.battle_group.getChildIndex(this.group_allies) > this.battle_group.getChildIndex(this.group_enemies) ) { this.battle_group.swapChildren(this.group_enemies, this.group_allies); } if (Math.cos(this.camera_angle.rad) < 0 && this.first_ally_char.z > this.last_ally_char.z) { //check ally z index order this.group_allies.reverse(); } else if (Math.cos(this.camera_angle.rad) > 0 && this.first_ally_char.z < this.last_ally_char.z) { this.group_allies.reverse(); } if (Math.cos(this.camera_angle.rad) < 0 && this.first_enemy_char.z < this.last_enemy_char.z) { //check enemy z index order this.group_enemies.reverse(); } else if (Math.cos(this.camera_angle.rad) > 0 && this.first_enemy_char.z > this.last_enemy_char.z) { this.group_enemies.reverse(); } } update_sprite_properties() { for (let i = 0; i < this.sprites.length; ++i) { const player_sprite = this.sprites[i]; if (this.pause_players_update && !player_sprite.force_stage_update) continue; const pos = this.get_player_position_in_stage(i); player_sprite.x = this.pos_update_factor.factor * player_sprite.x + (1 - this.pos_update_factor.factor) * pos.x; player_sprite.y = this.pos_update_factor.factor * player_sprite.y + (1 - this.pos_update_factor.factor) * pos.y; const relative_angle = player_sprite.is_ally ? this.camera_angle.rad : this.camera_angle.rad + Math.PI; const scale = BattleStage.get_scale(relative_angle); player_sprite.scale.setTo(scale, scale); if (Math.sin(relative_angle) > 0 && player_sprite.position !== battle_positions.BACK) { //change texture in function of position player_sprite.set_position(battle_positions.BACK); } else if (Math.sin(relative_angle) <= 0 && player_sprite.position !== battle_positions.FRONT) { player_sprite.set_position(battle_positions.FRONT); } if (Math.cos(relative_angle) > 0 && player_sprite.scale.x < 0) { //change side in function of position player_sprite.scale.setTo(player_sprite.scale.x, player_sprite.scale.y); } else if (Math.cos(relative_angle) <= 0 && player_sprite.scale.x > 0) { player_sprite.scale.setTo(-player_sprite.scale.x, player_sprite.scale.y); } } } unset_stage(on_fade_complete: Function, on_flash_complete: Function) { this.game.camera.fade(); this.game.camera.onFadeComplete.addOnce(() => { if (on_fade_complete) { on_fade_complete(); } this.sprites.forEach(sprite => { sprite.destroy(); }); this.group_allies.destroy(true); this.group_enemies.destroy(true); this.battle_group.destroy(true); this.upper_rect.height = this.lower_rect.height = numbers.GAME_HEIGHT >> 1; this.upper_rect.y = 0; this.lower_rect.y = numbers.GAME_HEIGHT >> 1; const fade_time = 300; this.game.camera.resetFX(); this.game.add .tween(this.upper_rect) .to( { height: 0, }, fade_time, Phaser.Easing.Linear.None, true ) .onComplete.addOnce(() => { if (on_flash_complete) { on_flash_complete(); } this.crop_group.destroy(); }); this.game.add.tween(this.lower_rect).to( { height: 0, y: numbers.GAME_HEIGHT, }, fade_time, Phaser.Easing.Linear.None, true ); }, this); } static ellipse(angle: number, a: number, b: number) { //ellipse formula a = a ?? SEMI_MAJOR_AXIS; b = b ?? SEMI_MINOR_AXIS; return (a * b) / Math.sqrt(Math.pow(b * Math.cos(angle), 2) + Math.pow(a * Math.sin(angle), 2)); } static ellipse_position(player_sprite: PlayerSprite, angle: number, is_x: boolean) { if (is_x) { const a = player_sprite.ellipses_semi_major; return CENTER_X + BattleStage.ellipse(angle, a, SEMI_MINOR_AXIS) * Math.cos(angle); } else { const b = player_sprite.ellipses_semi_minor; return CENTER_Y + BattleStage.ellipse(angle, SEMI_MAJOR_AXIS, b) * Math.sin(angle); } } static get_angle(angle: number) { //equidistant ellipse angle formula: https://math.stackexchange.com/a/1123448/202435 return ( angle + Math.atan( ((SEMI_MINOR_AXIS - SEMI_MAJOR_AXIS) * Math.tan(angle)) / (SEMI_MAJOR_AXIS + SEMI_MINOR_AXIS * Math.pow(Math.tan(angle), 2)) ) ); } static get_scale(angle: number, default_scale: number = 1.0) { return (Math.sin(angle) / 7 + SCALE_FACTOR) * default_scale; } }
the_stack
import { Injectable } from '@angular/core'; import { FormBuilder, FormControl, FormGroup } from '@angular/forms'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreFormFields } from '@singletons/form'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; import { makeSingleton, Translate } from '@singletons'; import { AddonModLesson, AddonModLessonAttemptsOverviewsAttemptWSData, AddonModLessonGetPageDataWSResponse, AddonModLessonProvider, } from './lesson'; /** * Helper service that provides some features for quiz. */ @Injectable({ providedIn: 'root' }) export class AddonModLessonHelperProvider { constructor( protected formBuilder: FormBuilder, ) {} /** * Given the HTML of next activity link, format it to extract the href and the text. * * @param activityLink HTML of the activity link. * @return Formatted data. */ formatActivityLink(activityLink: string): AddonModLessonActivityLink { const element = CoreDomUtils.convertToElement(activityLink); const anchor = element.querySelector('a'); if (!anchor) { // Anchor not found, return the original HTML. return { formatted: false, label: activityLink, href: '', }; } return { formatted: true, label: anchor.innerHTML, href: anchor.href, }; } /** * Given the HTML of an answer from a content page, extract the data to render the answer. * * @param html Answer's HTML. * @return Data to render the answer. */ getContentPageAnswerDataFromHtml(html: string): {buttonText: string; content: string} { const data = { buttonText: '', content: '', }; const element = CoreDomUtils.convertToElement(html); // Search the input button. const button = <HTMLInputElement> element.querySelector('input[type="button"]'); if (button) { // Extract the button content and remove it from the HTML. data.buttonText = button.value; button.remove(); } data.content = element.innerHTML.trim(); return data; } /** * Get the buttons to change pages. * * @param html Page's HTML. * @return List of buttons. */ getPageButtonsFromHtml(html: string): AddonModLessonPageButton[] { const buttons: AddonModLessonPageButton[] = []; const element = CoreDomUtils.convertToElement(html); // Get the container of the buttons if it exists. let buttonsContainer = element.querySelector('.branchbuttoncontainer'); if (!buttonsContainer) { // Button container not found, might be a legacy lesson (from 1.9). if (!element.querySelector('form input[type="submit"]')) { // No buttons found. return buttons; } buttonsContainer = element; } const forms = Array.from(buttonsContainer.querySelectorAll('form')); forms.forEach((form) => { const buttonSelector = 'input[type="submit"], button[type="submit"]'; const buttonEl = <HTMLInputElement | HTMLButtonElement> form.querySelector(buttonSelector); const inputs = Array.from(form.querySelectorAll('input')); if (!buttonEl || !inputs || !inputs.length) { // Button not found or no inputs, ignore it. return; } const button: AddonModLessonPageButton = { id: buttonEl.id, title: buttonEl.title || buttonEl.value, content: buttonEl.tagName == 'INPUT' ? buttonEl.value : buttonEl.innerHTML.trim(), data: {}, }; inputs.forEach((input) => { if (input.type != 'submit') { button.data[input.name] = input.value; } }); buttons.push(button); }); return buttons; } /** * Given a page data, get the page contents. * * @param data Page data. * @return Page contents. */ getPageContentsFromPageData(data: AddonModLessonGetPageDataWSResponse): string { // Search the page contents inside the whole page HTML. Use data.pagecontent because it's filtered. const element = CoreDomUtils.convertToElement(data.pagecontent || ''); const contents = element.querySelector('.contents'); if (contents) { return contents.innerHTML.trim(); } // Cannot find contents element. if (AddonModLesson.isQuestionPage(data.page?.type || -1) || data.page?.qtype == AddonModLessonProvider.LESSON_PAGE_BRANCHTABLE) { // Return page.contents to prevent having duplicated elements (some elements like videos might not work). return data.page?.contents || ''; } else { // It's an end of cluster, end of branch, etc. Return the whole pagecontent to match what's displayed in web. return data.pagecontent || ''; } } /** * Get a question and all the data required to render it from the page data. * * @param questionForm The form group where to add the controls. * @param pageData Page data. * @return Question data. */ getQuestionFromPageData(questionForm: FormGroup, pageData: AddonModLessonGetPageDataWSResponse): AddonModLessonQuestion { const element = CoreDomUtils.convertToElement(pageData.pagecontent || ''); // Get the container of the question answers if it exists. const fieldContainer = <HTMLElement> element.querySelector('.fcontainer'); // Get hidden inputs and add their data to the form group. const hiddenInputs = <HTMLInputElement[]> Array.from(element.querySelectorAll('input[type="hidden"]')); hiddenInputs.forEach((input) => { questionForm.addControl(input.name, this.formBuilder.control(input.value)); }); // Get the submit button and extract its value. const submitButton = <HTMLInputElement> element.querySelector('input[type="submit"]'); const question: AddonModLessonQuestion = { template: '', submitLabel: submitButton ? submitButton.value : Translate.instant('addon.mod_lesson.submit'), }; if (!fieldContainer) { // Element not found, return. return question; } let type = 'text'; switch (pageData.page?.qtype) { case AddonModLessonProvider.LESSON_PAGE_TRUEFALSE: case AddonModLessonProvider.LESSON_PAGE_MULTICHOICE: return this.getMultiChoiceQuestionData(questionForm, question, fieldContainer); case AddonModLessonProvider.LESSON_PAGE_NUMERICAL: type = 'number'; case AddonModLessonProvider.LESSON_PAGE_SHORTANSWER: return this.getInputQuestionData(questionForm, question, fieldContainer, type); case AddonModLessonProvider.LESSON_PAGE_ESSAY: { return this.getEssayQuestionData(questionForm, question, fieldContainer); } case AddonModLessonProvider.LESSON_PAGE_MATCHING: { return this.getMatchingQuestionData(questionForm, question, fieldContainer); } } return question; } /** * Get a multichoice question data. * * @param questionForm The form group where to add the controls. * @param question Basic question data. * @param fieldContainer HTMLElement containing the data. * @return Question data. */ protected getMultiChoiceQuestionData( questionForm: FormGroup, question: AddonModLessonQuestion, fieldContainer: HTMLElement, ): AddonModLessonMultichoiceQuestion { const multiChoiceQuestion = <AddonModLessonMultichoiceQuestion> { ...question, template: 'multichoice', options: [], multi: false, }; // Get all the inputs. Search radio first. let inputs = <HTMLInputElement[]> Array.from(fieldContainer.querySelectorAll('input[type="radio"]')); if (!inputs || !inputs.length) { // Radio buttons not found, it might be a multi answer. Search for checkbox. multiChoiceQuestion.multi = true; inputs = <HTMLInputElement[]> Array.from(fieldContainer.querySelectorAll('input[type="checkbox"]')); if (!inputs || !inputs.length) { // No checkbox found either. Stop. return multiChoiceQuestion; } } let controlAdded = false; inputs.forEach((input) => { const parent = input.parentElement; const option: AddonModLessonMultichoiceOption = { id: input.id, name: input.name, value: input.value, checked: !!input.checked, disabled: !!input.disabled, text: '', }; if (option.checked || multiChoiceQuestion.multi) { // Add the control. const value = multiChoiceQuestion.multi ? { value: option.checked, disabled: option.disabled } : option.value; questionForm.addControl(option.name, this.formBuilder.control(value)); controlAdded = true; } // Remove the input and use the rest of the parent contents as the label. input.remove(); option.text = parent?.innerHTML.trim() || ''; multiChoiceQuestion.options!.push(option); }); if (!multiChoiceQuestion.multi) { multiChoiceQuestion.controlName = inputs[0].name; if (!controlAdded) { // No checked option for single choice, add the control with an empty value. questionForm.addControl(multiChoiceQuestion.controlName, this.formBuilder.control('')); } } return multiChoiceQuestion; } /** * Get an input question data. * * @param questionForm The form group where to add the controls. * @param question Basic question data. * @param fieldContainer HTMLElement containing the data. * @param type Type of the input. * @return Question data. */ protected getInputQuestionData( questionForm: FormGroup, question: AddonModLessonQuestion, fieldContainer: HTMLElement, type: string, ): AddonModLessonInputQuestion { const inputQuestion = <AddonModLessonInputQuestion> question; inputQuestion.template = 'shortanswer'; // Get the input. const input = <HTMLInputElement> fieldContainer.querySelector('input[type="text"], input[type="number"]'); if (!input) { return inputQuestion; } inputQuestion.input = { id: input.id, name: input.name, maxlength: input.maxLength, type, }; // Init the control. questionForm.addControl(input.name, this.formBuilder.control({ value: input.value, disabled: input.readOnly })); return inputQuestion; } /** * Get an essay question data. * * @param questionForm The form group where to add the controls. * @param question Basic question data. * @param fieldContainer HTMLElement containing the data. * @return Question data. */ protected getEssayQuestionData( questionForm: FormGroup, question: AddonModLessonQuestion, fieldContainer: HTMLElement, ): AddonModLessonEssayQuestion { const essayQuestion = <AddonModLessonEssayQuestion> question; essayQuestion.template = 'essay'; // Get the textarea. const textarea = fieldContainer.querySelector('textarea'); if (!textarea) { // Textarea not found, probably review mode. const answerEl = fieldContainer.querySelector('.reviewessay'); if (!answerEl) { // Answer not found, stop. return essayQuestion; } essayQuestion.useranswer = answerEl.innerHTML; } else { essayQuestion.textarea = { id: textarea.id, name: textarea.name || 'answer[text]', }; // Init the control. essayQuestion.control = this.formBuilder.control(''); questionForm.addControl(essayQuestion.textarea.name, essayQuestion.control); } return essayQuestion; } /** * Get a matching question data. * * @param questionForm The form group where to add the controls. * @param question Basic question data. * @param fieldContainer HTMLElement containing the data. * @return Question data. */ protected getMatchingQuestionData( questionForm: FormGroup, question: AddonModLessonQuestion, fieldContainer: HTMLElement, ): AddonModLessonMatchingQuestion { const matchingQuestion = <AddonModLessonMatchingQuestion> { ...question, template: 'matching', rows: [], }; const rows = Array.from(fieldContainer.querySelectorAll('.answeroption')); rows.forEach((row) => { const label = row.querySelector('label'); const select = row.querySelector('select'); const options = Array.from(row.querySelectorAll('option')); if (!label || !select || !options || !options.length) { return; } // Get the row's text (label). const rowData: AddonModLessonMatchingRow = { text: label.innerHTML.trim(), id: select.id, name: select.name, options: [], }; // Treat each option. let controlAdded = false; options.forEach((option) => { if (typeof option.value == 'undefined') { // Option not valid, ignore it. return; } const optionData: AddonModLessonMatchingRowOption = { value: option.value, label: option.innerHTML.trim(), selected: option.selected, }; if (optionData.selected) { controlAdded = true; questionForm.addControl( rowData.name, this.formBuilder.control({ value: optionData.value, disabled: !!select.disabled }), ); } rowData.options.push(optionData); }); if (!controlAdded) { // No selected option, add the control with an empty value. questionForm.addControl(rowData.name, this.formBuilder.control({ value: '', disabled: !!select.disabled })); } matchingQuestion.rows.push(rowData); }); return matchingQuestion; } /** * Given the HTML of an answer from a question page, extract the data to render the answer. * * @param html Answer's HTML. * @return Object with the data to render the answer. If the answer doesn't require any parsing, return a string with the HTML. */ getQuestionPageAnswerDataFromHtml(html: string): AddonModLessonAnswerData { const element = CoreDomUtils.convertToElement(html); // Check if it has a checkbox. let input = <HTMLInputElement> element.querySelector('input[type="checkbox"][name*="answer"]'); if (input) { // Truefalse or multichoice. const data: AddonModLessonCheckboxAnswerData = { isCheckbox: true, checked: !!input.checked, name: input.name, highlight: !!element.querySelector('.highlight'), content: '', }; input.remove(); data.content = element.innerHTML.trim(); return data; } // Check if it has an input text or number. input = <HTMLInputElement> element.querySelector('input[type="number"],input[type="text"]'); if (input) { // Short answer or numeric. return { isText: true, value: input.value, }; } // Check if it has a select. const select = element.querySelector('select'); if (select?.options) { // Matching. const selectedOption = select.options[select.selectedIndex]; const data: AddonModLessonSelectAnswerData = { isSelect: true, id: select.id, value: selectedOption ? selectedOption.value : '', content: '', }; select.remove(); data.content = element.innerHTML.trim(); return data; } // The answer doesn't need any parsing, return the HTML as it is. return html; } /** * Get a label to identify a retake (lesson attempt). * * @param retake Retake object. * @param includeDuration Whether to include the duration of the retake. * @return Retake label. */ getRetakeLabel(retake: AddonModLessonAttemptsOverviewsAttemptWSData, includeDuration?: boolean): string { const data = { retake: retake.try + 1, grade: '', timestart: '', duration: '', }; const hasGrade = retake.grade != null; if (hasGrade || retake.end) { // Retake finished with or without grade (if the lesson only has content pages, it has no grade). if (hasGrade) { data.grade = Translate.instant('core.percentagenumber', { $a: retake.grade }); } data.timestart = CoreTimeUtils.userDate(retake.timestart * 1000); if (includeDuration) { data.duration = CoreTimeUtils.formatTime(retake.timeend - retake.timestart); } } else { // The user has not completed the retake. data.grade = Translate.instant('addon.mod_lesson.notcompleted'); if (retake.timestart) { data.timestart = CoreTimeUtils.userDate(retake.timestart * 1000); } } return Translate.instant('addon.mod_lesson.retakelabel' + (includeDuration ? 'full' : 'short'), data); } /** * Prepare the question data to be sent to server. * * @param question Question to prepare. * @param data Data to prepare. * @return Data to send. */ prepareQuestionData(question: AddonModLessonQuestion, data: CoreFormFields): CoreFormFields { if (question.template == 'essay') { const textarea = (<AddonModLessonEssayQuestion> question).textarea; // Add some HTML to the answer if needed. if (textarea) { data[textarea.name] = CoreTextUtils.formatHtmlLines(<string> data[textarea.name]); } } else if (question.template == 'multichoice' && (<AddonModLessonMultichoiceQuestion> question).multi) { // Only send the options with value set to true. for (const name in data) { if (name.match(/answer\[\d+\]/) && data[name] == false) { delete data[name]; } } } return data; } /** * Given the feedback of a process page in HTML, remove the question text. * * @param html Feedback's HTML. * @return Feedback without the question text. */ removeQuestionFromFeedback(html: string): string { const element = CoreDomUtils.convertToElement(html); // Remove the question text. CoreDomUtils.removeElement(element, '.generalbox:not(.feedback):not(.correctanswer)'); return element.innerHTML.trim(); } } export const AddonModLessonHelper = makeSingleton(AddonModLessonHelperProvider); /** * Page button data. */ export type AddonModLessonPageButton = { id: string; title: string; content: string; data: Record<string, string>; }; /** * Generic question data. */ export type AddonModLessonQuestionBasicData = { template: string; // Name of the template to use. submitLabel: string; // Text to display in submit. }; /** * Multichoice question data. */ export type AddonModLessonMultichoiceQuestion = AddonModLessonQuestionBasicData & { multi: boolean; // Whether it allows multiple answers. options: AddonModLessonMultichoiceOption[]; // Options for multichoice question. controlName?: string; // Name of the form control, for single choice. }; /** * Short answer or numeric question data. */ export type AddonModLessonInputQuestion = AddonModLessonQuestionBasicData & { input?: AddonModLessonQuestionInput; // Text input for text/number questions. }; /** * Essay question data. */ export type AddonModLessonEssayQuestion = AddonModLessonQuestionBasicData & { useranswer?: string; // User answer, for reviewing. textarea?: AddonModLessonTextareaData; // Data for the textarea. control?: FormControl; // Form control. }; /** * Matching question data. */ export type AddonModLessonMatchingQuestion = AddonModLessonQuestionBasicData & { rows: AddonModLessonMatchingRow[]; }; /** * Data for each option in a multichoice question. */ export type AddonModLessonMultichoiceOption = { id: string; name: string; value: string; checked: boolean; disabled: boolean; text: string; }; /** * Input data for text/number questions. */ export type AddonModLessonQuestionInput = { id: string; name: string; maxlength: number; type: string; }; /** * Textarea data for essay questions. */ export type AddonModLessonTextareaData = { id: string; name: string; }; /** * Data for each row in a matching question. */ export type AddonModLessonMatchingRow = { id: string; name: string; text: string; options: AddonModLessonMatchingRowOption[]; }; /** * Data for each option in a row in a matching question. */ export type AddonModLessonMatchingRowOption = { value: string; label: string; selected: boolean; }; /** * Checkbox answer. */ export type AddonModLessonCheckboxAnswerData = { isCheckbox: true; checked: boolean; name: string; highlight: boolean; content: string; }; /** * Text answer. */ export type AddonModLessonTextAnswerData = { isText: true; value: string; }; /** * Select answer. */ export type AddonModLessonSelectAnswerData = { isSelect: true; id: string; value: string; content: string; }; /** * Any possible answer data. */ export type AddonModLessonAnswerData = AddonModLessonCheckboxAnswerData | AddonModLessonTextAnswerData | AddonModLessonSelectAnswerData | string; /** * Any possible question data. */ export type AddonModLessonQuestion = AddonModLessonQuestionBasicData & Partial<AddonModLessonMultichoiceQuestion> & Partial<AddonModLessonInputQuestion> & Partial<AddonModLessonEssayQuestion> & Partial<AddonModLessonMatchingQuestion>; /** * Activity link data. */ export type AddonModLessonActivityLink = { formatted: boolean; label: string; href: string; };
the_stack
import { ParamDefinition as PD } from '../../../mol-util/param-definition'; import { VisualContext } from '../../visual'; import { Structure, StructureElement, Bond, Unit } from '../../../mol-model/structure'; import { Theme } from '../../../mol-theme/theme'; import { Mesh } from '../../../mol-geo/geometry/mesh/mesh'; import { Vec3 } from '../../../mol-math/linear-algebra'; import { BitFlags, arrayEqual } from '../../../mol-util'; import { createLinkCylinderImpostors, createLinkCylinderMesh, LinkBuilderProps, LinkStyle } from './util/link'; import { ComplexMeshParams, ComplexVisual, ComplexMeshVisual, ComplexCylindersParams, ComplexCylindersVisual } from '../complex-visual'; import { VisualUpdateState } from '../../util'; import { BondType } from '../../../mol-model/structure/model/types'; import { BondCylinderParams, BondIterator, getInterBondLoci, eachInterBond, makeInterBondIgnoreTest } from './util/bond'; import { Sphere3D } from '../../../mol-math/geometry'; import { Cylinders } from '../../../mol-geo/geometry/cylinders/cylinders'; import { WebGLContext } from '../../../mol-gl/webgl/context'; import { SortedArray } from '../../../mol-data/int/sorted-array'; const tmpRefPosBondIt = new Bond.ElementBondIterator(); function setRefPosition(pos: Vec3, structure: Structure, unit: Unit.Atomic, index: StructureElement.UnitIndex) { tmpRefPosBondIt.setElement(structure, unit, index); while (tmpRefPosBondIt.hasNext) { const bA = tmpRefPosBondIt.move(); bA.otherUnit.conformation.position(bA.otherUnit.elements[bA.otherIndex], pos); return pos; } return null; } const tmpRef = Vec3(); function getInterUnitBondCylinderBuilderProps(structure: Structure, theme: Theme, props: PD.Values<InterUnitBondCylinderParams>): LinkBuilderProps { const locE = StructureElement.Location.create(structure); const locB = Bond.Location(structure, undefined, undefined, structure, undefined, undefined); const bonds = structure.interUnitBonds; const { edgeCount, edges } = bonds; const { sizeFactor, sizeAspectRatio, adjustCylinderLength, aromaticBonds, multipleBonds } = props; const mbOff = multipleBonds === 'off'; const mbSymmetric = multipleBonds === 'symmetric'; const delta = Vec3(); let stub: undefined | ((edgeIndex: number) => boolean); const { child } = structure; if (props.includeParent && child) { stub = (edgeIndex: number) => { const b = edges[edgeIndex]; const childUnitA = child.unitMap.get(b.unitA); const childUnitB = child.unitMap.get(b.unitB); const unitA = structure.unitMap.get(b.unitA); const eA = unitA.elements[b.indexA]; const unitB = structure.unitMap.get(b.unitB); const eB = unitB.elements[b.indexB]; return ( childUnitA && SortedArray.has(childUnitA.elements, eA) && (!childUnitB || !SortedArray.has(childUnitB.elements, eB)) ); }; } const radius = (edgeIndex: number) => { const b = edges[edgeIndex]; locB.aUnit = structure.unitMap.get(b.unitA); locB.aIndex = b.indexA; locB.bUnit = structure.unitMap.get(b.unitB); locB.bIndex = b.indexB; return theme.size.size(locB) * sizeFactor; }; const radiusA = (edgeIndex: number) => { const b = edges[edgeIndex]; locE.unit = structure.unitMap.get(b.unitA); locE.element = locE.unit.elements[b.indexA]; return theme.size.size(locE) * sizeFactor; }; const radiusB = (edgeIndex: number) => { const b = edges[edgeIndex]; locE.unit = structure.unitMap.get(b.unitB); locE.element = locE.unit.elements[b.indexB]; return theme.size.size(locE) * sizeFactor; }; return { linkCount: edgeCount, referencePosition: (edgeIndex: number) => { const b = edges[edgeIndex]; let unitA: Unit.Atomic, unitB: Unit.Atomic; let indexA: StructureElement.UnitIndex, indexB: StructureElement.UnitIndex; if (b.unitA < b.unitB) { unitA = structure.unitMap.get(b.unitA) as Unit.Atomic; unitB = structure.unitMap.get(b.unitB) as Unit.Atomic; indexA = b.indexA; indexB = b.indexB; } else if (b.unitA > b.unitB) { unitA = structure.unitMap.get(b.unitB) as Unit.Atomic; unitB = structure.unitMap.get(b.unitA) as Unit.Atomic; indexA = b.indexB; indexB = b.indexA; } else { throw new Error('same units in createInterUnitBondCylinderMesh'); } return setRefPosition(tmpRef, structure, unitA, indexA) || setRefPosition(tmpRef, structure, unitB, indexB); }, position: (posA: Vec3, posB: Vec3, edgeIndex: number) => { const b = edges[edgeIndex]; const uA = structure.unitMap.get(b.unitA); const uB = structure.unitMap.get(b.unitB); uA.conformation.position(uA.elements[b.indexA], posA); uB.conformation.position(uB.elements[b.indexB], posB); if (adjustCylinderLength) { const rA = radiusA(edgeIndex), rB = radiusB(edgeIndex); const r = Math.min(rA, rB) * sizeAspectRatio; const oA = Math.sqrt(Math.max(0, rA * rA - r * r)) - 0.05; const oB = Math.sqrt(Math.max(0, rB * rB - r * r)) - 0.05; if (oA <= 0.01 && oB <= 0.01) return; Vec3.normalize(delta, Vec3.sub(delta, posB, posA)); Vec3.scaleAndAdd(posA, posA, delta, oA); Vec3.scaleAndAdd(posB, posB, delta, -oB); } }, style: (edgeIndex: number) => { const o = edges[edgeIndex].props.order; const f = BitFlags.create(edges[edgeIndex].props.flag); if (BondType.is(f, BondType.Flag.MetallicCoordination) || BondType.is(f, BondType.Flag.HydrogenBond)) { // show metallic coordinations and hydrogen bonds with dashed cylinders return LinkStyle.Dashed; } else if (o === 3) { return mbOff ? LinkStyle.Solid : mbSymmetric ? LinkStyle.Triple : LinkStyle.OffsetTriple; } else if (aromaticBonds && BondType.is(f, BondType.Flag.Aromatic)) { return LinkStyle.Aromatic; } return (o !== 2 || mbOff) ? LinkStyle.Solid : mbSymmetric ? LinkStyle.Double : LinkStyle.OffsetDouble; }, radius: (edgeIndex: number) => { return radius(edgeIndex) * sizeAspectRatio; }, ignore: makeInterBondIgnoreTest(structure, props), stub }; } function createInterUnitBondCylinderImpostors(ctx: VisualContext, structure: Structure, theme: Theme, props: PD.Values<InterUnitBondCylinderParams>, cylinders?: Cylinders) { if (!structure.interUnitBonds.edgeCount) return Cylinders.createEmpty(cylinders); const builderProps = getInterUnitBondCylinderBuilderProps(structure, theme, props); const m = createLinkCylinderImpostors(ctx, builderProps, props, cylinders); const { child } = structure; const sphere = Sphere3D.expand(Sphere3D(), (child ?? structure).boundary.sphere, 1 * props.sizeFactor); m.setBoundingSphere(sphere); return m; } function createInterUnitBondCylinderMesh(ctx: VisualContext, structure: Structure, theme: Theme, props: PD.Values<InterUnitBondCylinderParams>, mesh?: Mesh) { if (!structure.interUnitBonds.edgeCount) return Mesh.createEmpty(mesh); const builderProps = getInterUnitBondCylinderBuilderProps(structure, theme, props); const m = createLinkCylinderMesh(ctx, builderProps, props, mesh); const { child } = structure; const sphere = Sphere3D.expand(Sphere3D(), (child ?? structure).boundary.sphere, 1 * props.sizeFactor); m.setBoundingSphere(sphere); return m; } export const InterUnitBondCylinderParams = { ...ComplexMeshParams, ...ComplexCylindersParams, ...BondCylinderParams, sizeFactor: PD.Numeric(0.3, { min: 0, max: 10, step: 0.01 }), sizeAspectRatio: PD.Numeric(2 / 3, { min: 0, max: 3, step: 0.01 }), tryUseImpostor: PD.Boolean(true), includeParent: PD.Boolean(false), }; export type InterUnitBondCylinderParams = typeof InterUnitBondCylinderParams export function InterUnitBondCylinderVisual(materialId: number, structure: Structure, props: PD.Values<InterUnitBondCylinderParams>, webgl?: WebGLContext) { return props.tryUseImpostor && webgl && webgl.extensions.fragDepth ? InterUnitBondCylinderImpostorVisual(materialId) : InterUnitBondCylinderMeshVisual(materialId); } export function InterUnitBondCylinderImpostorVisual(materialId: number): ComplexVisual<InterUnitBondCylinderParams> { return ComplexCylindersVisual<InterUnitBondCylinderParams>({ defaultProps: PD.getDefaultValues(InterUnitBondCylinderParams), createGeometry: createInterUnitBondCylinderImpostors, createLocationIterator: BondIterator.fromStructure, getLoci: getInterBondLoci, eachLocation: eachInterBond, setUpdateState: (state: VisualUpdateState, newProps: PD.Values<InterUnitBondCylinderParams>, currentProps: PD.Values<InterUnitBondCylinderParams>, newTheme: Theme, currentTheme: Theme, newStructure: Structure, currentStructure: Structure) => { state.createGeometry = ( newProps.sizeAspectRatio !== currentProps.sizeAspectRatio || newProps.linkScale !== currentProps.linkScale || newProps.linkSpacing !== currentProps.linkSpacing || newProps.ignoreHydrogens !== currentProps.ignoreHydrogens || newProps.linkCap !== currentProps.linkCap || newProps.dashCount !== currentProps.dashCount || newProps.dashScale !== currentProps.dashScale || newProps.dashCap !== currentProps.dashCap || newProps.stubCap !== currentProps.stubCap || !arrayEqual(newProps.includeTypes, currentProps.includeTypes) || !arrayEqual(newProps.excludeTypes, currentProps.excludeTypes) || newProps.adjustCylinderLength !== currentProps.adjustCylinderLength || newProps.multipleBonds !== currentProps.multipleBonds ); if (newStructure.interUnitBonds !== currentStructure.interUnitBonds) { state.createGeometry = true; state.updateTransform = true; state.updateColor = true; state.updateSize = true; } }, mustRecreate: (structure: Structure, props: PD.Values<InterUnitBondCylinderParams>, webgl?: WebGLContext) => { return !props.tryUseImpostor || !webgl; } }, materialId); } export function InterUnitBondCylinderMeshVisual(materialId: number): ComplexVisual<InterUnitBondCylinderParams> { return ComplexMeshVisual<InterUnitBondCylinderParams>({ defaultProps: PD.getDefaultValues(InterUnitBondCylinderParams), createGeometry: createInterUnitBondCylinderMesh, createLocationIterator: BondIterator.fromStructure, getLoci: getInterBondLoci, eachLocation: eachInterBond, setUpdateState: (state: VisualUpdateState, newProps: PD.Values<InterUnitBondCylinderParams>, currentProps: PD.Values<InterUnitBondCylinderParams>, newTheme: Theme, currentTheme: Theme, newStructure: Structure, currentStructure: Structure) => { state.createGeometry = ( newProps.sizeFactor !== currentProps.sizeFactor || newProps.sizeAspectRatio !== currentProps.sizeAspectRatio || newProps.radialSegments !== currentProps.radialSegments || newProps.linkScale !== currentProps.linkScale || newProps.linkSpacing !== currentProps.linkSpacing || newProps.ignoreHydrogens !== currentProps.ignoreHydrogens || newProps.linkCap !== currentProps.linkCap || newProps.dashCount !== currentProps.dashCount || newProps.dashScale !== currentProps.dashScale || newProps.dashCap !== currentProps.dashCap || newProps.stubCap !== currentProps.stubCap || !arrayEqual(newProps.includeTypes, currentProps.includeTypes) || !arrayEqual(newProps.excludeTypes, currentProps.excludeTypes) || newProps.adjustCylinderLength !== currentProps.adjustCylinderLength || newProps.multipleBonds !== currentProps.multipleBonds ); if (newStructure.interUnitBonds !== currentStructure.interUnitBonds) { state.createGeometry = true; state.updateTransform = true; state.updateColor = true; state.updateSize = true; } }, mustRecreate: (structure: Structure, props: PD.Values<InterUnitBondCylinderParams>, webgl?: WebGLContext) => { return props.tryUseImpostor && !!webgl; } }, materialId); }
the_stack
const wd = new CodeceptJS.WebDriver() const str = 'text' const num = 1 wd.amOnPage() // $ExpectError wd.amOnPage('') // $ExpectType void wd.click() // $ExpectError wd.click('div') // $ExpectType void wd.click({ css: 'div' }) wd.click({ xpath: '//div' }) wd.click({ name: 'div' }) wd.click({ id: 'div' }) wd.click({ android: 'div' }) wd.click({ ios: 'div' }) wd.click(locate('div')) wd.click('div', 'body') wd.click('div', locate('div')) wd.click('div', { css: 'div' }) wd.click('div', { xpath: '//div' }) wd.click('div', { name: '//div' }) wd.click('div', { id: '//div' }) wd.click('div', { android: '//div' }) wd.click('div', { ios: '//div' }) wd.forceClick() // $ExpectError wd.forceClick('div') // $ExpectType void wd.forceClick({ css: 'div' }) wd.forceClick({ xpath: '//div' }) wd.forceClick({ name: 'div' }) wd.forceClick({ id: 'div' }) wd.forceClick({ android: 'div' }) wd.forceClick({ ios: 'div' }) wd.forceClick(locate('div')) wd.forceClick('div', 'body') wd.forceClick('div', locate('div')) wd.forceClick('div', { css: 'div' }) wd.forceClick('div', { xpath: '//div' }) wd.forceClick('div', { name: '//div' }) wd.forceClick('div', { id: '//div' }) wd.forceClick('div', { android: '//div' }) wd.forceClick('div', { ios: '//div' }) wd.doubleClick() // $ExpectError wd.doubleClick('div') // $ExpectType void wd.doubleClick({ css: 'div' }) wd.doubleClick({ xpath: '//div' }) wd.doubleClick({ name: 'div' }) wd.doubleClick({ id: 'div' }) wd.doubleClick({ android: 'div' }) wd.doubleClick({ ios: 'div' }) wd.doubleClick(locate('div')) wd.doubleClick('div', 'body') wd.doubleClick('div', locate('div')) wd.doubleClick('div', { css: 'div' }) wd.doubleClick('div', { xpath: '//div' }) wd.doubleClick('div', { name: '//div' }) wd.doubleClick('div', { id: '//div' }) wd.doubleClick('div', { android: '//div' }) wd.doubleClick('div', { ios: '//div' }) wd.rightClick() // $ExpectError wd.rightClick('div') // $ExpectType void wd.rightClick({ css: 'div' }) wd.rightClick({ xpath: '//div' }) wd.rightClick({ name: 'div' }) wd.rightClick({ id: 'div' }) wd.rightClick({ android: 'div' }) wd.rightClick({ ios: 'div' }) wd.rightClick(locate('div')) wd.rightClick('div', 'body') wd.rightClick('div', locate('div')) wd.rightClick('div', { css: 'div' }) wd.rightClick('div', { xpath: '//div' }) wd.rightClick('div', { name: '//div' }) wd.rightClick('div', { id: '//div' }) wd.rightClick('div', { android: '//div' }) wd.rightClick('div', { ios: '//div' }) wd.fillField() // $ExpectError wd.fillField('div') // $ExpectError wd.fillField('div', str) // $ExpectType void wd.fillField({ css: 'div' }, str) wd.fillField({ xpath: '//div' }, str) wd.fillField({ name: 'div' }, str) wd.fillField({ id: 'div' }, str) wd.fillField({ android: 'div' }, str) wd.fillField({ ios: 'div' }, str) wd.fillField(locate('div'), str) wd.appendField() // $ExpectError wd.appendField('div') // $ExpectError wd.appendField('div', str) // $ExpectType void wd.appendField({ css: 'div' }, str) wd.appendField({ xpath: '//div' }, str) wd.appendField({ name: 'div' }, str) wd.appendField({ id: 'div' }, str) wd.appendField({ android: 'div' }, str) wd.appendField({ ios: 'div' }, str) wd.appendField(locate('div'), str) wd.clearField() // $ExpectError wd.clearField('div') wd.clearField({ css: 'div' }) wd.clearField({ xpath: '//div' }) wd.clearField({ name: 'div' }) wd.clearField({ id: 'div' }) wd.clearField({ android: 'div' }) wd.clearField({ ios: 'div' }) wd.selectOption() // $ExpectError wd.selectOption('div') // $ExpectError wd.selectOption('div', str) // $ExpectType void wd.attachFile() // $ExpectError wd.attachFile('div') // $ExpectError wd.attachFile('div', str) // $ExpectType void wd.checkOption() // $ExpectError wd.checkOption('div') // $ExpectType void wd.uncheckOption() // $ExpectError wd.uncheckOption('div') // $ExpectType void wd.seeInTitle() // $ExpectError wd.seeInTitle(str) // $ExpectType void wd.seeTitleEquals() // $ExpectError wd.seeTitleEquals(str) // $ExpectType void wd.dontSeeInTitle() // $ExpectError wd.dontSeeInTitle(str) // $ExpectType void wd.see() // $ExpectError wd.see(str) // $ExpectType void wd.see(str, 'div') // $ExpectType void wd.dontSee() // $ExpectError wd.dontSee(str) // $ExpectType void wd.dontSee(str, 'div') // $ExpectType void wd.seeTextEquals() // $ExpectError wd.seeTextEquals(str) // $ExpectType void wd.seeTextEquals(str, 'div') // $ExpectType void wd.seeInField() // $ExpectError wd.seeInField('div') // $ExpectError wd.seeInField('div', str) // $ExpectType void wd.dontSeeInField() // $ExpectError wd.dontSeeInField('div') // $ExpectError wd.dontSeeInField('div', str) // $ExpectType void wd.seeCheckboxIsChecked() // $ExpectError wd.seeCheckboxIsChecked('div') // $ExpectType void wd.dontSeeCheckboxIsChecked() // $ExpectError wd.dontSeeCheckboxIsChecked('div') // $ExpectType void wd.seeElement() // $ExpectError wd.seeElement('div') // $ExpectType void wd.dontSeeElement() // $ExpectError wd.dontSeeElement('div') // $ExpectType void wd.seeElementInDOM() // $ExpectError wd.seeElementInDOM('div') // $ExpectType void wd.dontSeeElementInDOM() // $ExpectError wd.dontSeeElementInDOM('div') // $ExpectType void wd.seeInSource() // $ExpectError wd.seeInSource(str) // $ExpectType void wd.dontSeeInSource() // $ExpectError wd.dontSeeInSource(str) // $ExpectType void wd.seeNumberOfElements() // $ExpectError wd.seeNumberOfElements('div') // $ExpectError wd.seeNumberOfElements('div', num) // $ExpectType void wd.seeNumberOfVisibleElements() // $ExpectError wd.seeNumberOfVisibleElements('div') // $ExpectError wd.seeNumberOfVisibleElements('div', num) // $ExpectType void wd.seeCssPropertiesOnElements() // $ExpectError wd.seeCssPropertiesOnElements('div') // $ExpectError wd.seeCssPropertiesOnElements('div', str) // $ExpectType void wd.seeAttributesOnElements() // $ExpectError wd.seeAttributesOnElements('div') // $ExpectError wd.seeAttributesOnElements('div', str) // $ExpectType void wd.seeInCurrentUrl() // $ExpectError wd.seeInCurrentUrl(str) // $ExpectType void wd.seeCurrentUrlEquals() // $ExpectError wd.seeCurrentUrlEquals(str) // $ExpectType void wd.dontSeeInCurrentUrl() // $ExpectError wd.dontSeeInCurrentUrl(str) // $ExpectType void wd.dontSeeCurrentUrlEquals() // $ExpectError wd.dontSeeCurrentUrlEquals(str) // $ExpectType void wd.executeScript() // $ExpectError wd.executeScript(str) // $ExpectType Promise<any> wd.executeScript(() => {}) // $ExpectType Promise<any> wd.executeScript(() => {}, {}) // $ExpectType Promise<any> wd.executeAsyncScript() // $ExpectError wd.executeAsyncScript(str) // $ExpectType Promise<any> wd.executeAsyncScript(() => {}) // $ExpectType Promise<any> wd.executeAsyncScript(() => {}, {}) // $ExpectType Promise<any> wd.scrollIntoView() // $ExpectError wd.scrollIntoView('div') // $ExpectError wd.scrollIntoView('div', {behavior: "auto", block: "center", inline: "center"}) wd.scrollTo() // $ExpectError wd.scrollTo('div') // $ExpectType void wd.scrollTo('div', num, num) // $ExpectType void wd.moveCursorTo() // $ExpectError wd.moveCursorTo('div') // $ExpectType void wd.moveCursorTo('div', num, num) // $ExpectType void wd.saveScreenshot() // $ExpectError wd.saveScreenshot(str) // $ExpectType void wd.saveScreenshot(str, true) // $ExpectType void wd.setCookie() // $ExpectError wd.setCookie({name: str, value: str}) // $ExpectType void wd.setCookie([{name: str, value: str}]) // $ExpectType void wd.clearCookie() // $ExpectType void wd.clearCookie(str) // $ExpectType void wd.seeCookie() // $ExpectError wd.seeCookie(str) // $ExpectType void wd.acceptPopup() // $ExpectType void wd.cancelPopup() // $ExpectType void wd.seeInPopup() // $ExpectError wd.seeInPopup(str) // $ExpectType void wd.pressKeyDown() // $ExpectError wd.pressKeyDown(str) // $ExpectType void wd.pressKeyUp() // $ExpectError wd.pressKeyUp(str) // $ExpectType void wd.pressKey() // $ExpectError wd.pressKey(str) // $ExpectType void wd.type() // $ExpectError wd.type(str) // $ExpectType void wd.resizeWindow() // $ExpectError wd.resizeWindow(num) // $ExpectError wd.resizeWindow(num, num) // $ExpectType void wd.dragAndDrop() // $ExpectError wd.dragAndDrop('div') // $ExpectError wd.dragAndDrop('div', 'div') // $ExpectType void wd.dragSlider() // $ExpectError wd.dragSlider('div', num) // $ExpectType void wd.switchToWindow() // $ExpectError wd.switchToWindow(str) // $ExpectType void wd.closeOtherTabs() // $ExpectType void wd.wait() // $ExpectError wd.wait(num) // $ExpectType void wd.waitForEnabled() // $ExpectError wd.waitForEnabled('div') // $ExpectType void wd.waitForEnabled('div', num) // $ExpectType void wd.waitForElement() // $ExpectError wd.waitForElement('div') // $ExpectType void wd.waitForElement('div', num) // $ExpectType void wd.waitForClickable() // $ExpectError wd.waitForClickable('div') // $ExpectType void wd.waitForClickable('div', num) // $ExpectType void wd.waitForVisible() // $ExpectError wd.waitForVisible('div') // $ExpectType void wd.waitForVisible('div', num) // $ExpectType void wd.waitForInvisible() // $ExpectError wd.waitForInvisible('div') // $ExpectType void wd.waitForInvisible('div', num) // $ExpectType void wd.waitToHide() // $ExpectError wd.waitToHide('div') // $ExpectType void wd.waitToHide('div', num) // $ExpectType void wd.waitForDetached() // $ExpectError wd.waitForDetached('div') // $ExpectType void wd.waitForDetached('div', num) // $ExpectType void wd.waitForFunction() // $ExpectError wd.waitForFunction('div') // $ExpectType void wd.waitForFunction(() => {}) // $ExpectType void wd.waitForFunction(() => {}, [num], num) // $ExpectType void wd.waitForFunction(() => {}, [str], num) // $ExpectType void wd.waitInUrl() // $ExpectError wd.waitInUrl(str) // $ExpectType void wd.waitInUrl(str, num) // $ExpectType void wd.waitForText() // $ExpectError wd.waitForText(str) // $ExpectType void wd.waitForText(str, num, str) // $ExpectType void wd.waitForValue() // $ExpectError wd.waitForValue(str) // $ExpectError wd.waitForValue(str, str) // $ExpectType void wd.waitForValue(str, str, num) // $ExpectType void wd.waitNumberOfVisibleElements() // $ExpectError wd.waitNumberOfVisibleElements('div') // $ExpectError wd.waitNumberOfVisibleElements(str, num) // $ExpectType void wd.waitNumberOfVisibleElements(str, num, num) // $ExpectType void wd.waitUrlEquals() // $ExpectError wd.waitUrlEquals(str) // $ExpectType void wd.waitUrlEquals(str, num) // $ExpectType void wd.switchTo() // $ExpectType void wd.switchTo('div') // $ExpectType void wd.switchToNextTab(num, num) // $ExpectType void wd.switchToPreviousTab(num, num) // $ExpectType void wd.closeCurrentTab() // $ExpectType void wd.openNewTab() // $ExpectType void wd.refreshPage() // $ExpectType void wd.scrollPageToTop() // $ExpectType void wd.scrollPageToBottom() // $ExpectType void wd.setGeoLocation() // $ExpectError wd.setGeoLocation(num) // $ExpectError wd.setGeoLocation(num, num) // $ExpectType void wd.setGeoLocation(num, num, num) // $ExpectType void wd.dontSeeCookie() // $ExpectError wd.dontSeeCookie(str) // $ExpectType void wd.dragAndDrop(); // $ExpectError wd.dragAndDrop('#dragHandle'); // $ExpectError wd.dragAndDrop('#dragHandle', '#container'); wd.grabTextFromAll() // $ExpectError wd.grabTextFromAll('div') // $ExpectType Promise<string[]> wd.grabTextFrom() // $ExpectError wd.grabTextFrom('div') // $ExpectType Promise<string> wd.grabHTMLFromAll() // $ExpectError wd.grabHTMLFromAll('div') // $ExpectType Promise<string[]> wd.grabHTMLFrom() // $ExpectError wd.grabHTMLFrom('div') // $ExpectType Promise<string> wd.grabValueFromAll() // $ExpectError wd.grabValueFromAll('div') // $ExpectType Promise<string[]> wd.grabValueFrom() // $ExpectError wd.grabValueFrom('div') // $ExpectType Promise<string> wd.grabCssPropertyFromAll() // $ExpectError wd.grabCssPropertyFromAll('div') // $ExpectError wd.grabCssPropertyFromAll('div', 'color') // $ExpectType Promise<string[]> wd.grabCssPropertyFrom() // $ExpectError wd.grabCssPropertyFrom('div') // $ExpectError wd.grabCssPropertyFrom('div', 'color') // $ExpectType Promise<string> wd.grabAttributeFromAll() // $ExpectError wd.grabAttributeFromAll('div') // $ExpectError wd.grabAttributeFromAll('div', 'style') // $ExpectType Promise<string[]> wd.grabAttributeFrom() // $ExpectError wd.grabAttributeFrom('div') // $ExpectError wd.grabAttributeFrom('div', 'style') // $ExpectType Promise<string> wd.grabTitle() // $ExpectType Promise<string> wd.grabSource() // $ExpectType Promise<string> wd.grabBrowserLogs() // $ExpectType Promise<object[]> | undefined wd.grabCurrentUrl() // $ExpectType Promise<string> wd.grabNumberOfVisibleElements() // $ExpectError wd.grabNumberOfVisibleElements('div') // $ExpectType Promise<number> wd.grabCookie(); // $ExpectType Promise<string[]> | Promise<string> wd.grabCookie('name'); // $ExpectType Promise<string[]> | Promise<string> wd.grabPopupText() // $ExpectType Promise<string> wd.grabAllWindowHandles() // $ExpectType Promise<string[]> wd.grabCurrentWindowHandle() // $ExpectType Promise<string> wd.grabNumberOfOpenTabs() // $ExpectType Promise<number> const psp = wd.grabPageScrollPosition() // $ExpectType Promise<PageScrollPosition> psp.then( result => { result.x // $ExpectType number result.y // $ExpectType number } ) wd.grabGeoLocation() // $ExpectType Promise<{ latitude: number; longitude: number; altitude: number; }> wd.grabElementBoundingRect(); // $ExpectError wd.grabElementBoundingRect('h3'); // $ExpectType Promise<number> | Promise<DOMRect> wd.grabElementBoundingRect('h3', 'width') // $ExpectType Promise<number> | Promise<DOMRect>
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; import { CustomValidators } from './../shared/validation/validators'; import { ShopEventBus, PricingService, UserEventBus, Util } from './../shared/services/index'; import { PromotionTestConfigComponent } from './components/index'; import { ModalComponent, ModalResult, ModalAction } from './../shared/modal/index'; import { TaxVO, ShopVO, PromotionTestVO, CartVO, Pair, SearchResultVO, ValidationRequestVO } from './../shared/model/index'; import { Futures, Future } from './../shared/event/index'; import { Config } from './../../environments/environment'; import { UiUtil } from './../shared/ui/index'; import { LogUtil } from './../shared/log/index'; import { StorageUtil } from './../shared/storage/index'; @Component({ selector: 'cw-shop-taxes', templateUrl: 'shop-taxes.component.html', }) export class ShopTaxesComponent implements OnInit, OnDestroy { private static COOKIE_SHOP:string = 'ADM_UI_TAX_SHOP'; private static COOKIE_CURRENCY:string = 'ADM_UI_TAX_CURR'; private static _selectedShopCode:string; private static _selectedShop:ShopVO; private static _selectedCurrency:string; private static TAXES:string = 'taxes'; private static PRICELIST_TEST:string = 'pricelisttest'; public searchHelpTaxShow:boolean = false; //public forceShowAll:boolean = false; public viewMode:string = ShopTaxesComponent.TAXES; public taxes:SearchResultVO<TaxVO>; public taxesFilter:string; public taxesFilterRequired:boolean = true; private delayedFilteringTax:Future; private delayedFilteringMs:number = Config.UI_INPUT_DELAY; public selectedTax:TaxVO; public taxEdit:TaxVO; public taxEditForm:any; public validForSaveTax:boolean = false; @ViewChild('deleteConfirmationModalDialog') private deleteConfirmationModalDialog:ModalComponent; @ViewChild('editTaxModalDialog') private editTaxModalDialog:ModalComponent; @ViewChild('selectShopModalDialog') private selectShopModalDialog:ModalComponent; @ViewChild('selectCurrencyModalDialog') private selectCurrencyModalDialog:ModalComponent; @ViewChild('runTestModalDialog') private runTestModalDialog:PromotionTestConfigComponent; public deleteValue:String; public loading:boolean = false; public testCart:CartVO; private userSub:any; constructor(private _taxService:PricingService, fb: FormBuilder) { LogUtil.debug('ShopTaxesComponent constructed'); let that = this; let validCode = function(control:any):any { let basic = CustomValidators.requiredValidCode(control); if (basic == null) { let code = control.value; if (that.taxEdit == null || !that.taxEditForm || (!that.taxEditForm.dirty && that.taxEdit.taxId > 0)) { return null; } let req:ValidationRequestVO = { subject: 'tax', subjectId: that.taxEdit.taxId, field: 'code', value: code }; return CustomValidators.validRemoteCheck(control, req); } return basic; }; this.taxEditForm = fb.group({ 'code': ['', validCode], 'description': ['', CustomValidators.requiredNonBlankTrimmed], 'exclusiveOfPrice': [''], 'taxRate': ['', CustomValidators.requiredPositiveNumber], 'shopCode': ['', Validators.required], 'currency': ['', Validators.required], }); this.taxes = this.newSearchResultInstance(); } get selectedShop():ShopVO { return ShopTaxesComponent._selectedShop; } set selectedShop(selectedShop:ShopVO) { ShopTaxesComponent._selectedShop = selectedShop; } get selectedShopCode(): string { return ShopTaxesComponent._selectedShopCode; } set selectedShopCode(value: string) { ShopTaxesComponent._selectedShopCode = value; } get selectedCurrency():string { return ShopTaxesComponent._selectedCurrency; } set selectedCurrency(selectedCurrency:string) { ShopTaxesComponent._selectedCurrency = selectedCurrency; } newTaxInstance():TaxVO { return { taxId: 0, taxRate: 0, exclusiveOfPrice: false, shopCode: this.selectedShop.code, currency: this.selectedCurrency, code: '', guid: null, description: null}; } newSearchResultInstance():SearchResultVO<TaxVO> { return { searchContext: { parameters: { filter: [] }, start: 0, size: Config.UI_TABLE_PAGE_SIZE, sortBy: null, sortDesc: false }, items: [], total: 0 }; } ngOnInit() { LogUtil.debug('ShopTaxesComponent ngOnInit'); this.onRefreshHandler(); this.userSub = UserEventBus.getUserEventBus().userUpdated$.subscribe(user => { this.presetFromCookie(); }); let that = this; this.delayedFilteringTax = Futures.perpetual(function() { that.getFilteredTax(); }, this.delayedFilteringMs); this.formBind(); } ngOnDestroy() { LogUtil.debug('ShopTaxesComponent ngOnDestroy'); this.formUnbind(); if (this.userSub) { this.userSub.unsubscribe(); } } formBind():void { UiUtil.formBind(this, 'taxEditForm', 'formChangeTax', false); } formUnbind():void { UiUtil.formUnbind(this, 'taxEditForm'); } formChangeTax():void { LogUtil.debug('ShopTaxesComponent formChangeTax', this.taxEditForm.valid, this.taxEdit); this.validForSaveTax = this.taxEditForm.valid; } presetFromCookie() { if (this.selectedShop == null) { let shopCode = StorageUtil.readValue(ShopTaxesComponent.COOKIE_SHOP, null); if (shopCode != null) { let shops = ShopEventBus.getShopEventBus().currentAll(); if (shops != null) { shops.forEach(shop => { if (shop.code == shopCode) { this.selectedShop = shop; this.selectedShopCode = shop.code; LogUtil.debug('ShopTaxesComponent ngOnInit presetting shop from cookie', shop); } }); } } } if (this.selectedCurrency == null) { let curr = StorageUtil.readValue(ShopTaxesComponent.COOKIE_CURRENCY, null); if (curr != null) { this.selectedCurrency = curr; LogUtil.debug('ShopTaxesComponent ngOnInit presetting currency from cookie', curr); } } } onShopSelect() { LogUtil.debug('ShopTaxesComponent onShopSelect'); this.selectShopModalDialog.show(); } onShopSelected(event:ShopVO) { LogUtil.debug('ShopTaxesComponent onShopSelected'); this.selectedShop = event; if (this.selectedShop != null) { this.selectedShopCode = event.code; StorageUtil.saveValue(ShopTaxesComponent.COOKIE_SHOP, this.selectedShop.code); } else { this.selectedShopCode = null; } } onSelectShopResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxesComponent onSelectShopResult modal result is ', modalresult); if (this.selectedShop == null) { this.selectShopModalDialog.show(); } else if (this.selectedCurrency == null) { this.selectCurrencyModalDialog.show(); } else { this.getFilteredTax(); } } onCurrencySelect() { LogUtil.debug('ShopTaxesComponent onCurrencySelect'); this.selectCurrencyModalDialog.show(); } onCurrencySelected(event:string) { LogUtil.debug('ShopTaxesComponent onCurrencySelected'); this.selectedCurrency = event; if (this.selectedCurrency != null) { StorageUtil.saveValue(ShopTaxesComponent.COOKIE_CURRENCY, this.selectedCurrency); } } onSelectCurrencyResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxesComponent onSelectCurrencyResult modal result is ', modalresult); if (this.selectedCurrency == null) { this.selectCurrencyModalDialog.show(); } else { this.getFilteredTax(); } } onTestRules() { LogUtil.debug('ShopTaxesComponent onTestRules'); this.runTestModalDialog.showDialog(); } onRunTestResult(event:PromotionTestVO) { LogUtil.debug('ShopTaxesComponent onRunTestResult', event); if (event != null && this.selectedShop != null) { this.loading = true; event.shopCode = this.selectedShop.code; event.currency = this.selectedCurrency; this._taxService.testPromotions(event).subscribe(cart => { this.loading = false; LogUtil.debug('ShopTaxesComponent onTestRules', cart); this.viewMode = ShopTaxesComponent.PRICELIST_TEST; this.testCart = cart; } ); } } onTaxFilterChange(event:any) { this.taxes.searchContext.start = 0; // changing filter means we need to start from first page this.delayedFilteringTax.delay(); } onRefreshHandler() { LogUtil.debug('ShopTaxesComponent refresh handler'); if (UserEventBus.getUserEventBus().current() != null) { this.presetFromCookie(); this.getFilteredTax(); } } onPageSelected(page:number) { LogUtil.debug('ShopPromotionsComponent onPageSelected', page); this.taxes.searchContext.start = page; this.delayedFilteringTax.delay(); } onSortSelected(sort:Pair<string, boolean>) { LogUtil.debug('ShopPromotionsComponent ononSortSelected', sort); if (sort == null) { this.taxes.searchContext.sortBy = null; this.taxes.searchContext.sortDesc = false; } else { this.taxes.searchContext.sortBy = sort.first; this.taxes.searchContext.sortDesc = sort.second; } this.delayedFilteringTax.delay(); } onTaxSelected(data:TaxVO) { LogUtil.debug('ShopTaxesComponent onTaxSelected', data); this.selectedTax = data; // this.getFilteredTaxConfig(); } onSearchHelpToggleTax() { this.searchHelpTaxShow = !this.searchHelpTaxShow; } onSearchRate() { this.taxesFilter = '%'; this.searchHelpTaxShow = false; } onSearchType() { this.taxesFilter = '-'; this.searchHelpTaxShow = false; } onRowNew() { LogUtil.debug('ShopTaxesComponent onRowNew handler'); this.validForSaveTax = false; UiUtil.formInitialise(this, 'taxEditForm', 'taxEdit', this.newTaxInstance(), false, ['code']); this.editTaxModalDialog.show(); } onRowTaxDelete(row:TaxVO) { LogUtil.debug('ShopTaxesComponent onRowDelete handler', row); this.deleteValue = row.code + (row.description ? ': ' + row.description : ''); this.deleteConfirmationModalDialog.show(); } onRowDeleteSelected() { if (this.selectedTax != null) { this.onRowTaxDelete(this.selectedTax); } } onRowEditTax(row:TaxVO) { LogUtil.debug('ShopTaxesComponent onRowEditTax handler', row); this.validForSaveTax = false; UiUtil.formInitialise(this, 'taxEditForm', 'taxEdit', Util.clone(row), row.taxId > 0, ['code']); this.editTaxModalDialog.show(); } onRowEditSelected() { if (this.selectedTax != null) { this.onRowEditTax(this.selectedTax); } } onRowCopySelected() { if (this.selectedTax != null) { let copyTax:TaxVO = Util.clone(this.selectedTax); copyTax.taxId = 0; copyTax.shopCode = this.selectedShopCode; this.onRowEditTax(copyTax); } } onBackToList() { LogUtil.debug('ShopTaxesComponent onBackToList handler'); if (this.viewMode === ShopTaxesComponent.PRICELIST_TEST) { this.viewMode = ShopTaxesComponent.TAXES; } } onSaveHandler() { if (this.taxEdit != null) { if (this.validForSaveTax) { LogUtil.debug('ShopTaxesComponent Save handler tax', this.taxEdit); this.loading = true; this._taxService.saveTax(this.taxEdit).subscribe(rez => { LogUtil.debug('ShopTaxesComponent tax changed', rez); this.selectedTax = rez; this.loading = false; this.getFilteredTax(); } ); } } } onDiscardEventHandler() { LogUtil.debug('ShopTaxesComponent discard handler'); if (this.selectedTax != null) { this.onRowEditSelected(); } else { this.onRowNew(); } } onEditTaxResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxesComponent onEditTaxResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { this.onSaveHandler(); } else { this.taxEdit = null; } } onDeleteConfirmationResult(modalresult: ModalResult) { LogUtil.debug('ShopTaxesComponent onDeleteConfirmationResult modal result is ', modalresult); if (ModalAction.POSITIVE === modalresult.action) { if (this.selectedTax != null) { LogUtil.debug('ShopTaxesComponent onDeleteConfirmationResult', this.selectedTax); this.loading = true; this._taxService.removeTax(this.selectedTax).subscribe(res => { LogUtil.debug('ShopTaxesComponent removeTax', this.selectedTax); this.selectedTax = null; this.loading = false; this.getFilteredTax(); }); } } } onClearFilterTax() { this.taxesFilter = ''; this.delayedFilteringTax.delay(); } private getFilteredTax() { this.taxesFilterRequired = false; // !this.forceShowAll && (this.taxesFilter == null || this.taxesFilter.length < 2); LogUtil.debug('ShopTaxesComponent getFilteredTax'); if (this.selectedShop != null && this.selectedCurrency != null && !this.taxesFilterRequired) { this.loading = true; this.taxes.searchContext.parameters.filter = [ this.taxesFilter ]; this.taxes.searchContext.parameters.shopCode = [ this.selectedShop.code ]; this.taxes.searchContext.parameters.currency = [ this.selectedCurrency ]; this.taxes.searchContext.size = Config.UI_TABLE_PAGE_SIZE; this._taxService.getFilteredTax(this.taxes.searchContext).subscribe( alltaxes => { LogUtil.debug('ShopTaxesComponent getFilteredTax', alltaxes); this.taxes = alltaxes; this.selectedTax = null; this.validForSaveTax = false; this.viewMode = ShopTaxesComponent.TAXES; this.loading = false; }); } else { this.taxes = this.newSearchResultInstance(); this.selectedTax = null; this.validForSaveTax = false; this.viewMode = ShopTaxesComponent.TAXES; } } }
the_stack
import {AbstractComponent} from '@common/component/abstract.component'; import { Component, ElementRef, EventEmitter, HostListener, Injector, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {Field, Field as AbstractField} from '../../domain/workbook/configurations/field/field'; import {Alert} from '@common/util/alert.util'; import * as _ from 'lodash'; import {StringUtil} from '@common/util/string.util'; import {DIRECTION} from '@domain/workbook/configurations/sort'; import {AxisLabelType, ChartType, EventType, SeriesType} from '@common/component/chart/option/define/common'; import {AggregationType} from '@domain/workbook/configurations/field/measure-field'; import {UIChartAxis} from '@common/component/chart/option/ui-option/ui-axis'; import {Modal} from '@common/domain/modal'; import {UIChartColorByValue, UIOption} from '../../common/component/chart/option/ui-option'; import {ByTimeUnit, GranularityType, TimeUnit} from '@domain/workbook/configurations/field/timestamp-field'; import {Pivot} from '@domain/workbook/configurations/pivot'; import {PageWidget} from '@domain/dashboard/widget/page-widget'; import {Shelf} from '@domain/workbook/configurations/shelf/shelf'; import {UIMapOption} from '@common/component/chart/option/ui-option/map/ui-map-chart'; import {MapLayerType} from '@common/component/chart/option/define/map/map-common'; import {Format} from '@domain/workbook/configurations/format'; import {ColorPickerComponent} from '@common/component/color-picker/color.picker.component'; @Component({ selector: 'pivot-context', templateUrl: './pivot-context.component.html', styles: ['.sys-inverted {transform: scaleX(-1);}'] }) export class PivotContextComponent extends AbstractComponent implements OnInit, OnDestroy { @Input('uiOption') public uiOption: UIOption; @Input('editingField') public editingField: AbstractField; // Widget 데이터의 필터 목록 (필드명만 정제) @Input('filterFiledList') public filterFiledList: string[] = []; @Input('widget') public widget: PageWidget; // 차트 타입 @Input('chartType') public chartType: string; @Input('pivot') public pivot: Pivot; @Input('shelf') public shelf: Shelf; // combine 차트의 현재 선택된 editing 필드의 agg index @Input('combineAggIndex') public combineAggIndex: number; // aggregation @Input('aggTypeList') public aggTypeList: any[]; @Output() public editingFieldChange: EventEmitter<AbstractField> = new EventEmitter(); @Output('changePivotContext') public changePivotContext: EventEmitter<any> = new EventEmitter(); @ViewChild('colorPicker') public colorPicker: ColorPickerComponent; public isShowPicker: boolean = false; // editingField Alias 임시저장용 public editingFieldAlias: string; // 2Depth 컨텍스트 메뉴 고정여부 public fix2DepthContext: boolean = false; public fixMeasureFormatContext: boolean = false; public fixMeasureColorContext: boolean = false; public get seriesType(): typeof SeriesType { return SeriesType; } // 생성자 constructor(protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /** * 마우스 오버 이벤트 * @param {MouseEvent} event */ @HostListener('document:mouseover', ['$event']) public onMouseOverHost(event: MouseEvent) { if( this.isShowPicker ) { const $target = $(event.target); if( $target.hasClass('sys-individual-color-menu') || $target.closest('.sys-individual-color-menu').length || $target.hasClass('sp-container') || $target.closest('.sp-container').length ) { this.isShowPicker = true; } else { this.isShowPicker = false; this.colorPicker.closePicker(); } } } // func - onMouseOverHost /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Getter / Setter |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public get isCombineChart(): boolean { return this.chartType === 'combine'; } // get - isCombineChart public get isGridChart(): boolean { return this.chartType === 'grid'; } // get - isGridChart public get isLabelChart(): boolean { return this.chartType === 'label'; } // get - isLabelChart public get isMeasureField(): boolean { return this.editingField && this.editingField.type === 'measure'; } // get - isMeasureField /** * 보조축으로 사용중인 필드여부 */ public get isSecondaryAxis(): boolean { // X, Y축만 있다면 사용중이 아님 if (!this.uiOption.secondaryAxis) { return false; } if (undefined === this.editingField.isSecondaryAxis) { const aggrIdx = this.pivot.aggregations.findIndex(aggr => { const aggrName = aggr.aggregationType + '(' + aggr.name + ')'; const targetName = this.editingField.aggregationType + '(' + this.editingField.name + ')'; return (aggrName === targetName); }); return (0 !== aggrIdx % 2); } else { // 현재필드의 보조축인지 체크 return this.editingField.isSecondaryAxis; } } // get - isSecondaryAxis /** * 현재 색상 코드 */ public get colorCode(): string { if( this.editingField.color ) { return this.editingField.color.rgb ? this.editingField.color.rgb : '#ffcaba'; } else { return ''; } } // get - colorCode /** * 현재 색상 스키마 */ public get colorSchema(): string { if( this.editingField.color ) { return this.editingField.color.schema ? this.editingField.color.schema.key : 'VC1'; } else { return ''; } } // get - colorSchema /** * 현재 스키마 순번 */ public get colorSchemaIdx(): number { if( this.editingField.color ) { return this.editingField.color.schema ? this.editingField.color.schema.idx : 1; } else { return 0; } } // get - colorSchemaIdx /** * 현재 스키마 반전 여부 */ public isInvertedColorSchema():boolean { if( this.editingField.color ) { return this.editingField.color.schema ? this.editingField.color.schema.key.indexOf('R') === 0 : false; } else { return false; } } // get - isInvertedColorSchema /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 필터 On / Off 핸들러 */ public onChangeFilter($event): void { if (this.editingField.field.filtering) { $event.target ? $event.target.checked = true : $event.currentTarget.checked = true; Alert.warning(this.translateService.instant('msg.board.alert.recomm-filter.del.error')); return; } // emit this.changePivotContext.emit({type: 'toggleFilter', value: this.editingField}); } /** * 2 뎁스 메뉴 숨김 */ public hideAllSubContext(): void { this.fix2DepthContext = false; this.fixMeasureFormatContext = false; this.fixMeasureColorContext = false; } // func - hideAllSubContext /** * 마우스 오버시 필드 별칭 입력 초기값 설정 * @param {Field} editingField */ public setEditingFieldAlias(editingField: AbstractField) { if (this.isSetPivotAlias(editingField)) { if (editingField.pivotAlias) { this.editingFieldAlias = editingField.pivotAlias.trim(); } else { this.editingFieldAlias = editingField.alias.trim(); } } else { this.editingFieldAlias = ''; } } // function - setEditingFieldAlias /** * 피봇 별칭 수정에 대한 표시 문구 * @param {Field} editingField */ public getDisplayEditingPivotAlias(editingField: AbstractField): string { if (editingField.pivotAlias) { return editingField.pivotAlias; } else { return editingField.alias ? editingField.alias : 'NONE'; } } // function - getDisplayEditingPivotAlias /** * pivot Alias 가 설정되었는지 여부 반환 * @param {Field} editingField * @return {boolean} */ public isSetPivotAlias(editingField: AbstractField): boolean { if (editingField.pivotAlias) { return true; } else { return (editingField.alias && editingField.alias !== editingField.name && editingField.fieldAlias !== editingField.alias); } } // function - isSetPivotAlias /** * Alias for this chart: 적용 * @param event */ public onAliasApply(event: Event): void { // 이벤트 캔슬 event.stopPropagation(); // validation if (this.editingField.pivotAlias && this.editingField.pivotAlias.trim().length > 50) { Alert.info(this.translateService.instant('msg.page.alert.chart.title.maxlength.warn')); return; } // return pivot or shelf by chart type const list = this.returnPivotShelf(); // 중복체크 let duppIndex: number = _.findIndex(list, (item) => { return item.pivotAlias === this.editingFieldAlias || item.fieldAlias === this.editingFieldAlias; }); if (duppIndex === -1) { this.widget.dashBoard.configuration['fields'].forEach((field, index) => { if (field.nameAlias && field.nameAlias['nameAlias'] === this.editingFieldAlias) { duppIndex = index; return false; } }); } // 중복이면 알림 후 중단 if (duppIndex > -1) { Alert.info(this.translateService.instant('msg.page.alert.chart.alias.dupp.warn')); return; } // 값이 없다면 Reset 처리 if (this.editingFieldAlias.trim() === '') { this.onAliasReset(null); return; } // 값 적용 this.editingFieldAlias = this.editingFieldAlias === this.editingField.name ? this.editingFieldAlias + ' ' : this.editingFieldAlias; this.editingField.alias = this.editingFieldAlias; this.editingField.pivotAlias = this.editingFieldAlias; this.fix2DepthContext = false; // 이벤트 발생 this.changePivotContext.emit({type: 'changePivot', value: EventType.PIVOT_ALIAS}); // this.editingFieldChange.emit(this.editingField); } /** * Alias for this chart: 취소 * @param event */ public onAliasReset(event: Event): void { // 이벤트 캔슬 if (event) { event.stopPropagation(); } // 값 적용 delete this.editingField.alias; delete this.editingField.pivotAlias; this.editingFieldAlias = ''; this.fix2DepthContext = false; // 이벤트 발생 this.changePivotContext.emit({type: 'changePivot', value: EventType.PIVOT_ALIAS}); } /** * 사용자 정의 필드 Expresion 표현형태로 치환 * @param expr * @returns {string} */ public unescapeCustomColumnExpr(expr: string) { return StringUtil.unescapeCustomColumnExpr(expr); } // editFilter AlignName public getAlignName() { if (this.editingField.direction === DIRECTION.ASC) { return 'Ascending'; } else if (this.editingField.direction === DIRECTION.DESC) { return 'Descending'; } return 'In order of data'; } public onChangeOrder(direction: string) { this.editingField.direction = DIRECTION[direction]; // return pivot or shelf by chart type const list = this.returnPivotShelf(); // 기존의 마지막 Sort를 제거한다. list.forEach((item) => { delete item.lastDirection; }); this.editingField.lastDirection = true; this.changePivotContext.emit({type: 'changePivot'}); } public hasAlign(direction: string) { if (direction === 'NONE' && !this.editingField.hasOwnProperty('direction')) { return true; } return this.editingField.direction === DIRECTION[direction]; } /** * aggregationType 변경시 * @param aggregationTypeId aggregationType 아이디 (SUM/AVG/COUNT/MIN/MAX/PERCENTILE) * @param aggTypeOption PERCENTILE처럼 3depth의 선택값 */ public onChangeAggregationType(aggregationTypeId: string, aggTypeOption: number) { // 이벤트 버블링 stop event.stopPropagation(); // disabled된 aggregation Type을 선택시 return / percentile 제외 if (-1 !== this.editingField.aggregationTypeList.indexOf(aggregationTypeId) && String(AggregationType.PERCENTILE) !== aggregationTypeId) { return; } // percentile일때 options값이 없는경우 return if (String(AggregationType.PERCENTILE) === aggregationTypeId && !aggTypeOption) { return; } // aggregation 함수의 타입설정 this.editingField.aggregationType = aggregationTypeId; // value 값(aggType의 옵션) if (aggTypeOption) { // editingField options 설정 this.setEditingFieldOptions('value=', aggTypeOption); } this.changePivotContext.emit({type: 'changePivot', value: EventType.AGGREGATION}); } /** * 결합차트의 시리즈 차트타입 변경 * @param seriesType */ public combineChangeSeriesConvertType(seriesType: SeriesType) { // aggregation에서 현재 선택된 필드의 index 가져오기 this.combineAggIndex = this.pivot.aggregations.indexOf(this.editingField); // editing field options 해당 키에 맞게 설정 this.setEditingFieldOptions('series.type=', seriesType); this.changePivotContext.emit({type: 'changePivot'}); } /** * 포맷변경 핸들러 * @param formatType */ public onChangeFormat(formatType: string): void { if (formatType !== '') { // Dispatch Event const field: AbstractField = _.cloneDeep(this.editingField); if (!field.format) { field.format = {}; } field.format.type = formatType; this.changePivotContext.emit({type: 'format', value: field}); } else { this.changePivotContext.emit({type: 'format', value: null}); } } /** * Show value on chart 변경 핸들러 * @param showValue */ public onChangeShowValue(showValue: boolean): void { // Show Value On / Off 변경 this.editingField.showValue = showValue; // 이벤트 발생 this.changePivotContext.emit({type: 'pivotFilter'}); } // 시리즈로 표현가능 여부 public isPossibleSeries() { // 보조축이 가능한 차트인지 체크 if (!_.eq(this.chartType, ChartType.BAR) && !_.eq(this.chartType, ChartType.LINE) && !_.eq(this.chartType, ChartType.CONTROL)) { return false; } // editingFilter가 시리즈로 표현가능한지 체크 if (this.pivot.aggregations.length < 2) { return false; } // 첫번째 아이템이 아닌지 체크 if (this.pivot.aggregations[0] === this.editingField) { return false; } // 모두 통과시 return true; } /** * 보조축 On / Off 핸들러 */ public onChangeSecondaryAxis(_$event: Event): void { // 보조축 const secondaryAxis: UIChartAxis = _.cloneDeep(this.uiOption.yAxis); // secondaryAxis.name = this.editingField.alias; secondaryAxis.mode = AxisLabelType.SUBCOLUMN; this.editingField.isSecondaryAxis = !this.editingField.isSecondaryAxis; this.uiOption.secondaryAxis = secondaryAxis; // 이벤트 발생 this.changePivotContext.emit({type: 'changeSecondaryAxis', value: this.editingField}); } /** * * @param field * @param byUnitShowFl byUnit show/hide 설정 * @returns {string} */ public getGranularityName(field: AbstractField, byUnitShowFl?: boolean) { // byUnit이 있는경우 3depth에 대한 명칭도 보여줌 return field.format && field.format.unit ? field.format.byUnit && byUnitShowFl ? field.format.unit.toString() + ' BY ' + field.format.byUnit.toString() : field.format.unit.toString() : ''; } public onChangeGranularity(discontinuous: boolean, unit: string, byUnit?: string) { // 같은 granularity를 선택시 return if (this.editingField.format.discontinuous === discontinuous && this.editingField.format.unit === TimeUnit[unit] && this.editingField.format.byUnit === ByTimeUnit[byUnit]) { return; } // 사용자 색상이 설정된경우 granularity를 변경시 if (this.uiOption.color && (this.uiOption.color as UIChartColorByValue).ranges && (this.uiOption.color as UIChartColorByValue).ranges.length > 0 && (this.editingField.format.discontinuous !== discontinuous || this.editingField.format.unit !== TimeUnit[unit])) { const modal = new Modal(); modal.name = this.translateService.instant('msg.page.chart.color.measure.range.grid.original.description'); modal.data = { data: {discontinuous: discontinuous, unit: unit, byUnit: byUnit}, eventType: EventType.GRANULARITY }; // emit, open confirm popup this.changePivotContext.emit({type: 'showPopup', value: modal}); return; } this.changePivotContext.emit({type: 'onSetGranularity', value: {discontinuous, unit, byUnit}}); } /** * 사용 가능한 Granularity인지 여부 editingField로 호출 * @param discontinuous * @param unit * @param byUnit */ public isUseGranularity(discontinuous: boolean, unit: string, byUnit?: string): boolean { return this.useGranularity(discontinuous, unit, this.editingField.granularity, byUnit); } public isGranularitySelected(field: AbstractField, discontinuous: boolean, unit: string, byUnit?: string) { if (_.isUndefined(field.format)) { return false; } if (!discontinuous) { return (!field.format.discontinuous && field.format.unit === TimeUnit[unit]); } else { return (field.format.discontinuous && field.format.unit === TimeUnit[unit]) && (!byUnit || (byUnit && field.format.byUnit === ByTimeUnit[byUnit])); } } /** * 별칭에 대한 placeholder 문구 조회 * @param {Field} field * @return {string} */ public getAliasPlaceholder(field: AbstractField): string { const displayName: string = (field.fieldAlias) ? field.fieldAlias : field.name; return (field['aggregationType']) ? (field['aggregationType'] + '(' + displayName + ')') : displayName; } // function - getAliasPlaceholder /** * when click outside of context menu * * @param _event - 마우스 이벤트 */ public clickOutside(_event: MouseEvent) { this.editingField = null; this.hideAllSubContext(); // when it's null, two way binding doesn't work this.changePivotContext.emit({type: 'outside', value: this.editingField}); } /** * pivot change event * @param changedFormat */ public onPivotFormatChange(changedFormat: Format) { this.editingField.fieldFormat = changedFormat; this.changePivotContext.emit({type: 'changePivot'}); } // func - onPivotFormatChange /** * show / hide aggregate context menu * @returns {boolean} */ public showAggregate(): boolean { let returnValue: boolean = false; // type is measure, custom field aggregated is false => show if (this.editingField.type === 'measure' && !this.editingField.aggregated) { // map chart => point, heatmap if (ChartType.MAP === this.uiOption.type) { const mapUIOption = (this.uiOption as UIMapOption); const layerType = mapUIOption.layers[mapUIOption.layerNum].type; // point, heatmap, line, polygon => no aggregation / hexagon => set aggregation if (MapLayerType.TILE === layerType) { returnValue = true; } } // not map chart else { returnValue = true; } } return returnValue; } /** * 사용 가능한 Granularity인지 여부 * @param _discontinuous * @param unit * @param granularity * @param _byUnit */ private useGranularity(_discontinuous: boolean, unit: string, granularity: GranularityType, _byUnit?: string): boolean { // granularity 가중치 반환 (SECOND => YEAR로 갈수록 점수가 높아짐) const getGranularityScore = (granularityType: string): number => { let score: number = 0; switch (granularityType) { // 초단위 제거 요청으로 주석처리 case String(GranularityType.SECOND): score = 1; break; case String(GranularityType.MINUTE): score = 2; break; case String(GranularityType.HOUR): score = 3; break; case String(GranularityType.DAY): score = 4; break; case String(GranularityType.WEEK): score = 4; break; case String(GranularityType.MONTH): score = 6; break; case String(GranularityType.QUARTER): score = 6; break; case String(GranularityType.YEAR): score = 8; break; } return score; }; // 해당 필드가 가능한 최소 Granularity Scope const minGranularityScore: number = getGranularityScore(String(granularity)); // 체크할 Granularity가 최소 Granularity Scope보다 같거나 높아야만 true const granularityScore: number = getGranularityScore(unit); return granularityScore >= minGranularityScore; } /** * editing field options 해당 키에 맞게 설정 * @param key options에 들어갈 key값 * @param optionData options에 해당 key의 데이터 */ private setEditingFieldOptions(key: string, optionData: any) { // options가 없는경우 if (!this.editingField.options) { this.editingField.options = key + optionData; // options가 있는경우 } else { // value가 있는경우 if (this.editingField.options.indexOf(key) !== -1) { const optionsList = this.editingField.options.split(','); for (let num = 0; num < optionsList.length; num++) { const option = optionsList[num]; // 해당 key가 있는경우 if (option.indexOf(key) !== -1) { optionsList[num] = num !== 0 ? key + optionData : key + optionData; } } this.editingField.options = optionsList.join(); // 해당 key가 없는경우 } else { // 기존 option값에 해당 key 추가 this.editingField.options = this.editingField.options + ',' + key + optionData; } } } /** * return pivot or shelf by chart type * @returns {Field[]} */ private returnPivotShelf(): Field[] { let list: any[]; if (ChartType.MAP === this.uiOption.type) { list = this.shelf.layers[(this.uiOption as UIMapOption).layerNum].fields; } else { list = _.concat(this.pivot.columns, this.pivot.rows, this.pivot.aggregations); } return list; } /* +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= * Measure Color 관련 기능 * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/ /** * 컬러 타입 선택 여부 * @param type */ public isSelectedColorType(type: 'GRADATION' | 'INDIVIDUAL'): boolean { const fieldColor = this.editingField.color; if( fieldColor ) { if( 'GRADATION' === type ) { return fieldColor.schema && '' !== fieldColor.schema.key; } else { return fieldColor.rgb && '' !== fieldColor.rgb; } } else { return false; } } // func - isSelectedColorType /** * 그라데이션 색상 변경 * @param schemaInfo */ public changeGradationColor(schemaInfo: {index: number, colorNum: string}): void { // {index: 8, colorNum: "VC8"} console.log( '>>>>>> changeGradationColor : ', schemaInfo, this.editingField ); this.editingField.color = { schema : { idx : schemaInfo.index, key : schemaInfo.colorNum } }; this.changePivotContext.emit({type: 'changeMeasureColor', value: this.editingField}); } // func - changeGradationColor /** * 단색 변경 * @param colorCode */ public changeSolidColor(colorCode:string): void { // #30c5fe console.log( '>>>>>> changeSolidColor : ', colorCode, this.editingField ); this.editingField.color = { rgb : colorCode }; this.changePivotContext.emit({type: 'changeMeasureColor', value: this.editingField}); } // func - changeSolidColor /** * Picker 표시 */ public showPicker(): void { this.isShowPicker = true; this.colorPicker.openPicker(); } // func - showPicker }
the_stack
import { computed, reaction } from "mobx" import { assert, _ } from "spec.ts" import { addActionMiddleware, applyAction, DataModel, ExtendedDataModel, getParent, idProp, Model, model, modelAction, modelClass, ModelData, modelFlow, prop, registerRootStore, toTreeNode, tProp, types, _async, _await, } from "../../src" import "../commonSetup" import { autoDispose, delay } from "../utils" test("without type", async () => { let viewRuns = 0 @model("myApp/Todo1") class Todo extends DataModel({ done: prop<boolean>().withSetter(), text: prop<string>(), }) { ten = 10 get inverseDone() { return !this.done } toggleDone() { this.setDone(!this.done) } @computed get asString() { viewRuns++ return `${this.done ? "DONE" : "TODO"} ${this.text}` } @modelAction setText = (text: string) => { this.text = text } @modelAction setAll(done: boolean, text: string) { // just to see we can use views within actions const str = this.asString expect(str).toBe(`${this.done ? "DONE" : "TODO"} ${this.text}`) // just to see we can use actions within actions this.setDone(done) todo.text = text return 32 + this.ten } private *_asyncAction(done: boolean) { this.done = done yield* _await(delay(10)) return this.done } @modelFlow asyncAction = _async(this._asyncAction) } assert( _ as ModelData<Todo>, _ as { done: boolean text: string } ) const todo = new Todo({ done: true, text: "1" }) registerRootStore(todo.$) // props expect(todo.done).toBe(todo.$.done) expect(todo.text).toBe(todo.$.text) expect(todo.ten).toBe(10) expect(todo.inverseDone).toBe(false) todo.toggleDone() expect(todo.done).toBe(false) // uncached when not observed expect(viewRuns).toBe(0) expect(todo.asString).toBe("TODO 1") expect(todo.asString).toBe("TODO 1") expect(viewRuns).toBe(2) viewRuns = 0 // cached when observed autoDispose( reaction( () => todo.asString, () => {} ) ) expect(viewRuns).toBe(1) expect(todo.asString).toBe("TODO 1") expect(todo.asString).toBe("TODO 1") expect(viewRuns).toBe(1) viewRuns = 0 const events: any = [] autoDispose( addActionMiddleware({ subtreeRoot: todo.$, middleware(ctx, next) { events.push({ event: "action started", ctx, }) const result = next() events.push({ event: "action finished", ctx, result, }) return result }, }) ) expect(events.length).toBe(0) todo.setDone(true) expect(viewRuns).toBe(1) expect(todo.done).toBe(true) expect(todo.$.done).toBe(todo.done) todo.setText("2") expect(todo.text).toBe("2") expect(todo.$.text).toBe(todo.text) expect(todo.setAll(false, "3")).toBe(42) expect(todo.done).toBe(false) expect(todo.text).toBe("3") expect(events).toMatchInlineSnapshot(` Array [ Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setDone", "args": Array [ true, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setDone", "args": Array [ true, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": undefined, }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setText", "args": Array [ "2", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setText", "args": Array [ "2", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": undefined, }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setDone", "args": Array [ false, ], "data": Object {}, "parentContext": Object { "actionName": "fn::myApp/Todo1::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "rootContext": Object { "actionName": "fn::myApp/Todo1::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setDone", "args": Array [ false, ], "data": Object {}, "parentContext": Object { "actionName": "fn::myApp/Todo1::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "rootContext": Object { "actionName": "fn::myApp/Todo1::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": undefined, }, Object { "ctx": Object { "actionName": "fn::myApp/Todo1::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": 42, }, ] `) expect( applyAction(todo.$, { actionName: "fn::myApp/Todo1::setAll", args: [true, "4"], targetPath: [], targetPathIds: [], }) ).toBe(42) expect(todo.done).toBe(true) expect(todo.text).toBe("4") // flows const newDone = await todo.asyncAction(false) expect(todo.done).toBe(false) expect(newDone).toBe(false) }) test("with type", async () => { let viewRuns = 0 @model("myApp/Todo2") class Todo extends DataModel({ done: tProp(types.boolean).withSetter(), text: tProp(types.string), }) { ten = 10 get inverseDone() { return !this.done } toggleDone() { this.setDone(!this.done) } @computed get asString() { viewRuns++ return `${this.done ? "DONE" : "TODO"} ${this.text}` } @modelAction setText = (text: string) => { this.text = text } @modelAction setAll(done: boolean, text: string) { // just to see we can use views within actions const str = this.asString expect(str).toBe(`${this.done ? "DONE" : "TODO"} ${this.text}`) // just to see we can use actions within actions this.setDone(done) todo.text = text return 32 + this.ten } private *_asyncAction(done: boolean) { this.done = done yield* _await(delay(10)) return this.done } @modelFlow asyncAction = _async(this._asyncAction) } assert( _ as ModelData<Todo>, _ as { done: boolean text: string } ) const todo = new Todo({ done: true, text: "1" }) expect(todo.typeCheck()).toBe(null) registerRootStore(todo.$) // props expect(todo.done).toBe(todo.$.done) expect(todo.text).toBe(todo.$.text) expect(todo.ten).toBe(10) expect(todo.inverseDone).toBe(false) todo.toggleDone() expect(todo.done).toBe(false) // uncached when not observed expect(viewRuns).toBe(0) expect(todo.asString).toBe("TODO 1") expect(todo.asString).toBe("TODO 1") expect(viewRuns).toBe(2) viewRuns = 0 // cached when observed autoDispose( reaction( () => todo.asString, () => {} ) ) expect(viewRuns).toBe(1) expect(todo.asString).toBe("TODO 1") expect(todo.asString).toBe("TODO 1") expect(viewRuns).toBe(1) viewRuns = 0 const events: any = [] autoDispose( addActionMiddleware({ subtreeRoot: todo.$, middleware(ctx, next) { events.push({ event: "action started", ctx, }) const result = next() events.push({ event: "action finished", ctx, result, }) return result }, }) ) expect(events.length).toBe(0) todo.setDone(true) expect(viewRuns).toBe(1) expect(todo.done).toBe(true) expect(todo.$.done).toBe(todo.done) todo.setText("2") expect(todo.text).toBe("2") expect(todo.$.text).toBe(todo.text) expect(todo.setAll(false, "3")).toBe(42) expect(todo.done).toBe(false) expect(todo.text).toBe("3") expect(events).toMatchInlineSnapshot(` Array [ Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setDone", "args": Array [ true, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setDone", "args": Array [ true, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": undefined, }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setText", "args": Array [ "2", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setText", "args": Array [ "2", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": undefined, }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setDone", "args": Array [ false, ], "data": Object {}, "parentContext": Object { "actionName": "fn::myApp/Todo2::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "rootContext": Object { "actionName": "fn::myApp/Todo2::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setDone", "args": Array [ false, ], "data": Object {}, "parentContext": Object { "actionName": "fn::myApp/Todo2::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "rootContext": Object { "actionName": "fn::myApp/Todo2::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": undefined, }, Object { "ctx": Object { "actionName": "fn::myApp/Todo2::setAll", "args": Array [ false, "3", ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "done": false, "text": "3", }, "type": "sync", }, "event": "action finished", "result": 42, }, ] `) expect( applyAction(todo.$, { actionName: "fn::myApp/Todo2::setAll", args: [true, "4"], targetPath: [], targetPathIds: [], }) ).toBe(42) expect(todo.done).toBe(true) expect(todo.text).toBe("4") // flows const newDone = await todo.asyncAction(false) expect(todo.done).toBe(false) expect(newDone).toBe(false) }) test("idProp is not allowed", () => { expect(() => DataModel({ id: idProp, }) ).toThrow('expected no idProp but got some: ["id"]') }) test("onLazyInit gets called", () => { let lazyInitCalls = 0 @model("test/LazyInit") class LazyInit extends DataModel({ x: prop<number>(), }) { onLazyInit() { lazyInitCalls++ this.x++ } } expect(lazyInitCalls).toBe(0) const inst = new LazyInit({ x: 10 }) expect(lazyInitCalls).toBe(1) expect(inst.x).toBe(11) }) test("multiple calls to new with the same tree node return the same instance", () => { @model("test/SameInstance") class SameInstance extends DataModel({ x: prop<number>(), }) {} const inst1 = new SameInstance({ x: 10 }) const inst2 = new SameInstance(inst1.$) expect(inst1).toBe(inst2) }) test("type checking", () => { @model("test/TypeCheck") class TypeCheck extends DataModel({ x: tProp(types.number), }) {} const wrongData = { x: "10", } const errorMsg = "TypeCheckError: [/x] Expected: number" expect(() => new TypeCheck(wrongData as any)).toThrow(errorMsg) }) test("parent/child", () => { @model("test/ChildModel") class ChildModel extends DataModel({ x: tProp(types.number), }) {} @model("test/ParentModel") class ParentModel extends Model({ subObj: tProp(types.maybe(types.dataModelData(ChildModel))).withSetter(), }) {} const pm = new ParentModel({}) const tc = new ChildModel({ x: 10 }) expect(() => pm.setSubObj(tc)).toThrow( "data models are not directly supported. you may insert the data in the tree instead ('$' property)." ) pm.setSubObj(tc.$) expect(pm.subObj).toBe(tc.$) expect(getParent(tc.$)).toBe(pm) expect(() => getParent(tc)).toThrow("value must be a tree node") }) test("two different classes over the same data return different instances", () => { @model("test/a") class A extends DataModel({ x: prop<number>() }) {} @model("test/b") class B extends DataModel({ x: prop<number>() }) {} const data = toTreeNode({ x: 10 }) expect(new A(data)).not.toBe(new B(data)) }) test("extends works", () => { @model("test/extends/base") class Base extends DataModel({ x: prop<number>().withSetter() }) {} const bm = new Base({ x: 10 }) expect(bm.x).toBe(10) const events: any = [] autoDispose( addActionMiddleware({ subtreeRoot: bm.$, middleware(ctx, next) { events.push({ event: "action started", ctx, }) const result = next() events.push({ event: "action finished", ctx, result, }) return result }, }) ) bm.setX(30) expect(bm.x).toBe(30) expect(events).toMatchInlineSnapshot(` Array [ Object { "ctx": Object { "actionName": "fn::test/extends/base::setX", "args": Array [ 30, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "x": 30, }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::test/extends/base::setX", "args": Array [ 30, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "x": 30, }, "type": "sync", }, "event": "action finished", "result": undefined, }, ] `) @model("test/extends/extended") class Extended extends ExtendedDataModel(Base, { y: prop<number>().withSetter(), }) {} const m = new Extended({ x: 10, y: 20 }) expect(m.x).toBe(10) expect(m.y).toBe(20) events.length = 0 autoDispose( addActionMiddleware({ subtreeRoot: m.$, middleware(ctx, next) { events.push({ event: "action started", ctx, }) const result = next() return result }, }) ) m.setX(30) m.setY(40) expect(m.x).toBe(30) expect(m.y).toBe(40) expect(events).toMatchInlineSnapshot(` Array [ Object { "ctx": Object { "actionName": "fn::test/extends/extended::setX", "args": Array [ 30, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "x": 30, "y": 40, }, "type": "sync", }, "event": "action started", }, Object { "ctx": Object { "actionName": "fn::test/extends/extended::setY", "args": Array [ 40, ], "data": Object {}, "parentContext": undefined, "rootContext": [Circular], "target": Object { "x": 30, "y": 40, }, "type": "sync", }, "event": "action started", }, ] `) }) test("new pattern for generics", () => { @model("GenericModel") class GenericModel<T1, T2> extends DataModel(<U1, U2>() => ({ v1: prop<U1>(), v2: prop<U2>(), v3: prop<number>(), }))<T1, T2> {} assert(_ as ModelData<GenericModel<string, number>>, _ as { v1: string; v2: number; v3: number }) assert(_ as ModelData<GenericModel<number, string>>, _ as { v1: number; v2: string; v3: number }) const s = new GenericModel<string, number>({ v1: "1", v2: 2, v3: 3 }) expect(s.v1).toBe("1") expect(s.v2).toBe(2) expect(s.v3).toBe(3) @model("ExtendedGenericModel") class ExtendedGenericModel<T1, T2> extends ExtendedDataModel(<T1, T2>() => ({ baseModel: modelClass<GenericModel<T1, T2>>(GenericModel), props: { v4: prop<T2>(), }, }))<T1, T2> {} const e = new ExtendedGenericModel<string, number>({ v1: "1", v2: 2, v3: 3, v4: 4 }) expect(e.v1).toBe("1") expect(e.v2).toBe(2) expect(e.v3).toBe(3) expect(e.v4).toBe(4) })
the_stack
import mapboxgl from 'vue-iclient/static/libs/mapboxgl/mapbox-gl-enhance'; import bbox from '@turf/bbox'; import transformScale from '@turf/transform-scale'; import clonedeep from 'lodash.clonedeep'; import mergewith from 'lodash.mergewith'; import difference from 'lodash.difference'; import getFeatures from '../../common/_utils/get-features'; /** * @class AttributesViewModel * @description Attributes viewModel. * @param {Object} map - map实例对象。 * @fires mapLoaded - 地图加载 * @extends mapboxgl.Evented */ interface MapEventCallBack { (e: mapboxglTypes.MapMouseEvent): void; } interface AssociateWithMapParams { enabled?: boolean; zoomToFeature?: boolean; centerToFeature?: boolean; flyOptions?: mapboxglTypes.FlyToOptions; } interface PaginationParams { defaultCurrent?: number; current?: number; pageSize?: number; total?: number; } interface FieldConfigParams { title?: string; value: string; visible?: boolean; align?: string; filterMultiple?: boolean; onFilter?: Function; onFilterDropdownVisibleChange?: Function; sorter?: Function | boolean; defaultSortOrder?: string; width?: string | number; search?: boolean; customCell?: Function; customHeaderCell?: Function; } const HIGHLIGHT_COLOR = '#01ffff'; const defaultPaintTypes = { circle: ['circle-radius', 'circle-stroke-width'], line: ['line-width'], fill: ['line-width'] }; const mbglStyle = { circle: { 'circle-color': HIGHLIGHT_COLOR, 'circle-opacity': 0.6, 'circle-stroke-color': HIGHLIGHT_COLOR, 'circle-stroke-opacity': 1 }, line: { 'line-color': HIGHLIGHT_COLOR, 'line-opacity': 1 }, fill: { 'fill-color': HIGHLIGHT_COLOR, 'fill-opacity': 0.6, 'fill-outline-color': HIGHLIGHT_COLOR }, symbol: { layout: { 'icon-size': 5 } } }; class FeatureTableViewModel extends mapboxgl.Evented { map: mapboxglTypes.Map; layerStyle: Object; selectedKeys: Array<string>; addKeys: Array<string>; fire: any; layerName: string; selectLayerFn: MapEventCallBack; sourceId: string; layerId: string; strokeLayerID: string; associateWithMap: AssociateWithMapParams; featureMap: Object; dataset: any; lazy: boolean; sorter: Object; paginationOptions: PaginationParams; searchText: string; searchedColumn: string; fieldConfigs: FieldConfigParams; currentTitle: string; constructor(options) { super(); this.selectedKeys = []; this.addKeys = []; this.featureMap = {}; Object.keys(options).forEach(option => { this[option] = options[option]; }); this.clearSelectedRows(); if (this.useDataset()) { this.getDatas(); } this.selectLayerFn = this._selectLayerFn.bind(this); } setMap(mapInfo) { const { map } = mapInfo; this.map = map; this.fire('mapLoaded', map); this.handleAssociateWithMap(); this.clearSelectedRows(); if (this.layerName) { this.getDatas(); } } setLayerName(layerName) { this.layerName = layerName; this.getDatas(); } setDataset(dataset) { this.dataset = dataset; this.clearSelectedRows(); this.getDatas(); } setLazy(lazy) { this.lazy = lazy; this.clearSelectedRows(); this.getDatas(); } setSorter(sorter) { this.sorter = sorter; this.getDatas(); } setAssociateWithMap(associateWithMap) { this.associateWithMap = associateWithMap; this.handleAssociateWithMap(); } setPaginationOptions(paginationOptions) { this.paginationOptions = paginationOptions; this.getDatas(); } setFieldInfo(fieldConfigs) { this.fieldConfigs = fieldConfigs; this.getDatas(); } refresh() { this.paginationOptions.current = 1; this.clearSelectedRows(); this.getDatas(); } setSearchText(searchText, searchedColumn) { this.searchText = searchText; this.searchedColumn = searchedColumn; this.getDatas(); } _selectLayerFn(e) { let pos: mapboxglTypes.LngLatLike = [e.point.x, e.point.y]; const featuresInfo = this.map.queryRenderedFeatures(pos, { layers: [this.layerName] }); if (featuresInfo && featuresInfo.length) { this.fire('changeSelectLayer', featuresInfo[0]); } } enableSelectFeature() { this.map && this.map.on('click', this.selectLayerFn); } disableSelectFeature() { this.map && this.map.off('click', this.selectLayerFn); } zoomToFeatures(selectedKeys) { let highLightList = this.handleCoords(selectedKeys); if (Object.keys(selectedKeys).length && this.map) { let features = Object.values(highLightList); const geojson = { type: 'FeatureCollection', features }; // @ts-ignore let bounds = bbox(transformScale(geojson, 2)); this.map.fitBounds( [ [bounds[0], bounds[1]], [bounds[2], bounds[3]] ], { maxZoom: this.associateWithMap.zoomToFeature ? this.map.getMaxZoom() : this.map.getZoom(), ...this.associateWithMap.flyOptions } ); } } _inMapExtent(featureObj) { const mapbounds: mapboxglTypes.LngLatBoundsLike = this.map.getBounds(); if (this.addKeys.length) { return this.addKeys.every(key => { let { type, coordinates } = featureObj[key].geometry; if (['MultiLineString', 'Polygon'].includes(type)) { return coordinates.some(line => { return line.some(coordinate => { // @ts-ignore return mapbounds.contains(coordinate); }); }); } else if (['MultiPoint', 'LineString'].includes(type)) { return coordinates.some(coordinate => { // @ts-ignore return mapbounds.contains(coordinate); }); } else if (type === 'MultiPolygon') { return coordinates[0].some(polygon => { return polygon.some(coordinate => { // @ts-ignore return mapbounds.contains(coordinate); }); }); } // @ts-ignore return mapbounds.contains(coordinates); }); } return false; } addOverlaysToMap(selectedKeys, layerStyleOptions, attributesTitle) { selectedKeys = this.handleCoords(selectedKeys); this.addKeys = difference(Object.keys(selectedKeys), this.selectedKeys); this.selectedKeys = Object.keys(selectedKeys); let filter: any = ['any']; this.selectedKeys.forEach(key => { const feature = selectedKeys[key]; if (feature) { filter.push(['==', 'index', feature.properties.index]); } }); this.addOverlayToMap(filter, selectedKeys, layerStyleOptions, attributesTitle); } addOverlayToMap(filter, selectedKeys, layerStyleOptions, attributesTitle) { let { centerToFeature, zoomToFeature } = this.associateWithMap; if (!this.map) { return; } let layer = this.map.getLayer(this.layerName); let type, id: string, paint; let features = []; if (!layer) { if (!Object.keys(this.featureMap).length) { return; } if (attributesTitle && this.currentTitle && attributesTitle !== this.currentTitle) { this.removed(); } for (const key in this.featureMap) { features.push(this.featureMap[key]); } switch (features[0].geometry.type) { case 'Point': type = 'circle'; break; case 'LineString': case 'MultiLineString': type = 'line'; break; case 'Polygon': case 'MultiPolygon': type = 'fill'; break; default: break; } id = attributesTitle; this.currentTitle = attributesTitle; this.sourceId = id + '-attributes-SM-highlighted-source'; if (this.map.getSource(this.sourceId)) { // @ts-ignore this.map.getSource(this.sourceId).setData({ type: 'FeatureCollection', features }); } else { this.map.addSource(this.sourceId, { type: 'geojson', data: { type: 'FeatureCollection', features } }); } } else { type = layer.type; id = layer.id; paint = layer.paint; } // 如果是面的strokline,处理成面 if (id.includes('-strokeLine') && type === 'line') { type = 'fill'; paint = {}; } let layerStyle = this._setDefaultPaintWidth( type, id, defaultPaintTypes[type], layerStyleOptions || this.layerStyle ); this.layerId = id + '-attributes-SM-highlighted'; this.strokeLayerID = id + '-attributes-SM-StrokeLine'; if ( (!this.addKeys.length && !this.selectedKeys.length) || JSON.stringify(layerStyleOptions) !== JSON.stringify(this.layerStyle) ) { this.map.getLayer(this.layerId) && this.map.removeLayer(this.layerId); this.map.getLayer(this.strokeLayerID) && this.map.removeLayer(this.strokeLayerID); } if (['circle', 'fill', 'line'].includes(type)) { if (this.map.getLayer(this.layerId)) { this.map.setFilter(this.layerId, filter); } else { let highlightLayerStyle = layerStyle[type]; let highlightLayer = { id: this.layerId, type, paint: (highlightLayerStyle && highlightLayerStyle.paint) || Object.assign({}, paint, mbglStyle[type]), layout: (highlightLayerStyle && highlightLayerStyle.layout) || { visibility: 'visible' }, filter }; highlightLayer = Object.assign({}, layer || { source: this.sourceId }, highlightLayer); this.map.addLayer(highlightLayer); } if ( this.addKeys.length && (centerToFeature || zoomToFeature || (!zoomToFeature && Object.keys(selectedKeys).length && !this._inMapExtent(selectedKeys))) ) { this.zoomToFeatures(Object.keys(selectedKeys)); } } if (type === 'fill') { if (this.map.getLayer(this.strokeLayerID)) { this.map.setFilter(this.strokeLayerID, filter); } else { let stokeLineStyle = layerStyle.strokeLine || layerStyle.stokeLine || {}; let lineStyle = (stokeLineStyle && stokeLineStyle.paint) || { 'line-width': 3, 'line-color': HIGHLIGHT_COLOR, 'line-opacity': 1 }; let highlightLayer = { id: this.strokeLayerID, type: 'line', paint: lineStyle, layout: { visibility: 'visible' }, filter }; highlightLayer = Object.assign({}, layer || { source: this.sourceId }, highlightLayer); // @ts-ignore this.map.addLayer(highlightLayer); } } this.addKeys = []; } _setDefaultPaintWidth(type, layerId, paintTypes, layerStyle) { if (!paintTypes) { return; } paintTypes.forEach(paintType => { let mapPaintProperty; if (type !== 'fill') { mapPaintProperty = this.map.getLayer(layerId) && this.map.getPaintProperty(layerId, paintType); } else { type = 'stokeLine'; } layerStyle[type].paint[paintType] = layerStyle[type].paint[paintType] || mapPaintProperty; if (layerStyle[type].paint[paintType] === void 0 || layerStyle[type].paint[paintType] === '') { layerStyle[type].paint[paintType] = paintType === 'circle-stroke-width' || type === 'stokeLine' ? 2 : 8; } }); return layerStyle; } _getFeaturesFromLayer(layerName: string) { // @ts-ignore return this.map.getSource(layerName).getData().features; } async getDatas() { if (this.dataset || this.layerName) { let features; let totalCount; if (this.useDataset()) { const datas = await this._getFeaturesFromDataset(); features = datas.features; totalCount = datas.totalCount; } else { features = this._getFeaturesFromLayer(this.layerName); totalCount = features.length; } const content = this.toTableContent(features); const columns = this.toTableColumns(features[0].properties); this.fire('dataChanged', { content, totalCount, columns }); } } async _getFeaturesFromDataset() { // @ts-ignore const { url, geoJSON } = this.dataset; if (url || geoJSON) { let dataset = clonedeep(this.dataset); // @ts-ignore if (!this.associateWithMap.enabled) { dataset.hasGeometry = false; } if (this.canLazyLoad()) { if (this.searchText && this.searchedColumn) { dataset.attributeFilter = `${this.searchedColumn} like '%${this.searchText}%'`; } // @ts-ignore if (this.sorter && this.sorter.field && this.sorter.order) { // @ts-ignore let sortType = this.sorter.order === 'ascend' ? 'asc' : 'desc'; // @ts-ignore dataset.orderBy = `${this.sorter.field} ${sortType}`; } dataset.fromIndex = this.paginationOptions.pageSize * (this.paginationOptions.current - 1 || 0); dataset.toIndex = dataset.fromIndex + this.paginationOptions.pageSize - 1; } return await getFeatures(dataset); } } toTableContent(features) { let content = []; features && features.forEach((feature, index) => { let properties = feature.properties; let coordinates = feature.geometry && feature.geometry.coordinates; if (!properties) { return; } !properties.index && (properties.index = index); if (coordinates && coordinates.length) { this.featureMap[properties.index] = feature; } properties.key = +properties.index; JSON.stringify(properties) !== '{}' && content.push(properties); }); return content; } toTableColumns(headers) { let columns = []; Object.keys(headers).forEach(propertyName => { let columnConfig = { title: propertyName, dataIndex: propertyName, visible: true }; if (typeof +headers[propertyName] === 'number' && !isNaN(+headers[propertyName])) { // @ts-ignore columnConfig.sorter = (a, b) => a[propertyName] - b[propertyName]; } // @ts-ignore if (this.fieldConfigs && this.fieldConfigs.length) { // @ts-ignore const config = this.fieldConfigs.find(fieldConfig => { return fieldConfig.value === propertyName; }); if (config) { let copyConfig = clonedeep(config); copyConfig.dataIndex = copyConfig.value; delete copyConfig.value; columnConfig = mergewith(columnConfig, copyConfig, (obj, src) => { if (typeof src === 'undefined') { return obj; } }); // @ts-ignore if (columnConfig.sorter && typeof columnConfig.sorter === 'boolean') { // @ts-ignore columnConfig.sorter = (a, b) => a[propertyName] - b[propertyName]; } // @ts-ignore if (columnConfig.search) { // @ts-ignore if (!columnConfig.onFilter) { // @ts-ignore columnConfig.onFilter = (value, record) => { return (record[propertyName] + '').includes(value); }; } // @ts-ignore columnConfig.scopedSlots = { filterDropdown: 'filterDropdown', filterIcon: 'filterIcon', customRender: 'customRender' }; } // @ts-ignore if (!columnConfig.customCell) { // @ts-ignore columnConfig.customCell = record => { return { attrs: { title: record[copyConfig.dataIndex] } }; }; } } } columns.push(columnConfig); }); let columnOrder = []; let columnsResult = []; // @ts-ignore this.fieldConfigs && this.fieldConfigs.forEach(element => { columnOrder.push(element.value); }); columnOrder.forEach(str => { columns.forEach(element => { if (element.dataIndex === str) { columnsResult.push(element); } }); }); return columnsResult.length === 0 ? columns : columnsResult; } handleCoords(selectedKeys) { let highLightList = {}; selectedKeys.forEach(key => { if (this.featureMap[key]) { highLightList[key] = this.featureMap[key]; } }); return highLightList; } useDataset() { return !!(this.dataset && (this.dataset.url || this.dataset.geoJSON)); } canLazyLoad() { return this.lazy && this.dataset && this.dataset.url && this.dataset.type === 'iServer'; } handleAssociateWithMap() { if (this.associateWithMap.enabled && this.layerName) { this.enableSelectFeature(); } else { this.disableSelectFeature(); } } clearSelectedRows() { this.fire('clearselectedrows'); } removed() { this.map.getLayer(this.layerId) && this.map.removeLayer(this.layerId); this.map.getLayer(this.strokeLayerID) && this.map.removeLayer(this.strokeLayerID); this.map.getSource(this.sourceId) && this.map.removeSource(this.sourceId); this.map = null; } } export default FeatureTableViewModel;
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace mybusinessnotifications_v1 { export interface Options extends GlobalOptions { version: 'v1'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * My Business Notifications API * * The My Business Notification Settings API enables managing notification settings for business accounts. * * @example * ```js * const {google} = require('googleapis'); * const mybusinessnotifications = google.mybusinessnotifications('v1'); * ``` */ export class Mybusinessnotifications { context: APIRequestContext; accounts: Resource$Accounts; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.accounts = new Resource$Accounts(this.context); } } /** * A Google Pub/Sub topic where notifications can be published when a location is updated or has a new review. There will be only one notification setting resource per-account. */ export interface Schema$NotificationSetting { /** * Required. The resource name this setting is for. This is of the form `accounts/{account_id\}/notificationSetting`. */ name?: string | null; /** * The types of notifications that will be sent to the Pub/Sub topic. To stop receiving notifications entirely, use NotificationSettings.UpdateNotificationSetting with an empty notification_types or set the pubsub_topic to an empty string. */ notificationTypes?: string[] | null; /** * Optional. The Google Pub/Sub topic that will receive notifications when locations managed by this account are updated. If unset, no notifications will be posted. The account mybusiness-api-pubsub@system.gserviceaccount.com must have at least Publish permissions on the Pub/Sub topic. */ pubsubTopic?: string | null; } export class Resource$Accounts { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Returns the pubsub notification settings for the account. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/mybusinessnotifications.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const mybusinessnotifications = google.mybusinessnotifications('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await mybusinessnotifications.accounts.getNotificationSetting({ * // Required. The resource name of the notification setting we are trying to fetch. * name: 'accounts/my-account/notificationSetting', * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "notificationTypes": [], * // "pubsubTopic": "my_pubsubTopic" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ getNotificationSetting( params: Params$Resource$Accounts$Getnotificationsetting, options: StreamMethodOptions ): GaxiosPromise<Readable>; getNotificationSetting( params?: Params$Resource$Accounts$Getnotificationsetting, options?: MethodOptions ): GaxiosPromise<Schema$NotificationSetting>; getNotificationSetting( params: Params$Resource$Accounts$Getnotificationsetting, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; getNotificationSetting( params: Params$Resource$Accounts$Getnotificationsetting, options: MethodOptions | BodyResponseCallback<Schema$NotificationSetting>, callback: BodyResponseCallback<Schema$NotificationSetting> ): void; getNotificationSetting( params: Params$Resource$Accounts$Getnotificationsetting, callback: BodyResponseCallback<Schema$NotificationSetting> ): void; getNotificationSetting( callback: BodyResponseCallback<Schema$NotificationSetting> ): void; getNotificationSetting( paramsOrCallback?: | Params$Resource$Accounts$Getnotificationsetting | BodyResponseCallback<Schema$NotificationSetting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$NotificationSetting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$NotificationSetting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$NotificationSetting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Accounts$Getnotificationsetting; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Accounts$Getnotificationsetting; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://mybusinessnotifications.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$NotificationSetting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$NotificationSetting>(parameters); } } /** * Sets the pubsub notification setting for the account informing Google which topic to send pubsub notifications for. Use the notification_types field within notification_setting to manipulate the events an account wants to subscribe to. An account will only have one notification setting resource, and only one pubsub topic can be set. To delete the setting, update with an empty notification_types * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/mybusinessnotifications.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const mybusinessnotifications = google.mybusinessnotifications('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await mybusinessnotifications.accounts.updateNotificationSetting({ * // Required. The resource name this setting is for. This is of the form `accounts/{account_id\}/notificationSetting`. * name: 'accounts/my-account/notificationSetting', * // Required. The specific fields that should be updated. The only editable field is notification_setting. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "name": "my_name", * // "notificationTypes": [], * // "pubsubTopic": "my_pubsubTopic" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "notificationTypes": [], * // "pubsubTopic": "my_pubsubTopic" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ updateNotificationSetting( params: Params$Resource$Accounts$Updatenotificationsetting, options: StreamMethodOptions ): GaxiosPromise<Readable>; updateNotificationSetting( params?: Params$Resource$Accounts$Updatenotificationsetting, options?: MethodOptions ): GaxiosPromise<Schema$NotificationSetting>; updateNotificationSetting( params: Params$Resource$Accounts$Updatenotificationsetting, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; updateNotificationSetting( params: Params$Resource$Accounts$Updatenotificationsetting, options: MethodOptions | BodyResponseCallback<Schema$NotificationSetting>, callback: BodyResponseCallback<Schema$NotificationSetting> ): void; updateNotificationSetting( params: Params$Resource$Accounts$Updatenotificationsetting, callback: BodyResponseCallback<Schema$NotificationSetting> ): void; updateNotificationSetting( callback: BodyResponseCallback<Schema$NotificationSetting> ): void; updateNotificationSetting( paramsOrCallback?: | Params$Resource$Accounts$Updatenotificationsetting | BodyResponseCallback<Schema$NotificationSetting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$NotificationSetting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$NotificationSetting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$NotificationSetting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Accounts$Updatenotificationsetting; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Accounts$Updatenotificationsetting; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://mybusinessnotifications.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$NotificationSetting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$NotificationSetting>(parameters); } } } export interface Params$Resource$Accounts$Getnotificationsetting extends StandardParameters { /** * Required. The resource name of the notification setting we are trying to fetch. */ name?: string; } export interface Params$Resource$Accounts$Updatenotificationsetting extends StandardParameters { /** * Required. The resource name this setting is for. This is of the form `accounts/{account_id\}/notificationSetting`. */ name?: string; /** * Required. The specific fields that should be updated. The only editable field is notification_setting. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$NotificationSetting; } }
the_stack
import {readFileSync} from 'fs'; import {Utility} from '../misc/utility'; import {UnifiedPath} from '../misc/unifiedpath'; import {SourceFileEntry, ListFileLine} from './labels'; import {AsmConfigBase} from '../settings'; import * as minimatch from 'minimatch'; /** * This class is the base class for the assembler list file parsers. */ export class LabelParserBase { /// Map that associates memory addresses (PC values) with line numbers /// and files. /// Long addresses. protected fileLineNrs: Map<number, SourceFileEntry>; /// Map of arrays of line numbers. The key of the map is the filename. /// The array contains the correspondent memory address for the line number. /// Long addresses. protected lineArrays: Map<string, Array<number>>; /// An element contains either the offset from the last /// entry with labels or an array of labels for that number. /// Array contains a max 0x10000 entries. Thus it is for /// 64k addresses. protected labelsForNumber64k: Array<any>; /// This map is used to associate long addresses with labels. /// E.g. used for the call stack. /// Long addresses. protected labelsForLongAddress = new Map<number, Array<string>>(); /// Map with all labels (from labels file) and corresponding values. /// Long addresses. protected numberForLabel = new Map<string, number>(); /// Map with label / file location association. /// Does not store local labels. /// Is used only for unit tests. /// Long addresses. protected labelLocations: Map<string, {file: string, lineNr: number, address: number}>; /// Stores the address of the watchpoints together with the line contents. /// Long addresses. protected watchPointLines: Array<{address: number, line: string}>; /// Stores the address of the assertions together with the line contents. /// Long addresses. protected assertionLines: Array<{address: number, line: string}>; /// Stores the address of the logpoints together with the line contents. /// Long addresses. protected logPointLines: Array<{address: number, line: string}>; /// The config structure is stored here. protected config: AsmConfigBase; /// Array used temporary. Holds the converted list file. protected listFile: Array<ListFileLine>; /// Several prefixes might be stacked (a MODULE can happen inside a MODULE) protected modulePrefixStack: Array<string>; // Only used for sjasmplus /// Used for found MODULEs protected modulePrefix: string; protected lastLabel: string; // Only used for sjasmplus for local labels (without modulePrefix) /// The separator used for local labels and modules. /// Normally a dot, but could also be defined otherwise. protected labelSeparator = '.'; /// Holds the list file entry for the current line. protected currentFileEntry: ListFileLine; /// The stack of include files. For parsing filenames and line numbers. protected includeFileStack: Array<{fileName: string, lineNr: number}>; /// Used to determine if current (included) files are used or excluded in the addr <-> file search. protected excludedFileStackIndex: number; // Collects the warnings. protected warnings: string; // Constructor. public constructor( fileLineNrs: Map<number, SourceFileEntry>, lineArrays: Map<string, Array<number>>, labelsForNumber64k: Array<any>, labelsForLongAddress: Map<number, Array<string>>, numberForLabel: Map<string, number>, labelLocations: Map<string, {file: string, lineNr: number, address: number}>, watchPointLines: Array<{address: number, line: string}>, assertionLines: Array<{address: number, line: string}>, logPointLines: Array<{address: number, line: string}> ) { // Store variables this.fileLineNrs = fileLineNrs; this.lineArrays = lineArrays; this.labelsForNumber64k = labelsForNumber64k; this.labelsForLongAddress = labelsForLongAddress; this.numberForLabel = numberForLabel; this.labelLocations = labelLocations; this.watchPointLines = watchPointLines; this.assertionLines = assertionLines; this.logPointLines = logPointLines; this.warnings = ''; } /** * Reads the given file (an assembler .list file) and extracts all PC * values (the first 4 digits), so that each line can be associated with a * PC value. */ public loadAsmListFile(config: AsmConfigBase) { this.config=config; // Init (in case of several list files) this.excludedFileStackIndex=-1; this.includeFileStack=new Array<{fileName: string, lineNr: number}>(); this.listFile=new Array<ListFileLine>(); this.modulePrefixStack=new Array<string>(); this.modulePrefix=undefined as any; this.lastLabel=undefined as any; // Phase 1: Parse for labels and addresses this.parseAllLabelsAndAddresses(); // Check if Listfile-Mode if (config.srcDirs.length==0) { // Listfile-Mode this.listFileModeFinish(); return; } // Phase 2: Parse for source files this.parseAllFilesAndLineNumbers(); // Finish: Create fileLineNrs, lineArrays and labelLocations this.sourcesModeFinish(); } /** * Loops all lines of the list file and parses for labels and the addresses * for each line. */ protected parseAllLabelsAndAddresses() { // Loop through all lines const fileName=Utility.getRelFilePath(this.config.path); const listLinesFull = readFileSync(this.config.path).toString().split('\n'); // Strip away windows line endings const listLines = listLinesFull.map(line => line.trimRight()); let lineNr=0; for (let line of listLines) { // Prepare an entry this.currentFileEntry={fileName, lineNr, addr: undefined, size: 0, line, modulePrefix: this.modulePrefix, lastLabel: this.lastLabel}; this.listFile.push(this.currentFileEntry); // Parse this.parseLabelAndAddress(line); // Check for WPMEM, ASSERTION and LOGPOINT const address=this.currentFileEntry.addr; this.findWpmemAssertionLogpoint(address, line); // Next lineNr++; } } /** * Loops all entries of the listFile array and parses for the (include) file * names and line numbers. * @param startLineNr The line number to start the loop with. I.e. sometimes the * beginning of the list file contains information that is parsed differently. */ protected parseAllFilesAndLineNumbers(startLineNr = 0) { // Loop all lines const count=this.listFile.length; for (let listFileNumber=startLineNr; listFileNumber<count; listFileNumber++) { const entry=this.listFile[listFileNumber]; const line=entry.line; if (line.length==0) continue; // Let it parse this.currentFileEntry=entry; this.parseFileAndLineNumber(line); // Associate with right file const index=this.includeFileStack.length-1; if (index<0) continue; // No main file found so far //throw Error("File parsing error: no main file."); // Associate with right file this.associateSourceFileName(); } } /** * Parses the line for comments with WPMEM, ASSERTION or LOGPOINT. * Note: This only collect the lines. Parsing is done at a * later state when all labels are known. * @param address The address that correspondents to the line. * @param fullLine The line of the list file as string. */ protected findWpmemAssertionLogpoint(address: number|undefined, fullLine: string) { // Extract just comment const comment=this.getComment(fullLine); // WPMEM let match=/.*(\bWPMEM([\s,]|$).*)/.exec(comment); if (match) { // Add watchpoint at this address /* if (this.currentFileEntry&&this.currentFileEntry.size==0) this.watchPointLines.push({address: undefined as any, line: match[1]}); // watchpoint inside a macro or without data -> Does not work: WPMEM could be on a separate line else */ this.watchPointLines.push({address: address!, line: match[1]}); } if (address==undefined) return; // ASSERTION match =/.*(\bASSERTION([\s,]|$).*)/.exec(comment); if (match) { // Add ASSERTION at this address this.assertionLines.push({address, line: match[1]}); } // LOGPOINT match =/.*(\bLOGPOINT([\s,]|$).*)/.exec(comment); if (match) { // Add logpoint at this address this.logPointLines.push({address, line: match[1]}); } } /** * Check the list file line for a comment and returns just the comment. * Only override if you allow other line comment identifiers than ";". * @param line The line of the list file as string. E.g. "5 A010 00 00 00... defs 0x10 ; WPMEM, 5, w" * @returns Just the comment, e.g. the text after ";". E.g. " WPMEM, 5, w" */ protected getComment(line: string): string { const i=line.indexOf(";"); if (i<0) return ""; // No comment const comment=line.substr(i+1); return comment; } /** * Will check if the name is excluded (excludedFiles). * If so the source filename is not set to the source file name so that it * is "" and will be ignored. */ protected associateSourceFileName() { let fName=""; if (this.excludedFileStackIndex==-1) { // Not excluded const index=this.includeFileStack.length-1; if(index>=0) // safety check fName=this.includeFileStack[index].fileName; } this.currentFileEntry.fileName=fName; } /** * Finishes the list file mode. * Puts filename (the list file name) and line numbers into the * this.fileLineNrs and this.lineArrays structures. */ protected listFileModeFinish() { // Use list file directly instead of real filenames. const lineArray=new Array<number>(); const fileName=Utility.getRelFilePath(this.config.path); this.lineArrays.set(fileName, lineArray); for (const entry of this.listFile) { // Create label -> file location association const lastLabel=entry.lastLabel; if (lastLabel) { const fullLabel=this.getFullLabel(entry.modulePrefix, lastLabel); let fileLoc=this.labelLocations.get(fullLabel); if (!fileLoc) { // Add new file location const address: number = entry.addr!; fileLoc = {file: entry.fileName, lineNr: entry.lineNr, address}; this.labelLocations.set(fullLabel, fileLoc); } } // Check address if (entry.addr == undefined) continue; const prevFileLine = this.fileLineNrs.get(entry.addr); if (!prevFileLine || entry.size > 0) { // write new value this.fileLineNrs.set(entry.addr, {fileName: entry.fileName, lineNr: entry.lineNr, modulePrefix: entry.modulePrefix, lastLabel: entry.lastLabel}); } // Set address if (!lineArray[entry.lineNr]) { // without the check macros would lead to the last addr being stored. lineArray[entry.lineNr]=entry.addr; //console.log('filename='+entry.fileName+', lineNr='+realLineNr+', addr='+Utility.getHexString(entry.addr, 4)); } } } /** * Finishes the sources mode. * Puts filename (the list file name) and line numbers into the * this.labelLocations, this.fileLineNrs and this.lineArrays structures. */ protected sourcesModeFinish() { for (const entry of this.listFile) { if (entry.fileName.length==0) continue; // Skip lines with no filename (e.g. '# End of file') // Create label -> file location association const lastLabel=entry.lastLabel; if (lastLabel) { const fullLabel=this.getFullLabel(entry.modulePrefix, lastLabel); let fileLoc=this.labelLocations.get(fullLabel); if (!fileLoc) { // Add new file location const address: number = entry.addr!; fileLoc={file: entry.fileName, lineNr: entry.lineNr, address}; this.labelLocations.set(fullLabel, fileLoc); } } // Check address if (!entry.addr) continue; // last address entry wins: for (let i=0; i<entry.size; i++) { const addr=(i==0) ? entry.addr : (entry.addr+i)&0xFFFF; // Don't mask entry addr if size is 1, i.e. for sjasmplus sld allow higher addresses this.fileLineNrs.set(addr, {fileName: entry.fileName, lineNr: entry.lineNr, modulePrefix: entry.modulePrefix, lastLabel: entry.lastLabel}); } // Check if a new array need to be created if (!this.lineArrays.get(entry.fileName)) { this.lineArrays.set(entry.fileName, new Array<number>()); } // Get array const lineArray=this.lineArrays.get(entry.fileName)!; // Set address if (!lineArray[entry.lineNr]) { // without the check macros would lead to the last addr being stored. lineArray[entry.lineNr]=entry.addr; } } } /** * Override. * Parses one line for label and address. * Finds labels at start of the line and labels as EQUs. * Also finds the address of the line. * The function calls addLabelForNumber to add a label or equ and * addAddressLine to add the line and it's address. * @param line The current analyzed line of the list file. */ protected parseLabelAndAddress(line: string) { Utility.assert(false, "Override parseLabelAndAddress"); } /** * Override. * Parses one line for current file name and line number in this file. * The function determines the line number from the list file. * The line number is the line number in the correspondent source file. * Note: this is not the line number of the list file. * The list file may include other files. It's the line number of those files we are after. * Call 'setLineNumber' with the line number to set it. Note that source file numbers start at 0. * Furthermore it also determines the beginning and ending of include files. * Call 'includeStart(fname)' and 'includeEnd()'. * @param line The current analyzed line of the listFile array. */ protected parseFileAndLineNumber(line: string) { Utility.assert(false, "Override parseFileAndLineNumber"); } /** * Called by the parser if a new module is found. * @param moduleName The name of the module. */ protected moduleStart(moduleName: string) { this.modulePrefixStack.push(moduleName); this.modulePrefix=this.modulePrefixStack.join(this.labelSeparator)+this.labelSeparator; this.currentFileEntry.modulePrefix=this.modulePrefix; // Init last label this.lastLabel=undefined as any; this.currentFileEntry.lastLabel=this.lastLabel; } /** * Called by the parser if a module end is found. */ protected moduleEnd() { // Remove last prefix this.modulePrefixStack.pop(); if (this.modulePrefixStack.length>0) this.modulePrefix=this.modulePrefixStack.join(this.labelSeparator)+this.labelSeparator; else this.modulePrefix=undefined as any; this.currentFileEntry.modulePrefix=this.modulePrefix; // Forget last label this.lastLabel=undefined as any; this.currentFileEntry.lastLabel=this.lastLabel; } /** * Adds a new label to the labelsForNumber64k array. * Creates a new array if required. * Adds the the label/value pair also to the numberForLabelMap. * Don't use for EQUs > 64k. * On the other hand long addresses can be passed. * I.e. everything > 64k is interpreted as long address. * Handles 64k and long addresses. * @param value The value for which a new label is to be set. If a value > 64k it needs * to be a long address. * I.e. EQU values > 64k are not allowed here. * @param label The label to add. */ protected addLabelForNumber(value: number, label: string,) { // Remember last label (for local labels) this.lastLabel = label; this.currentFileEntry.lastLabel = this.lastLabel; this.currentFileEntry.modulePrefix = undefined; this.addLabelForNumberRaw(value, label); } /** * Adds a new label to the labelsForNumber64k array. * Creates a new array if required. * Adds the the label/value pair also to the numberForLabelMap. * Don't use for EQUs > 64k. * On the other hand long addresses can be passed. * I.e. everything > 64k is interpreted as long address. * Handles 64k and long addresses. * @param value The value for which a new label is to be set. If a value > 64k it needs * to be a long address. * I.e. EQU values > 64k are not allowed here. * @param label The label to add. * @param labelType I.e. NORMAL, LOCAL or GLOBAL. */ protected addLabelForNumberRaw(value: number, label: string) { // Label: add to label array, long address this.numberForLabel.set(label, value); // Add label to labelsForNumber64k (just 64k address) const value64k = value & 0xFFFF; let labelsArray = this.labelsForNumber64k[value64k]; //console.log("labelsArray", labelsArray, "value=", value); if (labelsArray === undefined) { // create a new array labelsArray = new Array<string>(); this.labelsForNumber64k[value64k] = labelsArray; } // Check if label already exists if (labelsArray.indexOf(label) < 0) labelsArray.push(label); // Add new label // Add label to labelsForLongAddress labelsArray = this.labelsForLongAddress.get(value); //console.log("labelsArray", labelsArray, "value=", value); if (labelsArray === undefined) { // create a new array labelsArray = new Array<string>(); this.labelsForLongAddress.set(value, labelsArray); } // Check if label already exists if (labelsArray.indexOf(label) < 0) labelsArray.push(label); // Add new label } /** * Adds the address to the list file array. * Call this even if size is 0. The addresses are also required for * lines that may contain only a comment, e.g. LOGPOINT, WPMEM, ASSERTION: * @param address The address of the line. Could be undefined. * @param size The size of the line. E.g. for a 2 byte instruction this is 2. * Has to be 1 if address is undefined. */ protected addAddressLine(address: number, size: number) { this.currentFileEntry.addr=address; this.currentFileEntry.size=size; } /** * Create complete label from module prefix and relative label * @param modulePrefix The first part of the label, e.g. "math." * @param label The last part of the label, e.g. "udiv_c_d" */ protected getFullLabel(modulePrefix: string|undefined, label: string) { let result=modulePrefix||''; if (result.length==0) return label; result+=label; return result; } /** * Called by the parser if a new include file is found. * Is also used to set the main file at the beginning of parsing or before parsing starts. * @param includeFileName The name of the include file. */ protected includeStart(includeFileName: string) { includeFileName=UnifiedPath.getUnifiedPath(includeFileName); const index=this.includeFileStack.length-1; let fileName; if (index>=0) { // Include the parent file dir in search const parentFileName=this.includeFileStack[this.includeFileStack.length-1].fileName; const dirName=UnifiedPath.dirname(parentFileName); fileName=Utility.getRelSourceFilePath(includeFileName, [dirName, ...this.config.srcDirs]); } else { // Main file fileName=Utility.getRelSourceFilePath(includeFileName, this.config.srcDirs); } this.includeFileStack.push({fileName, lineNr: 0}); // Now check if we need to exclude it from file/line <-> address relationship. if (this.excludedFileStackIndex==-1) { // Check if filename is one of the excluded file names. for (const exclGlob of this.config.excludeFiles) { const found=minimatch(fileName, exclGlob); if (found) { this.excludedFileStackIndex=index+1; break; } } } } /** * Called by the parser if the end of an include file is found. */ protected includeEnd() { if (this.includeFileStack.length==0) throw Error("File parsing error: include file stacking."); // Remove last include file this.includeFileStack.pop(); // Check if excluding files ended const index=this.includeFileStack.length; if (this.excludedFileStackIndex==index) { // Stop excluding this.excludedFileStackIndex=-1; } } /** * Called by the parser to set the line number parsed from the list file. * This is the line number inside an include file. * Should be called before 'includeStart' and 'includeEnd'. * But is not so important as there is no assembler code in these lines. * @param lineNr The parsed line number. Note this line number has to start at 0. */ protected setLineNumber(lineNr: number) { this.currentFileEntry.lineNr=lineNr; } /** * Creates a long address from the address and the page info. * This is overwritten by parsers that use it, e.g. sjasmplussdllabelparser. * @param address The 64k address, i.e. the upper bits are the slot index. * @param bank The bank the address is associated with. * @returns if bankSize: address+((page+1)<<16) * else: address. */ protected createLongAddress(address: number, bank: number) { return address; } /** * Returns the collected warnings. * undefined if no warnings. */ public getWarnings() { return this.warnings; } }
the_stack
import Parser from './Parser'; const abbreviatedTimezones = 'UT|' // https://www.timeanddate.com/time/zones/africa + 'CAT|CET|CVT|EAT|EET|GMT|MUT|RET|SAST|SCT|WAST|WAT|WEST|WET|WST|WT|' // https://www.timeanddate.com/time/zones/asia + 'ADT|AFT|ALMT|AMST|AMT|ANAST|ANAT|AQTT|AST|AZST|AZT|BNT|BST|BTT|CHOST|CHOT|' + 'CST|EEST|EET|GET|GST|HKT|HOVST|HOVT|ICT|IDT|IRDT|IRKST|IRKT|IST|JST|KGT|KRAST|' + 'KRAT|KST|MAGST|MAGT|MMT|MSK|MVT|NOVST|NOVT|NPT|OMSST|OMST|ORAT|PETST|PETT|PHT|' + 'PKT|PYT|QYZT|SAKT|SGT|SRET|TJT|TLT|TMT|TRT|ULAST|ULAT|UZT|VLAST|VLAT|WIB|WIT|' + 'YAKST|YAKT|YEKST|YEKT|' // https://www.timeanddate.com/time/zones/antarctica + 'ART|CAST|CEST|CLST|CLT|DAVT|DDUT|GMT|MAWT|NZDT|NZST|ROTT|SYOT|VOST|' // https://www.timeanddate.com/time/zones/atlantic + 'ADT|AST|AT|AZOST|AZOT|' // https://www.timeanddate.com/time/zones/au + 'ACDT|ACST|ACT|ACWST|AEDT|AEST|AET|AWDT|AWST|CXT|LHDT|LHST|NFDT|NFT|' // https://www.timeanddate.com/time/zones/caribbean + 'AST|AT|CDT|CIDST|CIST|CST|EDT|EST|ET|' // https://www.timeanddate.com/time/zones/ca + 'CST|CT|EST|ET|' // https://www.timeanddate.com/time/zones/eu + 'BST|CEST|CET|EEST|EET|FET|GET|GMT|IST|KUYT|MSD|MSK|SAMT|TRT|WEST|WET|' // https://www.timeanddate.com/time/zones/indian-ocean + 'CCT|EAT|IOT|TFT|' // https://www.timeanddate.com/time/zones/na + 'ADT|AKDT|AKST|AST|AT|CDT|CST|CT|EDT|EGST|EGT|ET|GMT|HDT|HST|MDT|MST|MT|NDT|NST|PDT|PMDT|PMST|PST|PT|WGST|WGT|' // https://www.timeanddate.com/time/zones/pacific + 'AoE|BST|CHADT|CHAST|CHUT|CKT|ChST|EASST|EAST|FJST|FJT|GALT|GAMT|GILT|HST|KOST|LINT|MART|' + 'MHT|NCT|NRT|NUT|NZDT|NZST|PGT|PHOT|PONT|PST|PWT|SBT|SST|TAHT|TKT|TOST|TOT|TVT|VUT|WAKT|WFT|WST|YAPT|' // https://www.timeanddate.com/time/zones/sa + 'ACT|AMST|AMT|ART|BOT|BRST|BRT|CLST|CLT|COT|ECT|FKST|FKT|FNT|GFT|GST|GYT|PET|PYST|PYT|SRT|UYST|UYT|VET|WARST'; /** * Date only * * - 1 Jan * - 1 January * - 1st Jan * - 1st January * - 01 Jan * - 01 January * * Date with time * * - 1 Jan, 10:00 AM * - Sunday, 1st January, 23:00 */ const dayOfMonthAndMonthNameDateFormatParser = new Parser( 'DayOfMonthAndMonthNameDateFormatParser', new RegExp('^' + '(?<dayOfWeek>(?:Sun?|Mon?|Tu(?:es)?|We(?:dnes)?|Th(?:urs)?|Fri?|Sa(?:tur)?)(?:day)?)?' + '(?<delim1>,)?' + '(?<delim2>\\s)?' + '(?<dayOfMonth>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:st|nd|rd|th)?)' + '(?<delim3>\\s)' + '(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?' + '|' + 'July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)' + '(?<delim4>,)?' + '(?<delim5>\\s)?' + '(?<year>\\d{4}|\\d{2})?' + '(?:' + '(?<delim6>,)?' + '(?<delim7>\\s)' + '(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))' + '(?:' + '(?<delim8>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim9>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim10>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim11>\\s)?' + '(?<meridiem>am|pm|AM|PM)?' + '(?:' + '(?<delim12>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + ')?' + '$' ) ); /** * ISO 8601 * https://en.wikipedia.org/wiki/ISO_8601 */ const iSO8601BasicDateTimeFormatParser = new Parser( 'ISO8601BasicDateTimeFormatParser', new RegExp('^' + '(?<year>[+-]\\d{6}|\\d{4})' + '(?:' + '(?<month>\\d{2})(?:(?<dayOfMonth>\\d{2}))?' + '|' + '(?<escapeText>W)(?<isoWeekOfYear>\\d{2})(?:(?<isoDayOfWeek>\\d))?' + '|' + '(?<dayOfYear>\\d{3})' + ')?' + '(?:' + '(?<delim1>T| )' + '(?:(?<twentyFourHour>\\d{2})(?:(?<minute>\\d{2})(?:(?<second>\\d{2})(?:(?<delim2>[.,])(?<millisecond>\\d{1,9}))?)?)?)' + '(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z)?' + ')?' + '$' ) ); /** * ISO 8601 * https://en.wikipedia.org/wiki/ISO_8601 */ const iSO8601ExtendedDateTimeFormatParser = new Parser( 'ISO8601ExtendedDateTimeFormatParser', new RegExp('^' + '(?<year>[+-]\\d{6}|\\d{4})' + '(?<delim1>\\-)' + '(?:' + '(?<month>\\d{2})(?:(?<delim2>\\-)(?<dayOfMonth>\\d{2}))?' + '|' + '(?<escapeText>W)(?<isoWeekOfYear>\\d{2})(?:(?<delim3>\\-)(?<isoDayOfWeek>\\d))?' + '|' + '(?<dayOfYear>\\d{3})' + ')' + '(?:' + '(?<delim4>T| )' + '(?:(?<twentyFourHour>\\d{2})(?:(?<delim5>:)(?<minute>\\d{2})(?:(?<delim6>:)(?<second>\\d{2})(?:(?<delim7>[.,])(?<millisecond>\\d{1,9}))?)?)?)' + '(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z)?' + ')?' + '$' ) ); /** * Date only * * - Jan 1 * - January 1 * - Jan 1st * - January 1st * - Jan 01 * - January 01 * * Date with time * * - Jan 1, 10:00 AM * - Sunday, January 1st, 23:00 * - Sunday, January 1st, 23:00 PDT */ const monthNameAndDayOfMonthDateFormatParser = new Parser( 'MonthNameAndDayOfMonthDateFormatParser', new RegExp('^' + '(?<dayOfWeek>(?:Sun?|Mon?|Tu(?:es)?|We(?:dnes)?|Th(?:urs)?|Fri?|Sa(?:tur)?)(?:day)?)?' + '(?<delim1>,)?' + '(?<delim2>\\s)?' + '(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?' + '|' + 'July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)' + '(?<delim3>\\s)' + '(?<dayOfMonth>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:st|nd|rd|th)?)' + '(?<delim4>,)?' + '(?<delim5>\\s)?' + '(?<year>\\d{4}|\\d{2})?' + '(?:' + '(?:' + '(?<delim6>,)?' + '(?<delim7>\\s)' + '(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))' + '(?:' + '(?<delim8>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim9>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim10>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim11>\\s)?' + '(?<meridiem>am|pm|AM|PM)?' + '(?:' + '(?<delim12>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + ')?' + ')?' + '$' ) ); /** * RFC 2822 * https://tools.ietf.org/html/rfc2822#section-3.3 */ const rFC2822DateTimeFormatParser = new Parser( 'RFC2822DateTimeFormatParser', new RegExp('^' + '(?:(?<dayOfWeek>Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?<delim1>,)?(?<delim2>\\s))?' + '(?<dayOfMonth>\\d{1,2})(?<delim3>\\s)(?<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(?<delim4>\\s)(?<year>\\d{2,4})' + '(?<delim5>\\s)' + '(?<twentyFourHour>\\d{2})(?<delim6>:)(?<minute>\\d{2})(?:(?<delim7>:)(?<second>\\d{2}))?' + '(?<delim8>\\s)' + '(?<timezone>(?:(?:UT|GMT|[ECMP][SD]T)|[Zz]|[+-]\\d{4}))' + '$' ) ); /* * YYYY/MM/DD [hh:mm a|A [abbr-tz]] * YYYY/M/D * YYYY/MM * YYYY/M */ const slashDelimitedDateTimeFormatParser = new Parser( 'SlashDelimitedDateFormatParser', new RegExp('^' + '(?<year>\\d{4}|\\d{2})' + '(?<delim1>[/.-])' + '(?<month>0?[1-9]|1[0-2])' + '(?:' + '(?<delim2>[/.-])' + '(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])' + ')?' + '(?:' + '(?:' + '(?<delim3>,)?' + '(?<delim4>\\s)' + '(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))' + '(?:' + '(?<delim5>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim6>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim7>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim8>\\s)?' + '(?<meridiem>am|pm|AM|PM)?' + '(?:' + '(?<delim9>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + ')?' + ')?' + '$' ) ); /** * hh:mm[AP]M * hh:mm[AP]M [abbr-tz] * hh[AP]M */ const twelveHourTimeFormatParser = new Parser( 'TwelveHourTimeFormatParser', new RegExp('^' + '(?<twelveHour>0?[1-9]|1[0-2])' + '(?:' + '(?<delim1>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim2>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim3>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim4>\\s)?' + '(?<meridiem>am|pm|AM|PM)' + '(?:' + '(?<delim5>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + '$' ) ); /** * HH:mm:ss[.ddd] * HH:mm * HH.mm.ss Z */ const twentyFourHourTimeFormatParser = new Parser( 'TwentyFourHourTimeFormatParser', new RegExp('^' + '(?<twentyFourHour>2[0-3]|0?\\d|1\\d)' + '(?<delim1>[:.])' + '(?<minute>[0-5]\\d)' + '(?:' + '(?<delim2>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim3>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?:' + '(?<delim4>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + '$' ) ); /* * UK style * * - DD/MM/YYYY * - D/M/YYYY * - DD/MM/YY * - DD/MM */ const uKStyleSlashDelimitedDateTimeFormatParser = new Parser( 'UKStyleSlashDelimitedDateFormatParser', new RegExp('^' + '(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])' + '(?<delim1>[/.-])' + '(?<month>0?[1-9]|1[0-2])' + '(?:' + '(?<delim2>[/.-])' + '(?<year>\\d{4}|\\d{2})' + ')?' + '(?:' + '(?:' + '(?<delim3>,)?' + '(?<delim4>\\s)' + '(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))' + '(?:' + '(?<delim5>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim6>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim7>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim8>\\s)?' + '(?<meridiem>am|pm|AM|PM)?' + '(?:' + '(?<delim9>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + ')?' + ')?' + '$' ) ); /* * US style * * - MM/DD/YYYY * - M/D/YYYY * * - MM/DD/YY * - M/D/YY * * - MM/DD * - M/D */ const uSStyleSlashDelimitedDateTimeFormatParser = new Parser( 'USStyleSlashDelimitedDateFormatParser', new RegExp('^' + '(?<month>0?[1-9]|1[0-2])' + '(?<delim1>[/.-])' + '(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])' + '(?:' + '(?<delim2>[/.-])' + '(?<year>\\d{4}|\\d{2})' + ')?' + '(?:' + '(?:' + '(?<delim3>,)?' + '(?<delim4>\\s)' + '(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))' + '(?:' + '(?<delim5>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim6>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim7>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim8>\\s)?' + '(?<meridiem>am|pm|AM|PM)?' + '(?:' + '(?<delim9>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + ')?' + ')?' + '$' ) ); const dashDelimitedWithMonthNameDateTimeFormatParser = new Parser( 'DashDelimitedWithMonthNameDateTimeFormatParser', new RegExp('^' + '(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])' + '(?<delim1>-)' + '(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?' + '|' + 'July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)' + '(?<delim2>-)?' + '(?<year>\\d{4}|\\d{2})?' + '(?:' + '(?:' + '(?<delim3>,)?' + '(?<delim4>\\s)' + '(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))' + '(?:' + '(?<delim5>[:.])' + '(?<minute>[0-5]\\d)' + ')?' + '(?:' + '(?<delim6>[:.])' + '(?<second>[0-5]\\d)' + ')?' + '(?:' + '(?<delim7>.)' + '(?<millisecond>\\d{3})' + ')?' + '(?<delim8>\\s)?' + '(?<meridiem>am|pm|AM|PM)?' + '(?:' + '(?<delim9>\\s)' + `(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones})` + ')?' + ')?' + ')?' + '$' ) ); const parsers = [ iSO8601ExtendedDateTimeFormatParser, iSO8601BasicDateTimeFormatParser, rFC2822DateTimeFormatParser, slashDelimitedDateTimeFormatParser, uKStyleSlashDelimitedDateTimeFormatParser, uSStyleSlashDelimitedDateTimeFormatParser, monthNameAndDayOfMonthDateFormatParser, dayOfMonthAndMonthNameDateFormatParser, twentyFourHourTimeFormatParser, twelveHourTimeFormatParser, dashDelimitedWithMonthNameDateTimeFormatParser, ]; export default parsers;
the_stack
import { Readable } from 'stream' import { CurlOptionName, CurlOptionCamelCaseMap, CurlOptionValueType, } from './generated/CurlOption' import { HeaderInfo } from './parseHeaders' import { Curl } from './Curl' import { CurlFeature } from './enum/CurlFeature' /** * Object the curly call resolves to. * * @public */ export interface CurlyResult<ResultData extends any = any> { /** * Data will be the body of the requested URL */ data: ResultData /** * Parsed headers * * See {@link HeaderInfo} */ headers: HeaderInfo[] /** * HTTP Status code for the last request */ statusCode: number } // This is basically http.METHODS const methods = [ 'acl', 'bind', 'checkout', 'connect', 'copy', 'delete', 'get', 'head', 'link', 'lock', 'm-search', 'merge', 'mkactivity', 'mkcalendar', 'mkcol', 'move', 'notify', 'options', 'patch', 'post', 'propfind', 'proppatch', 'purge', 'put', 'rebind', 'report', 'search', 'source', 'subscribe', 'trace', 'unbind', 'unlink', 'unlock', 'unsubscribe', ] as const type HttpMethod = typeof methods[number] export type CurlyResponseBodyParser = ( data: Buffer, header: HeaderInfo[], ) => any export type CurlyResponseBodyParsersProperty = { [key: string]: CurlyResponseBodyParser } /** * These are the options accepted by the {@link CurlyFunction | `CurlyFunction`} API. * * Most libcurl options are accepted as their specific name, like `PROXY_CAPATH`, or as a camel * case version of that name, like `proxyCaPath`. * * Options specific to the `curly` API are prefixed with `curly`, like `curlyBaseUrl`. * * For quick navigation use the sidebar. */ export interface CurlyOptions extends CurlOptionValueType { /** * Set this to a callback function that should be used as the progress callback. * * This is the only reliable way to set the progress callback. * * @remarks * * This basically calls one of the following methods, depending on if any of the streams feature is being used or not: * - If using streams: {@link "Curl".Curl.setStreamProgressCallback | `Curl#setStreamProgressCallback`} * - else: {@link "Curl".Curl.setProgressCallback | `Curl#setProgressCallback`} */ curlyProgressCallback?: CurlOptionValueType['xferInfoFunction'] /** * If set to a function this will always be called * for all requests, ignoring other response body parsers. * * This can also be set to `false`, which will disable the response parsing and will make * the raw `Buffer` of the response to be returned. */ curlyResponseBodyParser?: CurlyResponseBodyParser | false /** * Add more response body parsers, or overwrite existing ones. * * This object is merged with the {@link CurlyFunction.defaultResponseBodyParsers | `curly.defaultResponseBodyParsers`} */ curlyResponseBodyParsers?: CurlyResponseBodyParsersProperty /** * If set, this value will always prefix the `URL` of the request. * * No special handling is done, so make sure you set the url correctly later on. */ curlyBaseUrl?: string /** * If `true`, `curly` will lower case all headers before returning then. * * By default this is `false`. */ curlyLowerCaseHeaders?: boolean /** * If `true`, `curly` will return the response data as a stream. * * The `curly` call will resolve as soon as the stream is available. * * When using this option, if an error is thrown in the internal {@link "Curl".Curl | `Curl`} instance * after the `curly` call has been resolved (it resolves as soon as the stream is available) * it will cause the `error` event to be emitted on the stream itself, this way it's possible * to handle these too, if necessary. The error object will have the property `isCurlError` set to `true`. * * Calling `destroy()` on the stream will always cause the `Curl` instance to emit the error event. * Even if an error argument was not supplied to `stream.destroy()`. * * By default this is `false`. * * @remarks * * Make sure your libcurl version is greater than or equal 7.69.1. * Versions older than that one are not reliable for streams usage. * * This basically enables the {@link CurlFeature.StreamResponse | `CurlFeature.StreamResponse`} feature * flag in the internal {@link "Curl".Curl | `Curl`} instance. */ curlyStreamResponse?: boolean /** * This will set the `hightWaterMark` option in the response stream, if `curlyStreamResponse` is `true`. * * @remarks * * This basically calls {@link "Curl".Curl.setStreamResponseHighWaterMark | `Curl#setStreamResponseHighWaterMark`} * method in the internal {@link "Curl".Curl | `Curl`} instance. */ curlyStreamResponseHighWaterMark?: number /** * If set, the contents of this stream will be uploaded to the server. * * Keep in mind that if you set this option you **SHOULD** not set * `progressFunction` or `xferInfoFunction`, as these are used internally. * * If you need to set a progress callback, use the `curlyProgressCallback` option. * * If the stream set here is destroyed before libcurl finishes uploading it, the error * `Curl upload stream was unexpectedly destroyed` (Code `42`) will be emitted in the * internal {@link "Curl".Curl | `Curl`} instance, and so will cause the curly call to be rejected with that error. * * If the stream was destroyed with a specific error, this error will be passed instead. * * By default this is not set. * * @remarks * * Make sure your libcurl version is greater than or equal 7.69.1. * Versions older than that one are not reliable for streams usage. * * This basically calls {@link "Curl".Curl.setUploadStream | `Curl#setUploadStream`} * method in the internal {@link "Curl".Curl | `Curl`} instance. */ curlyStreamUpload?: Readable | null } interface CurlyHttpMethodCall { /** * **EXPERIMENTAL** This API can change between minor releases * * Async wrapper around the Curl class. * * The `curly.<field>` being used will be the HTTP verb sent. * * @typeParam ResultData You can use this to specify the type of the `data` property returned from this call. */ <ResultData extends any = any>(url: string, options?: CurlyOptions): Promise< CurlyResult<ResultData> > } // type HttpMethodCalls = { readonly [K in HttpMethod]: CurlyHttpMethodCall } type HttpMethodCalls = Record<HttpMethod, CurlyHttpMethodCall> export interface CurlyFunction extends HttpMethodCalls { /** * **EXPERIMENTAL** This API can change between minor releases * * Async wrapper around the Curl class. * * It's also possible to request using a specific http verb * directly by using `curl.<http-verb>(url: string, options?: CurlyOptions)`, like: * * ```js * curly.get('https://www.google.com') * ``` * @typeParam ResultData You can use this to specify the type of the `data` property returned from this call. */ <ResultData extends any = any>(url: string, options?: CurlyOptions): Promise< CurlyResult<ResultData> > /** * **EXPERIMENTAL** This API can change between minor releases * * This returns a new `curly` with the specified options set by default. */ create: (defaultOptions?: CurlyOptions) => CurlyFunction /** * These are the default response body parsers to be used. * * By default there are parsers for the following: * * - application/json * - text/* * - * */ defaultResponseBodyParsers: CurlyResponseBodyParsersProperty } const create = (defaultOptions: CurlyOptions = {}): CurlyFunction => { function curly<ResultData extends any>( url: string, options: CurlyOptions = {}, ): Promise<CurlyResult<ResultData>> { const curlHandle = new Curl() curlHandle.enable(CurlFeature.NoDataParsing) curlHandle.setOpt('URL', `${options.curlyBaseUrl || ''}${url}`) const finalOptions = { ...defaultOptions, ...options, } for (const key of Object.keys(finalOptions)) { const keyTyped = key as keyof CurlyOptions const optionName: CurlOptionName = keyTyped in CurlOptionCamelCaseMap ? CurlOptionCamelCaseMap[ keyTyped as keyof typeof CurlOptionCamelCaseMap ] : (keyTyped as CurlOptionName) // if it begins with curly we do not set it on the curlHandle // as it's an specific option for curly if (optionName.startsWith('curly')) continue // @ts-ignore @TODO Try to type this curlHandle.setOpt(optionName, finalOptions[key]) } // streams! const { curlyStreamResponse, curlyStreamResponseHighWaterMark, curlyStreamUpload, } = finalOptions const isUsingStream = !!(curlyStreamResponse || curlyStreamUpload) if (finalOptions.curlyProgressCallback) { if (typeof finalOptions.curlyProgressCallback !== 'function') { throw new TypeError( 'curlyProgressCallback must be a function with signature (number, number, number, number) => number', ) } const fnToCall = isUsingStream ? 'setStreamProgressCallback' : 'setProgressCallback' curlHandle[fnToCall](finalOptions.curlyProgressCallback) } if (curlyStreamResponse) { curlHandle.enable(CurlFeature.StreamResponse) if (curlyStreamResponseHighWaterMark) { curlHandle.setStreamResponseHighWaterMark( curlyStreamResponseHighWaterMark, ) } } if (curlyStreamUpload) { curlHandle.setUploadStream(curlyStreamUpload) } const lowerCaseHeadersIfNecessary = (headers: HeaderInfo[]) => { // in-place modification // yeah, I know mutability is bad and all that if (finalOptions.curlyLowerCaseHeaders) { for (const headersReq of headers) { const entries = Object.entries(headersReq) for (const [headerKey, headerValue] of entries) { delete headersReq[headerKey] headersReq[headerKey.toLowerCase()] = headerValue } } } } return new Promise((resolve, reject) => { let stream: Readable if (curlyStreamResponse) { curlHandle.on( 'stream', (_stream, statusCode, headers: HeaderInfo[]) => { lowerCaseHeadersIfNecessary(headers) stream = _stream resolve({ // @ts-ignore cannot be subtype yada yada data: stream, statusCode, headers, }) }, ) } curlHandle.on( 'end', (statusCode, data: Buffer, headers: HeaderInfo[]) => { curlHandle.close() // only need to the remaining here if we did not enabled // the stream response if (curlyStreamResponse) { return } const contentTypeEntry = Object.entries( headers[headers.length - 1], ).find(([k]) => k.toLowerCase() === 'content-type') let contentType = contentTypeEntry ? contentTypeEntry[1] : '' // remove the metadata of the content-type, like charset // See https://tools.ietf.org/html/rfc7231#section-3.1.1.5 contentType = contentType.split(';')[0] const responseBodyParsers = { ...curly.defaultResponseBodyParsers, ...finalOptions.curlyResponseBodyParsers, } let foundParser = finalOptions.curlyResponseBodyParser if (typeof foundParser === 'undefined') { for (const [contentTypeFormat, parser] of Object.entries( responseBodyParsers, )) { if (typeof parser !== 'function') { return reject( new TypeError( `Response body parser for ${contentTypeFormat} must be a function`, ), ) } if (contentType === contentTypeFormat) { foundParser = parser break } else if (contentTypeFormat === '*') { foundParser = parser break } else { const partsFormat = contentTypeFormat.split('/') const partsContentType = contentType.split('/') if ( partsContentType.length === partsFormat.length && partsContentType.every( (val, index) => partsFormat[index] === '*' || partsFormat[index] === val, ) ) { foundParser = parser break } } } } if (foundParser && typeof foundParser !== 'function') { return reject( new TypeError( '`curlyResponseBodyParser` passed to curly must be false or a function.', ), ) } lowerCaseHeadersIfNecessary(headers) try { resolve({ statusCode: statusCode, data: foundParser ? foundParser(data, headers) : data, headers: headers, }) } catch (error) { reject(error) } }, ) curlHandle.on('error', (error, errorCode) => { curlHandle.close() // @ts-ignore error.code = errorCode // @ts-ignore error.isCurlError = true // oops, if have a stream it means the promise // has been resolved with it // so instead of rejecting the original promise // we are emitting the error event on the stream if (stream) { stream.emit('error', error) } else { reject(error) } }) try { curlHandle.perform() } catch (error) /* istanbul ignore next: this should never happen 🤷‍♂️ */ { curlHandle.close() reject(error) } }) } curly.create = create curly.defaultResponseBodyParsers = { 'application/json': (data, _headers) => { try { const string = data.toString('utf8') return JSON.parse(string) } catch (error) { throw new Error( `curly failed to parse "application/json" content as JSON. This is generally caused by receiving malformed JSON data from the server. You can disable this automatic behavior by setting the option curlyResponseBodyParser to false, then a Buffer will be returned as the data. You can also overwrite the "application/json" parser with your own by changing one of the following: - curly.defaultResponseBodyParsers['application/json'] or - options.curlyResponseBodyParsers = { 'application/json': parser } If you want just a single function to handle all content-types, you can use the option "curlyResponseBodyParser". `, ) } }, // We are in [INSERT CURRENT YEAR], let's assume everyone is using utf8 encoding for text/* content-type. 'text/*': (data, _headers) => data.toString('utf8'), // otherwise let's just return the raw buffer '*': (data, _headers) => data, } as CurlyResponseBodyParsersProperty const httpMethodOptionsMap: Record< string, null | ((m: string, o: CurlyOptions) => CurlyOptions) > = { get: null, post: (_m, o) => ({ post: true, ...o, }), head: (_m, o) => ({ nobody: true, ...o, }), _: (m, o) => ({ customRequest: m.toUpperCase(), ...o, }), } for (const httpMethod of methods) { const httpMethodOptionsKey = Object.prototype.hasOwnProperty.call( httpMethodOptionsMap, httpMethod, ) ? httpMethod : '_' const httpMethodOptions = httpMethodOptionsMap[httpMethodOptionsKey] // @ts-ignore curly[httpMethod] = httpMethodOptions === null ? curly : (url: string, options: CurlyOptions = {}) => curly(url, { ...httpMethodOptions(httpMethod, options), }) } // @ts-ignore return curly } /** * Curly function * * @public */ export const curly = create()
the_stack
import path from 'path'; import glob from 'globby'; import { readJson, ensureDir, remove, pathExists } from 'fs-extra'; import { ExtensionBundle, PackageJSON, ExtensionMetadata, ExtensionConfigurationSchema, JSONSchema7, ExtensionSettings, } from '@botframework-composer/types'; import { ExtensionRegistration } from '@bfc/extension'; import mapKeys from 'lodash/mapKeys'; import settings from '../settings'; import logger from '../logger'; import { JsonStore } from '../store/store'; import { search, downloadPackage } from '../utility/npm'; import { isSubdirectory } from '../utility/isSubdirectory'; import { ExtensionContext } from '../models/extension/extensionContext'; const log = logger.extend('extension-manager'); function processBundles(extensionPath: string, bundles: ExtensionBundle[]) { return bundles.map((b) => ({ ...b, path: path.resolve(extensionPath, b.path), })); } function extractMetadata(extensionPath: string, packageJson: PackageJSON): ExtensionMetadata { return { id: packageJson.name, name: packageJson.composer?.name ?? packageJson.name, description: packageJson.description, version: packageJson.version, enabled: true, path: extensionPath, bundles: processBundles(extensionPath, packageJson.composer?.bundles ?? []), contributes: packageJson.composer?.contributes ?? {}, configurationSchema: packageJson.composer?.configuration, }; } export type ExtensionManifest = Record<string, ExtensionMetadata>; export class ExtensionManagerImp { public constructor( private _manifest?: JsonStore<ExtensionManifest>, private _settings?: JsonStore<ExtensionSettings> ) {} /** * Returns all extensions currently in the extension manifest */ public getAll(): ExtensionMetadata[] { const extensions = this.manifest.read(); return Object.values(extensions).filter(Boolean) as ExtensionMetadata[]; } /** * Returns the extension manifest entry & settings for the specified extension ID * @param id Id of the extension to search for */ public find(id: string) { return this.manifest.get(id); } /** * Loads all builtin extensions and remote extensions. */ public async loadAll() { await ensureDir(this.remoteDir); await ensureDir(this.dataDir); await this.loadFromDir(this.builtinDir, true); await this.loadFromDir(this.remoteDir); await this.cleanManifest(); } /** * Loads extensions from a given directory * @param dir directory to load extensions from * @param isBuiltin used to set extension metadata */ public async loadFromDir(dir: string, isBuiltin = false) { log('Loading extensions from %s', dir); const extensions = await glob('*/package.json', { cwd: dir }); for (const extensionPackageJsonPath of extensions) { const fullPath = path.join(dir, extensionPackageJsonPath); const extensionInstallPath = path.dirname(fullPath); const packageJson = (await readJson(fullPath)) as PackageJSON; const isEnabled = packageJson.composer?.enabled !== false; const metadata = extractMetadata(extensionInstallPath, packageJson); if (isEnabled) { this.updateManifest(metadata.id, { ...metadata, builtIn: isBuiltin, }); await this.load(metadata.id); } else if (this.manifest.get(metadata.id)) { // remove the extension if it exists in the manifest this.updateManifest(metadata.id, undefined); } } } /** * Installs a remote extension via NPM * @param name The name of the extension to install * @param version The version of the extension to install * @returns id of installed package */ public async installRemote(name: string, version?: string) { await ensureDir(this.remoteDir); const packageNameAndVersion = version ? `${name}@${version}` : `${name}@latest`; log('Installing %s to %s', packageNameAndVersion, this.remoteDir); try { const destination = path.join(this.remoteDir, name); if (!isSubdirectory(this.remoteDir, destination)) { throw new Error('Cannot install outside of the configured directory.'); } await downloadPackage(name, version ?? 'latest', destination); const packageJson = await this.getPackageJson(name, this.remoteDir); if (packageJson) { this.updateManifest(packageJson.name, extractMetadata(destination, packageJson)); } return name; } catch (err) { log('%O', err); throw new Error(`Unable to install ${packageNameAndVersion}`); } } public async load(id: string) { const metadata = this.manifest.get(id); try { // eslint-disable-next-line @typescript-eslint/no-var-requires, security/detect-non-literal-require const extension = metadata?.path && require(metadata.path); if (!extension || !metadata) { throw new Error(`Extension not found: ${id}`); } const getSettings = () => { return this.getSettingsForExtension(metadata.id); }; const registration = new ExtensionRegistration(ExtensionContext, metadata, getSettings, this.dataDir); if (typeof extension.default === 'function') { // the module exported just an init function await extension.default.call(null, registration); } else if (extension.default && extension.default.initialize) { // the module exported an object with an initialize method await extension.default.initialize.call(null, registration); } else if (extension.initialize && typeof extension.initialize === 'function') { // the module exported an object with an initialize method await extension.initialize.call(null, registration); } else { throw new Error('Could not init extension'); } } catch (err) { log('Unable to load extension `%s`', id); log('%O', err); if (!metadata?.builtIn) { await this.remove(id); } throw err; } } /** * Enables an extension * @param id Id of the extension to be enabled */ public async enable(id: string) { this.updateManifest(id, { enabled: true }); await this.load(id); } /** * Disables an extension * @param id Id of the extension to be disabled */ public async disable(id: string) { this.updateManifest(id, { enabled: false }); // TODO: tear down extension? } /** * Removes a remote extension via NPM * @param id Id of the extension to be removed */ public async remove(id: string) { const metadata = this.find(id); if (metadata) { log('Removing %s', id); if (metadata.builtIn) { this.updateManifest(id, { enabled: false }); return; } log('Removing %s', id); await remove(metadata.path); this.updateManifest(id, undefined); } else { throw new Error(`Unable to remove extension: ${id}`); } } /** * Searches for an extension via NPM's search function * @param query The search query */ public async search(query: string) { const results = await search(query); return results.filter((searchResult) => { const { id, keywords } = searchResult; return !this.find(id) && keywords.includes('extension'); }); } /** * Returns a specific bundle for an extension * @param id The id of the desired extension * @param bundleId The id of the desired extension's bundle */ public getBundle(id: string, bundleId: string): string | null { const info = this.find(id); if (!info) { throw new Error('extension not found'); } const bundle = info.bundles.find((b) => b.id === bundleId); if (!bundle) { throw new Error('bundle not found'); } return bundle.path; } public updateManifest(id: string, data: Partial<ExtensionMetadata> | undefined) { // remove from manifest if (data === undefined) { this.manifest.set(id, undefined); } else { const existingData = this.manifest.get(id); this.manifest.set(id, { ...existingData, ...data } as ExtensionMetadata); } } public get settingsSchema() { return { type: 'object', $schema: 'http://json-schema.org/draft-07/schema#', properties: this.combinedSettingsSchema, additionalProperties: false, } as JSONSchema7; } public getSettings(withDefaults = false) { const userSettings = this.settings.read(); if (withDefaults) { log('Including defaults in settings.'); Object.entries(this.combinedSettingsSchema).forEach(([key, schema]) => { if (!(key in userSettings) && schema.default) { userSettings[key] = schema.default; } }); } return userSettings; } // eslint-disable-next-line @typescript-eslint/no-explicit-any public updateSettings(newSettings: any) { log('Writing new settings. %O', newSettings); this.settings.write(newSettings); } private getSettingsForExtension(id: string) { const allSettings = this.getSettings(true); return Object.entries(allSettings).reduce((all, [key, value]) => { if (key.startsWith(id)) { all[key.replace(`${id}.`, '')] = value; } return all; }, {}) as ExtensionSettings; } private async cleanManifest() { for (const ext of this.getAll()) { if (!(await pathExists(ext.path))) { log('Removing %s. It is in the manifest but could not be located.', ext.id); this.remove(ext.id); } } } private async getPackageJson(id: string, dir: string): Promise<PackageJSON | undefined> { try { const extensionPackagePath = path.resolve(dir, id, 'package.json'); log('fetching package.json for %s at %s', id, extensionPackagePath); const packageJson = await readJson(extensionPackagePath); return packageJson as PackageJSON; } catch (err) /* istanbul ignore next */ { log('Error getting package json for %s', id); log('%O', err); } } private get combinedSettingsSchema() { return this.getAll().reduce((all, e) => { const extSchema = mapKeys(e.configurationSchema ?? {}, (_, k) => `${e.id}.${k}`); return { ...all, ...extSchema }; }, {} as ExtensionConfigurationSchema); } private get manifest() { /* istanbul ignore next */ if (!this._manifest) { this._manifest = new JsonStore(settings.extensions.manifestPath as string, {}); } return this._manifest; } private get settings() { /* istanbul ignore next */ if (!this._settings) { this._settings = new JsonStore(settings.extensions.settingsPath, {}); } return this._settings; } private get builtinDir() { return settings.extensions.builtinDir; } private get remoteDir() { return settings.extensions.remoteDir; } private get dataDir() { return settings.extensions.dataDir; } } const ExtensionManager = new ExtensionManagerImp(); export { ExtensionManager };
the_stack
import { GraphQLArgument, GraphQLInputObjectType, GraphQLList, GraphQLNamedType, GraphQLObjectType, GraphQLOutputType, GraphQLResolveInfo, GraphQLSchema, GraphQLType, IntrospectionObjectType, IntrospectionType, defaultFieldResolver, getNamedType, isEnumType, isInterfaceType, isObjectType, isScalarType, isUnionType } from 'graphql'; import { difference, each, eq, find, get, isArray, isEmpty, isObject, keys, map, set, union } from 'lodash'; import pluralize from 'pluralize'; import { Connection, DataResolver } from './GraphQLGenieInterfaces'; import { FindByUniqueError, getReturnType, typeIsList } from './GraphQLUtils'; export class Relation { public type0: string; public field0: string; public field0isList: boolean; public type1: string; public field1: string; public field1isList: boolean; constructor($type: string, $field: string, $field0isList: boolean) { this.type0 = $type; this.field0 = $field; this.field0isList = $field0isList; } setRelative(relation: Relation) { this.type1 = relation.type0; this.field1 = relation.field0; this.field1isList = relation.field0isList; } isValidRelative(relation: Relation) { if (!this.type1) { return true; } else { return this.isSameRelation(relation) || this.isCurrentRelation(relation); } } isSameRelation(relation: Relation): boolean { return this.type0 === relation.type0 && this.field0 === relation.field0 && this.field0isList === relation.field0isList; } isCurrentRelation(relation: Relation): boolean { return this.type1 === relation.type0 && this.field1 === relation.field0 && this.field1isList === relation.field0isList; } getInverse(type: string, field: string, inverseType?: string): string { const inverse = this.getInverseTuple(type, field, inverseType); return inverse ? inverse[1] : null; } getInverseTuple(type: string, field: string, inverseType?: string): [string, string] { let inverse = null; if (this.type0 === type && this.field0 === field && (!inverseType || this.type1 === inverseType)) { inverse = [this.type1, this.field1]; } else if (this.type1 === type && this.field1 === field && (!inverseType || this.type0 === inverseType)) { inverse = [this.type0, this.field0]; } return inverse; } } export class Relations { public relations: Map<string, Relation>; constructor() { this.relations = new Map<string, Relation>(); } public getRelation(name: string): Relation { let relations = null; if (this.relations.has(name)) { relations = this.relations.get(name); } return relations; } public getInverseWithoutName(type: string, field: string, inverseType: string): string { let inverse: string = null; const iter = this.relations.values(); let relation = iter.next().value; while (!inverse && relation) { inverse = relation.getInverse(type, field, inverseType); relation = iter.next().value; } return inverse; } public getInverse(name: string, type: string, field: string): string { let inverse = null; if (this.relations.has(name)) { const relation = this.relations.get(name); inverse = relation.getInverse(type, field); } return inverse; } public setRelation(name: string, type: string, field: string, fieldIsList: boolean) { const newRelation = new Relation(type, field, fieldIsList); if (!this.relations.has(name)) { this.relations.set(name, newRelation); } else { const relation = this.relations.get(name); if (relation.isValidRelative(newRelation)) { if (!relation.isSameRelation(newRelation)) { relation.setRelative(newRelation); } } else { this.throwError(name, type, field, relation.field0); } } } public setSelfRelation(name: string, type: string, field: string, fieldIsList: boolean) { const newRelation = new Relation(type, field, fieldIsList); newRelation.setRelative(newRelation); this.relations.set(name, newRelation); } private throwError(name: string, type: string, primaryField: string, relatedField: string) { throw new Error(`Bad schema, relation could apply to multiple fields relation name: ${name} fortune name: ${type} curr field: ${primaryField} other field: ${relatedField}`); } } const computeNumFieldsOfType = (type: IntrospectionObjectType, checkFieldTypeName: string): number => { let resultNum = 0; each(type.fields, field => { if (checkFieldTypeName === getReturnType(field.type)) { resultNum++; } }); return resultNum; }; const getNumFieldsOfType = (cache: Map<string, Map<string, number>>, type: IntrospectionObjectType, checkFieldTypeName: string): number => { let numFields = 0; const typeName = getReturnType(type); if (cache.has(typeName) && cache.get(typeName).has(checkFieldTypeName)) { numFields = cache.get(typeName).get(checkFieldTypeName); } else { numFields = computeNumFieldsOfType(type, checkFieldTypeName); if (!cache.has(typeName)) { cache.set(typeName, new Map<string, number>()); } cache.get(typeName).set(checkFieldTypeName, numFields); } return numFields; }; export const computeRelations = (schemaInfo: IntrospectionType[], typeNameResolver: (name: string) => string = (name: string) => name): Relations => { const numFieldsOfTypeCache = new Map<string, Map<string, number>>(); const relations = new Relations(); each(keys(schemaInfo), (typeName) => { const type = <IntrospectionObjectType>schemaInfo[typeName]; each(type.fields, field => { const relation = get(field, 'metadata.relation'); const fieldTypeName = getReturnType(field.type); const reslovedTypeName = typeNameResolver(fieldTypeName); if (relation) { relations.setRelation(relation.name, reslovedTypeName, field.name, typeIsList(field.type)); } else if (typeName === fieldTypeName) { relations.setSelfRelation(`${field.name}On${typeName}`, reslovedTypeName, field.name, typeIsList(field.type)); } else { const fieldTypeInfo = schemaInfo[fieldTypeName]; if (type && fieldTypeInfo) { const numFields = getNumFieldsOfType(numFieldsOfTypeCache, type, fieldTypeName); const reverseNumFields = getNumFieldsOfType(numFieldsOfTypeCache, fieldTypeInfo, typeName); if (numFields === 1 && reverseNumFields === 1) { const possibleTypes = [typeName, fieldTypeName]; possibleTypes.sort(); relations.setRelation(possibleTypes.join('_'), reslovedTypeName, field.name, typeIsList(field.type)); } } } }); }); return relations; }; export enum Mutation { Create, Update, Delete, Upsert } export const clean = (obj): any => { const returnObj = {}; for (const propName in obj) { if (obj[propName] !== null && obj[propName] !== undefined) { // tslint:disable-next-line:prefer-conditional-expression if (isObject(obj[propName]) && !isEmpty(obj[propName])) { returnObj[propName] = obj[propName]; } else { returnObj[propName] = obj[propName]; } } } return returnObj; }; const setupArgs = (results: any[], args: any[]) => { // setup the arguments to use the new types results.forEach((types: any[]) => { types = types ? types : []; types.forEach(type => { if (type && type.key && type.id && type.index > -1) { const key = type.key; const id = type.id; const arg = args[type.index]; if (isArray(arg[key])) { if (isArray(id)) { arg[key] = union(id, arg[key]); } else if (!arg[key].includes(id)) { arg[key].push(id); } } else { arg[key] = id; } } }); }); return args; }; const resolveArgs = async (args: Array<any>, returnType: GraphQLOutputType, mutation: Mutation, dataResolver: DataResolver, currRecord: any, _args: { [key: string]: any }, _context: any, _info: GraphQLResolveInfo): Promise<Array<any>> => { const promises: Array<Promise<any>> = []; args.forEach((currArg, index) => { for (const argName in currArg) { let argReturnType: GraphQLOutputType; let argReturnRootType: GraphQLOutputType; if ((isObjectType(returnType) || isInterfaceType(returnType)) && returnType.getFields()[argName]) { argReturnType = returnType.getFields()[argName].type; argReturnRootType = <GraphQLOutputType>getNamedType(argReturnType); if (argReturnRootType['name'].endsWith('Connection')) { argReturnRootType = <GraphQLOutputType>_info.schema.getType(argReturnRootType['name'].replace(/Connection$/g, '')); argReturnType = new GraphQLList(argReturnRootType); } } if (argReturnRootType && !isScalarType(argReturnRootType) && !isEnumType(argReturnRootType)) { const arg = currArg[argName]; if (isObject(arg) && argReturnType) { currArg[argName] = typeIsList(argReturnType) ? [] : undefined; if (isInterfaceType(argReturnRootType) || isUnionType(argReturnRootType)) { for (const argKey in arg) { const argTypeName = pluralize.singular(argKey).toLowerCase(); argReturnRootType = <GraphQLOutputType> find(_info.schema.getTypeMap(), type => { return type.name.toLowerCase() === argTypeName; }); promises.push(mutateResolver(mutation, dataResolver)(currRecord, arg[argKey], _context, _info, index, argName, argReturnRootType)); } } else { promises.push(mutateResolver(mutation, dataResolver)(currRecord, arg, _context, _info, index, argName, argReturnRootType)); } } } } }); const results = await Promise.all(promises); args = setupArgs(results, args); return args; }; const mutateResolver = (mutation: Mutation, dataResolver: DataResolver) => { return async (currRecord: any, _args: { [key: string]: any }, _context: any, _info: GraphQLResolveInfo, index?: number, key?: string, returnType?: GraphQLOutputType) => { await dataResolver.beginTransaction(); // iterate over all the non-id arguments and recursively create new types const recursed = returnType ? true : false; if (!returnType) { returnType = (<GraphQLObjectType>_info.returnType).getFields().data.type; returnType = <GraphQLObjectType>getNamedType(returnType); } const returnTypeName = getReturnType(returnType); const clientMutationId = _args.input && _args.input.clientMutationId ? _args.input.clientMutationId : ''; let createArgs = _args.create ? _args.create : mutation === Mutation.Create && get(_args, 'input.data') ? get(_args, 'input.data') : []; createArgs = createArgs && !isArray(createArgs) ? [createArgs] : createArgs; let updateArgs = _args.update ? _args.update : mutation === Mutation.Update && get(_args, 'input.data') ? get(_args, 'input.data') : []; updateArgs = updateArgs && !isArray(updateArgs) ? [updateArgs] : updateArgs; let upsertArgs = _args.upsert ? _args.upsert : mutation === Mutation.Upsert && get(_args, 'input') ? get(_args, 'input') : []; upsertArgs = upsertArgs && !isArray(upsertArgs) ? [upsertArgs] : upsertArgs; let deleteArgs = _args.delete ? _args.delete : mutation === Mutation.Delete && _args.input.where ? _args.input.where : []; deleteArgs = deleteArgs && !isArray(deleteArgs) ? [deleteArgs] : deleteArgs; let connectArgs = _args.connect ? _args.connect : []; connectArgs = connectArgs && !isArray(connectArgs) ? [connectArgs] : connectArgs; let disconnectArgs = _args.disconnect ? _args.disconnect : []; disconnectArgs = disconnectArgs && !isArray(disconnectArgs) ? [disconnectArgs] : disconnectArgs; const whereArgs = _args.where ? _args.where : _args.input && _args.input.where ? _args.input.where : null; const conditionsArgs = _args.conditions ? _args.conditions : _args.input && _args.input.conditions ? _args.input.conditions : null; // lets make sure we are able to add this (prevent duplicates on unique fields, etc) const canAddResults = await Promise.all([dataResolver.canAdd(returnTypeName, createArgs, {context: _context, info: _info}), dataResolver.canAdd(returnTypeName, updateArgs, {context: _context, info: _info})]); const cannotAdd = canAddResults.includes(false); if (cannotAdd) { throw new Error('Can not create record with duplicate on unique field on type ' + returnTypeName + ' ' + JSON.stringify(createArgs) + ' ' + JSON.stringify(updateArgs)); } const dataResolverPromises: Array<Promise<any>> = []; if (!isEmpty(updateArgs)) { if (whereArgs) { // we have a where so use that to get the record to update // pass true to where args if currRecord is already the one we want if (whereArgs !== true) { const returnTypeName = getReturnType(returnType); currRecord = await dataResolver.getValueByUnique(returnTypeName, whereArgs, {context: _context, info: _info}); if (!currRecord || isEmpty(currRecord)) { throw new FindByUniqueError(`${returnTypeName} does not exist with where args ${JSON.stringify(whereArgs)}`, 'update', {arg: whereArgs, typename: returnTypeName}); } } } else if (updateArgs[0].data && updateArgs[0].where) { // this is a nested update an a list type so we need to individually do updates updateArgs.forEach((currArg) => { dataResolverPromises.push( new Promise((resolve, reject) => { mutateResolver(mutation, dataResolver)(currRecord, { update: currArg.data, where: currArg.where }, _context, _info, index, key, returnType).then((result) => { if (recursed) { resolve(); } else { resolve(result[0]); } }).catch(reason => { reject(reason); }); }) ); }); updateArgs = []; } else if (key && currRecord) { // this is a nested input on a single field so we already know the where const recordToUpdate = await dataResolver.getValueByUnique(returnTypeName, { id: currRecord[key] }, {context: _context, info: _info}); if (recordToUpdate) { currRecord = recordToUpdate; } else { // trying to update an empty field updateArgs = []; } } } if (!isEmpty(upsertArgs)) { await Promise.all(upsertArgs.map(async (currArg) => { const whereArg = currArg.where; let upsertRecord = currRecord; if (whereArg) { // this is a root upsert or nested upsert with a where field upsertRecord = await dataResolver.getValueByUnique(returnTypeName, whereArg, {context: _context, info: _info}); } else if (upsertRecord && key) { // this is a nested upsert on a single field so we already have the where upsertRecord = upsertRecord[key] ? await dataResolver.getValueByUnique(returnTypeName, { id: upsertRecord[key] }, {context: _context, info: _info}) : null; } let newArgs: object = { create: currArg.create }; if (upsertRecord && !isEmpty(upsertRecord)) { // pass true to where args if currRecord will already be the one we want newArgs = { where: true, update: currArg.update, conditions: conditionsArgs }; } dataResolverPromises.push( new Promise((resolve, reject) => { mutateResolver(mutation, dataResolver)(upsertRecord, newArgs, _context, _info, index, key, returnType).then((result) => { if (result[0]) { resolve(result[0]); } else { resolve(); } }).catch(reason => { reject(reason); }); }) ); })); } [createArgs, updateArgs] = await Promise.all([ resolveArgs(createArgs, returnType, Mutation.Create, dataResolver, currRecord, _args, _context, _info), resolveArgs(updateArgs, returnType, Mutation.Update, dataResolver, currRecord, _args, _context, _info) ]); // could be creating more than 1 type createArgs.forEach((createArg) => { createArg = createArg.hasOwnProperty ? createArg : Object.assign({}, createArg); createArg = clean(createArg); if (createArg && !isEmpty(createArg)) { dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.create(returnTypeName, createArg, {context: _context, info: _info}).then(data => { const id = isArray(data) ? map(data, 'id') : data.id; resolve({ index, key, id, data }); }).catch(reason => { reject(reason); }); })); } }); // now updates updateArgs.forEach((updateArg) => { // make sure it is prototype correctly to prevent error updateArg = updateArg.hasOwnProperty ? updateArg : Object.assign({}, updateArg); // only do updates on new values for (const updateArgKey in updateArg) { const currArg = updateArg[updateArgKey]; const currRecordArg = currRecord[updateArgKey]; if (eq(currRecordArg, currArg)) { delete currRecord[updateArgKey]; } else if (isArray(currArg) && isArray(currRecordArg)) { // for relations we can't have duplicates, only relations will be arrays updateArg[updateArgKey] = difference(currArg, currRecordArg); } } const cleanArg = clean(updateArg); if (cleanArg && !isEmpty(cleanArg)) { dataResolverPromises.push(new Promise((resolve, reject) => { cleanArg.id = currRecord.id; const meta = {context: _context, info: _info}; meetsConditions(conditionsArgs, returnTypeName, returnType, currRecord, dataResolver, _context, _info).then(meetsConditionsResult => { if (!meetsConditionsResult) { resolve({ index, key, id: [], unalteredData: currRecord}); } else { dataResolver.update(returnTypeName, cleanArg, meta).then(data => { const id = isArray(data) ? map(data, 'id') : data.id; resolve({ index, key, id, data }); }).catch(reason => { reject(reason); }); } }).catch(reason => { reject(reason); }); })); } else if (currRecord) { currRecord = Object.assign(currRecord, updateArg); } }); // now add the connect types connectArgs.forEach(connectArg => { dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.getValueByUnique(returnTypeName, connectArg, {context: _context, info: _info}).then(data => { if (data && data['id']) { resolve({ index, key, id: data['id'], data }); } else { reject(new FindByUniqueError(`connect: ${returnTypeName} does not exist with where args ${JSON.stringify(connectArg)}`, 'disconnect', {arg: connectArg, typename: returnTypeName})); } }).catch(reason => { reject(reason); }); })); }); // disconnect const disconnectPromises: Array<Promise<any>> = []; disconnectArgs.forEach(disconnectArg => { if (disconnectArg === true) { dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.update(currRecord.__typename, { id: currRecord.id, [key]: null }, {context: _context, info: _info}).then(data => { resolve({ index, key, id: null, data }); }).catch(reason => { reject(reason); }); })); } else { disconnectPromises.push(new Promise((resolve, reject) => { dataResolver.getValueByUnique(returnTypeName, disconnectArg, {context: _context, info: _info}).then(data => { if (data && data['id']) { resolve(data['id']); } else { reject(new FindByUniqueError(`disconnect: ${returnTypeName} does not exist with where args ${JSON.stringify(disconnectArg)}`, 'disconnect', {arg: disconnectArg, typename: returnTypeName})); } }).catch(reason => { reject(reason); }); })); } }); const disconnectIds = await Promise.all(disconnectPromises); if (!isEmpty(disconnectIds)) { dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.update(currRecord.__typename, { id: currRecord.id, [key]: disconnectIds }, {context: _context, info: _info}, { pull: true }).then(data => { resolve({ index, key, id: data[key], data }); }).catch(reason => { reject(reason); }); })); } // delete const deletePromises: Array<Promise<any>> = []; deleteArgs.forEach(deleteArg => { if (deleteArg === true) { // nested singular delete dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.delete(dataResolver.getLink(currRecord.__typename, key), [currRecord[key]], {context: _context, info: _info}).then(data => { resolve({ index, key, id: null, data }); }).catch(reason => { reject(reason); }); })); } else if (whereArgs && !currRecord) { // delete resolver dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.getValueByUnique(returnTypeName, whereArgs, {context: _context, info: _info}).then(whereData => { currRecord = whereData; if (!currRecord || isEmpty(currRecord)) { throw new FindByUniqueError(`${returnTypeName} does not exist with where args ${JSON.stringify(whereArgs)}`, 'delete', {arg: whereArgs, typename: returnTypeName}); } meetsConditions(conditionsArgs, returnTypeName, returnType, currRecord, dataResolver, _context, _info).then(meetsConditionsResult => { if (!meetsConditionsResult) { resolve({ index, key, id: [], unalteredData: currRecord}); } else { dataResolver.delete(currRecord.__typename, [currRecord.id], {context: _context, info: _info}).then(() => { resolve({ index, key, id: null, data: currRecord }); }).catch(reason => { reject(reason); }); } }).catch(reason => { reject(reason); }); }).catch(reason => { reject(reason); }); })); } else { // nested delete on list deletePromises.push(new Promise((resolve, reject) => { const deleteTypeName = dataResolver.getLink(currRecord.__typename, key); dataResolver.getValueByUnique(deleteTypeName, deleteArg, {context: _context, info: _info}).then(data => { if (data && data['id']) { resolve(data['id']); } else { reject(new FindByUniqueError(`${deleteTypeName} does not exist with where args ${JSON.stringify(deleteArg)}`, 'delete', {arg: deleteArg, typename: deleteTypeName})); } }).catch(reason => { reject(reason); }); })); } }); const deleteIds = await Promise.all(deletePromises); if (!isEmpty(deleteIds)) { dataResolverPromises.push(new Promise((resolve, reject) => { dataResolver.delete(dataResolver.getLink(currRecord.__typename, key), deleteIds, {context: _context, info: _info}).then(data => { resolve({ index, key, id: data[key], data }); }).catch(reason => { reject(reason); }); })); } const dataResult = await Promise.all(dataResolverPromises); // if key this is recursed else it's the final value if (recursed) { return dataResult; } else { await dataResolver.endTransaction(); let data = get(dataResult, '[0].data'); const unalteredData = get(dataResult, '[0].unalteredData', null); if (!unalteredData && !data && mutation === Mutation.Delete) { data = currRecord; } else if (!unalteredData && !data) { // if everything was already done on the object (updates, deletions and disconnects) it should be the currRecord but with changes data = currRecord; } return { data, clientMutationId, unalteredData }; } }; }; export const createResolver = (dataResolver: DataResolver) => { return mutateResolver(Mutation.Create, dataResolver); }; export const updateResolver = (dataResolver: DataResolver) => { return mutateResolver(Mutation.Update, dataResolver); }; export const upsertResolver = (dataResolver: DataResolver) => { return mutateResolver(Mutation.Upsert, dataResolver); }; export const deleteResolver = (dataResolver: DataResolver) => { return mutateResolver(Mutation.Delete, dataResolver); }; export const getTypeResolver = (dataResolver: DataResolver, schema: GraphQLSchema, field: any, returnConnection = false) => { const schemaType = schema.getType(getReturnType(field.type)); let resolver; if (!isScalarType(schemaType) && !isEnumType(schemaType)) { resolver = async ( root: any, _args: { [key: string]: any }, _context: any, _info: GraphQLResolveInfo ): Promise<any> => { const fortuneReturn = root && root.fortuneReturn ? root.fortuneReturn : root; if (!fortuneReturn) { return fortuneReturn; } const cache = root && root.cache ? root.cache : new Map<string, object>(); const typeName = getReturnType(field.type); let result: any = []; let returnArray = false; let fieldValue = fortuneReturn[field.name]; returnArray = isArray(fieldValue); fieldValue = returnArray ? fieldValue : [fieldValue]; // actual value is filled from cache not just ids if (isObject(fieldValue[0])) { result = fieldValue; } const ids = []; let options = {}; _args = moveArgsIntoWhere(_args); let where = null; if (_args && _args.where) { where = _args.where; options = parseFilter(where, schemaType); } if (_args.orderBy) { set(options, 'orderBy', _args.orderBy); } if (_args.skip) { set(options, 'offset', _args.skip); } let connection: Connection; options = clean(options); // I guess use the args here instead of args as a result of cache if (!isEmpty(options)) { result = []; } if (isEmpty(result)) { fieldValue.forEach(id => { if (id) { if (cache.has(id)) { result.push(cache.get(id)); } else { ids.push(id); } } }); } let findOptions = {}; let applyOptionsWithCombinedResult = false; if (!isEmpty(result) && !isEmpty(options)) { applyOptionsWithCombinedResult = true; } else { findOptions = options; } if (!isEmpty(ids)) { let findResult = await dataResolver.find(typeName, ids, findOptions, {context: _context, info: _info}); if (findResult) { findResult = isArray(findResult) ? findResult : [findResult]; // remove null values findResult = findResult.filter(function(n) { return !!n; }); findResult.forEach(result => { cache.set(result.id, result); }); result = result.concat(findResult); } } if (applyOptionsWithCombinedResult) { result = dataResolver.applyOptions(typeName, result, options); } if ((_args.orderBy || where) && (isObjectType(schemaType) || isInterfaceType(schemaType))) { const pullIds = await filterNested(where, _args.orderBy, schemaType, fortuneReturn, cache, dataResolver, _context, _info); result = result.filter(entry => !pullIds.has(entry.id)); } // use cached data on subfields in order to support nested orderBy/where result.forEach(resultElement => { for (const resultElementField in resultElement) { if (cache.has(`${resultElement.id}.${resultElementField}`)) { resultElement[resultElementField] = cache.get(`${resultElement.id}.${resultElementField}`); } } }); connection = dataResolver.getConnection(result, _args.before, _args.after, _args.first, _args.last); result = connection.edges; result = result.map((entry) => { return { fortuneReturn: entry, cache: cache, __typename: entry.__typename }; }); result = !returnArray && result.length === 0 ? null : returnArray ? result : result[0]; if (returnConnection) { result = { edges: result, pageInfo: connection && connection.pageInfo ? connection.pageInfo : null, aggregate: connection && connection.aggregate ? connection.aggregate : null }; } return result; }; } else { resolver = async ( root: any, _args: { [key: string]: any }, _context: any, _info: GraphQLResolveInfo ): Promise<any> => { const fortuneReturn = root && root.fortuneReturn ? root.fortuneReturn : root; const result = await defaultFieldResolver.apply(this, [fortuneReturn, _args, _context, _info]); return result; }; } return resolver; }; export const getAllResolver = (dataResolver: DataResolver, schema: GraphQLSchema, type: IntrospectionObjectType, returnConnection = false) => { return async (_root: any, _args: { [key: string]: any }, _context: any, _info: GraphQLResolveInfo) => { let options = {}; let where = null; _args = moveArgsIntoWhere(_args); const schemaType: GraphQLNamedType = schema.getType(type.name); if (_args && _args.where) { where = _args.where; options = parseFilter(_args.where, schemaType); } if (_args.orderBy) { set(options, 'orderBy', _args.orderBy); } if (_args.skip) { set(options, 'offset', _args.skip); } let connection: Connection; let result: any = []; let fortuneReturn = await dataResolver.find(type.name, null, options, {context: _context, info: _info}); if (fortuneReturn && !isEmpty(fortuneReturn)) { fortuneReturn = isArray(fortuneReturn) ? fortuneReturn : [fortuneReturn]; connection = dataResolver.getConnection(fortuneReturn, _args.before, _args.after, _args.first, _args.last); fortuneReturn = connection.edges; const cache = new Map<string, object>(); fortuneReturn.forEach(result => { if (result && result.id) { cache.set(result.id, result); } }); if ((_args.orderBy || where) && (isObjectType(schemaType) || isInterfaceType(schemaType))) { const pullIds = await filterNested(where, _args.orderBy, schemaType, fortuneReturn, cache, dataResolver, _context, _info); fortuneReturn = pullIds.size > 0 ? fortuneReturn.filter(result => !pullIds.has(result ? result.id : '')) : fortuneReturn; } result = fortuneReturn.map((result) => { if (!result) { return result; } return { fortuneReturn: result, cache: cache, where, __typename: result.__typename }; }); } if (returnConnection) { result = { edges: result, pageInfo: connection && connection.pageInfo ? connection.pageInfo : null, aggregate: connection && connection.aggregate ? connection.aggregate : null }; } return result; }; }; export const queryArgs: Object = { 'first': { type: 'Int', description: 'Slice result from the start' }, 'last': { type: 'Int', description: 'Slice result from the end' }, 'skip': { type: 'Int', description: 'Skip results' }, 'before': { type: 'String', description: 'Cursor returned by previous connection queries for pagination' }, 'after': { type: 'String', description: 'Cursor returned by previous connection queries for pagination' }, }; export const fortuneFilters = ['not', 'or', 'and', 'range', 'match', 'exists']; const genieFindArgs = ['first', 'where', 'orderBy', 'local', 'last', 'skip', 'before', 'after']; export const getRootMatchFields = (matchInput: GraphQLInputObjectType): { [key: string]: GraphQLArgument } => { const matchFields = matchInput.getFields(); const args = {}; Object.keys(matchFields).forEach(key => { let newKey = key; if (genieFindArgs.includes(key)) { newKey = `f_${key}`; } args[newKey] = matchFields[key]; args[newKey].name = newKey; args[newKey].description = `${key} matches at least one of argument`; }); return args; }; export const moveArgsIntoWhere = (args: object): object => { if (!args) { return args; } Object.keys(args).forEach((argKey) => { if (!genieFindArgs.includes(argKey)) { set(args, 'where.match.' + argKey, args[argKey]); delete args[argKey]; } }); return args; }; export const parseFilter = (filter: object, type: GraphQLNamedType) => { if (!isObjectType(type) && !isInterfaceType(type)) { return filter; } if (!filter || !isObject(filter) || isArray(filter)) { return filter; } each(type.getFields(), field => { if (!fortuneFilters.includes(field.name) && filter[field.name]) { if (filter['and']) { filter['and'].push({ exists: { [field.name]: true } }); } else { set(filter, `exists.${field.name}`, true); } } }); return filter; }; export const filterNested = async (filter: object, orderBy: object, type: GraphQLNamedType, fortuneReturn: any[], cache: Map<string, object>, dataResolver: DataResolver, _context, _info): Promise<Set<string>> => { // if they have nested filters on types we need to get that data now so we can filter at this root query const pullIds = new Set<string>(); if (!cache) { cache = new Map<string, object>(); } if ((orderBy || filter) && (isObjectType(type) || isInterfaceType(type))) { await Promise.all(map(type.getFields(), async (field) => { const currFilter = filter && filter[field.name] ? filter[field.name] : filter && filter[`f_${field.name}`] ? filter[`f_${field.name}`] : null; const currOrderBy = orderBy && orderBy[field.name] ? orderBy[field.name] : orderBy && orderBy[`f_${field.name}`] ? orderBy[`f_${field.name}`] : null; const childType = getNamedType(field.type); if (!isScalarType(childType) && !isEnumType(childType) && (currFilter || currOrderBy)) { const options = currFilter ? parseFilter(currFilter, childType) : {}; await Promise.all(fortuneReturn.map(async (result) => { if (!result) { return result; } const childIds = result[field.name]; if (childIds && !isEmpty(childIds)) { if (currOrderBy) { options['orderBy'] = currOrderBy; } let childReturn = await dataResolver.find(childType.name, childIds, options, {context: _context, info: _info}); if (isArray(childReturn) && !isEmpty(childReturn)) { const recursePullIds = await filterNested(currFilter, currOrderBy, childType, childReturn, cache, dataResolver, _context, _info); childReturn = childReturn ? childReturn.filter(result => { if (!result) { return result; } return !recursePullIds.has(result.id); }) : childReturn; } else if (childReturn && (currOrderBy || currFilter)) { const recursePullIds = await filterNested(currFilter, currOrderBy, childType, [childReturn], cache, dataResolver, _context, _info); childReturn = childReturn ? [childReturn].filter(result => { if (!result) { return result; } return !recursePullIds.has(result.id); }) : childReturn; } if (childReturn && !isEmpty(childReturn)) { if (cache) { if (childReturn.id) { cache.set(childReturn.id, childReturn); } else { cache.set(`${result.id}.${field.name}`, childReturn); } } } else { pullIds.add(result.id); } } })); } })); } return pullIds; }; export const getPayloadTypeName = (typeName: string): string => { return `${typeName}Payload`; }; export const getPayloadTypeDef = (typeName: string): string => { return ` type ${getPayloadTypeName(typeName)} { data: ${typeName} clientMutationId: String #In the case of a update or delete and you had conditions, if the conditions did not match the existing object will be returned here. data will be null unalteredData: ${typeName} }`; }; export const capFirst = (val: string) => { return val ? val.charAt(0).toUpperCase() + val.slice(1) : ''; }; export const isConnectionType = (type: GraphQLType): boolean => { let isConnection = false; if (isObjectType(type) && type.name.endsWith('Connection')) { isConnection = true; // could add more logic to not have to ban fields ending with Connection } return isConnection; }; // resolvers may have meta info that's not wanted export const getRecordFromResolverReturn = (record) => { record = record && record.fortuneReturn ? record.fortuneReturn : record; record = record && record.edges ? record.edges : record; record = record && record.node ? record.node : record; record = record && record.fortuneReturn ? record.fortuneReturn : record; record = record && record.data ? record.data : record; return record; }; export const meetsConditions = async (conditionsArgs, returnTypeName, returnType, currRecord, dataResolver, _context, _info) => { let meetsConditions = true; if (conditionsArgs) { const conditionsOptions = parseFilter(conditionsArgs, <GraphQLNamedType> returnType); let dataAfterConditions = dataResolver.applyOptions(returnTypeName, currRecord, conditionsOptions); if (!isEmpty(dataAfterConditions)) { if (conditionsArgs && (isObjectType(returnType) || isInterfaceType(returnType))) { const pullIds = await filterNested(conditionsArgs, null, returnType, currRecord, null, dataResolver, _context, _info); dataAfterConditions = dataAfterConditions.filter(entry => !pullIds.has(entry.id)); } } if (isEmpty(dataAfterConditions)) { meetsConditions = false; } } return meetsConditions; };
the_stack
import express from 'express'; import authMiddleware from '@server/middleware/auth.middleware'; import asyncMiddleware from '@server/middleware/async.middleware'; import async from 'async'; import { EntityManager, getConnection, getManager, getRepository, getTreeRepository, In, } from 'typeorm'; import Asset from '@server/models/asset.model'; import path from 'path'; import BadRequestError from '@server/errors/bad-request-error'; import * as yup from 'yup'; import sizeOf from 'image-size'; import Tag from '@server/models/tag.model'; import FileDriver from '@server/drivers/file.driver'; import { getReplaceChildrenQuery, updateMeta, } from '@server/common/orm-helpers'; import { mapAsset } from '@server/common/mappers'; import Hooks from '@shared/features/hooks'; const app = express(); const FOLDER_MIME_TYPE = 'application/vnd.burdy.folder'; const IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']; export const generateUniqueName = async ( manager: EntityManager, name: string, parent: number, counter = 1 ) => { const ext = path.extname(name); const index = name.lastIndexOf(ext); let proposedName = name.substring(0, index); if (index > -1 && ext.length > 0) { proposedName = `${proposedName} (${counter})${ext}`; } else { proposedName = `${proposedName} (${counter})`; } const searchObj: any = { name: proposedName, }; if (parent) { searchObj.parentId = parent; } const asset = await manager.findOne(Asset, searchObj); if (asset) { counter++; proposedName = await generateUniqueName(manager, name, parent, counter); } return proposedName; }; const getParent = async ( manager: EntityManager, components: string[], parent ) => { if (components.length > 0) { let newParent; const name = components.shift(); const npath = parent ? `${parent.npath}/${name}` : name; try { newParent = await manager.findOne(Asset, { npath, }); if (!newParent) { newParent = await manager.save(Asset, { parent, name, mimeType: FOLDER_MIME_TYPE, npath, }); } } catch (err) { newParent = await manager.findOne(Asset, { npath, }); } parent = await getParent(manager, components, newParent); } return parent; }; app.get( '/assets', authMiddleware(), asyncMiddleware(async (req, res) => { const assetRepository = getRepository(Asset); const databaseType = getConnection().options.type; const { id, parentId, mimeType, search, npath } = req.query as any; const qb = assetRepository .createQueryBuilder('asset') .leftJoinAndSelect('asset.meta', 'meta') .leftJoinAndSelect('asset.tags', 'tags'); if (id) { qb.andWhereInIds(id.split(',')); } if (npath) { qb.andWhere('asset.npath IN (:...npath)', { npath: npath.split(',') }); } qb.leftJoinAndSelect( (q) => q .select([ 'npath', databaseType === 'postgres' ? '"parentId"' : 'parentId', databaseType === 'postgres' ? '"mimeType"' : 'mimeType', ]) .from(Asset, 'thumbnail') .where('thumbnail.mimeType IN (:...mimeTypes)', { mimeTypes: IMAGE_MIME_TYPES, }), 'thumbnail', databaseType === 'postgres' ? 'thumbnail."parentId" = asset.id' : 'thumbnail.parentId = asset.id' ); qb.addSelect('thumbnail.npath', 'asset_thumbnail'); if (search?.length > 0) { qb.andWhere('asset.mimeType != :mimeType', { mimeType: FOLDER_MIME_TYPE, }).andWhere('LOWER(asset.name) LIKE :search', { search: `%${search.toLowerCase()}%`, }); } if (mimeType?.length > 0) { qb.andWhere('asset.mimeType IN (:...mimeTypes)', { mimeTypes: [...mimeType.split(','), FOLDER_MIME_TYPE], }); } if (!(search?.length > 0) && !(id || npath)) { if (parentId) { qb.andWhere('asset.parentId = :parentId', { parentId }); } else { qb.andWhere('asset.parentId IS NULL'); } } const assets = await qb.orderBy('asset.name', 'DESC').getMany(); return res.send(assets.map(mapAsset)); }) ); app.get( '/assets/ancestors', authMiddleware(), asyncMiddleware(async (req, res) => { const assetTreeRepository = await getTreeRepository(Asset); let asset: Asset; let ancestorsTree: Asset; const { id } = req.query; if (id) { asset = await assetTreeRepository.findOne({ relations: ['tags'], where: { id, }, }); if (!asset) throw new BadRequestError('invalid_asset'); ancestorsTree = await assetTreeRepository.findAncestorsTree(asset); } res.send(Asset.getAncestorsList(ancestorsTree).reverse().map(mapAsset)); }) ); app.get('/assets/single', authMiddleware(), asyncMiddleware(async (req, res) => { const assetRepository = getRepository(Asset); const { attachment, npath } = req.query; const asset = await assetRepository.findOne({ relations: ['tags'], where: { npath }, }); if (!asset) throw new BadRequestError('invalid_asset'); if (asset.mimeType === FOLDER_MIME_TYPE) throw new BadRequestError('invalid_asset'); let content; if (asset.document) { content = await FileDriver.getInstance().read(asset.document); } res.set('Content-Type', asset.mimeType); res.set('Content-Length', `${asset.contentLength}`); if (IMAGE_MIME_TYPES.indexOf(asset.mimeType) === -1 || attachment) { res.attachment(asset.name); } res.send(content); }) ); app.get( '/assets/:id', authMiddleware(), asyncMiddleware(async (req, res) => { const assetRepository = getRepository(Asset); const { attachment } = req.query; const asset = await assetRepository.findOne({ relations: ['tags'], where: { id: req.params.id, }, }); if (!asset) throw new BadRequestError('invalid_asset'); if (asset.mimeType === FOLDER_MIME_TYPE) throw new BadRequestError('invalid_asset'); let content; if (asset.document) { content = await FileDriver.getInstance().read(asset.document); } res.set('Content-Type', asset.mimeType); res.set('Content-Length', `${asset.contentLength}`); if (IMAGE_MIME_TYPES.indexOf(asset.mimeType) === -1 || attachment) { res.attachment(asset.name); } res.send(content); }) ); const getKeyName = (key: string = '') => { return key.split('/').pop(); }; // Create folder, assets app.post( '/assets', authMiddleware(['assets_create']), FileDriver.getInstance().getUpload().single('file'), asyncMiddleware(async (req, res) => { const entityManager = getManager(); const params = req.body; const { duplicateName } = params; try { let asset; await entityManager.transaction(async (tManager) => { let parent; if (params.parentId) { parent = await tManager.findOne(Asset, { id: params.parentId }); if (!parent) throw new BadRequestError('invalid_parent'); } const nameComponents = params.name .split('/') .filter((cmp) => cmp?.length > 0); let name = nameComponents.pop(); if (nameComponents.length > 0) { parent = await getParent(entityManager, nameComponents, parent); } const searchObj: any = { name, }; if (parent) { searchObj.parentId = parent.id; } asset = await tManager.findOne(Asset, searchObj); if (asset) { if (duplicateName) { name = await generateUniqueName(tManager, name, parent); } else { throw new BadRequestError('duplicate_name'); } } const assetObj: any = { name, mimeType: params.mimeType, author: req?.data?.user, }; if (parent) { assetObj.parent = parent; assetObj.npath = `${parent.npath}/${name}`; } else { assetObj.npath = name; } if (params?.mimeType !== FOLDER_MIME_TYPE) { if (!req.file) throw new BadRequestError('invalid_file'); const stat = await FileDriver.getInstance().stat( req?.file?.filename || getKeyName(req?.file?.key) ); if (!stat) throw new BadRequestError('invalid_file'); if (IMAGE_MIME_TYPES.indexOf(params.mimeType) > -1) { const file = await FileDriver.getInstance().read( req?.file?.filename || getKeyName(req?.file?.key) ); const dimensions = sizeOf(file); assetObj.meta = [ { key: 'height', value: dimensions.height, }, { key: 'width', value: dimensions.width, }, ]; } assetObj.provider = FileDriver.getInstance().getName(); assetObj.contentLength = stat.contentLength; assetObj.document = req?.file?.filename || getKeyName(req?.file?.key); } asset = await tManager.save(Asset, assetObj); }); return res.send(mapAsset(asset)); } catch (err) { await FileDriver.getInstance().delete( req?.file?.filename || getKeyName(req?.file?.key) ); throw err; } }) ); app.put( '/assets/:id/rename', authMiddleware(['assets_update']), asyncMiddleware(async (req, res) => { await req.validate( { name: yup.string().required(), }, 'body' ); const entityManager = getManager(); let updatedAsset; await entityManager.transaction(async (tManager) => { const asset = await entityManager.findOne(Asset, { id: req?.params?.id }); if (!asset) throw new BadRequestError('invalid_asset'); asset.name = req.body.name; const originalNPath = asset.npath; const components = asset.npath.split('/'); components.pop(); components.push(req.body.name); const npath = components.join('/'); asset.npath = npath; await tManager.save(Asset, asset); const result = await tManager.query( getReplaceChildrenQuery('asset', 'npath', originalNPath, npath) ); // if not at least one entry (the very object we're renaming) was updated, then the query or the data is wrong if (result[1] < 1) { // throw new Error('Something went wrong during rename.'); } updatedAsset = await tManager.findOne(Asset, { id: req.params.id }); }); return res.send(mapAsset(updatedAsset)); }) ); app.put( '/assets/:id', authMiddleware(['assets_update']), asyncMiddleware(async (req, res) => { await req.validate( { alt: yup.string().max(256), copyright: yup.string().max(256), }, 'body' ); const entityManager = getManager(); await entityManager.transaction(async (tManager) => { const asset = await entityManager.findOne(Asset, { relations: ['meta'], where: { id: req?.params?.id, }, }); if (!asset) throw new BadRequestError('invalid_asset'); const meta = []; if (req?.body?.alt) { meta.push({ key: 'alt', value: req?.body?.alt, }); } if (req?.body?.copyright) { meta.push({ key: 'copyright', value: req?.body?.copyright, }); } await updateMeta(tManager, Asset, asset, meta, /^(alt|copyright)/); if (Array.isArray(req?.body?.tags)) { const tags = await tManager.getRepository(Tag).find({ where: { id: In(req?.body?.tags.map((tag) => tag?.id).filter((id) => !!id)), }, }); asset.tags = tags; } await tManager.save(asset); return res.send(mapAsset(asset)); }); }) ); app.delete( '/assets', authMiddleware(['assets_delete']), asyncMiddleware(async (req, res) => { const ids = req?.body ?? []; if (!ids || ids?.length === 0) return res.send([]); const entityManager = getManager(); const documents: string[] = []; const toDeleteAssets = []; await entityManager.transaction(async (tManager) => { const assetTreeRepository = tManager.getTreeRepository(Asset); const assets = await tManager.findByIds(Asset, ids); if (assets.length === 0) return []; await async.eachSeries(assets, async (asset, next) => { const children = await assetTreeRepository.findDescendants(asset); children.forEach((child) => { toDeleteAssets.push(child); if (child.document) { documents.push(child.document); } }); next(); }); return tManager.delete(Asset, { id: In(toDeleteAssets.map((asset) => asset.id)), }); }); FileDriver.getInstance().delete(documents); return res.send(toDeleteAssets.map((asset) => asset.id)); }) ); app.get( '/uploads/*', asyncMiddleware(async (req, res) => { const assetRepository = getRepository(Asset); const videoRange = req.headers.range; const asset = await assetRepository.findOne({ npath: req.params[0] }); if (!asset) throw new BadRequestError('invalid_asset'); if (asset.mimeType === FOLDER_MIME_TYPE) throw new BadRequestError('invalid_asset'); await Hooks.doAction('public/getAsset', asset); if (videoRange) { const parts = videoRange.replace(/bytes=/, '').split('-'); const start = parseInt(parts[0], 10); const end = parts[1] ? parseInt(parts[1], 10) : asset.contentLength - 1; const chunksize = end - start + 1; const file = FileDriver.getInstance().createReadStream(asset.document, { range: videoRange, start, end, }); const head = { 'Content-Range': `bytes ${start}-${end}/${asset.contentLength}`, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': asset.mimeType, 'Cache-Control': process.env.ASSETS_CACHE_CONTROL?.length > 0 ? process.env.ASSETS_CACHE_CONTROL : 'no-cache', }; res.writeHead(206, head); file.pipe(res); } else { const head = { 'Content-Length': asset.contentLength, 'Content-Type': asset.mimeType, 'Cache-Control': process.env.ASSETS_CACHE_CONTROL?.length > 0 ? process.env.ASSETS_CACHE_CONTROL : 'no-cache', }; res.writeHead(200, head); FileDriver.getInstance().createReadStream(asset.document).pipe(res); } }) ); export default app;
the_stack
import {Document, Error, Mongoose} from "mongoose"; import {Express} from "express"; import {fngServer} from "./index"; import Resource = fngServer.Resource; import ListField = fngServer.ListField; import FngOptions = fngServer.FngOptions; import IFngPlugin = fngServer.IFngPlugin; import IInternalSearchResult = fngServer.IInternalSearchResult; import Path = fngServer.Path; // This part of forms-angular borrows _very_ heavily from https://github.com/Alexandre-Strzelewicz/angular-bridge // (now https://github.com/Unitech/angular-bridge const _ = require('lodash'); const util = require('util'); const extend = require('node.extend'); const async = require('async'); let debug = false; function logTheAPICalls(req, res, next) { void (res); console.log('API : ' + req.method + ' ' + req.url + ' [ ' + JSON.stringify(req.body) + ' ]'); next(); } function processArgs(options: any, array: Array<any>): Array<any> { if (options.authentication) { let authArray = _.isArray(options.authentication) ? options.authentication : [options.authentication]; for (let i = authArray.length - 1; i >= 0; i--) { array.splice(1, 0, authArray[i]); } } if (debug) { array.splice(1, 0, logTheAPICalls); } array[0] = options.urlPrefix + array[0]; return array; } export class FormsAngular { app: Express; mongoose: Mongoose; options: FngOptions; resources: Resource[]; searchFunc: typeof async.forEach; constructor(mongoose: Mongoose, app: Express, options: FngOptions) { this.mongoose = mongoose; this.app = app; app.locals.formsAngular = app.locals.formsAngular || []; app.locals.formsAngular.push(this); mongoose.set('debug', debug); mongoose.Promise = global.Promise; this.options = _.extend({ urlPrefix: '/api/' }, options || {}); this.resources = []; this.searchFunc = async.forEach; const search = 'search/', schema = 'schema/', report = 'report/', resourceName = ':resourceName', id = '/:id'; this.app.get.apply(this.app, processArgs(this.options, ['models', this.models()])); this.app.get.apply(this.app, processArgs(this.options, [search + resourceName, this.search()])); this.app.get.apply(this.app, processArgs(this.options, [schema + resourceName, this.schema()])); this.app.get.apply(this.app, processArgs(this.options, [schema + resourceName + '/:formName', this.schema()])); this.app.get.apply(this.app, processArgs(this.options, [report + resourceName, this.report()])); this.app.get.apply(this.app, processArgs(this.options, [report + resourceName + '/:reportName', this.report()])); this.app.get.apply(this.app, processArgs(this.options, [resourceName, this.collectionGet()])); this.app.post.apply(this.app, processArgs(this.options, [resourceName, this.collectionPost()])); this.app.get.apply(this.app, processArgs(this.options, [resourceName + id, this.entityGet()])); this.app.post.apply(this.app, processArgs(this.options, [resourceName + id, this.entityPut()])); // You can POST or PUT to update data this.app.put.apply(this.app, processArgs(this.options, [resourceName + id, this.entityPut()])); this.app.delete.apply(this.app, processArgs(this.options, [resourceName + id, this.entityDelete()])); // return the List attributes for a record - used by select2 this.app.get.apply(this.app, processArgs(this.options, [resourceName + id + '/list', this.entityList()])); this.app.get.apply(this.app, processArgs(this.options, ['search', this.searchAll()])); for (let pluginName in this.options.plugins) { if (this.options.plugins.hasOwnProperty(pluginName)) { let pluginObj: IFngPlugin = this.options.plugins[pluginName]; this[pluginName] = pluginObj.plugin(this, processArgs, pluginObj.options); } } } getListFields(resource: Resource, doc: Document, cb) { function getFirstMatchingField(keyList, type?) { for (let i = 0; i < keyList.length; i++) { let fieldDetails = resource.model.schema['tree'][keyList[i]]; if (fieldDetails.type && (!type || fieldDetails.type.name === type) && keyList[i] !== '_id') { resource.options.listFields = [{field: keyList[i]}]; return doc[keyList[i]]; } } } const that = this; let display = ''; let listFields = resource.options.listFields; if (listFields) { async.map(listFields, function (aField, cbm) { if (typeof doc[aField.field] !== 'undefined') { if (aField.params) { if (aField.params.ref) { let fieldOptions = (resource.model.schema['paths'][aField.field] as any).options; if (typeof fieldOptions.ref === 'string') { let lookupResource = that.getResource(fieldOptions.ref); if (lookupResource) { let hiddenFields = that.generateHiddenFields(lookupResource, false); hiddenFields.__v = false; lookupResource.model.findOne({_id: doc[aField.field]}).select(hiddenFields).exec(function (err, doc2) { if (err) { cbm(err); } else { that.getListFields(lookupResource, doc2, cbm); } }); } } else { throw new Error('No support for ref type ' + aField.params.ref.type) } } else if (aField.params.params === 'timestamp') { let date = that.extractTimestampFromMongoID(doc[aField.field]); cbm(null, date.toLocaleDateString() + ' ' + date.toLocaleTimeString()); } } else { cbm(null, doc[aField.field]); } } else { cbm(null, '') } }, function (err, results) { if (err) { cb(err); } else { if (results) { cb(err, results.join(' ').trim()) } else { console.log('No results ' + listFields); } } }); } else { const keyList = Object.keys(resource.model.schema['tree']); // No list field specified - use the first String field, display = getFirstMatchingField(keyList, 'String') || // and if there aren't any then just take the first field getFirstMatchingField(keyList); cb(null, display.trim()); } }; newResource(model, options) { options = options || {}; options.suppressDeprecatedMessage = true; let passModel = model; if (typeof model !== 'function') { passModel = model.model; } this.addResource(passModel.modelName, passModel, options); }; // Add a resource, specifying the model and any options. // Models may include their own options, which means they can be passed through from the model file addResource(resourceName, model, options) { let resource: Resource = { resourceName: resourceName, options: options || {} }; if (!resource.options.suppressDeprecatedMessage) { console.log('addResource is deprecated - see https://github.com/forms-angular/forms-angular/issues/39'); } if (typeof model === 'function') { resource.model = model; } else { resource.model = model.model; for (const prop in model) { if (model.hasOwnProperty(prop) && prop !== 'model') { resource.options[prop] = model[prop]; } } } extend(resource.options, this.preprocess(resource, resource.model.schema['paths'], null)); if (resource.options.searchImportance) { this.searchFunc = async.forEachSeries; } if (this.searchFunc === async.forEachSeries) { this.resources.splice(_.sortedIndexBy(this.resources, resource, function (obj) { return obj.options.searchImportance || 99; }), 0, resource); } else { this.resources.push(resource); } }; getResource(name: string): Resource { return _.find(this.resources, function (resource) { return resource.resourceName === name; }); }; getResourceFromCollection(name: string): Resource { return _.find(this.resources, function (resource) { return resource.model.collection.collectionName === name; }); }; internalSearch(req, resourcesToSearch, includeResourceInResults, limit, callback) { if (typeof req.query === 'undefined') { req.query = {}; } const timestamps = {sentAt: req.query.sentAt, startedAt: new Date().valueOf(), completedAt: undefined}; let searches = [], resourceCount = resourcesToSearch.length, searchFor = req.query.q || '', filter = req.query.f; function translate(string, array, context) { if (array) { let translation = _.find(array, function (fromTo) { return fromTo.from === string && (!fromTo.context || fromTo.context === context); }); if (translation) { string = translation.to; } } return string; } // return a string that determines the sort order of the resultObject function calcResultValue(obj) { function padLeft(score: number, reqLength: number, str = '0') { return new Array(1 + reqLength - String(score).length).join(str) + score; } let sortString = ''; sortString += padLeft(obj.addHits || 9, 1); sortString += padLeft(obj.searchImportance || 99, 2); sortString += padLeft(obj.weighting || 9999, 4); sortString += obj.text; return sortString; } if (filter) { filter = JSON.parse(filter); } for (let i = 0; i < resourceCount; i++) { let resource = resourcesToSearch[i]; if (resourceCount === 1 || resource.options.searchImportance !== false) { let schema = resource.model.schema; let indexedFields = []; for (let j = 0; j < schema._indexes.length; j++) { let attributes = schema._indexes[j][0]; let field = Object.keys(attributes)[0]; if (indexedFields.indexOf(field) === -1) { indexedFields.push(field); } } for (let path in schema.paths) { if (path !== '_id' && schema.paths.hasOwnProperty(path)) { if (schema.paths[path]._index && !schema.paths[path].options.noSearch) { if (indexedFields.indexOf(path) === -1) { indexedFields.push(path); } } } } if (indexedFields.length === 0) { console.log('ERROR: Searching on a collection with no indexes ' + resource.resourceName); } for (let m = 0; m < indexedFields.length; m++) { searches.push({resource: resource, field: indexedFields[m]}); } } } const that = this; let results = []; let moreCount = 0; let searchCriteria; let searchStrings; let multiMatchPossible = false; if (searchFor === '?') { // interpret this as a wildcard (so there is no way to search for ? searchCriteria = null; } else { // THe snippet to escape the special characters comes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions searchFor = searchFor.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); multiMatchPossible = searchFor.includes(' '); if (multiMatchPossible) { searchStrings = searchFor.split(' '); } let modifiedSearchStr = multiMatchPossible ? searchStrings.join('|') : searchFor; searchFor = searchFor.toLowerCase(); // For later case-insensitive comparison // Removed the logic that preserved spaces when collection was specified because Louise asked me to. searchCriteria = {$regex: '^(' + modifiedSearchStr + ')', $options: 'i'}; } let handleSearchResultsFromIndex = function (err, docs, item, cb) { if (!err && docs && docs.length > 0) { async.map(docs, async function (aDoc, cbdoc) { // Do we already have them in the list? let thisId: string = aDoc._id.toString(), resultObject: IInternalSearchResult, resultPos: number; function handleResultsInList() { if (multiMatchPossible) { resultObject.matched = resultObject.matched || []; // record the index of string that matched, so we don't count it against another field for (let i = 0; i < searchStrings.length; i++) { if (aDoc[item.field].toLowerCase().indexOf(searchStrings[i]) === 0) { resultObject.matched.push(i); break; } } } resultObject.searchImportance = item.resource.options.searchImportance || 99; if (item.resource.options.localisationData) { resultObject.resource = translate(resultObject.resource, item.resource.options.localisationData, "resource"); resultObject.resourceText = translate(resultObject.resourceText, item.resource.options.localisationData, "resourceText"); resultObject.resourceTab = translate(resultObject.resourceTab, item.resource.options.localisationData, "resourceTab"); } results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject); cbdoc(null); } for (resultPos = results.length - 1; resultPos >= 0; resultPos--) { if (results[resultPos].id.toString() === thisId) { break; } } if (resultPos >= 0) { resultObject = Object.assign({}, results[resultPos]); // If they have already matched then improve their weighting if (multiMatchPossible) { // record the index of string that matched, so we don't count it against another field for (let i = 0; i < searchStrings.length; i++) { if (!resultObject.matched.includes(i) && aDoc[item.field].toLowerCase().indexOf(searchStrings[i]) === 0) { resultObject.matched.push(i); resultObject.addHits = Math.max((resultObject.addHits || 9) - 1, 0); // remove it from current position results.splice(resultPos, 1); // and re-insert where appropriate results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject); break; } } } cbdoc(null); } else { // Otherwise add them new... let addHits; if (multiMatchPossible) // If they match the whole search phrase in one index they get smaller addHits (so they sort higher) if (aDoc[item.field].toLowerCase().indexOf(searchFor) === 0) { addHits = 7; } // Use special listings format if defined let specialListingFormat = item.resource.options.searchResultFormat; if (specialListingFormat) { resultObject = await specialListingFormat.apply(aDoc); resultObject.addHits = addHits; handleResultsInList(); } else { that.getListFields(item.resource, aDoc, function (err, description) { if (err) { cbdoc(err); } else { (resultObject as any) = { id: aDoc._id, weighting: 9999, addHits, text: description }; if (resourceCount > 1 || includeResourceInResults) { resultObject.resource = resultObject.resourceText = item.resource.resourceName; } handleResultsInList(); } }); } } }, function (err) { cb(err); }); } else { cb(err); } }; this.searchFunc( searches, function (item, cb) { let searchDoc = {}; if (filter) { that.hackVariables(filter); extend(searchDoc, filter); if (filter[item.field]) { delete searchDoc[item.field]; let obj1 = {}, obj2 = {}; obj1[item.field] = filter[item.field]; obj2[item.field] = searchCriteria; searchDoc['$and'] = [obj1, obj2]; } else { if (searchCriteria) { searchDoc[item.field] = searchCriteria; } } } else { if (searchCriteria) { searchDoc[item.field] = searchCriteria; } } /* The +200 below line is an (imperfect) arbitrary safety zone for situations where items that match the string in more than one index get filtered out. An example where it fails is searching for "e c" which fails to get a old record Emily Carpenter in a big dataset sorted by date last accessed as they are not returned within the first 200 in forenames so don't get the additional hit score and languish outside the visible results, though those visible results end up containing people who only match either c or e (but have been accessed much more recently). Increasing the number would be a short term fix at the cost of slowing down the search. */ // TODO : Figure out a better way to deal with this if (item.resource.options.searchFunc) { item.resource.options.searchFunc(item.resource, req, null, searchDoc, item.resource.options.searchOrder, limit ? limit + 200 : 0, null, function (err, docs) { handleSearchResultsFromIndex(err, docs, item, cb); }); } else { that.filteredFind(item.resource, req, null, searchDoc, null, item.resource.options.searchOrder, limit ? limit + 200 : 0, null, function (err, docs) { handleSearchResultsFromIndex(err, docs, item, cb); }); } }, function (err) { if (err) { callback(err); } else { // Strip weighting from the results results = _.map(results, function (aResult) { delete aResult.weighting; return aResult; }); if (limit && results.length > limit) { moreCount += results.length - limit; results.splice(limit); } timestamps.completedAt = new Date().valueOf(); callback(null, {results, moreCount, timestamps}); } } ); }; wrapInternalSearch(req, res, resourcesToSearch, includeResourceInResults, limit) { this.internalSearch(req, resourcesToSearch, includeResourceInResults, limit, function (err, resultsObject) { if (err) { res.status(400, err) } else { res.send(resultsObject); } }); }; search() { return _.bind(function (req, res, next) { if (!(req.resource = this.getResource(req.params.resourceName))) { return next(); } this.wrapInternalSearch(req, res, [req.resource], false, 0); }, this); }; searchAll() { return _.bind(function (req, res) { this.wrapInternalSearch(req, res, this.resources, true, 10); }, this); }; models() { const that = this; return function (req, res) { // TODO: Make this less wasteful - we only need to send the resourceNames of the resources // Check for optional modelFilter and call it with the request and current list. Otherwise just return the list. res.send(that.options.modelFilter ? that.options.modelFilter.call(null, req, that.resources) : that.resources); }; }; renderError(err, redirectUrl, req, res) { if (typeof err === 'string') { res.send(err); } else { res.send(err.message); } }; redirect(address, req, res) { res.send(address); }; applySchemaSubset(vanilla, schema) { let outPath; if (schema) { outPath = {}; for (let fld in schema) { if (schema.hasOwnProperty(fld)) { if (vanilla[fld]) { outPath[fld] = _.cloneDeep(vanilla[fld]); if (vanilla[fld].schema) { outPath[fld].schema = this.applySchemaSubset(outPath[fld].schema, schema[fld].schema); } } else { if (fld.slice(0, 8) === "_bespoke") { outPath[fld] = { "path": fld, "instance": schema[fld]._type, } } else { throw new Error('No such field as ' + fld + '. Is it part of a sub-doc? If so you need the bit before the period.'); } } outPath[fld].options = outPath[fld].options || {}; for (var override in schema[fld]) { if (schema[fld].hasOwnProperty(override)) { if (override.slice(0, 1) !== '_') { if (schema[fld].hasOwnProperty(override)) { if (!outPath[fld].options.form) { outPath[fld].options.form = {}; } outPath[fld].options.form[override] = schema[fld][override]; } } } } } } } else { outPath = vanilla; } return outPath; }; preprocess(resource: Resource, paths, formSchema?) { let outPath: Path = {}, hiddenFields = [], listFields = []; if (resource && resource.options && resource.options.idIsList) { paths['_id'].options = paths['_id'].options || {}; paths['_id'].options.list = resource.options.idIsList; } for (let element in paths) { if (paths.hasOwnProperty(element) && element !== '__v') { // check for schemas if (paths[element].schema) { let subSchemaInfo = this.preprocess(null, paths[element].schema.paths); outPath[element] = {schema: subSchemaInfo.paths}; if (paths[element].options.form) { outPath[element].options = {form: extend(true, {}, paths[element].options.form)}; } // this provides support for entire nested schemas that wish to remain hidden if (paths[element].options.secure) { hiddenFields.push(element); } // to support hiding individual properties of nested schema would require us // to do something with subSchemaInfo.hide here } else { // check for arrays let realType = paths[element].caster ? paths[element].caster : paths[element]; if (!realType.instance) { if (realType.options.type) { let type = realType.options.type(), typeType = typeof type; if (typeType === 'string') { realType.instance = (!isNaN(Date.parse(type))) ? 'Date' : 'String'; } else { realType.instance = typeType; } } } outPath[element] = extend(true, {}, paths[element]); if (paths[element].options.secure) { hiddenFields.push(element); } if (paths[element].options.match) { outPath[element].options.match = paths[element].options.match.source || paths[element].options.match; } let schemaListInfo: any = paths[element].options.list; if (schemaListInfo) { let listFieldInfo: ListField = {field: element}; if (typeof schemaListInfo === 'object' && Object.keys(schemaListInfo).length > 0) { listFieldInfo.params = schemaListInfo; } listFields.push(listFieldInfo); } } } } outPath = this.applySchemaSubset(outPath, formSchema); let returnObj: any = {paths: outPath}; if (hiddenFields.length > 0) { returnObj.hide = hiddenFields; } if (listFields.length > 0) { returnObj.listFields = listFields; } return returnObj; }; schema() { return _.bind(function (req, res) { if (!(req.resource = this.getResource(req.params.resourceName))) { return res.status(404).end(); } let formSchema = null; if (req.params.formName) { formSchema = req.resource.model.schema.statics['form'](req.params.formName, req); } let paths = this.preprocess(req.resource, req.resource.model.schema.paths, formSchema).paths; res.send(paths); }, this); }; report() { return _.bind(async function (req, res, next) { if (!(req.resource = this.getResource(req.params.resourceName))) { return next(); } const self = this; if (typeof req.query === 'undefined') { req.query = {}; } let reportSchema; if (req.params.reportName) { reportSchema = await req.resource.model.schema.statics['report'](req.params.reportName, req); } else if (req.query.r) { switch (req.query.r[0]) { case '[': reportSchema = {pipeline: JSON.parse(req.query.r)}; break; case '{': reportSchema = JSON.parse(req.query.r); break; default: return self.renderError(new Error('Invalid "r" parameter'), null, req, res, next); } } else { let fields = {}; for (let key in req.resource.model.schema.paths) { if (req.resource.model.schema.paths.hasOwnProperty(key)) { if (key !== '__v' && !req.resource.model.schema.paths[key].options.secure) { if (key.indexOf('.') === -1) { fields[key] = 1; } } } } reportSchema = { pipeline: [ {$project: fields} ], drilldown: req.params.resourceName + '/|_id|/edit' }; } // Replace parameters in pipeline let schemaCopy: any = {}; extend(schemaCopy, reportSchema); schemaCopy.params = schemaCopy.params || []; self.reportInternal(req, req.resource, schemaCopy, function (err, result) { if (err) { self.renderError(err, null, req, res, next); } else { res.send(result); } }); }, this); }; hackVariablesInPipeline(runPipeline: Array<any>) { for (let pipelineSection = 0; pipelineSection < runPipeline.length; pipelineSection++) { if (runPipeline[pipelineSection]['$match']) { this.hackVariables(runPipeline[pipelineSection]['$match']); } } }; hackVariables(obj) { // Replace variables that cannot be serialised / deserialised. Bit of a hack, but needs must... // Anything formatted 1800-01-01T00:00:00.000Z or 1800-01-01T00:00:00.000+0000 is converted to a Date // Only handles the cases I need for now // TODO: handle arrays etc for (const prop in obj) { if (obj.hasOwnProperty(prop)) { if (typeof obj[prop] === 'string') { const dateTest = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3})(Z|[+ -]\d{4})$/.exec(obj[prop]); if (dateTest) { obj[prop] = new Date(dateTest[1] + 'Z'); } else { const objectIdTest = /^([0-9a-fA-F]{24})$/.exec(obj[prop]); if (objectIdTest) { obj[prop] = new this.mongoose.Types.ObjectId(objectIdTest[1]); } } } else if (_.isObject(obj[prop])) { this.hackVariables(obj[prop]); } } } }; sanitisePipeline( aggregationParam: any | any[], hiddenFields, findFuncQry: any): any[] { let that = this; let array = Array.isArray(aggregationParam) ? aggregationParam : [aggregationParam]; let retVal = []; let doneHiddenFields = false; if (findFuncQry) { retVal.unshift({$match: findFuncQry}); } for (let pipelineSection = 0; pipelineSection < array.length; pipelineSection++) { let stage = array[pipelineSection]; let keys = Object.keys(stage); if (keys.length !== 1) { throw new Error('Invalid pipeline instruction'); } switch (keys[0]) { case '$merge': case '$out': throw new Error('Cannot use potentially destructive pipeline stages') case '$match': this.hackVariables(array[pipelineSection]['$match']); retVal.push(array[pipelineSection]); if (!doneHiddenFields && Object.keys(hiddenFields) && Object.keys(hiddenFields).length > 0) { // We can now project out the hidden fields (we wait for the $match to make sure we don't break // a select that uses a hidden field retVal.push({$project: hiddenFields}); doneHiddenFields = true; } stage = null; break; case '$lookup': // hide any hiddenfields in the lookup collection const collectionName = stage.$lookup.from; const lookupField = stage.$lookup.as; if ((collectionName + lookupField).indexOf('$') !== -1) { throw new Error('No support for lookups where the "from" or "as" is anything other than a simple string') } const resource = that.getResourceFromCollection(collectionName); if (resource) { if (resource.options?.hide?.length > 0) { const hiddenLookupFields = this.generateHiddenFields(resource, false); let hiddenFieldsObj: any = {} Object.keys(hiddenLookupFields).forEach(hf => { hiddenFieldsObj[`${lookupField}.${hf}`] = false; }) retVal.push({$project: hiddenFieldsObj}); } } break; default: // nothing break; } if (stage) { retVal.push(stage); } } if (!doneHiddenFields && Object.keys(hiddenFields) && Object.keys(hiddenFields).length > 0) { // If there was no $match we still need to hide the hidden fields retVal.unshift({$project: hiddenFields}); } return retVal; } reportInternal(req, resource, schema, callback) { let runPipelineStr: string; let runPipelineObj: any; let self = this; if (typeof req.query === 'undefined') { req.query = {}; } self.doFindFunc(req, resource, function (err, queryObj) { if (err) { return 'There was a problem with the findFunc for model'; } else { runPipelineStr = JSON.stringify(schema.pipeline); for (let param in req.query) { if (req.query.hasOwnProperty(param)) { if (req.query[param]) { if (param !== 'r') { // we don't want to copy the whole report schema (again!) schema.params[param].value = req.query[param]; } } } } // Replace parameters with the value if (runPipelineStr) { runPipelineStr = runPipelineStr.replace(/"\(.+?\)"/g, function (match) { let sparam = schema.params[match.slice(2, -2)]; if (sparam.type === 'number') { return sparam.value; } else if (_.isObject(sparam.value)) { return JSON.stringify(sparam.value); } else if (sparam.value[0] === '{') { return sparam.value; } else { return '"' + sparam.value + '"'; } }); } runPipelineObj = JSON.parse(runPipelineStr); let hiddenFields = self.generateHiddenFields(resource, false); let toDo: any = { runAggregation: function (cb) { runPipelineObj = self.sanitisePipeline(runPipelineObj, hiddenFields, queryObj); resource.model.aggregate(runPipelineObj, cb); } }; let translations = []; // array of form {ref:'lookupname',translations:[{value:xx, display:' '}]} // if we need to do any column translations add the function to the tasks list if (schema.columnTranslations) { toDo.applyTranslations = ['runAggregation', function (results: any, cb) { function doATranslate(column, theTranslation) { results['runAggregation'].forEach(function (resultRow) { let valToTranslate = resultRow[column.field]; valToTranslate = (valToTranslate ? valToTranslate.toString() : ''); let thisTranslation = _.find(theTranslation.translations, function (option) { return valToTranslate === option.value.toString(); }); resultRow[column.field] = thisTranslation ? thisTranslation.display : ' * Missing columnTranslation * '; }); } schema.columnTranslations.forEach(function (columnTranslation) { if (columnTranslation.translations) { doATranslate(columnTranslation, columnTranslation); } if (columnTranslation.ref) { let theTranslation = _.find(translations, function (translation) { return (translation.ref === columnTranslation.ref); }); if (theTranslation) { doATranslate(columnTranslation, theTranslation); } else { cb('Invalid ref property of ' + columnTranslation.ref + ' in columnTranslations ' + columnTranslation.field); } } }); cb(null, null); }]; let callFuncs = false; for (let i = 0; i < schema.columnTranslations.length; i++) { let thisColumnTranslation = schema.columnTranslations[i]; if (thisColumnTranslation.field) { // if any of the column translations are adhoc funcs, set up the tasks to perform them if (thisColumnTranslation.fn) { callFuncs = true; } // if this column translation is a "ref", set up the tasks to look up the values and populate the translations if (thisColumnTranslation.ref) { let lookup = self.getResource(thisColumnTranslation.ref); if (lookup) { if (!toDo[thisColumnTranslation.ref]) { let getFunc = function (ref) { let lookup = ref; return function (cb) { let translateObject = {ref: lookup.resourceName, translations: []}; translations.push(translateObject); lookup.model.find({}, {}, {lean: true}, function (err, findResults) { if (err) { cb(err); } else { // TODO - this ref func can probably be done away with now that list fields can have ref let j = 0; async.whilst( function () { return j < findResults.length; }, function (cbres) { let theResult = findResults[j]; translateObject.translations[j] = translateObject.translations[j] || {}; let theTranslation = translateObject.translations[j]; j++; self.getListFields(lookup, theResult, function (err, description) { if (err) { cbres(err); } else { theTranslation.value = theResult._id; theTranslation.display = description; cbres(null); } }) }, cb ); } }); }; }; toDo[thisColumnTranslation.ref] = getFunc(lookup); toDo.applyTranslations.unshift(thisColumnTranslation.ref); // Make sure we populate lookup before doing translation } } else { return callback('Invalid ref property of ' + thisColumnTranslation.ref + ' in columnTranslations ' + thisColumnTranslation.field); } } if (!thisColumnTranslation.translations && !thisColumnTranslation.ref && !thisColumnTranslation.fn) { return callback('A column translation needs a ref, fn or a translations property - ' + thisColumnTranslation.field + ' has neither'); } } else { return callback('A column translation needs a field property'); } } if (callFuncs) { toDo['callFunctions'] = ['runAggregation', function (results, cb) { async.each(results.runAggregation, function (row, cb) { for (let i = 0; i < schema.columnTranslations.length; i++) { let thisColumnTranslation = schema.columnTranslations[i]; if (thisColumnTranslation.fn) { thisColumnTranslation.fn(row, cb); } } }, function () { cb(null); }); }]; toDo.applyTranslations.unshift('callFunctions'); // Make sure we do function before translating its result } } async.auto(toDo, function (err, results) { if (err) { callback(err); } else { // TODO: Could loop through schema.params and just send back the values callback(null, { success: true, schema: schema, report: results.runAggregation, paramsUsed: schema.params }); } }); } }); }; saveAndRespond(req, res, hiddenFields) { function internalSave(doc) { doc.save(function (err, doc2) { if (err) { let err2: any = {status: 'err'}; if (!err.errors) { err2.message = err.message; } else { extend(err2, err); } if (debug) { console.log('Error saving record: ' + JSON.stringify(err2)); } res.status(400).send(err2); } else { doc2 = doc2.toObject(); for (const hiddenField in hiddenFields) { if (hiddenFields.hasOwnProperty(hiddenField) && hiddenFields[hiddenField]) { let parts = hiddenField.split('.'); let lastPart = parts.length - 1; let target = doc2; for (let i = 0; i < lastPart; i++) { if (target.hasOwnProperty(parts[i])) { target = target[parts[i]]; } } if (target.hasOwnProperty(parts[lastPart])) { delete target[parts[lastPart]]; } } } res.send(doc2); } }); } let doc = req.doc; if (typeof req.resource.options.onSave === 'function') { req.resource.options.onSave(doc, req, function (err) { if (err) { throw err; } internalSave(doc); }); } else { internalSave(doc); } }; /** * All entities REST functions have to go through this first. */ processCollection(req) { req.resource = this.getResource(req.params.resourceName); }; /** * Renders a view with the list of docs, which may be modified by query parameters */ collectionGet() { return _.bind(function (req, res, next) { this.processCollection(req); if (!req.resource) { return next(); } if (typeof req.query === 'undefined') { req.query = {}; } try { const aggregationParam = req.query.a ? JSON.parse(req.query.a) : null; const findParam = req.query.f ? JSON.parse(req.query.f) : {}; const projectParam = req.query.p ? JSON.parse(req.query.p) : {}; const limitParam = req.query.l ? JSON.parse(req.query.l) : 0; const skipParam = req.query.s ? JSON.parse(req.query.s) : 0; const orderParam = req.query.o ? JSON.parse(req.query.o) : req.resource.options.listOrder; // Dates in aggregation must be Dates if (aggregationParam) { this.hackVariablesInPipeline(aggregationParam); } const self = this; this.filteredFind(req.resource, req, aggregationParam, findParam, projectParam, orderParam, limitParam, skipParam, function (err, docs) { if (err) { return self.renderError(err, null, req, res, next); } else { res.send(docs); } }); } catch (e) { res.send(e); } }, this); }; generateProjection(hiddenFields, projectParam): any { let type; function setSelectType(typeChar, checkChar) { if (type === checkChar) { throw new Error('Cannot mix include and exclude fields in select'); } else { type = typeChar; } } let retVal: any = hiddenFields; if (projectParam) { let projection = Object.keys(projectParam); if (projection.length > 0) { projection.forEach(p => { if (projectParam[p] === 0) { setSelectType('E', 'I'); } else if (projectParam[p] === 1) { setSelectType('I', 'E'); } else { throw new Error('Invalid projection: ' + projectParam); } }); if (type && type === 'E') { // We are excluding fields - can just merge with hiddenFields Object.assign(retVal, projectParam, hiddenFields); } else { // We are selecting fields - make sure none are hidden retVal = projectParam; for (let h in hiddenFields) { if (hiddenFields.hasOwnProperty(h)) { delete retVal[h]; } } } } } return retVal; }; doFindFunc(req, resource, cb) { if (resource.options.findFunc) { resource.options.findFunc(req, cb); } else { cb(null); } }; filteredFind( resource: Resource, req: Express.Request, aggregationParam: any, findParam: any, projectParam: any, sortOrder: any, limit: number | null, skip: number | null, callback: (err: Error, docs?: any[]) => void) { const that = this; let hiddenFields = this.generateHiddenFields(resource, false); let stashAggregationResults; function doAggregation(queryObj, cb) { if (aggregationParam) { aggregationParam = that.sanitisePipeline(aggregationParam, hiddenFields, queryObj); resource.model.aggregate(aggregationParam, function (err, aggregationResults) { if (err) { throw err; } else { stashAggregationResults = aggregationResults; cb(_.map(aggregationResults, function (obj) { return obj._id; })); } }); } else { cb([]); } } that.doFindFunc(req, resource, function (err, queryObj) { if (err) { callback(err); } else { doAggregation(queryObj, function (idArray) { if (aggregationParam && idArray.length === 0) { callback(null, []); } else { let query = resource.model.find(queryObj); if (idArray.length > 0) { query = query.where('_id').in(idArray); } if (findParam) { query = query.find(findParam); } query = query.select(that.generateProjection(hiddenFields, projectParam)); if (limit) { query = query.limit(limit); } if (skip) { query = query.skip(skip); } if (sortOrder) { query = query.sort(sortOrder); } query.exec(function (err, docs) { if (!err && stashAggregationResults) { docs.forEach(obj => { // Add any fields from the aggregation results whose field name starts __ to the mongoose Document let aggObj = stashAggregationResults.find(a => a._id.toString() === obj._id.toString()); Object.keys(aggObj).forEach(k => { if (k.slice(0, 2) === '__') { obj[k] = aggObj[k]; } }); }) } callback(err, docs) }); } }); } }); }; collectionPost() { return _.bind(function (req, res, next) { this.processCollection(req); if (!req.resource) { next(); return; } if (!req.body) { throw new Error('Nothing submitted.'); } let cleansedBody = this.cleanseRequest(req); req.doc = new req.resource.model(cleansedBody); this.saveAndRespond(req, res); }, this); }; /** * Generate an object of fields to not expose **/ generateHiddenFields(resource: Resource, state: boolean): { [fieldName: string]: boolean } { let hiddenFields = {}; if (resource.options['hide'] !== undefined) { resource.options.hide.forEach(function (dt) { hiddenFields[dt] = state; }); } return hiddenFields; }; /** Sec issue * Cleanse incoming data to avoid overwrite and POST request forgery * (name may seem weird but it was in French, so it is some small improvement!) */ cleanseRequest(req) { let reqData = req.body, resource = req.resource; delete reqData.__v; // Don't mess with Mongoose internal field (https://github.com/LearnBoost/mongoose/issues/1933) if (typeof resource.options['hide'] === 'undefined') { return reqData; } let hiddenFields = resource.options.hide; _.each(reqData, function (num, key) { _.each(hiddenFields, function (fi) { if (fi === key) { delete reqData[key]; } }); }); return reqData; }; generateQueryForEntity(req, resource, id, cb) { let that = this; let hiddenFields = this.generateHiddenFields(resource, false); hiddenFields.__v = false; that.doFindFunc(req, resource, function (err, queryObj) { if (err) { cb(err); } else { const idSel = {_id: id}; let crit; if (queryObj) { if (queryObj._id) { crit = {$and: [idSel, {_id: queryObj._id}]}; delete queryObj._id; if (Object.keys(queryObj).length > 0) { crit = extend(crit, queryObj); } } else { crit = extend(queryObj, idSel); } } else { crit = idSel; } cb(null, resource.model.findOne(crit).select(that.generateProjection(hiddenFields, req.query.p))); } }); }; /* * Entity request goes here first * It retrieves the resource */ processEntity(req, res, next) { if (!(req.resource = this.getResource(req.params.resourceName))) { next(); return; } this.generateQueryForEntity(req, req.resource, req.params.id, function (err, query) { if (err) { return res.status(500).send({ success: false, err: util.inspect(err) }); } else { query.exec(function (err, doc) { if (err) { return res.status(400).send({ success: false, err: util.inspect(err) }); } else if (doc == null) { return res.status(404).send({ success: false, err: 'Record not found' }); } req.doc = doc; next(); }); } }); }; /** * Gets a single entity * * @return {Function} The function to use as route */ entityGet() { return _.bind(function (req, res, next) { this.processEntity(req, res, function () { if (!req.resource) { return next(); } if (req.resource.options.onAccess) { req.resource.options.onAccess(req, function () { return res.status(200).send(req.doc); }); } else { return res.status(200).send(req.doc); } }); }, this); }; replaceHiddenFields(record, data) { const self = this; if (record) { record._replacingHiddenFields = true; _.each(data, function (value, name) { if (_.isObject(value) && !Array.isArray(value)) { self.replaceHiddenFields(record[name], value); } else if (!record[name]) { record[name] = value; } }); delete record._replacingHiddenFields; } }; entityPut() { return _.bind(function (req, res, next) { const that = this; this.processEntity(req, res, function () { if (!req.resource) { next(); return; } if (!req.body) { throw new Error('Nothing submitted.'); } let cleansedBody = that.cleanseRequest(req); // Merge for (let prop in cleansedBody) { if (cleansedBody.hasOwnProperty(prop)) { req.doc.set(prop, cleansedBody[prop] === '' ? undefined : cleansedBody[prop]) } } if (req.resource.options.hide !== undefined) { let hiddenFields = that.generateHiddenFields(req.resource, true); hiddenFields._id = false; req.resource.model.findById(req.doc._id, hiddenFields, {lean: true}, function (err, data) { that.replaceHiddenFields(req.doc, data); that.saveAndRespond(req, res, hiddenFields); }); } else { that.saveAndRespond(req, res); } }); }, this); }; entityDelete() { let that = this; return _.bind(async function (req, res, next) { function generateDependencyList(resource: Resource) { if (resource.options.dependents === undefined) { resource.options.dependents = that.resources.reduce(function (acc, r) { function searchPaths(schema, prefix) { var fldList = []; for (var fld in schema.paths) { if (schema.paths.hasOwnProperty(fld)) { var parts = fld.split('.'); var schemaType = schema.tree; while (parts.length > 0) { schemaType = schemaType[parts.shift()]; } if (schemaType.type) { if (schemaType.type.name === 'ObjectId' && schemaType.ref === resource.resourceName) { fldList.push(prefix + fld); } else if (_.isArray(schemaType.type)) { schemaType.type.forEach(function (t) { searchPaths(t, prefix + fld + '.'); }); } } } } if (fldList.length > 0) { acc.push({resource: r, keys: fldList}); } } if (r !== resource) { searchPaths(r.model.schema, ''); } return acc; }, []); } } async function removeDoc(doc: Document, resource: Resource): Promise<any> { switch (resource.options.handleRemove) { case 'allow': // old behaviour - no attempt to maintain data integrity return doc.remove(); case 'cascade': generateDependencyList(resource); res.status(400).send('"cascade" option not yet supported') break; default: generateDependencyList(resource); let promises = []; resource.options.dependents.forEach(collection => { collection.keys.forEach(key => { promises.push({ p: collection.resource.model.find({[key]: doc._id}).limit(1).exec(), collection, key }); }) }) return Promise.all(promises.map(p => p.p)) .then((results) => { results.forEach((r, i) => { if (r.length > 0) { throw new ForeignKeyError(resource.resourceName, promises[i].collection.resource.resourceName, promises[i].key, r[0]._id); } }) return doc.remove(); }) } } async function runDeletion(doc: Document, resource: Resource): Promise<any> { return new Promise((resolve) => { if (resource.options.onRemove) { resource.options.onRemove(doc, req, async function (err) { if (err) { throw err; } resolve(removeDoc(doc, resource)); }); } else { resolve(removeDoc(doc, resource)); } }) } this.processEntity(req, res, async function () { if (!req.resource) { next(); return; } let doc = req.doc; try { void await runDeletion(doc, req.resource) res.status(200).send(); } catch (e) { if (e instanceof ForeignKeyError) { res.status(400).send(e.message); } else { res.status(500).send(e.message); } } }); }, this); }; entityList() { return _.bind(function (req, res, next) { const that = this; this.processEntity(req, res, function () { if (!req.resource) { return next(); } that.getListFields(req.resource, req.doc, function (err, display) { if (err) { return res.status(500).send(err); } else { return res.send({list: display}); } }) }); }, this); }; extractTimestampFromMongoID(record: any): Date { let timestamp = record.toString().substring(0, 8); return new Date(parseInt(timestamp, 16) * 1000); } } class ForeignKeyError extends global.Error { constructor(resourceName, foreignKeyOnResource, foreignItem, id) { super(`Cannot delete this ${resourceName}, as it is the ${foreignItem} on ${foreignKeyOnResource} ${id}`); this.name = "ForeignKeyError"; this.stack = (<any>new global.Error('')).stack; } }
the_stack
// TODO: this is where we left off in the spec doc: // http://raml.org/spec.html#resource-types-and-traits declare module Raml08Parser { type GlobalSchemas = { [schemaName: string /* SchemaName */]: SchemaDefinition }[] type SchemaName = string type SecuredBy = Array<SecuritySchemeName | PartialSecuritySchemeDescribedByObject /* | Null*/> type SecuritySchemeName = string type PartialSecuritySchemeDescribedByObject = { [securitySchemeName: string]: { [name: string]: any } } type MarkdownString = string /** * One of: "HTTP", "HTTPS" */ type Protocol = string type ParameterMap = { [name: string]: string } type TraitReference = Array<string | { [trait: string]: ParameterMap }> type ResourceTypeReference = string | { [resourceType: string]: ParameterMap } /** * One of the following YAML media types: * - text/yaml * - text/x-yaml * - application/yaml * - application/x-yaml * * Any type from the list of IANA MIME Media Types, http://www.iana.org/assignments/media-types * A custom type that conforms to the regular expression, "application\/[A-Za-z.-0-1]*+?(json|xml)" * */ type MediaType = string /** * JSON Schemas as strings * XSDs as strings */ type SchemaDefinition = string /** * Regular expressions MUST follow the regular expression specification from ECMA 262/Perl 5. */ type RegexPattern = string /** * A valid HTTP method name in lowercase ( "put", "get", ... ) */ type HTTPMethodName = string /** * One of: * * - OAuth 1.0 * - OAuth 2.0 * - Basic Authentication * - Digest Authentication * - x-{other} * * @see http://raml.org/spec.html#type-1 */ type SecuritySchemeType = string interface Api { // TODO: what do we do with required types? // is the JS parser failing when such properties are missing? /** * * (Required) The title property is a short plain text description of the RESTful API. * The title property's value SHOULD be suitable for use as a title for the contained user documentation. * * @see http://raml.org/spec.html#api-title */ title?: string /** * (Optional) If the RAML API definition is targeted to a specific API version, the API definition MUST contain a version property. The version property is OPTIONAL and should not be used if: * * The API itself is not versioned. * The API definition does not change between versions. The API architect can decide whether a change to user documentation elements, but no change to the API's resources, constitutes a version change. * The API architect MAY use any versioning scheme so long as version numbers retain the same format. For example, "v3", "v3.0", and "V3" are all allowed, but are not considered to be equal. */ version?: string /** * * @see http://raml.org/spec.html#base-uri-and-baseuriparameters */ baseUri?: string /** * @see http://raml.org/spec.html#base-uri-and-baseuriparameters */ baseUriParameters?: NamedParameterMap /** * (Optional) A RESTful API can be reached HTTP, HTTPS, or both. * The protocols property MAY be used to specify the protocols that an API supports. * If the protocols property is not specified, the protocol specified at the baseUri property is used. * The protocols property MUST be an array of strings, of values "HTTP" and/or "HTTPS". * * @see http://raml.org/spec.html#protocols */ protocols?: Protocol[] /** * (Optional) The media types returned by API responses, and expected from API requests that accept a body, * MAY be defaulted by specifying the mediaType property. * This property is specified at the root level of the API definition. * The property's value MAY be a single string with a valid media type * * @see http://raml.org/spec.html#default-media-type */ mediaType?: MediaType /** * (Optional) To better achieve consistency and simplicity, * the API definition SHOULD include an OPTIONAL schemas property in the root section. * The schemas property specifies collections of schemas that could be used anywhere in the API definition. * The value of the schemas property is an array of maps; in each map, the keys are the schema name, * and the values are schema definitions. * * @see http://raml.org/spec.html#schemas */ schemas?: GlobalSchemas /** * * (Optional) In addition to the reserved URI parameters described in the baseUri property section, * a Level 1 Template URI can feature custom URI parameters, which are useful in a variety of scenarios. * For example, let's look at the following API provider that parametrizes the base URI with customer * information such as the company name. * * @see http://raml.org/spec.html#uri-parameters */ uriParameters?: NamedParameterMap /** * (Optional) The API definition can include a variety of documents that serve as a user guides * and reference documentation for the API. Such documents can clarify how the API works * or provide business context. * * @see http://raml.org/spec.html#user-documentation */ documentation?: DocumentationItem[] /** * @see http://raml.org/spec.html#resources-and-nested-resources */ resources?: Resource[] /** * * @see http://raml.org/spec.html#resource-types-and-traits */ resourceTypes?: { [resourceTypeName: string]: ResourceType }[] securitySchemes?: { [securitySchemeName: string]: SecurityScheme }[] traits?: { [traitName: string]: Trait }[] securedBy?: SecuredBy } interface Resource { relativeUri: string /** * This is added by the JS parser. * * relativeUri = /foo/{bar}/baz/{xxx} * relativeUriPathSegments = ['bar', 'xxx'] */ relativeUriPathSegments: string[] /** * The displayName attribute provides a friendly name to the resource and can be used by documentation generation tools. * The displayName key is OPTIONAL. * * If the displayName attribute is not defined for a resource, * documentation tools SHOULD refer to the resource by its property key (i.e. its relative URI, e.g., "/jobs"), * which acts as the resource's name. * * @see http://raml.org/spec.html#display-name */ displayName?: string /** * Each resource, whether top-level or nested, MAY contain a description property that briefly describes the resource. * It is RECOMMENDED that all the API definition's resources includes the description property. * * @see http://raml.org/spec.html#description-1 */ description?: MarkdownString /** * An array of applied traits on the current resource. * * https://github.com/raml-org/raml-spec/blob/master/raml-0.8.md#applying-resource-types-and-traits */ is?: TraitReference /** * * In a RESTful API, methods are operations that are performed on a resource. * A method MUST be one of the HTTP methods defined * in the HTTP version 1.1 specification [RFC2616] and its extension, RFC5789 [RFC5789]. * * @see http://raml.org/spec.html#methods */ methods?: Method[] /** * https://github.com/raml-org/raml-spec/blob/master/raml-0.8.md#applying-resource-types-and-traits */ type?: string | ResourceTypeReference /** * @see http://raml.org/spec.html#template-uris-and-uri-parameters */ uriParameters?: NamedParameterMap /** * * A resource or a method can override a base URI template's values. * This is useful to restrict or change the default or parameter selection in the base URI. * The baseUriParameters property MAY be used to override any or all parameters * defined at the root level baseUriParameters property, * as well as base URI parameters not specified at the root level. * * @see http://raml.org/spec.html#base-uri-parameters */ baseUriParameters?: NamedParameterMap resources?: Resource[] securedBy?: SecuredBy } /** * * In a RESTful API, methods are operations that are performed on a resource. * A method MUST be one of the HTTP methods defined in the HTTP version 1.1 specification [RFC2616] * and its extension, RFC5789 [RFC5789]. * * @see http://raml.org/spec.html#methods */ interface Method { /** * The HTTP verb corresponding to this method */ method: HTTPMethodName /** * * Each declared method MAY contain a description attribute that briefly describes * what the method does to the resource. * It is RECOMMENDED that all API definition methods include the description property. * * The value of the description property MAY be formatted using Markdown [MARKDOWN]. * * @see http://raml.org/spec.html#description-2 */ description?: MarkdownString /** * A method can override an API's protocols value for that single method by setting a different value for the fields. * * @see http://raml.org/spec.html#protocols-1 */ protocols?: Protocol[] /** * * An API's resources MAY be filtered (to return a subset of results) * or altered (such as transforming a response body from JSON to XML format) * by the use of query strings. * * If the resource or its method supports a query string, the query string * MUST be defined by the queryParameters property. * * @see http://raml.org/spec.html#query-strings */ queryParameters?: NamedParameterMap /** * * Resource methods MAY have one or more responses. * Responses MAY be described using the description property, and MAY include example attributes or schema properties. * * @see http://raml.org/spec.html#responses */ responses?: Responses /** * Null means that it is not secured ( it is anonymous ) */ securedBy?: SecuredBy /** * * Some method verbs expect the resource to be sent as a request body. * For example, to create a resource, the request must include the details of the resource to create. * * Resources CAN have alternate representations. * For example, an API might support both JSON and XML representations. * * If the API's media type is either application/x-www-form-urlencoded or multipart/form-data, * the formParameters property MUST specify the name-value pairs that the API is expecting. * * @see http://raml.org/spec.html#body */ body?: Bodies /** * * An API's methods MAY support or require non-standard HTTP headers. * In the API definition, specify the non-standard HTTP headers by using the headers property. * * @see http://raml.org/spec.html#headers */ headers?: NamedParameterMap /** * An array of applied traits on the current resource. * * https://github.com/raml-org/raml-spec/blob/master/raml-0.8.md#applying-resource-types-and-traits */ is?: TraitReference } interface ResourceType { description?: string uriParameters?: NamedParameterMap // TODO "get?"?: Method "post?"?: Method "put?"?: Method "delete?"?: Method } /** * Each document MUST contain title and content attributes, * both of which are REQUIRED. * Documentation-generators MUST process the content field as if it was defined using Markdown [MARKDOWN]. * * @see http://raml.org/spec.html#user-documentation */ interface DocumentationItem { title: string content: MarkdownString } /** * * Resource methods MAY have one or more responses. * * @see http://raml.org/spec.html#responses */ interface Response { /** * Responses MAY contain a description property that further clarifies why the response was emitted. * Response descriptions are particularly useful for describing error conditions. */ description?: MarkdownString /** * An API's methods may support custom header values in responses. * The custom, non-standard HTTP headers MUST be specified by the headers property. * * @see http://raml.org/spec.html#headers-1 */ headers?: NamedParameterMap body?: Bodies } /** * @see http://raml.org/spec.html#security */ interface SecurityScheme { type?: SecuritySchemeType description?: MarkdownString settings?: { [settingName: string]: string } describedBy?: SecuritySchemeDescription } interface SecuritySchemeDescription { uriParameters?: NamedParameterMap queryParameters?: NamedParameterMap headers?: NamedParameterMap responses?: Responses } // TODO interface Trait { description?: MarkdownString } interface Bodies { "application/x-www-form-urlencoded"?: WebFormBodyPayload; "multipart/form-data"?: WebFormBodyPayload; [mediaType: string]: BodyPayload; } interface BodyPayload { /** * The structure of a request or response body MAY be further specified by the schema property under the appropriate media type. * * All parsers of RAML MUST be able to interpret JSON Schema [JSON_SCHEMA] and XML Schema [XML_SCHEMA]. * * Alternatively, the value of the schema field MAY be the name of a schema specified in the * root-level schemas property * * @see http://raml.org/spec.html#schema */ schema?: SchemaName | SchemaDefinition /** * @see http://raml.org/spec.html#example-4 */ example?: string } /** * @see: http://raml.org/spec.html#web-forms */ interface WebFormBodyPayload { formParameters?: NamedParameterMap /** * @see http://raml.org/spec.html#example-4 */ example?: string } /** * if the entry is null it means that the response ( for the given status code ) exists but there's no more data describing it */ interface Responses { [statusCode: string]: Response // | Null } interface NamedParameterMap { [parameterName: string]: NamedParameter | NamedParameter[] } /** * @see http://raml.org/spec.html#named-parameters */ interface BasicNamedParameter { /** * (Optional) The description attribute describes the intended use or meaning of the parameter. * This value MAY be formatted using Markdown [MARKDOWN]. * * @see http://raml.org/spec.html#description */ description?: MarkdownString /** * (Optional) The displayName attribute specifies the parameter's display name. * It is a friendly name used only for display or documentation purposes. * If displayName is not specified, it defaults to the property's key (the name of the property itself). * * @see http://raml.org/spec.html#displayname */ displayName?: string /** * (Optional, applicable only for parameters of type string) * The enum attribute provides an enumeration of the parameter's valid values. * This MUST be an array. * * If the enum attribute is defined, API clients and servers MUST verify * that a parameter's value matches a value in the enum array. * * If there is no matching value, the clients and servers MUST treat this as an error. * * @see http://raml.org/spec.html#enum */ 'enum'?: any[] // TODO: types should be a string enum. They are not supported by Typescript at the moment /** * (Optional) The type attribute specifies the primitive type of the parameter's resolved value. * API clients MUST return/throw an error if the parameter's resolved value does not match the specified type. * If type is not specified, it defaults to string. * * @see http://raml.org/spec.html#type */ type?: string // string, integer // TODO: verify on JS parser output /** * (Optional) The example attribute shows an example value for the property. * This can be used, e.g., by documentation generators to generate sample values for the property. * * @see http://raml.org/spec.html#example */ example?: any // or string? // TODO: verify on JS parser output /** * (Optional) The repeat attribute specifies that the parameter can be repeated. * If the parameter can be used multiple times, the repeat parameter value MUST be set to 'true'. * Otherwise, the default value is 'false' and the parameter may not be repeated. * * @see http://raml.org/spec.html#repeat */ repeat?: boolean // TODO: verify on JS parser output /** * (Optional except as otherwise noted) * The required attribute specifies whether the parameter and its value MUST be present in the API definition. * It must be either 'true' if the value MUST be present or 'false' otherwise. * In general, parameters are optional unless the required attribute is included and its value set to 'true'. * For a URI parameter, the required attribute MAY be omitted, but its default value is 'true'. * * @see http://raml.org/spec.html#required */ required?: boolean // TODO: verify on JS parser output /** * (Optional) * The default attribute specifies the default value to use for the property if the property is omitted * or its value is not specified. * This SHOULD NOT be interpreted as a requirement for the client to send the default attribute's value * if there is no other value to send. Instead, the default attribute's value is the value the server uses * if the client does not send a value. */ 'default'?: any } interface NumericNamedParameter extends BasicNamedParameter { /** * (Optional, applicable only for parameters of type number or integer) * The minimum attribute specifies the parameter's minimum value. * * @see http://raml.org/spec.html#minimum */ minimum?: number /** * (Optional, applicable only for parameters of type number or integer) * The maximum attribute specifies the parameter's maximum value. * * @see http://raml.org/spec.html#maximum */ maximum?: number } interface StringNamedParameter extends BasicNamedParameter { // TODO: verify on JS parser output /** * (Optional, applicable only for parameters of type string) * * The pattern attribute is a regular expression that a parameter of type string MUST match. * The pattern MAY be enclosed in double quotes for readability and clarity. * ( in the JS parser. are the quotes preserved? ) * * @see http://raml.org/spec.html#pattern */ pattern?: RegexPattern // TODO: verify on JS parser output /** * (Optional, applicable only for parameters of type string) * The minLength attribute specifies the parameter value's minimum number of characters. * * @see http://raml.org/spec.html#minlength */ minLength?: number // TODO: verify on JS parser output /** * (Optional, applicable only for parameters of type string) * The maxLength attribute specifies the parameter value's maximum number of characters. * * @see http://raml.org/spec.html#maxlength */ maxLength?: number } type NamedParameter = BasicNamedParameter | NumericNamedParameter | StringNamedParameter } declare module "raml-parser" { class FileReader { constructor(cb: (path: string) => Promise<string>); } interface LoadOptions { reader: FileReader } function loadFile(url: string, options?: LoadOptions): Q.Promise<Raml08Parser.Api> function load(str: string, path?: string, options?: LoadOptions): Q.Promise<Raml08Parser.Api> }
the_stack
import { Model } from './model'; // import { Entity } from './entity'; import { ModelBuilder } from './builder'; import { Builder } from '../database/builder'; import { HasRelations, BelongsToMany } from './relations'; const inspect = Symbol.for('nodejs.util.inspect.custom'); export class Repository<TEntity = any> { /** * 模型仓库是否已存在 */ private exists = false; /** * 模型实例 */ private model: Model<TEntity>; /** * 已更新的字段名集合 */ private updateAttributeColumns: Set<string> = new Set(); /** * 渴求式加载对象集合 * Want to load a collection of objects */ private withs: Map<string, { relation: HasRelations; queryCallback?: (query: Builder) => void; }> = new Map(); /** * 创建模型仓库实例 * @param model */ constructor(model: Model<TEntity>) { this.model = model; return new Proxy(this, this.proxy()); } /** * 代理器 */ private proxy(): ProxyHandler<this> { return { set(target: any, p: string | number | symbol, value: any, receiver: any) { if (target.isExists()) { target.addUpdateAttributeColumn(p); } return Reflect.set(target, p, value, receiver); } }; } /** * 是否已存在 */ isExists() { return this.exists; } /** * 设置是否已存在 * @param exists */ setExists(exists = true) { this.exists = exists; return this; } /** * 是否更新了模型仓库的数据 */ private hasUpdatedAttributes() { return !!this.updateAttributeColumns.size; } /** * 添加修改更新的字段 * @param key */ private addUpdateAttributeColumn(key: string) { const columns = [...this.model.getColumns().keys()]; if (columns.includes(key)) { this.updateAttributeColumns.add(key); } return this; } /** * 获取已更新的属性 */ private getUpdatedAttributes() { const attributes: Record<string, any> = {}; for (const column of this.updateAttributeColumns) { attributes[column] = (this as any)[column]; } return attributes; } /** * 创建模型查询构造器 */ createQueryBuilder(): ModelBuilder<TEntity> & Builder { return (new ModelBuilder(this.model, this)).prepare() as ModelBuilder<TEntity> & Builder; } /** * 获取主键值 */ getPrimaryValue() { return (this as any)[this.model.getPrimaryKey()] ?? null; } /** * 填充数据到仓库 * @param data */ fill(data: any) { if (!data) return this; const keys = this.model.getColumns().keys(); for (const key of keys) { this.setAttribute(key, data[key]); } return this; } /** * 获取仓库数据属性 */ getAttributes() { const attributes: Record<string, any> = {}; const columns = this.model.getColumns().keys(); for (const column of columns) { attributes[column] = (this as any)[column]; } const customs = this.model.getCustomColumns().keys(); for (const custom of customs) { attributes[custom] = (this as any)[custom]; } const relationMap = this.model.getRelationMap(); for (const realtion of relationMap.keys()) { const _realtion = (this as any)[realtion]; if (_realtion) { if (Array.isArray(_realtion)) { attributes[realtion] = _realtion.map(item => item?.getAttributes()); } else { attributes[realtion] = _realtion?.getAttributes(); } } } return attributes; } /** * 设置仓库数据属性 * @param key * @param value */ setAttribute(key: string, value: any) { if (value === undefined) return this; (this as any)[key] = value; // 模型已存在的情况下配置更新字段 // Configure update fields if the model already exists if (this.isExists()) { this.addUpdateAttributeColumn(key); } return this; } /** * get attr with key * @param key */ getAttribute(key: string) { if (!key) return; if ( this.model.getColumns().has(key) || this.model.getCustomColumns().includes(key) || this.model.getRelationMap().has(key) ) return (this as any)[key]; } /** * Eager loading * @param relations */ with(relation: string, callback?: (query: Builder) => void) { const relationImp = this.model.getRelationImp(relation); if (relationImp) { this.setWith(relation, relationImp, callback); }; return this; } /** * 获取渴求式加载关联关系 */ getWiths() { return this.withs; } /** * set Eager load names * @param withs */ setWiths(withs: Map<string, any>) { this.withs = withs; return this; } /** * 设置渴求式加载关联关系 * @param relation * @param value */ setWith(relation: string, value: HasRelations, queryCallback?: (query: Builder) => void) { this.withs.set(relation, { relation: value, queryCallback }); return this; } /** * 渴求式加载 * @param result */ async eagerly(withs: Map<string, { relation: HasRelations; queryCallback?: (query: Builder) => void; }>, result: Repository) { for (const [relation, relationOption] of withs) { const { relation: relationImp, queryCallback } = relationOption; await relationImp.eagerly(result, relation, queryCallback); } } /** * 渴求式加载集合 * @param withs * @param results */ async eagerlyCollection(withs: Map<string, { relation: HasRelations; queryCallback?: (query: Builder) => void; }>, results: Repository[]) { for (const [relation, relationOption] of withs) { const { relation: relationImp, queryCallback } = relationOption; await relationImp.eagerlyMap(results, relation, queryCallback); } } /** * 对当前仓库执行删除操作 */ async delete() { if (!this.model.getPrimaryKey()) { throw new Error('Primary key not defined'); } if (!this.isExists()) return false; await this.executeDelete(); return true; } /** * 执行删除操作 */ private async executeDelete() { // 创建模型查询构建器 const query = this.createQueryBuilder(); // 强制删除数据库记录的情况 if (this.model.isForceDelete()) { await query.where( this.model.getPrimaryKey(), '=', this.getPrimaryValue() ).delete(); // 设置模型为不存在 this.setExists(false); return true; } // 软删除的情况 // 需要更新的字段 const attributes: Record<string, any> = {}; attributes[this.model.getSoftDeleteKey()] = this.model.getFormatedDate( this.model.getColumnType( this.model.getSoftDeleteKey() ) ); // 需要自动更新时间 if (this.model.hasUpdateTimestamp()) { const updateTimestampKey = this.model.getUpdateTimestampKey() as string; attributes[updateTimestampKey] = this.model.getFormatedDate( this.model.getColumnType(updateTimestampKey) ); } // 执行更新操作 return query.where( this.model.getPrimaryKey(), '=', this.getPrimaryValue() ).update(attributes); } /** * 根据主键获取模型仓库实例 * @param id */ async get(id: number | string) { const query = this.createQueryBuilder(); if (!this.model.isForceDelete()) { query.whereNull( this.model.getSoftDeleteKey() ); } return query.where( this.model.getPrimaryKey(), '=', id ).first(); } /** * 创建/更新数据库记录操作 * 自动根据场景来执行更新/创建操作 * Create/update database record operations * Update/create operations are performed automatically based on the scenario */ async save(): Promise<boolean> { const query = this.createQueryBuilder(); // 已存在模型 // Existing model if (this.isExists()) { // 没有字段需要更新的时候,直接返回 true if (!this.hasUpdatedAttributes()) return true; // 如果需要自动更新时间 if (this.model.hasUpdateTimestamp()) { const key = this.model.getUpdateTimestampKey() as string; const val = this.model.getFreshDateWithColumnKey(key); (this as any)[key] = val; } // 获取需要更新的数据 // 即模型实体有改动的的属性 const updatedAttributes = this.getUpdatedAttributes(); return this.executeUpdate( query, updatedAttributes ); } // 不存在模型 // There is no model else { if (this.model.hasCreateTimestamp()) { const key = this.model.getCreateTimestampKey() as string; const val = this.model.getFreshDateWithColumnKey(key); (this as any)[key] = val; } // 如果是递增主键 // 需要插入记录后并且返回记录id,将记录id设置到当前模型中 if (this.model.isIncrementing()) { // 执行插入操作并且设置模型主键值 await this.executeInsertAndSetId(query); } // 如果不是递增主键 // 普通主键必须由用户定义插入 // 由于不存在自动递增主键,当数据字段为空的时候直接返回 else { if (!this.model.getColumns().size) return true; await query.insert( this.getAttributes() ); } this.setExists(true); } return true; } /** * execute an insert operation, and set inserted id * @param query */ private async executeInsertAndSetId(query: ModelBuilder & Builder) { const id = await query.insert( this.getAttributes() ); this.setAttribute( this.model.getPrimaryKey(), id ); return this; } /** * execute an update operation * @param query * @param attributes */ private async executeUpdate(query: ModelBuilder & Builder, attributes: Record<string, any>) { await query.where( this.model.getPrimaryKey(), '=', this.getPrimaryValue() ).update(attributes); return true; } /** * 创建数据库记录 * Create database records * @param attributes */ async create(attributes: Record<string, any>) { // 创建一个不存在记录的模型 // Create a repos with no records const repos = this.model.createRepository().fill(attributes).setExists(false); await repos.save(); return repos; } /** * 根据主键值删除模型 * @param ids */ async destroy(...ids: (number | string)[]) { let count = 0; if (!ids.length) return count; const key = this.model.getPrimaryKey(); const results = await this.createQueryBuilder().whereIn(key, ids).find(); for (const result of results) { if (await result.delete()) { count++; } } return count; } /** * 转成 json 时只输出属性数据 */ toJSON() { return this.getAttributes(); } /** * 查看对象时只查看属性数据 */ [inspect]() { return this.toJSON(); } /** * 设置关联关系 * @param relation * @param ids */ async attach(relation: string, ...ids: (number | string)[]) { if (!this.isExists()) { throw new Error('model does not exists!'); } const relationMap = this.model.getRelationMap(); if (!relationMap.has(relation) || relationMap.get(relation)?.type !== 'belongsToMany') { throw new Error(`model does not have many to many relation: [${relation}]!`); } const imp = this.model.getRelationImp(relation) as BelongsToMany; const insertData: any[] = []; for (const id of ids) { insertData.push({ [`${imp.foreignPivotKey}`]: this.getPrimaryValue(), [`${imp.relatedPivotKey}`]: id, }); } const repos: Repository<TEntity> = imp.pivot.createRepository(); await repos .createQueryBuilder() .getBuilder() .insertAll(insertData); return repos; } /** * 取消关联关系 * @param relation * @param ids */ async detach(relation: string, ...ids: (number | string)[]) { if (!this.isExists()) { throw new Error('model does not exists!'); } const relationMap = this.model.getRelationMap(); if (!relationMap.has(relation) || relationMap.get(relation)?.type !== 'belongsToMany') { throw new Error(`model does not have many to many relation: [${relation}]!`); } const imp = this.model.getRelationImp(relation) as BelongsToMany; const repos: Repository<TEntity> = imp.pivot.createRepository(); await repos .createQueryBuilder() .getBuilder() .where(imp.foreignPivotKey as string, '=', this.getPrimaryValue()) .whereIn(imp.relatedPivotKey as string, ids) .delete(); return repos; } }
the_stack
import { IPivotValues, IDataOptions, IFieldOptions, IFilter, ISort, IFormatSettings } from './engine'; import { IDrillOptions, IValueSortSettings, IGroupSettings, IConditionalFormatSettings, ICustomGroups, FieldItemInfo } from './engine'; import { ICalculatedFieldSettings, IAuthenticationInfo, IGridValues, IAxisSet } from './engine'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { PivotView, PivotViewModel } from '../pivotview'; import { PivotFieldList, PivotFieldListModel } from '../pivotfieldlist'; import { DataManager, Query } from '@syncfusion/ej2-data'; import { SummaryTypes } from './types'; import { IOlapField } from './olap/engine'; import { ExcelExportProperties, ExcelRow } from '@syncfusion/ej2-grids'; /** * This is a file to perform common utility for OLAP and Relational datasource * @hidden */ export class PivotUtil { public static getType(value: any): string { let val: string; let dateValue: any = new Date(value); if (typeof value === 'boolean') { val = 'boolean'; } else if (!isNaN(Number(value))) { val = 'number'; } else if (dateValue instanceof Date && !isNaN(dateValue.valueOf())) { val = (dateValue && dateValue.getDay() && (dateValue.getHours() > 0 || dateValue.getMinutes() > 0 || dateValue.getSeconds() > 0 || dateValue.getMilliseconds() > 0) ? 'datetime' : 'date'); } else { val = typeof (value);; } return val; } public static resetTime(date: Date): Date { date.setHours(0, 0, 0, 0); return date; } /* eslint-disable */ public static getClonedData(data: { [key: string]: Object }[]): { [key: string]: Object }[] { let clonedData: { [key: string]: Object }[] = []; if (data) { for (let item of data as { [key: string]: Object }[]) { let fields: string[] = Object.keys(item); /* eslint-enable */ let keyPos: number = 0; /* eslint-disable @typescript-eslint/no-explicit-any */ let framedSet: any = {}; /* eslint-enable @typescript-eslint/no-explicit-any */ while (keyPos < fields.length) { framedSet[fields[keyPos]] = item[fields[keyPos]]; keyPos++; } clonedData.push(framedSet); } } return clonedData; } public static getClonedPivotValues(pivotValues: IPivotValues): IPivotValues { let clonedSets: IPivotValues = []; for (let i: number = 0; i < pivotValues.length; i++) { if (pivotValues[i]) { clonedSets[i] = []; for (let j: number = 0; j < pivotValues[i].length; j++) { if (pivotValues[i][j]) { /* eslint-disable */ clonedSets[i][j] = this.getClonedPivotValueObj(pivotValues[i][j] as { [key: string]: Object }); /* eslint-enable */ } } } } return clonedSets; } /* eslint-disable */ private static getClonedPivotValueObj(data: { [key: string]: Object }): { [key: string]: Object } { /* eslint-enable */ let keyPos: number = 0; /* eslint-disable @typescript-eslint/no-explicit-any */ let framedSet: any = {}; /* eslint-enable @typescript-eslint/no-explicit-any */ if (!(data === null || data === undefined)) { let fields: string[] = Object.keys(data); while (keyPos < fields.length) { framedSet[fields[keyPos]] = data[fields[keyPos]]; keyPos++; } } else { framedSet = data; } return framedSet; } /* eslint-disable @typescript-eslint/no-explicit-any */ private static getDefinedObj(data: { [key: string]: any }): { [key: string]: any } { let keyPos: number = 0; let framedSet: any = {}; /* eslint-enable @typescript-eslint/no-explicit-any */ if (!(data === null || data === undefined)) { let fields: string[] = Object.keys(data); while (keyPos < fields.length) { if (!(data[fields[keyPos]] === null || data[fields[keyPos]] === undefined)) { framedSet[fields[keyPos]] = data[fields[keyPos]]; } keyPos++; } } else { framedSet = data; } return framedSet; } /* eslint-disable */ public static inArray(value: Object, collection: Object[]): number { /* eslint-enable */ if (collection) { for (let i: number = 0, cnt: number = collection.length; i < cnt; i++) { if (collection[i] === value) { return i; } } } return -1; } /* eslint-disable */ public static isContainCommonElements(collection1: Object[], collection2: Object[]): boolean { /* eslint-enable */ for (let i: number = 0, cnt: number = collection1.length; i < cnt; i++) { for (let j: number = 0, lnt: number = collection2.length; j < lnt; j++) { if (collection2[j] === collection1[i]) { return true; } } } return false; } /* eslint-disable */ public static setPivotProperties(control: any, properties: any): void { /* eslint-enable */ control.allowServerDataBinding = false; if (control.pivotGridModule) { control.pivotGridModule.allowServerDataBinding = false; } control.setProperties(properties, true); control.allowServerDataBinding = true; if (control.pivotGridModule) { control.pivotGridModule.allowServerDataBinding = true; } } /* eslint-enable @typescript-eslint/no-explicit-any */ public static getClonedDataSourceSettings(dataSourceSettings: IDataOptions): IDataOptions { let clonesDataSource: IDataOptions = this.getDefinedObj({ type: dataSourceSettings.type, catalog: dataSourceSettings.catalog, cube: dataSourceSettings.cube, providerType: dataSourceSettings.providerType, url: dataSourceSettings.url, localeIdentifier: dataSourceSettings.localeIdentifier, excludeFields: isNullOrUndefined(dataSourceSettings.excludeFields) ? [] : [...dataSourceSettings.excludeFields], expandAll: dataSourceSettings.expandAll, allowLabelFilter: dataSourceSettings.allowLabelFilter, allowValueFilter: dataSourceSettings.allowValueFilter, allowMemberFilter: dataSourceSettings.allowMemberFilter, enableSorting: dataSourceSettings.enableSorting ? true : false, rows: this.cloneFieldSettings(dataSourceSettings.rows), columns: this.cloneFieldSettings(dataSourceSettings.columns), filters: this.cloneFieldSettings(dataSourceSettings.filters), values: this.cloneFieldSettings(dataSourceSettings.values), filterSettings: this.cloneFilterSettings(dataSourceSettings.filterSettings), sortSettings: this.cloneSortSettings(dataSourceSettings.sortSettings), drilledMembers: this.cloneDrillMemberSettings(dataSourceSettings.drilledMembers), valueSortSettings: this.CloneValueSortObject(dataSourceSettings.valueSortSettings), valueAxis: dataSourceSettings.valueAxis, formatSettings: this.cloneFormatSettings(dataSourceSettings.formatSettings), calculatedFieldSettings: this.cloneCalculatedFieldSettings(dataSourceSettings.calculatedFieldSettings), fieldMapping: this.cloneFieldSettings(dataSourceSettings.fieldMapping), showSubTotals: dataSourceSettings.showSubTotals, showRowSubTotals: dataSourceSettings.showRowSubTotals, showColumnSubTotals: dataSourceSettings.showColumnSubTotals, showGrandTotals: dataSourceSettings.showGrandTotals, showRowGrandTotals: dataSourceSettings.showRowGrandTotals, showColumnGrandTotals: dataSourceSettings.showColumnGrandTotals, showHeaderWhenEmpty: dataSourceSettings.showHeaderWhenEmpty, alwaysShowValueHeader: dataSourceSettings.alwaysShowValueHeader, conditionalFormatSettings: this.cloneConditionalFormattingSettings(dataSourceSettings.conditionalFormatSettings), emptyCellsTextContent: dataSourceSettings.emptyCellsTextContent, groupSettings: this.cloneGroupSettings(dataSourceSettings.groupSettings), showAggregationOnValueField: dataSourceSettings.showAggregationOnValueField, authentication: this.CloneAuthenticationObject(dataSourceSettings.authentication) /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any }); /* eslint-enable @typescript-eslint/no-explicit-any */ return clonesDataSource; } public static updateDataSourceSettings(control: PivotView | PivotFieldList, dataSourceSettings: IDataOptions): void { if (control) { this.setPivotProperties(control, { dataSourceSettings: this.getDefinedObj({ type: dataSourceSettings.type, catalog: dataSourceSettings.catalog, cube: dataSourceSettings.cube, providerType: dataSourceSettings.providerType, url: dataSourceSettings.url, localeIdentifier: dataSourceSettings.localeIdentifier, excludeFields: isNullOrUndefined(dataSourceSettings.excludeFields) ? [] : dataSourceSettings.excludeFields, expandAll: dataSourceSettings.expandAll, allowLabelFilter: dataSourceSettings.allowLabelFilter, allowValueFilter: dataSourceSettings.allowValueFilter, allowMemberFilter: dataSourceSettings.allowMemberFilter, enableSorting: dataSourceSettings.enableSorting ? true : false, rows: dataSourceSettings.rows, columns: dataSourceSettings.columns, filters: dataSourceSettings.filters, values: dataSourceSettings.values, filterSettings: dataSourceSettings.filterSettings, sortSettings: dataSourceSettings.sortSettings, drilledMembers: dataSourceSettings.drilledMembers, valueSortSettings: dataSourceSettings.valueSortSettings, valueAxis: dataSourceSettings.valueAxis, formatSettings: dataSourceSettings.formatSettings, calculatedFieldSettings: dataSourceSettings.calculatedFieldSettings, fieldMapping: dataSourceSettings.fieldMapping, showSubTotals: dataSourceSettings.showSubTotals, showRowSubTotals: dataSourceSettings.showRowSubTotals, showColumnSubTotals: dataSourceSettings.showColumnSubTotals, showGrandTotals: dataSourceSettings.showGrandTotals, showRowGrandTotals: dataSourceSettings.showRowGrandTotals, showColumnGrandTotals: dataSourceSettings.showColumnGrandTotals, showHeaderWhenEmpty: dataSourceSettings.showHeaderWhenEmpty, alwaysShowValueHeader: dataSourceSettings.alwaysShowValueHeader, conditionalFormatSettings: dataSourceSettings.conditionalFormatSettings, emptyCellsTextContent: dataSourceSettings.emptyCellsTextContent, groupSettings: dataSourceSettings.groupSettings, showAggregationOnValueField: dataSourceSettings.showAggregationOnValueField, authentication: this.CloneAuthenticationObject(dataSourceSettings.authentication) /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any }) /* eslint-enable @typescript-eslint/no-explicit-any */ }); } } public static cloneFieldSettings(collection: IFieldOptions[]): IFieldOptions[] { if (collection) { let clonedCollection: IFieldOptions[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, caption: set.caption, axis: set.axis, baseField: set.baseField, baseItem: set.baseItem, isCalculatedField: set.isCalculatedField, isNamedSet: set.isNamedSet, showNoDataItems: set.showNoDataItems, showSubTotals: set.showSubTotals, type: set.type, dataType: set.dataType, showFilterIcon: set.showFilterIcon, showSortIcon: set.showSortIcon, showRemoveIcon: set.showRemoveIcon, showValueTypeIcon: set.showValueTypeIcon, showEditIcon: set.showEditIcon, allowDragAndDrop: set.allowDragAndDrop /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } public static cloneFilterSettings(collection: IFilter[]): IFilter[] { if (collection) { let clonedCollection: IFilter[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, type: set.type, condition: set.condition, items: set.items ? [...set.items] : set.items, levelCount: set.levelCount, measure: set.measure, selectedField: set.selectedField, showDateFilter: set.showDateFilter, showLabelFilter: set.showLabelFilter, showNumberFilter: set.showNumberFilter, value1: set.value1, value2: set.value2 /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } private static cloneSortSettings(collection: ISort[]): ISort[] { if (collection) { let clonedCollection: ISort[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, order: set.order /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } public static cloneDrillMemberSettings(collection: IDrillOptions[]): IDrillOptions[] { if (collection) { let clonedCollection: IDrillOptions[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, delimiter: set.delimiter, items: set.items ? [...set.items] : set.items /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } public static cloneFormatSettings(collection: IFormatSettings[]): IFormatSettings[] { if (collection) { let clonedCollection: IFormatSettings[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, calendar: set.calendar, currency: set.currency, format: set.format, maximumFractionDigits: set.maximumFractionDigits, maximumSignificantDigits: set.maximumSignificantDigits, minimumFractionDigits: set.minimumFractionDigits, minimumIntegerDigits: set.minimumIntegerDigits, minimumSignificantDigits: set.minimumSignificantDigits, skeleton: set.skeleton, type: set.type, useGrouping: set.useGrouping /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } /* eslint-disable */ private static CloneValueSortObject(collection: IValueSortSettings): IValueSortSettings { /* eslint-enable */ if (collection) { let clonedCollection: IValueSortSettings = { columnIndex: collection.columnIndex, headerDelimiter: collection.headerDelimiter, headerText: collection.headerText, measure: collection.measure, sortOrder: collection.sortOrder }; return clonedCollection; } else { return collection; } } /* eslint-disable */ private static CloneAuthenticationObject(collection: IAuthenticationInfo): IAuthenticationInfo { /* eslint-enable */ if (collection) { let clonedCollection: IAuthenticationInfo = { userName: collection.userName, password: collection.password }; return clonedCollection; } else { return collection; } } public static cloneCalculatedFieldSettings(collection: ICalculatedFieldSettings[]): ICalculatedFieldSettings[] { if (collection) { let clonedCollection: ICalculatedFieldSettings[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, formatString: set.formatString, formula: set.formula, hierarchyUniqueName: set.hierarchyUniqueName /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } private static cloneConditionalFormattingSettings(collection: IConditionalFormatSettings[]): IConditionalFormatSettings[] { if (collection) { let clonedCollection: IConditionalFormatSettings[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ applyGrandTotals: set.applyGrandTotals, conditions: set.conditions, label: set.label, measure: set.measure, style: set.style ? { backgroundColor: set.style.backgroundColor, color: set.style.color, fontFamily: set.style.fontFamily, fontSize: set.style.fontSize } : set.style, value1: set.value1, value2: set.value2 /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } public static cloneGroupSettings(collection: IGroupSettings[]): IGroupSettings[] { if (collection) { let clonedCollection: IGroupSettings[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ name: set.name, caption: set.caption, customGroups: this.cloneCustomGroups(set.customGroups), endingAt: set.endingAt, startingAt: set.startingAt, groupInterval: set.groupInterval, rangeInterval: set.rangeInterval, type: set.type /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } private static cloneCustomGroups(collection: ICustomGroups[]): ICustomGroups[] { if (collection) { let clonedCollection: ICustomGroups[] = []; for (let set of collection) { clonedCollection.push(this.getDefinedObj({ groupName: set.groupName, items: set.items ? [...set.items] : set.items /* eslint-disable @typescript-eslint/no-explicit-any */ } as { [key: string]: any })); /* eslint-enable @typescript-eslint/no-explicit-any */ } return clonedCollection; } else { return collection; } } public static getFilterItemByName(fieldName: string, fields: IFilter[]): IFilter { let filterItems: IFilter[] = new DataManager({ json: fields }).executeLocal(new Query().where('name', 'equal', fieldName)); if (filterItems && filterItems.length > 0) { return filterItems[filterItems.length - 1]; } return undefined; } public static getFieldByName(fieldName: string, fields: IFieldOptions[] | ISort[] | IFormatSettings[] | IDrillOptions[] | IGroupSettings[] | ICalculatedFieldSettings[]): IFieldOptions | ISort | IFormatSettings | IDrillOptions | IGroupSettings | ICalculatedFieldSettings { /* eslint-disable-line */ return new DataManager({ json: fields }).executeLocal(new Query().where('name', 'equal', fieldName))[0]; } public static getFieldInfo(fieldName: string, control: PivotView | PivotFieldList, hasAllField?: boolean): FieldItemInfo { if (!hasAllField) { let rows: IFieldOptions[] = this.cloneFieldSettings(control.dataSourceSettings.rows); let columns: IFieldOptions[] = this.cloneFieldSettings(control.dataSourceSettings.columns); let values: IFieldOptions[] = this.cloneFieldSettings(control.dataSourceSettings.values); let filters: IFieldOptions[] = this.cloneFieldSettings(control.dataSourceSettings.filters); let fields: IFieldOptions[][] = [rows, columns, values, filters]; for (let i: number = 0, len: number = fields.length; i < len; i++) { for (let j: number = 0, cnt: number = (fields[i] ? fields[i].length : 0); j < cnt; j++) { if (fields[i][j] && fields[i][j].name === fieldName) { return { fieldName: fieldName, fieldItem: fields[i][j], axis: i === 0 ? 'rows' : i === 1 ? 'columns' : i === 2 ? 'values' : 'filters', position: j }; } } } } let fieldList: IOlapField = control.dataType === 'olap' ? control.olapEngineModule.fieldList[fieldName] : control.engineModule.fieldList[fieldName]; let fieldItem: IFieldOptions = (fieldList ? { name: fieldName, caption: fieldList.caption, baseField: fieldList.baseField, baseItem: fieldList.baseItem, isCalculatedField: fieldList.isCalculatedField, isNamedSet: fieldList.isNamedSets, showNoDataItems: fieldList.showNoDataItems, showSubTotals: fieldList.showSubTotals, type: fieldList.aggregateType as SummaryTypes, showFilterIcon: fieldList.showFilterIcon, showSortIcon: fieldList.showSortIcon, showRemoveIcon: fieldList.showRemoveIcon, showValueTypeIcon: fieldList.showValueTypeIcon, showEditIcon: fieldList.showEditIcon, allowDragAndDrop: fieldList.allowDragAndDrop } : undefined); return { fieldName: fieldName, fieldItem: fieldItem, axis: 'fieldlist', position: -1 }; } public static isButtonIconRefesh(prop: string, oldProp: PivotViewModel | PivotFieldListModel, newProp: PivotViewModel | PivotFieldListModel): boolean { /* eslint-disable-line */ let isButtonRefresh: boolean = false; try { if (prop === 'dataSourceSettings' && oldProp.dataSourceSettings && newProp.dataSourceSettings) { let propValidation: string[] = ['notAvail', 'notAvail', 'notAvail', 'notAvail']; let oldAxesProp: string[] = Object.keys(oldProp.dataSourceSettings); let newAxesProp: string[] = Object.keys(newProp.dataSourceSettings); if (oldAxesProp && newAxesProp && newAxesProp.length > 0 && oldAxesProp.length === newAxesProp.length) { let axes: string[] = ['rows', 'columns', 'values', 'filters']; /* eslint-disable @typescript-eslint/no-explicit-any */ for (let i: number = 0; i < newAxesProp.length; i++) { let oldAxis: string[] = (newAxesProp[i] in oldProp.dataSourceSettings && !isNullOrUndefined((oldProp.dataSourceSettings as any)[newAxesProp[i]])) ? Object.keys((oldProp.dataSourceSettings as any)[newAxesProp[i]]) : []; /* eslint-disable-line */ let newAxis: string[] = (newAxesProp[i] in newProp.dataSourceSettings && !isNullOrUndefined((newProp.dataSourceSettings as any)[newAxesProp[i]])) ? /* eslint-disable-line */ Object.keys((newProp.dataSourceSettings as any)[newAxesProp[i]]) : []; if (axes.indexOf(newAxesProp[i]) !== -1 && axes.indexOf(oldAxesProp[i]) !== -1 && oldAxis && newAxis && newAxis.length > 0 && oldAxis.length === newAxis.length) { let options: string[] = ['showFilterIcon', 'showSortIcon', 'showRemoveIcon', 'showValueTypeIcon', 'showEditIcon', 'allowDragAndDrop']; for (let j: number = 0; j < newAxis.length; j++) { let oldAxisProp: string[] = Object.keys((oldProp.dataSourceSettings as any)[newAxesProp[i]][newAxis[j]]); let newAxisProp: string[] = Object.keys((newProp.dataSourceSettings as any)[newAxesProp[i]][newAxis[j]]); for (let k: number = 0; k < newAxisProp.length; k++) { if (options.indexOf(newAxisProp[k]) !== -1 && options.indexOf(oldAxisProp[k]) !== -1) { propValidation[i] = 'update'; } else { propValidation[i] = 'break'; break; } } if (propValidation[i] === 'break') { break; } } } else { propValidation[i] = 'break'; } if (propValidation[i] === 'break') { break; } } /* eslint-enable @typescript-eslint/no-explicit-any */ } let a: number = 0; let b: number = 0; let c: number = 0; for (let validation of propValidation) { if (validation === 'break') { a++; } if (validation === 'notAvail') { b++; } if (validation === 'update') { c++; } } isButtonRefresh = (a > 0 || b === 4) ? false : (a === 0 && b < 4 && c > 0); } } catch (exception) { isButtonRefresh = false; } return isButtonRefresh; } /* eslint-disable */ public static formatPivotValues(pivotValues: any): any { let values: any = []; /* eslint-enable */ for (let i: number = 0; i < pivotValues.length; i++) { if (pivotValues[i]) { values[i] = []; for (let j: number = 0; j < pivotValues[i].length; j++) { if (pivotValues[i][j]) { values[i][j] = { axis: pivotValues[i][j].Axis, actualText: pivotValues[i][j].ActualText, indexObject: pivotValues[i][j].IndexObject, index: pivotValues[i][j].Index, rowHeaders: pivotValues[i][j].RowHeaders, columnHeaders: pivotValues[i][j].ColumnHeaders, formattedText: pivotValues[i][j].FormattedText, actualValue: pivotValues[i][j].ActualValue, rowIndex: pivotValues[i][j].RowIndex, colIndex: pivotValues[i][j].ColIndex, colSpan: pivotValues[i][j].ColSpan, level: pivotValues[i][j].Level, rowSpan: pivotValues[i][j].RowSpan, isSum: pivotValues[i][j].IsSum, isGrandSum: pivotValues[i][j].IsGrandSum, valueSort: pivotValues[i][j].ValueSort, ordinal: pivotValues[i][j].Ordinal, hasChild: pivotValues[i][j].HasChild, isDrilled: pivotValues[i][j].IsDrilled, value: pivotValues[i][j].Value, type: pivotValues[i][j].Type, members: pivotValues[i][j].Members }; } } } } return values; } /* eslint-disable */ public static formatPdfHeaderFooter(pdf: any): any { let contents: any = []; if (!isNullOrUndefined(pdf)) { for (let i: number = 0; i < pdf.length; i++) { let a = pdf[i]; let content = { /* eslint-enable */ type: a.Type, pageNumberType: a.PageNumberType, style: a.Style ? { penColor: a.Style.PenColor, penSize: a.Style.PenSize, dashStyle: a.Style.DashStyle, textBrushColor: a.Style.TextBrushColor, textPenColor: a.Style.TextPenColor, fontSize: a.Style.FontSize, hAlign: a.Style.HAlign, vAlign: a.Style.VAlign } : a.Style, points: a.Points !== null ? { x1: a.Points.X1, y1: a.Points.Y1, x2: a.Points.X2, y2: a.Points.Y2 } : null, format: a.Format, position: a.Position !== null ? { x: a.Position.X, y: a.Position.Y } : null, size: a.Size !== null ? { height: a.Size.Height, width: a.Size.Width } : null, src: a.Src, value: a.Value, font: a.Font }; contents.push(content); } } return contents; } /* eslint-disable */ public static formatPdfExportProperties(pdf: any): any { let values: any; /* eslint-enable */ values = this.getDefinedObj({ pageOrientation: typeof pdf.PageOrientation === 'string' ? pdf.PageOrientation : null, pageSize: typeof pdf.PageSize === 'string' ? pdf.PageSize : null, header: !isNullOrUndefined(pdf.Header) ? { fromTop: pdf.Header.FromTop, height: pdf.Header.Height, contents: this.formatPdfHeaderFooter(pdf.Header.Contents) } : null, columns: pdf.Columns, footer: !isNullOrUndefined(pdf.Footer) ? { fromTop: pdf.Footer.FromBottom, height: pdf.Footer.Height, contents: this.formatPdfHeaderFooter(pdf.Footer.Contents) } : null, includeHiddenColumn: pdf.IncludeHiddenColumn, dataSource: pdf.DataSource, exportType: typeof pdf.ExportType === 'string' ? pdf.ExportType : null, theme: !isNullOrUndefined(pdf.Theme) ? { header: pdf.Theme.Header, record: pdf.Theme.Record, caption: pdf.Theme.Caption } : null, fileName: pdf.FileName, hierarchyExportMode: typeof pdf.HierarchyExportMode === 'string' ? pdf.HierarchyExportMode : null, allowHorizontalOverflow: pdf.AllowHorizontalOverflow }); return values; } /* eslint-disable */ public static formatExcelStyle(style: any): any { let prop; /* eslint-enable */ if (!isNullOrUndefined(style)) { prop = this.getDefinedObj({ fontColor: style.FontColor, fontName: style.FontName, fontSize: style.FontSize, hAlign: style.HAlign === String ? style.HAlign : null, vAlign: style.VAlign === String ? style.VAlign : null, bold: style.Bold, indent: style.Indent, italic: style.Italic, underline: style.Underline, backColor: style.BackColor, wrapText: style.WrapText, borders: style.Borders, numberFormat: style.NumberFormat, type: style.Type }); } return prop; } /* eslint-disable */ public static formatExcelCell(cell: any): any { let cells: ExcelRow[] = []; if (!isNullOrUndefined(cell)) { for (let i: number = 0; i < cell.length; i++) { this.getDefinedObj({ index: !isNullOrUndefined(cell[i].Index) ? cell[i].Index : null, colSpan: !isNullOrUndefined(cell[i].ColSpan) ? cell[i].ColSpan : null, value: !isNullOrUndefined(cell[i].Value) ? cell[i].Value : null, hyperlink: { target: !isNullOrUndefined(cell[i].Hyperlink) ? cell[i].Hyperlink.Target : null, displayText: !isNullOrUndefined(cell[i].Hyperlink) ? cell[i].Hyperlink.DisplayText : null }, styles: this.formatExcelStyle(cell[i].Style), rowSpan: !isNullOrUndefined(cell[i].RowSpan) ? cell[i].RowSpan : null }); /* eslint-enable */ } } return cells; } /* eslint-disable */ public static formatExcelHeaderFooter(excel: any): any { let rows: ExcelRow[] = []; if (!isNullOrUndefined(excel)) { for (let i: number = 0; i < excel.Rows.length; i++) { let row = excel.Rows[i]; let prop = this.getDefinedObj({ index: !isNullOrUndefined(row.Index) ? row.Index : null, cells: this.formatExcelCell(row.Cells), grouping: !isNullOrUndefined(row.Grouping) ? row.Grouping : null }); rows.push(prop); } } return rows; } public static formatExcelExportProperties(excel: any): any { /* eslint-enable */ let prop: ExcelExportProperties; prop = this.getDefinedObj({ dataSource: excel.DataSource, query: excel.Query, multipleExport: this.getDefinedObj({ type: !isNullOrUndefined(excel.MultipleExport) ? excel.MultipleExport.Type : null, blankRows: !isNullOrUndefined(excel.MultipleExport) ? excel.MultipleExport.BlankRows : null }), header: this.getDefinedObj({ headerRows: !isNullOrUndefined(excel.Header) ? excel.Header.HeaderRows : null, rows: this.formatExcelHeaderFooter(excel.Header) }), footer: this.getDefinedObj({ footerRows: !isNullOrUndefined(excel.Footer) ? excel.Footer.FooterRows : null, rows: this.formatExcelHeaderFooter(excel.Footer) }), columns: excel.Columns, exportType: typeof excel.ExportType === 'string' ? excel.ExportType : undefined, includeHiddenColumn: excel.IncludeHiddenColumn, theme: !isNullOrUndefined(excel.Theme) ? { header: this.formatExcelStyle(excel.Theme.Header), record: this.formatExcelStyle(excel.Theme.Record), caption: this.formatExcelStyle(excel.Theme.Caption) } : undefined, fileName: excel.FileName, hierarchyExportMode: typeof excel.HierarchyExportMode === 'string' ? excel.HierarchyExportMode : undefined }); return prop; } /* eslint-disable */ public static formatFieldList(fieldList: any): any { let keys: string[] = Object.keys(fieldList); let fList: any = {}; for (let i: number = 0; i < keys.length; i++) { /* eslint-enable */ if (fieldList[keys[i]]) { fList[keys[i]] = { id: fieldList[keys[i]].Id, caption: fieldList[keys[i]].Caption, type: fieldList[keys[i]].Type, formatString: fieldList[keys[i]].FormatString, index: fieldList[keys[i]].Index, members: fieldList[keys[i]].Members, formattedMembers: fieldList[keys[i]].FormattedMembers, dateMember: fieldList[keys[i]].DateMember, filter: fieldList[keys[i]].Filter, sort: fieldList[keys[i]].Sort, aggregateType: fieldList[keys[i]].AggregateType, baseField: fieldList[keys[i]].BaseField, baseItem: fieldList[keys[i]].BaseItem, filterType: fieldList[keys[i]].FilterType, format: fieldList[keys[i]].Format, formula: fieldList[keys[i]].Formula, isSelected: fieldList[keys[i]].IsSelected, isExcelFilter: fieldList[keys[i]].IsExcelFilter, showNoDataItems: fieldList[keys[i]].ShowNoDataItems, isCustomField: fieldList[keys[i]].IsCustomField, showFilterIcon: fieldList[keys[i]].ShowFilterIcon, showSortIcon: fieldList[keys[i]].ShowSortIcon, showRemoveIcon: fieldList[keys[i]].ShowRemoveIcon, showEditIcon: fieldList[keys[i]].ShowEditIcon, showValueTypeIcon: fieldList[keys[i]].ShowValueTypeIcon, allowDragAndDrop: fieldList[keys[i]].AllowDragAndDrop, isCalculatedField: fieldList[keys[i]].IsCalculatedField, showSubTotals: fieldList[keys[i]].ShowSubTotals }; } } return fList; } /* eslint-disable */ public static frameContent(pivotValues: IPivotValues, type: string, rowPosition: number, control: PivotView | PivotFieldList): IGridValues { let dataContent: IGridValues = []; var pivot = control; if (pivot.dataSourceSettings.values.length > 0 && !pivot.engineModule.isEmptyData) { if ((pivot.enableValueSorting) || !pivot.engineModule.isEngineUpdated) { let rowCnt: number = 0; let start: number = type === 'value' ? rowPosition : 0; let end: number = type === 'value' ? pivotValues.length : rowPosition; for (var rCnt = start; rCnt < end; rCnt++) { if (pivotValues[rCnt]) { rowCnt = type === 'header' ? rCnt : rowCnt; dataContent[rowCnt] = {} as IAxisSet[]; for (var cCnt = 0; cCnt < pivotValues[rCnt].length; cCnt++) { if (pivotValues[rCnt][cCnt]) { dataContent[rowCnt][cCnt] = pivotValues[rCnt][cCnt] as IAxisSet; } } rowCnt++; } } } } return dataContent; } public static getLocalizedObject(control: PivotView | PivotFieldList): Object { let locale: Object = new Object(); (locale as any)["Null"] = control.localeObj.getConstant('null'); (locale as any)["Years"] = control.localeObj.getConstant('Years'); (locale as any)["Quarters"] = control.localeObj.getConstant('Quarters'); (locale as any)["Months"] = control.localeObj.getConstant('Months'); (locale as any)["Days"] = control.localeObj.getConstant('Days'); (locale as any)["Hours"] = control.localeObj.getConstant('Hours'); (locale as any)["Minutes"] = control.localeObj.getConstant('Minutes'); (locale as any)["Seconds"] = control.localeObj.getConstant('Seconds'); (locale as any)["QuarterYear"] = control.localeObj.getConstant('QuarterYear'); (locale as any)["Of"] = control.localeObj.getConstant('of'); (locale as any)["Qtr"] = control.localeObj.getConstant('qtr'); (locale as any)["Undefined"] = control.localeObj.getConstant('undefined'); (locale as any)["GroupOutOfRange"] = control.localeObj.getConstant('groupOutOfRange'); (locale as any)["Group"] = control.localeObj.getConstant('group'); return locale; } public static updateReport(control: PivotView | PivotFieldList, report: any): void { /* eslint-enable */ control.setProperties({ dataSourceSettings: { rows: [] } }, true); control.setProperties({ dataSourceSettings: { columns: [] } }, true); control.setProperties({ dataSourceSettings: { formatSettings: [] } }, true); for (let i: number = 0; i < report.Rows.length; i++) { control.dataSourceSettings.rows.push({ name: report.Rows[i].Name, caption: report.Rows[i].Caption, showNoDataItems: report.Rows[i].ShowNoDataItems, baseField: report.Rows[i].BaseField, baseItem: report.Rows[i].BaseItem, showFilterIcon: report.Rows[i].ShowFilterIcon, showSortIcon: report.Rows[i].ShowSortIcon, showEditIcon: report.Rows[i].ShowEditIcon, showRemoveIcon: report.Rows[i].ShowRemoveIcon, showSubTotals: report.Rows[i].ShowValueTypeIcon, allowDragAndDrop: report.Rows[i].AllowDragAndDrop, axis: report.Rows[i].Axis, dataType: report.Rows[i].DataType, isCalculatedField: report.Rows[i].IsCalculatedField, showValueTypeIcon: report.Rows[i].ShowValueTypeIcon, type: report.Rows[i].Type }); } for (let i: number = 0; i < report.Columns.length; i++) { control.dataSourceSettings.columns.push({ name: report.Columns[i].Name, caption: report.Columns[i].Caption, showNoDataItems: report.Columns[i].ShowNoDataItems, baseField: report.Columns[i].BaseField, baseItem: report.Columns[i].BaseItem, showFilterIcon: report.Columns[i].ShowFilterIcon, showSortIcon: report.Columns[i].ShowSortIcon, showEditIcon: report.Columns[i].ShowEditIcon, showRemoveIcon: report.Columns[i].ShowRemoveIcon, showSubTotals: report.Columns[i].ShowValueTypeIcon, allowDragAndDrop: report.Columns[i].AllowDragAndDrop, axis: report.Columns[i].Axis, dataType: report.Columns[i].DataType, isCalculatedField: report.Columns[i].IsCalculatedField, showValueTypeIcon: report.Columns[i].ShowValueTypeIcon, type: report.Columns[i].Type }); } for (let i: number = 0; i < report.FormatSettings.length; i++) { control.dataSourceSettings.formatSettings.push({ name: report.FormatSettings[i].Name, format: report.FormatSettings[i].Format, type: report.FormatSettings[i].Type, currency: report.FormatSettings[i].Currency, maximumFractionDigits: report.FormatSettings[i].MaximumFractionDigits, maximumSignificantDigits: report.FormatSettings[i].MaximumSignificantDigits, minimumFractionDigits: report.FormatSettings[i].MinimumFractionDigits, minimumIntegerDigits: report.FormatSettings[i].MinimumIntegerDigits, minimumSignificantDigits: report.FormatSettings[i].MinimumSignificantDigits, skeleton: report.FormatSettings[i].Skeleton, useGrouping: report.FormatSettings[i].UseGrouping }); } } public static generateUUID(): string { /* eslint-disable */ let d: number = new Date().getTime(); let d2: number = (performance && performance.now && (performance.now() * 1000)) || 0; return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { let r: number = Math.random() * 16; if (d > 0) { r = (d + r) % 16 | 0; d = Math.floor(d / 16); } else { r = (d2 + r) % 16 | 0; d2 = Math.floor(d2 / 16); } return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); /* eslint-enable */ } }
the_stack
import { Meta } from '@storybook/react' import { Insight } from '../Insight' import { rest } from 'msw' import { worker } from '../../../mocks/browser' import { FunnelResult, FunnelStep } from '~/types' import posthog from 'posthog-js' import { mockGetPersonProperties } from 'lib/components/TaxonomicFilter/__stories__/TaxonomicFilter.stories' import { createMemoryHistory } from 'history' import React from 'react' import { Provider } from 'kea' import { initKea } from '~/initKea' import { EventType } from '~/types' // Needed to be able to interact with project level correlation settings let correlationConfig: any = null export default { title: 'PostHog/Scenes/Insights/Funnels', decorators: [ (Story) => { worker.use( rest.get('/api/projects/:projectId', (_, res, ctx) => { return res(ctx.json({ id: 2, correlation_config: correlationConfig })) }), rest.patch('/api/projects/:projectId', (req, res, ctx) => { correlationConfig = (req.body as { correlation_config: any }).correlation_config return res(ctx.json({ id: 2, correlation_config: correlationConfig })) }) ) return <Story /> }, ], } as Meta export const WithCorrelationAndSkew = (): JSX.Element => { setFeatureFlags({ 'correlation-analysis': true }) worker.use( mockGetPersonProperties((_, res, ctx) => res( ctx.json([ { id: 1, name: '$geoip_country_code', count: 1 }, { id: 2, name: '$os', count: 2 }, { id: 3, name: '$browser', count: 3 }, ]) ) ), rest.get('https://api.posthog.com/some/people/url', (_, res, ctx) => res(ctx.json(samplePeople))), rest.post('/api/projects/:projectId/insights/funnel/', (_, res, ctx) => res(ctx.json(sampleSkewedFunnelResponse)) ), rest.post<FunnelCorrelationRequest>('/api/projects/:projectId/insights/funnel/correlation/', (req, res, ctx) => req.body.funnel_correlation_type === 'properties' ? res(ctx.json(samplePropertyCorrelationResponse)) : req.body.funnel_correlation_type === 'events' ? res(ctx.json(sampleEventCorrelationResponse)) : res(ctx.json(sampleEventWithPropertyCorrelationResponse)) ) ) const history = createMemoryHistory({ initialEntries: [ `/insights?${new URLSearchParams({ insight: 'FUNNELS', properties: JSON.stringify([]), filter_test_accounts: 'false', events: JSON.stringify([ { id: '$pageview', name: '$pageview', type: 'events', order: 0 }, { id: '$pageview', name: '$pageview', type: 'events', order: 1 }, { id: '$pageview', name: '$pageview', type: 'events', order: 2 }, ]), actions: JSON.stringify([]), funnel_viz_type: 'steps', display: 'FunnelViz', interval: 'day', new_entity: JSON.stringify([]), date_from: '-14d', exclusions: JSON.stringify([]), funnel_from_step: '0', funnel_to_step: '1', })}#fromItem=`, ], }) // @ts-ignore history.pushState = history.push // @ts-ignore history.replaceState = history.replace // This is data that is rendered into the html. I tried not to use this and just // use the endoints, but it appears to be difficult to set this up to not have // race conditions. // @ts-ignore window.POSTHOG_APP_CONTEXT = sampleContextData initKea({ routerHistory: history, routerLocation: history.location }) return ( <Provider> <Insight /> </Provider> ) } const setFeatureFlags = (featureFlags: { [flag: string]: boolean }): void => { // Allows for specifying featureflags to be enabled/disabled. It relies on // MSW. worker.use( rest.post('/decide/', (_, res, ctx) => { return res(ctx.json({ featureFlags })) }) ) // Trigger a reload of featureflags, as we could be using locally cached // ones posthog.reloadFeatureFlags() } // Types that should be defined elsewhere within an api cli // I tried to use `FunnelResult` from `types.ts` but it seems to not match up // with the request format I copied from a production api request. specifically, // `FunnelResult` expects a `type` property, and doesn't expect // `median_conversion_time`, and custom_name is not `string | undefined` type FunnelResponse = Omit< FunnelResult< (Omit<FunnelStep, 'custom_name'> & { median_conversion_time: number | null; custom_name: string | null })[] >, 'type' > type FunnelCorrelationRequest = { funnel_correlation_type: 'events' | 'properties' } type FunnelCorrelationResponse = { result: { events: { event: Partial<EventType> odds_ratio: number success_count: number failure_count: number success_people_url: string failure_people_url: string correlation_type: 'success' | 'failure' }[] skewed: boolean } last_refresh: string is_cached: boolean } // Sample responses used in stories const samplePropertyCorrelationResponse: FunnelCorrelationResponse = { result: { events: [ { event: { event: '$geoip_country_code::IE', }, success_count: 65, failure_count: 12, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 9.709598031173092, correlation_type: 'success', }, { event: { event: '$os::Mac OS X', }, success_count: 1737, failure_count: 1192, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 4.267011809020293, correlation_type: 'success', }, { event: { event: '$browser::Firefox', }, success_count: 382, failure_count: 192, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 4.048527814836648, correlation_type: 'success', }, ], skewed: false, }, last_refresh: '2021-10-11T15:00:54.248787Z', is_cached: true, } const sampleEventCorrelationResponse: FunnelCorrelationResponse = { result: { events: [ { event: { event: 'person viewed', }, success_count: 59, failure_count: 0, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 114.75839475839476, correlation_type: 'success', }, { event: { event: 'select edition: clicked get started', }, success_count: 42, failure_count: 0, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 81.86358695652174, correlation_type: 'success', }, { event: { event: 'insight viewed', }, success_count: 396, failure_count: 1300, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 0.621617558628984, correlation_type: 'failure', }, ], skewed: false, }, last_refresh: '2021-10-11T15:00:54.687382Z', is_cached: true, } const sampleEventWithPropertyCorrelationResponse: FunnelCorrelationResponse = { result: { events: [ { success_count: 155, failure_count: 0, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 27.594682835820894, correlation_type: 'success', event: { event: 'section heading viewed::$feature/new-paths-ui::true', properties: {}, elements: [] }, }, { success_count: 150, failure_count: 0, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 26.694674280386902, correlation_type: 'success', event: { event: 'section heading viewed::$lib_version::1.15.3', properties: {}, elements: [] }, }, { success_count: 155, failure_count: 1, success_people_url: 'https://api.posthog.com/some/people/url', failure_people_url: 'https://api.posthog.com/some/people/url', odds_ratio: 13.788246268656716, correlation_type: 'success', event: { event: 'section heading viewed::$feature/4156-tooltips-legends::true', properties: {}, elements: [], }, }, ], skewed: false, }, last_refresh: '2021-10-26T15:36:39.921274Z', is_cached: false, } const sampleSkewedFunnelResponse: FunnelResponse = { result: [ { action_id: '$pageview', name: '$pageview', custom_name: null, order: 0, people: ['017c567f-1f26-0000-bdb3-d29a6484acb6'], count: 10726, type: 'events', average_conversion_time: null, median_conversion_time: null, converted_people_url: 'https://api.posthog.com/some/people/url', dropped_people_url: 'https://api.posthog.com/some/people/url', }, { action_id: '$pageview', name: '$pageview', custom_name: null, order: 1, people: ['017c567f-1f26-0000-bdb3-d29a6484acb6'], count: 7627, type: 'events', average_conversion_time: 3605.594525238891, median_conversion_time: 2.0, converted_people_url: 'https://api.posthog.com/some/people/url', dropped_people_url: 'https://api.posthog.com/some/people/url', }, { action_id: '$pageview', name: '$pageview', custom_name: null, order: 2, people: ['017c567f-1f26-0000-bdb3-d29a6484acb6'], count: 10, type: 'events', average_conversion_time: 7734.935688918132, median_conversion_time: 6.0, converted_people_url: 'https://api.posthog.com/some/people/url', dropped_people_url: 'https://api.posthog.com/some/people/url', }, ], last_refresh: '2021-10-11T15:00:52.117340Z', is_cached: true, } const samplePeople = { results: [ { people: [ { id: 165374220, name: 'test@posthog.com', distinct_ids: ['2'], properties: { $initial_os: 'Mac OS X', }, is_identified: true, created_at: '2021-10-11T11:48:57.449000Z', uuid: '017c6f2f-35e8-0000-736e-50f22cae39d8', }, { id: 173639169, name: 'user@posthog.com', distinct_ids: ['1'], properties: { $os: 'Mac OS X', }, is_identified: false, created_at: '2021-10-20T13:15:00.555000Z', uuid: '017c9dd7-65cf-0000-173b-a91493a2faf4', }, ], count: 2, }, ], next: null, initial: 'https://app.posthog.com/api/person/funnel/?insight=FUNNELS&actions=%5B%5D&events=%5B%7B%22id%22%3A%22%24pageview%22%2C%22name%22%3A%22%24pageview%22%2C%22type%22%3A%22events%22%2C%22order%22%3A0%7D%2C%7B%22id%22%3A%22%24pageview%22%2C%22type%22%3A%22events%22%2C%22order%22%3A1%2C%22name%22%3A%22%24pageview%22%7D%5D&display=FunnelViz&interval=day&properties=%5B%5D&funnel_step=-2&funnel_viz_type=steps&funnel_to_step=1&funnel_step_breakdown=2&exclusions=%5B%5D&breakdown=organization_count&breakdown_type=person&funnel_custom_steps=%5B1%5D&funnel_from_step=0', is_cached: true, last_refresh: '2021-11-08T15:27:01.035422Z', } // This is data that is rendered into the html. I tried not to use this and just // use the endoints, but it appears to be difficult to set this up to not have // race conditions. // NOTE: these are not complete according to type, but the minimum I could get away with const sampleContextData = { current_team: { id: 2, }, current_user: { organization: { available_features: ['correlation_analysis'] } }, preflight: { is_clickhouse_enabled: true, instance_preferences: { disable_paid_fs: false }, }, default_event_name: '$pageview', persisted_feature_flags: ['correlation-analysis'], }
the_stack
import {typeColors} from '@workday/canvas-colors-web'; import {CanvasFontFamilies, fontFamilies} from './fontFamilies'; import {CanvasFontSizes, fontSizes} from './fontSizes'; import {CanvasFontWeights, fontWeights} from './fontWeights'; /** ### Canvas Type Hierarchy * [View Storybook Docs](https://workday.github.io/canvas-kit/?path=/story/tokens-tokens-react--type) * * --- * The hierarchy is organized into four levels, which correspond to levels defined in Figma. * * - `title`: Intended to be used for large page titles. * - `heading`: Intended to be used for headings and large text. * - `body`: Intended to be used for standard body text. * - `subtext`: Intended to be used for small subtext content or in tight spaces. * * Each level has three sizes: `large`, `medium`, and `small`. * * The type hierarchy tokens are recommended for most type usage. * These objects handle font sizes, weights, line heights, letter spacing, and color for you, * making it really simple to implement consistent type without much effort * * You can find more detailed information by inspecting individual levels and sizes. * * @example * ```tsx * import { type } from '@workday/canvas-kit-react/tokens'; * * const Heading = () => ( * <h3 css={type.levels.heading.medium}> * Heading Text * </h3> * ); * ``` */ export const levels: CanvasTypeHierarchy = { title: { large: { fontFamily: fontFamilies.default, /** 56px converted to base-16 rem (3.5rem)*/ fontSize: fontSizes[56], /** 64px converted to base-16 rem (4rem) */ lineHeight: '4rem', fontWeight: fontWeights.bold, color: typeColors.heading, }, medium: { fontFamily: fontFamilies.default, /** 48px converted to base-16 rem (3rem)*/ fontSize: fontSizes[48], /** 56px converted to base-16 rem (3.5rem) */ lineHeight: '3.5rem', fontWeight: fontWeights.bold, color: typeColors.heading, }, small: { fontFamily: fontFamilies.default, /** 40px converted to base-16 rem (2.5rem)*/ fontSize: fontSizes[40], /** 48px converted to base-16 rem (3rem) */ lineHeight: '3rem', fontWeight: fontWeights.bold, color: typeColors.heading, }, }, heading: { large: { fontFamily: fontFamilies.default, /** 32px converted to base-16 rem (2rem)*/ fontSize: fontSizes[32], /** 40px converted to base-16 rem (2.5rem) */ lineHeight: '2.5rem', fontWeight: fontWeights.bold, color: typeColors.heading, }, medium: { fontFamily: fontFamilies.default, /** 28px converted to base-16 rem (1.75rem)*/ fontSize: fontSizes[28], /** 36px converted to base-16 rem (2.25rem) */ lineHeight: '2.25rem', fontWeight: fontWeights.bold, color: typeColors.heading, }, small: { fontFamily: fontFamilies.default, /** 24px converted to base-16 rem (1.5rem)*/ fontSize: fontSizes[24], /** 32px converted to base-16 rem (2rem) */ lineHeight: '2rem', fontWeight: fontWeights.bold, color: typeColors.heading, }, }, body: { large: { fontFamily: fontFamilies.default, /** 20px converted to base-16 rem (1.25rem)*/ fontSize: fontSizes[20], /** 28px converted to base-16 rem (1.75rem) */ lineHeight: '1.75rem', fontWeight: fontWeights.regular, color: typeColors.body, }, medium: { fontFamily: fontFamilies.default, /** 18px converted to base-16 rem (1.125rem)*/ fontSize: fontSizes[18], /** 28px converted to base-16 rem (1.75rem) */ lineHeight: '1.75rem', fontWeight: fontWeights.regular, color: typeColors.body, }, small: { fontFamily: fontFamilies.default, /** 16px converted to base-16 rem (1rem)*/ fontSize: fontSizes[16], /** 24px converted to base-16 rem (1.5rem) */ lineHeight: '1.5rem', /** 0.16px converted to base-16 rem (0.01rem) */ letterSpacing: '0.01rem', fontWeight: fontWeights.regular, color: typeColors.body, }, }, subtext: { large: { fontFamily: fontFamilies.default, /** 14px converted to base-16 rem (0.875rem)*/ fontSize: fontSizes[14], /** 20px converted to base-16 rem (1.25rem) */ lineHeight: '1.25rem', /** 0.24px converted to base-16 rem (0.015rem) */ letterSpacing: '0.015rem', fontWeight: fontWeights.regular, color: typeColors.body, }, medium: { fontFamily: fontFamilies.default, /** 12px converted to base-16 rem (0.75rem)*/ fontSize: fontSizes[12], /** 16px converted to base-16 rem (1rem) */ lineHeight: '1rem', /** 0.32px converted to base-16 rem (0.02rem) */ letterSpacing: '0.02rem', fontWeight: fontWeights.regular, color: typeColors.body, }, small: { fontFamily: fontFamilies.default, /** 10px converted to base-16 rem (0.625rem)*/ fontSize: fontSizes[10], /** 16px converted to base-16 rem (1rem) */ lineHeight: '1rem', /** 0.4px converted to base-16 rem (0.025rem) */ letterSpacing: '0.025rem', fontWeight: fontWeights.regular, color: typeColors.body, }, }, }; export type CanvasTypeHierarchy = { /** ### Title Type Level * [View Storybook Docs](https://github.workday.io/canvas-kit/) * * --- * The `title` level is intended to be used for large page titles. * It has three sizes: `small`, `medium`, and `large`. * Here's a quick reference for font-sizes and weights: * * - `large`: font-size: 56px (3/5rem), font-weight: bold (700) * - `medium`: font-size: 48px (3rem), font-weight: bold (700) * - `small`: font-size: 40px (2.5rem), font-weight: bold (700) * * You can find more detailed styled information by inspecting individual sizes. * * Below is an example: * * @example * import { type } from '@workday/canvas-kit-react/tokens' * * const Title = () => ( * <h1 css={type.levels.title.medium}>Title Text</h2> * ); * */ title: CanvasTypeTitleLevel; /** ### Heading Type Level * [View Storybook Docs](https://github.workday.io/canvas-kit/) * * --- * The `heading` level is intended to be used for headings and large text. * It has three sizes: `small`, `medium`, and `large`. * Here's a quick reference for font-sizes and weights: * * - `large`: font-size: 32px (2rem), font-weight: bold (700) * - `medium`: font-size: 28px (1.75rem), font-weight: bold (700) * - `small`: font-size: 24px (1.5rem), font-weight: bold (700) * * You can find more detailed styled information by inspecting individual sizes. * * Below is an example: * * @example * import { type } from '@workday/canvas-kit-react/tokens' * * const Heading = () => ( * <h2 css={type.levels.heading.medium}>Heading Text</h2> * ); * */ heading: CanvasTypeHeadingLevel; /** ### Body Type Level * [View Storybook Docs](https://github.workday.io/canvas-kit/) * * --- * The `body` level is intended to be used for standard body text. * It has three sizes: `small`, `medium`, and `large`. * Here's a quick reference for font-sizes and weights: * * - `large`: font-size: 20px (1.25rem), font-weight: regular (400) * - `medium`: font-size: 18px (1.125rem), font-weight: regular (400) * - `small`: font-size: 16px (1rem), font-weight: regular (400) * * You can find more detailed styled information by inspecting individual sizes. * * Below is an example: * * @example * import { type } from '@workday/canvas-kit-react/tokens' * * const Body = () => ( * <p css={type.levels.body.medium}>Body text</p> * ); * * */ body: CanvasTypeBodyLevel; /** ### Subtext Type Level * [View Storybook Docs](https://github.workday.io/canvas-kit/) * * --- * The `subtext` level is intended to be used for small subtext content or in tight spaces. * It has three sizes: `small`, `medium`, and `large`. * Here's a quick reference for font-sizes and weights: * * - `large`: font-size: 14px (0.875rem), font-weight: regular (400) * - `medium`: font-size: 12px (0.75rem), font-weight: regular (400) * - `small`: font-size: 10px (0.625rem), font-weight: regular (400) * * You can find more detailed styled information by inspecting individual sizes. * * Below is an example: * * @example * import { type } from '@workday/canvas-kit-react/tokens' * * const Subtext = () => ( * <span css={type.levels.subtext.medium}>subtext</h2> * ); * * */ subtext: CanvasTypeSubtextLevel; }; type CanvasTypeTitleLevel = { large: { fontFamily: CanvasFontFamilies['default']; /** 56px converted to base-16 rem (3.5rem)*/ fontSize: CanvasFontSizes[56]; /** 64px converted to base-16 rem (4rem) */ lineHeight: '4rem'; fontWeight: CanvasFontWeights['bold']; color: typeof typeColors.heading; }; medium: { fontFamily: CanvasFontFamilies['default']; /** 48px converted to base-16 rem (3rem)*/ fontSize: CanvasFontSizes[48]; /** 56px converted to base-16 rem (3.5rem) */ lineHeight: '3.5rem'; fontWeight: CanvasFontWeights['bold']; color: typeof typeColors.heading; }; small: { fontFamily: CanvasFontFamilies['default']; /** 40px converted to base-16 rem (2.5rem)*/ fontSize: CanvasFontSizes[40]; /** 48px converted to base-16 rem (3rem) */ lineHeight: '3rem'; fontWeight: CanvasFontWeights['bold']; color: typeof typeColors.heading; }; }; type CanvasTypeHeadingLevel = { large: { fontFamily: CanvasFontFamilies['default']; /** 32px converted to base-16 rem (2rem)*/ fontSize: CanvasFontSizes[32]; /** 40px converted to base-16 rem (2.5rem) */ lineHeight: '2.5rem'; fontWeight: CanvasFontWeights['bold']; color: typeof typeColors.heading; }; medium: { fontFamily: CanvasFontFamilies['default']; /** 28px converted to base-16 rem (1.75rem)*/ fontSize: CanvasFontSizes[28]; /** 36px converted to base-16 rem (2.25rem) */ lineHeight: '2.25rem'; fontWeight: CanvasFontWeights['bold']; color: typeof typeColors.heading; }; small: { fontFamily: CanvasFontFamilies['default']; /** 24px converted to base-16 rem (1.5rem)*/ fontSize: CanvasFontSizes[24]; /** 32px converted to base-16 rem (2rem) */ lineHeight: '2rem'; fontWeight: CanvasFontWeights['bold']; color: typeof typeColors.heading; }; }; type CanvasTypeBodyLevel = { large: { fontFamily: CanvasFontFamilies['default']; /** 20px converted to base-16 rem (1.25rem)*/ fontSize: CanvasFontSizes[20]; /** 28px converted to base-16 rem (1.75rem) */ lineHeight: '1.75rem'; fontWeight: CanvasFontWeights['regular']; color: typeof typeColors.body; }; medium: { fontFamily: CanvasFontFamilies['default']; /** 18px converted to base-16 rem (1.125rem)*/ fontSize: CanvasFontSizes[18]; /** 28px converted to base-16 rem (1.75rem) */ lineHeight: '1.75rem'; fontWeight: CanvasFontWeights['regular']; color: typeof typeColors.body; }; small: { fontFamily: CanvasFontFamilies['default']; /** 16px converted to base-16 rem (1rem)*/ fontSize: CanvasFontSizes[16]; /** 24px converted to base-16 rem (1.5rem) */ lineHeight: '1.5rem'; /** 0.16px converted to base-16 rem (0.01rem) */ letterSpacing: '0.01rem'; fontWeight: CanvasFontWeights['regular']; color: typeof typeColors.body; }; }; type CanvasTypeSubtextLevel = { large: { fontFamily: CanvasFontFamilies['default']; /** 14px converted to base-16 rem (0.875rem)*/ fontSize: CanvasFontSizes[14]; /** 20px converted to base-16 rem (1.25rem) */ lineHeight: '1.25rem'; /** 0.24px converted to base-16 rem (0.015rem) */ letterSpacing: '0.015rem'; fontWeight: CanvasFontWeights['regular']; color: typeof typeColors.body; }; medium: { fontFamily: CanvasFontFamilies['default']; /** 12px converted to base-16 rem (0.75rem)*/ fontSize: CanvasFontSizes[12]; /** 16px converted to base-16 rem (1rem) */ lineHeight: '1rem'; /** 0.32px converted to base-16 rem (0.02rem) */ letterSpacing: '0.02rem'; fontWeight: CanvasFontWeights['regular']; color: typeof typeColors.body; }; small: { fontFamily: CanvasFontFamilies['default']; /** 10px converted to base-16 rem (0.625rem)*/ fontSize: CanvasFontSizes[10]; /** 16px converted to base-16 rem (1rem) */ lineHeight: '1rem'; /** 0.4px converted to base-16 rem (0.025rem) */ letterSpacing: '0.025rem'; fontWeight: CanvasFontWeights['regular']; color: typeof typeColors.body; }; };
the_stack
import assetStyles from '@adobe/spectrum-css-temp/components/asset/vars.css'; import {Card} from '..'; import {CardBase} from '../src/CardBase'; import {CardViewContext} from '../src/CardViewContext'; import {classNames, useSlotProps, useStyleProps} from '@react-spectrum/utils'; import {Content} from '@react-spectrum/view'; import { Default, DefaultSquare, DefaultTall, LongContentPoorWordSize, LongDescription, LongDetail, LongEverything, LongTitle, NoDescription, NoDescriptionSquare, WithIllustration } from './Card.stories'; import {getDescription, getImage} from './utils'; import {Heading, Text} from '@react-spectrum/text'; import {Image} from '@react-spectrum/image'; import {Meta, Story} from '@storybook/react'; import React, {Dispatch, SetStateAction, useState} from 'react'; import {SpectrumCardProps} from '@react-types/card'; import styles from '@adobe/spectrum-css-temp/components/card/vars.css'; import {usePress} from '@react-aria/interactions'; // see https://github.com/storybookjs/storybook/issues/8426#issuecomment-669021940 const StoryFn = ({storyFn}) => storyFn(); const meta: Meta<SpectrumCardProps> = { title: 'Card/quiet', component: Card, decorators: [storyFn => <StoryFn storyFn={storyFn} />] }; export default meta; const Template = (): Story<SpectrumCardProps> => (args) => ( <div style={{width: '208px'}}> <Card {...args} /> </div> ); /* This is a bit of a funny template, we can't get selected on a Card through context because * if there's context it assumes it's being rendered in a collection. It's just here for a quick check of styles. */ interface ISelectableCard { disabledKeys: Set<any>, selectionManager: { isSelected: () => boolean, select: () => Dispatch<SetStateAction<ISelectableCard>> } } let SelectableCard = (props) => { let [state, setState] = useState<ISelectableCard>({ disabledKeys: new Set(), selectionManager: { isSelected: () => true, select: () => setState(prev => ({ ...prev, selectionManager: { ...prev.selectionManager, isSelected: () => !prev.selectionManager.isSelected() } })) } }); let {pressProps} = usePress({onPress: () => setState(prev => ({ ...prev, selectionManager: { ...prev.selectionManager, isSelected: () => !prev.selectionManager.isSelected() } }))}); return ( <div style={{width: '208px'}} {...pressProps}> <CardViewContext.Provider value={{state}}> <CardBase {...props} /> </CardViewContext.Provider> </div> ); }; const TemplateSelected = (): Story<SpectrumCardProps> => (args) => ( <div style={{width: '208px'}}> <SelectableCard {...args} /> </div> ); export const Quiet = Template().bind({}); Quiet.args = {...Default.args, isQuiet: true}; export const QuietSquare = Template().bind({}); QuietSquare.args = {...Quiet.args, ...DefaultSquare.args}; export const QuietTall = Template().bind({}); QuietTall.args = {...Quiet.args, ...DefaultTall.args}; export const QuietNoDescription = Template().bind({}); QuietNoDescription.args = {...Quiet.args, ...NoDescription.args}; export const QuietNoDescriptionSquare = Template().bind({}); QuietNoDescriptionSquare.args = {...Quiet.args, ...NoDescriptionSquare.args}; export const QuietWithIllustration = Template().bind({}); QuietWithIllustration.args = {...Quiet.args, ...WithIllustration.args}; export const QuietLongTitle = Template().bind({}); QuietLongTitle.args = {...Quiet.args, ...LongTitle.args}; export const QuietLongDescription = Template().bind({}); QuietLongDescription.args = {...Quiet.args, ...LongDescription.args}; export const QuietLongContentPoorWordSize = Template().bind({}); QuietLongContentPoorWordSize.args = {...Quiet.args, ...LongContentPoorWordSize.args}; export const QuietLongDetail = Template().bind({}); QuietLongDetail.args = {...Quiet.args, ...LongDetail.args}; export const QuietLongEverything = Template().bind({}); QuietLongEverything.args = {...Quiet.args, ...LongEverything.args}; export const CardGrid = (props: SpectrumCardProps) => ( <div style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: '305px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <Card {...Quiet.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> </Card> ); }) } </div> ); export const CardWaterfall = (props: SpectrumCardProps) => ( <div style={{ width: '100%', height: '150vh', margin: '50px', display: 'flex', flexDirection: 'column', flexWrap: 'wrap', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{width: '208px', margin: '10px'}}> <Card {...Quiet.args} {...props} layout="waterfall" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>{getDescription(index)}</Content> </Card> </div> ); }) } </div> ); export const CardGallery = (props: SpectrumCardProps) => ( <div style={{ width: '100%', margin: '50px', display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{height: '339px', margin: '10px'}}> <Card {...Quiet.args} {...props} layout="gallery" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> </Card> </div> ); }) } </div> ); export const CardFloat = (props: SpectrumCardProps) => ( <div style={{ width: '100%', margin: '50px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{float: 'left', margin: '10px'}}> <Card {...Quiet.args} {...props} key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> </Card> </div> ); }) } </div> ); export const CardGridNoDescription = (props: SpectrumCardProps) => ( <div className={classNames(styles, 'spectrum-CardGrid')} style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: '274px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <Card {...QuietNoDescription.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> </Card> ); }) } </div> ); export const CardGridIllustrations = (props: SpectrumCardProps) => ( <div className={classNames(styles, 'spectrum-CardGrid')} style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: '274px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <Card {...QuietNoDescription.args} {...props} layout="grid" key={`${index}${url}`}> <File slot="illustration" /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> </Card> ); }) } </div> ); export const CardGridLongTitle = (props: SpectrumCardProps) => ( <div className={classNames(styles, 'spectrum-CardGrid')} style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: '305px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <Card {...Quiet.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>This is a long title about how dinosaurs used to rule the earth before a meteor came and wiped them all out {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> </Card> ); }) } </div> ); export const CardGridTallRows = (props: SpectrumCardProps) => ( <div className={classNames(styles, 'spectrum-CardGrid')} style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: '400px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <Card {...Quiet.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> </Card> ); }) } </div> ); export const CardGridMessyText = (props: SpectrumCardProps) => ( <div style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: '305px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <Card {...Quiet.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>{index} Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Heading> <Text slot="detail">Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> </Card> ); }) } </div> ); export const CardWaterfallMessyText = (props: SpectrumCardProps) => ( <div style={{ width: '100%', height: '150vh', margin: '50px', display: 'flex', flexDirection: 'column', flexWrap: 'wrap', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{width: '208px', margin: '10px'}}> <Card {...Quiet.args} {...props} layout="waterfall" key={`${index}${url}`}> <Image src={url} /> <Heading>{index} Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Heading> <Text slot="detail">Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> </Card> </div> ); }) } </div> ); export const CardGalleryMessyText = (props: SpectrumCardProps) => ( <div style={{ width: '100%', margin: '50px', display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{height: '339px', margin: '10px'}}> <Card {...Quiet.args} {...props} layout="gallery" key={`${index}${url}`}> <Image src={url} /> <Heading>{index} Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Heading> <Text slot="detail">Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> </Card> </div> ); }) } </div> ); CardGalleryMessyText.decorators = [(Story) => ( <> <div style={{position: 'absolute', top: '5px'}}>{'ignore extra horizontal space, it will not do this in a real gallery layout'}</div> <Story /> </> )]; export const Selected = TemplateSelected().bind({}); Selected.args = {...Quiet.args}; function File(props) { props = useSlotProps(props, 'asset'); let {styleProps} = useStyleProps(props); return ( <div className={classNames(assetStyles, styleProps.className)}> <svg viewBox="0 0 128 128" {...props} {...styleProps} className={classNames(assetStyles, 'spectrum-Asset-file')} aria-label={props.alt} aria-hidden={props.decorative || null} role="img"> <g> <path className={classNames(assetStyles, 'spectrum-Asset-fileBackground')} d="M24,126c-5.5,0-10-4.5-10-10V12c0-5.5,4.5-10,10-10h61.5c2.1,0,4.1,0.8,5.6,2.3l20.5,20.4c1.5,1.5,2.4,3.5,2.4,5.7V116c0,5.5-4.5,10-10,10H24z" /> <g> <path className={classNames(assetStyles, 'spectrum-Asset-fileOutline')} d="M113.1,23.3L92.6,2.9C90.7,1,88.2,0,85.5,0H24c-6.6,0-12,5.4-12,12v104c0,6.6,5.4,12,12,12h80c6.6,0,12-5.4,12-12V30.4C116,27.8,114.9,25.2,113.1,23.3z M90,6l20.1,20H92c-1.1,0-2-0.9-2-2V6z M112,116c0,4.4-3.6,8-8,8H24c-4.4,0-8-3.6-8-8V12c0-4.4,3.6-8,8-8h61.5c0.2,0,0.3,0,0.5,0v20c0,3.3,2.7,6,6,6h20c0,0.1,0,0.3,0,0.4V116z" /> </g> </g> </svg> </div> ); }
the_stack
import { app, Menu, MenuItemConstructorOptions, ipcMain, MenuItem} from "electron"; import i18n from "./i18n"; import { FileHistory } from "./file-history"; import { AppStatus } from "./main"; const macOS = process.platform === "darwin"; export class AppMenu { private status: AppStatus; private fileHistory: FileHistory; private _enabled: boolean; constructor(status: AppStatus, fileHistory: FileHistory) { this.status = status; this.fileHistory = fileHistory; this._enabled = true; } get enabled() { return this._enabled; } set enabled(value) { if (this._enabled === value) return; this._enabled = value; this.setup(); } private fileUsable() { return this.enabled && this.status.editorEnabled && !this.status.projectsEnabled } private editorUsable() { return this.enabled && this.status.editorEnabled } public setup(){ const file: MenuItemConstructorOptions ={ label: i18n.__("menu.file"), submenu: [ { label: i18n.__("menu.new"), enabled: this.fileUsable(), accelerator: "CmdOrCtrl+N", click() { ipcMain.emit("file:new"); } }, { label: i18n.__("menu.open") + "...", enabled: this.fileUsable(), accelerator: "CmdOrCtrl+O", click() { ipcMain.emit("file:open"); } }, { label: i18n.__("menu.openRecent") + "...", enabled: false, submenu: [], }, { type: "separator"}, { label: i18n.__("menu.saveDeploy"), enabled: this.editorUsable(), accelerator: "CmdOrCtrl+S", click() { ipcMain.emit("file:save"); } }, { label: i18n.__("menu.saveAsDeploy") + "...", enabled: this.fileUsable(), accelerator: "Shift+CmdOrCtrl+S", click() { ipcMain.emit("file:save-as"); } }, { type: 'separator'}, { label: i18n.__('menu.settings') + "...", enabled: this.enabled, click() { ipcMain.emit("settings"); } }, { type: 'separator'}, { label: i18n.__('menu.openUserDir'), enabled: true, click() { ipcMain.emit("file:open-userdir"); } }, { label: i18n.__('menu.openLogFile'), enabled: true, click() { ipcMain.emit("file:open-logfile"); } }, { type: "separator"}, { label: i18n.__("menu.relaunch"), enabled: this.editorUsable(), click() { ipcMain.emit("browser:relaunch"); } }, { type: "separator"}, { label: i18n.__("menu.quit"), role: "quit" } ] }; if (macOS) { //@ts-ignore file.submenu.splice(-4); //@ts-ignore file.submenu.splice(-5, 2); }; const edit: MenuItemConstructorOptions = { label: i18n.__("menu.edit"), submenu: [ { label: i18n.__("menu.undo"), role: "undo" }, { label: i18n.__("menu.redo"), role: "redo" }, { type: "separator" }, { label: i18n.__("menu.cut"), role: "cut" }, { label: i18n.__("menu.copy"), role: "copy" }, { label: i18n.__("menu.paste"), role: "paste" }, { label: i18n.__("menu.pasteandmatchstyle"), role: "pasteandmatchstyle" }, { label: i18n.__("menu.delete"), role: "delete" }, { label: i18n.__("menu.selectall"), role: "selectall" } ] as MenuItemConstructorOptions[] }; const endpoint: MenuItemConstructorOptions = { label: i18n.__("menu.endpoint"), submenu: [ { label: i18n.__("menu.openLocalURL"), enabled: this.editorUsable(), click() { ipcMain.emit("endpoint:local"); } }, { label: i18n.__("menu.openLocalAdminURL"), enabled: this.editorUsable(), click() { ipcMain.emit("endpoint:local-admin"); } }, { type: "separator" }, { label: i18n.__("menu.ngrokConnect"), enabled: this.enabled && (this.status.ngrokUrl.length === 0), click() { ipcMain.emit("ngrok:connect"); } }, { label: i18n.__("menu.ngrokDisconnect"), enabled: this.enabled && (this.status.ngrokUrl.length > 0), click() { ipcMain.emit("ngrok:disconnect") } }, { label: i18n.__("menu.openPublicURL"), enabled: this.enabled && (this.status.ngrokUrl.length > 0), click() { ipcMain.emit("endpoint:public"); } }, { label: i18n.__("menu.openNgrokInspect"), enabled: this.enabled && this.status.ngrokStarted, click() { ipcMain.emit("ngrok:inspect"); } } ] }; const tools: MenuItemConstructorOptions = { label: i18n.__("menu.tools"), submenu: [ { label: i18n.__("menu.addLocalNode") + "...", enabled: this.enabled, click() { ipcMain.emit("node:addLocal"); } }, { label: i18n.__("menu.addRemoteNode") + "...", enabled: this.enabled, click() { ipcMain.emit("node:addRemote"); } }, { type: "separator"}, { id: "tools.nodegen", label: i18n.__("menu.nodegen"), enabled: false, click() { ipcMain.emit("node:nodegen"); } } ] }; const view: MenuItemConstructorOptions = { label: i18n.__("menu.view"), submenu: [ { label: i18n.__("menu.reload"), enabled: this.enabled, accelerator: "CmdOrCtrl+R", click(item, focusedWindow) { ipcMain.emit("view:reload", item, focusedWindow); } }, { type: "separator" }, { label: i18n.__("menu.locales") + "...", enabled: this.enabled, submenu: [], }, { type: "separator" }, { label: i18n.__("menu.togglefullscreen"), enabled: this.enabled, role: "togglefullscreen" }, { label: i18n.__("menu.minimize"), enabled: this.enabled, role: "minimize" } ] }; if (macOS) { const viewMac = [ { type: "separator" }, { label: i18n.__("menu.resetzoom"), enabled: this.enabled, role: "resetzoom" }, { label: i18n.__("menu.zoomin"), enabled: this.enabled, role: "zoomin" }, { label: i18n.__("menu.zoomout"), enabled: this.enabled, role: "zoomout" } ]; //@ts-ignore view.submenu.splice(-3, 0, ...viewMac); }; const help: MenuItemConstructorOptions = { label: i18n.__("menu.help"), submenu: [ { label: "Node-RED", enabled: this.enabled, click() { ipcMain.emit("help:node-red"); } }, { label: "Node-RED-Desktop", enabled: this.enabled, click() { ipcMain.emit("help:node-red-desktop"); } }, // { // label: "Author", // click() { ipcMain.emit("help:author"); } // }, { type: "separator" }, { label: i18n.__("menu.checkversion") + "...", enabled: this.enabled, click() { ipcMain.emit("help:check-updates"); } }, { label: i18n.__("menu.version"), enabled: this.enabled, click() { ipcMain.emit("help:version"); } } ] }; if (macOS) { //@ts-ignore help.submenu.splice(-1); }; const dev: MenuItemConstructorOptions = { label: "Dev", submenu: [ { label: "Toggle Developer Tools", accelerator: "Ctrl+Shift+I", click(item, focusedWindow) { ipcMain.emit("dev:tools", item, focusedWindow); } } ] }; if (macOS) { //@ts-ignore dev.submenu[0].accelerator = "Alt+Command+I"; } const darwin: MenuItemConstructorOptions = { label: app.name, submenu: [ { label: i18n.__('menu.about'), enabled: this.enabled, click() { ipcMain.emit("help:version"); } }, { type: 'separator'}, { label: i18n.__('menu.settings') + "...", enabled: this.enabled, accelerator: 'Command+,', click() { ipcMain.emit("settings"); } }, { type: "separator" }, { role: "services", submenu: []}, { type: "separator" }, { label: i18n.__('menu.hide'), role: 'hide'}, { label: i18n.__('menu.hideothers'), role: 'hideothers'}, { label: i18n.__('menu.unhide'), role: 'unhide'}, { type: 'separator'}, { label: i18n.__("menu.relaunch"), click() { ipcMain.emit("browser:relaunch"); } }, { type: "separator"}, { label: i18n.__('menu.quit'), role: 'quit' } ] as MenuItemConstructorOptions[] }; let template: MenuItemConstructorOptions[]; let openRecentMenu: Menu | any; let localesMenu: Menu | any; if (macOS) { template = [darwin, file, edit, endpoint, tools, view, help]; } else { template = [file, endpoint, tools, view, help]; } if (new RegExp(`${app.name}-debug`).exec(process.env.NODE_DEBUG!)) { template.push(dev); }; const menu = Menu.buildFromTemplate(template); if (macOS) { openRecentMenu = (menu.items[1] as any).submenu.items[2]; localesMenu = (menu.items[5] as any).submenu.items[2]; } else { openRecentMenu = (menu.items[0] as any).submenu.items[2]; localesMenu = (menu.items[3] as any).submenu.items[2]; } this.setOpenRecentMenu(openRecentMenu.submenu); openRecentMenu.enabled = (openRecentMenu.submenu.items.length > 0); this.setLocalesMenu(localesMenu.submenu); Menu.setApplicationMenu(menu); } private setOpenRecentMenu(openRecentMenu: Menu): void { const files = this.fileHistory.history; if (files.length > 0){ for(let i = 0; i < files.length; i++){ if (!files[i]) continue; openRecentMenu.append( new MenuItem({ label: files[i], enabled: this.fileUsable(), click(){ ipcMain.emit("file:open", files[i]); } }) ); } openRecentMenu.append(new MenuItem({ type: 'separator' })); openRecentMenu.append( new MenuItem({ label: i18n.__('menu.clearRecent'), enabled: this.enabled, click(){ ipcMain.emit("file:clear-recent"); } }) ); } } private setLocalesMenu(localesMenu: Menu): void { const locales = i18n.getLocales(); for(let i = 0; i < locales.length; i++){ localesMenu.append( new MenuItem( { label: locales[i], type: "checkbox", enabled: this.enabled, checked: (this.status.locale == locales[i]), click(item, focusedWindow) { ipcMain.emit("view:set-locale", item, focusedWindow); } }, ) ) } } public setMenuItemEnabled(id: string, enabled: boolean){ const menu = Menu.getApplicationMenu()!.getMenuItemById(id); if (menu) menu.enabled = enabled; } }
the_stack
import * as vscode from 'vscode'; import { IssueItem } from '../explorer/item/issue-item'; import { configuration, issueHelper, logger, selectValues, store } from '../services'; import { IPickValue } from '../services/configuration.model'; import { CONFIG } from '../shared/constants'; export default async function createIssue(issueItem: IssueItem): Promise<void> { const project = configuration.get(CONFIG.WORKING_PROJECT); if (store.verifyCurrentProject(project)) { try { // first of first we decide the type of the ticket const availableTypes = await store.state.jira.getAllIssueTypesWithFields(project); if (!!availableTypes) { // here the user select which type of issue create issueHelper.init(await selectValues.selectIssueType(false, availableTypes)); if (!!issueHelper.issueTypeSelected) { // store project issueHelper.populateNewIssue({ project }); // store issueType and project in payload // user cannot modify the values issueHelper.populateRequest({ issuetype: { id: issueHelper.issueTypeSelected.id, }, project: { key: project, }, }); let loopStatus = issueHelper.NEW_ISSUE_STATUS.CONTINUE; // this variable is used for retrieve only one time the available values inside the loop let executeretrieveValues = true; while (loopStatus === issueHelper.NEW_ISSUE_STATUS.CONTINUE) { // all selector available items const newIssuePicks = []; for (const fieldName in issueHelper.issueTypeSelected.fields) { // type and project forced before in the payload if (fieldName !== 'issuetype' && fieldName !== 'project') { // load values for every field if necessary if (executeretrieveValues) { await issueHelper.retrieveValues(fieldName); } // if there is issuelinks field we need also of issuelinksType // so we add the field in selector available items if (fieldName === issueHelper.NEW_ISSUE_FIELDS.ISSUE_LINKS.field) { issueHelper.addDefaultIssueLinkTypesIfNessesary(newIssuePicks); } const field = issueHelper.getField(fieldName); if (!field.hideField) { // create the item, use preselected value or default label 'Insert + fieldName' newIssuePicks.push({ field: fieldName, label: `${issueHelper.issueTypeSelected.fields[fieldName].required ? '$(star) ' : ''}${field.name}`, description: !!issueHelper.newIssueIstance[fieldName] ? issueHelper.newIssueIstance[fieldName].toString() : `Insert ${field.name}`, pickValue: field, fieldSchema: field.schema, }); } } } executeretrieveValues = false; // add last 3 custom items in the list newIssuePicks.push( { field: issueHelper.NEW_ISSUE_FIELDS.DIVIDER.field, label: issueHelper.NEW_ISSUE_FIELDS.DIVIDER.label, description: issueHelper.NEW_ISSUE_FIELDS.DIVIDER.description, }, { field: issueHelper.NEW_ISSUE_FIELDS.INSERT_ISSUE.field, label: issueHelper.NEW_ISSUE_FIELDS.INSERT_ISSUE.label, description: issueHelper.NEW_ISSUE_FIELDS.INSERT_ISSUE.description, }, { field: issueHelper.NEW_ISSUE_FIELDS.EXIT.field, label: issueHelper.NEW_ISSUE_FIELDS.EXIT.label, description: issueHelper.NEW_ISSUE_FIELDS.EXIT.description, } ); // second selector with all the fields const fieldToModifySelection = await vscode.window.showQuickPick(newIssuePicks, { placeHolder: `Insert Jira issue`, matchOnDescription: true, }); // manage the selected field from selector if (!!fieldToModifySelection && fieldToModifySelection.field !== issueHelper.NEW_ISSUE_FIELDS.DIVIDER.field) { switch (fieldToModifySelection.field) { case issueHelper.NEW_ISSUE_FIELDS.INSERT_ISSUE.field: // check if the mandatory field are populated, if not, we go on loopStatus = issueHelper.mandatoryFieldsOk ? issueHelper.NEW_ISSUE_STATUS.INSERT : loopStatus; break; case issueHelper.NEW_ISSUE_FIELDS.EXIT.field: loopStatus = issueHelper.NEW_ISSUE_STATUS.STOP; break; default: // with the field selected values populate the palyload await manageSelectedField(fieldToModifySelection); } } } if (loopStatus === issueHelper.NEW_ISSUE_STATUS.INSERT) { // Jira create issue API await issueHelper.insertNewTicket(); } else { // Exit } } } } catch (err) { logger.printErrorMessageInOutputAndShowAlert(err); } } } // from the preloaded values we generate selector items const generatePicks = (values: any[]) => { return values .map((value) => { return { pickValue: value, label: issueHelper.getPickValue(value), description: value.description || value.summary || '', }; }) .sort((a, b) => (a.label < b.label ? -1 : a.label > b.label ? 1 : 0)); }; // after selection we fill the payload and the user choices const manageSelectedField = async (fieldToModifySelection: any): Promise<void> => { switch (fieldToModifySelection.fieldSchema.type) { case 'string': { // simple input const text = await vscode.window.showInputBox({ ignoreFocusOut: true, placeHolder: `Insert ${fieldToModifySelection.pickValue.name}`, value: fieldToModifySelection.description !== `Insert ${fieldToModifySelection.pickValue.name}` ? fieldToModifySelection.description : undefined, }); // update user choices issueHelper.newIssueIstance[fieldToModifySelection.field] = text; // update payload if (issueHelper.isIssueTimetrackingOriginalEstimateField(fieldToModifySelection.field)) { issueHelper.requestJson[issueHelper.timetrakingJsonField] = { ...issueHelper.requestJson[issueHelper.timetrakingJsonField], originalEstimate: text, }; } else if (issueHelper.isIssueTimetrackingRemainingEstimateField(fieldToModifySelection.field)) { issueHelper.requestJson[issueHelper.timetrakingJsonField] = { ...issueHelper.requestJson[issueHelper.timetrakingJsonField], remainingEstimate: text, }; } else { issueHelper.requestJson[fieldToModifySelection.field] = text; } } break; case 'number': { // simple input const text = await vscode.window.showInputBox({ ignoreFocusOut: true, placeHolder: `Insert ${fieldToModifySelection.pickValue.name}`, value: fieldToModifySelection.description !== `Insert ${fieldToModifySelection.pickValue.name}` ? fieldToModifySelection.description : undefined, }); if (!!text) { // update user choices issueHelper.newIssueIstance[fieldToModifySelection.field] = parseInt(text); // update payload issueHelper.requestJson[fieldToModifySelection.field] = parseInt(text); } } break; default: { // if there are some preloaded values for the field if ( !!issueHelper.preloadedListValues[fieldToModifySelection.field] && issueHelper.preloadedListValues[fieldToModifySelection.field].length > 0 ) { const canPickMany = issueHelper.isCanPickMany(fieldToModifySelection); const selected = await vscode.window.showQuickPick<any>( generatePicks(issueHelper.preloadedListValues[fieldToModifySelection.field]), { placeHolder: `Insert value`, matchOnDescription: true, canPickMany, } ); // clear previous selection issueHelper.newIssueIstance[fieldToModifySelection.field] = undefined; // clear previous payload delete issueHelper.requestJson[fieldToModifySelection.field]; if (!canPickMany ? !!selected : !!selected && selected.length > 0) { // update user choices const newValueSelected: IPickValue[] = !canPickMany ? [selected] : [...selected]; issueHelper.newIssueIstance[fieldToModifySelection.field] = newValueSelected.map((value: any) => value.label).join(' '); // assignee/reporter want a name prop and NOT id or key if (issueHelper.isAssigneeOrReporterField(fieldToModifySelection.field)) { const values = newValueSelected.map((value: any) => value.pickValue.name); issueHelper.requestJson[fieldToModifySelection.field] = { name: !canPickMany ? values[0] : values }; } // straight string or string[] if ( issueHelper.isEpicLinkFieldSchema(fieldToModifySelection.fieldSchema) || issueHelper.isSprintFieldSchema(fieldToModifySelection.fieldSchema) || issueHelper.isLabelsField(fieldToModifySelection.field) || issueHelper.isIssuelinksField(fieldToModifySelection.field) || issueHelper.isArrayOfStringField(fieldToModifySelection.fieldSchema) ) { const values = newValueSelected.map((value: any) => value.pickValue.id || value.pickValue.key || value.pickValue.label); issueHelper.requestJson[fieldToModifySelection.field] = !canPickMany ? values[0] : values; } // save inward for issuelinksType if (issueHelper.isIssuelinksTypeField(fieldToModifySelection.field)) { const values = newValueSelected.map((value: any) => value.pickValue.inward); issueHelper.requestJson[fieldToModifySelection.field] = !canPickMany ? values[0] : values; } // update payload statndard way use id or key if (!issueHelper.requestJson[fieldToModifySelection.field]) { let jsonField = ''; // do not change order if (!jsonField && !!newValueSelected[0].pickValue.name) { jsonField = 'name'; } if (!jsonField && !!newValueSelected[0].pickValue.id) { jsonField = 'id'; } if (!jsonField && !!newValueSelected[0].pickValue.key) { jsonField = 'key'; } const values = newValueSelected.map((value: any) => value.pickValue[jsonField]); issueHelper.requestJson[fieldToModifySelection.field] = !canPickMany ? { [jsonField]: values[0], } : values.map((value) => { return { [jsonField]: value }; }); } } } else { vscode.window.showErrorMessage(`Debug msg - type not managed ${fieldToModifySelection.fieldSchema.type}`); } } } };
the_stack
import { workspace as Workspace, window as Window, languages as Languages, version as VSCodeVersion, TextDocument, Disposable, OutputChannel, FileSystemWatcher as VFileSystemWatcher, DiagnosticCollection, Diagnostic as VDiagnostic, Uri, CancellationToken, WorkspaceEdit as VWorkspaceEdit, MessageItem, WorkspaceFolder as VWorkspaceFolder, env as Env, TextDocumentShowOptions, CancellationError, CancellationTokenSource, FileCreateEvent, FileRenameEvent, FileDeleteEvent, FileWillCreateEvent, FileWillRenameEvent, FileWillDeleteEvent, CompletionItemProvider, HoverProvider, SignatureHelpProvider, DefinitionProvider, ReferenceProvider, DocumentHighlightProvider, CodeActionProvider, DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider, OnTypeFormattingEditProvider, RenameProvider, DocumentSymbolProvider, DocumentLinkProvider, DeclarationProvider, FoldingRangeProvider, ImplementationProvider, DocumentColorProvider, SelectionRangeProvider, TypeDefinitionProvider, CallHierarchyProvider, LinkedEditingRangeProvider, TypeHierarchyProvider, WorkspaceSymbolProvider, ProviderResult, TextEdit as VTextEdit } from 'vscode'; import { RAL, Message, MessageSignature, Logger, ResponseError, RequestType0, RequestType, NotificationType0, NotificationType, ProtocolRequestType, ProtocolRequestType0, RequestHandler, RequestHandler0, GenericRequestHandler, ProtocolNotificationType, ProtocolNotificationType0, NotificationHandler, NotificationHandler0, GenericNotificationHandler, MessageReader, MessageWriter, Trace, Tracer, TraceFormat, TraceOptions, Event, Emitter, createProtocolConnection, ClientCapabilities, WorkspaceEdit, RegistrationRequest, RegistrationParams, UnregistrationRequest, UnregistrationParams, InitializeRequest, InitializeParams, InitializeResult, ServerCapabilities, TextDocumentSyncKind, TextDocumentSyncOptions, InitializedNotification, ShutdownRequest, ExitNotification, LogMessageNotification, MessageType, ShowMessageNotification, ShowMessageRequest, TelemetryEventNotification, DocumentSelector, DidChangeTextDocumentNotification, DidChangeWatchedFilesNotification, FileEvent, PublishDiagnosticsNotification, PublishDiagnosticsParams, ApplyWorkspaceEditRequest, ApplyWorkspaceEditParams, TextDocumentEdit, ResourceOperationKind, FailureHandlingKind, ProgressType, ProgressToken, DiagnosticTag, LSPErrorCodes, ShowDocumentRequest, ShowDocumentParams, ShowDocumentResult, WorkDoneProgress, SemanticTokensRequest, SemanticTokensRangeRequest, SemanticTokensDeltaRequest, Diagnostic, ApplyWorkspaceEditResult, CancellationStrategy, InitializeError, WorkDoneProgressBegin, WorkDoneProgressReport, WorkDoneProgressEnd, DidOpenTextDocumentNotification, WillSaveTextDocumentNotification, WillSaveTextDocumentWaitUntilRequest, DidSaveTextDocumentNotification, DidCloseTextDocumentNotification, DidCreateFilesNotification, DidRenameFilesNotification, DidDeleteFilesNotification, WillRenameFilesRequest, WillCreateFilesRequest, WillDeleteFilesRequest, CompletionRequest, HoverRequest, SignatureHelpRequest, DefinitionRequest, ReferencesRequest, DocumentHighlightRequest, CodeActionRequest, CodeLensRequest, DocumentFormattingRequest, DocumentRangeFormattingRequest, DocumentOnTypeFormattingRequest, RenameRequest, DocumentSymbolRequest, DocumentLinkRequest, DocumentColorRequest, DeclarationRequest, FoldingRangeRequest, ImplementationRequest, SelectionRangeRequest, TypeDefinitionRequest, CallHierarchyPrepareRequest, SemanticTokensRegistrationType, LinkedEditingRangeRequest, TypeHierarchyPrepareRequest, InlineValueRequest, InlayHintRequest, WorkspaceSymbolRequest, TextDocumentRegistrationOptions, FileOperationRegistrationOptions, ConnectionOptions, PositionEncodingKind, DocumentDiagnosticRequest, NotebookDocumentSyncRegistrationType, NotebookDocumentSyncRegistrationOptions, ErrorCodes } from 'vscode-languageserver-protocol'; import * as c2p from './codeConverter'; import * as p2c from './protocolConverter'; import * as Is from './utils/is'; import { Delayer, Semaphore } from './utils/async'; import * as UUID from './utils/uuid'; import { ProgressPart } from './progressPart'; import { DynamicFeature, ensure, FeatureClient, LSPCancellationError, TextDocumentSendFeature, RegistrationData, StaticFeature, TextDocumentProviderFeature, WorkspaceProviderFeature } from './features'; import { DiagnosticFeature, DiagnosticProviderMiddleware, DiagnosticProviderShape, $DiagnosticPullOptions } from './diagnostic'; import { NotebookDocumentMiddleware, $NotebookDocumentOptions, NotebookDocumentProviderShape, NotebookDocumentSyncFeature } from './notebook'; import { ConfigurationFeature, ConfigurationMiddleware, $ConfigurationOptions, DidChangeConfigurationMiddleware, SyncConfigurationFeature, SynchronizeOptions } from './configuration'; import { DidChangeTextDocumentFeature, DidChangeTextDocumentFeatureShape, DidCloseTextDocumentFeature, DidCloseTextDocumentFeatureShape, DidOpenTextDocumentFeature, DidOpenTextDocumentFeatureShape, DidSaveTextDocumentFeature, DidSaveTextDocumentFeatureShape, ResolvedTextDocumentSyncCapabilities, TextDocumentSynchronizationMiddleware, WillSaveFeature, WillSaveWaitUntilFeature } from './textSynchronization'; import { CompletionItemFeature, CompletionMiddleware } from './completion'; import { HoverFeature, HoverMiddleware } from './hover'; import { DefinitionFeature, DefinitionMiddleware } from './definition'; import { SignatureHelpFeature, SignatureHelpMiddleware } from './signatureHelp'; import { DocumentHighlightFeature, DocumentHighlightMiddleware } from './documentHighlight'; import { DocumentSymbolFeature, DocumentSymbolMiddleware } from './documentSymbol'; import { WorkspaceSymbolFeature, WorkspaceSymbolMiddleware } from './workspaceSymbol'; import { ReferencesFeature, ReferencesMiddleware } from './reference'; import { TypeDefinitionMiddleware } from './typeDefinition'; import { ImplementationMiddleware } from './implementation'; import { ColorProviderMiddleware } from './colorProvider'; import { CodeActionFeature, CodeActionMiddleware } from './codeAction'; import { CodeLensFeature, CodeLensMiddleware, CodeLensProviderShape } from './codeLens'; import { DocumentFormattingFeature, DocumentOnTypeFormattingFeature, DocumentRangeFormattingFeature, FormattingMiddleware } from './formatting'; import { RenameFeature, RenameMiddleware } from './rename'; import { DocumentLinkFeature, DocumentLinkMiddleware } from './documentLink'; import { ExecuteCommandFeature, ExecuteCommandMiddleware } from './executeCommand'; import { FoldingRangeProviderMiddleware } from './foldingRange'; import { DeclarationMiddleware } from './declaration'; import { SelectionRangeProviderMiddleware } from './selectionRange'; import { CallHierarchyMiddleware } from './callHierarchy'; import { SemanticTokensMiddleware, SemanticTokensProviderShape } from './semanticTokens'; import { LinkedEditingRangeMiddleware } from './linkedEditingRange'; import { TypeHierarchyMiddleware } from './typeHierarchy'; import { InlineValueMiddleware, InlineValueProviderShape } from './inlineValue'; import { InlayHintsMiddleware, InlayHintsProviderShape } from './inlayHint'; import { WorkspaceFolderMiddleware } from './workspaceFolder'; import { FileOperationsMiddleware } from './fileOperations'; import { FileSystemWatcherFeature } from './fileSystemWatcher'; import { ColorProviderFeature } from './colorProvider'; import { ImplementationFeature } from './implementation'; import { TypeDefinitionFeature } from './typeDefinition'; import { WorkspaceFoldersFeature } from './workspaceFolder'; import { FoldingRangeFeature } from './foldingRange'; import { DeclarationFeature } from './declaration'; import { SelectionRangeFeature } from './selectionRange'; import { ProgressFeature } from './progress'; import { CallHierarchyFeature } from './callHierarchy'; import { SemanticTokensFeature } from './semanticTokens'; import { DidCreateFilesFeature, DidDeleteFilesFeature, DidRenameFilesFeature, WillCreateFilesFeature, WillDeleteFilesFeature, WillRenameFilesFeature } from './fileOperations'; import { LinkedEditingFeature } from './linkedEditingRange'; import { TypeHierarchyFeature } from './typeHierarchy'; import { InlineValueFeature } from './inlineValue'; import { InlayHintsFeature } from './inlayHint'; /** * Controls when the output channel is revealed. */ export enum RevealOutputChannelOn { Info = 1, Warn = 2, Error = 3, Never = 4 } /** * A handler that is invoked when the initialization of the server failed. */ export type InitializationFailedHandler = /** * @param error The error returned from the server * @returns if true is returned the client tries to reinitialize the server. * Implementors of a handler are responsible to not initialize the server * infinitely. Return false if initialization should stop and an error * should be reported. */ (error: ResponseError<InitializeError> | Error | any) => boolean; /** * An action to be performed when the connection is producing errors. */ export enum ErrorAction { /** * Continue running the server. */ Continue = 1, /** * Shutdown the server. */ Shutdown = 2 } export type ErrorHandlerResult = { /** * The action to take. */ action: ErrorAction; /** * An optional message to be presented to the user. */ message?: string; }; /** * An action to be performed when the connection to a server got closed. */ export enum CloseAction { /** * Don't restart the server. The connection stays closed. */ DoNotRestart = 1, /** * Restart the server. */ Restart = 2, } export type CloseHandlerResult = { /** * The action to take. */ action: CloseAction; /** * An optional message to be presented to the user. */ message?: string; }; /** * A plugable error handler that is invoked when the connection is either * producing errors or got closed. */ export interface ErrorHandler { /** * An error has occurred while writing or reading from the connection. * * @param error - the error received * @param message - the message to be delivered to the server if know. * @param count - a count indicating how often an error is received. Will * be reset if a message got successfully send or received. */ error(error: Error, message: Message | undefined, count: number | undefined): ErrorHandlerResult; /** * The connection to the server got closed. */ closed(): CloseHandlerResult; } /** * Signals in which state the language client is in. */ export enum State { /** * The client is stopped or got never started. */ Stopped = 1, /** * The client is starting but not ready yet. */ Starting = 3, /** * The client is running and ready. */ Running = 2, } /** * An event signaling a state change. */ export interface StateChangeEvent { oldState: State; newState: State; } export enum SuspendMode { /** * Don't allow suspend mode. */ off = 'off', /** * Support suspend mode even if not all * registered providers have a corresponding * activation listener. */ on = 'on', } export type SuspendOptions = { /** * Whether suspend mode is supported. If suspend mode is allowed * the client will stop a running server when going into suspend mode. * If omitted defaults to SuspendMode.off; */ mode?: SuspendMode; /** * A callback that is invoked before actually suspending * the server. If `false` is returned the client will not continue * suspending the server. */ callback?: () => Promise<boolean>; /** * The interval in milliseconds used to check if the server * can be suspended. If the check passes three times in a row * (e.g. the server can be suspended for 3 * interval ms) the * server is suspended. Defaults to 60000ms, which is also the * minimum allowed value. */ interval?: number; }; export interface DidChangeWatchedFileSignature { (this: void, event: FileEvent): Promise<void>; } type _WorkspaceMiddleware = { didChangeWatchedFile?: (this: void, event: FileEvent, next: DidChangeWatchedFileSignature) => Promise<void>; }; export type WorkspaceMiddleware = _WorkspaceMiddleware & ConfigurationMiddleware & DidChangeConfigurationMiddleware & WorkspaceFolderMiddleware & FileOperationsMiddleware; interface _WindowMiddleware { showDocument?: (this: void, params: ShowDocumentParams, next: ShowDocumentRequest.HandlerSignature) => Promise<ShowDocumentResult>; } export type WindowMiddleware = _WindowMiddleware; export interface HandleDiagnosticsSignature { (this: void, uri: Uri, diagnostics: VDiagnostic[]): void; } export interface HandleWorkDoneProgressSignature { (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd): void; } interface _Middleware { handleDiagnostics?: (this: void, uri: Uri, diagnostics: VDiagnostic[], next: HandleDiagnosticsSignature) => void; handleWorkDoneProgress?: (this: void, token: ProgressToken, params: WorkDoneProgressBegin | WorkDoneProgressReport | WorkDoneProgressEnd, next: HandleWorkDoneProgressSignature) => void; workspace?: WorkspaceMiddleware; window?: WindowMiddleware; } /** * The Middleware lets extensions intercept the request and notifications send and received * from the server */ export type Middleware = _Middleware & TextDocumentSynchronizationMiddleware & CompletionMiddleware & HoverMiddleware & DefinitionMiddleware & SignatureHelpMiddleware & DocumentHighlightMiddleware & DocumentSymbolMiddleware & WorkspaceSymbolMiddleware & ReferencesMiddleware & TypeDefinitionMiddleware & ImplementationMiddleware & ColorProviderMiddleware & CodeActionMiddleware & CodeLensMiddleware & FormattingMiddleware & RenameMiddleware & DocumentLinkMiddleware & ExecuteCommandMiddleware & FoldingRangeProviderMiddleware & DeclarationMiddleware & SelectionRangeProviderMiddleware & CallHierarchyMiddleware & SemanticTokensMiddleware & LinkedEditingRangeMiddleware & TypeHierarchyMiddleware & InlineValueMiddleware & InlayHintsMiddleware & NotebookDocumentMiddleware & DiagnosticProviderMiddleware; export type LanguageClientOptions = { documentSelector?: DocumentSelector | string[]; diagnosticCollectionName?: string; outputChannel?: OutputChannel; outputChannelName?: string; traceOutputChannel?: OutputChannel; revealOutputChannelOn?: RevealOutputChannelOn; /** * The encoding use to read stdout and stderr. Defaults * to 'utf8' if omitted. */ stdioEncoding?: string; initializationOptions?: any | (() => any); initializationFailedHandler?: InitializationFailedHandler; progressOnInitialization?: boolean; errorHandler?: ErrorHandler; middleware?: Middleware; uriConverters?: { code2Protocol: c2p.URIConverter; protocol2Code: p2c.URIConverter; }; workspaceFolder?: VWorkspaceFolder; connectionOptions?: { cancellationStrategy: CancellationStrategy; maxRestartCount?: number; }; markdown?: { isTrusted?: boolean; supportHtml?: boolean; }; } & $NotebookDocumentOptions & $DiagnosticPullOptions & $ConfigurationOptions; // type TestOptions = { // $testMode?: boolean; // }; type ResolvedClientOptions = { documentSelector?: DocumentSelector; synchronize: SynchronizeOptions; diagnosticCollectionName?: string; outputChannelName: string; revealOutputChannelOn: RevealOutputChannelOn; stdioEncoding: string; initializationOptions?: any | (() => any); initializationFailedHandler?: InitializationFailedHandler; progressOnInitialization: boolean; errorHandler: ErrorHandler; middleware: Middleware; uriConverters?: { code2Protocol: c2p.URIConverter; protocol2Code: p2c.URIConverter; }; workspaceFolder?: VWorkspaceFolder; connectionOptions?: { cancellationStrategy: CancellationStrategy; maxRestartCount?: number; }; markdown: { isTrusted: boolean; supportHtml: boolean; }; } & Required<$NotebookDocumentOptions> & Required<$DiagnosticPullOptions>; class DefaultErrorHandler implements ErrorHandler { private readonly restarts: number[]; constructor(private client: BaseLanguageClient, private maxRestartCount: number) { this.restarts = []; } public error(_error: Error, _message: Message, count: number): ErrorHandlerResult { if (count && count <= 3) { return { action: ErrorAction.Continue }; } return { action: ErrorAction.Shutdown }; } public closed(): CloseHandlerResult { this.restarts.push(Date.now()); if (this.restarts.length <= this.maxRestartCount) { return { action: CloseAction.Restart }; } else { let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; if (diff <= 3 * 60 * 1000) { return { action: CloseAction.DoNotRestart, message: `The ${this.client.name} server crashed ${this.maxRestartCount+1} times in the last 3 minutes. The server will not be restarted. See the output for more information.` }; } else { this.restarts.shift(); return { action: CloseAction.Restart }; } } } } enum ClientState { Initial = 'initial', Starting = 'starting', StartFailed = 'startFailed', Running = 'running', Stopping = 'stopping', Stopped = 'stopped' } export interface MessageTransports { reader: MessageReader; writer: MessageWriter; detached?: boolean; } export namespace MessageTransports { export function is(value: any): value is MessageTransports { let candidate: MessageTransports = value; return candidate && MessageReader.is(value.reader) && MessageWriter.is(value.writer); } } export abstract class BaseLanguageClient implements FeatureClient<Middleware, LanguageClientOptions> { private _id: string; private _name: string; private _clientOptions: ResolvedClientOptions; private _state: ClientState; private _onStart: Promise<void> | undefined; private _onStop: Promise<void> | undefined; private _connection: Connection | undefined; private _idleInterval: Disposable | undefined; private readonly _ignoredRegistrations: Set<string>; // private _idleStart: number | undefined; private readonly _listeners: Disposable[]; private _disposed: 'disposing' | 'disposed' | undefined; private readonly _notificationHandlers: Map<string, GenericNotificationHandler>; private readonly _notificationDisposables: Map<string, Disposable>; private readonly _pendingNotificationHandlers: Map<string, GenericNotificationHandler>; private readonly _requestHandlers: Map<string, GenericRequestHandler<unknown, unknown>>; private readonly _requestDisposables: Map<string, Disposable>; private readonly _pendingRequestHandlers: Map<string, GenericRequestHandler<unknown, unknown>>; private readonly _progressHandlers: Map<string | number, { type: ProgressType<any>; handler: NotificationHandler<any> }>; private readonly _pendingProgressHandlers: Map<string | number, { type: ProgressType<any>; handler: NotificationHandler<any> }>; private readonly _progressDisposables: Map<string | number, Disposable>; private _initializeResult: InitializeResult | undefined; private _outputChannel: OutputChannel | undefined; private _disposeOutputChannel: boolean; private _traceOutputChannel: OutputChannel | undefined; private _capabilities!: ServerCapabilities & ResolvedTextDocumentSyncCapabilities; private _diagnostics: DiagnosticCollection | undefined; private _syncedDocuments: Map<string, TextDocument>; private _fileEvents: FileEvent[]; private _fileEventDelayer: Delayer<void>; private _telemetryEmitter: Emitter<any>; private _stateChangeEmitter: Emitter<StateChangeEvent>; private _trace: Trace; private _traceFormat: TraceFormat = TraceFormat.Text; private _tracer: Tracer; private readonly _c2p: c2p.Converter; private readonly _p2c: p2c.Converter; public constructor(id: string, name: string, clientOptions: LanguageClientOptions) { this._id = id; this._name = name; clientOptions = clientOptions || {}; const markdown = { isTrusted: false, supportHtml: false }; if (clientOptions.markdown !== undefined) { markdown.isTrusted = clientOptions.markdown.isTrusted === true; markdown.supportHtml = clientOptions.markdown.supportHtml === true; } // const defaultInterval = (clientOptions as TestOptions).$testMode ? 50 : 60000; this._clientOptions = { documentSelector: clientOptions.documentSelector ?? [], synchronize: clientOptions.synchronize ?? {}, diagnosticCollectionName: clientOptions.diagnosticCollectionName, outputChannelName: clientOptions.outputChannelName ?? this._name, revealOutputChannelOn: clientOptions.revealOutputChannelOn ?? RevealOutputChannelOn.Error, stdioEncoding: clientOptions.stdioEncoding ?? 'utf8', initializationOptions: clientOptions.initializationOptions, initializationFailedHandler: clientOptions.initializationFailedHandler, progressOnInitialization: !!clientOptions.progressOnInitialization, errorHandler: clientOptions.errorHandler ?? this.createDefaultErrorHandler(clientOptions.connectionOptions?.maxRestartCount), middleware: clientOptions.middleware ?? {}, uriConverters: clientOptions.uriConverters, workspaceFolder: clientOptions.workspaceFolder, connectionOptions: clientOptions.connectionOptions, markdown, // suspend: { // mode: clientOptions.suspend?.mode ?? SuspendMode.off, // callback: clientOptions.suspend?.callback ?? (() => Promise.resolve(true)), // interval: clientOptions.suspend?.interval ? Math.max(clientOptions.suspend.interval, defaultInterval) : defaultInterval // }, diagnosticPullOptions: clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false }, notebookDocumentOptions: clientOptions.notebookDocumentOptions ?? { } }; this._clientOptions.synchronize = this._clientOptions.synchronize || {}; this._state = ClientState.Initial; this._ignoredRegistrations = new Set(); this._listeners = []; this._notificationHandlers = new Map(); this._pendingNotificationHandlers = new Map(); this._notificationDisposables = new Map(); this._requestHandlers = new Map(); this._pendingRequestHandlers = new Map(); this._requestDisposables = new Map(); this._progressHandlers = new Map(); this._pendingProgressHandlers = new Map(); this._progressDisposables = new Map(); this._connection = undefined; // this._idleStart = undefined; this._initializeResult = undefined; if (clientOptions.outputChannel) { this._outputChannel = clientOptions.outputChannel; this._disposeOutputChannel = false; } else { this._outputChannel = undefined; this._disposeOutputChannel = true; } this._traceOutputChannel = clientOptions.traceOutputChannel; this._diagnostics = undefined; this._fileEvents = []; this._fileEventDelayer = new Delayer<void>(250); this._onStop = undefined; this._telemetryEmitter = new Emitter<any>(); this._stateChangeEmitter = new Emitter<StateChangeEvent>(); this._trace = Trace.Off; this._tracer = { log: (messageOrDataObject: string | any, data?: string) => { if (Is.string(messageOrDataObject)) { this.logTrace(messageOrDataObject, data); } else { this.logObjectTrace(messageOrDataObject); } }, }; this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined); this._p2c = p2c.createConverter( clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined, this._clientOptions.markdown.isTrusted, this._clientOptions.markdown.supportHtml); this._syncedDocuments = new Map<string, TextDocument>(); this.registerBuiltinFeatures(); } public get name(): string { return this._name; } public get middleware(): Middleware { return this._clientOptions.middleware ?? Object.create(null); } public get clientOptions(): LanguageClientOptions { return this._clientOptions; } public get protocol2CodeConverter(): p2c.Converter { return this._p2c; } public get code2ProtocolConverter(): c2p.Converter { return this._c2p; } public get onTelemetry(): Event<any> { return this._telemetryEmitter.event; } public get onDidChangeState(): Event<StateChangeEvent> { return this._stateChangeEmitter.event; } public get outputChannel(): OutputChannel { if (!this._outputChannel) { this._outputChannel = Window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name); } return this._outputChannel; } public get traceOutputChannel(): OutputChannel { if (this._traceOutputChannel) { return this._traceOutputChannel; } return this.outputChannel; } public get diagnostics(): DiagnosticCollection | undefined { return this._diagnostics; } public get state(): State { return this.getPublicState(); } private get $state(): ClientState { return this._state; } private set $state(value: ClientState) { let oldState = this.getPublicState(); this._state = value; let newState = this.getPublicState(); if (newState !== oldState) { this._stateChangeEmitter.fire({ oldState, newState }); } } private getPublicState(): State { switch (this.$state) { case ClientState.Starting: return State.Starting; case ClientState.Running: return State.Running; default: return State.Stopped; } } public get initializeResult(): InitializeResult | undefined { return this._initializeResult; } public sendRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, token?: CancellationToken): Promise<R>; public sendRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, params: P, token?: CancellationToken): Promise<R>; public sendRequest<R, E>(type: RequestType0<R, E>, token?: CancellationToken): Promise<R>; public sendRequest<P, R, E>(type: RequestType<P, R, E>, params: P, token?: CancellationToken): Promise<R>; public sendRequest<R>(method: string, token?: CancellationToken): Promise<R>; public sendRequest<R>(method: string, param: any, token?: CancellationToken): Promise<R>; public async sendRequest<R>(type: string | MessageSignature, ...params: any[]): Promise<R> { if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) { return Promise.reject(new ResponseError(ErrorCodes.ConnectionInactive, `Client is not running`)); } try { // Ensure we have a connection before we force the document sync. const connection = await this.$start(); await this.forceDocumentSync(); return connection.sendRequest<R>(type, ...params); } catch (error) { this.error(`Sending request ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } public onRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, handler: RequestHandler0<R, E>): Disposable; public onRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, handler: RequestHandler<P, R, E>): Disposable; public onRequest<R, E>(type: RequestType0<R, E>, handler: RequestHandler0<R, E>): Disposable; public onRequest<P, R, E>(type: RequestType<P, R, E>, handler: RequestHandler<P, R, E>): Disposable; public onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): Disposable; public onRequest<R, E>(type: string | MessageSignature, handler: GenericRequestHandler<R, E>): Disposable { const method = typeof type === 'string' ? type : type.method; this._requestHandlers.set(method, handler); const connection = this.activeConnection(); let disposable: Disposable; if (connection !== undefined) { this._requestDisposables.set(method, connection.onRequest(type, handler)); disposable = { dispose: () => { const disposable = this._requestDisposables.get(method); if (disposable !== undefined) { disposable.dispose(); this._requestDisposables.delete(method); } } }; } else { this._pendingRequestHandlers.set(method, handler); disposable = { dispose: () => { this._pendingRequestHandlers.delete(method); const disposable = this._requestDisposables.get(method); if (disposable !== undefined) { disposable.dispose(); this._requestDisposables.delete(method); } } }; } return { dispose: () => { this._requestHandlers.delete(method); disposable.dispose(); } }; } public sendNotification<RO>(type: ProtocolNotificationType0<RO>): Promise<void>; public sendNotification<P, RO>(type: ProtocolNotificationType<P, RO>, params?: P): Promise<void>; public sendNotification(type: NotificationType0): Promise<void>; public sendNotification<P>(type: NotificationType<P>, params?: P): Promise<void>; public sendNotification(method: string): Promise<void>; public sendNotification(method: string, params: any): Promise<void>; public async sendNotification<P>(type: string | MessageSignature, params?: P): Promise<void> { if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) { return Promise.reject(new ResponseError(ErrorCodes.ConnectionInactive, `Client is not running`)); } try { // Ensure we have a connection before we force the document sync. const connection = await this.$start(); await this.forceDocumentSync(); return connection.sendNotification(type, params); } catch (error) { this.error(`Sending notification ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } public onNotification<RO>(type: ProtocolNotificationType0<RO>, handler: NotificationHandler0): Disposable; public onNotification<P, RO>(type: ProtocolNotificationType<P, RO>, handler: NotificationHandler<P>): Disposable; public onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable; public onNotification<P>(type: NotificationType<P>, handler: NotificationHandler<P>): Disposable; public onNotification(method: string, handler: GenericNotificationHandler): Disposable; public onNotification(type: string | MessageSignature, handler: GenericNotificationHandler): Disposable { const method = typeof type === 'string' ? type : type.method; this._notificationHandlers.set(method, handler); const connection = this.activeConnection(); let disposable: Disposable; if (connection !== undefined) { this._notificationDisposables.set(method, connection.onNotification(type, handler)); disposable = { dispose: () => { const disposable = this._notificationDisposables.get(method); if (disposable !== undefined) { disposable.dispose(); this._notificationDisposables.delete(method); } } }; } else { this._pendingNotificationHandlers.set(method, handler); disposable = { dispose: () => { this._pendingNotificationHandlers.delete(method); const disposable = this._notificationDisposables.get(method); if (disposable !== undefined) { disposable.dispose(); this._notificationDisposables.delete(method); } } }; } return { dispose: () => { this._notificationHandlers.delete(method); disposable.dispose(); } }; } public async sendProgress<P>(type: ProgressType<P>, token: string | number, value: P): Promise<void> { if (this.$state === ClientState.StartFailed || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped) { return Promise.reject(new ResponseError(ErrorCodes.ConnectionInactive, `Client is not running`)); } try { // Ensure we have a connection before we force the document sync. const connection = await this.$start(); return connection.sendProgress(type, token, value); } catch (error) { this.error(`Sending progress for token ${token} failed.`, error); throw error; } } public onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable { this._progressHandlers.set(token, { type, handler }); const connection = this.activeConnection(); let disposable: Disposable; const handleWorkDoneProgress = this._clientOptions.middleware?.handleWorkDoneProgress; const realHandler = WorkDoneProgress.is(type) && handleWorkDoneProgress !== undefined ? (params: P) => { handleWorkDoneProgress(token, params as any, () => handler(params as unknown as P)); } : handler; if (connection !== undefined) { this._progressDisposables.set(token, connection.onProgress(type, token, realHandler)); disposable = { dispose: () => { const disposable = this._progressDisposables.get(token); if (disposable !== undefined) { disposable.dispose(); this._progressDisposables.delete(token); } } }; } else { this._pendingProgressHandlers.set(token, { type, handler }); disposable = { dispose: () => { this._pendingProgressHandlers.delete(token); const disposable = this._progressDisposables.get(token); if (disposable !== undefined) { disposable.dispose(); this._progressDisposables.delete(token); } } }; } return { dispose: (): void => { this._progressHandlers.delete(token); disposable.dispose(); } }; } public createDefaultErrorHandler(maxRestartCount?: number): ErrorHandler { if (maxRestartCount !== undefined && maxRestartCount < 0) { throw new Error(`Invalid maxRestartCount: ${maxRestartCount}`); } return new DefaultErrorHandler(this, maxRestartCount ?? 4); } public async setTrace(value: Trace): Promise<void> { this._trace = value; const connection = this.activeConnection(); if (connection !== undefined) { await connection.trace(this._trace, this._tracer, { sendNotification: false, traceFormat: this._traceFormat }); } } private data2String(data: Object): string { if (data instanceof ResponseError) { const responseError = data as ResponseError<any>; return ` Message: ${responseError.message}\n Code: ${responseError.code} ${responseError.data ? '\n' + responseError.data.toString() : ''}`; } if (data instanceof Error) { if (Is.string(data.stack)) { return data.stack; } return (data as Error).message; } if (Is.string(data)) { return data; } return data.toString(); } public info(message: string, data?: any, showNotification: boolean = true): void { this.outputChannel.appendLine(`[Info - ${(new Date().toLocaleTimeString())}] ${message}`); if (data !== null && data !== undefined) { this.outputChannel.appendLine(this.data2String(data)); } if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) { this.showNotificationMessage(MessageType.Info, message); } } public warn(message: string, data?: any, showNotification: boolean = true): void { this.outputChannel.appendLine(`[Warn - ${(new Date().toLocaleTimeString())}] ${message}`); if (data !== null && data !== undefined) { this.outputChannel.appendLine(this.data2String(data)); } if (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) { this.showNotificationMessage(MessageType.Warning, message); } } public error(message: string, data?: any, showNotification: boolean | 'force' = true): void { this.outputChannel.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`); if (data !== null && data !== undefined) { this.outputChannel.appendLine(this.data2String(data)); } if (showNotification === 'force' || (showNotification && this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error)) { this.showNotificationMessage(MessageType.Error, message); } } private showNotificationMessage(type: MessageType, message?: string) { message = message ?? 'A request has failed. See the output for more information.'; const messageFunc = type === MessageType.Error ? Window.showErrorMessage : type === MessageType.Warning ? Window.showWarningMessage : Window.showInformationMessage; void messageFunc(message, 'Go to output').then((selection) => { if (selection !== undefined) { this.outputChannel.show(true); } }); } private logTrace(message: string, data?: any): void { this.traceOutputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.traceOutputChannel.appendLine(this.data2String(data)); } } private logObjectTrace(data: any): void { if (data.isLSPMessage && data.type) { this.traceOutputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `); } else { this.traceOutputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `); } if (data) { this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`); } } public needsStart(): boolean { return this.$state === ClientState.Initial || this.$state === ClientState.Stopping || this.$state === ClientState.Stopped; } public needsStop(): boolean { return this.$state === ClientState.Starting || this.$state === ClientState.Running; } private activeConnection(): Connection | undefined { return this.$state === ClientState.Running && this._connection !== undefined ? this._connection : undefined; } public isRunning(): boolean { return this.$state === ClientState.Running; } public async start(): Promise<void> { if (this._disposed === 'disposing' || this._disposed === 'disposed') { throw new Error(`Client got disposed and can't be restarted.`); } if (this.$state === ClientState.Stopping) { throw new Error(`Client is currently stopping. Can only restart a full stopped client`); } // We are already running or are in the process of getting up // to speed. if (this._onStart !== undefined) { return this._onStart; } const [promise, resolve, reject] = this.createOnStartPromise(); this._onStart = promise; // If we restart then the diagnostics collection is reused. if (this._diagnostics === undefined) { this._diagnostics = this._clientOptions.diagnosticCollectionName ? Languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName) : Languages.createDiagnosticCollection(); } // When we start make all buffer handlers pending so that they // get added. for (const [method, handler] of this._notificationHandlers) { if (!this._pendingNotificationHandlers.has(method)) { this._pendingNotificationHandlers.set(method, handler); } } for (const [method, handler] of this._requestHandlers) { if (!this._pendingRequestHandlers.has(method)) { this._pendingRequestHandlers.set(method, handler); } } for (const [token, data] of this._progressHandlers) { if (!this._pendingProgressHandlers.has(token)) { this._pendingProgressHandlers.set(token, data); } } this.$state = ClientState.Starting; try { const connection = await this.createConnection(); connection.onNotification(LogMessageNotification.type, (message) => { switch (message.type) { case MessageType.Error: this.error(message.message, undefined, false); break; case MessageType.Warning: this.warn(message.message, undefined, false); break; case MessageType.Info: this.info(message.message, undefined, false); break; default: this.outputChannel.appendLine(message.message); } }); connection.onNotification(ShowMessageNotification.type, (message) => { switch (message.type) { case MessageType.Error: void Window.showErrorMessage(message.message); break; case MessageType.Warning: void Window.showWarningMessage(message.message); break; case MessageType.Info: void Window.showInformationMessage(message.message); break; default: void Window.showInformationMessage(message.message); } }); connection.onRequest(ShowMessageRequest.type, (params) => { let messageFunc: <T extends MessageItem>(message: string, ...items: T[]) => Thenable<T>; switch (params.type) { case MessageType.Error: messageFunc = Window.showErrorMessage; break; case MessageType.Warning: messageFunc = Window.showWarningMessage; break; case MessageType.Info: messageFunc = Window.showInformationMessage; break; default: messageFunc = Window.showInformationMessage; } let actions = params.actions || []; return messageFunc(params.message, ...actions); }); connection.onNotification(TelemetryEventNotification.type, (data) => { this._telemetryEmitter.fire(data); }); connection.onRequest(ShowDocumentRequest.type, async (params): Promise<ShowDocumentResult> => { const showDocument = async (params: ShowDocumentParams): Promise<ShowDocumentResult> => { const uri = this.protocol2CodeConverter.asUri(params.uri); try { if (params.external === true) { const success = await Env.openExternal(uri); return { success }; } else { const options: TextDocumentShowOptions = {}; if (params.selection !== undefined) { options.selection = this.protocol2CodeConverter.asRange(params.selection); } if (params.takeFocus === undefined || params.takeFocus === false) { options.preserveFocus = true; } else if (params.takeFocus === true) { options.preserveFocus = false; } await Window.showTextDocument(uri, options); return { success: true }; } } catch (error) { return { success: false }; } }; const middleware = this._clientOptions.middleware.window?.showDocument; if (middleware !== undefined) { return middleware(params, showDocument); } else { return showDocument(params); } }); connection.listen(); await this.initialize(connection); resolve(); } catch (error) { this.$state = ClientState.StartFailed; this.error(`${this._name} client: couldn't create connection to server.`, error, 'force'); reject(error); } return this._onStart; } private createOnStartPromise(): [ Promise<void>, () => void, (error:any) => void] { let resolve!: () => void; let reject!: (error: any) => void; const promise: Promise<void> = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); return [promise, resolve, reject]; } private async initialize(connection: Connection): Promise<InitializeResult> { this.refreshTrace(connection, false); const initOption = this._clientOptions.initializationOptions; // If the client is locked to a workspace folder use it. In this case the workspace folder // feature is not registered and we need to initialize the value here. const [rootPath, workspaceFolders] = this._clientOptions.workspaceFolder !== undefined ? [this._clientOptions.workspaceFolder.uri.fsPath, [{ uri: this._c2p.asUri(this._clientOptions.workspaceFolder.uri), name: this._clientOptions.workspaceFolder.name }]] : [this._clientGetRootPath(), null]; const initParams: InitializeParams = { processId: null, clientInfo: { name: Env.appName, version: VSCodeVersion }, locale: this.getLocale(), rootPath: rootPath ? rootPath : null, rootUri: rootPath ? this._c2p.asUri(Uri.file(rootPath)) : null, capabilities: this.computeClientCapabilities(), initializationOptions: Is.func(initOption) ? initOption() : initOption, trace: Trace.toString(this._trace), workspaceFolders: workspaceFolders }; this.fillInitializeParams(initParams); if (this._clientOptions.progressOnInitialization) { const token: ProgressToken = UUID.generateUuid(); const part: ProgressPart = new ProgressPart(connection, token); initParams.workDoneToken = token; try { const result = await this.doInitialize(connection, initParams); part.done(); return result; } catch (error) { part.cancel(); throw error; } } else { return this.doInitialize(connection, initParams); } } private async doInitialize(connection: Connection, initParams: InitializeParams): Promise<InitializeResult> { try { const result = await connection.initialize(initParams); if (result.capabilities.positionEncoding !== undefined && result.capabilities.positionEncoding !== PositionEncodingKind.UTF16) { throw new Error(`Unsupported position encoding (${result.capabilities.positionEncoding}) received from server ${this.name}`); } this._initializeResult = result; this.$state = ClientState.Running; let textDocumentSyncOptions: TextDocumentSyncOptions | undefined = undefined; if (Is.number(result.capabilities.textDocumentSync)) { if (result.capabilities.textDocumentSync === TextDocumentSyncKind.None) { textDocumentSyncOptions = { openClose: false, change: TextDocumentSyncKind.None, save: undefined }; } else { textDocumentSyncOptions = { openClose: true, change: result.capabilities.textDocumentSync, save: { includeText: false } }; } } else if (result.capabilities.textDocumentSync !== undefined && result.capabilities.textDocumentSync !== null) { textDocumentSyncOptions = result.capabilities.textDocumentSync as TextDocumentSyncOptions; } this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions }); connection.onNotification(PublishDiagnosticsNotification.type, params => this.handleDiagnostics(params)); connection.onRequest(RegistrationRequest.type, params => this.handleRegistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/registerFeature', params => this.handleRegistrationRequest(params)); connection.onRequest(UnregistrationRequest.type, params => this.handleUnregistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/unregisterFeature', params => this.handleUnregistrationRequest(params)); connection.onRequest(ApplyWorkspaceEditRequest.type, params => this.handleApplyWorkspaceEdit(params)); // Add pending notification, request and progress handlers. for (const [method, handler] of this._pendingNotificationHandlers) { this._notificationDisposables.set(method, connection.onNotification(method, handler)); } this._pendingNotificationHandlers.clear(); for (const [method, handler] of this._pendingRequestHandlers) { this._requestDisposables.set(method, connection.onRequest(method, handler)); } this._pendingRequestHandlers.clear(); for (const [token, data] of this._pendingProgressHandlers) { this._progressDisposables.set(token, connection.onProgress(data.type, token, data.handler)); } this._pendingProgressHandlers.clear(); // if (this._clientOptions.suspend.mode !== SuspendMode.off) { // this._idleInterval = RAL().timer.setInterval(() => this.checkSuspend(), this._clientOptions.suspend.interval); // } await connection.sendNotification(InitializedNotification.type, {}); this.hookFileEvents(connection); this.hookConfigurationChanged(connection); this.initializeFeatures(connection); return result; } catch (error: any) { if (this._clientOptions.initializationFailedHandler) { if (this._clientOptions.initializationFailedHandler(error)) { void this.initialize(connection); } else { void this.stop(); } } else if (error instanceof ResponseError && error.data && error.data.retry) { void Window.showErrorMessage(error.message, { title: 'Retry', id: 'retry' }).then(item => { if (item && item.id === 'retry') { void this.initialize(connection); } else { void this.stop(); } }); } else { if (error && error.message) { void Window.showErrorMessage(error.message); } this.error('Server initialization failed.', error); void this.stop(); } throw error; } } private _clientGetRootPath(): string | undefined { let folders = Workspace.workspaceFolders; if (!folders || folders.length === 0) { return undefined; } let folder = folders[0]; if (folder.uri.scheme === 'file') { return folder.uri.fsPath; } return undefined; } public stop(timeout: number = 2000): Promise<void> { // Wait 2 seconds on stop return this.shutdown('stop', timeout); } public dispose(timeout: number = 2000): Promise<void> { try { this._disposed = 'disposing'; return this.stop(timeout); } finally { this._disposed = 'disposed'; } } private async shutdown(mode: 'suspend' | 'stop', timeout: number): Promise<void> { // If the client is stopped or in its initial state return. if (this.$state === ClientState.Stopped || this.$state === ClientState.Initial) { return; } // If we are stopping the client and have a stop promise return it. if (this.$state === ClientState.Stopping) { if (this._onStop !== undefined) { return this._onStop; } else { throw new Error(`Client is stopping but no stop promise available.`); } } const connection = this.activeConnection(); // We can't stop a client that is not running (e.g. has no connection). Especially not // on that us starting since it can't be correctly synchronized. if (connection === undefined || this.$state !== ClientState.Running) { throw new Error(`Client is not running and can't be stopped. It's current state is: ${this.$state}`); } this._initializeResult = undefined; this.$state = ClientState.Stopping; this.cleanUp(mode); const tp = new Promise<undefined>(c => { RAL().timer.setTimeout(c, timeout); }); const shutdown = (async (connection) => { await connection.shutdown(); await connection.exit(); return connection; })(connection); return this._onStop = Promise.race([tp, shutdown]).then((connection) => { // The connection won the race with the timeout. if (connection !== undefined) { connection.end(); connection.dispose(); } else { this.error(`Stopping server timed out`, undefined, false); throw new Error(`Stopping the server timed out`); } }, (error) => { this.error(`Stopping server failed`, error, false); throw error; }).finally(() => { this.$state = ClientState.Stopped; mode === 'stop' && this.cleanUpChannel(); this._onStart = undefined; this._onStop = undefined; this._connection = undefined; this._ignoredRegistrations.clear(); }); } private cleanUp(mode: 'restart' | 'suspend' | 'stop'): void { // purge outstanding file events. this._fileEvents = []; this._fileEventDelayer.cancel(); const disposables = this._listeners.splice(0, this._listeners.length); for (const disposable of disposables) { disposable.dispose(); } if (this._syncedDocuments) { this._syncedDocuments.clear(); } // Dispose features in reverse order; for (const feature of Array.from(this._features.entries()).map(entry => entry[1]).reverse()) { feature.dispose(); } if (mode === 'stop' && this._diagnostics !== undefined) { this._diagnostics.dispose(); this._diagnostics = undefined; } if (this._idleInterval !== undefined) { this._idleInterval.dispose(); this._idleInterval = undefined; } // this._idleStart = undefined; } private cleanUpChannel(): void { if (this._outputChannel !== undefined && this._disposeOutputChannel) { this._outputChannel.dispose(); this._outputChannel = undefined; } } private notifyFileEvent(event: FileEvent): void { const client = this; async function didChangeWatchedFile(this: void, event: FileEvent): Promise<void> { client._fileEvents.push(event); return client._fileEventDelayer.trigger(async (): Promise<void> => { const connection = await client.$start(); await client.forceDocumentSync(); const result = connection.sendNotification(DidChangeWatchedFilesNotification.type, { changes: client._fileEvents }); client._fileEvents = []; return result; }); } const workSpaceMiddleware = this.clientOptions.middleware?.workspace; (workSpaceMiddleware?.didChangeWatchedFile ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event)).catch((error) => { client.error(`Notify file events failed.`, error); }); } private _didChangeTextDocumentFeature: DidChangeTextDocumentFeature | undefined; private async forceDocumentSync(): Promise<void> { if (this._didChangeTextDocumentFeature === undefined) { this._didChangeTextDocumentFeature = this._dynamicFeatures.get(DidChangeTextDocumentNotification.type.method) as DidChangeTextDocumentFeature; } return this._didChangeTextDocumentFeature.forceDelivery(); } private _diagnosticQueue: Map<string, Diagnostic[]> = new Map(); private _diagnosticQueueState: { state: 'idle' } | { state: 'busy'; document: string; tokenSource: CancellationTokenSource } = { state: 'idle' }; private handleDiagnostics(params: PublishDiagnosticsParams) { if (!this._diagnostics) { return; } const key = params.uri; if (this._diagnosticQueueState.state === 'busy' && this._diagnosticQueueState.document === key) { // Cancel the active run; this._diagnosticQueueState.tokenSource.cancel(); } this._diagnosticQueue.set(params.uri, params.diagnostics); this.triggerDiagnosticQueue(); } private triggerDiagnosticQueue(): void { RAL().timer.setImmediate(() => { this.workDiagnosticQueue(); }); } private workDiagnosticQueue(): void { if (this._diagnosticQueueState.state === 'busy') { return; } const next = this._diagnosticQueue.entries().next(); if (next.done === true) { // Nothing in the queue return; } const [document, diagnostics] = next.value; this._diagnosticQueue.delete(document); const tokenSource = new CancellationTokenSource(); this._diagnosticQueueState = { state: 'busy', document: document, tokenSource }; this._p2c.asDiagnostics(diagnostics, tokenSource.token).then((converted) => { if (!tokenSource.token.isCancellationRequested) { const uri = this._p2c.asUri(document); const middleware = this.clientOptions.middleware!; if (middleware.handleDiagnostics) { middleware.handleDiagnostics(uri, converted, (uri, diagnostics) => this.setDiagnostics(uri, diagnostics)); } else { this.setDiagnostics(uri, converted); } } }).finally(() => { this._diagnosticQueueState = { state: 'idle' }; this.triggerDiagnosticQueue(); }); } private setDiagnostics(uri: Uri, diagnostics: VDiagnostic[] | undefined) { if (!this._diagnostics) { return; } this._diagnostics.set(uri, diagnostics); } protected abstract getLocale(): string; protected abstract createMessageTransports(encoding: string): Promise<MessageTransports>; private async $start(): Promise<Connection> { if (this.$state === ClientState.StartFailed) { throw new Error(`Previous start failed. Can't restart server.`); } await this.start(); const connection = this.activeConnection(); if (connection === undefined) { throw new Error(`Starting server failed`); } return connection; } private async createConnection(): Promise<Connection> { let errorHandler = (error: Error, message: Message | undefined, count: number | undefined) => { this.handleConnectionError(error, message, count); }; let closeHandler = () => { this.handleConnectionClosed(); }; const transports = await this.createMessageTransports(this._clientOptions.stdioEncoding || 'utf8'); this._connection = createConnection(transports.reader, transports.writer, errorHandler, closeHandler, this._clientOptions.connectionOptions); return this._connection; } protected handleConnectionClosed(): void { // Check whether this is a normal shutdown in progress or the client stopped normally. if (this.$state === ClientState.Stopped) { return; } try { if (this._connection !== undefined) { this._connection.dispose(); } } catch (error) { // Disposing a connection could fail if error cases. } let handlerResult: CloseHandlerResult = { action: CloseAction.DoNotRestart }; if (this.$state !== ClientState.Stopping) { try { handlerResult = this._clientOptions.errorHandler!.closed(); } catch (error) { // Ignore errors coming from the error handler. } } this._connection = undefined; if (handlerResult.action === CloseAction.DoNotRestart) { this.error(handlerResult.message ?? 'Connection to server got closed. Server will not be restarted.', undefined, 'force'); this.cleanUp('stop'); if (this.$state === ClientState.Starting) { this.$state = ClientState.StartFailed; } else { this.$state = ClientState.Stopped; } this._onStop = Promise.resolve(); this._onStart = undefined; } else if (handlerResult.action === CloseAction.Restart) { this.info(handlerResult.message ?? 'Connection to server got closed. Server will restart.'); this.cleanUp('restart'); this.$state = ClientState.Initial; this._onStop = Promise.resolve(); this._onStart = undefined; this.start().catch((error) => this.error(`Restarting server failed`, error, 'force')); } } private handleConnectionError(error: Error, message: Message | undefined, count: number | undefined): void { const handlerResult: ErrorHandlerResult = this._clientOptions.errorHandler!.error(error, message, count); if (handlerResult.action === ErrorAction.Shutdown) { this.error(handlerResult.message ?? `Client ${this._name}: connection to server is erroring. Shutting down server.`, undefined, 'force'); this.stop().catch((error) => { this.error(`Stopping server failed`, error, false); }); } } private hookConfigurationChanged(connection: Connection): void { this._listeners.push(Workspace.onDidChangeConfiguration(() => { this.refreshTrace(connection, true); })); } private refreshTrace(connection: Connection, sendNotification: boolean = false): void { const config = Workspace.getConfiguration(this._id); let trace: Trace = Trace.Off; let traceFormat: TraceFormat = TraceFormat.Text; if (config) { const traceConfig = config.get('trace.server', 'off'); if (typeof traceConfig === 'string') { trace = Trace.fromString(traceConfig); } else { trace = Trace.fromString(config.get('trace.server.verbosity', 'off')); traceFormat = TraceFormat.fromString(config.get('trace.server.format', 'text')); } } this._trace = trace; this._traceFormat = traceFormat; connection.trace(this._trace, this._tracer, { sendNotification, traceFormat: this._traceFormat }).catch((error) => { this.error(`Updating trace failed with error`, error, false);}); } private hookFileEvents(_connection: Connection): void { let fileEvents = this._clientOptions.synchronize.fileEvents; if (!fileEvents) { return; } let watchers: VFileSystemWatcher[]; if (Is.array(fileEvents)) { watchers = <VFileSystemWatcher[]>fileEvents; } else { watchers = [<VFileSystemWatcher>fileEvents]; } if (!watchers) { return; } (this._dynamicFeatures.get(DidChangeWatchedFilesNotification.type.method)! as FileSystemWatcherFeature).registerRaw(UUID.generateUuid(), watchers); } private readonly _features: (StaticFeature | DynamicFeature<any>)[] = []; private readonly _dynamicFeatures: Map<string, DynamicFeature<any>> = new Map<string, DynamicFeature<any>>(); public registerFeatures(features: (StaticFeature | DynamicFeature<any>)[]): void { for (let feature of features) { this.registerFeature(feature); } } public registerFeature(feature: StaticFeature | DynamicFeature<any>): void { this._features.push(feature); if (DynamicFeature.is(feature)) { const registrationType = feature.registrationType; this._dynamicFeatures.set(registrationType.method, feature); } } getFeature(request: typeof DidOpenTextDocumentNotification.method): DidOpenTextDocumentFeatureShape; getFeature(request: typeof DidChangeTextDocumentNotification.method): DidChangeTextDocumentFeatureShape; getFeature(request: typeof WillSaveTextDocumentNotification.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentSendFeature<(textDocument: TextDocument) => Promise<void>>; getFeature(request: typeof WillSaveTextDocumentWaitUntilRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentSendFeature<(textDocument: TextDocument) => ProviderResult<VTextEdit[]>>; getFeature(request: typeof DidSaveTextDocumentNotification.method): DidSaveTextDocumentFeatureShape; getFeature(request: typeof DidCloseTextDocumentNotification.method): DidCloseTextDocumentFeatureShape; getFeature(request: typeof DidCreateFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileCreateEvent) => Promise<void> }; getFeature(request: typeof DidRenameFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileRenameEvent) => Promise<void> }; getFeature(request: typeof DidDeleteFilesNotification.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileDeleteEvent) => Promise<void> }; getFeature(request: typeof WillCreateFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileWillCreateEvent) => Promise<void> }; getFeature(request: typeof WillRenameFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileWillRenameEvent) => Promise<void> }; getFeature(request: typeof WillDeleteFilesRequest.method): DynamicFeature<FileOperationRegistrationOptions> & { send: (event: FileWillDeleteEvent) => Promise<void> }; getFeature(request: typeof CompletionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CompletionItemProvider>; getFeature(request: typeof HoverRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<HoverProvider>; getFeature(request: typeof SignatureHelpRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SignatureHelpProvider>; getFeature(request: typeof DefinitionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DefinitionProvider>; getFeature(request: typeof ReferencesRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<ReferenceProvider>; getFeature(request: typeof DocumentHighlightRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentHighlightProvider>; getFeature(request: typeof CodeActionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CodeActionProvider>; getFeature(request: typeof CodeLensRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CodeLensProviderShape>; getFeature(request: typeof DocumentFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentFormattingEditProvider>; getFeature(request: typeof DocumentRangeFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentRangeFormattingEditProvider>; getFeature(request: typeof DocumentOnTypeFormattingRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<OnTypeFormattingEditProvider>; getFeature(request: typeof RenameRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<RenameProvider>; getFeature(request: typeof DocumentSymbolRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentSymbolProvider>; getFeature(request: typeof DocumentLinkRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentLinkProvider>; getFeature(request: typeof DocumentColorRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DocumentColorProvider>; getFeature(request: typeof DeclarationRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DeclarationProvider>; getFeature(request: typeof FoldingRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<FoldingRangeProvider>; getFeature(request: typeof ImplementationRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<ImplementationProvider>; getFeature(request: typeof SelectionRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SelectionRangeProvider>; getFeature(request: typeof TypeDefinitionRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<TypeDefinitionProvider>; getFeature(request: typeof CallHierarchyPrepareRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<CallHierarchyProvider>; getFeature(request: typeof SemanticTokensRegistrationType.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<SemanticTokensProviderShape>; getFeature(request: typeof LinkedEditingRangeRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<LinkedEditingRangeProvider>; getFeature(request: typeof TypeHierarchyPrepareRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<TypeHierarchyProvider>; getFeature(request: typeof InlineValueRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<InlineValueProviderShape>; getFeature(request: typeof InlayHintRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<InlayHintsProviderShape>; getFeature(request: typeof WorkspaceSymbolRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & WorkspaceProviderFeature<WorkspaceSymbolProvider>; getFeature(request: typeof DocumentDiagnosticRequest.method): DynamicFeature<TextDocumentRegistrationOptions> & TextDocumentProviderFeature<DiagnosticProviderShape> | undefined; getFeature(request: typeof NotebookDocumentSyncRegistrationType.method): DynamicFeature<NotebookDocumentSyncRegistrationOptions> & NotebookDocumentProviderShape | undefined; public getFeature(request: string): DynamicFeature<any> | undefined { return this._dynamicFeatures.get(request); } hasDedicatedTextSynchronizationFeature(textDocument: TextDocument): boolean { const feature = this.getFeature(NotebookDocumentSyncRegistrationType.method); if (feature === undefined || !(feature instanceof NotebookDocumentSyncFeature)) { return false; } return feature.handles(textDocument); } protected registerBuiltinFeatures() { this.registerFeature(new ConfigurationFeature(this)); this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new DidChangeTextDocumentFeature(this)); this.registerFeature(new WillSaveFeature(this)); this.registerFeature(new WillSaveWaitUntilFeature(this)); this.registerFeature(new DidSaveTextDocumentFeature(this)); this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event))); this.registerFeature(new CompletionItemFeature(this)); this.registerFeature(new HoverFeature(this)); this.registerFeature(new SignatureHelpFeature(this)); this.registerFeature(new DefinitionFeature(this)); this.registerFeature(new ReferencesFeature(this)); this.registerFeature(new DocumentHighlightFeature(this)); this.registerFeature(new DocumentSymbolFeature(this)); this.registerFeature(new WorkspaceSymbolFeature(this)); this.registerFeature(new CodeActionFeature(this)); this.registerFeature(new CodeLensFeature(this)); this.registerFeature(new DocumentFormattingFeature(this)); this.registerFeature(new DocumentRangeFormattingFeature(this)); this.registerFeature(new DocumentOnTypeFormattingFeature(this)); this.registerFeature(new RenameFeature(this)); this.registerFeature(new DocumentLinkFeature(this)); this.registerFeature(new ExecuteCommandFeature(this)); this.registerFeature(new SyncConfigurationFeature(this)); this.registerFeature(new TypeDefinitionFeature(this)); this.registerFeature(new ImplementationFeature(this)); this.registerFeature(new ColorProviderFeature(this)); // We only register the workspace folder feature if the client is not locked // to a specific workspace folder. if (this.clientOptions.workspaceFolder === undefined) { this.registerFeature(new WorkspaceFoldersFeature(this)); } this.registerFeature(new FoldingRangeFeature(this)); this.registerFeature(new DeclarationFeature(this)); this.registerFeature(new SelectionRangeFeature(this)); this.registerFeature(new ProgressFeature(this)); this.registerFeature(new CallHierarchyFeature(this)); this.registerFeature(new SemanticTokensFeature(this)); this.registerFeature(new LinkedEditingFeature(this)); this.registerFeature(new DidCreateFilesFeature(this)); this.registerFeature(new DidRenameFilesFeature(this)); this.registerFeature(new DidDeleteFilesFeature(this)); this.registerFeature(new WillCreateFilesFeature(this)); this.registerFeature(new WillRenameFilesFeature(this)); this.registerFeature(new WillDeleteFilesFeature(this)); this.registerFeature(new TypeHierarchyFeature(this)); this.registerFeature(new InlineValueFeature(this)); this.registerFeature(new InlayHintsFeature(this)); this.registerFeature(new DiagnosticFeature(this)); this.registerFeature(new NotebookDocumentSyncFeature(this)); } public registerProposedFeatures() { this.registerFeatures(ProposedFeatures.createAll(this)); } protected fillInitializeParams(params: InitializeParams): void { for (let feature of this._features) { if (Is.func(feature.fillInitializeParams)) { feature.fillInitializeParams(params); } } } private computeClientCapabilities(): ClientCapabilities { const result: ClientCapabilities = {}; ensure(result, 'workspace')!.applyEdit = true; const workspaceEdit = ensure(ensure(result, 'workspace')!, 'workspaceEdit')!; workspaceEdit.documentChanges = true; workspaceEdit.resourceOperations = [ResourceOperationKind.Create, ResourceOperationKind.Rename, ResourceOperationKind.Delete]; workspaceEdit.failureHandling = FailureHandlingKind.TextOnlyTransactional; workspaceEdit.normalizesLineEndings = true; workspaceEdit.changeAnnotationSupport = { groupsOnLabel: true }; const diagnostics = ensure(ensure(result, 'textDocument')!, 'publishDiagnostics')!; diagnostics.relatedInformation = true; diagnostics.versionSupport = false; diagnostics.tagSupport = { valueSet: [ DiagnosticTag.Unnecessary, DiagnosticTag.Deprecated ] }; diagnostics.codeDescriptionSupport = true; diagnostics.dataSupport = true; const windowCapabilities = ensure(result, 'window')!; const showMessage = ensure(windowCapabilities, 'showMessage')!; showMessage.messageActionItem = { additionalPropertiesSupport: true }; const showDocument = ensure(windowCapabilities, 'showDocument')!; showDocument.support = true; const generalCapabilities = ensure(result, 'general')!; generalCapabilities.staleRequestSupport = { cancel: true, retryOnContentModified: Array.from(BaseLanguageClient.RequestsToCancelOnContentModified) }; generalCapabilities.regularExpressions = { engine: 'ECMAScript', version: 'ES2020' }; generalCapabilities.markdown = { parser: 'marked', version: '1.1.0', }; generalCapabilities.positionEncodings = ['utf-16']; if (this._clientOptions.markdown.supportHtml) { generalCapabilities.markdown.allowedTags = ['ul', 'li', 'p', 'code', 'blockquote', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'em', 'pre', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'del', 'a', 'strong', 'br', 'img', 'span']; } for (let feature of this._features) { feature.fillClientCapabilities(result); } return result; } private initializeFeatures(_connection: Connection): void { const documentSelector = this._clientOptions.documentSelector; for (const feature of this._features) { if (Is.func(feature.preInitialize)) { feature.preInitialize(this._capabilities, documentSelector); } } for (const feature of this._features) { feature.initialize(this._capabilities, documentSelector); } } private async handleRegistrationRequest(params: RegistrationParams): Promise<void> { // We will not receive a registration call before a client is running // from a server. However if we stop or shutdown we might which might // try to restart the server. So ignore registrations if we are not running if (!this.isRunning()) { for (const registration of params.registrations) { this._ignoredRegistrations.add(registration.id); } return; } interface WithDocumentSelector { documentSelector: DocumentSelector | undefined; } for (const registration of params.registrations) { const feature = this._dynamicFeatures.get(registration.method); if (feature === undefined) { return Promise.reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`)); } const options = registration.registerOptions ?? {}; (options as unknown as WithDocumentSelector).documentSelector = (options as unknown as WithDocumentSelector).documentSelector ?? this._clientOptions.documentSelector; const data: RegistrationData<any> = { id: registration.id, registerOptions: options }; try { feature.register(data); } catch (err) { return Promise.reject(err); } } } private async handleUnregistrationRequest(params: UnregistrationParams): Promise<void> { for (let unregistration of params.unregisterations) { if (this._ignoredRegistrations.has(unregistration.id)) { continue; } const feature = this._dynamicFeatures.get(unregistration.method); if (!feature) { return Promise.reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`)); } feature.unregister(unregistration.id); } } private workspaceEditLock: Semaphore<VWorkspaceEdit> = new Semaphore(1); private async handleApplyWorkspaceEdit(params: ApplyWorkspaceEditParams): Promise<ApplyWorkspaceEditResult> { const workspaceEdit: WorkspaceEdit = params.edit; // Make sure we convert workspace edits one after the other. Otherwise // we might execute a workspace edit received first after we received another // one since the conversion might race. const converted = await this.workspaceEditLock.lock(() => { return this._p2c.asWorkspaceEdit(workspaceEdit); }); // This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit. // However doing it here adds some safety since the server can lag more behind then an extension. const openTextDocuments: Map<string, TextDocument> = new Map<string, TextDocument>(); Workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document)); let versionMismatch = false; if (workspaceEdit.documentChanges) { for (const change of workspaceEdit.documentChanges) { if (TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { const textDocument = openTextDocuments.get(change.textDocument.uri); if (textDocument && textDocument.version !== change.textDocument.version) { versionMismatch = true; break; } } } } if (versionMismatch) { return Promise.resolve({ applied: false }); } return Is.asPromise(Workspace.applyEdit(converted).then((value) => { return { applied: value }; })); } private static RequestsToCancelOnContentModified: Set<string> = new Set([ SemanticTokensRequest.method, SemanticTokensRangeRequest.method, SemanticTokensDeltaRequest.method ]); public handleFailedRequest<T>(type: MessageSignature, token: CancellationToken | undefined, error: any, defaultValue: T, showNotification: boolean = true): T { // If we get a request cancel or a content modified don't log anything. if (error instanceof ResponseError) { // The connection got disposed while we were waiting for a response. // Simply return the default value. Is the best we can do. if (error.code === ErrorCodes.PendingResponseRejected || error.code === ErrorCodes.ConnectionInactive) { return defaultValue; } if (error.code === LSPErrorCodes.RequestCancelled || error.code === LSPErrorCodes.ServerCancelled) { if (token !== undefined && token.isCancellationRequested) { return defaultValue; } else { if (error.data !== undefined) { throw new LSPCancellationError(error.data); } else { throw new CancellationError(); } } } else if (error.code === LSPErrorCodes.ContentModified) { if (BaseLanguageClient.RequestsToCancelOnContentModified.has(type.method)) { throw new CancellationError(); } else { return defaultValue; } } } this.error(`Request ${type.method} failed.`, error, showNotification); throw error; } // private checkSuspend(): void { // if (this.$state !== ClientState.Running) { // return; // } // const connection = this.activeConnection(); // if (connection === undefined) { // this._idleStart = undefined; // return; // } // // Since the last idle start we sent a request. Cancel the idle counting. // if (connection.hasPendingResponse() || (this._idleStart !== undefined && connection.lastUsed > this._idleStart)) { // this._idleStart = undefined; // return; // } // if (this.isIdle()) { // const production = (this.clientOptions as TestOptions).$testMode !== true; // // Only do this in production since in test cases we only have // // 2000 ms to suspend. // if (production) { // if (this._idleStart === undefined) { // this._idleStart = Date.now(); // return; // } // const interval = this._clientOptions.suspend.interval; // const diff = Date.now() - this._idleStart; // if (diff < interval * 3) { // return; // } // if (diff > interval * 5) { // // Avoid that we shutdown the server when a computer resumes from sleep. // this._idleStart = undefined; // return; // } // } // this._idleStart = undefined; // this.info(`Suspending server`); // this._clientOptions.suspend.callback().then((approved) => { // if (!approved) { // this._idleStart = undefined; // return; // } // return this.suspend().then(() => { // this.info(`Server got suspended`); // }); // }, (error) => { // this.error(`Suspending server failed`, error, 'force'); // }); // } else { // this._idleStart = undefined; // } // } // private isIdle(): boolean { // const suspendMode = this._clientOptions.suspend.mode; // if (suspendMode === SuspendMode.off) { // return false; // } // for (const feature of this._features) { // const state = feature.getState(); // // 'static' feature don't depend on registrations. So they // // can't block suspend // if (state.kind === 'static') { // continue; // } // // The feature has no registrations. So no blocking of the // // suspend. // if (!state.registrations) { // continue; // } // if (state.kind === 'document' && state.matches === true) { // return false; // } // } // return true; // } } interface Connection { /** * A timestamp indicating when the connection was last used (.e.g a request * or notification has been sent) */ lastUsed: number; resetLastUsed(): void; listen(): void; sendRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, token?: CancellationToken): Promise<R>; sendRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, params: P, token?: CancellationToken): Promise<R>; sendRequest<R, E>(type: RequestType0<R, E>, token?: CancellationToken): Promise<R>; sendRequest<P, R, E>(type: RequestType<P, R, E>, params: P, token?: CancellationToken): Promise<R>; sendRequest<R>(method: string, token?: CancellationToken): Promise<R>; sendRequest<R>(method: string, param: any, token?: CancellationToken): Promise<R>; sendRequest<R>(type: string | MessageSignature, ...params: any[]): Promise<R>; onRequest<R, PR, E, RO>(type: ProtocolRequestType0<R, PR, E, RO>, handler: RequestHandler0<R, E>): Disposable; onRequest<P, R, PR, E, RO>(type: ProtocolRequestType<P, R, PR, E, RO>, handler: RequestHandler<P, R, E>): Disposable; onRequest<R, E>(type: RequestType0<R, E>, handler: RequestHandler0<R, E>): Disposable; onRequest<P, R, E>(type: RequestType<P, R, E>, handler: RequestHandler<P, R, E>): Disposable; onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): Disposable; onRequest<R, E>(method: string | MessageSignature, handler: GenericRequestHandler<R, E>): Disposable; hasPendingResponse(): boolean; sendNotification<RO>(type: ProtocolNotificationType0<RO>): Promise<void>; sendNotification<P, RO>(type: ProtocolNotificationType<P, RO>, params?: P): Promise<void>; sendNotification(type: NotificationType0): Promise<void>; sendNotification<P>(type: NotificationType<P>, params?: P): Promise<void>; sendNotification(method: string): Promise<void>; sendNotification(method: string, params: any): Promise<void>; sendNotification(method: string | MessageSignature, params?: any): Promise<void>; onNotification<RO>(type: ProtocolNotificationType0<RO>, handler: NotificationHandler0): Disposable; onNotification<P, RO>(type: ProtocolNotificationType<P, RO>, handler: NotificationHandler<P>): Disposable; onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable; onNotification<P>(type: NotificationType<P>, handler: NotificationHandler<P>): Disposable; onNotification(method: string, handler: GenericNotificationHandler): Disposable; onNotification(method: string | MessageSignature, handler: GenericNotificationHandler): Disposable; onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable; sendProgress<P>(type: ProgressType<P>, token: string | number, value: P): Promise<void>; trace(value: Trace, tracer: Tracer, sendNotification?: boolean): Promise<void>; trace(value: Trace, tracer: Tracer, traceOptions?: TraceOptions): Promise<void>; initialize(params: InitializeParams): Promise<InitializeResult>; shutdown(): Promise<void>; exit(): Promise<void>; end(): void; dispose(): void; } class ConsoleLogger implements Logger { public error(message: string): void { RAL().console.error(message); } public warn(message: string): void { RAL().console.warn(message); } public info(message: string): void { RAL().console.info(message); } public log(message: string): void { RAL().console.log(message); } } interface ConnectionErrorHandler { (error: Error, message: Message | undefined, count: number | undefined): void; } interface ConnectionCloseHandler { (): void; } function createConnection(input: MessageReader, output: MessageWriter, errorHandler: ConnectionErrorHandler, closeHandler: ConnectionCloseHandler, options?: ConnectionOptions): Connection { let _lastUsed: number = -1; const logger = new ConsoleLogger(); const connection = createProtocolConnection(input, output, logger, options); connection.onError((data) => { errorHandler(data[0], data[1], data[2]); }); connection.onClose(closeHandler); const result: Connection = { get lastUsed(): number { return _lastUsed; }, resetLastUsed: (): void => { _lastUsed = -1; }, listen: (): void => connection.listen(), sendRequest: <R>(type: string | MessageSignature, ...params: any[]): Promise<R> => { _lastUsed = Date.now(); return connection.sendRequest(type as string, ...params); }, onRequest: <R, E>(type: string | MessageSignature, handler: GenericRequestHandler<R, E>): Disposable => connection.onRequest(type, handler), hasPendingResponse: (): boolean => connection.hasPendingResponse(), sendNotification: (type: string | MessageSignature, params?: any): Promise<void> => { _lastUsed = Date.now(); return connection.sendNotification(type, params); }, onNotification: (type: string | MessageSignature, handler: GenericNotificationHandler): Disposable => connection.onNotification(type, handler), onProgress: connection.onProgress, sendProgress: connection.sendProgress, trace: (value: Trace, tracer: Tracer, sendNotificationOrTraceOptions?: boolean | TraceOptions): Promise<void> => { const defaultTraceOptions: TraceOptions = { sendNotification: false, traceFormat: TraceFormat.Text }; if (sendNotificationOrTraceOptions === undefined) { return connection.trace(value, tracer, defaultTraceOptions); } else if (Is.boolean(sendNotificationOrTraceOptions)) { return connection.trace(value, tracer, sendNotificationOrTraceOptions); } else { return connection.trace(value, tracer, sendNotificationOrTraceOptions); } }, initialize: (params: InitializeParams) => { _lastUsed = Date.now(); return connection.sendRequest(InitializeRequest.type, params); }, shutdown: () => { _lastUsed = Date.now(); return connection.sendRequest(ShutdownRequest.type, undefined); }, exit: () => { _lastUsed = Date.now(); return connection.sendNotification(ExitNotification.type); }, end: () => connection.end(), dispose: () => connection.dispose() }; return result; } // Exporting proposed protocol. export namespace ProposedFeatures { export function createAll(_client: FeatureClient<Middleware, LanguageClientOptions>): (StaticFeature | DynamicFeature<any>)[] { let result: (StaticFeature | DynamicFeature<any>)[] = [ ]; return result; } }
the_stack
import { Store } from 'storage/store'; import { IdbBackend, MemoryBackend } from 'storage/backends'; import { Hash, HashedObject, HashedSet, HashReference, MutationOp } from 'data/model'; import { SomethingHashed, createHashedObjects } from '../data/types/SomethingHashed'; import { SomethingMutable, SomeMutation } from '../data//types/SomethingMutable'; import { describeProxy } from 'config'; import { HistoryFragment } from 'data/history/HistoryFragment'; import { OpHeader } from 'data/history/OpHeader'; import { SQLiteBackend } from '@hyper-hyper-space/sqlite'; describeProxy('[STR] Storage', () => { test('[STR01] Indexeddb-based load / store cycle', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testLoadStoreCycle(store); store.close(); }); test('[STR02] Memory-based load / store cycle', async() => { let store = new Store(new MemoryBackend('test-storage-backend')); await testLoadStoreCycle(store); store.close(); }); test('[STR03] SQLite-based load / store cycle', async() => { let store = new Store(new SQLiteBackend(':memory:')); await testLoadStoreCycle(store); store.close(); }); test('[STR04] Indexeddb-based reference-based load hit', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testReferenceBasedLoadHit(store); store.close(); }); test('[STR05] Memory-based reference-based load hit', async () => { let store = new Store(new MemoryBackend('test-storage-backend')); await testReferenceBasedLoadHit(store); store.close(); }); test('[STR06] SQLite-based reference-based load hit', async () => { let store = new Store(new SQLiteBackend(':memory:')); await testReferenceBasedLoadHit(store); store.close(); }); test('[STR07] Indexeddb-based reference-based load miss', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testReferenceBasedLoadMiss(store); store.close(); }); test('[STR08] Memory-based reference-based load miss', async () => { let store = new Store(new MemoryBackend('test-storage-backend')); await testReferenceBasedLoadMiss(store); store.close(); }); test('[STR09] SQLite-based reference-based load miss', async () => { let store = new Store(new SQLiteBackend(':memory:')); await testReferenceBasedLoadMiss(store); store.close(); }); test('[STR07] Indexeddb-based mutation op saving and loading', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testMutationOps(store); store.close(); }); test('[STR08] Memory-based mutation op saving and loading', async () => { let store = new Store(new MemoryBackend('test-storage-backend')); await testMutationOps(store); store.close(); }); test('[STR09] SQLite-based mutation op saving and loading', async () => { let store = new Store(new SQLiteBackend(':memory:')); await testMutationOps(store); store.close(); }); test('[STR10] Indexeddb-based mutation op saving and auto-loading', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testMutationOpAutoLoad(store); store.close(); }); test('[STR11] Memory-based mutation op saving and auto-loading', async () => { let store = new Store(new MemoryBackend('test-storage-backend')); await testMutationOpAutoLoad(store); store.close(); }); test('[STR12] SQLite-based mutation op saving and auto-loading', async () => { let store = new Store(new SQLiteBackend(':memory:')); await testMutationOpAutoLoad(store); store.close(); }); test('[STR13] Indexeddb-based mutation op automatic prevOp generation', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testPrevOpGeneration(store); store.close(); }); test('[STR14] Memory-based mutation op automatic prevOp generation', async () => { let store = new Store(new MemoryBackend('test-storage-backend')); await testPrevOpGeneration(store); store.close(); }); test('[STR15] SQLite-based mutation op automatic prevOp generation', async () => { let store = new Store(new SQLiteBackend(':memory:')); await testPrevOpGeneration(store); store.close(); }); test('[STR16] Validate history retrieved from IDB store', async () => { let store = new Store(new IdbBackend('test-storage-backend')); await testHistoryGeneration(store); store.close(); }); test('[STR17] Validate history retrieved from memory store', async () => { let store = new Store(new MemoryBackend('test-storage-backend')); await testHistoryGeneration(store); store.close(); }); test('[STR18] Validate history retrieved from SQLite store', async () => { let store = new Store(new SQLiteBackend(':memory:')); await testHistoryGeneration(store); store.close(); }); }); async function testLoadStoreCycle(store: Store) { let objects = createHashedObjects(); let a: SomethingHashed = objects.a; let b: SomethingHashed = objects.b; await store.save(a); let a2 = await store.load(a.hash()) as HashedObject; expect(a.equals(a2 as HashedObject)).toBeTruthy(); let hashedThings = await store.loadByClass(SomethingHashed.className); expect(hashedThings.objects[0].hash()).toEqual(b.hash()); expect(hashedThings.objects[1].hash()).toEqual(a.hash()); } async function testReferenceBasedLoadHit(store: Store) { let objects = createHashedObjects(); let a: SomethingHashed = objects.a; let b: SomethingHashed = objects.b; await store.save(a); let result = await store.loadByReferencingClass(SomethingHashed.className, 'reference', b.hash()); let a2 = result.objects[0]; expect(a.equals(a2 as HashedObject)).toBeTruthy(); let hashedThings = await store.loadByClass(SomethingHashed.className); expect(hashedThings.objects[0].hash()).toEqual(b.hash()); expect(hashedThings.objects[1].hash()).toEqual(a.hash()); } async function testReferenceBasedLoadMiss(store: Store) { let objects = createHashedObjects(); let a: SomethingHashed = objects.a; let b: SomethingHashed = objects.b; await store.save(a); let result = await store.loadByReferencingClass(SomethingHashed.className, 'non-existent-path', b.hash()); expect(result.objects.length).toEqual(0); } async function testMutationOps(store: Store) { let sm = new SomethingMutable(); await sm.testOperation('hello'); await sm.testOperation('world'); await sm.testOperation('!'); await store.save(sm); let hash = sm.getLastHash(); let sm2 = await store.load(hash) as SomethingMutable; await sm2.loadAllChanges(); let hs = new HashedSet(sm._operations.keys()); let hs2 = new HashedSet(sm2._operations.keys()); let h = hs.toArrays().hashes; let h2 = hs2.toArrays().hashes; expect(h.length).toEqual(h2.length); for (let i=0; i<h.length; i++) { expect(h[i]).toEqual(h2[i]); } } async function testMutationOpAutoLoad(store: Store) { let sm = new SomethingMutable(); await store.save(sm); let hash = sm.getLastHash(); let sm2 = await store.load(hash) as SomethingMutable; sm2.watchForChanges(true); await sm.testOperation('hello'); await sm.testOperation('world'); await sm.testOperation('!'); await store.save(sm); let hs = new HashedSet(sm._operations.keys()); let hs2 = new HashedSet(sm2._operations.keys()); let h = hs.toArrays().hashes; let h2 = hs2.toArrays().hashes; let checks = 0; while(h.length !== h2.length && checks < 20) { await new Promise(r => setTimeout(r, 100)); checks = checks + 1; hs = new HashedSet(sm._operations.keys()); hs2 = new HashedSet(sm2._operations.keys()); h = hs.toArrays().hashes; h2 = hs2.toArrays().hashes; } expect(h2.length).toEqual(h.length); for (let i=0; i<h.length; i++) { expect(h[i]).toEqual(h2[i]); } } async function testPrevOpGeneration(store: Store) { let sm = new SomethingMutable(); await store.save(sm); await sm.testOperation('hello'); let hash = sm.getLastHash(); let sm2 = await store.load(hash) as SomethingMutable; await sm2.testOperation('another'); await store.save(sm2); await sm.loadAllChanges(); // 2021.6.16: Added after removing peeking from store for // prevOp generation. await sm.testOperation('world'); await sm.testOperation('!'); await store.save(sm); let sm3 = await store.load(hash) as SomethingMutable; await sm3.loadAllChanges(); let world: SomeMutation|undefined = undefined; for (const op of sm3._operations.values()) { const mut = op as SomeMutation; if (mut.payload === 'world') { world = mut; } } expect(world !== undefined).toBeTruthy(); if (world !== undefined) { expect(world.prevOps?.toArrays().elements.length === 2).toBeTruthy(); let another = false; let hello = false; for (const opRef of (world.prevOps as HashedSet<HashReference<MutationOp>>).toArrays().elements) { let op = sm3._operations.get(opRef.hash); another = another || op?.payload === 'another'; hello = hello || op?.payload === 'hello'; } expect(another).toBeTruthy(); expect(hello).toBeTruthy(); } } async function testHistoryGeneration(store: Store) { let sm = new SomethingMutable(); await store.save(sm); await sm.testOperation('hello'); await sm.testOperation('world'); await sm.saveQueuedOps(); let hash = sm.getLastHash(); let sm2 = await store.load(hash) as SomethingMutable; await sm2.loadAllChanges(); await sm2.testOperation('!!'); await sm.testOperation('!'); await sm2.saveQueuedOps(); await sm.saveQueuedOps(); await sm.loadAllChanges(); let hello: SomeMutation|undefined = undefined; let world: SomeMutation|undefined = undefined; let bang: SomeMutation|undefined = undefined; let bangbang: SomeMutation|undefined = undefined; for (const op of sm._operations.values()) { const mut = op as SomeMutation; if (mut.payload === 'hello') { hello = mut; //console.log('hello: ' + hello.hash()); } if (mut.payload === 'world') { world = mut; //console.log('world: ' + world.hash()); } if (mut.payload === '!') { bang = mut; //console.log('!: ' + bang.hash()); } if (mut.payload === '!!') { bangbang = mut; //console.log('!!: ' + bangbang.hash()); } } let frag = new HistoryFragment(sm.getLastHash()); const bangHistory = await store.loadOpHeader(bang?.hash() as Hash) as OpHeader; const bangbangHistory = await store.loadOpHeader(bangbang?.hash() as Hash) as OpHeader; const worldHistory = await store.loadOpHeader(world?.hash() as Hash) as OpHeader; const helloHistory = await store.loadOpHeader(hello?.hash() as Hash) as OpHeader const bangHistoryByHash = await store.loadOpHeaderByHeaderHash(bangHistory.headerHash); expect(bangHistoryByHash?.headerHash).toEqual(bangHistory.headerHash); expect(bangHistoryByHash?.opHash).toEqual(bangHistory.opHash); expect(bangHistory.computedProps?.height).toEqual(3); expect(bangHistory.computedProps?.size).toEqual(3); frag.add(bangHistory); expect(frag.missingPrevOpHeaders.size).toEqual(1); expect(frag.missingPrevOpHeaders.has(worldHistory?.hash() as Hash)).toBeTruthy(); expect(frag.terminalOpHeaders.size).toEqual(1); expect(frag.getTerminalOps().has(bang?.hash() as Hash)); expect(bangbangHistory.computedProps?.height).toEqual(3); expect(bangbangHistory.computedProps?.size).toEqual(3); frag.add(bangbangHistory); expect(frag.missingPrevOpHeaders.size).toEqual(1); expect(frag.missingPrevOpHeaders.has(worldHistory?.hash() as Hash)).toBeTruthy(); expect(frag.terminalOpHeaders.size).toEqual(2); expect(frag.getTerminalOps().has(bang?.hash() as Hash)); expect(frag.getTerminalOps().has(bangbang?.hash() as Hash)); expect(worldHistory.computedProps?.height).toEqual(2); expect(worldHistory.computedProps?.size).toEqual(2); frag.add(worldHistory); expect(frag.missingPrevOpHeaders.size).toEqual(1); expect(frag.missingPrevOpHeaders.has(helloHistory?.hash() as Hash)).toBeTruthy(); expect(frag.terminalOpHeaders.size).toEqual(2); expect(frag.getTerminalOps().has(bang?.hash() as Hash)); expect(frag.getTerminalOps().has(bangbang?.hash() as Hash)); expect(helloHistory.computedProps?.height).toEqual(1); expect(helloHistory.computedProps?.size).toEqual(1); frag.add(helloHistory); expect(frag.terminalOpHeaders.size).toEqual(2); expect(frag.missingPrevOpHeaders.size).toEqual(0); //expect(frag.checkAndComputeProps(new Map())).toBeTruthy(); }
the_stack
import parserCore = require("./parser/wrapped-ast/parserCoreApi") import apiLoader = require("./parser/apiLoader") export import jsonTypings = require("./typings-new-format/raml"); var PromiseConstructor = require('promise-polyfill'); /** * RAML 1.0 top-level AST interfaces. */ export import api10 = require("./parser/artifacts/raml10parserapi") /** * RAML 0.8 top-level AST interfaces. */ export import api08 = require("./parser/artifacts/raml08parserapi") /** * Load RAML asynchronously. May load both Api and Typed fragments. The Promise is rejected with [[ApiLoadingError]] if the result contains errors and the 'rejectOnErrors' option is set to 'true'. * @param ramlPathOrContent Path to RAML: local file system path or Web URL; or RAML file content. * @param options Load options * @return Object representation of the specification wrapped into a Promise. **/ export function load(ramlPathOrContent:string,options?:parserCore.LoadOptions):Promise<jsonTypings.RAMLParseResult>{ return apiLoader.load(ramlPathOrContent,options); } /** * Load RAML synchronously. May load both Api and Typed fragments. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for RAML which contains errors. * @param ramlPathOrContent Path to RAML: local file system path or Web URL; or RAML file content. * @param options Load options * @return Object representation of the specification. **/ export function loadSync(ramlPathOrContent:string,options?:parserCore.LoadOptions):jsonTypings.RAMLParseResult{ return apiLoader.loadSync(ramlPathOrContent,options); } /** * Load RAML asynchronously. May load both Api and Typed fragments. The Promise is rejected with [[ApiLoadingError]] if the result contains errors and the 'rejectOnErrors' option is set to 'true'. * @param ramlPathOrContent Path to RAML: local file system path or Web URL; or RAML file content. * @param options Load options * @return High level AST root wrapped into a Promise. **/ export function parse(ramlPathOrContent:string,options?:parserCore.LoadOptions):Promise<hl.IHighLevelNode>{ return apiLoader.parse(ramlPathOrContent,options); } /** * Load RAML synchronously. May load both Api and Typed fragments. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for RAML which contains errors. * @param ramlPathOrContent Path to RAML: local file system path or Web URL; or RAML file content. * @param options Load options * @return High level AST root. **/ export function parseSync(ramlPathOrContent:string,options?:parserCore.LoadOptions):hl.IHighLevelNode{ return apiLoader.parseSync(ramlPathOrContent,options); } /** * Load API synchronously. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for Api which contains errors. * @param apiPath Path to API: local file system path or Web URL * @param options Load options * @return Api instance. **/ export function loadApiSync(apiPath:string, options?:parserCore.Options):api10.Api|api08.Api; /** * Load API synchronously. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for Api which contains errors. * @param apiPath Path to API: local file system path or Web URL * @param options Load options * @param extensionsAndOverlays Paths to extensions and overlays to be applied listed in the order of application. Relevant for RAML 1.0 only. * @return Api instance. **/ export function loadApiSync(apiPath:string, extensionsAndOverlays:string[], options?:parserCore.Options):api10.Api|api08.Api; export function loadApiSync(apiPath:string, arg1?:string[]|parserCore.Options, arg2?:parserCore.Options):api10.Api|api08.Api{ return <api10.Api|api08.Api>apiLoader.loadApi(apiPath,arg1,arg2).getOrElse(null); } /** * Load RAML synchronously. May load both Api and Typed fragments. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for RAML which contains errors. * @param ramlPath Path to RAML: local file system path or Web URL * @param options Load options * @param extensionsAndOverlays Paths to extensions and overlays to be applied listed in the order of application. Relevant for RAML 1.0 only. * @return RAMLLanguageElement instance. **/ export function loadRAMLSync(ramlPath:string, extensionsAndOverlays:string[], options?:parserCore.Options):hl.BasicNode export function loadRAMLSync(ramlPath:string, arg1?:string[]|parserCore.Options, arg2?:parserCore.Options):hl.BasicNode{ return <any>apiLoader.loadApi(ramlPath,arg1,arg2).getOrElse(null); } /** * Load RAML synchronously. May load both Api and Typed fragments. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for RAML which contains errors. * @param content content of the raml * @param options Load options (note you should path a resolvers if you want includes to be resolved) * @return RAMLLanguageElement instance. **/ export function parseRAMLSync(content:string, arg2?:parserCore.Options):hl.BasicNode{ let filePath = apiLoader.virtualFilePath(arg2); let optionsForContent = apiLoader.optionsForContent(content,arg2, filePath); return <any>apiLoader.loadApi(filePath,[],optionsForContent).getOrElse(null); } /** * Load RAML asynchronously. May load both Api and Typed fragments. If the 'rejectOnErrors' option is set to true, [[ApiLoadingError]] is thrown for RAML which contains errors. * @param content content of the raml * @param options Load options (note you should path a resolvers if you want includes to be resolved) * @return RAMLLanguageElement instance. **/ export function parseRAML(content:string, arg2?:parserCore.Options):Promise<hl.BasicNode>{ let filePath = apiLoader.virtualFilePath(arg2); let optionsForContent = apiLoader.optionsForContent(content,arg2, filePath); return <any>apiLoader.loadApiAsync(filePath,[],optionsForContent); } /** * Load API asynchronously. The Promise is rejected with [[ApiLoadingError]] if the resulting Api contains errors and the 'rejectOnErrors' option is set to 'true'. * @param apiPath Path to API: local file system path or Web URL * @param options Load options * @return Promise&lt;Api&gt;. **/ export function loadApi(apiPath:string, options?:parserCore.Options):Promise<api10.Api|api08.Api>; /** * Load API asynchronously. The Promise is rejected with [[ApiLoadingError]] if the resulting Api contains errors and the 'rejectOnErrors' option is set to 'true'. * @param apiPath Path to API: local file system path or Web URL * @param options Load options * @param extensionsAndOverlays Paths to extensions and overlays to be applied listed in the order of application. Relevant for RAML 1.0 only. * @return Promise&lt;Api&gt;. **/ export function loadApi(apiPath:string,extensionsAndOverlays:string[], options?:parserCore.Options):Promise<api10.Api|api08.Api>; export function loadApi(apiPath:string, arg1?:string[]|parserCore.Options, arg2?:parserCore.Options):Promise<api10.Api|api08.Api>{ return apiLoader.loadApiAsync(apiPath,arg1,arg2); } /** * Load RAML asynchronously. May load both Api and Typed fragments. The Promise is rejected with [[ApiLoadingError]] if the resulting RAMLLanguageElement contains errors and the 'rejectOnErrors' option is set to 'true'. * @param ramlPath Path to RAML: local file system path or Web URL * @param options Load options * @param extensionsAndOverlays Paths to extensions and overlays to be applied listed in the order of application. Relevant for RAML 1.0 only. * @return Promise&lt;RAMLLanguageElement&gt;. **/ export function loadRAML(ramlPath:string,extensionsAndOverlays:string[], options?:parserCore.Options):Promise<hl.BasicNode>; export function loadRAML(ramlPath:string, arg1?:string[]|parserCore.Options, arg2?:parserCore.Options):Promise<hl.BasicNode>{ return apiLoader.loadRAMLAsync(ramlPath,arg1,arg2); } /** * Gets AST node by runtime type, if runtime type matches any. * @param runtimeType - runtime type to find the match for */ export function getLanguageElementByRuntimeType(runtimeType : hl.ITypeDefinition) : parserCore.BasicNode { return apiLoader.getLanguageElementByRuntimeType(runtimeType); } /** * Check if the AST node represents fragment */ export function isFragment(node:api10.Api|api10.Library|api10.Overlay|api10.Extension|api10.Trait|api10.TypeDeclaration|api10.ResourceType|api10.DocumentationItem):boolean{ return api10.isFragment(<any>node); } /** * Convert fragment representing node to FragmentDeclaration instance. */ export function asFragment(node:api10.Api|api10.Library|api10.Overlay|api10.Extension|api10.Trait|api10.TypeDeclaration|api10.ResourceType|api10.DocumentationItem):api10.FragmentDeclaration{ return api10.asFragment(<any>node); } /** * High-level AST interfaces. */ export import hl=require("./parser/highLevelAST") /** * Low-level AST interfaces. */ export import ll=require("./parser/lowLevelAST") /** * Search functionality, operates on high AST level. */ export import search=require("./search/search-interface") /** * High-level stub node factory methods. */ export import stubs=require("./stubProxy") export import utils=require("./utils") /** * Low-level project factory. */ export import project=require("./project") /** * Helpers for classification of high-level AST entity types. */ export import universeHelpers=require("./parser/tools/universeHelpers") /** * Definition system. */ export import ds=require("raml-definition-system") /** * Schema utilities. */ export import schema=require("./schema"); /** * A set of constants describing definition system entities. * @hidden **/ export var universes=ds.universesInfo /** * Exposed parser model modification methods. Operate on high-level. */ export import parser = require("./parser") /** * Applies traits and resources types to API on high-level. * Top-level expansion should be performed via calling expand() method of API node. */ export import expander=require("./expanderStub") /** * Exposed part of custom methods applied to top-level AST during generation. * Not to be used by parser clients. */ export import wrapperHelper=require("./wrapperHelperStub") /** * Abstract high-level node potentially having children. * @hidden **/ export type IHighLevelNode=hl.IHighLevelNode; /** * Abstract high-level node property. * @hidden */ export type IProperty=hl.IProperty; /** * The root of high-level node interface hierarchy. * @hidden **/ export type IParseResult=hl.IParseResult; if(typeof Promise === 'undefined' && typeof window !== 'undefined') { (<any>window).Promise = PromiseConstructor; }
the_stack
import {isReportFunnelEnabled} from '@/feature-switch'; import {ConnectedSpace} from '@/services/data/tuples/connected-space-types'; import {Dashboard} from '@/services/data/tuples/dashboard-types'; import {fetchEnum} from '@/services/data/tuples/enum'; import {Enum} from '@/services/data/tuples/enum-types'; import {Report} from '@/services/data/tuples/report-types'; import {Topic} from '@/services/data/tuples/topic-types'; import {ICON_BAN, ICON_DRAG_HANDLE, ICON_FILTER} from '@/widgets/basic/constants'; import {useEventBus} from '@/widgets/events/event-bus'; import {EventTypes} from '@/widgets/events/types'; import {Lang} from '@/widgets/langs'; import {useDragAndResize} from '@/widgets/report/drag-and-resize/use-drag-and-resize'; import {DragType} from '@/widgets/report/types'; import {ChartDragHandle, ChartDragHandlePart} from '@/widgets/report/widgets'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import React, {useEffect, useRef, useState} from 'react'; import {v4} from 'uuid'; import {useDashboardEventBus} from '../../dashboard-event-bus'; import {DashboardEventTypes} from '../../dashboard-event-bus-types'; import {FunnelEditorWrapper} from './funnel-editor'; import {FunnelDefs, FunnelsState, GroupedFunnel} from './types'; import { buildFunnelDefsFromDashboard, fetchTopics, fillFunnelDefsByEnumIds, gatherTopicIds, groupFunnels } from './utils'; import { DashboardReportsFunnelEditors, DashboardReportsFunnels, DashboardReportsFunnelsButton, DashboardReportsFunnelsHeader, DashboardReportsFunnelsTitle, ReportsFunnelsRect } from './widgets'; export const ReportsFunnels = (props: { connectedSpaces: Array<ConnectedSpace>; dashboard: Dashboard; reports: Array<Report>; transient: boolean; }) => { const {connectedSpaces, dashboard, reports, transient} = props; const containerRef = useRef<HTMLDivElement>(null); const dndRef = useRef<HTMLDivElement>(null); const {fire: fireGlobal} = useEventBus(); const {on, off, fire} = useDashboardEventBus(); const [effective, setEffective] = useState(true); const [rect, setRect] = useState<ReportsFunnelsRect>({x: 16, y: 16, width: 0, height: 0}); const [state, setState] = useState<FunnelsState>({ initialized: false, topics: [], enums: [], defs: {}, groups: [] }); // initialize useEffect(() => { if (state.initialized || connectedSpaces.length === 0 || reports.length === 0) { return; } // don't use console since dashboard can be shared and whole data is unnecessary const defs = buildFunnelDefsFromDashboard(connectedSpaces); fireGlobal(EventTypes.INVOKE_REMOTE_REQUEST, async () => { const topics = await fetchTopics(gatherTopicIds(defs)); const {defs: completedDefs, enumIds} = fillFunnelDefsByEnumIds(defs, topics); if (enumIds.length !== 0) { const enums = await Promise.all(enumIds.map(async enumId => await fetchEnum(enumId))); return {topics, defs: completedDefs, enums}; } else { return {topics, defs: completedDefs, enums: []}; } }, ({topics, enums, defs}: { topics: Array<Topic>; enums: Array<Enum>; defs: FunnelDefs }) => { setState({ topics, enums, defs, groups: groupFunnels(reports, defs), initialized: true }); }); }, [fireGlobal, state.initialized, connectedSpaces, reports]); useEffect(() => { const save = (before: () => void) => { before(); fire(DashboardEventTypes.SAVE_DASHBOARD, dashboard); }; const onReportAdded = (report: Report) => { // eslint-disable-next-line const dashboardReport = (dashboard.reports || []).find(r => r.reportId == report.reportId); if (!dashboardReport) { return; } // construct cloned report, add into reports const displayReport = { ...(JSON.parse(JSON.stringify(report))), rect: dashboardReport.rect }; reports.push(displayReport); save(() => { if (!report.funnels || report.funnels.length === 0 || report.funnels.every(funnel => !funnel.enabled)) { // do nothing, since added report has not funnels defined // repaint fire(DashboardEventTypes.REPAINT_REPORTS_ON_ADDED, dashboard); } else { // eslint-disable-next-line const defs = buildFunnelDefsFromDashboard(connectedSpaces); fireGlobal(EventTypes.INVOKE_REMOTE_REQUEST, async () => { // find new topic ids const topicIds = gatherTopicIds(defs).filter(topicId => { // eslint-disable-next-line return state.topics.every(topic => topic.topicId != topicId); }); // load new topic const topics = topicIds.length === 0 ? state.topics : [...state.topics, ...await fetchTopics(topicIds)]; // rebuild funnel defs const {defs: completedDefs, enumIds: allEnumIds} = fillFunnelDefsByEnumIds(defs, topics); // find new enum ids const enumIds = allEnumIds.filter(enumId => { // eslint-disable-next-line return state.enums.every(e => e.enumId != enumId); }); if (enumIds.length !== 0) { // load new enums const enums = await Promise.all(enumIds.map(async enumId => await fetchEnum(enumId))); return {topics, defs: completedDefs, enums: [...state.enums, ...enums]}; } else { return {topics, defs: completedDefs, enums: state.enums}; } }, ({topics, enums, defs}: { topics: Array<Topic>; enums: Array<Enum>; defs: FunnelDefs }) => { setState({ topics, enums, defs, groups: groupFunnels([displayReport], defs, state.groups), initialized: true }); fire(DashboardEventTypes.REPAINT_REPORTS_ON_ADDED, dashboard); }); } }); }; const onReportRemoved = (report: Report) => { save(() => { // remove cloned report when report is removed from dashboard // eslint-disable-next-line const index = reports.findIndex(r => r.reportId == report.reportId); if (index !== -1) { reports.splice(index, 1); // rebuild grouped funnels const groups = state.groups.filter(group => { // remove report from group // eslint-disable-next-line group.reports = group.reports.filter(({report: r}) => r.reportId != report.reportId); return group.reports.length !== 0; }); // one or more groups are removed since report removed if (groups.length !== state.groups.length) { setState(state => { return {...state, groups}; }); } } fire(DashboardEventTypes.REPAINT_REPORTS_ON_REMOVED, dashboard); }); }; on(DashboardEventTypes.REPORT_ADDED, onReportAdded); on(DashboardEventTypes.REPORT_REMOVED, onReportRemoved); return () => { off(DashboardEventTypes.REPORT_ADDED, onReportAdded); off(DashboardEventTypes.REPORT_REMOVED, onReportRemoved); }; }, [ fireGlobal, on, off, fire, connectedSpaces, dashboard, reports, state.topics, state.enums, state.groups ]); const {onMouseUp, onMouseLeave, onMouseDown, onMouseMove, dragState} = useDragAndResize({ containerRef, dndRef, writeToRect: (rect) => setRect(rect), onDrop: () => (void 0) }); if (!isReportFunnelEnabled() || !state.initialized || state.groups.length === 0) { return null; } const copyFunnelValues = (group: GroupedFunnel) => { group.reports.forEach(({report, funnel}) => { // copy values from grouped funnel (values collected from ui input) to original funnel funnel.values = group.funnel.values; // since report is built by parent, is a memory object // find dashboard report as copy funnels to it // eslint-disable-next-line const dashboardReport = (dashboard.reports ?? []).find(r => r.reportId == report.reportId); if (dashboardReport) { // copy funnels data to original report object, which will be persisted dashboardReport.funnels = report.funnels; } }); }; // synchronize values from grouped funnel to funnel in report object const onFunnelChanged = async (group: GroupedFunnel) => { copyFunnelValues(group); fire(DashboardEventTypes.REPAINT_REPORTS, dashboard, group.reports.map(r => r.report)); if (!transient) { // in transient, funnel values change will not save to server side fire(DashboardEventTypes.SAVE_DASHBOARD, dashboard); } }; const onFilterClicked = () => { setEffective(!effective); // console.log(JSON.stringify(state.groups.map(group => group.funnel).flat())); if (effective) { // original is effective, now remove all funnel's values, repaint related reports const reports = state.groups.map(group => group.reports) .flat() .map(r => r.report) .reduce((reports, report) => { if (!reports.includes(report)) { reports.push(report); } return reports; }, [] as Array<Report>) // find report with funnels .filter(report => report.funnels != null && report.funnels.length !== 0) // find report with funnel values .filter(report => { return (report.funnels || []).some(funnel => { return funnel.enabled && funnel.values != null && funnel.values.length !== 0 && funnel.values.some(value => value != null && value !== ''); }); }) .map(report => { // clear funnel values // will keep values from group funnel (report.funnels || []).forEach(funnel => { if (funnel.range) { funnel.values = [null, null]; } else { funnel.values = [null]; } }); return report; }); fire(DashboardEventTypes.REPAINT_REPORTS, dashboard, reports); console.log(JSON.stringify(reports.map(report => report.funnels).flat())); } else { // original is not effective, now copy values to report funnels, and repaint reports const reports = state.groups .filter(({funnel}) => { return funnel.values != null && funnel.values.length !== 0 && funnel.values.some(value => value != null && value !== ''); }) .map(group => { copyFunnelValues(group); return group; }) .map(group => group.reports) .flat() .map(r => r.report) .reduce((reports, report) => { if (!reports.includes(report)) { reports.push(report); } return reports; }, [] as Array<Report>); fire(DashboardEventTypes.REPAINT_REPORTS, dashboard, reports); console.log(JSON.stringify(reports.map(report => report.funnels).flat())); } // console.log(JSON.stringify(state.groups.map(group => group.funnel).flat())); }; return <DashboardReportsFunnels rect={rect} ref={containerRef}> <DashboardReportsFunnelsHeader> <DashboardReportsFunnelsTitle>{Lang.CONSOLE.DASHBOARD.FUNNEL_TITLE}</DashboardReportsFunnelsTitle> <DashboardReportsFunnelsButton onClick={onFilterClicked}> {effective ? <FontAwesomeIcon icon={ICON_FILTER}/> : <span className="fa-layers fa-fw"> <FontAwesomeIcon icon={ICON_BAN}/> <FontAwesomeIcon icon={ICON_FILTER}/> </span>} </DashboardReportsFunnelsButton> </DashboardReportsFunnelsHeader> <DashboardReportsFunnelEditors> {state.groups.map(group => { return <FunnelEditorWrapper group={group} enums={state.enums} onChange={onFunnelChanged} key={v4()}/>; })} </DashboardReportsFunnelEditors> <ChartDragHandle onMouseDown={onMouseDown} onMouseUp={onMouseUp} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} dragging={dragState.type !== DragType.NONE}> <ChartDragHandlePart data-part-type="dragging" data-position={dragState.type}/> <ChartDragHandlePart data-position={DragType.DND} ref={dndRef}> <FontAwesomeIcon icon={ICON_DRAG_HANDLE}/> </ChartDragHandlePart> </ChartDragHandle> </DashboardReportsFunnels>; };
the_stack
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import 'chrome://resources/cr_elements/cr_icons_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import '../icons.js'; import '../settings_shared_css.js'; import '../settings_vars_css.js'; import './passwords_shared_css.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {MultiStorePasswordUiEntry} from './multi_store_password_ui_entry.js'; import {PasswordManagerImpl} from './password_manager_proxy.js'; interface PasswordEditDialogElement { $: { dialog: CrDialogElement, passwordInput: CrInputElement, storePicker: HTMLSelectElement, usernameInput: CrInputElement, websiteInput: CrInputElement, }; } const PasswordEditDialogElementBase = I18nMixin(PolymerElement); /** * Contains the possible modes for 'password-edit-dialog'. * VIEW: entry is an existing federation credential * EDIT: entry is an existing password * ADD: no existing entry */ enum PasswordDialogMode { VIEW = 'view', EDIT = 'edit', ADD = 'add', } /* TODO(crbug.com/1255127): Revisit usage for 3 different modes. */ class PasswordEditDialogElement extends PasswordEditDialogElementBase { static get is() { return 'password-edit-dialog'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * Has value for dialog in VIEW and EDIT modes. */ existingEntry: {type: Object, value: null}, isAccountStoreUser: {type: Boolean, value: false}, accountEmail: {type: String, value: null}, storeOptionAccountValue: {type: String, value: 'account', readonly: true}, storeOptionDeviceValue: {type: String, value: 'device', readonly: true}, /** * Saved passwords after deduplicating versions that are repeated in the * account and on the device. */ savedPasswords: { type: Array, value: () => [], }, /** * Usernames for the same website. Used for the fast check whether edited * username is already used. */ usernamesForSameOrigin_: { type: Object, value: null, }, dialogMode_: { type: String, computed: 'computeDialogMode_(existingEntry)', }, /** * True if existing entry is a federated credential. */ isInViewMode_: { type: Boolean, computed: 'computeIsInViewMode_(dialogMode_)', }, /** * Whether the password is visible or obfuscated. */ isPasswordVisible_: { type: Boolean, value: false, }, /** * Has value if entered website is a valid url. */ websiteUrls_: {type: Object, value: null}, /** * Whether the website input is invalid. */ websiteInputInvalid_: {type: Boolean, value: false}, /** * Error message if the website input is invalid. */ websiteInputErrorMessage_: {type: String, value: null}, /** * Whether the username input is invalid. */ usernameInputInvalid_: {type: Boolean, value: false}, /** * Current value in password input. */ password_: {type: String, value: ''}, /** * If either username or password entered incorrectly the save button will * be disabled. * */ isSaveButtonDisabled_: { type: Boolean, computed: 'computeIsSaveButtonDisabled_(websiteUrls_, usernameInputInvalid_, password_)' } }; } existingEntry: MultiStorePasswordUiEntry|null; isAccountStoreUser: boolean; accountEmail: string|null; readonly storeOptionAccountValue: string; readonly storeOptionDeviceValue: string; savedPasswords: Array<MultiStorePasswordUiEntry>; private usernamesForSameOrigin_: Set<string>|null; private dialogMode_: PasswordDialogMode; private isInViewMode_: boolean; private isPasswordVisible_: boolean; private websiteUrls_: chrome.passwordsPrivate.UrlCollection|null; private websiteInputInvalid_: boolean; private websiteInputErrorMessage_: string|null; private usernameInputInvalid_: boolean; private password_: string; private isSaveButtonDisabled_: boolean; connectedCallback() { super.connectedCallback(); if (this.existingEntry) { this.websiteUrls_ = this.existingEntry.urls; } this.password_ = this.getPassword_(); if (this.dialogMode_ === PasswordDialogMode.EDIT) { this.usernamesForSameOrigin_ = new Set( this.savedPasswords .filter( item => item.urls.shown === this.existingEntry!.urls.shown && (item.isPresentOnDevice() === this.existingEntry!.isPresentOnDevice() || item.isPresentInAccount() === this.existingEntry!.isPresentInAccount())) .map(item => item.username)); } } /** Closes the dialog. */ close() { this.$.dialog.close(); } private computeDialogMode_(): PasswordDialogMode { if (this.existingEntry) { return this.existingEntry.federationText ? PasswordDialogMode.VIEW : PasswordDialogMode.EDIT; } return PasswordDialogMode.ADD; } private computeIsInViewMode_(): boolean { return this.dialogMode_ === PasswordDialogMode.VIEW; } private computeIsSaveButtonDisabled_(): boolean { return !this.websiteUrls_ || this.usernameInputInvalid_ || !this.password_.length; } /** * Handler for tapping the 'cancel' button. Should just dismiss the dialog. */ private onCancel_() { this.close(); } /** * Gets the password input's type. Should be 'text' when input content is * visible otherwise 'password'. If the entry is a federated credential, * the content (federation text) is always visible. */ private getPasswordInputType_(): string { // VIEW mode implies |existingEntry| is a federated credential. if (this.isInViewMode_) { return 'text'; } return this.isPasswordVisible_ ? 'text' : 'password'; } /** * Gets the title text for the show/hide icon. */ private showPasswordTitle_(): string { assert(!this.isInViewMode_); return this.isPasswordVisible_ ? this.i18n('hidePassword') : this.i18n('showPassword'); } /** * Get the right icon to display when hiding/showing a password. */ private getIconClass_(): string { assert(!this.isInViewMode_); return this.isPasswordVisible_ ? 'icon-visibility-off' : 'icon-visibility'; } /** * Gets the initial text to show in the website input. */ private getWebsite_(): string { return this.dialogMode_ === PasswordDialogMode.ADD ? '' : this.existingEntry!.urls.link; } /** * Gets the initial text to show in the username input. */ private getUsername_(): string { return this.dialogMode_ === PasswordDialogMode.ADD ? '' : this.existingEntry!.username; } /** * Gets the initial text to show in the password input: the password for a * regular credential, the federation text for a federated credential or empty * string in the ADD mode. */ private getPassword_(): string { switch (this.dialogMode_) { case PasswordDialogMode.VIEW: // VIEW mode implies |existingEntry| is a federated credential. return this.existingEntry!.federationText!; case PasswordDialogMode.EDIT: return this.existingEntry!.password; case PasswordDialogMode.ADD: return ''; default: assertNotReached(); return ''; } } /** * Handler for tapping the show/hide button. */ private onShowPasswordButtonTap_() { assert(!this.isInViewMode_); this.isPasswordVisible_ = !this.isPasswordVisible_; } /** * Handler for tapping the 'done' or 'save' button depending on |dialogMode_|. * For 'save' button it should save new password. After pressing action button * the edit dialog should be closed. */ private onActionButtonTap_() { switch (this.dialogMode_) { case PasswordDialogMode.VIEW: this.close(); return; case PasswordDialogMode.EDIT: this.changePassword_(); return; case PasswordDialogMode.ADD: this.addPassword_(); return; default: assertNotReached(); } } private addPassword_() { const useAccountStore = !this.$.storePicker.hidden ? (this.$.storePicker.value === this.storeOptionAccountValue) : false; PasswordManagerImpl.getInstance() .addPassword({ url: this.$.websiteInput.value, username: this.$.usernameInput.value, password: this.password_, useAccountStore: useAccountStore }) .finally(() => { this.close(); }); } private changePassword_() { const idsToChange = []; const accountId = this.existingEntry!.accountId; const deviceId = this.existingEntry!.deviceId; if (accountId !== null) { idsToChange.push(accountId); } if (deviceId !== null) { idsToChange.push(deviceId); } PasswordManagerImpl.getInstance() .changeSavedPassword( idsToChange, this.$.usernameInput.value, this.$.passwordInput.value) .finally(() => { this.close(); }); } private getActionButtonName_(): string { return this.isInViewMode_ ? this.i18n('done') : this.i18n('save'); } /** * Manually de-select texts for readonly inputs. */ private onInputBlur_() { this.shadowRoot!.getSelection()!.removeAllRanges(); } /** * Gets the HTML-formatted message to indicate in which locations the password * is stored. */ private getStorageDetailsMessage_(): string { if (this.dialogMode_ === PasswordDialogMode.ADD) { // Storage message is not shown in the ADD mode. return ''; } if (this.existingEntry!.isPresentInAccount() && this.existingEntry!.isPresentOnDevice()) { return this.i18n('passwordStoredInAccountAndOnDevice'); } return this.existingEntry!.isPresentInAccount() ? this.i18n('passwordStoredInAccount') : this.i18n('passwordStoredOnDevice'); } private getStoreOptionAccountText_(): string { if (this.dialogMode_ !== PasswordDialogMode.ADD) { // Store picker is only shown in the ADD mode. return ''; } return this.i18n('addPasswordStoreOptionAccount', this.accountEmail!); } private getTitle_(): string { switch (this.dialogMode_) { case PasswordDialogMode.ADD: return this.i18n('addPasswordTitle'); case PasswordDialogMode.EDIT: return this.i18n('editPasswordTitle'); case PasswordDialogMode.VIEW: return this.i18n('passwordDetailsTitle'); default: assertNotReached(); return ''; } } private shouldShowStorageDetails_(): boolean { return this.dialogMode_ !== PasswordDialogMode.ADD && this.isAccountStoreUser; } private shouldShowStorePicker_(): boolean { return this.dialogMode_ === PasswordDialogMode.ADD && this.isAccountStoreUser; } private isWebsiteEditable_(): boolean { return this.dialogMode_ === PasswordDialogMode.ADD; } /** * @return The text to be displayed as the dialog's footnote. */ private getFootnote_(): string { return this.dialogMode_ === PasswordDialogMode.ADD ? this.i18n('addPasswordFootnote') : this.i18n('editPasswordFootnote', this.existingEntry!.urls.shown); } private getClassForWebsiteInput_(): string { // If website input is empty, it is invalid, but has no error message. // To handle this, the error is shown only if 'has-error-message' is set. return this.websiteInputErrorMessage_ ? 'has-error-message' : ''; } /** * Helper function that checks whether the entered url is valid. */ private validateWebsite_() { assert(this.dialogMode_ === PasswordDialogMode.ADD); if (!this.$.websiteInput.value.length) { this.websiteUrls_ = null; this.websiteInputErrorMessage_ = null; this.websiteInputInvalid_ = true; return; } PasswordManagerImpl.getInstance() .getUrlCollection(this.$.websiteInput.value) .then(urlCollection => { if (urlCollection) { this.websiteUrls_ = urlCollection; this.websiteInputErrorMessage_ = null; this.websiteInputInvalid_ = false; } else { this.websiteUrls_ = null; this.websiteInputErrorMessage_ = this.i18n('notValidWebAddress'); this.websiteInputInvalid_ = true; } }); } /** * Helper function that checks whether edited username is not used for the * same website. */ private validateUsername_() { assert(!this.isInViewMode_); if (this.dialogMode_ === PasswordDialogMode.ADD) { // TODO(crbug.com/1236053): handle duplicates in ADD mode. return; } if (this.existingEntry!.username !== this.$.usernameInput.value) { this.usernameInputInvalid_ = this.usernamesForSameOrigin_!.has(this.$.usernameInput.value); } else { this.usernameInputInvalid_ = false; } } } customElements.define(PasswordEditDialogElement.is, PasswordEditDialogElement);
the_stack
import Users from '../../lib/collections/users/collection'; import { Comments } from '../../lib/collections/comments' import { Posts } from '../../lib/collections/posts' import { Vulcan, createMutator } from '../vulcan-lib'; import { slugify } from '../../lib/vulcan-lib/utils'; import { sanitize } from '../vulcan-lib/utils'; import moment from 'moment'; import { markdownToHtml } from '../editor/make_editable_callbacks'; import pgp from 'pg-promise'; import mapValues from 'lodash/mapValues'; import groupBy from 'lodash/groupBy'; import pick from 'lodash/pick'; import htmlToText from 'html-to-text'; import * as _ from 'underscore'; import { randomId } from '../../lib/random'; const postgresImportDetails = { host: 'localhost', port: 5432, database: 'reddit', user: 'reddit', password: '' // Ommitted for obvious reasons } Vulcan.postgresImport = async () => { // Set up DB connection let postgresConnector = pgp({}); let database = postgresConnector(postgresImportDetails); /* USER DATA IMPORT */ //eslint-disable-next-line no-console console.info("Starting user data import"); // Query for user data const rawUserData = await database.any('SELECT thing_id, key, value from reddit_data_account', [true]); const rawUserMetaData = await database.any('SELECT thing_id, deleted, date from reddit_thing_account', [true]); // Process user data const groupedUserData = groupBy(rawUserData, (row) => row.thing_id); const flattenedUserData = mapValues(groupedUserData, keyValueArraytoObject); // Process user metadata const groupedUserMetaData = groupBy(rawUserMetaData, (row) => row.thing_id); const flattenedUserMetaData = mapValues(groupedUserMetaData, (v) => _.pick(v[0], 'deleted', 'date')); // Merge data const mergedGroupedUserData = deepObjectExtend(flattenedUserData, flattenedUserMetaData) // Convert to LW2 user format const processedUsers = _.map(mergedGroupedUserData, legacyUserToNewUser); // Construct user lookup table to avoid repeated querying let legacyIdToUserMap = new Map((await Users.find().fetch()).map((user) => [user.legacyId, user])); // Upsert Users await upsertProcessedUsers(processedUsers, legacyIdToUserMap); // Construct user lookup table to avoid repeated querying legacyIdToUserMap = new Map((await Users.find().fetch()).map((user) => [user.legacyId, user])); /* POST DATA IMPORT */ //eslint-disable-next-line no-console console.log("Starting post data import"); // Query for post data const rawPostData = await database.any('SELECT thing_id, key, value from reddit_data_link', [true]); const rawPostMetaData = await database.any('SELECT thing_id, ups, downs, deleted, spam, descendant_karma, date from reddit_thing_link', [true]); // Process post data const groupedPostData = groupBy(rawPostData, (row) => row.thing_id); const flattenedPostData = mapValues(groupedPostData, keyValueArraytoObject); // Process post metadata const groupedPostMetaData = groupBy(rawPostMetaData, (row) => row.thing_id); const flattenedPostMetaData = mapValues(groupedPostMetaData, (v) => _.pick(v[0], 'ups', 'downs', 'deleted', 'spam', 'descendant_karma', 'date')); // Merge data const mergedGroupedPostData = deepObjectExtend(flattenedPostData, flattenedPostMetaData); // Convert to LW2 post format const processedPosts = mapValues(mergedGroupedPostData, (post, id) => legacyPostToNewPost(post, id, legacyIdToUserMap.get(post.author_id))); // Construct post lookup table to avoid repeated querying let legacyIdToPostMap = new Map((await Posts.find().fetch()).map((post) => [post.legacyId, post])); // Upsert Posts await upsertProcessedPosts(processedPosts, legacyIdToPostMap); // Construct post lookup table to avoid repeated querying legacyIdToPostMap = new Map((await Posts.find().fetch()).map((post) => [post.legacyId, post])); /* COMMENT DATA IMPORT */ //eslint-disable-next-line no-console console.log("Starting the comment data import"); // Query for comment data let rawCommentData = await database.any('SELECT thing_id, key, value from reddit_data_comment', [true]); let rawCommentMetadata = await database.any('SELECT thing_id, ups, downs, deleted, spam, date from reddit_thing_comment', [true]); // Process comment data let commentData: any = groupBy(rawCommentData, (row) => row.thing_id); commentData = mapValues(commentData, keyValueArraytoObject); // Process post metadata let commentMetaData: any = groupBy(rawCommentMetadata, (row) => row.thing_id); commentMetaData = mapValues(commentMetaData, (v) => pick(v[0], 'ups', 'downs', 'deleted', 'spam', 'date')); // Merge data commentData = deepObjectExtend(commentData, commentMetaData); // Convert to LW2 comment format [Does not yet include parentCommentIds and topLevelCommentIds] // @ts-ignore commentData = await Promise.all(mapValues(commentData, (comment, id) => legacyCommentToNewComment(comment, id, legacyIdToUserMap.get(comment.author_id), legacyIdToPostMap.get(comment.link_id)) )); let legacyIdToCommentMap = new Map((await Comments.find().fetch()).map((comment) => [comment.legacyId, comment])); commentData = _.map(commentData, (comment: any, id: any) => addParentCommentId(comment, legacyIdToCommentMap.get(comment.legacyParentId) || commentData[comment.legacyParentId])) //eslint-disable-next-line no-console console.log("Finished Comment Data Processing", commentData[25], commentData[213]); await upsertProcessedComments(commentData, legacyIdToCommentMap); //eslint-disable-next-line no-console console.log("Finished Upserting comments"); // construct comment lookup table to avoid repeated querying legacyIdToCommentMap = new Map((await Comments.find().fetch()).map((comment) => [comment.legacyId, comment])); //eslint-disable-next-line no-console console.log("Finished comment data import"); } const addParentCommentId = (comment, parentComment) => { if (parentComment) { return {...comment, parentCommentId: parentComment._id, topLevelCommentId: parentComment._id}; } else { return comment; } } Vulcan.syncUserPostCount = async () => { const postCounters = await Posts.aggregate([ {"$group" : {_id:"$userId", count:{$sum:1}}} ]) //eslint-disable-next-line no-console console.log("Started updating post counts:", postCounters); const postCounterArray = await postCounters.toArray(); const userUpdates = postCounterArray.map((counter) => ({ updateOne : { filter : {_id: counter.userId}, update : {$set: {'postCount' : counter.count}} } })) const userUpdateCursor = await Users.rawCollection().bulkWrite(userUpdates, {ordered: false}) //eslint-disable-next-line no-console console.log("Finished updating users:", userUpdateCursor); } const deepObjectExtend = (target, source) => { for (var prop in source) if (prop in target) deepObjectExtend(target[prop], source[prop]); else target[prop] = source[prop]; return target; } const upsertProcessedPosts = async (posts, postMap) => { const postUpdates = _.map(posts, (post: any) => { const existingPost = postMap.get(post.legacyId); if (existingPost) { let set: any = {legacyData: post.legacyData}; if (post.deleted || post.spam) { set.status = 3; } return { updateOne : { filter : {_id: existingPost._id}, update : {$set: set}, upsert : false } } } else { return { insertOne : { document : post} } } }) await Posts.rawCollection().bulkWrite(postUpdates, {ordered: false}); // console.log("Upserted posts: ", postUpdateCursor); } const upsertProcessedUsers = async (users, userMap) => { let userCounter = 0; // We first find all the users for which we already have an existing user in the DB const usersToUpdate = _.filter(users, (user: any) => userMap.get(user.legacyId)) //eslint-disable-next-line no-console //console.log("Updating N users: ", _.size(usersToUpdate), usersToUpdate[22], typeof usersToUpdate); const usersToInsert = _.filter(users, (user: any) => !userMap.get(user.legacyId)) //eslint-disable-next-line no-console //console.log("Inserting N users: ", _.size(usersToInsert), usersToInsert[22], typeof usersToInsert); if (usersToUpdate && _.size(usersToUpdate)) {await bulkUpdateUsers(usersToUpdate, userMap);} if (usersToInsert && _.size(usersToInsert)) { for(let key in usersToInsert) { await insertUser(usersToInsert[key]); userCounter++; if(userCounter % 1000 == 0){ //eslint-disable-next-line no-console console.log("UserCounter: " + userCounter); } } } } const bulkUpdateUsers = async (users, userMap) => { const userUpdates = users.map((newUser) => { const oldUser = userMap.get(newUser.legacyId); let set: any = {legacyData: newUser.legacyData, deleted: newUser.deleted}; if (newUser.legacyData.email !== oldUser.legacyData.email && oldUser.email === oldUser.legacyData.email) { //eslint-disable-next-line no-console console.log("Found email change", newUser.username, newUser.legacyData.email, oldUser.email); set.email = newUser.legacyData.email; set.emails = [{address: newUser.legacyData.email, verified: true}] } return { updateOne : { filter : {_id: oldUser._id}, update : {$set: set}, upsert : false } } }) const userUpdateCursor = await Users.rawCollection().bulkWrite(userUpdates, {ordered: false}); //eslint-disable-next-line no-console console.log("userUpdateCursor: ", userUpdateCursor); } const insertUser = async (user) => { // console.log("insertUser", user); try { await createMutator({ collection: Users, document: user, validate: false }) } catch(err) { if (err.code == 11000) { const newUser = {...user, username: user.username + "_duplicate" + Math.random().toString(), emails: []} try { await createMutator({ collection: Users, document: newUser, validate: false }) } catch(err) { //eslint-disable-next-line no-console console.error("User Import failed", err, user); } } else { //eslint-disable-next-line no-console console.error("User Import failed", err, user); } } } const upsertProcessedComments = async (comments, commentMap) => { let postUpdates: Array<any> = []; let userUpdates: Array<any> = []; let commentUpdates: Array<any> = []; _.map(comments, (comment: any) => { const existingComment = commentMap.get(comment.legacyId); if (existingComment) { let set: any = {legacyData: comment.legacyData, parentCommentId: comment.parentCommentId, topLevelCommentId: comment.topLevelCommentId}; if (comment.retracted) { set.retracted = true; } commentUpdates.push({ updateOne : { filter : {_id: existingComment._id}, update : {$set: set}, upsert : false } }) } else { commentUpdates.push({ insertOne : { document : comment } }) postUpdates.push({ updateOne : { filter : {_id: comment.postId}, update : { $inc: {commentCount: 1}, $max: {lastCommentedAt: comment.postedAt}, $addToSet: {commenters: comment.userId} }, upsert : false, } }) userUpdates.push({ updateOne : { filter : {_id: comment.userId}, update : {$inc: {commentCount: 1}}, upsert : false } }) } }) if (_.size(postUpdates)) { const postUpdateCursor = await Posts.rawCollection().bulkWrite(postUpdates, {ordered: false}); //eslint-disable-next-line no-console console.log("postUpdateCursor", postUpdateCursor); } if (_.size(userUpdates)) { const userUpdateCursor = await Users.rawCollection().bulkWrite(userUpdates, {ordered: false}); //eslint-disable-next-line no-console console.log("userUpdateCursor", userUpdateCursor); } if (_.size(commentUpdates)) { const commentUpdateCursor = await Comments.rawCollection().bulkWrite(commentUpdates, {ordered: false}); //eslint-disable-next-line no-console console.log("commentUpdateCursor", commentUpdateCursor); } } const keyValueArraytoObject = (keyValueArray) => { return keyValueArray.reduce( (prev,curr) => { prev[curr.key]=curr.value; return prev; }, {} // Initial Value ) } const legacyUserToNewUser = (user, legacyId) => { return { legacy: true, legacyId: legacyId, legacyData: user, username: user.name, email: user.email, deleted: user.deleted, createdAt: moment(user.date).toDate(), services: {}, emails: user.email ? [{address: user.email, verified: true}] : null, } } const legacyPostToNewPost = (post, legacyId, user) => { const body = htmlToText.fromString(post.article); const isPublished = post.sr_id === "2" || post.sr_id === "3" || post.sr_id === "3391" || post.sr_id === "4"; return { _id: randomId(), legacy: true, legacyId: legacyId, legacyData: post, title: post.title, userId: user && user._id, contents: { originalContents: { type: "html", data: post.article }, html: post.article }, userIP: post.ip, status: post.deleted || post.spam ? 3 : 2, legacySpam: post.spam, baseScore: post.ups - post.downs, url: absoluteURLRegex.test(post.url) ? post.url : null, createdAt: moment(post.date).toDate(), postedAt: moment(post.date).toDate(), slug: slugify(post.title), excerpt: body.slice(0,600), draft: !isPublished, }; } const legacyCommentToNewComment = async (comment, legacyId, author, parentPost) => { //eslint-disable-next-line no-console if (!author) {console.warn("Missing author for comment:", comment)} //eslint-disable-next-line no-console if (!parentPost) {console.warn("Missing parent post for comment: ", comment)} return { _id: randomId(), legacy: true, legacyId: legacyId, legacyParentId: comment.parent_id, legacyData: comment, postId: parentPost && parentPost._id, userId: author && author._id, baseScore: comment.ups - comment.downs, retracted: comment.retracted, deleted: comment.deleted, isDeleted: comment.isDeleted, createdAt: moment(comment.date).toDate(), postedAt: moment(comment.date).toDate(), contents: { originalContents: { type: "markdown", data: comment.body }, html: comment.body && sanitize(await markdownToHtml(comment.body)) }, }; } const absoluteURLRegex = new RegExp('^(?:[a-z]+:)?//', 'i');
the_stack
// This class was written principally as a workaround for bugs related to // RTCDataChannel.close behavior, such as https://crbug.com/474688. // However, it should also help to reduce startup latency, by removing a // roundtrip from each connection request (waiting for the "open ack"). // It may therefore be worth preserving even after any platform bugs are // resolved. import * as peerconnection from '../webrtc/peerconnection'; import * as datachannel from '../webrtc/datachannel'; import * as handler from '../handler/queue'; import * as queue from '../queue/queue'; import * as logging from '../logging/logging'; var log :logging.Log = new logging.Log('pool'); // This is the only exported class in this module. It mimics the data channel // aspects of the PeerConnection interface. Internally, it provides a pool // of channels that keeps old channels for reuse instead of closing them, and // makes new channels as needed when the pool runs dry. Crucially, the local // and remote pools do not interfere with each other, even if they use the // same labels, because the browser ensures that data channels created by each // peer are drawn from separate ID spaces (odd vs. even). export default class Pool { public peerOpenedChannelQueue :handler.QueueHandler<datachannel.DataChannel, void>; private localPool_ :LocalPool; constructor( pc:peerconnection.PeerConnection<Object>, name_:string) { this.localPool_ = new LocalPool(pc, name_); var remotePool = new RemotePool(pc, name_); this.peerOpenedChannelQueue = remotePool.peerOpenedChannelQueue; } public openDataChannel = () : Promise<datachannel.DataChannel> => { return this.localPool_.openDataChannel(); } } // Manages a pool of data channels opened by this peer. The only public method // is openDataChannel. class LocalPool { private nextChannelId_ = 0; private numChannels_ = 0; // Channels which have been closed, and may be re-opened. private pool_ = new queue.Queue<PoolChannel>(); constructor( private pc_:peerconnection.PeerConnection<Object>, private name_:string) {} public openDataChannel = () : Promise<PoolChannel> => { return this.reuseOrCreate_().then((channel:PoolChannel) => { return channel.open().then(() => { // When this channel closes, reset it and return it to the pool. channel.onceClosed.then(() => { this.onChannelClosed_(channel); }); return channel; }); }); } private reuseOrCreate_ = () : Promise<PoolChannel> => { // If there are no channels available right now, open a new one. // TODO: limit the number of channels (probably should be <=256). if (this.pool_.length > 0) { var channel = this.pool_.shift(); log.debug('%1: re-using channel %2 (%3/%4)', this.name_, channel.getLabel(), this.pool_.length, this.numChannels_); return Promise.resolve(channel); } else { return this.openNewChannel_(); } } // Creates and returns a new channel, wrapping it. private openNewChannel_ = () : Promise<PoolChannel> => { var newChannelId = ++this.nextChannelId_; log.info('%1: opening channel (id %2)', this.name_, newChannelId); return this.pc_.openDataChannel('p' + newChannelId, { id: newChannelId }).then((dc:datachannel.DataChannel) => { this.numChannels_++; return dc.onceOpened.then(() => { return new PoolChannel(dc); }); }, (e:Error) => { this.nextChannelId_--; throw e; }); } // Resets the channel, making it ready for use again, and adds it // to the pool. private onChannelClosed_ = (poolChannel:PoolChannel) : void => { if (!poolChannel.reset()) { return; } this.pool_.push(poolChannel); log.debug('%1: returned channel %2 to the pool (%3/%4)', this.name_, poolChannel.getLabel(), this.pool_.length, this.numChannels_); } } // Tracks a pool of channels that were opened by the remote peer. class RemotePool { public peerOpenedChannelQueue = new handler.Queue<PoolChannel,void>(); constructor( private pc_:peerconnection.PeerConnection<Object>, private name_:string) { this.pc_.peerOpenedChannelQueue.setSyncHandler(this.onNewChannel_); } private onNewChannel_ = (dc:datachannel.DataChannel) => { log.debug('%1: remote side created new channel: %2', this.name_, dc.getLabel()); dc.onceOpened.then(() => { var poolChannel = new PoolChannel(dc); this.listenForOpenAndClose_(poolChannel); }); } private listenForOpenAndClose_ = (poolChannel:PoolChannel) : void => { poolChannel.onceOpened.then(() => { this.peerOpenedChannelQueue.handle(poolChannel); }); poolChannel.onceClosed.then(() => { if (!poolChannel.reset()) { return; } this.listenForOpenAndClose_(poolChannel); }); } } // These are the two control messages used. To help debugging, and // improve forward-compatibility, we send the string name on the wire, // not the numerical enum value. Therefore, these names are part of // the normative protocol, and will break compatibility if changed. enum ControlMessage { OPEN, CLOSE } enum State { OPEN, CLOSING, // Waiting for CLOSE ack CLOSED, PERMANENTLY_CLOSED } // Each PoolChannel wraps an actual DataChannel, and provides behavior // that is intended to be indistinguishable to the caller. However, // close() does not actually close the underlying channel. Instead, // it sends an in-band control message indicating the close, and the // channel is returned to the pool of inactive channels, ready for // reuse when the client asks for a new channel. class PoolChannel implements datachannel.DataChannel { private fulfillOpened_ :() => void; public onceOpened : Promise<void>; private fulfillClosed_ :() => void; public onceClosed : Promise<void>; // Every call to dataFromPeerQueue.handle() must also set // lastDataFromPeerHandled_ to the new return value, so that we can // tell when all pending data from the peer has been drained. public dataFromPeerQueue :handler.Queue<datachannel.Data,void>; private lastDataFromPeerHandled_ : Promise<void>; private state_ :State = State.CLOSED; // dc_.onceOpened must already have resolved constructor(private dc_:datachannel.DataChannel) { this.reset(); this.dc_.onceClosed.then(() => { this.changeState_(State.PERMANENTLY_CLOSED); this.fulfillClosed_(); }); } public reset = () : boolean => { if (this.state_ !== State.CLOSED) { return false; } this.dataFromPeerQueue = new handler.Queue<datachannel.Data,void>(); this.lastDataFromPeerHandled_ = Promise.resolve(); this.onceOpened = new Promise<void>((F, R) => { this.fulfillOpened_ = F; }); this.onceClosed = new Promise<void>((F, R) => { this.fulfillClosed_ = F; }); this.dc_.dataFromPeerQueue.setSyncHandler(this.onDataFromPeer_); return true; } private changeState_ = (state:State) : void => { log.debug('%1: %2 -> %3', this.getLabel(), State[this.state_], State[state]); this.state_ = state; } private doOpen_ = () : void => { this.changeState_(State.OPEN); this.fulfillOpened_(); } private doClose_ = () : void => { this.changeState_(State.CLOSED); this.fulfillClosed_(); } public getLabel = () : string => { return this.dc_.getLabel(); } public send = (data:datachannel.Data) : Promise<void> => { if (this.state_ !== State.OPEN) { return Promise.reject(new Error('Can\'t send while closed')); } // To distinguish control messages from application data, all string // messages are encapsulated in a JSON layer. Binary messages are unaffected. if (data.str) { return this.dc_.send({ str: JSON.stringify({ data: data.str }) }); } return this.dc_.send(data); } private sendControlMessage_ = (controlMessage:ControlMessage) : Promise<void> => { log.debug('%1: sending control message: %2', this.getLabel(), ControlMessage[controlMessage]); return this.dc_.send({ str: JSON.stringify({ control: ControlMessage[controlMessage] }) }); } private onDataFromPeer_ = (data:datachannel.Data) : void => { if (data.str) { try { var msg = JSON.parse(data.str); } catch (e) { log.error('%1: Got non-JSON string: %2', this.getLabel(), data.str); return; } if (typeof msg.data === 'string') { this.lastDataFromPeerHandled_ = this.dataFromPeerQueue.handle({str: msg.data}); } else if (typeof msg.control === 'string') { this.onControlMessage_(msg.control); } else { log.error('No data or control message found'); } return; } this.lastDataFromPeerHandled_ = this.dataFromPeerQueue.handle(data); } private onControlMessage_ = (controlMessage:string) : void => { log.debug('%1: received control message: %2', this.getLabel(), controlMessage); if (controlMessage === ControlMessage[ControlMessage.OPEN]) { if (this.state_ === State.CLOSING) { log.warn('%1: Got OPEN while closing (should be queued!)', this.getLabel()); this.onceClosed.then(() => { log.debug('%1: Immediately reopening after close', this.getLabel()); this.doOpen_(); }); } else if (this.state_ === State.PERMANENTLY_CLOSED) { log.warn('%1: Got open message on permanently closed channel', this.getLabel()); } else { if (this.state_ === State.OPEN) { log.warn('%1: Got redundant open message', this.getLabel()); } this.doOpen_(); } } else if (controlMessage === ControlMessage[ControlMessage.CLOSE]) { // Stop handling messages immediately, so that a pending OPEN is not // processed until after a call to reset(). this.dc_.dataFromPeerQueue.stopHandling(); if (this.state_ === State.OPEN) { this.changeState_(State.CLOSING); // Drain messages, then ack the close. this.lastDataFromPeerHandled_.then(() => { return this.sendControlMessage_(ControlMessage.CLOSE); }).then(() => { if (this.state_ === State.PERMANENTLY_CLOSED) { log.warn('%1: Underlying channel closed while draining', this.getLabel()); return; } log.debug('%1: Changing state to CLOSED after draining ' + 'messages', this.getLabel()); this.doClose_(); }); } else if (this.state_ === State.CLOSING) { // We both sent a "close" command at the same time. this.doClose_(); } else if (this.state_ === State.CLOSED) { log.warn('%1: Got redundant close message', this.getLabel()); } else if (this.state_ === State.PERMANENTLY_CLOSED) { log.warn('%1: Got close message on permanently closed channel', this.getLabel()); } } else { log.error('%1: unknown control message: %2', this.getLabel(), controlMessage); } } public getBrowserBufferedAmount = () : Promise<number> => { return this.dc_.getBrowserBufferedAmount(); } public getJavascriptBufferedAmount = () : number => { return this.dc_.getJavascriptBufferedAmount(); } public isInOverflow = () : boolean => { return this.dc_.isInOverflow(); } public setOverflowListener = (listener:(overflow:boolean) => void) : void => { this.dc_.setOverflowListener(listener); } // New method for PoolChannel, not present in the DataChannel interface. public open = () : Promise<void> => { log.debug(this.getLabel() + ': open'); if (this.state_ === State.OPEN) { return Promise.reject(new Error('channel is already open')); } this.sendControlMessage_(ControlMessage.OPEN); // Immediate open; there is no open-ack this.doOpen_(); return this.onceOpened; } public close = () : Promise<void> => { log.debug('%1: close', this.getLabel()); if (this.state_ !== State.OPEN) { log.warn('%1: Ignoring close in %2 state', this.getLabel(), State[this.state_]); return; } this.changeState_(State.CLOSING); this.sendControlMessage_(ControlMessage.CLOSE); return this.onceClosed; } public toString = () : string => { return 'PoolChannel(' + this.dc_.toString() + ')'; } }
the_stack
import { Office } from "../../server/express/types/Office"; describe("Schedule", () => { beforeEach(() => { // only mock setInterval and date, but not setTimeout to not break socket.io sockets cy.clock(new Date(Date.UTC(2020, 11, 18, 9, 49, 0)).getTime(), ["setInterval", "clearInterval", "Date"]); }); describe("shows a schedule", () => { let office: Office; beforeEach(() => { office = { rooms: [], groups: [], schedule: { tracks: [], sessions: [], }, }; }); describe("with a single track", () => { beforeEach(() => { office.schedule.tracks = [{ id: "track1", name: "Track 1" }]; }); describe("and a single room", () => { beforeEach(() => { office.rooms = [{ roomId: "1", name: "A room", meetingId: "123", joinUrl: "join-url" }]; }); it("with a subtitle", () => { office.rooms = [ { roomId: "1", name: "A room", subtitle: "With a subtitle", meetingId: "123", joinUrl: "join-url" }, ]; office.schedule.sessions = [{ start: "09:00", end: "11:00", roomId: "1", trackId: "track1" }]; cy.replaceOffice(office); cy.visit("/"); cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(9:00 AM-11:00 AM UTC) With a subtitle", isJoinable: true, }); }); it("that is disabled", () => { office.schedule.sessions = [{ start: "10:00", end: "12:00", roomId: "1", trackId: "track1" }]; cy.replaceOffice(office); cy.visit("/"); cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(10:00 AM-12:00 PM UTC)", isJoinable: false }); }); it("that is active", () => { office.schedule.sessions = [{ start: "08:00", end: "10:00", roomId: "1", trackId: "track1" }]; cy.replaceOffice(office); cy.visit("/"); cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(8:00 AM-10:00 AM UTC)", isJoinable: true }); }); }); }); describe("with multiple tracks", () => { beforeEach(() => { office.schedule.tracks = [ { id: "track1", name: "Track 1" }, { id: "track2", name: "Track 2" }, { id: "track3", name: "Track 3" }, ]; }); it("and parallel sessions", () => { office.rooms = [ { roomId: "1", name: "Session 1", meetingId: "123", joinUrl: "join-url" }, { roomId: "2", name: "Session 2", meetingId: "123", joinUrl: "join-url" }, { roomId: "3", name: "Session 3", meetingId: "123", joinUrl: "join-url" }, { roomId: "4", name: "Session 4", meetingId: "123", joinUrl: "join-url" }, ]; office.schedule.sessions = [ { start: "09:00", end: "12:00", roomId: "1", trackId: "track1" }, { start: "10:00", end: "12:30", roomId: "2", trackId: "track2" }, { start: "10:00", end: "14:00", roomId: "3", trackId: "track3" }, { start: "14:00", end: "16:00", roomId: "4" }, ]; cy.replaceOffice(office); cy.visit("/"); cy.findByText("Session 1").parents(".MuiCard-root").as("session1Card"); cy.findByText("Session 2").parents(".MuiCard-root").as("session2Card"); cy.findByText("Session 3").parents(".MuiCard-root").as("session3Card"); cy.findByText("Session 4").parents(".MuiCard-root").as("session4Card"); cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-12:00 PM UTC)", isJoinable: true, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", subtitle: "(10:00 AM-12:30 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session3Card", title: "Session 3", subtitle: "(10:00 AM-2:00 PM UTC)", isJoinable: false, }); tickMinutes(2); // 09:51 cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-12:00 PM UTC)", isJoinable: true, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", subtitle: "(10:00 AM-12:30 PM UTC)", isJoinable: true, }); cy.assertCard({ alias: "@session3Card", title: "Session 3", subtitle: "(10:00 AM-2:00 PM UTC)", isJoinable: true, }); tickMinutes(10 + 120); // 12:01 cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-12:00 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", subtitle: "(10:00 AM-12:30 PM UTC)", isJoinable: true, }); cy.assertCard({ alias: "@session3Card", title: "Session 3", subtitle: "(10:00 AM-2:00 PM UTC)", isJoinable: true, }); tickMinutes(30); // 12:31 cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-12:00 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", subtitle: "(10:00 AM-12:30 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session3Card", title: "Session 3", subtitle: "(10:00 AM-2:00 PM UTC)", isJoinable: true, }); tickMinutes(120); // 14:31 cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-12:00 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", subtitle: "(10:00 AM-12:30 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session3Card", title: "Session 3", subtitle: "(10:00 AM-2:00 PM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session4Card", title: "Session 4", subtitle: "(2:00 PM-4:00 PM UTC)", isJoinable: true, }); }); it("and sessions with groups", () => { office.groups = [{ id: "group1", name: "Group 1" }]; office.rooms = [ { roomId: "1", name: "Session 1", meetingId: "123", joinUrl: "join-url" }, { roomId: "2", groupId: "group1", name: "Session 2", meetingId: "123", joinUrl: "join-url" }, { roomId: "3", groupId: "group1", name: "Session 3", meetingId: "123", joinUrl: "join-url" }, ]; office.schedule.sessions = [ { start: "09:00", end: "10:00", roomId: "1", trackId: "track1" }, { start: "10:00", end: "12:00", groupId: "group1" }, ]; cy.replaceOffice(office); cy.visit("/"); cy.findByText("Session 1").parents(".MuiCard-root").as("session1Card"); cy.findByText("Session 2").parents(".MuiCard-root").as("session2Card"); cy.findByText("Session 3").parents(".MuiCard-root").as("session3Card"); cy.findByText("Group 1").parents(".MuiCard-root").as("group1Card"); cy.get("@group1Card").should("have.css", "opacity", "0.65"); cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-10:00 AM UTC)", isJoinable: true, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", isJoinable: false }); cy.assertCard({ alias: "@session3Card", title: "Session 3", isJoinable: false }); tickMinutes(12); // 10:01 cy.get("@group1Card").should("have.css", "opacity", "1"); cy.assertCard({ alias: "@session1Card", title: "Session 1", subtitle: "(9:00 AM-10:00 AM UTC)", isJoinable: false, }); cy.assertCard({ alias: "@session2Card", title: "Session 2", isJoinable: true }); cy.assertCard({ alias: "@session3Card", title: "Session 3", isJoinable: true }); }); }); }); it("should enable a card when the start time is reached", () => { cy.replaceOffice({ rooms: [{ roomId: "1", name: "A room", meetingId: "123", joinUrl: "join-url" }], groups: [], schedule: { tracks: [{ id: "track1", name: "Track 1" }], sessions: [{ start: "10:00", end: "12:00", roomId: "1", trackId: "track1" }], }, }); cy.visit("/"); cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(10:00 AM-12:00 PM UTC)", isJoinable: false }); tickMinutes(11); cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(10:00 AM-12:00 PM UTC)", isJoinable: true }); }); it("should disable a card when the end time is reached", () => { cy.replaceOffice({ rooms: [{ roomId: "1", name: "A room", meetingId: "123", joinUrl: "join-url" }], groups: [], schedule: { tracks: [{ id: "track1", name: "Track 1" }], sessions: [{ start: "08:00", end: "10:00", roomId: "1", trackId: "track1" }], }, }); cy.visit("/"); cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(8:00 AM-10:00 AM UTC)", isJoinable: true }); tickMinutes(11); // 10:01 cy.get(".MuiCard-root").as("card"); cy.assertCard({ alias: "@card", title: "A room", subtitle: "(8:00 AM-10:00 AM UTC)", isJoinable: false }); }); }); const tickMinutes = (minutes: number) => { cy.tick(1000 * 60 * minutes); };
the_stack
// tslint:disable-next-line:ordered-imports import pnp, { CamlQuery, ICachingOptions, PermissionKind, setup, Web, Logger, LogLevel } from "sp-pnp-js"; import IDiscussion from "../models/IDiscussion"; import { DiscussionPermissionLevel, IDiscussionReply } from "../models/IDiscussionReply"; class SocialModule { private discussionListServerRelativeUrl: string; /** * Initialize a new social module * @param listServerRelativeUrl the discussion board list server relative URL (e.g. '/sites/mysite/Lists/MyList') */ public constructor(listServerRelativeUrl: string) { this.discussionListServerRelativeUrl = listServerRelativeUrl; } /** * Ensure all script dependencies are loaded before using the taxonomy SharePoint CSOM functions * @return {Promise<void>} A promise allowing you to execute your code logic. */ public init(): Promise<void> { // Initialize SharePoint script dependencies SP.SOD.registerSod("sp.runtime.js", "/_layouts/15/sp.runtime.js"); SP.SOD.registerSod("sp.js", "/_layouts/15/sp.js"); SP.SOD.registerSod("reputation.js", "/_layouts/15/reputation.js"); SP.SOD.registerSodDep("reputation.js", "sp.js"); SP.SOD.registerSodDep("sp.js", "sp.runtime.js"); const p = new Promise<void>((resolve) => { SP.SOD.loadMultiple(["reputation.js", "sp.runtime.js", "sp.js"], () => { resolve(); }); }); return p; } /** * Create a new discussion in a disucssion board list * @param discussion the discussion properties */ public async createNewDiscussion(associatedPageId: number, discussionTitle: string, discussionBody: string): Promise<IDiscussion> { const p = new Promise<IDiscussion>((resolve, reject) => { const context = SP.ClientContext.get_current(); const list = context.get_web().getList(this.discussionListServerRelativeUrl); const reply = SP.Utilities.Utility.createNewDiscussion(context, list, discussionTitle); reply.set_item("Body", discussionBody); reply.set_item("AssociatedPageId", associatedPageId); // Need to explicitly update the item to actually create it (doesn't work otherwise) reply.update(); context.load(reply, "Id", "Author", "Created", "AssociatedPageId", "Body", "Title"); context.executeQueryAsync(async () => { // tslint:disable-next-line:no-object-literal-type-assertion resolve({ AssociatedPageId: reply.get_item("AssociatedPageId"), Body: reply.get_item("Body"), Id: reply.get_id(), Title: reply.get_item("Title"), // tslint:disable-next-line:object-literal-sort-keys Created: reply.get_item("Created"), Author: reply.get_item("Author"), Replies: [], } as IDiscussion); }, (sender, args) => { Logger.write(`[SocialModule:getDiscussionById]: ${args.get_message()}`, LogLevel.Error); reject(args.get_message()); }); }); return p; } /** * Add a reply to an existing discussion * @param parentItemId the parent item id for this reply * @param replyBody the content of the reply */ public async createNewDiscussionReply(parentItemId: number, replyBody: string): Promise<IDiscussionReply> { const p = new Promise<IDiscussionReply>((resolve, reject) => { const context = SP.ClientContext.get_current(); const list = context.get_web().getList(this.discussionListServerRelativeUrl); const parentItem = list.getItemById(parentItemId); const web = context.get_web(); const currentUser = web.get_currentUser(); const reply = SP.Utilities.Utility.createNewDiscussionReply(context, parentItem); reply.set_item("Body", replyBody); // Need to explicitly update the item to actually create it (doesn't work otherwise) reply.update(); context.load(currentUser); context.load(reply, "Id", "Author", "ParentItemID", "Modified", "Created", "ParentList"); context.executeQueryAsync(async () => { // Get user detail const authorProperties = await this.getUserProperties(currentUser.get_loginName()); const PictureUrl = authorProperties["PictureUrl"] ? authorProperties["PictureUrl"] : "/_layouts/15/images/person.gif?rev=23"; // Create a new dsicussion reply with initial property values // tslint:disable-next-line:no-object-literal-type-assertion resolve({ Body: replyBody, Id: reply.get_id(), ParentItemID: reply.get_item("ParentItemID"), Posted: reply.get_item("Created"), // tslint:disable-next-line:object-literal-sort-keys Edited: reply.get_item("Modified"), Author: { DisplayName: authorProperties["DisplayName"], PictureUrl, }, UserPermissions: await this.getCurrentUserPermissionsOnItem(reply.get_id(), currentUser.get_loginName()), Children: [], LikedBy: [], LikesCount: 0, ParentListId: reply.get_parentList().get_id().toString(), } as IDiscussionReply); }, (sender, args) => { Logger.write(`[SocialModule:getDiscussionById]: ${args.get_message()}`, LogLevel.Error); reject(args.get_message()); }); }); return p; } /** * Get a disucssion feed by id * @param id the id of the associated page */ public async getDiscussionById(associatedPageId: number): Promise<IDiscussion> { let web = new Web(_spPageContextInfo.webAbsoluteUrl); try { const discussion = await web.getList(this.discussionListServerRelativeUrl).items .filter(`AssociatedPageId eq ${ associatedPageId }`) .select("Id", "Folder", "AssociatedPageId") .expand("Folder") .top(1) .get(); if (discussion.length > 0) { // Get replies from this discussion (i.e. folder) const query: CamlQuery = { FolderServerRelativeUrl: `${this.discussionListServerRelativeUrl}/${discussion[0].Folder.Name}`, ViewXml: `<View> <ViewFields> <FieldRef Name="Id"></FieldRef> <FieldRef Name="ParentItemID"></FieldRef> <FieldRef Name="Created"></FieldRef> <FieldRef Name="Modified"></FieldRef> <FieldRef Name="Body"></FieldRef> <FieldRef Name="ParenListId"></FieldRef> <FieldRef Name="LikedBy"></FieldRef> <FieldRef Name="LikesCount"></FieldRef> </ViewFields> <Query/> </View>`, }; const replies = await web.getList(this.discussionListServerRelativeUrl).getItemsByCAMLQuery(query); // Batch are not supported on Sharepoint 2013 // https://github.com/SharePoint/PnP-JS-Core/issues/492 const batch = pnp.sp.createBatch(); const isSPO = _spPageContextInfo["isSPO"]; // tslint:disable-next-line:array-type const discussionReplies: Promise<IDiscussionReply>[] = replies.map(async (reply) => { web = new Web(_spPageContextInfo.webAbsoluteUrl); let item; // tslint:disable-next-line:prefer-conditional-expression if (isSPO) { item = await web.getList(this.discussionListServerRelativeUrl).items.getById(reply.Id).select("Author/Name", "ParentList/Id").expand("Author/Name", "ParentList/Id").inBatch(batch).get(); } else { item = await web.getList(this.discussionListServerRelativeUrl).items.getById(reply.Id).select("Author/Name", "ParentList/Id").expand("Author/Name", "ParentList/Id").get(); } const authorProperties = await this.getUserProperties(item.Author.Name); const PictureUrl = authorProperties["PictureUrl"] ? authorProperties["PictureUrl"] : "/_layouts/15/images/person.gif?rev=23"; // tslint:disable-next-line:no-object-literal-type-assertion return { Author: { DisplayName: authorProperties["DisplayName"], Id: item.Author.Id, PictureUrl, }, Body: reply.Body, Children: [], Edited: reply.Modified, Id: reply.Id, LikedBy: reply.LikedByStringId ? reply.LikedByStringId.results : [], LikesCount: reply.LikesCount ? reply.LikesCount : 0, ParentItemID: reply.ParentItemID, ParentListId: item.ParentList.Id, Posted: reply.Created, UserPermissions: await this.getCurrentUserPermissionsOnItem(reply.Id, item.Author.Name), } as IDiscussionReply; }); if (isSPO) { await batch.execute(); } // Get rating experience settings const folderSettings = await web.getFolderByServerRelativeUrl(this.discussionListServerRelativeUrl).properties.select("Ratings_VotingExperience").get(); const ratingExperience: string = folderSettings.Ratings_x005f_VotingExperience; let areLikesEnabled; if (ratingExperience) { areLikesEnabled = ratingExperience.localeCompare("Likes") === 0 ? true : false; } // tslint:disable-next-line:no-object-literal-type-assertion return { AreLikesEnabled: areLikesEnabled, AssociatedPageId: discussion[0].AssociatedPageId, Id: discussion[0].Id, Replies: await Promise.all(discussionReplies), Title: discussion[0].Title, } as IDiscussion; } else { return null; } } catch (error) { Logger.write(`[SocialModule:getDiscussionById]: ${error}`, LogLevel.Error); throw error; } } /** * Delete a reply in an existing discussion * @param replyId the item id to delete */ public async deleteReply(replyId: number): Promise<number> { try { const web = new Web(_spPageContextInfo.webAbsoluteUrl); await web.getList(this.discussionListServerRelativeUrl).items.getById(replyId).delete(); return replyId; } catch (error) { Logger.write(`[SocialModule:deleteReply]: ${error}`, LogLevel.Error); throw error; } } /** * Deletes a replies hierarchy recursively * @param rootReply the parent reply id in the list * @param deletedIds currently deleted ids */ public async deleteRepliesHierachy(rootReply: IDiscussionReply, deletedIds: number[]): Promise<number[]> { if (rootReply.Children.length > 0) { try { // Delete children await Promise.all(rootReply.Children.map(async (currentReply) => { deletedIds.push(await this.deleteReply(currentReply.Id)); await this.deleteRepliesHierachy(currentReply, deletedIds); })); } catch (error) { Logger.write(`[SocialModule:deleteRepliesHierachy]: ${error}`, LogLevel.Error); throw error; } } return deletedIds; } /** * Updates a reply * @param replyId The reply id to update * @param replyBody The new reply body */ public async updateReply(replyId: number, replyBody: string): Promise<void> { try { const web = new Web(_spPageContextInfo.webAbsoluteUrl); const result = await web.getList(this.discussionListServerRelativeUrl).items.getById(replyId).select("Modified").update({ Body: replyBody, }); return; } catch (error) { Logger.write(`[SocialModule:updateReply]: ${error}`, LogLevel.Error); throw error; } } public async getCurrentUserPermissionsOnList(listServerRelativeUrl: string): Promise<DiscussionPermissionLevel[]> { const permissionsList = []; const web = new Web(_spPageContextInfo.webAbsoluteUrl); const permissions = await web.getList(listServerRelativeUrl).getCurrentUserEffectivePermissions(); const canAddListItems = web.hasPermissions(permissions, PermissionKind.AddListItems); const canManageLists = web.hasPermissions(permissions, PermissionKind.ManageLists); if (canAddListItems) { permissionsList.push(DiscussionPermissionLevel.Add); } if (canManageLists) { permissionsList.push(DiscussionPermissionLevel.ManageLists); } return permissionsList; } public toggleLike(itemId: number, parentListId: string, isLiked: boolean): Promise<number> { const p = new Promise<number>((resolve, reject) => { const context = SP.ClientContext.get_current(); Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, parentListId, itemId, isLiked); context.executeQueryAsync((sender, args) => { const result = sender["$15_0"] ? sender["$15_0"] : (sender["$1L_0"] ? sender["$1L_0"] : null); if (result) { // According the specs, the server method retunrs the updated likes count const likesCount = Object.keys(result).map((key) => { return result[key]; })[0].get_value(); resolve(likesCount); } else { resolve(null); } }, (sender, args) => { Logger.write(`[SocialModule:toggleLike]: ${args.get_message()}`, LogLevel.Error); reject(args.get_message()); }); }); return p; } /** * Gets the current user permnissions on a reply * @param itemId the item id * @param replyAuthorLoginName the reply auhtor name (to check if the current user is the actual author) */ private async getCurrentUserPermissionsOnItem(itemId: number, replyAuthorLoginName: string): Promise<DiscussionPermissionLevel[]> { const permissionsList = []; const web = new Web(_spPageContextInfo.webAbsoluteUrl); const permissions = await web.getList(this.discussionListServerRelativeUrl).items.getById(itemId).getCurrentUserEffectivePermissions(); const canAddListItems = web.hasPermissions(permissions, PermissionKind.AddListItems); const canEditListItems = web.hasPermissions(permissions, PermissionKind.EditListItems); const canDeleteListItems = web.hasPermissions(permissions, PermissionKind.DeleteListItems); const canManageLists = web.hasPermissions(permissions, PermissionKind.ManageLists); if (canManageLists) { permissionsList.push(DiscussionPermissionLevel.ManageLists); permissionsList.push(DiscussionPermissionLevel.Delete); permissionsList.push(DiscussionPermissionLevel.Edit); } if ((canEditListItems && !canManageLists) || (canDeleteListItems && !canManageLists)) { pnp.storage.local.deleteExpired(); // The "WriteSecurity" property isn't availabe through REST with SharePoint 2013. In this case, we need to get the whole list XML schema to extract this info // Not very efficient but we do not have any other option here // Not List Item Level Security is different than item permissions so we can't rely on native REST methods (i.e. getCurrentUserEffectivePermissions()) const writeSecurityStorageKey = String.format("{0}_{1}", _spPageContextInfo.webServerRelativeUrl, "commentsListWriteSecurity"); let writeSecurity = pnp.storage.local.get(writeSecurityStorageKey); if (!writeSecurity) { const list = await web.getList(this.discussionListServerRelativeUrl).select("SchemaXml").get(); // tslint:disable-next-line:radix writeSecurity = parseInt(/WriteSecurity="(\d)"/.exec(list.SchemaXml)[1]); pnp.storage.local.put(writeSecurityStorageKey, writeSecurity, pnp.util.dateAdd(new Date(), "minute", 60)); } // 2 = Create items and edit items that were created by the user if (writeSecurity === 2) { const userLoginNameStorageKey = String.format("{0}_{1}", _spPageContextInfo.webServerRelativeUrl, "currentUserLoginName"); let currentUserLoginName = pnp.storage.local.get(userLoginNameStorageKey); if (!currentUserLoginName) { const currentUser = await web.currentUser.select("LoginName").get(); currentUserLoginName = currentUser.LoginName; pnp.storage.local.put(userLoginNameStorageKey, currentUserLoginName, pnp.util.dateAdd(new Date(), "minute", 20)); } // If the current user is the author of the comment if (replyAuthorLoginName === currentUserLoginName) { if (canEditListItems) { permissionsList.push(DiscussionPermissionLevel.EditAsAuthor); } if (canDeleteListItems) { permissionsList.push(DiscussionPermissionLevel.DeleteAsAuthor); } } } else { if (canDeleteListItems) { permissionsList.push(DiscussionPermissionLevel.Delete); } if (canEditListItems) { permissionsList.push(DiscussionPermissionLevel.Edit); } } } if (canAddListItems) { permissionsList.push(DiscussionPermissionLevel.Add); } return permissionsList; } private async getUserProperties(accountName: string): Promise<any> { pnp.storage.local.deleteExpired(); const authorPropertiesStorageKey = String.format("{0}_{1}", _spPageContextInfo.webServerRelativeUrl, accountName); let authorProperties = pnp.storage.local.get(authorPropertiesStorageKey); if (!authorProperties) { try { // Get user detail authorProperties = await pnp.sp.profiles.select("AccountName", "PictureUrl", "DisplayName", "Email").getPropertiesFor(accountName); pnp.storage.local.put(authorPropertiesStorageKey, authorProperties, pnp.util.dateAdd(new Date(), "minute", 60)); } catch (error) { Logger.write(`[SocialModule:getUserProperties]: ${error}`, LogLevel.Error); } } return authorProperties; } } export default SocialModule;
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * In Cloud Firestore, the unit of storage is the document. A document is a lightweight record * that contains fields, which map to values. Each document is identified by a name. * * To get more information about Document, see: * * * [API documentation](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) * * How-to Guides * * [Official Documentation](https://cloud.google.com/firestore/docs/manage-data/add-data) * * > **Warning:** This resource creates a Firestore Document on a project that already has * Firestore enabled. If you haven't already enabled it, you can create a * `gcp.appengine.Application` resource with `databaseType` set to * `"CLOUD_FIRESTORE"` to do so. Your Firestore location will be the same as * the App Engine location specified. * * ## Example Usage * ### Firestore Document Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const mydoc = new gcp.firestore.Document("mydoc", { * collection: "somenewcollection", * documentId: "my-doc-%{random_suffix}", * fields: "{\"something\":{\"mapValue\":{\"fields\":{\"akey\":{\"stringValue\":\"avalue\"}}}}}", * project: "my-project-name", * }); * ``` * ### Firestore Document Nested Document * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const mydoc = new gcp.firestore.Document("mydoc", { * collection: "somenewcollection", * documentId: "my-doc-%{random_suffix}", * fields: "{\"something\":{\"mapValue\":{\"fields\":{\"akey\":{\"stringValue\":\"avalue\"}}}}}", * project: "my-project-name", * }); * const subDocument = new gcp.firestore.Document("sub_document", { * collection: pulumi.interpolate`${mydoc.path}/subdocs`, * documentId: "bitcoinkey", * fields: "{\"something\":{\"mapValue\":{\"fields\":{\"ayo\":{\"stringValue\":\"val2\"}}}}}", * project: "my-project-name", * }); * const subSubDocument = new gcp.firestore.Document("sub_sub_document", { * collection: pulumi.interpolate`${subDocument.path}/subsubdocs`, * documentId: "asecret", * fields: "{\"something\":{\"mapValue\":{\"fields\":{\"secret\":{\"stringValue\":\"hithere\"}}}}}", * project: "my-project-name", * }); * ``` * * ## Import * * Document can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:firestore/document:Document default {{name}} * ``` */ export class Document extends pulumi.CustomResource { /** * Get an existing Document 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?: DocumentState, opts?: pulumi.CustomResourceOptions): Document { return new Document(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:firestore/document:Document'; /** * Returns true if the given object is an instance of Document. 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 Document { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Document.__pulumiType; } /** * The collection ID, relative to database. For example: chatrooms or chatrooms/my-document/private-messages. */ public readonly collection!: pulumi.Output<string>; /** * Creation timestamp in RFC3339 format. */ public /*out*/ readonly createTime!: pulumi.Output<string>; /** * The Firestore database id. Defaults to `"(default)"`. */ public readonly database!: pulumi.Output<string | undefined>; /** * The client-assigned document ID to use for this document during creation. */ public readonly documentId!: pulumi.Output<string>; /** * The document's [fields](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) formated as a json string. */ public readonly fields!: pulumi.Output<string>; /** * A server defined name for this index. Format: * 'projects/{{project_id}}/databases/{{database_id}}/documents/{{path}}/{{document_id}}' */ public /*out*/ readonly name!: pulumi.Output<string>; /** * A relative path to the collection this document exists within */ public /*out*/ readonly path!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * Last update timestamp in RFC3339 format. */ public /*out*/ readonly updateTime!: pulumi.Output<string>; /** * Create a Document 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: DocumentArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: DocumentArgs | DocumentState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as DocumentState | undefined; inputs["collection"] = state ? state.collection : undefined; inputs["createTime"] = state ? state.createTime : undefined; inputs["database"] = state ? state.database : undefined; inputs["documentId"] = state ? state.documentId : undefined; inputs["fields"] = state ? state.fields : undefined; inputs["name"] = state ? state.name : undefined; inputs["path"] = state ? state.path : undefined; inputs["project"] = state ? state.project : undefined; inputs["updateTime"] = state ? state.updateTime : undefined; } else { const args = argsOrState as DocumentArgs | undefined; if ((!args || args.collection === undefined) && !opts.urn) { throw new Error("Missing required property 'collection'"); } if ((!args || args.documentId === undefined) && !opts.urn) { throw new Error("Missing required property 'documentId'"); } if ((!args || args.fields === undefined) && !opts.urn) { throw new Error("Missing required property 'fields'"); } inputs["collection"] = args ? args.collection : undefined; inputs["database"] = args ? args.database : undefined; inputs["documentId"] = args ? args.documentId : undefined; inputs["fields"] = args ? args.fields : undefined; inputs["project"] = args ? args.project : undefined; inputs["createTime"] = undefined /*out*/; inputs["name"] = undefined /*out*/; inputs["path"] = undefined /*out*/; inputs["updateTime"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Document.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Document resources. */ export interface DocumentState { /** * The collection ID, relative to database. For example: chatrooms or chatrooms/my-document/private-messages. */ collection?: pulumi.Input<string>; /** * Creation timestamp in RFC3339 format. */ createTime?: pulumi.Input<string>; /** * The Firestore database id. Defaults to `"(default)"`. */ database?: pulumi.Input<string>; /** * The client-assigned document ID to use for this document during creation. */ documentId?: pulumi.Input<string>; /** * The document's [fields](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) formated as a json string. */ fields?: pulumi.Input<string>; /** * A server defined name for this index. Format: * 'projects/{{project_id}}/databases/{{database_id}}/documents/{{path}}/{{document_id}}' */ name?: pulumi.Input<string>; /** * A relative path to the collection this document exists within */ path?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Last update timestamp in RFC3339 format. */ updateTime?: pulumi.Input<string>; } /** * The set of arguments for constructing a Document resource. */ export interface DocumentArgs { /** * The collection ID, relative to database. For example: chatrooms or chatrooms/my-document/private-messages. */ collection: pulumi.Input<string>; /** * The Firestore database id. Defaults to `"(default)"`. */ database?: pulumi.Input<string>; /** * The client-assigned document ID to use for this document during creation. */ documentId: pulumi.Input<string>; /** * The document's [fields](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) formated as a json string. */ fields: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; }
the_stack
module Fayde.Controls { import GridUnitType = minerva.controls.grid.GridUnitType; export class Slider extends Primitives.RangeBase { private _DragValue: number = 0; static IsDirectionReversedProperty: DependencyProperty = DependencyProperty.RegisterCore("IsDirectionReversed", () => Boolean, Slider, false, (d, args) => (<Slider>d)._UpdateTrackLayout()); static IsFocusedProperty: DependencyProperty = DependencyProperty.RegisterReadOnlyCore("IsFocused", () => Boolean, Slider, false, (d, args) => (<Slider>d).UpdateVisualState()); static OrientationProperty: DependencyProperty = DependencyProperty.RegisterCore("Orientation", () => new Enum(Orientation), Slider, Orientation.Horizontal, (d, args) => (<Slider>d)._OnOrientationChanged()); IsDirectionReversed: boolean; IsFocused: boolean; Orientation: Orientation; constructor() { super(); this.DefaultStyleKey = Slider; this.SizeChanged.on(this._HandleSizeChanged, this); } private $HorizontalTemplate: FrameworkElement; private $HorizontalLargeIncrease: Primitives.RepeatButton; private $HorizontalLargeDecrease: Primitives.RepeatButton; private $HorizontalThumb: Primitives.Thumb; private $VerticalTemplate: FrameworkElement; private $VerticalLargeIncrease: Primitives.RepeatButton; private $VerticalLargeDecrease: Primitives.RepeatButton; private $VerticalThumb: Primitives.Thumb; OnApplyTemplate() { super.OnApplyTemplate(); this.$HorizontalTemplate = <FrameworkElement>this.GetTemplateChild("HorizontalTemplate", FrameworkElement); this.$HorizontalLargeIncrease = <Primitives.RepeatButton>this.GetTemplateChild("HorizontalTrackLargeChangeIncreaseRepeatButton", Primitives.RepeatButton); this.$HorizontalLargeDecrease = <Primitives.RepeatButton>this.GetTemplateChild("HorizontalTrackLargeChangeDecreaseRepeatButton", Primitives.RepeatButton); this.$HorizontalThumb = <Primitives.Thumb>this.GetTemplateChild("HorizontalThumb", Primitives.Thumb); this.$VerticalTemplate = <FrameworkElement>this.GetTemplateChild("VerticalTemplate", FrameworkElement); this.$VerticalLargeIncrease = <Primitives.RepeatButton>this.GetTemplateChild("VerticalTrackLargeChangeIncreaseRepeatButton", Primitives.RepeatButton); this.$VerticalLargeDecrease = <Primitives.RepeatButton>this.GetTemplateChild("VerticalTrackLargeChangeDecreaseRepeatButton", Primitives.RepeatButton); this.$VerticalThumb = <Primitives.Thumb>this.GetTemplateChild("VerticalThumb", Primitives.Thumb); if (this.$HorizontalThumb != null) { this.$HorizontalThumb.DragStarted.on(this._OnThumbDragStarted, this); this.$HorizontalThumb.DragDelta.on(this._OnThumbDragDelta, this); } if (this.$HorizontalLargeDecrease != null) { this.$HorizontalLargeDecrease.Click.on(function (sender, e) { this.Focus(); this.Value -= this.LargeChange; }, this); } if (this.$HorizontalLargeIncrease != null) { this.$HorizontalLargeIncrease.Click.on(function (sender, e) { this.Focus(); this.Value += this.LargeChange; }, this); } if (this.$VerticalThumb != null) { this.$VerticalThumb.DragStarted.on(this._OnThumbDragStarted, this); this.$VerticalThumb.DragDelta.on(this._OnThumbDragDelta, this); } if (this.$VerticalLargeDecrease != null) { this.$VerticalLargeDecrease.Click.on(function (sender, e) { this.Focus(); this.Value -= this.LargeChange; }, this); } if (this.$VerticalLargeIncrease != null) { this.$VerticalLargeIncrease.Click.on(function (sender, e) { this.Focus(); this.Value += this.LargeChange; }, this); } this._OnOrientationChanged(); this.UpdateVisualState(false); } OnIsEnabledChanged(e: IDependencyPropertyChangedEventArgs) { super.OnIsEnabledChanged(e); this.UpdateVisualState(); } OnMinimumChanged(oldMin: number, newMin: number) { super.OnMinimumChanged(oldMin, newMin); this._UpdateTrackLayout(); } OnMaximumChanged(oldMax: number, newMax: number) { super.OnMaximumChanged(oldMax, newMax); this._UpdateTrackLayout(); } OnValueChanged(oldValue: number, newValue: number) { super.OnValueChanged(oldValue, newValue); this._UpdateTrackLayout(); } private _HandleSizeChanged(sender, e: SizeChangedEventArgs) { this._UpdateTrackLayout(); } private _OnOrientationChanged() { var isHorizontal = this.Orientation === Orientation.Horizontal; if (this.$HorizontalTemplate != null) this.$HorizontalTemplate.Visibility = isHorizontal ? Visibility.Visible : Visibility.Collapsed; if (this.$VerticalTemplate != null) this.$VerticalTemplate.Visibility = !isHorizontal ? Visibility.Visible : Visibility.Collapsed; this._UpdateTrackLayout(); } private _UpdateTrackLayout() { var max = this.Maximum; var min = this.Minimum; var val = this.Value; var isHorizontal = this.Orientation === Orientation.Horizontal; var temp = isHorizontal ? this.$HorizontalTemplate : this.$VerticalTemplate; if (!(temp instanceof Grid)) return; var templateGrid = <Grid>temp; var isReversed = this.IsDirectionReversed; var largeDecrease: Primitives.RepeatButton; var largeIncrease: Primitives.RepeatButton; var thumb: Primitives.Thumb; if (isHorizontal) { var coldefs = templateGrid.ColumnDefinitions; largeDecrease = this.$HorizontalLargeDecrease; largeIncrease = this.$HorizontalLargeIncrease; thumb = this.$HorizontalThumb; if (coldefs && coldefs.Count === 3) { (<ColumnDefinition>coldefs.GetValueAt(0)).Width = new GridLength(1, isReversed ? GridUnitType.Star : GridUnitType.Auto); (<ColumnDefinition>coldefs.GetValueAt(2)).Width = new GridLength(1, isReversed ? GridUnitType.Auto : GridUnitType.Star); if (largeDecrease != null) Grid.SetColumn(largeDecrease, isReversed ? 2 : 0); if (largeIncrease != null) Grid.SetColumn(largeIncrease, isReversed ? 0 : 2); } } else { var rowdefs = templateGrid.RowDefinitions; largeDecrease = this.$VerticalLargeDecrease; largeIncrease = this.$VerticalLargeIncrease; thumb = this.$VerticalThumb; if (rowdefs && rowdefs.Count === 3) { (<RowDefinition>rowdefs.GetValueAt(0)).Height = new GridLength(1, isReversed ? GridUnitType.Auto : GridUnitType.Star); (<RowDefinition>rowdefs.GetValueAt(2)).Height = new GridLength(1, isReversed ? GridUnitType.Star : GridUnitType.Auto); if (largeDecrease != null) Grid.SetRow(largeDecrease, isReversed ? 0 : 2); if (largeIncrease != null) Grid.SetRow(largeIncrease, isReversed ? 2 : 0); } } if (max === min) return; var percent = val / (max - min); if (largeDecrease != null && thumb != null) { if (isHorizontal) largeDecrease.Width = Math.max(0, percent * (this.ActualWidth - thumb.ActualWidth)); else largeDecrease.Height = Math.max(0, percent * (this.ActualHeight - thumb.ActualHeight)); } } private _OnThumbDragStarted(sender, e: Primitives.DragStartedEventArgs) { this.Focus(); this._DragValue = this.Value; } private _OnThumbDragDelta(sender, e: Primitives.DragDeltaEventArgs) { var offset = 0; var isHorizontal = this.Orientation === Orientation.Horizontal; if (isHorizontal && this.$HorizontalThumb != null) { offset = e.HorizontalChange / (this.ActualWidth - this.$HorizontalThumb.ActualWidth) * (this.Maximum - this.Minimum); } else if (!isHorizontal && this.$VerticalThumb != null) { offset = -e.VerticalChange / (this.ActualHeight - this.$VerticalThumb.ActualHeight) * (this.Maximum - this.Minimum); } if (!isNaN(offset) && isFinite(offset)) { this._DragValue += this.IsDirectionReversed ? -offset : offset; var newValue = Math.min(this.Maximum, Math.max(this.Minimum, this._DragValue)); if (newValue != this.Value) this.Value = newValue; } } OnMouseEnter(e: Input.MouseEventArgs) { super.OnMouseEnter(e); if ((this.Orientation === Fayde.Orientation.Horizontal && this.$HorizontalThumb != null && this.$HorizontalThumb.IsDragging) || (this.Orientation === Fayde.Orientation.Vertical && this.$VerticalThumb != null && this.$VerticalThumb.IsDragging)) { this.UpdateVisualState(); } } OnMouseLeave(e: Input.MouseEventArgs) { super.OnMouseLeave(e); if ((this.Orientation === Fayde.Orientation.Horizontal && this.$HorizontalThumb != null && this.$HorizontalThumb.IsDragging) || (this.Orientation === Fayde.Orientation.Vertical && this.$VerticalThumb != null && this.$VerticalThumb.IsDragging)) { this.UpdateVisualState(); } } OnMouseLeftButtonDown(e: Input.MouseButtonEventArgs) { super.OnMouseLeftButtonDown(e); if (e.Handled) return; e.Handled = true; this.Focus(); this.CaptureMouse(); } OnLostMouseCapture(e: Input.MouseEventArgs) { super.OnLostMouseCapture(e); this.UpdateVisualState(); } OnKeyDown(e: Input.KeyEventArgs) { super.OnKeyDown(e); if (e.Handled) return; if (!this.IsEnabled) return; switch (e.Key) { case Input.Key.Left: case Input.Key.Down: this.Value += (this.IsDirectionReversed ? this.SmallChange : -this.SmallChange); break; case Input.Key.Right: case Input.Key.Up: this.Value += (this.IsDirectionReversed ? -this.SmallChange : this.SmallChange); break; case Input.Key.Home: this.Value = this.Minimum; break; case Input.Key.End: this.Value = this.Maximum; break; } } OnGotFocus(e: RoutedEventArgs) { super.OnGotFocus(e); this.SetValueInternal(Slider.IsFocusedProperty, true); } OnLostFocus(e: RoutedEventArgs) { super.OnLostFocus(e); this.SetValueInternal(Slider.IsFocusedProperty, false); } } Fayde.CoreLibrary.add(Slider); TemplateVisualStates(Slider, { GroupName: "CommonStates", Name: "Normal" }, { GroupName: "CommonStates", Name: "MouseOver" }, { GroupName: "CommonStates", Name: "Disabled" }, { GroupName: "FocusStates", Name: "Unfocused" }, { GroupName: "FocusStates", Name: "Focused" }); TemplateParts(Slider, { Name: "HorizontalTemplate", Type: FrameworkElement }, { Name: "HorizontalThumb", Type: Primitives.Thumb }, { Name: "HorizontalTrackLargeChangeIncreaseRepeatButton", Type: Primitives.RepeatButton }, { Name: "HorizontalTrackLargeChangeDecreaseRepeatButton", Type: Primitives.RepeatButton }, { Name: "VerticalTemplate", Type: FrameworkElement }, { Name: "VerticalThumb", Type: Primitives.Thumb }, { Name: "VerticalTrackLargeChangeIncreaseRepeatButton", Type: Primitives.RepeatButton }, { Name: "VerticalTrackLargeChangeDecreaseRepeatButton", Type: Primitives.RepeatButton }); }
the_stack
// createHelloWorld("TW1-"); // createApplesGrow("TW4-"); createMineRocks("TW5-"); createPushBoxes("TW6-"); createEatDots("TW7-"); createSwapSprites("TW8-"); // createChangeBug("TW2-"); // createCatsDogsAndSnakes("TW2-"); // createSideScroller("TW8-"); createSkeletonDungeon("TW1-"); // createDescendingAliens("TW8-"); // createSortingDiamonds("TW8-"); // createPaint("TW8-"); createLeftHandRule("TW4-"); // -------------------------------------- function createMineRocks(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 108 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0f17120f17120f171204112f12120f17120f17120f171203122f121205132e1201132f131 20f171203132f11120f17120f171205132e120322132e1205132e120f17120f17120f17120f17120 f17120f17120f17120f17120f17120f17120f17120f17120f171f0a0`); // buffer length = 73 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffffffffffffbf10ffffffffffff4f21ff9f2112ff2f1221ffffff2f2112ffffffffbf31ff1f 21122f111211ff6f31ffffffffffffffffffffffffffffffffffffffffffffff6f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 147 settings.writeBuffer(prefix+"BackI0", hex` 1010fd181d363826181618161816181d2618361816181618161816181d1618163826181618161816 181d1816281d28561816181d1816183d1876181d1816281d2876181d1618163886181d2618361866 281d26181618164826381d2618161816181628261816181d2618161816182618261816181d261816 1816182618261816181d261816181618162826381d48163866f828`); // buffer length = 112 settings.writeBuffer(prefix+"BackI1", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); // buffer length = 55 settings.writeBuffer(prefix+"BackI2", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 35 settings.writeBuffer(prefix+"BackI3", hex` 1010bd21ed217d1bcd21ed21fd6d1bfd5d11fdfd8d2bed2bfdfd8d1b4d1bfded1bfd1d`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 120 settings.writeBuffer(prefix+"SpriteI1", hex` 1010804ca02c1b1c1b2c901c1d2b1c1b2c603c2d1b1c1b2c303c2b1c1b2d4c201c1b2d3b1c2d1b3c 201c5d3b1d1b4c101b5d3b1d1b2c1b1c101b5d3b1d2b1c2b1c1b6d2b1d1b1d1c2b1c101b5d2b1d1b 1d1c2b1c201b4d1b1d2b1d1c2b1c201b3d2b1d1b1d3b1c407b1d1c2b1c701b3d2c1b1c902b2c2b30 `); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); // buffer length = 101 settings.writeBuffer(prefix+"SpriteI3", hex` 10106057a01730373fb0271c111d1f408f1b1c1f302f5d1b1c1f211d1f101f1b513d1f1b1c1f201f 611d1b1c1b1c111d2f812f1d3f101f811d111b3f101f811d213f101f812f1b3f201f611d1b1c1d3f 201f1b513d3f402f5d1b1c1f807f1cc01f1c1b1f40`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 20262200011623030c060002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 4120220014143210ff060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB4", hex` 41202200141332103c060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB5", hex` 222622000102230010140300`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB7", hex` 414122001416320014042110ff063110ff060000`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB8", hex` 322022001403320001160401`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB9", hex` 6310220010160400`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 21212200141232103c060003`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB6", hex` 203122000116230004163305140600020002`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB10", hex` 2016220001160102`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB13", hex` 222122001412230554060004`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB1", hex` 2031220001162300041633103c0600020003`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB12", hex` 6110220001160102`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB14", hex` 222122000112230004060004`); settings.writeNumber(prefix+"PlayerN",0); } function createApplesGrow(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 109 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0f17120f17120f17120f17120f17120f17120f17120f17120f17120a122a1209142912081 52912081529120815291209132a120f17120f17120f17120f17120f171204122f111203142f12031 42f1203132f111204122f11120f17120f17120f17120f17120f171f0a0`); // buffer length = 70 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffffffffffffffffbf12ffffaf11ff8f11ff8f10ffbf12ffffffcf12ff2f12ffffffff3f12ff ffffffffffaf12ffbf12ffffffffffffffff4f12ffffffff12ffffffff6f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 55 settings.writeBuffer(prefix+"BackI1", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI0", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 107 settings.writeBuffer(prefix+"SpriteI1", hex` 1010a02c2fb01c16372c801c272c16111c701c1627161c1f2c701c37361f1c701c37361f1c701c37 161c1f111c701c372c162c404c16671c302c361c57161c301c27262c16371f1c201c37462c2f161c 201c273c761c201c171c201c661c301c161c302c461c302c505c20`); // buffer length = 71 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0502c6e70ae603e523e403e821e402ea21e303e921e303c92142027161c921420172ea21430 121e247214123022251462141e401214151452141260622412701e621ef050`); // buffer length = 35 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0f0f0f0f0801e8012602e7012602c12601260161c828072901452f0f0f0f0f0a0`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB1", hex` 212622000412230005020002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 212622000412120005010001`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 212622000412320005030003`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB5", hex` 2016220001160002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB7", hex` 222622000112231104060401`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB9", hex` 21262200040221004c36030002010002`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB0", hex` 4110220005140002`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB4", hex` 4116220001120002`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB10", hex` 2226220001322300102605010202040203000203`); settings.writeNumber(prefix+"PlayerN",0); } function createSwapSprites(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 83 settings.writeBuffer(prefix+"WBackM", hex` 2018b0d1109110d1109110d1109110d1109110d1109110d1109110d1109110d1109110d1109110d1 109110d1109110d1109110d1b0f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1 f1f1a1`); // buffer length = 138 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffaf13111223121122ff1213211311131112ff1211231112111211ff1113111213111223ff10 12132113121112ff131211121311131211ff13111211221123ff222311231211ff221311232112ff 1113111213112213ff2213111213111213ff1113121112231112ffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffff5f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 55 settings.writeBuffer(prefix+"BackI1", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 112 settings.writeBuffer(prefix+"BackI2", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); // buffer length = 53 settings.writeBuffer(prefix+"BackI3", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 71 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0f0707f801f751f601f951f501f353f351f501f251f301f251f501f251f301f251f501f251f 301f251f501f251f301f251f501f353f351f501f951f601f751f807ff0f060`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); // buffer length = 120 settings.writeBuffer(prefix+"SpriteI2", hex` 1010804ca02c1b1c1b2c901c1d2b1c1b2c603c2d1b1c1b2c303c2b1c1b2d4c201c1b2d3b1c2d1b3c 201c5d3b1d1b4c101b5d3b1d1b2c1b1c101b5d3b1d2b1c2b1c1b6d2b1d1b1d1c2b1c101b5d2b1d1b 1d1c2b1c201b4d1b1d2b1d1c2b1c201b3d2b1d1b1d3b1c407b1d1c2b1c701b3d2c1b1c902b2c2b30 `); // buffer length = 89 settings.writeBuffer(prefix+"SpriteI3", hex` 1010506c802c7e12501cae12404e523e12204e821e12203ea21e12104e921e121e4c92141e1c2716 1c92141e272ea2141e101e121e247214121e101e22251462141e301e121415145214121e301e7224 121e502e622e806e50`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 32 settings.writeBuffer(prefix+"RuleB0", hex` 6143220040242100401423004024120000260300010103000300010106000402`); // buffer length = 34 settings.writeBuffer(prefix+"RuleB1", hex` 61432200102421001024230010241200002603000101030001010300010106000402`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB2", hex` 6130220054163204fc061200001600030600`); // buffer length = 34 settings.writeBuffer(prefix+"RuleB3", hex` 61432200042423000424210004241200002603000101030001010300010106000402`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB7", hex` 202622080116231000060002`); // buffer length = 24 settings.writeBuffer(prefix+"RuleB8", hex` 205622000116230400061230000621300006323000060002`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB4", hex` 412322205424212054240000010300020103`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB6", hex` 4010222001160101`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB9", hex` 4016220801160102`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB11", hex` 612322805424218054240000010100020101`); // buffer length = 24 settings.writeBuffer(prefix+"RuleB10", hex` 61502280541621c0000612c0000623c0000632c000060101`); settings.writeNumber(prefix+"PlayerN",0); } function createLeftHandRule(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 246 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0e11071201160117071201110411011105110712011101120111011501110712011102110 11101110113011107120114011104120111071206110112011201110719011201120111071201110 71101120111071201140114011201110712041101110412011107120112011101120114011107120 11201110211011101120111071201120114011101120111071201120411011104110712011201140 11401110712011201110911071201120111011701110712011201110211041101110712011201110 112011201110111071201170114011107120e11071f020f1f11120f17120f17120f17120f17120f1 7120f171f0a0`); // buffer length = 67 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffff8f10ffffffffffaf11ffffffffffffcf11ffff8f21ffffffaf11ff8f11ff4f11ffffffff ffffffdf115f11ffffbf11ffffffffffffffffffffffffffffff8f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 53 settings.writeBuffer(prefix+"BackI1", hex` 101015f7f71715471637155715472516e72516b725f725f71725d7251647158715165725d7151715 c725167715571516f7f7f75725`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); // buffer length = 113 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0c01c111b605f101f111b1f402f3d1b1c2f211b301f1b313d1b1f111b1f301f411d1b1c112c 111f201f612f111d1b1f301f611d211b1f401f611d311b401f612f111b2f401f411d1b1c111d1c11 1b301f1b313d1b1f111b1f402f3d1b1c2f211b605f101f111b1fc01f1c111bf030`); // buffer length = 43 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0f0f0f0f0f0b0153015a01514151015141580151410141514101415701430143014f0f0f0f0 f0f0a0`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 412022000114120400060001`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB1", hex` 41362200011121010006120400060001`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB2", hex` 11362200011131010006210400060000`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB3", hex` 1146220001111201000621010006230400060002`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB4", hex` 1146220001112101000612010006230100060003`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB5", hex` 3226220001133200041604020300`); settings.writeNumber(prefix+"PlayerN",0); } function createSortingDiamonds(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 140 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a071101110c12071101110c12071101110c120511011101110c120311031101110c1101311 10311011101110c120311031101110c120511011101110c12071101110c12071101110c120711011 10c1c0c120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f171 20f17120f17120f17120f17120f17120f171f0a0`); // buffer length = 55 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffffffffffffffffff9f13ffffffffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffff8f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 53 settings.writeBuffer(prefix+"BackI1", hex` 101015f7f71715471637155715472516e72516b725f725f71725d7251647158715165725d7151715 c725167715571516f7f7f75725`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 68 settings.writeBuffer(prefix+"SpriteI1", hex` 1010c02cd03cc04cc01f3cb01e1f3ca01c1e1f1e2c802e1c121c3e702e121c121c122e7012241e12 1e32803e141e32a02e1f32b01e1f2412c01e2214c02e22d03ee02e20`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI2", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",1); settings.writeNumber(prefix+"HighN",undefined); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 412022004014320400060003`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB1", hex` 4140220040133201000633040006310400060002`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB2", hex` 3140220040133201000633040006310400060000`); // buffer length = 22 settings.writeBuffer(prefix+"RuleB3", hex` 31402200402331010006320100063301000605030203`); settings.writeNumber(prefix+"PlayerN",0); } function createEatDots(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 247 settings.writeBuffer(prefix+"WBackM", hex` 201880111012b0211061101110111011103110311021101120111011101110111011101110311011 10211011201110113011301130111011102110f13110111021101120115011301110113011102110 11203110711031101110211041103110131011103110311021401130113311301130111021104110 3110131011103110311021101120311071103110111021101120115011301110113011102110f131 10111021101120111011301130113011101110211011201110111011101110111011103110111021 106110111011101110311031102180111012101190c110f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1 f1f1f1f1f1f141`); // buffer length = 185 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffaf613f113f311f314f112f111f113f113f111f311f114f112f111f113f113f113f111f114f f1311f114f112f115f113f111f113f114f112f316f211f311f114f411f212f123f311f317f114f12 1f124f103f114f411f212f123f311f314f112f316f211f311f114f112f115f113f111f113f114ff1 311f114f112f111f113f113f113f111f114f112f111f113f113f111f311f114f613f113f311f31ff ffffffffffffffffffffffffffffffffffffffffffffffffcf`); settings.writeNumber(prefix+"BackN",4); // buffer length = 93 settings.writeBuffer(prefix+"BackI0", hex` 1010ff4fa85f18af183f183f683f182f182f186f182f182f181f188f181f182f181f188f181f182f 181f188f181f182f181f188f181f182f181f188f181f182f181f188f181f182f182f186f182f182f 183f683f183f18af185fa8ff4f`); // buffer length = 20 settings.writeBuffer(prefix+"BackI1", hex` 1010ffffffffffffffffffffffffffffffffff1f`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e152f142e3f302f1e152f251d1e151214 4f121e151f1e251d141512143f12131e151f1e142d14351f101f221e151f1e142d14351f102f121e 151f1e251d141512142f102f1e152f251d1e1512142f103f1e152f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 23 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f0f0f0f0f0f0d025d045c045d025f0f0f0f0f0f0d0`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI2", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",950); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 202622000116231400060002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB2", hex` 2226220001022300042603000402`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB3", hex` 20202220013621040006030005020200`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB4", hex` 00202220013623040006030005020200`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB6", hex` 2146220010121201000623040006320100060002`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB7", hex` 2146220010122301000612010006320400060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB8", hex` 212622001014120400060001`); // buffer length = 20 settings.writeBuffer(prefix+"RuleB9", hex` 2146220010123201000623010006120400060001`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB10", hex` 21362200101223040006320400060002`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB11", hex` 21362200101223040006320400060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB12", hex` 222622001012230001060401`); settings.writeNumber(prefix+"PlayerN",0); } function createDescendingAliens(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 93 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0f17120f17120f17120f17120f17120f17120f17120f17120f17190f190f120f17120f171 20f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120 f17120f17120f17120f171f0a0`); // buffer length = 61 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffaf12ffffff2f12ffffff2f124f10ffffcf12ffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffdf`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 55 settings.writeBuffer(prefix+"BackI1", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 68 settings.writeBuffer(prefix+"SpriteI0", hex` 1010c02cd03cc04cc01f3cb01e1f3ca01c1e1f1e2c802e1c121c3e702e121c121c122e7012241e12 1e32803e141e32a02e1f32b01e1f2412c01e2214c02e22d03ee02e20`); // buffer length = 71 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f0f0707f801f751f601f951f501f353f351f501f251f301f251f501f251f301f251f501f251f 301f251f501f251f301f251f501f353f351f501f951f601f751f807ff0f060`); // buffer length = 113 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0c01c111b605f101f111b1f402f3d1b1c2f211b301f1b313d1b1f111b1f301f411d1b1c112c 111f201f612f111d1b1f301f611d211b1f401f611d311b401f612f111b2f401f411d1b1c111d1c11 1b301f1b313d1b1f111b1f402f3d1b1c2f211b605f101f111b1fc01f1c111bf030`); // buffer length = 43 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0f0f0f0f0f0b0153015a01514151015141580151410141514101415701430143014f0f0f0f0 f0f0a0`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 202122000116230300060002`); // buffer length = 10 settings.writeBuffer(prefix+"RuleB1", hex` 10102200012602030001`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB2", hex` 1110220040110001`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 122022004011120100060300`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB4", hex` 4110220010140002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB5", hex` 212122001012230100060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB6", hex` 212122001013230100060000`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB7", hex` 312022001010210400060000`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB8", hex` 022122001010210001060401`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB9", hex` 122022004001120010160300`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB10", hex` 6110220090160300`); settings.writeNumber(prefix+"PlayerN",0); } function createPushBoxes(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 121 settings.writeBuffer(prefix+"WBackM", hex` 2018118041b011101210123110e13011302110e120311011121110e1204112111210e12021124110 e170121110e1105140e110f18110f18110f18110f18120f17120f17120f17120f17120f17120f171 20f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f171f0 a0`); // buffer length = 64 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffff11ff4f10ff8f113f13ff5f211f11ff8f11ffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffbf`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 55 settings.writeBuffer(prefix+"BackI1", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 61 settings.writeBuffer(prefix+"BackI2", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f176c4f3c1f375c7f573c8f572c8f2c375f1c4f4c 175f3c3f5c4f4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 65 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f020ee20ee202e844e202e745e202e643e142e202e543e242e202e443e342e202e343e442e20 2e243e542e202e143e642e205e742e205e742e20ee20eef020`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI2", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 2026220001162314cc060002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB1", hex` 2026220001162300441600020002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 322622004413320144060004`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 322622000113320044060004`); // buffer length = 10 settings.writeBuffer(prefix+"RuleB4", hex` 61102220042603000203`); // buffer length = 10 settings.writeBuffer(prefix+"RuleB5", hex` 61102208402603000201`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB6", hex` 6310220004160400`); settings.writeNumber(prefix+"PlayerN",0); } function createHelloWorld(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 117 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0f17120f17120f17120f17150f141202110f1412021102150c1207110e1207110e120f171 20f171204110f121204110f1212041103110d12011403110d12011106110d1201110f15120f17120 f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f171f0a0`); // buffer length = 63 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffaf10ffdf11ffffffffffff11ff8f123f12ffffffffffffffffffffffffffff4f1112ffffff ffffffffffffffffffffffffffffffffffffffffffff3f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 53 settings.writeBuffer(prefix+"BackI1", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 35 settings.writeBuffer(prefix+"BackI2", hex` 1010bd21ed217d1bcd21ed21fd6d1bfd5d11fdfd8d2bed2bfdfd8d1b4d1bfded1bfd1d`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 89 settings.writeBuffer(prefix+"SpriteI1", hex` 1010506c802c7e12501cae12404e523e12204e821e12203ea21e12104e921e121e4c92141e1c2716 1c92141e272ea2141e101e121e247214121e101e22251462141e301e121415145214121e301e7224 121e502e622e806e50`); // buffer length = 107 settings.writeBuffer(prefix+"SpriteI2", hex` 1010a02c2fb01c16372c801c272c16111c701c1627161c1f2c701c37361f1c701c37361f1c701c37 161c1f111c701c372c162c404c16671c302c361c57161c301c27262c16371f1c201c37462c2f161c 201c273c761c201c171c201c661c301c161c302c461c302c505c20`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",1); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 202622000116230400060002`); // buffer length = 6 settings.writeBuffer(prefix+"RuleB1", hex` 201022000106`); // buffer length = 6 settings.writeBuffer(prefix+"RuleB2", hex` 201022000106`); // buffer length = 6 settings.writeBuffer(prefix+"RuleB3", hex` 201022000106`); // buffer length = 6 settings.writeBuffer(prefix+"RuleB4", hex` 401022000106`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB5", hex` 2226220001022300042603000402`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB6", hex` 222622000102230010160401`); settings.writeNumber(prefix+"PlayerN",0); } function createPaint(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 95 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120 f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f1 7120f17120f17120f17120f171f0a0`); // buffer length = 55 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffffffffffffffff4f10ffffffffffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffdf`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 53 settings.writeBuffer(prefix+"BackI1", hex` 101015f7f71715471637155715472516e72516b725f725f71725d7251647158715165725d7151715 c725167715571516f7f7f75725`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 68 settings.writeBuffer(prefix+"SpriteI1", hex` 1010c02cd03cc04cc01f3cb01e1f3ca01c1e1f1e2c802e1c121c3e702e121c121c122e7012241e12 1e32803e141e32a02e1f32b01e1f2412c01e2214c02e22d03ee02e20`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI2", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",1); settings.writeNumber(prefix+"HighN",0); // buffer length = 8 settings.writeBuffer(prefix+"RuleB0", hex` 2016220001160002`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB1", hex` 4010220001160103`); settings.writeNumber(prefix+"PlayerN",0); } function createSokoban2(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 121 settings.writeBuffer(prefix+"WBackM", hex` 2018118041b011101210123110e13011302110e120311011121110e1204112111210e12021124110 e170121110e1105140e110f18110f18110f18110f18120f17120f17120f17120f17120f17120f171 20f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f171f0 a0`); // buffer length = 64 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffff11ff4f10ff8f113f11ff5f211f11ff8f11ffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffbf`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 55 settings.writeBuffer(prefix+"BackI1", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 61 settings.writeBuffer(prefix+"BackI2", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f176c4f3c1f375c7f573c8f572c8f2c375f1c4f4c 175f3c3f5c4f4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 67 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f020ee20ee202e844e202e745e202e643e142e202e34401e242e202e3440342e202e3440342e 202e241e40342e202e143e642e205e742e205e742e20ee20eef020`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI2", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 2026220001162314cc060002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB1", hex` 2026220001162300441600020002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 322622000413320104060004`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 322622000113320044060004`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB6", hex` 6310220804160400`); settings.writeNumber(prefix+"PlayerN",0); } function createSideScroller(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 156 settings.writeBuffer(prefix+"WBackM", hex` 2018f090511310f11110511310f11110511310f11110511310f11110511310f11110511310f11110 511310f11110511310f11110511310f11110511310f11110511310f11110511310f11110511210f1 11106110f11110f18110f18110f18110f181104113f13110f181104113f131103113f141104113f1 31103113f141104113f131104113f131104113f131104113f13110f18110f1811061f030`); // buffer length = 77 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffef12ff8f12ff8f12ff8f12ff8f12ff7f1012ff8f12ff8f12ff8f12ff8f12ff8f12ff8f12ff 8f12ffffff1f13ffffffffffffffffff8f13ffffffffffffffffff8f13ffffffffffffffaf`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 55 settings.writeBuffer(prefix+"BackI1", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 112 settings.writeBuffer(prefix+"SpriteI0", hex` 101030241ec014351ea01435142e2f7014252435145f20142514251f251614251f301e7516251f50 1e45141f16251f501e45141f16252f301e7516351f20142514251f251615141f3014252435161425 1f301435142e2f24251f3014351e301f143f40241e301f251fb01f251fb03f60`); // buffer length = 112 settings.writeBuffer(prefix+"SpriteI1", hex` 1010f0201e3c1f2e2f701e1d1b131b3d1b5f201e2d1b131d1f2d121b2d1f301c5d1f1d122d1f501f 5d1b122d1f501f1b4d1b122d2f301c5d1f1d123d1f201e2d1b131d1f2d121d1b1f301e1d1b131b3d 121b2d1f301e3c1f2e2f2b2d1fb01f1b3f801b3f1d1fa01f3d1b1fa01b4ff050`); // buffer length = 71 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0f0707f801f751f601f951f501f353f351f501f251f301f251f501f251f301f251f501f251f 301f251f501f251f301f251f501f353f351f501f951f601f751f807ff0f060`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI3", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",280); // buffer length = 8 settings.writeBuffer(prefix+"RuleB0", hex` 6110220040160000`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB1", hex` 02202200401021010026030005030203`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 402022000116320010060001`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 6120220001163204c0060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB4", hex` 022022004010210001060401`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB5", hex` 412622000116320040060402`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB6", hex` 612022001016214000060000`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB7", hex` 612022001046210100060300050202020000`); settings.writeNumber(prefix+"PlayerN",0); } function createCatsDogsAndSnakes(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 114 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a08310d1208110d1208110d1208110d1208110d1208110d1208110d1208110d1208110d120 11621110d1208210d1208210d1208210d12011621110d1208110d1208310d1b0d120f17120f17120 f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f171f0a0`); // buffer length = 78 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffffff7f12ff6f124f12ff4f121f12ff9f12ffffff10ffffffffffff4f11ff7f111f111f111f 11ff1f115f11ff6f11ffffffffffffffffffffffffffffffffffffffffffffffffffffffff6f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 112 settings.writeBuffer(prefix+"BackI1", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 35 settings.writeBuffer(prefix+"BackI3", hex` 1010bd21ed217d1bcd21ed21fd6d1bfd5d11fdfd8d2bed2bfdfd8d1b4d1bfded1bfd1d`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 112 settings.writeBuffer(prefix+"SpriteI0", hex` 101030241ec014351ea01435142e2f7014252435145f20142514251f251614251f301e7516251f50 1e45141f16251f501e45141f16252f301e7516351f20142514251f251615141f3014252435161425 1f301435142e2f24251f3014351e301f143f40241e301f251fb01f251fb03f60`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI1", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); // buffer length = 112 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0201e3c1f2e2f701e1d1b131b3d1b5f201e2d1b131d1f2d121b2d1f301c5d1f1d122d1f501f 5d1b122d1f501f1b4d1b122d2f301c5d1f1d123d1f201e2d1b131d1f2d121d1b1f301e1d1b131b3d 121b2d1f301e3c1f2e2f2b2d1fb01f1b3f801b3f1d1fa01f3d1b1fa01b4ff050`); // buffer length = 71 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0f0707f801f751f601f951f501f353f351f501f251f301f251f501f251f301f251f501f251f 301f251f501f251f301f251f501f353f351f501f951f601f751f807ff0f060`); settings.writeNumber(prefix+"HelpN",0); settings.writeNumber(prefix+"HighN",80); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 202622000116230300060002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB1", hex` 2026220001162300101600020002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 222622001012230100060004`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB4", hex` 222622001012230010060004`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB5", hex` 4010220001160203`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB6", hex` 6110220040160002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB8", hex` 412022000414211000060000`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB9", hex` 4120220004102104ff1600020102`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB10", hex` 012022000410211000060000`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB11", hex` 012022000412231000060002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB7", hex` 2220220040122310001603000101`); // buffer length = 16 settings.writeBuffer(prefix+"RuleB12", hex` 61302200101623100006210300060000`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB13", hex` 222022001012234000060402`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB3", hex` 222622000112231000060004`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB14", hex` 6316220810160400`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB15", hex` 222622001112230004060401`); settings.writeNumber(prefix+"PlayerN",0); } function createChangeBug(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 119 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a03110f131203110f131203110f131203110f131203110f131203110f131203110f1312031 10f131203110f131203110f131203110f131203110f13160f13120f17120f17120f17120f17120f1 7120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f17120f171f0a0`); // buffer length = 57 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffffffffffffffff3f10ff8f11ffffffffffffffffffffffffffffffffffffffffffffffffff ffffffffffffffffffffffffffffffff5f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 53 settings.writeBuffer(prefix+"BackI1", hex` 101015f7f71715471637155715472516e72516b725f725f71725d7251647158715165725d7151715 c725167715571516f7f7f75725`); // buffer length = 53 settings.writeBuffer(prefix+"BackI2", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 112 settings.writeBuffer(prefix+"BackI3", hex` 10101f6e3f1e2f2e1f2e342e1f5e1f3e544e341e1f2e642e541e1f2e541e743e541e741e1f2e342e 742e1f3e1f1e1f1e541e1f1e4f3e1f1e341e1f2e2f2e345e1f1e142e1f1e541e1f1e1f1e341e1f1e 542e1f1e441e1f1e641e1f1e443e641e1f2e342e1f1e347e144e1f4e2f1e1f3e`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 141 settings.writeBuffer(prefix+"SpriteI1", hex` 1010902fa05f1b1f702f234b3e401f1b333b1f1e142f201f1e231e2f1e3f1c1b1f101f15141e131b 1f1b11141f1b2d112f141514231e2f141e2d1b1d1f142514133e241e3d111b142514133e241e2d1b 1d1b1f141514231e2f141e3d112f15141e131b1f1b11141f1b1d1b1d1f101f1e231e2f1e3f1c1b1f 301f1b333b1f1e142f402f234b3e705f1b1fd02f50`); // buffer length = 112 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0201e3c1f2e2f701e1d1b131b3d1b5f201e2d1b131d1f2d121b2d1f301c5d1f1d122d1f501f 5d1b122d1f501f1b4d1b122d2f301c5d1f1d123d1f201e2d1b131d1f2d121d1b1f301e1d1b131b3d 121b2d1f301e3c1f2e2f2b2d1fb01f1b3f801b3f1d1fa01f3d1b1fa01b4ff050`); // buffer length = 123 settings.writeBuffer(prefix+"SpriteI3", hex` 1010b01c2f502c2f301c21161f301c16371f101c1731161c101c271c16271f27412c1627161f271c 22412c3726271c37312c3726271c2726212c37161f17161c171c1f26112c371c16171c17161f2c16 112c16773c361c101c67161f561c201c1637161f27461f302c3f37261c1f801c27161c2fa01c171c e02c50`); settings.writeNumber(prefix+"HelpN",1); settings.writeNumber(prefix+"HighN",NaN); // buffer length = 8 settings.writeBuffer(prefix+"RuleB0", hex` 4010220001160001`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB1", hex` 122022000111120100060004`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 612022000116320400060003`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB3", hex` 4110220004140001`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB4", hex` 412022000414320400060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB5", hex` 122022000411120100060004`); settings.writeNumber(prefix+"PlayerN",0); } function createSkeletonDungeon(prefix: string) { if (settings.exists(prefix+"VersionS")) return; settings.writeString(prefix+"VersionS","4.0.0"); // buffer length = 200 settings.writeBuffer(prefix+"WBackM", hex` 2018f0a0131032403220624013104220422062406221422062115042204220627022304220429022 30422032903230422032804230422032803240422042703240422052604220524042603230425042 60223042604240324022803240322052406240323042208230324042208230423042208230423042 20428022304230421032402220523082303240422042103220521062204210322052205220421032 2052304220421032205230428012403230522072403220622182303230522082402240425052f0a0 `); // buffer length = 77 settings.writeBuffer(prefix+"WSpriteM", hex` 2018ffdf21ffffdf10ffffff6f12ff7f12ff8f12ffffffffffff3f12ef12ffffff4f12ffffffffff ffcf12ffffffffffef12ffff12ffffff1f12ffffff3f13bf125f12ffffdf124f12ffffff4f`); settings.writeNumber(prefix+"BackN",4); // buffer length = 94 settings.writeBuffer(prefix+"BackI0", hex` 10101b6d1c1b6d1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d7b 1d7b6c1b1a6c1b1a1b6d1c1b6d1b1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c1d6b1c106b1c1d6b1c1d6b 1c1d6b1c1d7b1d6b7c1b1a6c1b1a`); // buffer length = 53 settings.writeBuffer(prefix+"BackI1", hex` 101017f6f61617461836175617462718e62718b627f627f61627d6271846178617185627d6171617 c627187617561718f6f6f65627`); // buffer length = 55 settings.writeBuffer(prefix+"BackI2", hex` 1010ff3f3ccf5c4f3c4f6c2f5c4f5c1f7c3f5c1f7c4f3c2f7caf5ccf3c8f3c7f1c4f5c5f3c3f5c4f 4c3f6c3f4c3f6c4f3c4f3c7f1cff1f`); // buffer length = 68 settings.writeBuffer(prefix+"BackI3", hex` 10101ff0d01f6052501f408270324132602211431132502211531132502211531132502211531122 4022115311323022115311324022114311325032413270829052f080`); settings.writeNumber(prefix+"SpriteN",4); // buffer length = 130 settings.writeBuffer(prefix+"SpriteI0", hex` 1010f0802fa05f1e1f101e24403f1e1f3e1f141d14303f1e122f142e3f302f1e122f1b111d1e2214 4f121e121f1e2f1d1422143f12131e121f1e142d1422151f101f221e121f1e142d1422151f102f12 1e121f1e2f1d1422142f102f1e122f1b111d1e22142f103f1e122f142e3f402f2e1f3e1f141d1450 5f1e1f101e24902ff080`); // buffer length = 89 settings.writeBuffer(prefix+"SpriteI1", hex` 1010506c802c7e12501cae12404e523e12204e821e12203ea21e12104e921e121e4c92141e1c2716 1c92141e272ea2141e101e121e247214121e101e22251462141e301e121415145214121e301e7224 121e502e622e806e50`); // buffer length = 113 settings.writeBuffer(prefix+"SpriteI2", hex` 1010f0c01c111b605f101f111b1f402f3d1b1c2f211b301f1b313d1b1f111b1f301f411d1b1c112c 111f201f612f111d1b1f301f611d211b1f401f611d311b401f612f111b2f401f411d1b1c111d1c11 1b301f1b313d1b1f111b1f402f3d1b1c2f211b605f101f111b1fc01f1c111bf030`); // buffer length = 64 settings.writeBuffer(prefix+"SpriteI3", hex` 1010f0502839a0384980485960586950587940281928893018391899201839111981201829211971 301841196140184119517031194180311931a0211921f080`); settings.writeNumber(prefix+"HelpN",1); settings.writeNumber(prefix+"HighN",0); // buffer length = 12 settings.writeBuffer(prefix+"RuleB0", hex` 202622000116235000060002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB3", hex` 2026220001162300441600020002`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB4", hex` 412022001014121000060001`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB5", hex` 412022001014120100060003`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB7", hex` 412022001013321000060003`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB6", hex` 322222001003320001460300050302000102`); // buffer length = 8 settings.writeBuffer(prefix+"RuleB1", hex` 6316220001160401`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB2", hex` 222622004012230100060004`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB8", hex` 322022004003320400160102`); // buffer length = 28 settings.writeBuffer(prefix+"RuleB9", hex` 41602200401423010006210100063101000632010006330100060400`); // buffer length = 18 settings.writeBuffer(prefix+"RuleB10", hex` 203622000116210044162350000600020002`); // buffer length = 14 settings.writeBuffer(prefix+"RuleB11", hex` 3222220010133200041603000300`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB12", hex` 322622004413320144060004`); // buffer length = 12 settings.writeBuffer(prefix+"RuleB13", hex` 322622000113320044060004`); settings.writeNumber(prefix+"PlayerN",0); }
the_stack
import QlogConnection from '@/data/Connection'; import * as d3 from 'd3'; import * as qlog from '@/data/QlogSchema'; import StreamGraphDataHelper from './MultiplexingGraphDataHelper'; import MultiplexingGraphD3ByterangesRenderer from './MultiplexingGraphD3ByterangesRenderer'; import MultiplexingGraphD3WaterfallRenderer from './MultiplexingGraphD3WaterfallRenderer'; interface StreamRange { currentHead:number, // up to and including where the stream has been moved to the HTTP layer highestReceived:number, // up to where the stream has been received (with holes between currentHead and this if they're not equal) holes:Array<Range>, filled:Array<Range>, cumulativeTimeDifference:number, timeDifferenceSampleCount:number, frameCount:number, } interface Range { time: number, from: number, to: number } enum FrameArrivalType { Normal, Future, Duplicate, Retransmit, Reordered, UNKNOWN, } interface ArrivalInfo { type: FrameArrivalType, timeDifference: number, createdHole:Array<number>|undefined } export default class MultiplexingGraphD3CollapsedRenderer { public containerID:string; public axisLocation:"top"|"bottom" = "bottom"; public byteRangeRenderer!:MultiplexingGraphD3ByterangesRenderer; public waterfallRenderer:MultiplexingGraphD3WaterfallRenderer|undefined = undefined; // set from outside. FIXME: dirty! // public svgID:string; public rendering:boolean = false; protected svg!:any; protected tooltip!:any; protected connection!:QlogConnection; protected barHeight = 70; protected currentDomain:any = undefined; private dimensions:any = {}; constructor(containerID:string, byteRangeContainerID:string) { this.containerID = containerID; this.byteRangeRenderer = new MultiplexingGraphD3ByterangesRenderer(byteRangeContainerID); } public async render(connection:QlogConnection):Promise<boolean> { if ( this.rendering ) { return false; } console.log("MultiplexingGraphD3CollapsedRenderer:render", connection); this.rendering = true; const canContinue:boolean = this.setup(connection); if ( !canContinue ) { this.rendering = false; return false; } await this.renderLive(); this.rendering = false; return true; } protected setup(connection:QlogConnection){ this.connection = connection; this.connection.setupLookupTable(); const container:HTMLElement = document.getElementById(this.containerID)!; this.dimensions.margin = {top: 0, right: 40, bottom: 20, left: 20}; // this.dimensions.margin = {top: 0, right: (this.waterfallRenderer as any).dimensions.margin.right, bottom: 20, left: 20}; if ( this.axisLocation === "top" ){ this.dimensions.margin.top = 20; } else { this.dimensions.margin.bottom = 40; } // width and height are the INTERNAL widths (so without the margins) this.dimensions.width = container.clientWidth - this.dimensions.margin.left - this.dimensions.margin.right; this.dimensions.height = this.barHeight; // clear old rendering d3.select( "#" + this.containerID ).selectAll("*").remove(); this.svg = d3.select("#" + this.containerID) .append("svg") .attr("width", this.dimensions.width + this.dimensions.margin.left + this.dimensions.margin.right) .attr("height", this.dimensions.height + this.dimensions.margin.top + this.dimensions.margin.bottom) // .attr("viewBox", [0, 0, this.dimensions.width, this.dimensions.height]) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("font-family", "Trebuchet-ms") .append("g") .attr("transform", "translate(" + this.dimensions.margin.left + "," + this.dimensions.margin.top + ")"); this.tooltip = d3.select("#multiplexing-packet-tooltip") .style("opacity", 0) .style("position", "absolute") .style("padding", "5px") .style("pointer-events", "none") // crucial! .style("background", "lightsteelblue"); // this.svg.append("text") // .attr("x", 0) // .attr("y", (this.barHeight / 2)) // .attr("dominant-baseline", "central") // .style("text-anchor", "end") // .style("font-size", "12") // .style("font-family", "Trebuchet MS") // .style("font-style", "italic") // .attr("fill", "#000000") // .text("" + "COLLAPSED"); return true; } protected async renderLive() { console.log("Rendering multiplexinggraph"); const parser = this.connection.getEventParser(); // want total millisecond range in this trace, so last - first const xMSRange = parser.load(this.connection.getEvents()[ this.connection.getEvents().length - 1 ]).absoluteTime - parser.load(this.connection.getEvents()[0]).absoluteTime; console.log("DEBUG MS range for this trace: ", xMSRange); let frameCount = 1; let packetIndex = 0; const streamIDs:Set<number> = new Set<number>(); // clients receive data, servers send it let eventType = qlog.TransportEventType.packet_received; let directionText = "received"; if ( this.connection.vantagePoint && this.connection.vantagePoint.type === qlog.VantagePointType.server ){ eventType = qlog.TransportEventType.packet_sent; directionText = "sent"; } // const packets = this.connection.lookup( qlog.EventCategory.transport, eventType ); // filled[0] holes[0] filled[1] holes[1] filled[2] // .../////////////////////////////| _____ |/////////| _______ |/////////////| // ^ ^ // currentHead highestReceived // we want to keep track of the filled ranges but also the holes and then especially: when those holes become filled! // if it takes a long time for a hole to become filled, it indicates a retransmit. A short time indicates a re-order. const streamRanges:Map<number, StreamRange> = new Map<number, StreamRange>(); // approach: only tracking holes gives a difficult algorithm in practice (I tried...) // so, we do it differently: we keep track of the filled ranges and generate the holes from that on each step // we track the timestamps between the new holes and the old holes const calculateFrameArrivalType = (range:StreamRange, timestamp:number, from:number, to:number):ArrivalInfo => { // console.log("TIMESTAMP: ", timestamp, from, to, range.currentHead, range.highestReceived); // step 1: find hole where this new frame fits (if none found: this is a new packet: either Normal or Future!) // step 2: add frame to filled list // step 3: generate holes from filled list, backfilling the timestamps from the old holes let outputType = FrameArrivalType.UNKNOWN; let outputTimestampDifference = 0; let outputHole:Range|undefined = undefined; // 1. let foundHole:Range|undefined = undefined; for ( const hole of range.holes ) { // ignore if we overlap 2 holes for now if ( (from >= hole.from && from <= hole.to) || (to >= hole.from && to <= hole.to) ) { foundHole = hole; break; } } if ( !foundHole ) { // just checking to < range.currentHead only finds overlaps in the past // if we are having spurious retransmits between currentHead and highestReceived, they are found by checking overlaps in filled instead let foundFilled:Range|undefined = undefined; for ( const filled of range.filled ) { if ( (from >= filled.from && from <= filled.to) || (to >= filled.from && to <= filled.to) ) { foundFilled = filled; break; } } if ( foundFilled ) { console.error("DUPLICATE FOUND VIA FILLED!", foundFilled, from, to); return { type: FrameArrivalType.Duplicate, timeDifference: 0, createdHole: undefined }; } else if ( to < range.currentHead ) { // total duplicate, no need to update state // alert("DUPLICATE FOUND!" + from + "->" + to); // never happened in our tests console.error("calculateFrameArrivalType : duplicate data found! Not really an error, but means spurious retransmissions.", range.currentHead, from, to, timestamp); return { type: FrameArrivalType.Duplicate, timeDifference: 0, createdHole: undefined }; } else if ( from > range.highestReceived + 1 ) { // creates a hole outputType = FrameArrivalType.Future; outputHole = { time: timestamp, from: range.highestReceived + 1, to: from }; } else if ( from === range.highestReceived + 1 ){ // normal, everything arrives in-order without gaps outputType = FrameArrivalType.Normal; } else if ( to > range.highestReceived + 1 ) { // partial overlap at the end: from is < highestReceived, to is > : mark this as "normal" for now outputType = FrameArrivalType.Normal; } else { // 2 options: // a) range "spans" a hole (starts overlapping with 1 filled, then covers hole, then ends in another filled) // b) unknown situation we haven't seen before // a) // filled is sorted by .from, lowest to highest let spanning = false; for ( let i = 0; i < range.filled.length - 1; ++i ){ const filled1 = range.filled[i]; const filled2 = range.filled[i + 1]; if ( from >= filled1.from && to > filled1.to && to <= filled2.to ) { spanning = true; } } if ( spanning ){ foundHole = undefined; for ( const hole of range.holes ) { // look for the hole we're spanning if ( (from < hole.from && to > hole.to) ) { foundHole = hole; break; } } if ( foundHole ){ console.error("Found spanning frame, shouldn't happen in practice, only when debugging", foundHole, from, to, range); outputTimestampDifference = timestamp - foundHole.time; outputType = FrameArrivalType.Retransmit; } else { console.error("calculateFrameArrivalType: Spanning frame, but not hole found... very weird", from, to, range); outputType = FrameArrivalType.UNKNOWN; } } else { console.error("calculateFrameArrivalType: no hole found for frame, but also nowhere else we would expect it...", from, to, range); outputType = FrameArrivalType.UNKNOWN; } } } else { outputTimestampDifference = timestamp - foundHole.time; outputType = FrameArrivalType.Retransmit; } if ( outputType === FrameArrivalType.Retransmit ){ // TODO: maybe only decide it's a re-order if it fits perfectly in a hole? ++range.timeDifferenceSampleCount; range.cumulativeTimeDifference += outputTimestampDifference; const avg = range.cumulativeTimeDifference / range.timeDifferenceSampleCount; if ( outputTimestampDifference < 20 && outputTimestampDifference < avg * 0.3 ) { // lower than 20ms and within 30% of the current RTT estimate is -probably- reorder outputType = FrameArrivalType.Reordered; // console.log("REORDERED PACKET FOUND", foundHole, from, to, outputTimestampDifference, avg); } // else { // console.log("RETRANSMITTED PACKET FOUND", foundHole, from, to, outputTimestampDifference, avg); // } } if ( to > range.highestReceived ) { range.highestReceived = to; } // 2. // https://www.geeksforgeeks.org/merging-intervals/ // https://algorithmsandme.com/arrays-merge-overlapping-intervals/ range.filled.push ( {from: from, to: to, time: timestamp} ); range.filled.sort( (a:Range, b:Range):number => { return a.from - b.from; }); // ascending order, just the way we like it const stack = new Array<Range>(); stack.push( range.filled[0] ); for ( let i = 1; i < range.filled.length; ++i ){ const previousInterval = stack.pop(); const currentInterval = range.filled[i]; // If current interval's start time is less than end time of // previous interval, find max of end times of two intervals // and push new interval on to stack. if ( previousInterval!.to + 1 >= currentInterval.from ) { const endTime = Math.max( previousInterval!.to, currentInterval.to ); stack.push ( { from: previousInterval!.from, to : endTime, time: timestamp } ); } else { stack.push ( previousInterval! ); stack.push ( currentInterval ); } } range.filled = stack; // should also be sorted now! // console.log( "filled ranges are now ", JSON.stringify(range.filled) ); // 3. const newHoles:Array<Range> = new Array<Range>(); for ( let i = 0; i < range.filled.length - 1; ++i ) { const filled1 = range.filled[i]; const filled2 = range.filled[i + 1]; const newHole = { from: filled1.to + 1, to: filled2.from - 1, time: -666 }; let foundHole2:Range|undefined = undefined; for ( const hole of range.holes ) { // ignore if we overlap 2 holes for now if ( (newHole.from >= hole.from && newHole.from <= hole.to) || (newHole.to >= hole.from && newHole.to <= hole.to) ) { foundHole2 = hole; break; } } if ( foundHole2 ){ newHole.time = foundHole2.time; } else { newHole.time = timestamp; // new hole due to a future frame } newHoles.push ( newHole ); } range.holes = newHoles; if ( range.holes.length > 0 ) { range.currentHead = range.holes[0].from - 1; } else { range.currentHead = range.filled[ range.filled.length - 1 ].to; } // console.log("Ended arrival algorithm ", FrameArrivalType[outputType], outputTimestampDifference, range.currentHead, range.highestReceived, range.holes, range.filled ); // console.log("--------------------------------------"); return { type: outputType, timeDifference: outputTimestampDifference, createdHole: ((outputHole !== undefined) ? [outputHole.from, outputHole.to] : undefined) }; }; const dataSent:Array<any> = []; const dataMoved:Array<any> = []; for ( const eventRaw of this.connection.getEvents() ) { const event = this.connection.parseEvent( eventRaw ); const data = event.data; if ( event.name === eventType ){ // packet_sent or _received, the ones we want to plot const streamFrames = new Array<any>(); if ( data.frames && data.frames.length > 0 ){ for ( const frame of data.frames ) { if ( frame.stream_id === undefined || !StreamGraphDataHelper.isDataStream( "" + frame.stream_id )){ // skip control streams like QPACK continue; } const streamID = parseInt( frame.stream_id, 10 ); if ( frame.frame_type && frame.frame_type === qlog.QUICFrameTypeName.stream ){ streamFrames.push ( frame ); let ranges = streamRanges.get( streamID ); if ( !ranges ){ ranges = {currentHead:-1, highestReceived: -1, holes: new Array<Range>(), filled:new Array<Range>(), cumulativeTimeDifference: 0, timeDifferenceSampleCount: 0, frameCount: 0 }; streamRanges.set( streamID, ranges ); } const arrivalInfo:ArrivalInfo = calculateFrameArrivalType(ranges, event.relativeTime, parseInt(frame.offset, 10), parseInt(frame.offset, 10) + parseInt(frame.length, 10) - 1 ); ranges.frameCount += 1; dataSent.push( { streamID: streamID, packetNumber: data.header.packet_number, index: packetIndex, size: frame.length, countStart: frameCount, countEnd: frameCount + 1, arrivalType: arrivalInfo.type, arrivalTimeDifference: arrivalInfo.timeDifference, arrivalCreatedHole: arrivalInfo.createdHole, offset: parseInt(frame.offset, 10), length: parseInt(frame.length, 10), time: event.relativeTime, }); ++frameCount; ++packetIndex; streamIDs.add( streamID ); } } } } else if ( event.name === qlog.HTTP3EventType.data_moved ) { if ( !StreamGraphDataHelper.isDataStream( "" + data.stream_id )){ continue; } if ( data.from !== "transport" && data.to !== "application") { // only dealing with data bubbling up from the transport at the moment continue; } if ( dataSent.length === 0 ) { console.error("data moved but no stream frames seen yet... shouldn't happen!", data); continue; } const movedOffset = parseInt( data.offset, 10 ); const movedLength = parseInt( data.length, 10 ); if ( movedLength === 0 ) { console.error("data_moved event with length 0, shouldn't happen! ignoring...", data); continue; } // can't simply say dataSent[ dataSent.length - 1 ] is the STREAM frame we need, because multiple STREAM frames of different streams could be in a single packet // as such, find the last STREAM frame of the stream the data_moved belongs to // NOTE: if you e.g., have 15 small STREAM frames of the same stream in one packet (which is possible, but a bit odd) // then this won't be 100% accurate, as the first data_moved was probably triggered by the first STREAM frame, not the 15th, though here we find the 15th // we had older versions of this code looking for that, but the benefits didn't outweight the complexity in the end. let foundFrame = undefined; for ( let i = dataSent.length - 1; i >= 0; --i ) { if ( "" + dataSent[i].streamID === "" + data.stream_id ) { foundFrame = dataSent[i]; break; } } if ( !foundFrame ) { console.error("Data moved but didn't start at previous stream's offset, impossible!!!", foundFrame, event.relativeTime, data); continue; } dataMoved.push({ streamID: parseInt(data.stream_id, 10), countStart: foundFrame.countStart, countEnd: foundFrame.countEnd, offset: movedOffset, length: movedLength, }); } } for ( const [stream_id, range] of streamRanges ) { if ( range.holes && range.holes.length !== 0 ) { console.warn("MultiplexingGraphD3CollapsedRenderer : stream has holes, didn't finish completely! Did this connection end pre-maturely?", stream_id, range.holes); } } // console.log("IDs present ", dataSent.map( (d) => d.streamID).filter((item, i, ar) => ar.indexOf(item) === i)); const clip = this.svg.append("defs").append("SVG:clipPath") .attr("id", "clip") .append("SVG:rect") .attr("width", this.dimensions.width ) .attr("height", this.dimensions.height ) .attr("x", 0 ) .attr("y", 0); const rects = this.svg.append('g') .attr("clip-path", "url(#clip)"); // if ( streamIDs.size <= 1 || frameCount < 5 ){ // rects // // text // .append("text") // .attr("x", 200 ) // .attr("y", 30 ) // + 1 is eyeballed magic number // .attr("dominant-baseline", "baseline") // .style("text-anchor", "start") // .style("font-size", "14") // .style("font-family", "Trebuchet MS") // // .style("font-weight", "bold") // .attr("fill", "#000000") // .text( "This trace doesn't contain multiple independent streams (or has less than 5 STREAM frames), which is needed for this visualization." ); // return; // } const packetSidePadding = 0.3; const xDomain = d3.scaleLinear() .domain([1, frameCount]) .range([ 0, this.dimensions.width ]); this.currentDomain = xDomain; const xAxis = this.svg.append("g"); if ( this.axisLocation === "top" ) { xAxis // .attr("transform", "translate(0," + this.dimensions.height + ")") .call(d3.axisTop(xDomain)); } else { xAxis .attr("transform", "translate(0," + this.dimensions.height + ")") .call(d3.axisBottom(xDomain)); } // https://bl.ocks.org/d3noob/a22c42db65eb00d4e369 const packetMouseOver = (data:any, index:number) => { this.tooltip.transition() .duration(100) .style("opacity", .95); let text = ""; text += data.time + "ms : stream " + data.streamID + " : packet number " + data.packetNumber + "<br/>"; text += "[" + data.offset + ", " + (data.offset + data.length - 1) + "] (size: " + data.length + ")"; if ( data.arrivalType === FrameArrivalType.Retransmit || data.arrivalType === FrameArrivalType.Reordered ) { text += "<br/>"; text += "Fills gap that was created " + data.arrivalTimeDifference + "ms ago"; } else if ( data.arrivalCreatedHole !== undefined ){ text += "<br/>"; text += "Creates gap from " + data.arrivalCreatedHole[0] + " to " + data.arrivalCreatedHole[1] + " (size: " + (data.arrivalCreatedHole[1] - data.arrivalCreatedHole[0]) + ")"; } this.tooltip .html( text ) .style("left", (d3.event.pageX + 15) + "px") .style("top", (d3.event.pageY - 75) + "px"); }; const packetMouseOut = (data:any, index:number) => { this.tooltip.transition() .duration(200) .style("opacity", 0); }; const packetHeight = this.barHeight * 0.65; const typeGap = this.barHeight * 0.05; const typeHeight = this.barHeight * 0.275; rects .selectAll("rect.packet") .data(dataSent) .enter() .append("rect") .attr("x", (d:any) => xDomain(d.countStart) - packetSidePadding ) .attr("y", (d:any) => (d.index % 2 === 0 ? 0 : packetHeight * 0.05) ) .attr("fill", (d:any) => StreamGraphDataHelper.StreamIDToColor("" + d.streamID)[0] /*"" + colorDomain( "" + d.streamID )*/ ) .style("opacity", 1) .attr("class", "packet") .attr("width", (d:any) => xDomain(d.countEnd) - xDomain(d.countStart) + packetSidePadding * 2) .attr("height", (d:any) => packetHeight * (d.index % 2 === 0 ? 1 : 0.90)) .style("pointer-events", "all") .on("mouseover", packetMouseOver) .on("mouseout", packetMouseOut) .on("click", (d:any) => { this.byteRangeRenderer.render(dataSent, dataMoved, d.streamID); this.byteRangeRenderer.zoom( this.currentDomain ); }); rects .selectAll("rect.retransmitPacket") .data( dataSent.filter( (d:any) => { return d.arrivalType === FrameArrivalType.Retransmit; } ) ) .enter() .append("rect") .attr("x", (d:any) => xDomain(d.countStart) - packetSidePadding ) .attr("y", (d:any) => packetHeight + typeGap ) .attr("fill", (d:any) => "black" ) .style("opacity", 1) .attr("class", "retransmitPacket") .attr("width", (d:any) => xDomain(d.countEnd) - xDomain(d.countStart) + packetSidePadding * 2) .attr("height", (d:any) => typeHeight); rects .selectAll("rect.reorderPacket") .data( dataSent.filter( (d:any) => { return d.arrivalType === FrameArrivalType.Reordered; } ) ) .enter() .append("rect") .attr("x", (d:any) => xDomain(d.countStart) - packetSidePadding ) .attr("y", (d:any) => packetHeight + typeGap ) .attr("fill", (d:any) => "blue" ) .style("opacity", 1) .attr("class", "reorderPacket") .attr("width", (d:any) => xDomain(d.countEnd) - xDomain(d.countStart) + packetSidePadding * 2) .attr("height", (d:any) => typeHeight); rects .selectAll("rect.duplicatePacket") .data( dataSent.filter( (d:any) => { return d.arrivalType === FrameArrivalType.Duplicate; } ) ) .enter() .append("rect") .attr("x", (d:any) => xDomain(d.countStart) - packetSidePadding ) .attr("y", (d:any) => packetHeight + typeGap ) .attr("fill", (d:any) => "red" ) .style("opacity", 1) .attr("class", "duplicatePacket") .attr("width", (d:any) => xDomain(d.countEnd) - xDomain(d.countStart) + packetSidePadding * 2) .attr("height", (d:any) => typeHeight); rects .selectAll("rect.futurePacket") .data( dataSent.filter( (d:any) => { return d.arrivalType === FrameArrivalType.Future; } ) ) .enter() .append("rect") .attr("x", (d:any) => xDomain(d.countStart) - packetSidePadding ) .attr("y", (d:any) => packetHeight + typeGap ) .attr("fill", (d:any) => "purple" ) .style("opacity", 1) .attr("class", "futurePacket") .attr("width", (d:any) => xDomain(d.countEnd) - xDomain(d.countStart) + packetSidePadding * 2) .attr("height", (d:any) => typeHeight); // legend this.svg.append('g') // text .append("text") .attr("x", xDomain(frameCount / 2) ) .attr("y", this.dimensions.height + this.dimensions.margin.bottom - 10 ) // + 1 is eyeballed magic number .attr("dominant-baseline", "baseline") .style("text-anchor", "middle") .style("font-size", "14") .style("font-family", "Trebuchet MS") // .style("font-weight", "bold") .attr("fill", "#000000") .text( "Count of STREAM frames " + directionText + " (regardless of size, includes retransmits)" ); const updateChart = () => { // recover the new scale const newX = d3.event.transform.rescaleX(xDomain); this.currentDomain = newX; // update axes with these new boundaries // xAxis./*transition().duration(200).*/call(d3.axisBottom(newX)); if ( this.axisLocation === "top" ){ xAxis.call(d3.axisTop(newX)); } else { xAxis.call(d3.axisBottom(newX)); } // update position rects .selectAll(".packet,.retransmitPacket,.reorderPacket,.duplicatePacket,.futurePacket") // .transition().duration(200) .attr("x", (d:any) => newX(d.countStart) - packetSidePadding ) // .attr("y", (d:any) => { return 50; } ) .attr("width", (d:any) => newX(d.countEnd) - newX(d.countStart) + packetSidePadding * 2) this.byteRangeRenderer.zoom( newX ); }; const zoom = d3.zoom() .scaleExtent([1, 30]) // This control how much you can unzoom (x0.5) and zoom (x20) .translateExtent([[0, 0], [this.dimensions.width, this.dimensions.height]]) .extent([[0, 0], [this.dimensions.width, this.dimensions.height]]) .on("zoom", updateChart); this.svg.call(zoom); if ( dataSent.length > 0 ) { this.byteRangeRenderer.render( dataSent, dataMoved, 0 ); } // make sure that if someone clicks on the waterfall renderer, it also updates the byteRangeRenderer if ( this.waterfallRenderer !== undefined ){ this.waterfallRenderer.onStreamClicked = (streamID:string) => { if ( this.byteRangeRenderer !== undefined ) { this.byteRangeRenderer.render( dataSent, dataMoved, parseInt(streamID, 0) ); this.byteRangeRenderer.zoom( this.currentDomain ); } }; } } }
the_stack
import { ElementTexturizer } from "./ElementTexturizer"; import { Utils } from "../Utils"; import { CoreContext } from "./CoreContext"; import { TextureSource } from "../TextureSource"; import { CoreRenderState } from "./CoreRenderState"; import { Shader } from "../Shader"; import { ElementCoreContext } from "./ElementCoreContext"; import { RenderTextureInfo } from "./RenderTextureInfo"; import { ElementEventCallback } from "../ElementListeners"; import { FlexContainer, FlexItem, FlexNode, FlexSubject } from "flexbox.js"; import { Element } from "../Element"; export class ElementCore implements FlexSubject { private _element: Element; public readonly context: CoreContext; /** * Recalc flags in bits. */ private flags: number = 0; private _parent?: ElementCore = undefined; private _onUpdate?: ElementEventCallback = undefined; private updatedFlags: number = 0; private _worldContext = new ElementCoreContext(); private _hasUpdates: boolean = false; private _localAlpha: number = 1; private _onAfterCalcs?: ElementEventCallback = undefined; private _onAfterUpdate?: ElementEventCallback = undefined; // All local translation/transform updates: directly propagated from x/y/w/h/scale/whatever. private _localPx: number = 0; private _localPy: number = 0; private _localTa: number = 1; private _localTb: number = 0; private _localTc: number = 0; private _localTd: number = 1; private _isComplex: boolean = false; private _dimsUnknown: boolean = false; private _clipping: boolean = false; private _zSort: boolean = false; private _outOfBounds: number = 0; /** * The texture source to be displayed. */ private _displayedTextureSource?: TextureSource = undefined; private _zContextUsage: number = 0; public _children?: ElementCore[] = undefined; private _hasRenderUpdates: number = 0; private _zIndexedChildren?: ElementCore[] = undefined; private _renderContext: ElementCoreContext = this._worldContext; private renderState: CoreRenderState; private _scissor?: number[] = undefined; // The ancestor ElementCore that defined the inherited shader. Undefined if none is active (default shader). private _shaderOwner?: ElementCore = undefined; // Counter while updating the tree order. private _updateTreeOrder: number = 0; // Texture corner point colors. private _colorUl: number = 0xffffffff; private _colorUr: number = 0xffffffff; private _colorBl: number = 0xffffffff; private _colorBr: number = 0xffffffff; // Internal coords. private _x: number = 0; private _y: number = 0; private _w: number = 0; private _h: number = 0; // Actual settings. private _sx: number = 0; private _sy: number = 0; private _sw: number = 0; private _sh: number = 0; // Active texture size. private _tw: number = 0; private _th: number = 0; // Defines which relative functions are enabled. private _relFuncFlags: number = 0; private _funcX?: RelativeFunction = undefined; private _funcY?: RelativeFunction = undefined; private _funcW?: RelativeFunction = undefined; private _funcH?: RelativeFunction = undefined; private _scaleX: number = 1; private _scaleY: number = 1; private _pivotX: number = 0.5; private _pivotY: number = 0.5; private _mountX: number = 0; private _mountY: number = 0; private _rotation: number = 0; private _alpha: number = 1; private _visible: boolean = true; // Texture clipping. public ulx: number = 0; public uly: number = 0; public brx: number = 1; public bry: number = 1; private _isRoot: boolean = false; private _zIndex: number = 0; private _forceZIndexContext: boolean = false; private _zParent?: ElementCore = undefined; /** * Iff true, during next zSort, this element should be 're-sorted' because either: * - zIndex did change * - zParent did change * - element was moved in the render tree */ private _zIndexResort: boolean = false; private _shader?: Shader = undefined; // Element is rendered on another texture. private _renderToTextureEnabled: boolean = false; // Manages the render texture. private _texturizer?: ElementTexturizer = undefined; private _useRenderToTexture: boolean = false; private _boundsMargin?: number[]; private _recBoundsMargin?: number[]; private _withinBoundsMargin: boolean = false; private _viewport?: number[] = undefined; // If this element is out of viewport, the branch is also skipped in updating and rendering. private _clipbox: boolean = false; // The render function. _renderAdvanced is only used if necessary. public render: () => void = this._renderSimple; // Flex layouting if enabled. private _layout?: FlexNode = undefined; private _stashedTexCoords?: number[] = undefined; private _stashedColors?: number[] = undefined; constructor(element: Element) { this._element = element; this.context = element.stage.context; this.renderState = this.context.renderState; } getRenderContext(): ElementCoreContext { return this._renderContext; } get x() { return this._sx; } set x(v: number) { const dx = (v as number) - this._sx; if (dx) { this._sx = v as number; if (!this._funcX) { this._x += dx; this.updateLocalTranslateDelta(dx, 0); } } } get funcX() { return this._funcX; } set funcX(v: RelativeFunction | undefined) { if (this._funcX !== v) { if (v) { this._relFuncFlags |= 1; this._funcX = v; } else { this._disableFuncX(); } if (this.hasFlexLayout()) { this.layout.forceLayout(); } else { this._triggerRecalcTranslate(); } } } _disableFuncX() { this._relFuncFlags = this._relFuncFlags & (0xffff - 1); this._funcX = undefined; } get y() { return this._sy; } set y(v: number) { const dy = (v as number) - this._sy; if (dy) { this._sy = v as number; if (!this._funcY) { this._y += dy; this.updateLocalTranslateDelta(0, dy); } } } get funcY() { return this._funcY; } set funcY(v: RelativeFunction | undefined) { if (this._funcY !== v) { if (v) { this._relFuncFlags |= 2; this._funcY = v; } else { this._disableFuncY(); } if (this.hasFlexLayout()) { this.layout.forceLayout(); } else { this._triggerRecalcTranslate(); } } } _disableFuncY() { this._relFuncFlags = this._relFuncFlags & (0xffff - 2); this._funcY = undefined; } get w() { return this._sw; } set w(v: number) { if (this._sw !== v) { this._sw = v as number; this._updateBaseDimensions(); } } get funcW() { return this._funcW; } set funcW(v) { if (this._funcW !== v) { if (v) { this._relFuncFlags |= 4; this._funcW = v; } else { this._disableFuncW(); } this._updateBaseDimensions(); } } _disableFuncW() { this._relFuncFlags = this._relFuncFlags & (0xffff - 4); this._funcW = undefined; } get h() { return this._sh; } set h(v: number) { if (this._sh !== v) { this._sh = v as number; this._updateBaseDimensions(); } } get funcH() { return this._funcH; } set funcH(v) { if (this._funcH !== v) { if (v) { this._relFuncFlags |= 8; this._funcH = v; } else { this._disableFuncH(); } this._updateBaseDimensions(); } } _disableFuncH() { this._relFuncFlags = this._relFuncFlags & (0xffff - 8); this._funcH = undefined; } get scaleX() { return this._scaleX; } set scaleX(v) { if (this._scaleX !== v) { this._scaleX = v; this._updateLocalTransform(); } } get scaleY() { return this._scaleY; } set scaleY(v) { if (this._scaleY !== v) { this._scaleY = v; this._updateLocalTransform(); } } get scale() { return this.scaleX; } set scale(v) { if (this._scaleX !== v || this._scaleY !== v) { this._scaleX = v; this._scaleY = v; this._updateLocalTransform(); } } get pivotX() { return this._pivotX; } set pivotX(v) { if (this._pivotX !== v) { this._pivotX = v; this._updateLocalTranslate(); } } get pivotY() { return this._pivotY; } set pivotY(v) { if (this._pivotY !== v) { this._pivotY = v; this._updateLocalTranslate(); } } get pivot() { return this._pivotX; } set pivot(v) { if (this._pivotX !== v || this._pivotY !== v) { this._pivotX = v; this._pivotY = v; this._updateLocalTranslate(); } } get mountX() { return this._mountX; } set mountX(v) { if (this._mountX !== v) { this._mountX = v; this._updateLocalTranslate(); } } get mountY() { return this._mountY; } set mountY(v) { if (this._mountY !== v) { this._mountY = v; this._updateLocalTranslate(); } } get mount() { return this._mountX; } set mount(v) { if (this._mountX !== v || this._mountY !== v) { this._mountX = v; this._mountY = v; this._updateLocalTranslate(); } } get rotation() { return this._rotation; } set rotation(v) { if (this._rotation !== v) { this._rotation = v; this._updateLocalTransform(); } } get alpha() { return this._alpha; } set alpha(v) { // Account for rounding errors. v = v > 1 ? 1 : v < 1e-14 ? 0 : v; if (this._alpha !== v) { const prev = this._alpha; this._alpha = v; this.updateLocalAlpha(); if ((prev === 0) !== (v === 0)) { this._element._updateEnabledFlag(); } } } get visible() { return this._visible; } set visible(v) { if (this._visible !== v) { this._visible = v; this.updateLocalAlpha(); this._element._updateEnabledFlag(); if (this.hasFlexLayout()) { this.layout.updateVisible(); } } } _updateLocalTransform() { if (this._rotation !== 0 && this._rotation % (2 * Math.PI)) { // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes const _sr = Math.sin(this._rotation); const _cr = Math.cos(this._rotation); this._setLocalTransform(_cr * this._scaleX, -_sr * this._scaleY, _sr * this._scaleX, _cr * this._scaleY); } else { this._setLocalTransform(this._scaleX, 0, 0, this._scaleY); } this._updateLocalTranslate(); } _updateLocalTranslate() { this.updateLocalTranslate(); this._triggerRecalcTranslate(); } private updateLocalTranslate() { const pivotXMul = this._pivotX * this._w; const pivotYMul = this._pivotY * this._h; let px = this._x - (pivotXMul * this._localTa + pivotYMul * this._localTb) + pivotXMul; let py = this._y - (pivotXMul * this._localTc + pivotYMul * this._localTd) + pivotYMul; px -= this._mountX * this._w; py -= this._mountY * this._h; this._localPx = px; this._localPy = py; } private updateLocalTranslateDelta(dx: number, dy: number) { this._addLocalTranslate(dx, dy); } private updateLocalAlpha() { this._setLocalAlpha(this._visible ? this._alpha : 0); } hasUpdates() { return this._hasUpdates; } hasRenderUpdates() { return this._hasRenderUpdates > 0; } hasRenderTextureUpdates() { return this._hasRenderUpdates >= 3; } clearHasRenderUpdates() { this._hasRenderUpdates = 0; } /** * @param level - Level of updates: * 0: no updates * 1: re-invoke shader * 3: re-create render texture and re-invoke shader */ setHasRenderUpdates(level: number) { if (this._worldContext.alpha) { // Ignore if 'world invisible'. Render updates will be reset to 3 for every element that becomes visible. let p: ElementCore | undefined = this as ElementCore; p!._hasRenderUpdates = Math.max(level, p!._hasRenderUpdates); while (true) { p = p!._parent; if (!p || p._hasRenderUpdates >= 3) { break; } p._hasRenderUpdates = 3; } } } /** * Marks recalculation updates. * @param type - What needs to be recalculated * 1: alpha * 2: translate * 4: transform * 128: becomes visible * 256: flex layout updated */ private setFlag(type: number) { this.flags |= type; this._setHasUpdates(); // Any changes in descendants should trigger texture updates. if (this._parent) { this._parent.setHasRenderUpdates(3); } } _setHasUpdates() { let p = this as ElementCore | undefined; while (p && !p._hasUpdates) { p._hasUpdates = true; p = p._parent; } } getParent(): ElementCore | undefined { return this._parent; } private setParent(parent?: ElementCore) { if (parent !== this._parent) { const prevIsZContext = this.isZContext(); const prevParent = this._parent; this._parent = parent; // Notify flex layout engine. if (this._layout || FlexNode.getActiveLayoutNode(parent)?.isFlexEnabled()) { this.layout.setParent(prevParent, parent); } if (prevParent) { // When elements are deleted, the render texture must be re-rendered. prevParent.setHasRenderUpdates(3); } this.setFlag(1 + 2 + 4); if (this._parent) { // Force parent to propagate hasUpdates flag. this._parent._setHasUpdates(); } if (this._zIndex === 0) { this.setZParent(parent); } else { this.setZParent(parent ? parent.findZContext() : undefined); } if (prevIsZContext !== this.isZContext()) { if (!this.isZContext()) { this.disableZContext(); } else { const prevZContext = prevParent ? prevParent.findZContext() : undefined; this.enableZContext(prevZContext); } } // Tree order did change: even if zParent stays the same, we must resort. this._zIndexResort = true; if (this._zParent) { this._zParent.enableZSort(); } if (!this._shader) { const newShaderOwner = parent && !parent._renderToTextureEnabled ? parent._shaderOwner : undefined; if (newShaderOwner !== this._shaderOwner) { this.setHasRenderUpdates(1); this._setShaderOwnerRecursive(newShaderOwner); } } } } private enableZSort(force = false) { if (!this._zSort && this._zContextUsage > 0) { this._zSort = true; if (force) { // ZSort must be done, even if this element is invisible. // This is done to prevent memory leaks when removing element from inactive render branches. this.context.forceZSort(this); } } } addChildAt(index: number, child: ElementCore) { if (!this._children) this._children = []; if (this._children.length === index) { this._children.push(child); } else { this._children.splice(index, 0, child); } child.setParent(this); } setChildAt(index: number, child: ElementCore) { if (!this._children) this._children = []; this._children[index].setParent(undefined); this._children[index] = child; child.setParent(this); } removeChildAt(index: number) { if (this._children) { const child = this._children[index]; this._children.splice(index, 1); child.setParent(undefined); } } removeChildren() { if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { this._children[i].setParent(undefined); } this._children.splice(0); if (this._zIndexedChildren) { this._zIndexedChildren.splice(0); } } } syncChildren(removed: ElementCore[], added: ElementCore[], order: ElementCore[]) { this._children = order; for (let i = 0, n = removed.length; i < n; i++) { removed[i].setParent(undefined); } for (let i = 0, n = added.length; i < n; i++) { added[i].setParent(this); } } moveChild(fromIndex: number, toIndex: number) { if (this._children) { const c = this._children[fromIndex]; this._children.splice(fromIndex, 1); this._children.splice(toIndex, 0, c); } // Tree order changed: must resort! this._zIndexResort = true; if (this._zParent) { this._zParent.enableZSort(); } } private _setLocalTransform(a: number, b: number, c: number, d: number) { this.setFlag(4); this._localTa = a; this._localTb = b; this._localTc = c; this._localTd = d; // We also regard negative scaling as a complex case, so that we can optimize the non-complex case better. this._isComplex = b !== 0 || c !== 0 || a < 0 || d < 0; } private _addLocalTranslate(dx: number, dy: number) { this._localPx += dx; this._localPy += dy; this._triggerRecalcTranslate(); } private _setLocalAlpha(a: number) { if (!this._worldContext.alpha && this._parent && this._parent._worldContext.alpha && a) { // Element is becoming visible. We need to force update. this.setFlag(1 + 128); } else { this.setFlag(1); } if (a < 1e-14) { // Tiny rounding errors may cause failing visibility tests. a = 0; } this._localAlpha = a; } setTextureDimensions(w: number, h: number, isEstimate: boolean = this._dimsUnknown) { // In case of an estimation, the update loop should perform different bound checks. this._dimsUnknown = isEstimate; if (this._tw !== w || this._th !== h) { this._tw = w; this._th = h; this._updateBaseDimensions(); } } private _updateBaseDimensions() { if (this._funcW || this._funcH) { this._triggerRecalcTranslate(); } const w = this._sw || this._tw; const h = this._sh || this._th; if (this.hasFlexLayout()) { // Notify layout. this.layout.updatedSourceW(); this.layout.updatedSourceH(); } else { if ((!this._funcW && this._w !== w) || (!this._funcH && this._h !== h)) { if (!this._funcW) { this._w = w; } if (!this._funcH) { this._h = h; } this.onDimensionsChanged(); } } } setLayoutCoords(x: number, y: number) { if (this._x !== x || this._y !== y) { this._x = x; this._y = y; this._updateLocalTranslate(); } } setLayoutDimensions(w: number, h: number) { if (this._w !== w || this._h !== h) { this._w = w; this._h = h; this.onDimensionsChanged(); } } private onDimensionsChanged() { // Due to width/height change: update the translation vector. this._updateLocalTranslate(); if (this._texturizer) { this._texturizer.releaseRenderTexture(); this._texturizer.updateResultTexture(); } this.element._onResize(this._w, this._h); } setTextureCoords(ulx: number, uly: number, brx: number, bry: number) { this.setHasRenderUpdates(3); this.ulx = ulx; this.uly = uly; this.brx = brx; this.bry = bry; } get displayedTextureSource(): TextureSource | undefined { return this._displayedTextureSource; } setDisplayedTextureSource(textureSource: TextureSource | undefined) { this.setHasRenderUpdates(3); this._displayedTextureSource = textureSource; } get isRoot(): boolean { return this._isRoot; } setupAsRoot() { // Use parent dummy. this._parent = new ElementCore(this._element); // After setting root, make sure it's updated. this._parent.w = this.context.stage.coordsWidth; this._parent.h = this.context.stage.coordsHeight; this._parent._hasRenderUpdates = 3; this._parent._hasUpdates = true; // Root is, and will always be, the primary zContext. this._isRoot = true; this.context.root = this; // Set scissor area of 'fake parent' to stage's viewport. this._parent._viewport = [0, 0, this.context.stage.coordsWidth, this.context.stage.coordsHeight]; this._parent._scissor = this._parent._viewport; // When recBoundsMargin is undefined, the defaults are used (100 for all sides). this._parent._recBoundsMargin = undefined; this.setFlag(1 + 2 + 4); } private isAncestorOf(c: ElementCore) { let p: ElementCore | undefined = c as ElementCore; while (true) { p = p!._parent; if (!p) { return false; } if (this === p) return true; } } private isZContext(): boolean { return ( this._forceZIndexContext || this._renderToTextureEnabled || this._zIndex !== 0 || this._isRoot || !this._parent ); } private findZContext(): ElementCore { if (this.isZContext()) { return this; } else { return this._parent!.findZContext(); } } private setZParent(newZParent?: ElementCore) { if (this._zParent !== newZParent) { if (this._zParent) { if (this._zIndex !== 0) { this._zParent.decZContextUsage(); } // We must filter out this item upon the next resort. this._zParent.enableZSort(); } if (newZParent !== undefined) { const hadZContextUsage = newZParent._zContextUsage > 0; // @pre: new parent's children array has already been modified. if (this._zIndex !== 0) { newZParent.incZContextUsage(); } if (newZParent._zContextUsage > 0) { if (!hadZContextUsage && this._parent === newZParent) { // This child was already in the children list. // Do not add double. } else { // Add new child to array. newZParent._zIndexedChildren!.push(this); } // Order should be checked. newZParent.enableZSort(); } } this._zParent = newZParent; // Newly added element must be marked for resort. this._zIndexResort = true; } } private incZContextUsage() { this._zContextUsage++; if (this._zContextUsage === 1) { if (!this._zIndexedChildren) { this._zIndexedChildren = []; } if (this._children) { // Copy. for (let i = 0, n = this._children.length; i < n; i++) { this._zIndexedChildren.push(this._children[i]); } // Initially, children are already sorted properly (tree order). this._zSort = false; } } } private decZContextUsage() { this._zContextUsage--; if (this._zContextUsage === 0) { this._zSort = false; this._zIndexedChildren!.splice(0); } } get zIndex(): number { return this._zIndex; } set zIndex(zIndex: number) { if (this._zIndex !== zIndex) { this.setHasRenderUpdates(1); let newZParent = this._zParent; const prevIsZContext = this.isZContext(); if (zIndex === 0 && this._zIndex !== 0) { if (this._parent === this._zParent) { if (this._zParent) { this._zParent.decZContextUsage(); } } else { newZParent = this._parent; } } else if (zIndex !== 0 && this._zIndex === 0) { newZParent = this._parent ? this._parent.findZContext() : undefined; if (newZParent === this._zParent) { if (this._zParent) { this._zParent.incZContextUsage(); this._zParent.enableZSort(); } } } else if (zIndex !== this._zIndex) { if (this._zParent && this._zParent._zContextUsage) { this._zParent.enableZSort(); } } if (newZParent !== this._zParent) { this.setZParent(undefined); } this._zIndex = zIndex; if (newZParent !== this._zParent) { this.setZParent(newZParent); } if (prevIsZContext !== this.isZContext()) { if (!this.isZContext()) { this.disableZContext(); } else { const prevZContext = this._parent ? this._parent.findZContext() : undefined; this.enableZContext(prevZContext); } } // Make sure that resort is done. this._zIndexResort = true; if (this._zParent) { this._zParent.enableZSort(); } } } get forceZIndexContext() { return this._forceZIndexContext; } set forceZIndexContext(v) { this.setHasRenderUpdates(1); const prevIsZContext = this.isZContext(); this._forceZIndexContext = v; if (prevIsZContext !== this.isZContext()) { if (!this.isZContext()) { this.disableZContext(); } else { const prevZContext = this._parent ? this._parent.findZContext() : undefined; this.enableZContext(prevZContext); } } } private enableZContext(prevZContext?: ElementCore) { if (prevZContext && prevZContext._zContextUsage > 0) { // Transfer from upper z context to this z context. const results = this._getZIndexedDescs(); results.forEach((c) => { if (this.isAncestorOf(c) && c._zIndex !== 0) { c.setZParent(this); } }); } } private _getZIndexedDescs() { const results: ElementCore[] = []; if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { this._children[i]._getZIndexedDescsRec(results); } } return results; } private _getZIndexedDescsRec(results: ElementCore[]) { if (this._zIndex) { results.push(this); } else if (this._children && !this.isZContext()) { for (let i = 0, n = this._children.length; i < n; i++) { this._children[i]._getZIndexedDescsRec(results); } } } private disableZContext() { // Transfer from this z context to upper z context. if (this._zContextUsage > 0) { const newZParent = this._parent ? this._parent.findZContext() : undefined; // Make sure that z-indexed children are up to date (old ones removed). if (this._zSort) { this.sortZIndexedChildren(); } this._zIndexedChildren!.slice().forEach((c) => { if (c._zIndex !== 0) { c.setZParent(newZParent); } }); } } get colorUl() { return this._colorUl; } set colorUl(color) { if (this._colorUl !== color) { this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); this._colorUl = color; } } get colorUr() { return this._colorUr; } set colorUr(color) { if (this._colorUr !== color) { this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); this._colorUr = color; } } get colorBl() { return this._colorBl; } set colorBl(color) { if (this._colorBl !== color) { this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); this._colorBl = color; } } get colorBr() { return this._colorBr; } set colorBr(color) { if (this._colorBr !== color) { this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); this._colorBr = color; } } set onUpdate(f: ElementEventCallback | undefined) { this._onUpdate = f; this.setFlag(7); } get onUpdate() { return this._onUpdate; } set onAfterUpdate(f: ElementEventCallback | undefined) { this._onAfterUpdate = f; this.setFlag(7); } get onAfterUpdate() { return this._onUpdate; } set onAfterCalcs(f: ElementEventCallback | undefined) { this._onAfterCalcs = f; this.setFlag(7); } get onAfterCalcs() { return this._onUpdate; } get shader() { return this._shader; } set shader(v) { this.setHasRenderUpdates(1); const prevShader = this._shader; this._shader = v; if (!v && prevShader) { // Disabled shader. const newShaderOwner = this._parent && !this._parent._renderToTextureEnabled ? this._parent._shaderOwner : undefined; this._setShaderOwnerRecursive(newShaderOwner); } else if (v) { // Enabled shader. this._setShaderOwnerRecursive(this); } } get activeShader() { return this._shaderOwner ? this._shaderOwner.shader! : this.renderState.defaultShader; } get activeShaderOwner() { return this._shaderOwner; } get clipping() { return this._clipping; } set clipping(v) { if (this._clipping !== v) { this._clipping = v; // Force update of scissor by updating translate. // Alpha must also be updated because the scissor area may have been empty. this.setFlag(1 + 2); } } get clipbox() { return this._clipbox; } set clipbox(v) { // In case of out-of-bounds element, all children will also be ignored. // It will save us from executing the update/render loops for those. // The optimization will be used immediately during the next frame. this._clipbox = v; } private _setShaderOwnerRecursive(elementCore?: ElementCore) { this._shaderOwner = elementCore; if (this._children && !this._renderToTextureEnabled) { for (let i = 0, n = this._children.length; i < n; i++) { const c = this._children[i]; if (!c._shader) { c._setShaderOwnerRecursive(elementCore); c._hasRenderUpdates = 3; } } } } private _setShaderOwnerChildrenRecursive(elementCore?: ElementCore) { if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { const c = this._children[i]; if (!c._shader) { c._setShaderOwnerRecursive(elementCore); c._hasRenderUpdates = 3; } } } } private _hasRenderContext() { return this._renderContext !== this._worldContext; } get renderContext() { return this._renderContext; } public updateRenderToTextureEnabled() { // Enforce texturizer initialisation. const texturizer = this.texturizer; const v = texturizer.enabled; if (v) { this._enableRenderToTexture(); } else { this._disableRenderToTexture(); texturizer.releaseRenderTexture(); } } private _enableRenderToTexture() { if (!this._renderToTextureEnabled) { const prevIsZContext = this.isZContext(); this._renderToTextureEnabled = true; this._renderContext = new ElementCoreContext(); // If render to texture is active, a new shader context is started. this._setShaderOwnerChildrenRecursive(undefined); if (!prevIsZContext) { // Render context forces z context. this.enableZContext(this._parent ? this._parent.findZContext() : undefined); } this.setHasRenderUpdates(3); // Make sure that the render coordinates get updated. this.setFlag(7); this.render = this._renderAdvanced; } } private _disableRenderToTexture() { if (this._renderToTextureEnabled) { this._renderToTextureEnabled = false; this._setShaderOwnerChildrenRecursive(this._shaderOwner); this._renderContext = this._worldContext; if (!this.isZContext()) { this.disableZContext(); } // Make sure that the render coordinates get updated. this.setFlag(7); this.setHasRenderUpdates(3); this.render = this._renderSimple; } } public isWhite() { return ( this._colorUl === 0xffffffff && this._colorUr === 0xffffffff && this._colorBl === 0xffffffff && this._colorBr === 0xffffffff ); } public hasSimpleTexCoords() { return this.ulx === 0 && this.uly === 0 && this.brx === 1 && this.bry === 1; } private _stashTexCoords() { this._stashedTexCoords = [this.ulx, this.uly, this.brx, this.bry]; this.ulx = 0; this.uly = 0; this.brx = 1; this.bry = 1; } private _unstashTexCoords() { this.ulx = this._stashedTexCoords![0]; this.uly = this._stashedTexCoords![1]; this.brx = this._stashedTexCoords![2]; this.bry = this._stashedTexCoords![3]; this._stashedTexCoords = undefined; } private _stashColors() { this._stashedColors = [this._colorUl, this._colorUr, this._colorBr, this._colorBl]; this._colorUl = 0xffffffff; this._colorUr = 0xffffffff; this._colorBr = 0xffffffff; this._colorBl = 0xffffffff; } private _unstashColors() { this._colorUl = this._stashedColors![0]; this._colorUr = this._stashedColors![1]; this._colorBr = this._stashedColors![2]; this._colorBl = this._stashedColors![3]; this._stashedColors = undefined; } isDisplayed() { return this._visible; } isVisible() { return this._localAlpha > 1e-14; } get outOfBounds() { return this._outOfBounds; } set boundsMargin(v) { /** * undefined: inherit from parent. * number[4]: specific margins: left, top, right, bottom. */ this._boundsMargin = v ? v.slice() : undefined; // We force recalc in order to set all boundsMargin recursively during the next update. this._triggerRecalcTranslate(); } get boundsMargin() { return this._boundsMargin; } private hasRelativeDimensionFunctions() { return this._relFuncFlags & 12; } public update(): void { // Inherit flags. this.flags |= this._parent!.updatedFlags & 135; if (this._layout && this._layout.isEnabled()) { const relativeDimsFlexRoot = this.isFlexLayoutRoot() && this.hasRelativeDimensionFunctions(); if (this.flags & 256 || relativeDimsFlexRoot) { this._layout.layoutFlexTree(); } } else if (this.flags & 2 && this._relFuncFlags) { this._applyRelativeDimFuncs(); } if (this._onUpdate) { // Block all 'upwards' updates when changing things in this branch. this._hasUpdates = true; this._onUpdate({ element: this.element }); } const pw = this._parent!._worldContext; const w = this._worldContext; const visible = pw.alpha && this._localAlpha; /** * We must update if: * - branch contains updates (even when invisible because it may contain z-indexed descendants) * - there are (inherited) updates and this branch is visible * - this branch becomes invisible (descs may be z-indexed so we must update all alpha values) */ if (this._hasUpdates || (this.flags && visible) || (w.alpha && !visible)) { let recalc = this.flags; // Update world coords/alpha. if (recalc & 1) { if (!w.alpha && visible) { // Becomes visible. this._hasRenderUpdates = 3; } w.alpha = pw.alpha * this._localAlpha; if (w.alpha < 1e-14) { // Tiny rounding errors may cause failing visibility tests. w.alpha = 0; } } if (recalc & 6) { w.px = pw.px + this._localPx * pw.ta; w.py = pw.py + this._localPy * pw.td; if (pw.tb !== 0) w.px += this._localPy * pw.tb; if (pw.tc !== 0) w.py += this._localPx * pw.tc; } if (recalc & 4) { w.ta = this._localTa * pw.ta; w.tb = this._localTd * pw.tb; w.tc = this._localTa * pw.tc; w.td = this._localTd * pw.td; if (this._isComplex) { w.ta += this._localTc * pw.tb; w.tb += this._localTb * pw.ta; w.tc += this._localTc * pw.td; w.td += this._localTb * pw.tc; } } // Update render coords/alpha. const pr = this._parent!._renderContext; if (this._parent!._hasRenderContext()) { const init = this._renderContext === this._worldContext; if (init) { // First render context build: make sure that it is fully initialized correctly. // Otherwise, if we get into bounds later, the render context would not be initialized correctly. this._renderContext = new ElementCoreContext(); } const rc = this._renderContext; // Update world coords/alpha. if (init || recalc & 1) { rc.alpha = pr.alpha * this._localAlpha; if (rc.alpha < 1e-14) { rc.alpha = 0; } } if (init || recalc & 6) { rc.px = pr.px + this._localPx * pr.ta; rc.py = pr.py + this._localPy * pr.td; if (pr.tb !== 0) rc.px += this._localPy * pr.tb; if (pr.tc !== 0) rc.py += this._localPx * pr.tc; } if (init) { // We set the recalc toggle, because we must make sure that the scissor is updated. recalc |= 2; } if (init || recalc & 4) { rc.ta = this._localTa * pr.ta; rc.tb = this._localTd * pr.tb; rc.tc = this._localTa * pr.tc; rc.td = this._localTd * pr.td; if (this._isComplex) { rc.ta += this._localTc * pr.tb; rc.tb += this._localTb * pr.ta; rc.tc += this._localTc * pr.td; rc.td += this._localTb * pr.tc; } } } else { this._renderContext = this._worldContext; } if (this.context.updateTreeOrder === -1) { this.context.updateTreeOrder = this._updateTreeOrder + 1; } else { this._updateTreeOrder = this.context.updateTreeOrder++; } // Determine whether we must use a 'renderTexture'. const useRenderToTexture = this._renderToTextureEnabled && this._texturizer!.mustRenderToTexture(); if (this._useRenderToTexture !== useRenderToTexture) { // Coords must be changed. this.flags |= 2 + 4; // Scissor may change: force update. recalc |= 2; if (!this._useRenderToTexture) { // We must release the texture. this._texturizer!.release(); } } this._useRenderToTexture = useRenderToTexture; const r = this._renderContext; const bboxW = this._dimsUnknown ? 2048 : this._w; const bboxH = this._dimsUnknown ? 2048 : this._h; // Calculate a bbox for this element. let sx; let sy; let ex; let ey; const rComplex = r.tb !== 0 || r.tc !== 0 || r.ta < 0 || r.td < 0; if (rComplex) { sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; } else { sx = r.px; ex = r.px + r.ta * bboxW; sy = r.py; ey = r.py + r.td * bboxH; } if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTd < 1)) { // If we are dealing with a non-identity matrix, we must extend the bbox so that withinBounds and // scissors will include the complete range of (positive) dimensions. const nx = this._x * pr.ta + this._y * pr.tb + pr.px; const ny = this._x * pr.tc + this._y * pr.td + pr.py; if (nx < sx) sx = nx; if (ny < sy) sy = ny; if (nx > ex) ex = nx; if (ny > ey) ey = ny; } if (recalc & 6 || !this._scissor /* initial */) { // Determine whether we must 'clip'. if (this._clipping && r.isSquare()) { // If the parent renders to a texture, it's scissor should be ignored; const area = this._parent!._useRenderToTexture ? this._parent!._viewport : this._parent!._scissor; if (area) { // Merge scissor areas. const lx = Math.max(area[0], sx); const ly = Math.max(area[1], sy); this._scissor = [ lx, ly, Math.min(area[2] + area[0], ex) - lx, Math.min(area[3] + area[1], ey) - ly, ]; } else { this._scissor = [sx, sy, ex - sx, ey - sy]; } } else { // No clipping: reuse parent scissor. this._scissor = this._parent!._useRenderToTexture ? this._parent!._viewport : this._parent!._scissor; } } // Calculate the outOfBounds margin. if (this._boundsMargin) { this._recBoundsMargin = this._boundsMargin; } else { this._recBoundsMargin = this._parent!._recBoundsMargin; } if (this._onAfterCalcs) { this._onAfterCalcs({ element: this.element }); // After calcs may change render coords, scissor and/or recBoundsMargin. // Recalculate bbox. if (rComplex) { sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; } else { sx = r.px; ex = r.px + r.ta * bboxW; sy = r.py; ey = r.py + r.td * bboxH; } if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { const nx = this._x * pr.ta + this._y * pr.tb + pr.px; const ny = this._x * pr.tc + this._y * pr.td + pr.py; if (nx < sx) sx = nx; if (ny < sy) sy = ny; if (nx > ex) ex = nx; if (ny > ey) ey = ny; } } if (this._parent!._outOfBounds === 2) { // Inherit parent out of boundsness. this._outOfBounds = 2; if (this._withinBoundsMargin) { this._withinBoundsMargin = false; this.element._disableWithinBoundsMargin(); } } else { if (recalc & 6) { // Recheck if element is out-of-bounds (all settings that affect this should enable recalc bit 2 or 4). this._outOfBounds = 0; let withinMargin = true; // Offscreens are always rendered as long as the parent is within bounds. if (!this._renderToTextureEnabled || !this._texturizer || !this._texturizer.renderOffscreen) { const scissor = this._scissor!; if (scissor && (scissor[2] <= 0 || scissor[3] <= 0)) { // Empty scissor area. this._outOfBounds = 2; } else { // Use bbox to check out-of-boundness. if ( scissor[0] > ex || scissor[1] > ey || sx > scissor[0] + scissor[2] || sy > scissor[1] + scissor[3] ) { this._outOfBounds = 1; } if (this._outOfBounds) { if (this._clipping || this._useRenderToTexture || (this._clipbox && bboxW && bboxH)) { this._outOfBounds = 2; } } } withinMargin = this._outOfBounds === 0; if (!withinMargin) { // Re-test, now with margins. if (this._recBoundsMargin) { withinMargin = !( ex < scissor[0] - this._recBoundsMargin[2] || ey < scissor[1] - this._recBoundsMargin[3] || sx > scissor[0] + scissor[2] + this._recBoundsMargin[0] || sy > scissor[1] + scissor[3] + this._recBoundsMargin[1] ); } else { withinMargin = !( ex < scissor[0] - 100 || ey < scissor[1] - 100 || sx > scissor[0] + scissor[2] + 100 || sy > scissor[1] + scissor[3] + 100 ); } if (withinMargin && this._outOfBounds === 2) { // Children must be visited because they may contain elements that are within margin, so must be visible. this._outOfBounds = 1; } } } if (this._withinBoundsMargin !== withinMargin) { this._withinBoundsMargin = withinMargin; if (this._withinBoundsMargin) { // This may update things (txLoaded events) in the element itself, but also in descendants and ancestors. // Changes in ancestors should be executed during the next call of the stage update. But we must // take care that the _recalc and _hasUpdates flags are properly registered. That's why we clear // both before entering the children, and use _pRecalc to transfer inherited updates instead of // _recalc directly. // Changes in descendants are automatically executed within the current update loop, though we must // take care to not update the hasUpdates flag unnecessarily in ancestors. We achieve this by making // sure that the hasUpdates flag of this element is turned on, which blocks it for ancestors. this._hasUpdates = true; const savedRecalc = this.flags; this.flags = 0; this.element._enableWithinBoundsMargin(); if (this.flags) { this.flags = savedRecalc | this.flags; // This element needs to be re-updated now, because we want the dimensions (and other changes) to be updated. return this.update(); } this.flags = savedRecalc; } else { this.element._disableWithinBoundsMargin(); } } } } if (this._useRenderToTexture) { // Set viewport necessary for children scissor calculation. if (this._viewport) { this._viewport[2] = bboxW; this._viewport[3] = bboxH; } else { this._viewport = [0, 0, bboxW, bboxH]; } } // Copy inheritable flags (except layout). this.updatedFlags = this.flags & 151; // Clear flags so that future updates are properly detected. this.flags = 0; this._hasUpdates = false; if (this._outOfBounds < 2) { if (this._useRenderToTexture) { if (this._worldContext.isIdentity()) { // Optimization. // The world context is already identity: use the world context as render context to prevents the // ancestors from having to update the render context. this._renderContext = this._worldContext; } else { // Temporarily replace the render coord attribs by the identity matrix. // This allows the children to calculate the render context. this._renderContext = ElementCoreContext.IDENTITY; } } if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { this._children[i].update(); } } if (this._useRenderToTexture) { this._renderContext = r; } } else { if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { if (this._children[i]._hasUpdates) { this._children[i].update(); } else { // Make sure we don't lose the 'inherited' updates when they become active again. this._children[i].flags |= this.updatedFlags; this._children[i].updateOutOfBounds(); } } } } if (this._onAfterUpdate) { this._onAfterUpdate({ element: this.element }); } } else { if (this.context.updateTreeOrder === -1 || this._updateTreeOrder >= this.context.updateTreeOrder) { // If new tree order does not interfere with the current (gaps allowed) there's no need to traverse the branch. this.context.updateTreeOrder = -1; } else { this.updateTreeOrder(); } } } _applyRelativeDimFuncs() { const layoutParent = this.getLayoutParent()!; if (this._relFuncFlags & 1) { const x = this._funcX!(layoutParent._w, layoutParent._h); if (x !== this._x) { this._localPx += x - this._x; this._x = x; } } if (this._relFuncFlags & 2) { const y = this._funcY!(layoutParent._w, layoutParent._h); if (y !== this._y) { this._localPy += y - this._y; this._y = y; } } let changedDims = false; if (this._relFuncFlags & 4) { const w = this._funcW!(layoutParent._w, layoutParent._h); if (w !== this._w) { this._w = w; changedDims = true; } } if (this._relFuncFlags & 8) { const h = this._funcH!(layoutParent._w, layoutParent._h); if (h !== this._h) { this._h = h; changedDims = true; } } if (changedDims) { this.onDimensionsChanged(); } } private getLayoutParent() { let current: ElementCore = this.getParent()!; while (current.skipInLayout) { const parent = current.getParent(); if (!parent) return current; current = parent; } return current; } updateOutOfBounds() { // Propagate outOfBounds flag to descendants (necessary because of z-indexing). // Invisible elements are not drawn anyway. When alpha is updated, so will _outOfBounds. if (this._outOfBounds !== 2 && this._renderContext.alpha > 0) { // Inherit parent out of boundsness. this._outOfBounds = 2; if (this._withinBoundsMargin) { this._withinBoundsMargin = false; this.element._disableWithinBoundsMargin(); } if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { this._children[i].updateOutOfBounds(); } } } } updateTreeOrder() { if (this._localAlpha && this._outOfBounds !== 2) { this._updateTreeOrder = this.context.updateTreeOrder++; if (this._children) { for (let i = 0, n = this._children.length; i < n; i++) { this._children[i].updateTreeOrder(); } } } } _renderSimple() { this._hasRenderUpdates = 0; if (this._zSort) { this.sortZIndexedChildren(); } if (this._outOfBounds < 2 && this._renderContext.alpha) { const renderState = this.renderState; if (this._outOfBounds === 0 && this._displayedTextureSource) { renderState.setShader(this.activeShader, this._shaderOwner); renderState.setScissor(this._scissor!); renderState.addElementCore(this); } // Also add children to the VBO. if (this._children) { if (this._zContextUsage) { for (let i = 0, n = this._zIndexedChildren!.length; i < n; i++) { this._zIndexedChildren![i].render(); } } else { for (let i = 0, n = this._children.length; i < n; i++) { if (this._children[i]._zIndex === 0) { // If zIndex is set, this item already belongs to a zIndexedChildren array in one of the ancestors. this._children[i].render(); } } } } } } _renderAdvanced() { const hasRenderUpdates = this._hasRenderUpdates; // We must clear the hasRenderUpdates flag before rendering, because updating result textures in combination // with z-indexing may trigger render updates on a render branch that is 'half done'. // We need to ensure that the full render branch is marked for render updates, not only half (leading to freeze). this._hasRenderUpdates = 0; if (this._zSort) { this.sortZIndexedChildren(); } if (this._outOfBounds < 2 && this._renderContext.alpha) { const renderState = this.renderState; let mustRenderChildren = true; let renderTextureInfo!: RenderTextureInfo; let prevRenderTextureInfo; if (this._useRenderToTexture) { if (this._w === 0 || this._h === 0) { // Ignore this branch and don't draw anything. return; } else if (!this._texturizer!.hasRenderTexture() || hasRenderUpdates >= 3) { // Switch to default shader for building up the render texture. renderState.setShader(renderState.defaultShader, this); prevRenderTextureInfo = renderState.renderTextureInfo; renderTextureInfo = { renderTexture: undefined, reusableTexture: undefined, reusableRenderStateOffset: 0, // Set by CoreRenderState. w: this._w, h: this._h, empty: true, cleared: false, ignore: false, cache: false, }; if ( this._texturizer!.hasResultTexture() || (!renderState.isCachingTexturizer && hasRenderUpdates < 3) ) { /** * Normally, we cache render textures. But there are exceptions to preserve memory usage! * * The rule is, that caching for a specific render texture is only enabled if: * - There is a result texture to be updated. * - There were no render updates -within the contents- since last frame (ElementCore.hasRenderUpdates < 3) * - AND there are no ancestors that are being cached during this frame (CoreRenderState.isCachingTexturizer) * If an ancestor is cached anyway, deeper caches are unlikely to be used. If the top level is to * change later while a lower one is not, that lower level will be cached instead at that instant. * * In some cases, this prevents having to cache all blur levels and stages, saving a huge amount * of GPU memory! * * Especially when using multiple stacked layers of the same dimensions that are render-to-texture this will have a very * noticable effect on performance as less render textures need to be allocated. */ renderTextureInfo.cache = true; renderState.isCachingTexturizer = true; } if (!this._texturizer!.hasResultTexture()) { // We can already release the current texture to the pool, as it will be rebuild anyway. // In case of multiple layers of 'filtering', this may save us from having to create one // render-to-texture layer. // Notice that we don't do this when there is a result texture, as any other element may rely on // that result texture being filled. this._texturizer!.releaseRenderTexture(); } renderState.setRenderTextureInfo(renderTextureInfo); renderState.setScissor(undefined); if (this._displayedTextureSource) { const r = this._renderContext; // Use an identity context for drawing the displayed texture to the render texture. this._renderContext = ElementCoreContext.IDENTITY; // Add displayed texture source in local coordinates. this.renderState.addElementCore(this); this._renderContext = r; } } else { mustRenderChildren = false; } } else { if (this._outOfBounds === 0 && this._displayedTextureSource) { renderState.setShader(this.activeShader, this._shaderOwner); renderState.setScissor(this._scissor); this.renderState.addElementCore(this); } } // Also add children to the VBO. if (mustRenderChildren && this._children) { if (this._zContextUsage) { for (let i = 0, n = this._zIndexedChildren!.length; i < n; i++) { this._zIndexedChildren![i].render(); } } else { for (let i = 0, n = this._children.length; i < n; i++) { if (this._children[i]._zIndex === 0) { // If zIndex is set, this item already belongs to a zIndexedChildren array in one of the ancestors. this._children[i].render(); } } } } if (this._useRenderToTexture) { let updateResultTexture = false; if (mustRenderChildren) { // Finished refreshing renderTexture. renderState.finishedRenderTexture(); // If nothing was rendered, we store a flag in the texturizer and prevent unnecessary // render-to-texture and filtering. this._texturizer!.empty = renderTextureInfo.empty; if (renderTextureInfo.empty) { // We ignore empty render textures and do not draw the final quad. // The following cleans up memory and enforces that the result texture is also cleared. this._texturizer!.releaseRenderTexture(); } else if (renderTextureInfo.reusableTexture) { // If nativeTexture is set, we can reuse that directly instead of creating a new render texture. this._texturizer!.reuseTextureAsRenderTexture(renderTextureInfo.reusableTexture); renderTextureInfo.ignore = true; } else { if (this._texturizer!.renderTextureReused) { // Quad operations must be written to a render texture actually owned. this._texturizer!.releaseRenderTexture(); } // Just create the render texture. renderTextureInfo.renderTexture = this._texturizer!.getRenderTexture(); } // Restore the parent's render texture. renderState.setRenderTextureInfo(prevRenderTextureInfo); updateResultTexture = true; } if (!this._texturizer!.empty) { const resultTexture = this._texturizer!.getResultTexture(); if (updateResultTexture) { if (resultTexture) { // Logging the update frame can be handy. resultTexture.updateFrame = this.element.stage.frameCounter; } this._texturizer!.updateResultTexture(); } if (!this._texturizer!.renderOffscreen) { // Render result texture to the actual render target. renderState.setShader(this.activeShader, this._shaderOwner); renderState.setScissor(this._scissor); // If no render texture info is set, the cache can be reused. const cache = !renderTextureInfo || renderTextureInfo.cache; renderState.setTexturizer(this._texturizer!, cache); this._stashTexCoords(); if (!this._texturizer!.colorize) this._stashColors(); this.renderState.addElementCore(this); if (!this._texturizer!.colorize) this._unstashColors(); this._unstashTexCoords(); renderState.setTexturizer(undefined, false); } } } if (renderTextureInfo && renderTextureInfo.cache) { // Allow siblings to cache. renderState.isCachingTexturizer = false; } } } get zSort() { return this._zSort; } sortZIndexedChildren() { /** * We want to avoid resorting everything. Instead, we do a single pass of the full array: * - filtering out elements with a different zParent than this (were removed) * - filtering out, but also gathering (in a temporary array) the elements that have zIndexResort flag * - then, finally, we merge-sort both the new array and the 'old' one * - element may have been added 'double', so when merge-sorting also check for doubles. * - if the old one is larger (in size) than it should be, splice off the end of the array. */ const n = this._zIndexedChildren!.length; let ptr = 0; const a = this._zIndexedChildren!; // Notice that items may occur multiple times due to z-index changing. const b = []; for (let i = 0; i < n; i++) { if (a[i]._zParent === this) { if (a[i]._zIndexResort) { b.push(a[i]); } else { if (ptr !== i) { a[ptr] = a[i]; } ptr++; } } } const m = b.length; if (m) { for (let j = 0; j < m; j++) { b[j]._zIndexResort = false; } b.sort(ElementCore.sortZIndexedChildren); const amount = ptr; if (!amount) { ptr = 0; let j = 0; do { a[ptr++] = b[j++]; } while (j < m); if (a.length > ptr) { // Slice old (unnecessary) part off array. a.splice(ptr); } } else { // Merge-sort arrays; ptr = 0; let i = 0; let j = 0; const mergeResult: ElementCore[] = []; do { const v = a[i]._zIndex === b[j]._zIndex ? a[i]._updateTreeOrder - b[j]._updateTreeOrder : a[i]._zIndex - b[j]._zIndex; const add = v > 0 ? b[j++] : a[i++]; if (ptr === 0 || mergeResult[ptr - 1] !== add) { mergeResult[ptr++] = add; } if (i >= amount) { do { const elementCore = b[j++]; if (ptr === 0 || mergeResult[ptr - 1] !== elementCore) { mergeResult[ptr++] = elementCore; } } while (j < m); break; } else if (j >= m) { do { const elementCore = a[i++]; if (ptr === 0 || mergeResult[ptr - 1] !== elementCore) { mergeResult[ptr++] = elementCore; } } while (i < amount); break; } } while (true); this._zIndexedChildren = mergeResult; } } else { if (a.length > ptr) { // Slice old (unnecessary) part off array. a.splice(ptr); } } this._zSort = false; } get localTa() { return this._localTa; } get localTb() { return this._localTb; } get localTc() { return this._localTc; } get localTd() { return this._localTd; } get element() { return this._element; } get renderUpdates() { return this._hasRenderUpdates; } get texturizer() { if (!this._texturizer) { this._texturizer = new ElementTexturizer(this); } return this._texturizer; } getCornerPoints() { const w = this._worldContext; return [ w.px, w.py, w.px + this._w * w.ta, w.py + this._w * w.tc, w.px + this._w * w.ta + this._h * w.tb, w.py + this._w * w.tc + this._h * w.td, w.px + this._h * w.tb, w.py + this._h * w.td, ]; } getRenderTextureCoords(relX: number, relY: number) { const r = this._renderContext; return [r.px + r.ta * relX + r.tb * relY, r.py + r.tc * relX + r.td * relY]; } getAbsoluteCoords(relX: number, relY: number) { const w = this._renderContext; return [w.px + w.ta * relX + w.tb * relY, w.py + w.tc * relX + w.td * relY]; } get skipInLayout(): boolean { return this._layout ? this._layout.skip : false; } set skipInLayout(v: boolean) { if (this.skipInLayout !== v) { // Force an update as absolute layout may be affected (on itself or on layout children). this._triggerRecalcTranslate(); this.layout.skip = v; } } get layout(): FlexNode { this._ensureLayout(); return this._layout!; } hasLayout(): boolean { return !!this._layout; } getLayout(): FlexNode { return this.layout; } enableFlexLayout() { this._ensureLayout(); } private _ensureLayout() { if (!this._layout) { this._layout = new FlexNode(this); } } disableFlexLayout() { this._triggerRecalcTranslate(); } hasFlexLayout() { return this._layout && this._layout.isEnabled(); } private isFlexLayoutRoot() { return this._layout && this._layout.isLayoutRoot(); } getFlexContainer(): FlexContainer | undefined { return this.layout.isFlexEnabled() ? this.layout.flex : undefined; } getFlexItem(): FlexItem | undefined { return this.layout.flexItem; } triggerLayout() { this.setFlag(256); } _triggerRecalcTranslate() { this.setFlag(2); } public getRenderWidth() { return this._w; } public getRenderHeight() { return this._h; } public isWithinBoundsMargin(): boolean { return this._withinBoundsMargin; } get parent() { return this._parent; } hasTexturizer(): boolean { return !!this._texturizer; } getChildren(): ElementCore[] | undefined { return this._children; } getSourceFuncX() { return this._funcX; } getSourceFuncY() { return this._funcY; } getSourceFuncW() { return this._funcW; } getSourceFuncH() { return this._funcH; } static sortZIndexedChildren(a: ElementCore, b: ElementCore) { return a._zIndex === b._zIndex ? a._updateTreeOrder - b._updateTreeOrder : a._zIndex - b._zIndex; } getSourceX() { return this._sx; } getSourceY() { return this._sy; } getSourceW() { // If no source width is specified, the texture width is automatically used. return this._sw || this._tw; } getSourceH() { return this._sh || this._th; } getLayoutX() { return this._x; } getLayoutY() { return this._y; } getLayoutW() { return this._w; } getLayoutH() { return this._h; } convertWorldCoordsToLocal(worldX: number, worldY: number): number[] { const wc = this._worldContext; worldX = worldX - wc.px; worldY = worldY - wc.py; if (wc.isIdentity()) { return [worldX, worldY]; } else if (wc.isSquare()) { return [worldX / wc.ta, worldY / wc.td]; } else { // Solve linear system of equations by substitution. const tcTa = wc.tc / wc.ta; const iy = (worldY - tcTa * worldX) / (wc.td - wc.tb * tcTa); const ix = (worldX - wc.tb * iy) / wc.ta; return [ix, iy]; } } public isCoordsWithinElement(localOffsetX: number, localOffsetY: number) { return localOffsetX >= 0 && localOffsetY >= 0 && localOffsetX < this._w && localOffsetY < this._h; } private getCoordinatesOrigin(): ElementCore { const parent = this._parent!; if (!parent) { return this; } else if (parent._useRenderToTexture) { return parent; } else { return parent.getCoordinatesOrigin(); } } private isWorldCoordinatesInScissor(worldX: number, worldY: number) { const s = this._scissor; if (s) { const renderRoot = this.getCoordinatesOrigin(); const [rx, ry] = renderRoot.convertWorldCoordsToLocal(worldX, worldY); if (rx < s[0] || ry < s[1] || rx >= s[0] + s[2] || ry >= s[1] + s[3]) { return false; } else { return true; } } else { return true; } } /** * @pre element core must be up-to-date (update method called). */ gatherElementsAtCoordinates(worldX: number, worldY: number, results: ElementCoordinatesInfo[]) { let withinBounds = false; if (!this._renderContext.alpha) { return; } const [offsetX, offsetY] = this.convertWorldCoordsToLocal(worldX, worldY); // Make coords relative to world context. withinBounds = this.isCoordsWithinElement(offsetX, offsetY); if (withinBounds && this.zIndex !== 0) { // We must make sure that the not yet visited ancestors do not clip out this texture. // renderToTexture is no problem as it creates a new z context so must already be checked. // clipping is a possible problem, so we must check the scissor. if (!this.isWorldCoordinatesInScissor(worldX, worldY)) { withinBounds = false; } } if (withinBounds) { results.push({ offsetX, offsetY, element: this.element }); } // When the render context is not square, clipping is ignored while rendering. const useClipping = this._useRenderToTexture || (this._clipping && this._renderContext.isSquare()); const mustRecurse = withinBounds || !useClipping; if (this._children && mustRecurse) { if (this._zContextUsage) { for (let i = 0, n = this._zIndexedChildren!.length; i < n; i++) { this._zIndexedChildren![i].gatherElementsAtCoordinates(worldX, worldY, results); } } else { for (let i = 0, n = this._children.length; i < n; i++) { if (this._children[i]._zIndex === 0) { // If zIndex is set, this item already belongs to a zIndexedChildren array in one of the ancestors. this._children[i].gatherElementsAtCoordinates(worldX, worldY, results); } } } } } checkWithinBounds() { this.setFlag(6); } } export type ElementCoordinatesInfo<DATA = any> = { offsetX: number; offsetY: number; element: Element<DATA>; }; export type RelativeFunction = (parentW: number, parentH: number) => number;
the_stack
import { ColorMapResult, ColorReducer } from "./colorreductionmanagement"; import { CancellationToken, delay, IMap, RGB } from "./common"; import { FacetBorderSegmenter } from "./facetBorderSegmenter"; import { FacetBorderTracer } from "./facetBorderTracer"; import { FacetCreator } from "./facetCreator"; import { FacetLabelPlacer } from "./facetLabelPlacer"; import { FacetResult } from "./facetmanagement"; import { FacetReducer } from "./facetReducer"; import { time, timeEnd } from "./gui"; import { Settings } from "./settings"; import { Point } from "./structs/point"; export class ProcessResult { public facetResult!: FacetResult; public colorsByIndex!: RGB[]; } /** * Manages the GUI states & processes the image step by step */ export class GUIProcessManager { public static async process(settings: Settings, cancellationToken: CancellationToken): Promise<ProcessResult> { const c = document.getElementById("canvas") as HTMLCanvasElement; const ctx = c.getContext("2d")!; let imgData = ctx.getImageData(0, 0, c.width, c.height); if (settings.resizeImageIfTooLarge && (c.width > settings.resizeImageWidth || c.height > settings.resizeImageHeight)) { let width = c.width; let height = c.height; if (width > settings.resizeImageWidth) { const newWidth = settings.resizeImageWidth; const newHeight = c.height / c.width * settings.resizeImageWidth; width = newWidth; height = newHeight; } if (height > settings.resizeImageHeight) { const newHeight = settings.resizeImageHeight; const newWidth = width / height * newHeight; width = newWidth; height = newHeight; } const tempCanvas = document.createElement("canvas"); tempCanvas.width = width; tempCanvas.height = height; tempCanvas.getContext("2d")!.drawImage(c, 0, 0, width, height); c.width = width; c.height = height; ctx.drawImage(tempCanvas, 0, 0, width, height); imgData = ctx.getImageData(0, 0, c.width, c.height); } // reset progress $(".status .progress .determinate").css("width", "0px"); $(".status").removeClass("complete"); const tabsOutput = M.Tabs.getInstance(document.getElementById("tabsOutput")!); // k-means clustering const kmeansImgData = await GUIProcessManager.processKmeansClustering(imgData, tabsOutput, ctx, settings, cancellationToken); let facetResult: FacetResult = new FacetResult(); let colormapResult: ColorMapResult = new ColorMapResult(); // build color map colormapResult = ColorReducer.createColorMap(kmeansImgData); if (settings.narrowPixelStripCleanupRuns === 0) { // facet building facetResult = await GUIProcessManager.processFacetBuilding(colormapResult, cancellationToken); // facet reduction await GUIProcessManager.processFacetReduction(facetResult, tabsOutput, settings, colormapResult, cancellationToken); } else { for (let run = 0; run < settings.narrowPixelStripCleanupRuns; run++) { // clean up narrow pixel strips await ColorReducer.processNarrowPixelStripCleanup(colormapResult); // facet building facetResult = await GUIProcessManager.processFacetBuilding(colormapResult, cancellationToken); // facet reduction await GUIProcessManager.processFacetReduction(facetResult, tabsOutput, settings, colormapResult, cancellationToken); // the colormapResult.imgColorIndices get updated as the facets are reduced, so just do a few runs of pixel cleanup } } // facet border tracing await GUIProcessManager.processFacetBorderTracing(tabsOutput, facetResult, cancellationToken); // facet border segmentation const cBorderSegment = await GUIProcessManager.processFacetBorderSegmentation(facetResult, tabsOutput, settings, cancellationToken); // facet label placement await GUIProcessManager.processFacetLabelPlacement(facetResult, cBorderSegment, tabsOutput, cancellationToken); // everything is now ready to generate the SVG, return the result const processResult = new ProcessResult(); processResult.facetResult = facetResult; processResult.colorsByIndex = colormapResult.colorsByIndex; return processResult; } private static async processKmeansClustering(imgData: ImageData, tabsOutput: M.Tabs, ctx: CanvasRenderingContext2D, settings: Settings, cancellationToken: CancellationToken) { time("K-means clustering"); const cKmeans = document.getElementById("cKMeans") as HTMLCanvasElement; cKmeans.width = imgData.width; cKmeans.height = imgData.height; const ctxKmeans = cKmeans.getContext("2d")!; ctxKmeans.fillStyle = "white"; ctxKmeans.fillRect(0, 0, cKmeans.width, cKmeans.height); const kmeansImgData = ctxKmeans.getImageData(0, 0, cKmeans.width, cKmeans.height); tabsOutput.select("kmeans-pane"); $(".status.kMeans").addClass("active"); await ColorReducer.applyKMeansClustering(imgData, kmeansImgData, ctx, settings, (kmeans) => { const progress = (100 - (kmeans.currentDeltaDistanceDifference > 100 ? 100 : kmeans.currentDeltaDistanceDifference)) / 100; $("#statusKMeans").css("width", Math.round(progress * 100) + "%"); ctxKmeans.putImageData(kmeansImgData, 0, 0); console.log(kmeans.currentDeltaDistanceDifference); if (cancellationToken.isCancelled) { throw new Error("Cancelled"); } }); $(".status").removeClass("active"); $(".status.kMeans").addClass("complete"); timeEnd("K-means clustering"); return kmeansImgData; } private static async processFacetBuilding(colormapResult: ColorMapResult, cancellationToken: CancellationToken) { time("Facet building"); $(".status.facetBuilding").addClass("active"); const facetResult = await FacetCreator.getFacets(colormapResult.width, colormapResult.height, colormapResult.imgColorIndices, (progress) => { if (cancellationToken.isCancelled) { throw new Error("Cancelled"); } $("#statusFacetBuilding").css("width", Math.round(progress * 100) + "%"); }); $(".status").removeClass("active"); $(".status.facetBuilding").addClass("complete"); timeEnd("Facet building"); return facetResult; } private static async processFacetReduction(facetResult: FacetResult, tabsOutput: M.Tabs, settings: Settings, colormapResult: ColorMapResult, cancellationToken: CancellationToken) { time("Facet reduction"); const cReduction = document.getElementById("cReduction") as HTMLCanvasElement; cReduction.width = facetResult.width; cReduction.height = facetResult.height; const ctxReduction = cReduction.getContext("2d")!; ctxReduction.fillStyle = "white"; ctxReduction.fillRect(0, 0, cReduction.width, cReduction.height); const reductionImgData = ctxReduction.getImageData(0, 0, cReduction.width, cReduction.height); tabsOutput.select("reduction-pane"); $(".status.facetReduction").addClass("active"); await FacetReducer.reduceFacets(settings.removeFacetsSmallerThanNrOfPoints, settings.removeFacetsFromLargeToSmall, settings.maximumNumberOfFacets, colormapResult.colorsByIndex, facetResult, colormapResult.imgColorIndices, (progress) => { if (cancellationToken.isCancelled) { throw new Error("Cancelled"); } // update status & image $("#statusFacetReduction").css("width", Math.round(progress * 100) + "%"); let idx = 0; for (let j: number = 0; j < facetResult.height; j++) { for (let i: number = 0; i < facetResult.width; i++) { const facet = facetResult.facets[facetResult.facetMap.get(i, j)]; const rgb = colormapResult.colorsByIndex[facet!.color]; reductionImgData.data[idx++] = rgb[0]; reductionImgData.data[idx++] = rgb[1]; reductionImgData.data[idx++] = rgb[2]; idx++; } } ctxReduction.putImageData(reductionImgData, 0, 0); }); $(".status").removeClass("active"); $(".status.facetReduction").addClass("complete"); timeEnd("Facet reduction"); } private static async processFacetBorderTracing(tabsOutput: M.Tabs, facetResult: FacetResult, cancellationToken: CancellationToken) { time("Facet border tracing"); tabsOutput.select("borderpath-pane"); const cBorderPath = document.getElementById("cBorderPath") as HTMLCanvasElement; cBorderPath.width = facetResult.width; cBorderPath.height = facetResult.height; const ctxBorderPath = cBorderPath.getContext("2d")!; $(".status.facetBorderPath").addClass("active"); await FacetBorderTracer.buildFacetBorderPaths(facetResult, (progress) => { if (cancellationToken.isCancelled) { throw new Error("Cancelled"); } // update status & image $("#statusFacetBorderPath").css("width", Math.round(progress * 100) + "%"); ctxBorderPath.fillStyle = "white"; ctxBorderPath.fillRect(0, 0, cBorderPath.width, cBorderPath.height); for (const f of facetResult.facets) { if (f != null && f.borderPath != null) { ctxBorderPath.beginPath(); ctxBorderPath.moveTo(f.borderPath[0].getWallX(), f.borderPath[0].getWallY()); for (let i: number = 1; i < f.borderPath.length; i++) { ctxBorderPath.lineTo(f.borderPath[i].getWallX(), f.borderPath[i].getWallY()); } ctxBorderPath.stroke(); } } }); $(".status").removeClass("active"); $(".status.facetBorderPath").addClass("complete"); timeEnd("Facet border tracing"); } private static async processFacetBorderSegmentation(facetResult: FacetResult, tabsOutput: M.Tabs, settings: Settings, cancellationToken: CancellationToken) { time("Facet border segmentation"); const cBorderSegment = document.getElementById("cBorderSegmentation") as HTMLCanvasElement; cBorderSegment.width = facetResult.width; cBorderSegment.height = facetResult.height; const ctxBorderSegment = cBorderSegment.getContext("2d")!; tabsOutput.select("bordersegmentation-pane"); $(".status.facetBorderSegmentation").addClass("active"); await FacetBorderSegmenter.buildFacetBorderSegments(facetResult, settings.nrOfTimesToHalveBorderSegments, (progress) => { if (cancellationToken.isCancelled) { throw new Error("Cancelled"); } // update status & image $("#statusFacetBorderSegmentation").css("width", Math.round(progress * 100) + "%"); ctxBorderSegment.fillStyle = "white"; ctxBorderSegment.fillRect(0, 0, cBorderSegment.width, cBorderSegment.height); for (const f of facetResult.facets) { if (f != null && progress > f.id / facetResult.facets.length) { ctxBorderSegment.beginPath(); const path = f.getFullPathFromBorderSegments(false); ctxBorderSegment.moveTo(path[0].x, path[0].y); for (let i: number = 1; i < path.length; i++) { ctxBorderSegment.lineTo(path[i].x, path[i].y); } ctxBorderSegment.stroke(); } } }); $(".status").removeClass("active"); $(".status.facetBorderSegmentation").addClass("complete"); timeEnd("Facet border segmentation"); return cBorderSegment; } private static async processFacetLabelPlacement(facetResult: FacetResult, cBorderSegment: HTMLCanvasElement, tabsOutput: M.Tabs, cancellationToken: CancellationToken) { time("Facet label placement"); const cLabelPlacement = document.getElementById("cLabelPlacement") as HTMLCanvasElement; cLabelPlacement.width = facetResult.width; cLabelPlacement.height = facetResult.height; const ctxLabelPlacement = cLabelPlacement.getContext("2d")!; ctxLabelPlacement.fillStyle = "white"; ctxLabelPlacement.fillRect(0, 0, cBorderSegment.width, cBorderSegment.height); ctxLabelPlacement.drawImage(cBorderSegment, 0, 0); tabsOutput.select("labelplacement-pane"); $(".status.facetLabelPlacement").addClass("active"); await FacetLabelPlacer.buildFacetLabelBounds(facetResult, (progress) => { if (cancellationToken.isCancelled) { throw new Error("Cancelled"); } // update status & image $("#statusFacetLabelPlacement").css("width", Math.round(progress * 100) + "%"); for (const f of facetResult.facets) { if (f != null && f.labelBounds != null) { ctxLabelPlacement.fillStyle = "red"; ctxLabelPlacement.fillRect(f.labelBounds.minX, f.labelBounds.minY, f.labelBounds.width, f.labelBounds.height); } } }); $(".status").removeClass("active"); $(".status.facetLabelPlacement").addClass("complete"); timeEnd("Facet label placement"); } /** * Creates a vector based SVG image of the facets with the given configuration */ public static async createSVG(facetResult: FacetResult, colorsByIndex: RGB[], sizeMultiplier: number, fill: boolean, stroke: boolean, addColorLabels: boolean, fontSize: number = 50, fontColor: string = "black", onUpdate: ((progress: number) => void) | null = null) { const xmlns = "http://www.w3.org/2000/svg"; const svg = document.createElementNS(xmlns, "svg"); svg.setAttribute("width", sizeMultiplier * facetResult.width + ""); svg.setAttribute("height", sizeMultiplier * facetResult.height + ""); let count = 0; for (const f of facetResult.facets) { if (f != null && f.borderSegments.length > 0) { let newpath: Point[] = []; const useSegments = true; if (useSegments) { newpath = f.getFullPathFromBorderSegments(false); // shift from wall coordinates to pixel centers /*for (const p of newpath) { p.x+=0.5; p.y+=0.5; }*/ } else { for (let i: number = 0; i < f.borderPath.length; i++) { newpath.push(new Point(f.borderPath[i].getWallX() + 0.5, f.borderPath[i].getWallY() + 0.5)); } } if (newpath[0].x !== newpath[newpath.length - 1].x || newpath[0].y !== newpath[newpath.length - 1].y) { newpath.push(newpath[0]); } // close loop if necessary // Create a path in SVG's namespace // using quadratic curve absolute positions const svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path"); let data = "M "; data += newpath[0].x * sizeMultiplier + " " + newpath[0].y * sizeMultiplier + " "; for (let i: number = 1; i < newpath.length; i++) { const midpointX = (newpath[i].x + newpath[i - 1].x) / 2; const midpointY = (newpath[i].y + newpath[i - 1].y) / 2; data += "Q " + (midpointX * sizeMultiplier) + " " + (midpointY * sizeMultiplier) + " " + (newpath[i].x * sizeMultiplier) + " " + (newpath[i].y * sizeMultiplier) + " "; // data += "L " + (newpath[i].x * sizeMultiplier) + " " + (newpath[i].y * sizeMultiplier) + " "; } data += "Z"; svgPath.setAttribute("data-facetId", f.id + ""); // Set path's data svgPath.setAttribute("d", data); if (stroke) { svgPath.style.stroke = "#000"; } else { // make the border the same color as the fill color if there is no border stroke // to not have gaps in between facets if (fill) { svgPath.style.stroke = `rgb(${colorsByIndex[f.color][0]},${colorsByIndex[f.color][1]},${colorsByIndex[f.color][2]})`; } } svgPath.style.strokeWidth = "1px"; // Set stroke width if (fill) { svgPath.style.fill = `rgb(${colorsByIndex[f.color][0]},${colorsByIndex[f.color][1]},${colorsByIndex[f.color][2]})`; } else { svgPath.style.fill = "none"; } svg.appendChild(svgPath); /* for (const seg of f.borderSegments) { const svgSegPath = document.createElementNS("http://www.w3.org/2000/svg", "path"); let segData = "M "; const segPoints = seg.originalSegment.points; segData += segPoints[0].x * sizeMultiplier + " " + segPoints[0].y * sizeMultiplier + " "; for (let i: number = 1; i < segPoints.length; i++) { const midpointX = (segPoints[i].x + segPoints[i - 1].x) / 2; const midpointY = (segPoints[i].y + segPoints[i - 1].y) / 2; //data += "Q " + (midpointX * sizeMultiplier) + " " + (midpointY * sizeMultiplier) + " " + (newpath[i].x * sizeMultiplier) + " " + (newpath[i].y * sizeMultiplier) + " "; segData += "L " + (segPoints[i].x * sizeMultiplier) + " " + (segPoints[i].y * sizeMultiplier) + " "; } console.log("Facet " + f.id + ", segment " + segPoints[0].x + "," + segPoints[0].y + " -> " + segPoints[segPoints.length-1].x + "," + segPoints[segPoints.length-1].y); svgSegPath.setAttribute("data-segmentFacet", f.id + ""); // Set path's data svgSegPath.setAttribute("d", segData); svgSegPath.style.stroke = "#FF0"; svgSegPath.style.fill = "none"; svg.appendChild(svgSegPath); } */ // add the color labels if necessary. I mean, this is the whole idea behind the paint by numbers part // so I don't know why you would hide them if (addColorLabels) { const txt = document.createElementNS(xmlns, "text"); txt.setAttribute("font-family", "Tahoma"); const nrOfDigits = (f.color + "").length; txt.setAttribute("font-size", (fontSize / nrOfDigits) + ""); txt.setAttribute("dominant-baseline", "middle"); txt.setAttribute("text-anchor", "middle"); txt.setAttribute("fill", fontColor); txt.textContent = f.color + ""; const subsvg = document.createElementNS(xmlns, "svg"); subsvg.setAttribute("width", f.labelBounds.width * sizeMultiplier + ""); subsvg.setAttribute("height", f.labelBounds.height * sizeMultiplier + ""); subsvg.setAttribute("overflow", "visible"); subsvg.setAttribute("viewBox", "-50 -50 100 100"); subsvg.setAttribute("preserveAspectRatio", "xMidYMid meet"); subsvg.appendChild(txt); const g = document.createElementNS(xmlns, "g"); g.setAttribute("class", "label"); g.setAttribute("transform", "translate(" + f.labelBounds.minX * sizeMultiplier + "," + f.labelBounds.minY * sizeMultiplier + ")"); g.appendChild(subsvg); svg.appendChild(g); } if (count % 100 === 0) { await delay(0); if (onUpdate != null) { onUpdate(f.id / facetResult.facets.length); } } } count++; } if (onUpdate != null) { onUpdate(1); } return svg; } }
the_stack
import {Curve} from '@core/api'; import StateTransitionManager from '@core/StateTransitionManager'; import * as tape from 'tape'; import * as TestHelpers from '../TestHelpers'; tape('Test state transitions', (t) => { const bytecode = { timelines: { Default: {}, }, template: {}, }; TestHelpers.createComponent(bytecode, {}, (component, teardown, mount) => { const stateTransitionManager = new StateTransitionManager(component); const haikuClock = component.getClock(); stateTransitionManager.setState({ var1: 0, var2: 5, varString: 'string', varArray: [10, 0], varObject: { varString: 'string', var: 5, }, varNull: null, varBool: true, }); stateTransitionManager.setState( { var1: 10, var2: 10, }, { duration: 4000, curve: Curve.Linear, }, ); haikuClock.setTime(0); stateTransitionManager.tickStateTransitions(); t.deepEqual([component.state.var1, component.state.var2], [0, 5], 'Simple state transition at 0ms'); haikuClock.setTime(1000); stateTransitionManager.tickStateTransitions(); t.deepEqual([component.state.var1, component.state.var2], [2.5, 6.25], 'Simple state transition at 1000ms'); haikuClock.setTime(2000); stateTransitionManager.tickStateTransitions(); t.deepEqual([component.state.var1, component.state.var2], [5, 7.5], 'Simple state transition at 2000ms'); haikuClock.setTime(4000); stateTransitionManager.tickStateTransitions(); t.deepEqual([component.state.var1, component.state.var2], [10, 10], 'Simple state transition at 4000ms'); t.is(stateTransitionManager.numQueuedTransitions, 0, 'Check is expired transition is deleted'); stateTransitionManager.setState( {var1: 5}, { duration: 1000, curve: Curve.Linear, }, ); stateTransitionManager.setState( {var2: 0}, { duration: 2000, curve: Curve.Linear, }, ); t.deepEqual([component.state.var1, component.state.var2], [10, 10], 'Dual state transition at 4000ms'); t.is(stateTransitionManager.numQueuedTransitions, 2, 'Check number of transitions at 6000ms'); haikuClock.setTime(5000); stateTransitionManager.tickStateTransitions(); t.deepEqual([component.state.var1, component.state.var2], [5, 5], 'Dual state transition at 5000ms'); t.is(stateTransitionManager.numQueuedTransitions, 1, 'Check number of transitions at 6000ms'); haikuClock.setTime(6000); stateTransitionManager.tickStateTransitions(); t.deepEqual([component.state.var1, component.state.var2], [5, 0], 'Dual state transition at 6000ms'); t.is(stateTransitionManager.numQueuedTransitions, 0, 'Check number of transitions at 6000ms'); stateTransitionManager.setState( { var3: 5, var1: 0, }, { duration: 1000, curve: Curve.Linear, }, ); haikuClock.setTime(7000); stateTransitionManager.tickStateTransitions(); t.ok(!('var3' in component.state), 'Ignore non pre existant states'); stateTransitionManager.setState( {var1: 5}, { duration: 10000, curve: Curve.Linear, }, ); stateTransitionManager.setState( {var2: 5}, { duration: 20000, curve: Curve.Linear, }, ); haikuClock.setTime(8000); stateTransitionManager.tickStateTransitions(); stateTransitionManager.deleteAllStateTransitions(); t.is(stateTransitionManager.numQueuedTransitions, 0, 'Delete all state transitions'); stateTransitionManager.setState( {varString: 10}, { duration: 1000, curve: Curve.Linear, }, ); haikuClock.setTime(8000); stateTransitionManager.tickStateTransitions(); t.is(component.state.varString, 'string', 'Do not state transition strings'); stateTransitionManager.setState( {varArray: [20, 20]}, { duration: 1000, curve: Curve.Linear, }, ); haikuClock.setTime(8500); stateTransitionManager.tickStateTransitions(); t.deepEqual(component.state.varArray, [15, 10], 'State transition array'); haikuClock.setTime(9000); stateTransitionManager.tickStateTransitions(); t.deepEqual(component.state.varArray, [20, 20], 'State transition array'); stateTransitionManager.setState( { varObject: { varString: 10, var: 10, }, }, { duration: 1000, curve: Curve.Linear, }, ); haikuClock.setTime(9500); stateTransitionManager.tickStateTransitions(); t.deepEqual( component.state.varObject, { varString: 'string', var: 7.5, }, 'Interpolate numbers and set transition end directly on non interpolable objects', ); haikuClock.setTime(10000); stateTransitionManager.tickStateTransitions(); t.deepEqual( component.state.varObject, { varString: 10, var: 10, }, 'Interpolate numbers and set transitionEnd directly on non interpolable objects', ); stateTransitionManager.setState( {varNull: 10}, { duration: 1000, curve: Curve.EaseOutQuad, }, ); haikuClock.setTime(11000); stateTransitionManager.tickStateTransitions(); t.is(component.state.varNull, 10, 'Set transitionEnd directly on non interpolable objects'); // State transitions for boolean are not defined. The state transition with // boolean will directly update to target value upon completion stateTransitionManager.setState( {varBool: false}, { duration: 1000, curve: Curve.Linear, }, ); haikuClock.setTime(11400); stateTransitionManager.tickStateTransitions(); t.is(component.state.varBool, true, 'State transition boolean'); haikuClock.setTime(11500); stateTransitionManager.tickStateTransitions(); t.is(component.state.varBool, true, 'State transition boolean'); haikuClock.setTime(11501); stateTransitionManager.tickStateTransitions(); t.is(component.state.varBool, true, 'State transition boolean'); haikuClock.setTime(12000); stateTransitionManager.tickStateTransitions(); t.is(component.state.varBool, false, 'State transition boolean'); stateTransitionManager.setState( {var1: 5}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 10}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 15}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 2}, { duration: 1000, curve: Curve.Linear, }, ); stateTransitionManager.setState( {var1: 4}, { duration: 1000, curve: Curve.Linear, }, ); t.is(stateTransitionManager.numQueuedTransitions, 1, 'queue=false should overwrite previous transitions'); haikuClock.setTime(13000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 4, 'With queued=false, last state transition should overwrite old ones'); stateTransitionManager.setState( {var1: 2}, { duration: 1000, curve: Curve.Linear, }, ); stateTransitionManager.setState( {var1: 5}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 10}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 15}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); t.is(stateTransitionManager.numQueuedTransitions, 4, 'queue=true should not overwrite previous transitions'); haikuClock.setTime(14000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 2, 'Check if first queue=false transition is executed'); haikuClock.setTime(15000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 5, 'Check if second queue=true transition is executed'); haikuClock.setTime(16000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 10, 'Check if third queue=true transition is executed'); haikuClock.setTime(17000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 15, 'Check if fourth queue=true transition is executed'); stateTransitionManager.setState( {var1: 15}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 20}, { duration: 2000, curve: Curve.Linear, queue: true, }, ); haikuClock.setTime(17500); stateTransitionManager.tickStateTransitions(); stateTransitionManager.setState({var1: 18}); haikuClock.setTime(18000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 18, 'A setState without transition parameter should cancel any queued transition'); stateTransitionManager.setState( {var1: 20}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); stateTransitionManager.setState( {var1: 22}, { duration: 1000, curve: Curve.Linear, queue: true, }, ); haikuClock.setTime(19000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 20, 'First queued state transition should be executed'); haikuClock.setTime(19500); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 21, 'Second queued state transition is updated on its start'); haikuClock.setTime(20000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 22, 'Second queued state transition should be executed'); t.is(stateTransitionManager.numQueuedTransitions, 0, 'All transitions should be finished'); stateTransitionManager.setState( {var1: 50}, { duration: 1000, curve: Curve.EaseInExpo, }, ); haikuClock.setTime(21000); stateTransitionManager.tickStateTransitions(); t.is(component.state.var1, 50, 'Second queued state transition should be executed'); t.is(stateTransitionManager.numQueuedTransitions, 0, 'All transitions should be finished'); let flag = false; stateTransitionManager.setState( {var1: 100}, { duration: 2000, curve: Curve.Linear, onComplete: () => { flag = true; }, }, ); haikuClock.setTime(21000); stateTransitionManager.tickStateTransitions(); t.is(flag, false, 'onComplete callback is not called before the state transition ends'); haikuClock.setTime(23000); stateTransitionManager.tickStateTransitions(); t.is(flag, true, 'onComplete callback is called when the state transition ends'); t.is(stateTransitionManager.numQueuedTransitions, 0, 'All transitions should be finished'); t.end(); teardown(); }); });
the_stack
import type { Axis } from "./axes/Axis"; import type { XYCursor } from "./XYCursor"; import type { AxisRenderer } from "./axes/AxisRenderer"; import type { DataItem } from "../../core/render/Component"; import type { IDisposer } from "../../core/util/Disposer"; import type { XYSeries, IXYSeriesDataItem } from "./series/XYSeries"; import type { IPointerEvent } from "../../core/render/backend/Renderer"; import type { Scrollbar } from "../../core/render/Scrollbar"; import type { Tooltip } from "../../core/render/Tooltip"; import type { IPoint } from "../../core/util/IPoint"; import { XYChartDefaultTheme } from "./XYChartDefaultTheme"; import { Container } from "../../core/render/Container"; import { Rectangle } from "../../core/render/Rectangle"; import { SerialChart, ISerialChartPrivate, ISerialChartSettings, ISerialChartEvents } from "../../core/render/SerialChart"; import { ListAutoDispose } from "../../core/util/List"; import { p100 } from "../../core/util/Percent"; import { Color } from "../../core/util/Color"; import { Button } from "../../core/render/Button"; import { Graphics } from "../../core/render/Graphics"; import { Percent } from "../../core/util/Percent"; import * as $array from "../../core/util/Array"; import * as $order from "../../core/util/Order"; import * as $type from "../../core/util/Type"; import type { Animation } from "../../core/util/Entity"; export interface IXYChartSettings extends ISerialChartSettings { /** * horizontal scrollbar. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/scrollbars/} for more info */ scrollbarX?: Scrollbar; /** * Vertical scrollbar. * */ scrollbarY?: Scrollbar; /** * If this is set to `true`, users will be able to pan the chart horizontally * by dragging plot area. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/zoom-and-pan/#Panning} for more info */ panX?: boolean; /** * If this is set to `true`, users will be able to pan the chart vertically * by dragging plot area. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/zoom-and-pan/#Panning} for more info */ panY?: boolean; /** * Indicates what happens when mouse wheel is spinned horizontally while over * plot area. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/zoom-and-pan/#Mouse_wheel_behavior} for more info */ wheelX?: "zoomX" | "zoomY" | "zoomXY" | "panX" | "panY" | "panXY" | "none"; /** * Indicates what happens when mouse wheel is spinned vertically while over * plot area. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/zoom-and-pan/#Mouse_wheel_behavior} for more info */ wheelY?: "zoomX" | "zoomY" | "zoomXY" | "panX" | "panY" | "panXY" | "none"; /** * Indicates the relative "speed" of the mouse wheel. * * @default 0.25 */ wheelStep?: number; /** * Chart's cursor. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/} for more info */ cursor?: XYCursor; /** * Indicates maximum distance from pointer (moust or touch) to points * tooltips need to be shown for. * * Points that are further from pointer than this setting will not be shown. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/#Tooltips} for more info */ maxTooltipDistance?: number; /** * If set to `false` the chart will not check for overlapping of multiple * tooltips, and will not arrange them to not overlap. * * Will work only if chart has an `XYCursor` enabled. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/#Tooltips} for more info * @default true */ arrangeTooltips?: boolean } export interface IXYChartPrivate extends ISerialChartPrivate { /** * A list of [[Series]] that currently have their tooltip being displayed. */ tooltipSeries?: Array<XYSeries> } export interface IXYChartEvents extends ISerialChartEvents { /** * Invoked when panning starts. * * @since 5.0.4 */ panstarted: {}; /** * Invoked when panning ends. * * @since 5.0.4 */ panended: {}; /** * Invoked when wheel caused zoom ends. * * @since 5.0.4 */ wheelended: {}; } /** * Creates an XY chart. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/} for more info * @important */ export class XYChart extends SerialChart { public static className: string = "XYChart"; public static classNames: Array<string> = SerialChart.classNames.concat([XYChart.className]); declare public _settings: IXYChartSettings; declare public _privateSettings: IXYChartPrivate; declare public _seriesType: XYSeries; declare public _events: IXYChartEvents; /** * A list of horizontal axes. */ public readonly xAxes: ListAutoDispose<Axis<AxisRenderer>> = new ListAutoDispose(); /** * A list of vertical axes. */ public readonly yAxes: ListAutoDispose<Axis<AxisRenderer>> = new ListAutoDispose(); /** * A [[Container]] located on top of the chart, used to store top horizontal * axes. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly topAxesContainer: Container = this.chartContainer.children.push(Container.new(this._root, { width: p100, layout: this._root.verticalLayout })); /** * A [[Container]] located in the middle the chart, used to store vertical axes * and plot area container. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly yAxesAndPlotContainer: Container = this.chartContainer.children.push(Container.new(this._root, { width: p100, height: p100, layout: this._root.horizontalLayout })); /** * A [[Container]] located on bottom of the chart, used to store bottom * horizontal axes. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly bottomAxesContainer: Container = this.chartContainer.children.push(Container.new(this._root, { width: p100, layout: this._root.verticalLayout })); /** * A [[Container]] located on left of the chart, used to store left-hand * vertical axes. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly leftAxesContainer: Container = this.yAxesAndPlotContainer.children.push(Container.new(this._root, { height: p100, layout: this._root.horizontalLayout })); /** * A [[Container]] located in the middle of the chart, used to store actual * plots (series). * * NOTE: `plotContainer` will automatically have its `background` preset. If * you need to modify background or outline for chart's plot area, you can * use `plotContainer.get("background")` for that. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly plotContainer: Container = this.yAxesAndPlotContainer.children.push(Container.new(this._root, { width: p100, height: p100, maskContent: false })); /** * A [[Container]] axis grid elements are stored in. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly gridContainer: Container = this.plotContainer.children.push(Container.new(this._root, { width: p100, height: p100, isMeasured: false })); /** * A [[Container]] axis background grid elements are stored in. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly topGridContainer: Container = Container.new(this._root, { width: p100, height: p100, isMeasured: false }); /** * A [[Container]] located on right of the chart, used to store right-hand * vertical axes. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/xy-chart-containers/} for more info * @default Container.new() */ public readonly rightAxesContainer: Container = this.yAxesAndPlotContainer.children.push(Container.new(this._root, { height: p100, layout: this._root.horizontalLayout })); /** * A [[Container]] axis headers are stored in. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/axis-headers/} for more info * @default Container.new() */ public readonly axisHeadersContainer: Container = this.plotContainer.children.push(Container.new(this._root, {})); /** * A button that is shown when chart is not fully zoomed out. * * @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/zoom-and-pan/#Zoom_out_button} for more info * @default Button.new() */ public readonly zoomOutButton: Button = this.plotContainer.children.push(Button.new(this._root, { themeTags: ["zoom"], icon: Graphics.new(this._root, { themeTags: ["button", "icon"] }) })); public _movePoint: IPoint = { x: 0, y: 0 }; protected _wheelDp: IDisposer | undefined; public _otherCharts?: Array<XYChart>; protected _afterNew() { this._defaultThemes.push(XYChartDefaultTheme.new(this._root)); super._afterNew(); this._disposers.push(this.xAxes); this._disposers.push(this.yAxes); const root = this._root; let verticalLayout = this._root.verticalLayout; const zoomOutButton = this.zoomOutButton; zoomOutButton.events.on("click", () => { this.zoomOut(); }) zoomOutButton.set("opacity", 0); zoomOutButton.states.lookup("default")!.set("opacity", 1); this.chartContainer.set("layout", verticalLayout); const plotContainer = this.plotContainer; plotContainer.children.push(this.seriesContainer); this._disposers.push(this._processAxis(this.xAxes, this.bottomAxesContainer)); this._disposers.push(this._processAxis(this.yAxes, this.leftAxesContainer)); plotContainer.children.push(this.topGridContainer); plotContainer.children.push(this.bulletsContainer); plotContainer.children.moveValue(zoomOutButton); // Setting trasnparent background so that full body of the plot container // is interactive plotContainer.set("interactive", true); plotContainer.set("interactiveChildren", false); plotContainer.set("background", Rectangle.new(root, { themeTags: ["xy", "background"], fill: Color.fromHex(0x000000), fillOpacity: 0 })); this._disposers.push(plotContainer.events.on("pointerdown", (event) => { this._handlePlotDown(event.originalEvent); })); this._disposers.push(plotContainer.events.on("globalpointerup", (event) => { this._handlePlotUp(event.originalEvent); })); this._disposers.push(plotContainer.events.on("globalpointermove", (event) => { this._handlePlotMove(event.originalEvent); })); } protected _removeSeries(series: this["_seriesType"]) { const xAxis = series.get("xAxis"); if (xAxis) { $array.remove(xAxis.series, series); } const yAxis = series.get("yAxis"); if (yAxis) { $array.remove(yAxis.series, series); } super._removeSeries(series); } protected _handleSetWheel() { const wheelX = this.get("wheelX"); const wheelY = this.get("wheelY"); const plotContainer = this.plotContainer; if (wheelX !== "none" || wheelY !== "none") { this._wheelDp = plotContainer.events.on("wheel", (event) => { const wheelEvent = event.originalEvent; wheelEvent.preventDefault(); const plotPoint = plotContainer.toLocal(this._root.documentPointToRoot({ x: wheelEvent.clientX, y: wheelEvent.clientY })) const wheelStep = this.get("wheelStep", 0.2); const shiftY = wheelEvent.deltaY / 100; const shiftX = wheelEvent.deltaX / 100; if ((wheelX === "zoomX" || wheelX === "zoomXY") && shiftX != 0) { this.xAxes.each((axis) => { if (axis.get("zoomX")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.x / plotContainer.width()); let newStart = start - wheelStep * (end - start) * shiftX * position; let newEnd = end + wheelStep * (end - start) * shiftX * (1 - position); if (1 / (newEnd - newStart) < axis.get("maxZoomFactor", Infinity)) { this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } } }) } if ((wheelY === "zoomX" || wheelY === "zoomXY") && shiftY != 0) { this.xAxes.each((axis) => { if (axis.get("zoomX")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.x / plotContainer.width()); let newStart = start - wheelStep * (end - start) * shiftY * position; let newEnd = end + wheelStep * (end - start) * shiftY * (1 - position); if (1 / (newEnd - newStart) < axis.get("maxZoomFactor", Infinity)) { this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } } }) } if ((wheelX === "zoomY" || wheelX === "zoomXY") && shiftX != 0) { this.yAxes.each((axis) => { if (axis.get("zoomY")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.y / plotContainer.height()); let newStart = start - wheelStep * (end - start) * shiftX * position; let newEnd = end + wheelStep * (end - start) * shiftX * (1 - position); if (1 / (newEnd - newStart) < axis.get("maxZoomFactor", Infinity)) { this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } } }) } if ((wheelY === "zoomY" || wheelY === "zoomXY") && shiftY != 0) { this.yAxes.each((axis) => { if (axis.get("zoomY")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.y / plotContainer.height()); let newStart = start - wheelStep * (end - start) * shiftY * position; let newEnd = end + wheelStep * (end - start) * shiftY * (1 - position); if (1 / (newEnd - newStart) < axis.get("maxZoomFactor", Infinity)) { this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } } }) } if ((wheelX === "panX" || wheelX === "panXY") && shiftX != 0) { this.xAxes.each((axis) => { if (axis.get("panX")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.x / plotContainer.width()); let newStart = start + wheelStep * (end - start) * shiftX * position; let newEnd = end + wheelStep * (end - start) * shiftX * (1 - position); this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } }) } if ((wheelY === "panX" || wheelY === "panXY") && shiftY != 0) { this.xAxes.each((axis) => { if (axis.get("panX")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.x / plotContainer.width()); let newStart = start + wheelStep * (end - start) * shiftY * position; let newEnd = end + wheelStep * (end - start) * shiftY * (1 - position); this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } }) } if ((wheelX === "panY" || wheelX === "panXY") && shiftX != 0) { this.yAxes.each((axis) => { if (axis.get("panY")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.y / plotContainer.height()); let newStart = start + wheelStep * (end - start) * shiftX * position; let newEnd = end + wheelStep * (end - start) * shiftX * (1 - position); this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } }) } if ((wheelY === "panY" || wheelY === "panXY") && shiftY != 0) { this.yAxes.each((axis) => { if (axis.get("panY")) { let start = axis.get("start")!; let end = axis.get("end")!; let position = axis.fixPosition(plotPoint.y / plotContainer.height()); let newStart = start + wheelStep * (end - start) * shiftY * position; let newEnd = end + wheelStep * (end - start) * shiftY * (1 - position); this._handleWheelAnimation(axis.zoom(newStart, newEnd)); } }) } }); this._disposers.push(this._wheelDp); } else { if (this._wheelDp) { this._wheelDp.dispose(); } } } protected _handlePlotDown(event: IPointerEvent) { // TODO: handle multitouch if (this.get("panX") || this.get("panY")) { const plotContainer = this.plotContainer; let local = plotContainer.toLocal(this._root.documentPointToRoot({ x: event.clientX, y: event.clientY })); if (local.x >= 0 && local.y >= 0 && local.x <= plotContainer.width() && local.y <= this.height()) { this._downPoint = local; const panX = this.get("panX"); const panY = this.get("panY"); if (panX) { this.xAxes.each((axis) => { axis._panStart = axis.get("start")!; axis._panEnd = axis.get("end")!; }) } if (panY) { this.yAxes.each((axis) => { axis._panStart = axis.get("start")!; axis._panEnd = axis.get("end")!; }) } const eventType = "panstarted"; if (this.events.isEnabled(eventType)) { this.events.dispatch(eventType, { type: eventType, target: this }); } } } } protected _handleWheelAnimation(animation?: Animation<any>) { if (animation) { animation.events.on("stopped", () => { this._dispatchWheelAnimation(); }) } else { this._dispatchWheelAnimation(); } } protected _dispatchWheelAnimation() { const eventType = "wheelended"; if (this.events.isEnabled(eventType)) { this.events.dispatch(eventType, { type: eventType, target: this }); } } protected _handlePlotUp(_event: IPointerEvent) { if (this._downPoint) { if (this.get("panX") || this.get("panY")) { const eventType = "panended"; if (this.events.isEnabled(eventType)) { this.events.dispatch(eventType, { type: eventType, target: this }); } } } // TODO: handle multitouch this._downPoint = undefined; this.xAxes.each((xAxis) => { xAxis._isPanning = false; }) this.yAxes.each((yAxis) => { yAxis._isPanning = false; }) } protected _handlePlotMove(event: IPointerEvent) { // TODO: handle multitouch const downPoint = this._downPoint!; if (downPoint) { const plotContainer = this.plotContainer; let local = plotContainer.toLocal(this._root.documentPointToRoot({ x: event.clientX, y: event.clientY })); const panX = this.get("panX"); const panY = this.get("panY"); if (panX) { let scrollbarX = this.get("scrollbarX"); if (scrollbarX) { scrollbarX.events.disableType("rangechanged"); } this.xAxes.each((axis) => { if (axis.get("panX")) { axis._isPanning = true; //const maxDeviation = axis.get("maxDeviation", 0); let panStart = axis._panStart; let panEnd = axis._panEnd; let difference = (panEnd - panStart); let deltaX = difference * (downPoint.x - local.x) / plotContainer.width(); if (axis.get("renderer").get("inversed")) { deltaX *= -1; } let start = panStart + deltaX; let end = panEnd + deltaX; if (end - start < 1 + axis.get("maxDeviation", 1) * 2) { axis.set("start", start); axis.set("end", end); } } }) if (scrollbarX) { scrollbarX.events.enableType("rangechanged"); } } if (panY) { let scrollbarY = this.get("scrollbarY"); if (scrollbarY) { scrollbarY.events.disableType("rangechanged"); } this.yAxes.each((axis) => { if (axis.get("panY")) { axis._isPanning = true; //const maxDeviation = axis.get("maxDeviation", 0); let panStart = axis._panStart; let panEnd = axis._panEnd; let difference = (panEnd - panStart); let deltaY = difference * (downPoint.y - local.y) / plotContainer.height(); if (axis.get("renderer").get("inversed")) { deltaY *= -1; } let start = panStart - deltaY; let end = panEnd - deltaY; if (end - start < 1 + axis.get("maxDeviation", 1) * 2) { axis.set("start", start); axis.set("end", end); } } }) if (scrollbarY) { scrollbarY.events.enableType("rangechanged"); } } } } public _handleCursorPosition() { const cursor = this.get("cursor"); if (cursor) { const cursorPoint = cursor.getPrivate("point"); const snapToSeries = cursor.get("snapToSeries"); if (snapToSeries && cursorPoint) { const dataItems: Array<DataItem<IXYSeriesDataItem>> = []; $array.each(snapToSeries, (series) => { if (!series.isHidden() && !series.isHiding()) { const startIndex = series.startIndex(); const endIndex = series.endIndex(); for (let i = startIndex; i < endIndex; i++) { const dataItem = series.dataItems[i]; if (dataItem && !dataItem.isHidden()) { dataItems.push(dataItem); } } } }) let minDistance = Infinity; let closestItem: DataItem<IXYSeriesDataItem> | undefined; const snapToSeriesBy = cursor.get("snapToSeriesBy"); $array.each(dataItems, (dataItem) => { const point = dataItem.get("point"); if (point) { let distance = 0; if (snapToSeriesBy == "x") { distance = Math.abs(cursorPoint.x - point.x); } else if (snapToSeriesBy == "y") { distance = Math.abs(cursorPoint.y - point.y); } else { distance = Math.hypot(cursorPoint.x - point.x, cursorPoint.y - point.y); } if (distance < minDistance) { minDistance = distance; closestItem = dataItem; } } }) $array.each(snapToSeries, (series) => { const tooltip = series.get("tooltip"); if (tooltip) { tooltip._setDataItem(undefined); } }) if (closestItem) { let series = closestItem.component as XYSeries; series.showDataItemTooltip(closestItem); const point = closestItem.get("point"); if (point) { cursor.handleMove(series.toGlobal(point), true); } } } } } public _updateCursor() { let cursor = this.get("cursor"); if (cursor) { cursor.handleMove(); } } protected _addCursor(cursor: XYCursor) { this.plotContainer.children.push(cursor); } public _prepareChildren() { super._prepareChildren(); this.series.each((series) => { this._colorize(series); }) if (this.isDirty("wheelX") || this.isDirty("wheelY")) { this._handleSetWheel(); } if (this.isDirty("cursor")) { const previous = this._prevSettings.cursor; const cursor = this.get("cursor")!; if (cursor !== previous) { this._disposeProperty("cursor"); if (previous) { previous.dispose(); } if (cursor) { cursor._setChart(this); this._addCursor(cursor); this._pushPropertyDisposer("cursor", cursor.events.on("selectended", () => { this._handleCursorSelectEnd(); })) } //this.setRaw("cursor", cursor) // to reset previous value this._prevSettings.cursor = cursor; } } if (this.isDirty("scrollbarX")) { const previous = this._prevSettings.scrollbarX; const scrollbarX = this.get("scrollbarX")!; if (scrollbarX !== previous) { this._disposeProperty("scrollbarX"); if (previous) { previous.dispose(); } if (scrollbarX) { if (!scrollbarX.parent) { this.topAxesContainer.children.push(scrollbarX); } this._pushPropertyDisposer("scrollbarX", scrollbarX.events.on("rangechanged", (e) => { this._handleScrollbar(this.xAxes, e.start, e.end); })) // Used to populate `ariaLabel` with meaningful values scrollbarX.setPrivate("positionTextFunction", (position: number) => { const axis = this.xAxes.getIndex(0); return axis ? axis.getTooltipText(position) || "" : ""; }); } this._prevSettings.scrollbarX = scrollbarX; } } if (this.isDirty("scrollbarY")) { const previous = this._prevSettings.scrollbarY; const scrollbarY = this.get("scrollbarY")!; if (scrollbarY !== previous) { this._disposeProperty("scrollbarY"); if (previous) { previous.dispose(); } if (scrollbarY) { if (!scrollbarY.parent) { this.rightAxesContainer.children.push(scrollbarY); } this._pushPropertyDisposer("scrollbarY", scrollbarY.events.on("rangechanged", (e) => { this._handleScrollbar(this.yAxes, e.start, e.end); })) // Used to populate `ariaLabel` with meaningful values scrollbarY.setPrivate("positionTextFunction", (position: number) => { const axis = this.yAxes.getIndex(0); return axis ? axis.getTooltipText(position) || "" : ""; }); } this._prevSettings.scrollbarY = scrollbarY; } } this._handleZoomOut(); } protected _processSeries(series: this["_seriesType"]) { super._processSeries(series); this._colorize(series); } protected _colorize(series: this["_seriesType"]) { const colorSet = this.get("colors")!; if (colorSet) { if (series.get("fill") == null) { const color = colorSet.next(); series._setSoft("stroke", color); series._setSoft("fill", color); } } } protected _handleCursorSelectEnd() { const cursor = this.get("cursor")!; const behavior = cursor.get("behavior"); const downPositionX = cursor.getPrivate("downPositionX", 0); const downPositionY = cursor.getPrivate("downPositionY", 0); const positionX = cursor.getPrivate("positionX", 0.5); const positionY = cursor.getPrivate("positionY", 0.5); this.xAxes.each((axis) => { if (behavior === "zoomX" || behavior === "zoomXY") { let position0 = axis.toAxisPosition(downPositionX); let position1 = axis.toAxisPosition(positionX); axis.zoom(position0, position1); } axis.setPrivate("updateScrollbar", true); }) this.yAxes.each((axis) => { if (behavior === "zoomY" || behavior === "zoomXY") { let position0 = axis.toAxisPosition(downPositionY); let position1 = axis.toAxisPosition(positionY); axis.zoom(position0, position1); } axis.setPrivate("updateScrollbar", true); }) } protected _handleScrollbar(axes: ListAutoDispose<Axis<any>>, start: number, end: number) { axes.each((axis) => { let axisStart = axis.fixPosition(start); let axisEnd = axis.fixPosition(end); let zoomAnimation = axis.zoom(axisStart, axisEnd); const updateScrollbar = "updateScrollbar"; axis.setPrivateRaw(updateScrollbar, false); if (zoomAnimation) { zoomAnimation.events.on("stopped", () => { axis.setPrivateRaw(updateScrollbar, true); }); } else { axis.setPrivateRaw(updateScrollbar, true); } }) } protected _processAxis<R extends AxisRenderer>(axes: ListAutoDispose<Axis<R>>, container: Container): IDisposer { return axes.events.onAll((change) => { if (change.type === "clear") { $array.each(change.oldValues, (axis) => { this._removeAxis(axis); }) } else if (change.type === "push") { container.children.push(change.newValue); change.newValue.processChart(this); } else if (change.type === "setIndex") { container.children.setIndex(change.index, change.newValue); change.newValue.processChart(this); } else if (change.type === "insertIndex") { container.children.insertIndex(change.index, change.newValue); change.newValue.processChart(this); } else if (change.type === "removeIndex") { this._removeAxis(change.oldValue); } else if (change.type === "moveIndex") { container.children.moveValue(change.value, change.newIndex); change.value.processChart(this); } else { throw new Error("Unknown IListEvent type"); } }); } protected _removeAxis(axis: Axis<AxisRenderer>) { if (!axis.isDisposed()) { const axisParent = axis.parent if (axisParent) { axisParent.children.removeValue(axis); } const gridContainer = axis.gridContainer; const gridParent = gridContainer.parent; if (gridParent) { gridParent.children.removeValue(gridContainer); } const topGridContainer = axis.topGridContainer; const topGridParent = topGridContainer.parent; if (topGridParent) { topGridParent.children.removeValue(topGridContainer); } } } public _updateChartLayout() { const left = this.leftAxesContainer.width(); const right = this.rightAxesContainer.width(); const bottomAxesContainer = this.bottomAxesContainer; bottomAxesContainer.set("paddingLeft", left); bottomAxesContainer.set("paddingRight", right); const topAxesContainer = this.topAxesContainer; topAxesContainer.set("paddingLeft", left); topAxesContainer.set("paddingRight", right); } /** * @ignore */ public processAxis(_axis: Axis<AxisRenderer>) { }; public _handleAxisSelection(axis: Axis<any>) { let start = axis.fixPosition(axis.get("start", 0)); let end = axis.fixPosition(axis.get("end", 1)); if (start > end) { [start, end] = [end, start]; } if (this.xAxes.indexOf(axis) != -1) { if (axis.getPrivate("updateScrollbar")) { let scrollbarX = this.get("scrollbarX"); if (scrollbarX && !scrollbarX.getPrivate("isBusy")) { scrollbarX.setRaw("start", start); scrollbarX.setRaw("end", end); scrollbarX.updateGrips(); } } } else if (this.yAxes.indexOf(axis) != -1) { if (axis.getPrivate("updateScrollbar")) { let scrollbarY = this.get("scrollbarY"); if (scrollbarY && !scrollbarY.getPrivate("isBusy")) { scrollbarY.setRaw("start", start); scrollbarY.setRaw("end", end); scrollbarY.updateGrips(); } } } this._handleZoomOut(); } protected _handleZoomOut() { let zoomOutButton = this.zoomOutButton; if (zoomOutButton && zoomOutButton.parent) { let visible = false; this.xAxes.each((axis) => { if (axis.get("start") != 0 || axis.get("end") != 1) { visible = true; } }) this.yAxes.each((axis) => { if (axis.get("start") != 0 || axis.get("end") != 1) { visible = true; } }) if (visible) { if (zoomOutButton.isHidden()) { zoomOutButton.show(); } } else { zoomOutButton.hide(); } } } /** * Checks if point is within plot area. * * @param point Reference point * @return Is within plot area? */ public inPlot(point: IPoint): boolean { const plotContainer = this.plotContainer; const otherCharts = this._otherCharts; const global = plotContainer.toGlobal(point); if (point.x >= -0.1 && point.y >= -0.1 && point.x <= plotContainer.width() + 0.1 && point.y <= plotContainer.height() + 0.1) { return true; } if (otherCharts) { for (let i = otherCharts.length - 1; i >= 0; i--) { const chart = otherCharts[i]; if (chart != this) { const chartPlotContainer = chart.plotContainer; const local = chartPlotContainer.toLocal(global); if (local.x >= -0.1 && local.y >= -0.1 && local.x <= chartPlotContainer.width() + 0.1 && local.y <= chartPlotContainer.height() + 0.1) { return true; } } } } return false; } /** * @ignore */ public arrangeTooltips() { const plotContainer = this.plotContainer; const w = plotContainer.width(); const h = plotContainer.height(); let plotT = plotContainer._display.toGlobal({ x: 0, y: 0 }); let plotB = plotContainer._display.toGlobal({ x: w, y: h }); const tooltips: Array<Tooltip> = []; let sum = 0; let minDistance = Infinity; let movePoint = this._movePoint; let maxTooltipDistance = this.get("maxTooltipDistance"); let closest: XYSeries; let closestPoint: IPoint; if ($type.isNumber(maxTooltipDistance)) { this.series.each((series) => { const tooltip = series.get("tooltip"); if (tooltip) { let point = tooltip.get("pointTo")!; if (point) { let distance = Math.hypot(movePoint.x - point.x, movePoint.y - point.y); if (distance < minDistance) { minDistance = distance; closest = series; closestPoint = point; } } } }) } const tooltipSeries: Array<XYSeries> = []; this.series.each((series) => { const tooltip = series.get("tooltip")!; if (tooltip) { let hidden = false; let point = tooltip.get("pointTo")!; if (point) { if (maxTooltipDistance >= 0) { let point = tooltip.get("pointTo")!; if (point) { if (series != closest) { let distance = Math.hypot(closestPoint.x - point.x, closestPoint.y - point.y); if (distance > maxTooltipDistance) { hidden = true; } } } } else if (maxTooltipDistance == -1) { if (series != closest) { hidden = true; } } if (!this.inPlot(this._tooltipToLocal(point)) || !tooltip.dataItem) { hidden = true; } else { if (!hidden) { sum += point.y; } } if (hidden || series.isHidden() || series.isHiding()) { tooltip.hide(0); } else { tooltip.show(); tooltips.push(tooltip); tooltipSeries.push(series); } } } }) this.setPrivate("tooltipSeries", tooltipSeries); if (this.get("arrangeTooltips")) { const tooltipContainer = this._root.tooltipContainer; tooltips.sort((a, b) => $order.compareNumber(a.get("pointTo")!.y, b.get("pointTo")!.y)); const count = tooltips.length; const average = sum / count; if (average > h / 2 + plotT.y) { tooltips.reverse(); let prevY = plotB.y; $array.each(tooltips, (tooltip) => { let height = tooltip.height(); let centerY = tooltip.get("centerY"); if (centerY instanceof Percent) { height *= centerY.value; } height += tooltip.get("marginBottom", 0); tooltip.set("bounds", { left: plotT.x, top: plotT.y, right: plotB.x, bottom: prevY }) prevY = Math.min(prevY - height, tooltip._fy - height); tooltipContainer.children.moveValue(tooltip, 0); }) } else { let prevY = 0; $array.each(tooltips, (tooltip) => { let height = tooltip.height(); let centerY = tooltip.get("centerY"); if (centerY instanceof Percent) { height *= centerY.value; } height += tooltip.get("marginBottom", 0); tooltip.set("bounds", { left: plotT.x, top: prevY, right: plotB.x, bottom: Math.max(plotT.y + h, prevY + height) }) tooltipContainer.children.moveValue(tooltip, 0); prevY = Math.max(prevY + height, tooltip._fy + height); }) } } } protected _tooltipToLocal(point: IPoint): IPoint { return this.plotContainer.toLocal(point); } /** * Fully zooms out the chart. */ public zoomOut() { this.xAxes.each((axis) => { axis.setPrivate("updateScrollbar", true); axis.zoom(0, 1); }) this.yAxes.each((axis) => { axis.setPrivate("updateScrollbar", true); axis.zoom(0, 1); }) } }
the_stack
module es { export class Collider extends Component { public static readonly lateSortOrder = 999; public castSortOrder: number = 0; /** * 对撞机的基本形状 */ public shape: Shape; /** * 如果这个碰撞器是一个触发器,它将不会引起碰撞,但它仍然会触发事件 */ public isTrigger: boolean = false; /** * 在处理冲突时,physicsLayer可以用作过滤器。Flags类有帮助位掩码的方法 */ public physicsLayer = new Ref(1 << 0); /** * 碰撞器在使用移动器移动时应该碰撞的层 * 默认为所有层 */ public collidesWithLayers: Ref<number> = new Ref(Physics.allLayers); /** * 如果为true,碰撞器将根据附加的变换缩放和旋转 */ public shouldColliderScaleAndRotateWithTransform = true; /** * 这个对撞机在物理系统注册时的边界。 * 存储这个允许我们始终能够安全地从物理系统中移除对撞机,即使它在试图移除它之前已经被移动了。 */ public registeredPhysicsBounds: Rectangle = new Rectangle(); protected _colliderRequiresAutoSizing: boolean; public _localOffsetLength: number; public _isPositionDirty: boolean = true; public _isRotationDirty: boolean = true; /** * 标记来跟踪我们的实体是否被添加到场景中 */ protected _isParentEntityAddedToScene; /** * 标记来记录我们是否注册了物理系统 */ protected _isColliderRegistered; /** * 镖师碰撞器的绝对位置 */ public get absolutePosition(): Vector2 { return Vector2.add(this.entity.transform.position, this._localOffset); } /** * 封装变换。如果碰撞器没和实体一起旋转 则返回transform.rotation */ public get rotation(): number { if (this.shouldColliderScaleAndRotateWithTransform && this.entity != null) return this.entity.transform.rotation; return 0; } public get bounds(): Rectangle { if (this._isPositionDirty || this._isRotationDirty) { this.shape.recalculateBounds(this); this._isPositionDirty = this._isRotationDirty = false; } return this.shape.bounds; } protected _localOffset: Vector2 = Vector2.zero; /** * 将localOffset添加到实体。获取碰撞器几何图形的最终位置。 * 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转 */ public get localOffset(): Vector2 { return this._localOffset; } /** * 将localOffset添加到实体。获取碰撞器几何图形的最终位置。 * 允许向一个实体添加多个碰撞器并分别定位,还允许你设置缩放/旋转 * @param value */ public set localOffset(value: Vector2) { this.setLocalOffset(value); } /** * 将localOffset添加到实体。获取碰撞器的最终位置。 * 这允许您向一个实体添加多个碰撞器并分别定位它们。 * @param offset */ public setLocalOffset(offset: Vector2): Collider { if (!this._localOffset.equals(offset)) { this.unregisterColliderWithPhysicsSystem(); this._localOffset.setTo(offset.x, offset.y); this._localOffsetLength = this._localOffset.magnitude(); this._isPositionDirty = true; this.registerColliderWithPhysicsSystem(); } return this; } /** * 如果为true,碰撞器将根据附加的变换缩放和旋转 * @param shouldColliderScaleAndRotationWithTransform */ public setShouldColliderScaleAndRotateWithTransform(shouldColliderScaleAndRotationWithTransform: boolean): Collider { this.shouldColliderScaleAndRotateWithTransform = shouldColliderScaleAndRotationWithTransform; this._isPositionDirty = this._isRotationDirty = true; return this; } public onAddedToEntity() { if (this._colliderRequiresAutoSizing) { let renderable = null; for (let i = 0; i < this.entity.components.buffer.length; i ++) { let component = this.entity.components.buffer[i]; if (component instanceof RenderableComponent){ renderable = component; break; } } if (renderable != null) { let renderableBounds = renderable.bounds.clone(); let width = renderableBounds.width / this.entity.transform.scale.x; let height = renderableBounds.height / this.entity.transform.scale.y; if (this instanceof CircleCollider) { this.radius = Math.max(width, height) * 0.5; this.localOffset = renderableBounds.center.sub(this.entity.transform.position); } else if (this instanceof BoxCollider) { this.width = width; this.height = height; this.localOffset = renderableBounds.center.sub(this.entity.transform.position); } } } this._isParentEntityAddedToScene = true; this.registerColliderWithPhysicsSystem(); } public onRemovedFromEntity() { this.unregisterColliderWithPhysicsSystem(); this._isParentEntityAddedToScene = false; } public onEntityTransformChanged(comp: ComponentTransform) { switch (comp) { case ComponentTransform.position: this._isPositionDirty = true; break; case ComponentTransform.scale: this._isPositionDirty = true; break; case ComponentTransform.rotation: this._isRotationDirty = true; break; } if (this._isColliderRegistered) Physics.updateCollider(this); } public onEnabled() { this.registerColliderWithPhysicsSystem(); this._isPositionDirty = this._isRotationDirty = true; } public onDisabled() { this.unregisterColliderWithPhysicsSystem(); } /** * 父实体会在不同的时间调用它(当添加到场景,启用,等等) */ public registerColliderWithPhysicsSystem() { // 如果在将我们添加到实体之前更改了origin等属性,则实体可以为null if (this._isParentEntityAddedToScene && !this._isColliderRegistered) { Physics.addCollider(this); this._isColliderRegistered = true; } } /** * 父实体会在不同的时候调用它(从场景中移除,禁用,等等) */ public unregisterColliderWithPhysicsSystem() { if (this._isParentEntityAddedToScene && this._isColliderRegistered) { Physics.removeCollider(this); } this._isColliderRegistered = false; } /** * 检查这个形状是否与物理系统中的其他对撞机重叠 * @param other */ public overlaps(other: Collider): boolean { return this.shape.overlaps(other.shape); } /** * 检查这个与运动应用的碰撞器(移动向量)是否与碰撞器碰撞。如果是这样,将返回true,并且结果将填充碰撞数据。 * @param collider * @param motion * @param result */ public collidesWith(collider: Collider, motion: Vector2, result: CollisionResult = new CollisionResult()): boolean { // 改变形状的位置,使它在移动后的位置,这样我们可以检查重叠 const oldPosition = this.entity.position; this.entity.position = this.entity.position.add(motion); const didCollide = this.shape.collidesWithShape(collider.shape, result); if (didCollide) result.collider = collider; // 将图形位置返回到检查前的位置 this.entity.position = oldPosition; return didCollide; } /** * 检查这个对撞机是否与对撞机发生碰撞。如果碰撞,则返回true,结果将被填充 * @param collider * @param result */ public collidesWithNonMotion(collider: Collider, result: CollisionResult = new CollisionResult()): boolean { if (this.shape.collidesWithShape(collider.shape, result)) { result.collider = collider; return true; } result.collider = null; return false; } /** * 检查此碰撞器是否已应用运动(增量运动矢量)与任何碰撞器发生碰撞。 * 如果是这样,则将返回true,并且将使用碰撞数据填充结果。 运动将设置为碰撞器在碰撞之前可以行进的最大距离。 * @param motion * @param result */ public collidesWithAny(motion: Vector2, result: CollisionResult) { // 在我们的新位置上获取我们可能会碰到的任何东西 let colliderBounds = this.bounds.clone(); colliderBounds.x += motion.x; colliderBounds.y += motion.y; let neighbors = Physics.boxcastBroadphaseExcludingSelf(this, colliderBounds, this.collidesWithLayers.value); // 更改形状位置,使其处于移动后的位置,以便我们检查是否有重叠 let oldPosition = this.shape.position.clone(); this.shape.position = Vector2.add(this.shape.position, motion); let didCollide = false; for (let neighbor of neighbors) { if (neighbor.isTrigger) continue; if (this.collidesWithNonMotion(neighbor, result)) { motion = motion.sub(result.minimumTranslationVector); this.shape.position = this.shape.position.sub(result.minimumTranslationVector); didCollide = true; } } // 将形状位置返回到检查之前的位置 this.shape.position = oldPosition.clone(); return didCollide; } /** * 检查此碰撞器是否与场景中的其他碰撞器碰撞。它相交的第一个碰撞器将在碰撞结果中返回碰撞数据。 * @param result */ public collidesWithAnyNonMotion(result: CollisionResult = new CollisionResult()) { // 在我们的新位置上获取我们可能会碰到的任何东西 let neighbors = Physics.boxcastBroadphaseExcludingSelfNonRect(this, this.collidesWithLayers.value); for (let neighbor of neighbors) { if (neighbor.isTrigger) continue; if (this.collidesWithNonMotion(neighbor, result)) return true; } return false; } } }
the_stack
import { inject } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/auth'; import { AngularFirestore, AngularFirestoreCollection, } from '@angular/fire/firestore'; import firebase from 'firebase/app'; import { switchMap, tap, map } from 'rxjs/operators'; import { Observable, of, combineLatest } from 'rxjs'; import { Store } from '@datorama/akita'; import { FireAuthState, initialAuthState } from './auth.model'; import { WriteOptions, UpdateCallback } from '../utils/types'; export const authProviders = [ 'github', 'google', 'microsoft', 'facebook', 'twitter', 'email', 'apple', ] as const; export type FireProvider = typeof authProviders[number]; type UserCredential = firebase.auth.UserCredential; type AuthProvider = firebase.auth.AuthProvider; /** Verify if provider is part of the list of Authentication provider provided by Firebase Auth */ export function isFireAuthProvider(provider: any): provider is FireProvider { return ( typeof provider === 'string' && authProviders.includes(provider as any) ); } /** * Get the custom claims of a user. If no key is provided, return the whole claims object * @param user The user object returned by Firebase Auth * @param roles Keys of the custom claims inside the claim objet */ export async function getCustomClaims( user: firebase.User, roles?: string | string[] ): Promise<Record<string, any>> { const { claims } = await user.getIdTokenResult(); if (!roles) { return claims; } const keys = Array.isArray(roles) ? roles : [roles]; return Object.keys(claims) .filter((key) => keys.includes(key)) .reduce((acc, key) => { acc[key] = claims[key]; return acc; }, {}); } /** * Get the Authentication Provider based on its name * @param provider string literal representing the name of the provider */ export function getAuthProvider(provider: FireProvider) { switch (provider) { case 'email': return new firebase.auth.EmailAuthProvider(); case 'facebook': return new firebase.auth.FacebookAuthProvider(); case 'github': return new firebase.auth.GithubAuthProvider(); case 'google': return new firebase.auth.GoogleAuthProvider(); case 'microsoft': return new firebase.auth.OAuthProvider('microsoft.com'); case 'twitter': return new firebase.auth.TwitterAuthProvider(); case 'apple': return new firebase.auth.OAuthProvider('apple.com'); } } export class FireAuthService<S extends FireAuthState> { private collection: AngularFirestoreCollection<S['profile']>; protected collectionPath = 'users'; protected db: AngularFirestore; public auth: AngularFireAuth; /** Triggered when the profile has been created */ protected onCreate?(profile: S['profile'], options: WriteOptions): any; /** Triggered when the profile has been updated */ protected onUpdate?(profile: S['profile'], options: WriteOptions): any; /** Triggered when the profile has been deleted */ protected onDelete?(options: WriteOptions): any; /** Triggered when user signin for the first time or signup with email & password */ protected onSignup?(user: UserCredential, options: WriteOptions): any; /** Triggered when a user signin, except for the first time @see onSignup */ protected onSignin?(user: UserCredential): any; /** Triggered when a user signout */ protected onSignout?(): any; constructor( protected store: Store<S>, db?: AngularFirestore, auth?: AngularFireAuth ) { this.db = db || inject(AngularFirestore); this.auth = auth || inject(AngularFireAuth); this.collection = this.db.collection(this.path); } /** * Select the profile in the Firestore * @note can be override to point to a different place */ protected selectProfile(user: firebase.User): Observable<S['profile']> { return this.collection.doc<S['profile']>(user.uid).valueChanges(); } /** * Select the roles for this user. Can be in custom claims or in a Firestore collection * @param user The user given by FireAuth * @see getCustomClaims to get the custom claims out of the user * @note Can be overwritten */ protected selectRoles( user: firebase.User ): Promise<S['roles']> | Observable<S['roles']> { return of(null); } /** * Function triggered when getting data from firestore * @note should be overwritten */ protected formatFromFirestore(user: any): S['profile'] { return user; } /** * Function triggered when adding/updating data to firestore * @note should be overwritten */ protected formatToFirestore(user: S['profile']): any { return user; } /** * Function triggered when transforming a user into a profile * @param user The user object from FireAuth * @param ctx The context given on signup * @note Should be override */ protected createProfile( user: firebase.User, ctx?: any ): Promise<Partial<S['profile']>> | Partial<S['profile']> { return { photoURL: user.photoURL, displayName: user.displayName, } as any; } /** * The current sign-in user (or null) * @returns a Promise in v6.*.* & a snapshot in v5.*.* */ get user() { return this.auth.currentUser; } get idKey() { return this.constructor['idKey'] || 'id'; } /** The path to the profile in firestore */ get path() { return this.constructor['path'] || this.collectionPath; } /** Start listening on User */ sync() { return this.auth.authState.pipe( switchMap((user) => user ? combineLatest([ of(user), this.selectProfile(user), this.selectRoles(user), ]) : of([undefined, undefined, undefined]) ), tap(([user = {}, userProfile, roles]) => { const profile = this.formatFromFirestore(userProfile); const { uid, emailVerified } = user; this.store.update({ uid, emailVerified, profile, roles } as any); }), map(([user, userProfile, roles]) => user ? [user, this.formatFromFirestore(userProfile), roles] : null ) ); } /** * @description Delete user from authentication service and database * WARNING This is security sensitive operation */ async delete(options: WriteOptions = {}) { const user = await this.user; if (!user) { throw new Error('No user connected'); } const { write = this.db.firestore.batch(), ctx } = options; const { ref } = this.collection.doc(user.uid); write.delete(ref); if (this.onDelete) { await this.onDelete({ write, ctx }); } if (!options.write) { await (write as firebase.firestore.WriteBatch).commit(); } return user.delete(); } /** Update the current profile of the authenticated user */ async update( profile: Partial<S['profile']> | UpdateCallback<S['profile']>, options: WriteOptions = {} ) { const user = await this.user; if (!user.uid) { throw new Error('No user connected.'); } const { ref } = this.collection.doc(user.uid); if (typeof profile === 'function') { return this.db.firestore.runTransaction(async (tx) => { const snapshot = await tx.get(ref); const doc = Object.freeze({ ...snapshot.data(), [this.idKey]: snapshot.id, }); const data = (profile as UpdateCallback<S['profile']>)( this.formatToFirestore(doc), tx ); tx.update(ref, data); if (this.onUpdate) { await this.onUpdate(data, { write: tx, ctx: options.ctx }); } return tx; }); } else if (typeof profile === 'object') { const { write = this.db.firestore.batch(), ctx } = options; write.update(ref, this.formatToFirestore(profile)); if (this.onUpdate) { await this.onUpdate(profile, { write, ctx }); } // If there is no atomic write provided if (!options.write) { return (write as firebase.firestore.WriteBatch).commit(); } } } /** Create a user based on email and password */ async signup( email: string, password: string, options: WriteOptions = {} ): Promise<UserCredential> { const cred = await this.auth.createUserWithEmailAndPassword( email, password ); const { write = this.db.firestore.batch(), ctx } = options; if (this.onSignup) { await this.onSignup(cred, { write, ctx }); } const profile = await this.createProfile(cred.user, ctx); const { ref } = this.collection.doc(cred.user.uid); (write as firebase.firestore.WriteBatch).set( ref, this.formatToFirestore(profile) ); if (this.onCreate) { await this.onCreate(profile, { write, ctx }); } if (!options.write) { await (write as firebase.firestore.WriteBatch).commit(); } return cred; } /** Signin with email & password, provider name, provider objet or custom token */ // tslint:disable-next-line: unified-signatures signin( email: string, password: string, options?: WriteOptions ): Promise<UserCredential>; signin( authProvider: AuthProvider, options?: WriteOptions ): Promise<UserCredential>; signin( provider?: FireProvider, options?: WriteOptions ): Promise<UserCredential>; // tslint:disable-next-line: unified-signatures signin(token: string, options?: WriteOptions): Promise<UserCredential>; async signin( provider?: FireProvider | AuthProvider | string, passwordOrOptions?: string | WriteOptions ): Promise<UserCredential> { this.store.setLoading(true); let profile; try { let cred: UserCredential; const write = this.db.firestore.batch(); if (!provider) { cred = await this.auth.signInAnonymously(); } else if ( passwordOrOptions && typeof provider === 'string' && typeof passwordOrOptions === 'string' ) { cred = await this.auth.signInWithEmailAndPassword( provider, passwordOrOptions ); } else if (typeof provider === 'object') { cred = await this.auth.signInWithPopup(provider); } else if (isFireAuthProvider(provider)) { const authProvider = getAuthProvider(provider); cred = await this.auth.signInWithPopup(authProvider); } else { cred = await this.auth.signInWithCustomToken(provider); } if (cred.additionalUserInfo.isNewUser) { if (this.onSignup) { await this.onSignup(cred, {}); } profile = await this.createProfile(cred.user); this.store.update({ profile } as S['profile']); const { ref } = this.collection.doc(cred.user.uid); write.set(ref, this.formatToFirestore(profile)); if (this.onCreate) { if (typeof passwordOrOptions === 'object') { await this.onCreate(profile, { write, ctx: passwordOrOptions.ctx }); } else { await this.onCreate(profile, { write, ctx: {} }); } } await write.commit(); } else { try { const collection = this.collection.doc(cred.user.uid); const document = await collection.get().toPromise(); const { uid, emailVerified } = cred.user; if (document.exists) { profile = this.formatFromFirestore(document.data()); } else { profile = await this.createProfile(cred.user); write.set(collection.ref, this.formatToFirestore(profile)); write.commit(); } this.store.update({ profile, uid, emailVerified } as any); } catch (error) { console.error(error); } } if (this.onSignin) { await this.onSignin(cred); } this.store.setLoading(false); return cred; } catch (err) { this.store.setLoading(false); if (err.code === 'auth/operation-not-allowed') { console.warn( 'You tried to connect with a disabled auth provider. Enable it in Firebase console' ); } throw err; } } /** Signs out the current user and clear the store */ async signOut() { await this.auth.signOut(); this.store.update(initialAuthState as Partial<S>); if (this.onSignout) { await this.onSignout(); } } }
the_stack
import { mat4, quat, vec3, vec4 } from 'gl-matrix'; import { auxiliaries, } from 'webgl-operate'; import { Buffer, Camera, Canvas, Context, DefaultFramebuffer, EventProvider, Invalidate, Navigation, Program, Renderer, Shader, Wizard, } from 'webgl-operate'; import { Demo } from '../demo'; // import { Benchmark } from './benchmark'; import { importPointsFromCSV } from './csv-import'; /* spellchecker: enable */ // tslint:disable:max-classes-per-file export class PointCloudRenderer extends Renderer { protected static readonly DEFAULT_POINT_SIZE = 1.0 / 8.0; // protected _benchmark: Benchmark; protected _camera: Camera; protected _navigation: Navigation; protected _model: mat4; protected _particleVBO: Buffer; protected _instancesVBO: Buffer; protected readonly _uvLocation: GLuint = 0; protected readonly _positionLocation: GLuint = 1; protected _data: Array<Float32Array> = new Array<Float32Array>(0); protected _push = false; protected _drawIndex = -1; protected _drawRanges: Array<[GLuint, GLuint]>; // protected _triangles = 6; protected _program: Program; protected _pointSize: GLfloat = PointCloudRenderer.DEFAULT_POINT_SIZE; protected _billboards = true; protected _alpha2Coverage = false; protected _alphaBlending = false; protected _phongShading = true; protected _renderingConfigAltered = true; protected _uModel: WebGLUniformLocation; protected _uView: WebGLUniformLocation; protected _uViewProjection: WebGLUniformLocation; protected _uLight: WebGLUniformLocation; protected _defaultFBO: DefaultFramebuffer; /** * Initializes and sets up buffer, cube geometry, camera and links shaders with program. * @param context - valid context to create the object for. * @param identifier - meaningful name for identification of this instance. * @param mouseEventProvider - required for mouse interaction * @returns - whether initialization was successful */ protected onInitialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean { const gl = context.gl; const gl2facade = context.gl2facade; context.enable(['ANGLE_instanced_arrays']); this._defaultFBO = new DefaultFramebuffer(context, 'DefaultFBO'); this._defaultFBO.initialize(); this._defaultFBO.bind(); const floatSize: number = context.byteSizeOfFormat(gl.R32F); const particle = new Float32Array([-1.0, -1.0, +1.0, -1.0, +1.0, +1.0, -1.0, +1.0]); // Generate triangle fan geometry of n triangles: // const hypotenuse = Math.sqrt(1 + Math.pow(Math.tan(Math.PI / this._triangles), 2.0)); // const particle = new Float32Array(2 * (2 + this._triangles)); // particle[0] = 0.0; // particle[1] = 0.0; // for (let i = 0; i <= this._triangles; ++i) { // const alpha = i * (2.0 * Math.PI / this._triangles); // particle[i * 2 + 2] = Math.cos(alpha) * hypotenuse; // particle[i * 2 + 3] = Math.sin(alpha) * hypotenuse; // } this._particleVBO = new Buffer(context, 'particleVBO'); this._particleVBO.initialize(gl.ARRAY_BUFFER); this._particleVBO.attribEnable(this._uvLocation, 2, gl.FLOAT, false , 2 * floatSize, 0, true, false); gl2facade.vertexAttribDivisor(this._uvLocation, 0); this._particleVBO.data(particle, gl.STATIC_DRAW); this._instancesVBO = new Buffer(context, 'instancesVBO'); this._instancesVBO.initialize(gl.ARRAY_BUFFER); this._instancesVBO.attribEnable(this._positionLocation, 3, gl.FLOAT, false , 3 * floatSize, 0, true, false); gl2facade.vertexAttribDivisor(this._positionLocation, 1); // this._instancesVBO.data(this._data[i], gl.DYNAMIC_DRAW); const vert = new Shader(context, gl.VERTEX_SHADER, 'particle.vert'); vert.initialize(require('./particle.vert')); const frag = new Shader(context, gl.FRAGMENT_SHADER, 'particle.frag'); frag.initialize(require('./particle.frag')); this._program = new Program(context, 'ParticleProgram'); this._program.initialize([vert, frag], false); this._program.attribute('a_uv', this._uvLocation); this._program.attribute('a_position', this._positionLocation); this._program.link(); this._program.bind(); this._uModel = this._program.uniform('u_model'); this._uView = this._program.uniform('u_view'); this._uViewProjection = this._program.uniform('u_viewProjection'); this._uLight = this._program.uniform('u_light'); this._camera = new Camera(); this._camera.center = vec3.fromValues(0.0, 0.0, 0.0); this._camera.up = vec3.fromValues(0.0, 1.0, 0.0); this._camera.eye = vec3.fromValues(0.0, 0.0, 5.0); this._camera.near = 0.1; this._camera.far = 5.0 + Math.sqrt(32.0); // 1² + 1² -> range in that particles are generated ... gl.uniform2f(this._program.uniform('u_nearFar'), this._camera.near, this._camera.far); this._navigation = new Navigation(callback, eventProvider); this._navigation.camera = this._camera; this._model = mat4.fromRotationTranslationScale(mat4.create(), quat.create() , [0.0, 0.0, 0.0], [2.0, 2.0, 2.0]); const positions = new Float32Array(1 * 1e4); positions.forEach((value, index, array) => array[index] = Math.random() * 5.0 - 2.5); this.data = new Array(positions); // prepare draw binding this._defaultFBO.bind(); this._defaultFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, true, false); gl.viewport(0, 0, this._frameSize[0], this._frameSize[1]); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); gl.enable(gl.DEPTH_TEST); this._particleVBO.bind(); this._instancesVBO.bind(); this._program.bind(); this._alphaBlending = true; this._alpha2Coverage = context.antialias; return true; } /** * Uninitializes buffers, geometry and program. */ protected onUninitialize(): void { super.uninitialize(); this._particleVBO.attribDisable(this._uvLocation); this._particleVBO.uninitialize(); this._instancesVBO.attribDisable(this._positionLocation); this._instancesVBO.uninitialize(); this._program.uninitialize(); this._defaultFBO.uninitialize(); } protected onDiscarded(): void { this._altered.alter('canvasSize'); this._altered.alter('clearColor'); this._altered.alter('frameSize'); this._altered.alter('multiFrameNumber'); } /** * This is invoked in order to check if rendering of a frame is required by means of implementation specific * evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation, * frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have * changed or the renderer was invalidated @see{@link invalidate}. * @returns whether to redraw */ protected onUpdate(): boolean { this._navigation.update(); // return this._altered.any || this._camera.altered || this._renderingConfigAltered; return true; } /** * This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and * camera-updates. */ protected onPrepare(): void { const gl = this._context.gl; if (this._altered.canvasSize) { this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; this._camera.viewport = this._canvasSize; gl.uniform2f(this._program.uniform('u_size'), this._pointSize, this._frameSize[0]); } if (this._altered.clearColor) { this._defaultFBO.clearColor(this._clearColor); } this._altered.reset(); this._camera.altered = false; // Create full float32 array containing all provided data set. if (this._push) { const range = this._drawRanges[this._data.length - 1]; const buffer = new Float32Array(range[0] + range[1]); for (let i = 0; i < this._data.length; ++i) { buffer.set(this._data[i], this._drawRanges[i][0]); } this._instancesVBO.data(buffer, gl.STATIC_DRAW); this._push = false; } if (!this._renderingConfigAltered) { return; } gl.uniform2f(this._program.uniform('u_size'), this._pointSize, this._frameSize[0]); gl.uniform2i(this._program.uniform('u_mode'), !this._billboards, this._phongShading); // enable alpha to coverage and appropriate blending (if context was initialized with antialiasing enabled) if (this._alpha2Coverage) { gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE); gl.sampleCoverage(1.0, false); } else { gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); } if (this._alphaBlending) { gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } else { gl.disable(gl.BLEND); } this._renderingConfigAltered = false; } protected onFrame(): void { const gl = this._context.gl; const gl2facade = this.context.gl2facade; this._defaultFBO.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, false, false); gl.viewport(0, 0, this._frameSize[0], this._frameSize[1]); gl.uniformMatrix4fv(this._uModel, false, this._model); gl.uniformMatrix4fv(this._uView, false, this._camera.view); gl.uniformMatrix4fv(this._uViewProjection, false, this._camera.viewProjection); const light = vec4.fromValues(-2.0, 2.0, 4.0, 0.0); vec4.normalize(light, vec4.transformMat4(light, light, this._camera.view)); gl.uniform3f(this._uLight, light[0], light[1], light[2]); if (this._drawIndex < 0) { return; } const first = this._drawRanges[this._drawIndex][0]; const instanceCount = this._drawRanges[this._drawIndex][1] / 3; this._instancesVBO.attribEnable(this._positionLocation, 3, gl.FLOAT, false , 3 * 4, first * 4, true, false); if (this._billboards) { gl2facade.drawArraysInstanced(gl.TRIANGLE_FAN, 0, 4, instanceCount); } else { gl2facade.drawArraysInstanced(gl.POINTS, 0, 1, instanceCount); } } protected onSwap(): void { // if (this._benchmark && this._benchmark.running) { // this._benchmark.frame(); // this.invalidate(true); // } if (this._data.length > 1) { this.draw = (this._drawIndex + 1) % this._data.length; this.invalidate(true); } } set data(data: Array<Float32Array>) { this._data = data; this._drawRanges = new Array<[number, number]>(data.length); let index = 0; for (let i = 0; i < data.length; ++i) { this._drawRanges[i] = [index, data[i].length]; index += data[i].length; } this.draw = 0; this._push = true; } set draw(index: number) { if (this._drawIndex === index) { return; } this._drawIndex = index; } // benchmark(): void { // if (!this._benchmark) { // this._benchmark = new Benchmark(); // } // const values = [0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 2e6, 4e6, 6e6, 8e6, 10e6, 12e6, 14e6, 16e6]; // const numPointsRendered = this._numPointsToRender; // this._benchmark.initialize(values.length, 1000, 100, // (frame: number, framesForWarmup: number, framesPerCycle: number, cycle: number): void => { // // called per frame benchmarked ... // const phi = Math.PI * 2.0 * 1.0 / (cycle < 0 ? framesForWarmup : framesPerCycle) * frame; // this._camera.up = vec3.fromValues(0.0, 1.0, 0.0); // this._camera.center = vec3.fromValues(0.0, 0.0, 0.0); // this._camera.eye = vec3.fromValues(4.0 * Math.sin(phi), 0.0, 4.0 * Math.cos(phi)); // if (cycle < 0) { // warmup // this._numPointsToRender = 1e6; // } else { // this._numPointsToRender = values[cycle]; // } // }, // (cycles: number, framesForWarmup: number, framesPerCycle: number, results: Array<number>): void => { // console.log(`BENCHMARK CONFIG`); // console.log(`frameSize: ${this._frameSize}, pointSize: ${this._pointSize}`); // console.log(`alpha2Coverage: ${this._alpha2Coverage}, alphaBlending ${this._alphaBlending}, // billboards: ${this._billboards}, phongShading: ${this._phongShading}`); // console.log(`#cycles: ${cycles}, #framesForWarmup: ${framesForWarmup}, // #framesPerCycle: ${framesPerCycle}`); // console.log(`values: ${JSON.stringify(values)}`); // console.log(`BENCHMARK RESULTS`); // console.log(JSON.stringify(results)); // this._numPointsToRender = numPointsRendered; // }); // this.invalidate(true); // } set model(model: mat4) { this._model = model; this.invalidate(true); } set pointSize(size: GLfloat) { if (this._pointSize === size) { return; } this._pointSize = Math.max(0.0, Math.min(128.0, size)); this._renderingConfigAltered = true; this.invalidate(); } get pointSize(): GLfloat { return this._pointSize; } set alpha2Coverage(value: boolean) { if (this._alpha2Coverage === value) { return; } this._alpha2Coverage = value; this._renderingConfigAltered = true; this.invalidate(); } get alpha2Coverage(): boolean { return this._alpha2Coverage; } set alphaBlending(value: boolean) { if (this._alphaBlending === value) { return; } this._alphaBlending = value; this._renderingConfigAltered = true; this.invalidate(); } get alphaBlending(): boolean { return this._alphaBlending; } set billboards(value: boolean) { if (this._billboards === value) { return; } this._billboards = value; this._renderingConfigAltered = true; this.invalidate(); } get billboards(): boolean { return this._billboards; } set phongShading(value: boolean) { if (this._phongShading === value) { return; } this._phongShading = value; this._renderingConfigAltered = true; this.invalidate(); } get phongShading(): boolean { return this._phongShading; } } export class PointCloudDemo extends Demo { private _canvas: Canvas; private _renderer: PointCloudRenderer; onInitialize(element: HTMLCanvasElement | string): boolean { const aa = auxiliaries.GETparameter('antialias'); this._canvas = new Canvas(element, { antialias: aa === undefined ? true : JSON.parse(aa!), }); this._canvas.controller.multiFrameNumber = 1; this._canvas.framePrecision = Wizard.Precision.byte; this._canvas.frameScale = [1.0, 1.0]; this._renderer = new PointCloudRenderer(); this._canvas.renderer = this._renderer; const input = document.getElementById('input-file')! as HTMLInputElement; // const label = document.getElementById('label-file')! as HTMLLabelElement; input.addEventListener('change', () => { const progress = document.getElementById('progress-file')! as HTMLProgressElement; importPointsFromCSV(input.files!, progress).then(result => this._renderer.data = result); }); return true; } onUninitialize(): void { this._canvas.dispose(); (this._renderer as Renderer).uninitialize(); } get canvas(): Canvas { return this._canvas; } get renderer(): PointCloudRenderer { return this._renderer; } }
the_stack
import { waffle } from "hardhat" import { expect } from "chai" import blsData from "./data/bls" import { blsDeployment } from "./fixtures" import type { BLS } from "../typechain" describe("BLS", () => { let bls: BLS beforeEach("load test fixture", async () => { const contracts = await waffle.loadFixture(blsDeployment) bls = contracts.bls as BLS }) it("should be able to verify BLS signature", async () => { // Corresponding test in Go library: bls_test.go TestSignAndVerifyG1 const result = await bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) await expect(result).to.be.true }) it("should be able to verify threshold BLS recovered/reconstructed signature", async () => { // Corresponding test in Go library: bls_test.go TestThresholdBLS const result = await bls.verify( "0x1644bcbb604e3608225d1826bab0b926f2df4fb506e1aa3641d5ab350ebceb5825c7df94f3a87e9dd6e11865dfdbdd3db69eab4951c8bc2250fb51da5f813009131e0c9e6d90d91741458b522b57ca99b597dd922dd31f61a2f69412ce3220d31a1ec4b09ef2ea1d6ba7cad98386f6049b5eec5fb3a40408229dc75c5759f184", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x23cbfa4b2fcbf43a44d8a4b2a9aa1a9123f183794fa7b53c633c2de7ada5b5ca174f81900dc4ca5672768d51c12dfcb0eac2aafba0a66ac54b76f689dc1fe321" ) await expect(result).to.be.true }) it("should use reasonable amount of gas", async () => { // Corresponding test in Go library: bls_test.go TestThresholdBLS const gasEstimate = await bls.estimateGas.verify( "0x1644bcbb604e3608225d1826bab0b926f2df4fb506e1aa3641d5ab350ebceb5825c7df94f3a87e9dd6e11865dfdbdd3db69eab4951c8bc2250fb51da5f813009131e0c9e6d90d91741458b522b57ca99b597dd922dd31f61a2f69412ce3220d31a1ec4b09ef2ea1d6ba7cad98386f6049b5eec5fb3a40408229dc75c5759f184", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x23cbfa4b2fcbf43a44d8a4b2a9aa1a9123f183794fa7b53c633c2de7ada5b5ca174f81900dc4ca5672768d51c12dfcb0eac2aafba0a66ac54b76f689dc1fe321" ) // make sure no change will make the verification more expensive than it is now await expect(gasEstimate.toNumber()).to.be.lessThan( 306682, "BLS verification is too expensive" ) }) it("should be able to verify BLS aggregated signature", async () => { // Corresponding test in Go library: bls_test.go TestAggregateBLS const result = await bls.verify( "0x04ab0e5862ecdffda6bab4465c4ee88a3b71a86f178c1ac6e89a4827464c618215f83a353b5ba5126f7fdfb21998fb36d1169db87ea4042ac0d60106c98c9b8122c158a3411a0ea19841c60bcc1da84cf94f5959f1783d7ee751a48d909f58f10bbcfc4acb66b369e61c91b3a5620167ab861a80c639d1fd14b2414cd386853b", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x0855a2afab929270bd423e0d4069250519a45e4c3bcb33f53531f5b6988bb87b14301047405783a8d52311f4dfebe6a8f5acc7f299cf576c38cf726bc9fc0a1a" ) await expect(result).to.be.true }) it("should fail to verify invalid BLS signature", async () => { const result = await bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x0855a2afab929270bd423e0d4069250519a45e4c3bcb33f53531f5b6988bb87b14301047405783a8d52311f4dfebe6a8f5acc7f299cf576c38cf726bc9fc0a1a" ) await expect(result).to.be.false }) it("should fail to verify BLS signature without valid message", async () => { const result = await bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x1a01114fce4c287d8beb49616ca8f2c2be211820b73340c79bd4aada0c4f66af1bcbbb9c398c87dc504e9d275b6f5f97215a081a85d3161910158b4ab331f7bc", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) await expect(result).to.be.false }) it("should fail to verify BLS signature without valid public key", async () => { const result = await bls.verify( "0x1644bcbb604e3608225d1826bab0b926f2df4fb506e1aa3641d5ab350ebceb5825c7df94f3a87e9dd6e11865dfdbdd3db69eab4951c8bc2250fb51da5f813009131e0c9e6d90d91741458b522b57ca99b597dd922dd31f61a2f69412ce3220d31a1ec4b09ef2ea1d6ba7cad98386f6049b5eec5fb3a40408229dc75c5759f184", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) await expect(result).to.be.false }) it("should be able to sign a message and verify it", async () => { const message = "0x4120626561722077616c6b7320696e746f206120626172203132332e2e2e" const signature = await bls.sign(message, blsData.secretKey) const actual = await bls.verifyBytes( blsData.groupPubKey, message, signature ) await expect(actual).to.be.true }) describe("verify", async () => { it("should fail for public key having less than 128 bytes", async () => { await await expect( bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034df", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) // TODO: The exact message should be "Invalid G2 bytes length" but due to // https://github.com/nomiclabs/hardhat/issues/1873 the message // is "library was called directly". Until it's resolved, we don't // assert about the message. ).to.be.reverted }) it("should fail for public key having more than 128 bytes", async () => { await await expect( bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcdcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) // TODO: The exact message should be "Invalid G2 bytes length" but due to // https://github.com/nomiclabs/hardhat/issues/1873 the message // is "library was called directly". Until it's resolved, we don't // assert about the message. ).to.be.reverted }) it("should fail for message having less than 64 bytes", async () => { await await expect( bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d2234606", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) // TODO: The exact message should be "Invalid G1 bytes length" but due to // https://github.com/nomiclabs/hardhat/issues/1873 the message // is "library was called directly". Until it's resolved, we don't // assert about the message. ).to.be.reverted }) it("should fail for message having more than 64 bytes", async () => { await await expect( bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d22346066363", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c" ) // TODO: The exact message should be "Invalid G1 bytes length" but due to // https://github.com/nomiclabs/hardhat/issues/1873 the message // is "library was called directly". Until it's resolved, we don't // assert about the message. ).to.be.reverted }) it("should fail for signature having less than 64 bytes", async () => { await await expect( bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa737" ) // TODO: The exact message should be "Invalid G1 bytes length" but due to // https://github.com/nomiclabs/hardhat/issues/1873 the message // is "library was called directly". Until it's resolved, we don't // assert about the message. ).to.be.reverted }) it("should fail for signature having more than 64 bytes", async () => { await await expect( bls.verify( "0x1f1954b33144db2b5c90da089e8bde287ec7089d5d6433f3b6becaefdb678b1b2a9de38d14bef2cf9afc3c698a4211fa7ada7b4f036a2dfef0dc122b423259d01659dc18b57722ecf6a4beb4d04dfe780a660c4c3bb2b165ab8486114c464c621bf37ecdba226629c20908c7f475c5b3a7628ce26d696436eab0b0148034dfcd", "0x15c30f4b6cf6dbbcbdcc10fe22f54c8170aea44e198139b776d512d8f027319a1b9e8bfaf1383978231ce98e42bafc8129f473fc993cf60ce327f7d223460663", "0x112d462728e89432b0fe40251eeb6608aed4560f3dc833a9877f5010ace9b1312006dbbe2f30c6e0e3e7ec47dc078b7b6b773379d44d64e44ec4e017bfa7375c5c" ) // TODO: The exact message should be "Invalid G1 bytes length" but due to // https://github.com/nomiclabs/hardhat/issues/1873 the message // is "library was called directly". Until it's resolved, we don't // assert about the message. ).to.be.reverted }) }) })
the_stack
import React, { useState, useEffect, useRef, CSSProperties, useContext, KeyboardEvent } from "react" import { RouteComponentProps as CProps } from "@reach/router" import { ReactiveBase, ReactiveList, DataSearch, MultiList, SelectedFilters, SingleRange, SingleDataList, StateProvider, DateRange, MultiDataList } from '@appbaseio/reactivesearch' import { ytTheme, media, isGatsbyServer, CenterDiv } from "../MainLayout" import styled from 'styled-components' import _, { Dictionary } from 'lodash' import { VideoSearchResults, SearchHelp, NoResult } from './VideoSearchResults' import { useMediaQuery } from 'react-responsive' import { Button } from '../Button' import { FilterList as IconFilter, Close as IconClose, List as IconList } from '@styled-icons/material' import { TopSiteBar } from '../SiteMenu' import { IdToken } from '@auth0/auth0-spa-js' import { EsCfg } from '../../common/Elastic' import queryString from 'query-string' import { saveSearch } from '../../common/YtApi' import { UserContext } from '../UserContext' const Page = styled.div` display:flex; flex-direction:column; height:100vh; ` const SearchAndFilterPane = styled.div` display:flex; flex-direction:column; min-height:0; flex-direction:row; ` const ContentPane = styled.div` padding:0; display:flex; flex-direction:column; width:100%; max-width:1100px; margin:0 auto; position: relative; ` const FiltersPane = styled.div` display:none; flex-flow:column; overflow-y: auto; justify-content:start; align-content:start; background-color: ${ytTheme.backColorBolder}; min-height:0px; /*needed for column wrap to kick in*/ padding:0.5em 0.5em; /* @media (min-width: 580px) { flex-flow: column wrap; } */ @media (${media.width.medium}) { flex-flow: column; min-width:310px; } > * { padding:0.5em 1em; /* max-width:250px; */ /* @media (${media.width.medium}) { max-width:none; } */ } > .multi-list { flex: 1 1 auto; min-height:300px; /*needed for column wrap to kick in*/ } > .multi-list.tags { flex: 4 1 auto } ul { overflow-y:auto; max-height:none; padding: 0 1em 0 0.2em; li { min-height:none; margin:0em; padding: 0px; label { padding:0px; } } li.active, li:hover { span, label { font-weight: normal; color: ${ytTheme.themeColorBolder}; text-shadow: ${ytTheme.fontThemeShadow}; } } } h2 { text-transform: uppercase; color: ${ytTheme.fontColor}; margin:0.5em 0em; } .DayPickerInput input { height: 2.5em !important; padding: 1em .7em !important; } ` const SearchTextBoxStyle = styled.div` width:100%; input { width:100%; font-size:1.5em; } ` const SearchPane = styled.div` padding: 0.5em 1em; ` const SearchSelectionPane = styled.div` display: flex; justify-content: space-between; padding: 0.5em 0 0; ` const ResultsPane = styled.div` position:relative; height:100%; width:100%; overflow-y:scroll; select { background:${ytTheme.backColor}; outline:1px solid #333; color:${ytTheme.fontColor}; } ` const FilteredListStyle: React.CSSProperties = { display: "flex", flexDirection: "column" } interface SortValue { field: string, sort: 'asc' | 'desc' } const sortOptions: Dictionary<string> = { 'Relevance': '_score', //'Views': 'views', 'Uploaded': 'upload_date' } export const VideoSearch = ({ esCfg }: CProps<{ esCfg: EsCfg }>) => { const [sort, setSort] = useState<SortValue>({ field: '_score', sort: 'desc' }) const [filterOpened, setFilterOpened] = useState(false) const filterOnRight = useMediaQuery({ query: `(${media.width.medium})` }) const filterVisible = filterOnRight || filterOpened const resultsVisible = filterOnRight || !filterOpened if (isGatsbyServer()) return <div></div> return ( <ReactiveBase app={esCfg.indexes.caption} url={esCfg.url} credentials={esCfg.creds} themePreset="dark" theme={{ typography: { fontSize: ytTheme.fontSize, fontFamily: ytTheme.fontFamily }, colors: { textColor: ytTheme.fontColor, primaryColor: ytTheme.themeColor } }} > <Page> <TopSiteBar showLogin style={{ flex: '0 0 auto' }} /> <SearchAndFilterPane style={{ flex: '1 1 auto', flexDirection: filterOpened && !filterOnRight ? 'column' : 'row' }}> <ContentPane> <SearchPane> <SearchTexBox /> <SearchSelectionPane> <SelectedFilters /> {!filterOnRight && <div style={{ verticalAlign: 'top' }} > <Button label={filterOpened ? "Results" : "Filter"} icon={filterOpened ? <IconList /> : <IconFilter />} onclick={_ => setFilterOpened(!filterOpened)} /> </div>} </SearchSelectionPane> </SearchPane> <ResultsPane id="results" style={{ display: resultsVisible ? 'block' : 'none' }}> <StateProvider strict={false} > {({ searchState }) => { const query = searchState?.q?.value const empty = !query && !searchState?.channel?.value && !searchState?.group?.value if (empty) return SearchHelp return <ReactiveList componentId="result" react={{ and: ['q', 'sort', 'tags', 'channel', 'upload', 'part'] }} infiniteScroll scrollTarget="results" size={50} dataField={sort.field} sortBy={sort.sort} showResultStats={false} showLoader={false} renderNoResults={() => <NoResult />} onError={e => console.log("search error:", e)} > {(renderState) => <VideoSearchResults renderState={renderState} query={query} />} </ReactiveList> }} </StateProvider> </ResultsPane> </ContentPane> <FiltersPaneComponent setSort={setSort} sort={sort} style={{ display: filterVisible ? 'flex' : 'none' }} /> </SearchAndFilterPane> </Page> </ReactiveBase > ) } const SearchTexBox: React.FunctionComponent = () => { const [query, setQuery] = useState<string>() const [inputValue, setInputValue] = useState<string>("") const ref = useRef<HTMLInputElement>() const userCtx = useContext(UserContext) const user = userCtx?.user return <SearchTextBoxStyle> {/* the default behavior of DataSearch is to show results as you type. We can override thi behavior by using a controlled component, but this prevents smooth typing on mobile. Our solution is to use an invisible controlled DataSearch component and let users type in a vanilla input. */} <StateProvider strict={false} > {({ searchState }) => <input ref={ref} type='text' autoFocus placeholder="search..." value={inputValue} onChange={e => setInputValue(e.currentTarget.value)} onKeyPress={(e: KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter") { const q = e.currentTarget.value setQuery(q) saveSearch({ origin: location.origin, email: user?.email, query: q, channels: searchState.channel.value, tags: searchState.tags.value, updated: new Date() }) } }} /> } </StateProvider> <DataSearch componentId="q" filterLabel="Search" dataField={["caption"]} placeholder="Search video captions" autosuggest={false} showIcon={false} searchOperators queryFormat='and' style={{ display: 'none' }} URLParams onChange={(value: string) => { setInputValue(value) setQuery(value) }} value={query} /> </SearchTextBoxStyle > } const FiltersPaneComponent = ({ setSort, sort, style }: { setSort: React.Dispatch<React.SetStateAction<SortValue>>, sort: SortValue, style: CSSProperties }) => <FiltersPane style={style}> <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}> <SingleDataList componentId='sort' title='Sort' filterLabel='Sort' dataField={sort.field} data={_(sortOptions).keys().map(k => ({ label: k })).value()} showRadio={false} showCount={false} showSearch={false} onValueChange={(label: string) => { setSort({ field: sortOptions[label], sort: 'desc' }) }} /> {/* <SingleRange componentId="views" title="Views" filterLabel="Views" dataField="views" data={[ // { start: null, end: null, label: 'any' }, { start: 0, end: 1000, label: '<1k' }, { start: 1000, end: 10000, label: '1k-10k' }, { start: 10000, end: 100000, label: '10k-100k' }, { start: 100000, end: 1000000, label: '100k-1M' }, { start: 1000000, end: null, label: '1M+' }, ]} showRadio={false} URLParams /> */} <MultiDataList componentId='part' title='Part' filterLabel='Part' dataField={'part'} data={[ { label: 'Title', value: 'Title' }, { label: 'Keywords', value: 'Keywords' }, { label: 'Caption', value: 'Caption' }, { label: 'Description', value: 'Description' }, ]} defaultValue={['Title', 'Caption', 'Description']} showCheckbox={false} showSearch={false} URLParams /> </div> <DateRange componentId="upload" title="Uploaded" dataField="upload_date" URLParams /> <MultiList className="multi-list tag" componentId="tags" title="Tag" filterLabel="Group" dataField="tags" showCheckbox={false} showCount showMissing showSearch={false} react={{ and: ['q', 'upload', 'part'] }} style={FilteredListStyle} defaultQuery={_ => ({ aggs: { "tags": { aggs: { video_count: { cardinality: { field: "video_id" } } }, terms: { field: "tags", size: 50, order: { "video_count": "desc" }, missing: "N/A" } } } })} transformData={(data: any[]) => { const res = data.map(d => ({ key: d.key as string, doc_count: +d.video_count.value })) return res }} URLParams /> <MultiList className="multi-list channel" componentId="channel" filterLabel="Channel" dataField="channel_title.keyword" title="Channel" showCheckbox={false} showCount showSearch={true} react={{ and: ['q', 'tags', 'upload', 'part'] }} style={FilteredListStyle} defaultQuery={_ => ({ aggs: { "channel_title.keyword": { aggs: { video_count: { cardinality: { field: "video_id" } } }, terms: { field: "channel_title.keyword", size: 100, order: { "video_count": "desc" }, missing: "N/A" } } } })} transformData={(data: any[]) => { const res = data.map(d => ({ key: d.key as string, doc_count: +d.video_count.value })) return res }} URLParams /> </FiltersPane>
the_stack
import { RendererFactory2, Renderer2, RendererType2, RendererStyleFlags2, InjectionToken, Inject, Injectable, NgZone, Sanitizer, SecurityContext, AnimationPlayer, SchemaMetadata, Compiler } from "@angular/core"; import {ElementSchemaRegistry} from "@angular/compiler"; import {Node, ElementNode, TextNode, nodeMap, CommentNode} from "./node"; import {ReactNativeWrapper} from "./../wrapper/wrapper"; import { NativeCommand, NativeCommandCreate, NativeCommandUpdate, NativeCommandAttach, NativeCommandDetach, NativeCommandAttachAfter } from "./native_command"; export const REACT_NATIVE_WRAPPER: InjectionToken<string> = new InjectionToken("ReactNativeWrapper"); export class ReactNativeElementSchemaRegistry extends ElementSchemaRegistry { getDefaultComponentElementName(): string { return 'def-cpt'; } hasProperty(tagName: string, propName: string): boolean { return true; } hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean { return true; } getMappedPropName(propName: string): string { return propName; } securityContext(tagName: string, propName: string): any { return 0; } validateProperty(name: string): {error: boolean; msg?: string} { return {error: false}; } validateAttribute(name: string): {error: boolean; msg?: string} { return {error: false}; } allKnownElementNames(): string[] { return []; } normalizeAnimationStyleProperty(propName: string): string { return propName; } normalizeAnimationStyleValue( camelCaseProp: string, userProvidedProp: string, val: string|number): {error: string, value: string} { return {error: null, value: '' + val} } } export class ReactNativeSanitizer implements Sanitizer { sanitize(ctx: SecurityContext, value: any): string { return value; } } @Injectable() export class ReactNativeRootRenderer implements RendererFactory2 { public zone: NgZone; public wrapper: ReactNativeWrapper; private _registeredComponents: Map<string, ReactNativeRenderer> = new Map<string, ReactNativeRenderer>(); private _createCommands: Map<Node, NativeCommandCreate> = new Map<Node, NativeCommandCreate>(); private _updateCommands: Map<Node, NativeCommandUpdate> = new Map<Node, NativeCommandUpdate>(); private _attachCommands: Map<Node, NativeCommandAttach> = new Map<Node, NativeCommandAttach>(); private _attachAfterCommands: Map<Node, NativeCommandAttachAfter> = new Map<Node, NativeCommandAttachAfter>(); private _detachCommands: Map<Node, NativeCommandDetach> = new Map<Node, NativeCommandDetach>(); constructor(@Inject(REACT_NATIVE_WRAPPER) _wrapper: ReactNativeWrapper) { this.wrapper = _wrapper; this.wrapper.patchReactNativeEventEmitter(nodeMap); } createRenderer(hostElement: any, type: RendererType2 | any): Renderer2 { return new ReactNativeRenderer(this); } addCreateCommand(node: Node, props: {[s: string]: any } = null) { var cmd = new NativeCommandCreate(node); if (props) { cmd.props = props; } this._createCommands.set(node, cmd); } addUpdateCommand(node: Node, key: string, value: any) { var propEater: NativeCommandCreate | NativeCommandUpdate = <NativeCommandCreate | NativeCommandUpdate>this._createCommands.get(node) || this._updateCommands.get(node); if (propEater) { propEater.props[key] = value; } else { this._updateCommands.set(node, new NativeCommandUpdate(node, key, value)); } } addAttachCommand(node: Node, toRoot: boolean) { this._attachCommands.set(node, new NativeCommandAttach(node, toRoot)); } addAttachAfterCommand(node: Node, anchor: Node) { this._attachAfterCommands.set(node, new NativeCommandAttachAfter(node, anchor)); } addDetachCommand(node: Node) { this._detachCommands.set(node, new NativeCommandDetach(node)); } executeCommands(): void { this._detachCommands.forEach((command: NativeCommandDetach) => command.execute(this.wrapper)); this._createCommands.forEach((command: NativeCommandCreate) => command.execute(this.wrapper)); this._updateCommands.forEach((command: NativeCommandUpdate) => command.execute(this.wrapper)); this._attachCommands.forEach((command: NativeCommandAttach) => command.execute(this.wrapper)); var counters: Map<Node,number> = new Map<Node, number>(); this._attachAfterCommands.forEach((command: NativeCommandAttachAfter) => command.executeWithCounters(this.wrapper, counters)); counters.clear(); NativeCommand.mergeAndApply(this.wrapper); this._detachCommands.clear(); this._createCommands.clear(); this._updateCommands.clear(); this._attachCommands.clear(); this._attachAfterCommands.clear(); } } export class ReactNativeRenderer implements Renderer2 { data: {[key: string]: any;} = {}; constructor(private _rootRenderer: ReactNativeRootRenderer) {} selectRootElement(selector: string): Node { const root = this.createElement(selector.startsWith('#root') ? 'test-cmp' : selector); this._createElementCommand(root); this._rootRenderer.addAttachCommand(root, true); return root; } createElement(name: string, namespace?: string | any): Node { //console.log('createElement:' + name); return new ElementNode(name, this._rootRenderer.wrapper, this._rootRenderer); } createComment(value: string): any { return new CommentNode(this._rootRenderer.wrapper, this._rootRenderer); } createText(value: string): Node { //console.log('createText:' + value); return new TextNode(value, this._rootRenderer.wrapper, this._rootRenderer); } destroyNode(node: Node): any { node.toBeDestroyed = true; } destroy(): void { //console.log('NOT IMPLEMENTED: destroy', arguments); } appendChild(parent: Node, newChild: Node): void { //console.log('appendChild'); newChild.attachTo(parent); if (newChild.getAncestorWithNativeCreated()) { if (this._createNativeRecursively(newChild)) { this._rootRenderer.addAttachCommand(newChild, false); } } } insertBefore(parent: any, newChild: any, refChild: any): void { //console.log('insertBefore'); const index = parent.children.indexOf(refChild); newChild.attachToAt(parent, index); if (newChild.getAncestorWithNativeCreated()) { if (this._createNativeRecursively(newChild)) { this._rootRenderer.addAttachCommand(newChild, false); } } } removeChild(parent: any, oldChild: any): void { const index = parent.children.indexOf(oldChild); parent.children.splice(index, 1); this._rootRenderer.addDetachCommand(oldChild); } parentNode(node: Node): Node { return node.parent; } nextSibling(node: Node): any { let res = null; const parent = node.parent; if (parent) { const index = parent.children.indexOf(node) + 1; if (parent.children.length > index) { res = parent.children[index]; } } return res; } setAttribute(el: Node, name: string, value: string, namespace?: string | any): void { var val: any = value; if (name == "ng-version") return; if (value == "false") val = false; if (value == "true") val = true; if (value == "null") val = null; if (!isNaN(parseInt(val))) val = parseInt(val); if (value.startsWith('#')) val = this._rootRenderer.wrapper.processColor(value); this.setProperty(el, name, val); } removeAttribute(el: any, name: string, namespace?: string | any): void { } addClass(el: any, name: string): void { console.error('NOT IMPLEMENTED: addClass', arguments); } removeClass(el: any, name: string): void { console.error('NOT IMPLEMENTED: removeClass', arguments); } setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void { console.error('NOT IMPLEMENTED: setStyle', arguments); } removeStyle(el: any, style: string, flags?: RendererStyleFlags2): void { console.error('NOT IMPLEMENTED: removeStyle', arguments); } setProperty(el: Node, name: string, value: any): void { if (typeof value !== 'undefined') { const cleanPropertyName = name.startsWith('_on') ? name.substr(1) : name; el.setProperty(cleanPropertyName, value, false); if (el.isCreated) { this._rootRenderer.addUpdateCommand(el, cleanPropertyName, value); } } } setValue(node: Node, value: string): void { if (node instanceof TextNode) { const trimedText = node.setText(value); this.setProperty(node, 'text', trimedText); } } listen(target: 'window' | 'document' | 'body' | Node, eventName: string, callback: (event: any) => boolean | void): () => void { if (target === 'window' || target == 'document' || target == 'body') { console.error('NOT IMPLEMENTED: listen on ' + target, arguments); return () => {}; } else { target.addEventListener(eventName, callback); return () => {target.removeEventListener(eventName, callback);}; } } private _createElementCommand(node: Node): void { this._rootRenderer.addCreateCommand(node); node.isCreated = true; } private _createTextCommand(node: TextNode): void { this._rootRenderer.addCreateCommand(node, {text: node.properties['text']}); var cmd = new NativeCommandCreate(node); node.isCreated = true; } private _createNativeRecursively(node: Node, isRoot: boolean = true): boolean { var didCreate: boolean = false; if (!node.isCreated) { if (!node.isVirtual) { node instanceof TextNode ? this._createTextCommand(node) : this._createElementCommand(node); didCreate = !(node instanceof TextNode) || isRoot; } for (var i = 0; i < node.children.length; i++) { var child = node.children[i]; didCreate = this._createNativeRecursively(child, false) || didCreate; if (!child.isVirtual && !(isRoot && node.isVirtual)) { this._rootRenderer.addAttachCommand(child, false); } } } return didCreate; } }
the_stack
import { Body, Controller, Get, Param, ParseUUIDPipe, Post, Put, Query, UseInterceptors, } from '@nestjs/common' import { ApiBody, ApiOAuth2, ApiOkResponse, ApiParam, ApiTags, ApiExtraModels, ApiOperation, IntersectionType, } from '@nestjs/swagger' import { Audit } from '@island.is/nest/audit' import { EndorsementList } from './endorsementList.model' import { EndorsementListService } from './endorsementList.service' import { EndorsementListDto } from './dto/endorsementList.dto' import { FindEndorsementListByTagsDto } from './dto/findEndorsementListsByTags.dto' import { ChangeEndorsmentListClosedDateDto } from './dto/changeEndorsmentListClosedDate.dto' import { UpdateEndorsementListDto } from './dto/updateEndorsementList.dto' import { BypassAuth, CurrentUser, Scopes } from '@island.is/auth-nest-tools' import { EndorsementListByIdPipe } from './pipes/endorsementListById.pipe' import { environment } from '../../../environments' import { EndorsementsScope } from '@island.is/auth/scopes' import type { User } from '@island.is/auth-nest-tools' import { HasAccessGroup } from '../../guards/accessGuard/access.decorator' import { AccessGroup } from '../../guards/accessGuard/access.enum' import { PaginationDto } from '@island.is/nest/pagination' import { PaginatedEndorsementListDto } from './dto/paginatedEndorsementList.dto' import { PaginatedEndorsementDto } from '../endorsement/dto/paginatedEndorsement.dto' import { SearchQueryDto } from './dto/searchQuery.dto' import { EndorsementListInterceptor } from './interceptors/endorsementList.interceptor' import { EndorsementListsInterceptor } from './interceptors/endorsementLists.interceptor' export class FindTagPaginationComboDto extends IntersectionType( FindEndorsementListByTagsDto, PaginationDto, ) {} export class SearchPaginationComboDto extends IntersectionType( SearchQueryDto, PaginationDto, ) {} @Audit({ namespace: `${environment.audit.defaultNamespace}/endorsement-list`, }) @ApiTags('endorsementList') @Controller('endorsement-list') @ApiOAuth2([]) @ApiExtraModels(FindTagPaginationComboDto, PaginatedEndorsementListDto) export class EndorsementListController { constructor( private readonly endorsementListService: EndorsementListService, ) {} @ApiOperation({ summary: 'Finds all endorsement lists belonging to given tags, if user is not admin then no locked lists will appear', }) @ApiOkResponse({ type: PaginatedEndorsementListDto }) @Get() @UseInterceptors(EndorsementListsInterceptor) @Scopes(EndorsementsScope.main) async findByTags( @CurrentUser() user: User, @Query() query: FindTagPaginationComboDto, ): Promise<PaginatedEndorsementListDto> { return await this.endorsementListService.findListsByTags( // query parameters of length one are not arrays, we normalize all tags input to arrays here !Array.isArray(query.tags) ? [query.tags] : query.tags, query, user.nationalId, ) } // get gp lists - relay @ApiOperation({ summary: 'Gets General Petition Lists' }) @ApiOkResponse({ type: PaginatedEndorsementListDto }) @Get('general-petition-lists') @UseInterceptors(EndorsementListsInterceptor) @BypassAuth() async getGeneralPetitionLists( @Query() query: PaginationDto, ): Promise<PaginatedEndorsementListDto> { return await this.endorsementListService.findOpenListsTaggedGeneralPetition( query, ) } // get gp list - relay @ApiOperation({ summary: 'Gets a General Petition List by Id' }) @ApiOkResponse({ type: EndorsementList }) @ApiParam({ name: 'listId', type: 'string' }) @Get('general-petition-list/:listId') @UseInterceptors(EndorsementListInterceptor) @BypassAuth() async getGeneralPetitionList( @Param('listId') listId: string, ): Promise<EndorsementList | null> { return await this.endorsementListService.findSingleOpenListTaggedGeneralPetition( listId, ) } @Scopes(EndorsementsScope.main) @ApiOperation({ summary: 'Finds all endorsements for the currently authenticated user', }) @ApiOkResponse({ type: PaginatedEndorsementDto }) @Get('/endorsements') @Audit<PaginatedEndorsementDto>({ resources: ({ data: endorsement }) => endorsement.map((e) => e.id), meta: ({ data: endorsement }) => ({ count: endorsement.length }), }) async findEndorsements( @CurrentUser() user: User, @Query() query: PaginationDto, ): Promise<PaginatedEndorsementDto> { return await this.endorsementListService.findAllEndorsementsByNationalId( user.nationalId, query, ) } @ApiOperation({ summary: 'Finds all endorsement lists owned by the currently authenticated user', }) @ApiOkResponse({ type: PaginatedEndorsementListDto }) @Get('/endorsementLists') @UseInterceptors(EndorsementListsInterceptor) @Audit<PaginatedEndorsementListDto>({ resources: ({ data: endorsement }) => endorsement.map((e) => e.id), meta: ({ data: endorsement }) => ({ count: endorsement.length }), }) async findEndorsementLists( @CurrentUser() user: User, @Query() query: PaginationDto, ): Promise<PaginatedEndorsementListDto> { return await this.endorsementListService.findAllEndorsementListsByNationalId( user.nationalId, query, ) } @ApiOkResponse({ description: 'Finds a single endorsements list by id', type: EndorsementList, }) @ApiOperation({ summary: 'Finds a single endorsements list by id' }) @ApiParam({ name: 'listId', type: 'string' }) @Scopes(EndorsementsScope.main) @Get(':listId') @UseInterceptors(EndorsementListInterceptor) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, }) async findOne( @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<EndorsementList> { return endorsementList } @ApiOperation({ summary: 'Close a single endorsements list by id' }) @ApiOkResponse({ description: 'Close a single endorsements list by id', type: EndorsementList, }) @ApiParam({ name: 'listId', type: 'string' }) @Scopes(EndorsementsScope.main) @Put(':listId/close') @UseInterceptors(EndorsementListInterceptor) @HasAccessGroup(AccessGroup.Owner) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, }) async close( @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<EndorsementList> { return await this.endorsementListService.close(endorsementList) } @ApiOperation({ summary: 'Open a single endorsements list by id' }) @ApiOkResponse({ description: 'Open a single endorsements list by id', type: EndorsementList, }) @ApiParam({ name: 'listId', type: 'string' }) @ApiBody({ type: ChangeEndorsmentListClosedDateDto }) @Scopes(EndorsementsScope.main) @Put(':listId/open') @UseInterceptors(EndorsementListInterceptor) @HasAccessGroup(AccessGroup.Owner) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, }) async open( @Body() newDate: ChangeEndorsmentListClosedDateDto, @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<EndorsementList> { return await this.endorsementListService.open(endorsementList, newDate) } @ApiOkResponse({ description: 'Lock a single endorsements list by id', type: EndorsementList, }) @ApiParam({ name: 'listId', type: 'string' }) @Scopes(EndorsementsScope.main) @Put(':listId/lock') @UseInterceptors(EndorsementListInterceptor) @HasAccessGroup(AccessGroup.Admin) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, }) async lock( @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<EndorsementList> { return await this.endorsementListService.lock(endorsementList) } @ApiOkResponse({ description: 'Unlock a single endorsements list by id', type: EndorsementList, }) @ApiParam({ name: 'listId', type: 'string' }) @Scopes(EndorsementsScope.main) @Put(':listId/unlock') @UseInterceptors(EndorsementListInterceptor) @HasAccessGroup(AccessGroup.Admin) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, }) async unlock( @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<EndorsementList> { return await this.endorsementListService.unlock(endorsementList) } @ApiOkResponse({ description: 'Admin update a single endorsements list by id and request body', type: EndorsementList, }) @ApiParam({ name: 'listId', type: 'string' }) @ApiBody({ type: UpdateEndorsementListDto }) @Scopes(EndorsementsScope.main) @Put(':listId/update') @HasAccessGroup(AccessGroup.Admin) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, }) async update( @Body() newData: UpdateEndorsementListDto, @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<EndorsementList> { return await this.endorsementListService.updateEndorsementList( endorsementList, newData, ) } @ApiOperation({ summary: 'Create an endorsements list' }) @ApiOkResponse({ description: 'Create an endorsements list', type: EndorsementList, }) @ApiBody({ type: EndorsementListDto }) @Scopes(EndorsementsScope.main) @Post() @UseInterceptors(EndorsementListInterceptor) @Audit<EndorsementList>({ resources: (endorsementList) => endorsementList.id, meta: (endorsementList) => ({ tags: endorsementList.tags, }), }) async create( @Body() endorsementList: EndorsementListDto, @CurrentUser() user: User, ): Promise<EndorsementList> { return await this.endorsementListService.create({ ...endorsementList, owner: user.nationalId, }) } @ApiOperation({ summary: 'Fetches owner info from national registry' }) @ApiOkResponse({ description: 'Create an endorsements list', type: String, }) @ApiParam({ name: 'listId', type: 'string' }) @BypassAuth() @Get(':listId/ownerInfo') async getOwnerInfo( @Param( 'listId', new ParseUUIDPipe({ version: '4' }), EndorsementListByIdPipe, ) endorsementList: EndorsementList, ): Promise<String> { return await this.endorsementListService.getOwnerInfo(endorsementList) } }
the_stack
import Backburner from 'backburner'; import lolex from 'lolex'; const originalDateNow = Date.now; const originalDateValueOf = Date.prototype.valueOf; let fakeClock; QUnit.module('tests/set-timeout-test', { afterEach() { Date.now = originalDateNow; Date.prototype.valueOf = originalDateValueOf; if (fakeClock) { fakeClock.uninstall(); } } }); QUnit.test('later', function(assert) { assert.expect(6); let bb = new Backburner(['one']); let step = 0; let instance; let done = assert.async(); // Force +new Date to return the same result while scheduling // run.later timers. Otherwise: non-determinism! let now = +new Date(); Date.prototype.valueOf = function() { return now; }; bb.later(null, () => { instance = bb.currentInstance; assert.equal(step++, 0); }, 10); bb.later(null, () => { assert.equal(step++, 1); assert.equal(instance, bb.currentInstance, 'same instance'); }, 10); Date.prototype.valueOf = originalDateValueOf; // spin so that when we execute timers (+new Date()) will be greater than the // time scheduled above; not a problem in real life as we will never 'wait' // 0ms while ((+ new Date()) <= now + 10) {} bb.later(null, () => { assert.equal(step++, 2); bb.later(null, () => { assert.equal(step++, 3); assert.ok(true, 'Another later will execute correctly'); done(); }, 1); }, 20); }); QUnit.test('later should rely on stubbed `Date.now`', function(assert) { assert.expect(1); let bb = new Backburner(['one']); let done = assert.async(); let globalNowWasUsed = false; Date.now = function() { globalNowWasUsed = true; return originalDateNow(); }; bb.later(() => { assert.ok(globalNowWasUsed); done(); }, 1); }); QUnit.test('later shedules timers correctly after time travel', function(assert) { assert.expect(2); let bb = new Backburner(['one']); let done = assert.async(); let start = originalDateNow(); let now = start; Date.now = () => now; let called1At = 0; let called2At = 0; bb.later(() => called1At = originalDateNow(), 1000); now += 1000; bb.later(() => called2At = originalDateNow(), 10); now += 10; setTimeout(() => { assert.ok(called1At !== 0, 'timeout 1 was called'); assert.ok(called2At !== 0, 'timeout 2 was called'); done(); }, 20); }); let bb; QUnit.module('later arguments / arity', { beforeEach() { bb = new Backburner(['one']); }, afterEach() { bb = undefined; if (fakeClock) { fakeClock.uninstall(); } } }); QUnit.test('[callback]', function(assert) { assert.expect(2); let done = assert.async(); bb.later(function() { assert.equal(arguments.length, 0); assert.ok(true, 'was called'); done(); }); }); QUnit.test('[callback, undefined]', function(assert) { assert.expect(2); let done = assert.async(); bb.later(function() { assert.equal(arguments.length, 1); assert.ok(true, 'was called'); done(); }, undefined); }); QUnit.test('[null, callback, undefined]', function(assert) { assert.expect(2); let done = assert.async(); bb.later(null, function() { assert.equal(arguments.length, 0); assert.ok(true, 'was called'); done(); }); }); QUnit.test('[null, callback, undefined]', function(assert) { assert.expect(2); let done = assert.async(); bb.later(null, function() { assert.equal(arguments.length, 1); assert.ok(true, 'was called'); done(); }, undefined); }); QUnit.test('[null, callback, null]', function(assert) { assert.expect(3); let done = assert.async(); bb.later(null, function() { assert.equal(arguments.length, 1); assert.equal(arguments[0], null); assert.ok(true, 'was called'); done(); }, null); }); QUnit.test('[callback, string, string, string]', function(assert) { assert.expect(5); let done = assert.async(); bb.later(function() { assert.equal(arguments.length, 3); assert.equal(arguments[0], 'a'); assert.equal(arguments[1], 'b'); assert.equal(arguments[2], 'c'); assert.ok(true, 'was called'); done(); }, 'a', 'b', 'c'); }); QUnit.test('[null, callback, string, string, string]', function(assert) { assert.expect(5); let done = assert.async(); bb.later(null, function() { assert.equal(arguments.length, 3); assert.equal(arguments[0], 'a'); assert.equal(arguments[1], 'b'); assert.equal(arguments[2], 'c'); assert.ok(true, 'was called'); done(); }, 'a', 'b', 'c'); }); QUnit.test('[null, callback, string, string, string, number]', function(assert) { assert.expect(5); let done = assert.async(); bb.later(null, function() { assert.equal(arguments.length, 3); assert.equal(arguments[0], 'a'); assert.equal(arguments[1], 'b'); assert.equal(arguments[2], 'c'); assert.ok(true, 'was called'); done(); }, 'a', 'b', 'c', 10); }); QUnit.test('[null, callback, string, string, string, numericString]', function(assert) { assert.expect(5); let done = assert.async(); bb.later(null, function() { assert.equal(arguments.length, 3); assert.equal(arguments[0], 'a'); assert.equal(arguments[1], 'b'); assert.equal(arguments[2], 'c'); assert.ok(true, 'was called'); done(); }, 'a', 'b', 'c', '1'); }); QUnit.test('[obj, string]', function(assert) { assert.expect(1); let done = assert.async(); bb.later({ bro() { assert.ok(true, 'was called'); done(); } }, 'bro'); }); QUnit.test('[obj, string, value]', function(assert) { assert.expect(3); let done = assert.async(); bb.later({ bro() { assert.equal(arguments.length, 1); assert.equal(arguments[0], 'value'); assert.ok(true, 'was called'); done(); } }, 'bro', 'value'); }); QUnit.test('[obj, string, value, number]', function(assert) { let done = assert.async(); bb.later({ bro() { assert.equal(arguments.length, 1); assert.equal(arguments[0], 'value'); assert.ok(true, 'was called'); done(); } }, 'bro', 'value', 1); }); QUnit.test('[obj, string, value, numericString]', function(assert) { let done = assert.async(); bb.later({ bro() { assert.equal(arguments.length, 1); assert.equal(arguments[0], 'value'); assert.ok(true, 'was called'); done(); } }, 'bro', 'value', '1'); }); QUnit.test('onError', function(assert) { assert.expect(1); let done = assert.async(); function onError(error) { assert.equal('test error', error.message); done(); } bb = new Backburner(['errors'], { onError }); bb.later(() => { throw new Error('test error'); }, 1); }); QUnit.test('later doesn\'t trigger twice with earlier later', function(assert) { assert.expect(4); bb = new Backburner(['one']); let called1 = 0; let called2 = 0; let beginCalls = 0; let endCalls = 0; let oldBegin = bb.begin; let oldEnd = bb.end; let done = assert.async(); bb.begin = function() { beginCalls++; oldBegin.call(bb); }; bb.end = function() { endCalls++; oldEnd.call(bb); }; bb.later(() => called1++, 50); bb.later(() => called2++, 10); setTimeout(() => { assert.equal(called1, 1, 'timeout 1 was called once'); assert.equal(called2, 1, 'timeout 2 was called once'); assert.equal(beginCalls, 2, 'begin() was called twice'); assert.equal(endCalls, 2, 'end() was called twice'); done(); }, 100); }); QUnit.test('later with two Backburner instances', function(assert) { assert.expect(8); let steps = 0; let done = assert.async(); let bb1 = new Backburner(['one'], { onBegin() { assert.equal(++steps, 4); } }); let bb2 = new Backburner(['one'], { onBegin() { assert.equal(++steps, 6); } }); assert.equal(++steps, 1); bb1.later(() => assert.equal(++steps, 5), 10); assert.equal(++steps, 2); bb2.later(() => assert.equal(++steps, 7), 10); assert.equal(++steps, 3); setTimeout(() => { assert.equal(++steps, 8); done(); }, 50); }); QUnit.test('expired timeout doesn\'t hang when setting a new timeout', function(assert) { assert.expect(3); let called1At = 0; let called2At = 0; let done = assert.async(); bb.later(() => called1At = Date.now(), 1); // Block JS to simulate https://github.com/ebryn/backburner.js/issues/135 let waitUntil = Date.now() + 5; while (Date.now() < waitUntil) { } bb.later(() => called2At = Date.now(), 50); setTimeout(() => { assert.ok(called1At !== 0, 'timeout 1 was called'); assert.ok(called2At !== 0, 'timeout 2 was called'); assert.ok(called2At - called1At > 10, 'timeout 1 did not wait for timeout 2'); done(); }, 60); }); QUnit.test('NaN timeout doesn\'t hang other timeouts', function(assert) { assert.expect(2); let done = assert.async(); let called1At = 0; let called2At = 0; bb.later(() => called1At = Date.now(), 1); bb.later(() => {}, NaN); bb.later(() => called2At = Date.now(), 10); setTimeout(() => { assert.ok(called1At !== 0, 'timeout 1 was called'); assert.ok(called2At !== 0, 'timeout 2 was called'); done(); }, 20); }); QUnit.test('when [callback, string] args passed', function(assert) { assert.expect(1); let done = assert.async(); let bb = new Backburner(['one']); bb.later(function(name) { assert.equal(name, 'batman'); done(); }, 'batman', 0); }); QUnit.test('can be ran "early" with fake timers GH#351', function(assert) { assert.expect(1); let done = assert.async(); let bb = new Backburner(['one']); fakeClock = lolex.install(); let startTime = originalDateNow(); bb.later(function(name) { let endTime = originalDateNow(); assert.ok(endTime - startTime < 100, 'did not wait for 5s to run timer'); done(); }, 5000); fakeClock.tick(5001); }); QUnit.test('debounce called before later', function(assert) { assert.expect(1); let done = assert.async(1); let bb = new Backburner(['one']); let func = function() {}; bb.run(() => { bb.debounce(func, 1000); setTimeout(function() { bb.debounce(func, 1000); }, 50); let before = Date.now(); bb.later(function() { let diff = Date.now() - before; assert.ok(diff < 1010, '.later called with too much delay'); done(); }, 1000); }); }); QUnit.test('boundRunExpiredTimers is called once when first timer canceled', function(assert) { let done = assert.async(1); let bb = new Backburner(['one']); let timer = bb.later(function() {}, 500); bb.cancel(timer); let boundRunExpiredTimers = bb['_boundRunExpiredTimers']; bb['_boundRunExpiredTimers'] = function() { assert.ok(true); done(); return boundRunExpiredTimers.apply(bb, arguments); }; bb.later(function() {}, 800); });
the_stack
import * as THREE from "three"; import { combineLatest as observableCombineLatest, concat as observableConcat, empty as observableEmpty, zip as observableZip, Observable, Subscription, Subject, } from "rxjs"; import { catchError, debounceTime, distinctUntilChanged, filter, first, map, pairwise, publishReplay, refCount, scan, skipWhile, startWith, switchMap, withLatestFrom, } from "rxjs/operators"; import { SliderImages, SliderCombination, GLRendererOperation, PositionLookat, } from "./interfaces/SliderInterfaces"; import { Image } from "../../graph/Image"; import { Container } from "../../viewer/Container"; import { Navigator } from "../../viewer/Navigator"; import { Spatial } from "../../geo/Spatial"; import { ViewportCoords } from "../../geo/ViewportCoords"; import { RenderPass } from "../../render/RenderPass"; import { GLRenderHash } from "../../render/interfaces/IGLRenderHash"; import { ViewportSize } from "../../render/interfaces/ViewportSize"; import { VirtualNodeHash } from "../../render/interfaces/VirtualNodeHash"; import { RenderCamera } from "../../render/RenderCamera"; import { IAnimationState } from "../../state/interfaces/IAnimationState"; import { AnimationFrame } from "../../state/interfaces/AnimationFrame"; import { State } from "../../state/State"; import { TileLoader } from "../../tile/TileLoader"; import { TileStore } from "../../tile/TileStore"; import { TileBoundingBox } from "../../tile/interfaces/TileBoundingBox"; import { TileRegionOfInterest } from "../../tile/interfaces/TileRegionOfInterest"; import { RegionOfInterestCalculator } from "../../tile/RegionOfInterestCalculator"; import { TextureProvider } from "../../tile/TextureProvider"; import { Component } from "../Component"; import { SliderConfiguration, SliderConfigurationMode, } from "../interfaces/SliderConfiguration"; import { SliderGLRenderer } from "./SliderGLRenderer"; import { Transform } from "../../geo/Transform"; import { SliderDOMRenderer } from "./SliderDOMRenderer"; import { isSpherical } from "../../geo/Geo"; import { ComponentName } from "../ComponentName"; /** * @class SliderComponent * * @classdesc Component for comparing pairs of images. Renders * a slider for adjusting the curtain of the first image. * * Deactivate the sequence, direction and image plane * components when activating the slider component to avoid * interfering UI elements. * * To retrive and use the slider component * * @example * ```js * var viewer = new Viewer({ ... }); * * viewer.deactivateComponent("image"); * viewer.deactivateComponent("direction"); * viewer.deactivateComponent("sequence"); * * viewer.activateComponent("slider"); * * var sliderComponent = viewer.getComponent("slider"); * ``` */ export class SliderComponent extends Component<SliderConfiguration> { public static componentName: ComponentName = "slider"; private _viewportCoords: ViewportCoords; private _domRenderer: SliderDOMRenderer; private _imageTileLoader: TileLoader; private _roiCalculator: RegionOfInterestCalculator; private _spatial: Spatial; private _glRendererOperation$: Subject<GLRendererOperation>; private _glRenderer$: Observable<SliderGLRenderer>; private _glRendererCreator$: Subject<void>; private _glRendererDisposer$: Subject<void>; private _waitSubscription: Subscription; /** @ignore */ constructor( name: string, container: Container, navigator: Navigator, viewportCoords?: ViewportCoords) { super(name, container, navigator); this._viewportCoords = !!viewportCoords ? viewportCoords : new ViewportCoords(); this._domRenderer = new SliderDOMRenderer(container); this._imageTileLoader = new TileLoader(navigator.api); this._roiCalculator = new RegionOfInterestCalculator(); this._spatial = new Spatial(); this._glRendererOperation$ = new Subject<GLRendererOperation>(); this._glRendererCreator$ = new Subject<void>(); this._glRendererDisposer$ = new Subject<void>(); this._glRenderer$ = this._glRendererOperation$.pipe( scan( (glRenderer: SliderGLRenderer, operation: GLRendererOperation): SliderGLRenderer => { return operation(glRenderer); }, null), filter( (glRenderer: SliderGLRenderer): boolean => { return glRenderer != null; }), distinctUntilChanged( undefined, (glRenderer: SliderGLRenderer): number => { return glRenderer.frameId; })); this._glRendererCreator$.pipe( map( (): GLRendererOperation => { return (glRenderer: SliderGLRenderer): SliderGLRenderer => { if (glRenderer != null) { throw new Error("Multiple slider states can not be created at the same time"); } return new SliderGLRenderer(); }; })) .subscribe(this._glRendererOperation$); this._glRendererDisposer$.pipe( map( (): GLRendererOperation => { return (glRenderer: SliderGLRenderer): SliderGLRenderer => { glRenderer.dispose(); return null; }; })) .subscribe(this._glRendererOperation$); } protected _activate(): void { const subs = this._subscriptions; subs.push(this._domRenderer.mode$ .subscribe( (mode: SliderConfigurationMode): void => { this.configure({ mode }); })); subs.push(this._glRenderer$.pipe( map( (glRenderer: SliderGLRenderer): GLRenderHash => { let renderHash: GLRenderHash = { name: this._name, renderer: { frameId: glRenderer.frameId, needsRender: glRenderer.needsRender, render: glRenderer.render.bind(glRenderer), pass: RenderPass.Background, }, }; return renderHash; })) .subscribe(this._container.glRenderer.render$)); const position$ = observableConcat( this.configuration$.pipe( map( (configuration: SliderConfiguration): number => { return configuration.initialPosition != null ? configuration.initialPosition : 1; }), first()), this._domRenderer.position$); const mode$ = this.configuration$.pipe( map( (configuration: SliderConfiguration): SliderConfigurationMode => { return configuration.mode; }), distinctUntilChanged()); const motionless$ = this._navigator.stateService.currentState$.pipe( map( (frame: AnimationFrame): boolean => { return frame.state.motionless; }), distinctUntilChanged()); const spherical$ = this._navigator.stateService.currentState$.pipe( map( (frame: AnimationFrame): boolean => { return isSpherical(frame.state.currentImage.cameraType); }), distinctUntilChanged()); const sliderVisible$ = observableCombineLatest( this._configuration$.pipe( map( (configuration: SliderConfiguration): boolean => { return configuration.sliderVisible; })), this._navigator.stateService.currentState$.pipe( map( (frame: AnimationFrame): boolean => { return !(frame.state.currentImage == null || frame.state.previousImage == null || (isSpherical( frame.state.currentImage.cameraType) && !isSpherical( frame.state.previousImage.cameraType))); }), distinctUntilChanged())).pipe( map( ([sliderVisible, enabledState]: [boolean, boolean]): boolean => { return sliderVisible && enabledState; }), distinctUntilChanged()); this._waitSubscription = observableCombineLatest( mode$, motionless$, spherical$, sliderVisible$).pipe( withLatestFrom(this._navigator.stateService.state$)) .subscribe( ([[mode, motionless, spherical, sliderVisible], state]: [[SliderConfigurationMode, boolean, boolean, boolean], State]): void => { const interactive: boolean = sliderVisible && (motionless || mode === SliderConfigurationMode.Stationary || spherical); if (interactive && state !== State.WaitingInteractively) { this._navigator.stateService.waitInteractively(); } else if (!interactive && state !== State.Waiting) { this._navigator.stateService.wait(); } }); subs.push(observableCombineLatest( position$, mode$, motionless$, spherical$, sliderVisible$) .subscribe( ([position, mode, motionless, spherical]: [number, SliderConfigurationMode, boolean, boolean, boolean]): void => { if (motionless || mode === SliderConfigurationMode.Stationary || spherical) { this._navigator.stateService.moveTo(1); } else { this._navigator.stateService.moveTo(position); } })); subs.push(observableCombineLatest( position$, mode$, motionless$, spherical$, sliderVisible$, this._container.renderService.size$).pipe( map( ([position, mode, motionless, spherical, sliderVisible]: [number, SliderConfigurationMode, boolean, boolean, boolean, ViewportSize]): VirtualNodeHash => { return { name: this._name, vNode: this._domRenderer.render(position, mode, motionless, spherical, sliderVisible), }; })) .subscribe(this._container.domRenderer.render$)); this._glRendererCreator$.next(null); subs.push(observableCombineLatest( position$, spherical$, sliderVisible$, this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$).pipe( map( ([position, spherical, visible, render, transform]: [number, boolean, boolean, RenderCamera, Transform]): number => { if (!spherical) { return visible ? position : 1; } const basicMin: number[] = this._viewportCoords.viewportToBasic(-1.15, 0, transform, render.perspective); const basicMax: number[] = this._viewportCoords.viewportToBasic(1.15, 0, transform, render.perspective); const shiftedMax: number = basicMax[0] < basicMin[0] ? basicMax[0] + 1 : basicMax[0]; const basicPosition: number = basicMin[0] + position * (shiftedMax - basicMin[0]); return basicPosition > 1 ? basicPosition - 1 : basicPosition; }), map( (position: number): GLRendererOperation => { return (glRenderer: SliderGLRenderer): SliderGLRenderer => { glRenderer.updateCurtain(position); return glRenderer; }; })) .subscribe(this._glRendererOperation$)); subs.push(observableCombineLatest( this._navigator.stateService.currentState$, mode$).pipe( map( ([frame, mode]: [AnimationFrame, SliderConfigurationMode]): GLRendererOperation => { return (glRenderer: SliderGLRenderer): SliderGLRenderer => { glRenderer.update(frame, mode); return glRenderer; }; })) .subscribe(this._glRendererOperation$)); subs.push(this._configuration$.pipe( filter( (configuration: SliderConfiguration): boolean => { return configuration.ids != null; }), switchMap( (configuration: SliderConfiguration): Observable<SliderCombination> => { return observableZip( observableZip( this._catchCacheImage$( configuration.ids.background), this._catchCacheImage$( configuration.ids.foreground)).pipe( map( (images: [Image, Image]) : SliderImages => { return { background: images[0], foreground: images[1] }; })), this._navigator.stateService.currentState$.pipe(first())).pipe( map( (nf: [SliderImages, AnimationFrame]): SliderCombination => { return { images: nf[0], state: nf[1].state }; })); })) .subscribe( (co: SliderCombination): void => { if (co.state.currentImage != null && co.state.previousImage != null && co.state.currentImage.id === co.images.foreground.id && co.state.previousImage.id === co.images.background.id) { return; } if (co.state.currentImage.id === co.images.background.id) { this._navigator.stateService.setImages([co.images.foreground]); return; } if (co.state.currentImage.id === co.images.foreground.id && co.state.trajectory.length === 1) { this._navigator.stateService.prependImages([co.images.background]); return; } this._navigator.stateService.setImages([co.images.background]); this._navigator.stateService.setImages([co.images.foreground]); }, (e: Error): void => { console.error(e); })); const textureProvider$ = this._container.configurationService.imageTiling$.pipe( switchMap( (active): Observable<AnimationFrame> => { return active ? this._navigator.stateService.currentState$ : new Subject(); }), distinctUntilChanged( undefined, (frame: AnimationFrame): string => { return frame.state.currentImage.id; }), withLatestFrom( this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), map( ([frame, renderer, size]: [AnimationFrame, THREE.WebGLRenderer, ViewportSize]): TextureProvider => { const state: IAnimationState = frame.state; const viewportSize: number = Math.max(size.width, size.height); const currentImage: Image = state.currentImage; const currentTransform: Transform = state.currentTransform; const tileSize: number = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512; return new TextureProvider( currentImage.id, currentTransform.basicWidth, currentTransform.basicHeight, currentImage.image, this._imageTileLoader, new TileStore(), renderer); }), publishReplay(1), refCount()); subs.push(textureProvider$.subscribe(() => { /*noop*/ })); subs.push(textureProvider$.pipe( map( (provider: TextureProvider): GLRendererOperation => { return (renderer: SliderGLRenderer): SliderGLRenderer => { renderer.setTextureProvider(provider.id, provider); return renderer; }; })) .subscribe(this._glRendererOperation$)); subs.push(textureProvider$.pipe( pairwise()) .subscribe( (pair: [TextureProvider, TextureProvider]): void => { let previous: TextureProvider = pair[0]; previous.abort(); })); const roiTrigger$ = this._container.configurationService.imageTiling$.pipe( switchMap( (active): Observable<[RenderCamera, ViewportSize]> => { return active ? observableCombineLatest( this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(debounceTime(250))) : new Subject(); }), map( ([camera, size]: [RenderCamera, ViewportSize]): PositionLookat => { return [ camera.camera.position.clone(), camera.camera.lookat.clone(), camera.zoom.valueOf(), size.height.valueOf(), size.width.valueOf()]; }), pairwise(), skipWhile( (pls: [PositionLookat, PositionLookat]): boolean => { return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0; }), map( (pls: [PositionLookat, PositionLookat]): boolean => { let samePosition: boolean = pls[0][0].equals(pls[1][0]); let sameLookat: boolean = pls[0][1].equals(pls[1][1]); let sameZoom: boolean = pls[0][2] === pls[1][2]; let sameHeight: boolean = pls[0][3] === pls[1][3]; let sameWidth: boolean = pls[0][4] === pls[1][4]; return samePosition && sameLookat && sameZoom && sameHeight && sameWidth; }), distinctUntilChanged(), filter( (stalled: boolean): boolean => { return stalled; }), switchMap( (): Observable<RenderCamera> => { return this._container.renderService.renderCameraFrame$.pipe( first()); }), withLatestFrom( this._container.renderService.size$, this._navigator.stateService.currentTransform$)); subs.push(textureProvider$.pipe( switchMap( (provider: TextureProvider): Observable<[TileRegionOfInterest, TextureProvider]> => { return roiTrigger$.pipe( map( ([camera, size, transform]: [RenderCamera, ViewportSize, Transform]): [TileRegionOfInterest, TextureProvider] => { return [ this._roiCalculator.computeRegionOfInterest(camera, size, transform), provider, ]; })); }), filter( (args: [TileRegionOfInterest, TextureProvider]): boolean => { return !args[1].disposed; })) .subscribe( (args: [TileRegionOfInterest, TextureProvider]): void => { let roi: TileRegionOfInterest = args[0]; let provider: TextureProvider = args[1]; provider.setRegionOfInterest(roi); })); const hasTexture$ = textureProvider$.pipe( switchMap( (provider: TextureProvider): Observable<boolean> => { return provider.hasTexture$; }), startWith(false), publishReplay(1), refCount()); subs.push(hasTexture$.subscribe(() => { /*noop*/ })); const textureProviderPrev$ = this._container.configurationService.imageTiling$.pipe( switchMap( (active): Observable<AnimationFrame> => { return active ? this._navigator.stateService.currentState$ : new Subject(); }), filter( (frame: AnimationFrame): boolean => { return !!frame.state.previousImage; }), distinctUntilChanged( undefined, (frame: AnimationFrame): string => { return frame.state.previousImage.id; }), withLatestFrom( this._container.glRenderer.webGLRenderer$, this._container.renderService.size$), map( ([frame, renderer, size]: [AnimationFrame, THREE.WebGLRenderer, ViewportSize]): TextureProvider => { const state = frame.state; const previousImage = state.previousImage; const previousTransform = state.previousTransform; return new TextureProvider( previousImage.id, previousTransform.basicWidth, previousTransform.basicHeight, previousImage.image, this._imageTileLoader, new TileStore(), renderer); }), publishReplay(1), refCount()); subs.push(textureProviderPrev$.subscribe(() => { /*noop*/ })); subs.push(textureProviderPrev$.pipe( map( (provider: TextureProvider): GLRendererOperation => { return (renderer: SliderGLRenderer): SliderGLRenderer => { renderer.setTextureProviderPrev(provider.id, provider); return renderer; }; })) .subscribe(this._glRendererOperation$)); subs.push(textureProviderPrev$.pipe( pairwise()) .subscribe( (pair: [TextureProvider, TextureProvider]): void => { let previous: TextureProvider = pair[0]; previous.abort(); })); const roiTriggerPrev$ = this._container.configurationService.imageTiling$.pipe( switchMap( (active): Observable<[RenderCamera, ViewportSize]> => { return active ? observableCombineLatest( this._container.renderService.renderCameraFrame$, this._container.renderService.size$.pipe(debounceTime(250))) : new Subject(); }), map( ([camera, size]: [RenderCamera, ViewportSize]): PositionLookat => { return [ camera.camera.position.clone(), camera.camera.lookat.clone(), camera.zoom.valueOf(), size.height.valueOf(), size.width.valueOf()]; }), pairwise(), skipWhile( (pls: [PositionLookat, PositionLookat]): boolean => { return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0; }), map( (pls: [PositionLookat, PositionLookat]): boolean => { let samePosition: boolean = pls[0][0].equals(pls[1][0]); let sameLookat: boolean = pls[0][1].equals(pls[1][1]); let sameZoom: boolean = pls[0][2] === pls[1][2]; let sameHeight: boolean = pls[0][3] === pls[1][3]; let sameWidth: boolean = pls[0][4] === pls[1][4]; return samePosition && sameLookat && sameZoom && sameHeight && sameWidth; }), distinctUntilChanged(), filter( (stalled: boolean): boolean => { return stalled; }), switchMap( (): Observable<RenderCamera> => { return this._container.renderService.renderCameraFrame$.pipe( first()); }), withLatestFrom( this._container.renderService.size$, this._navigator.stateService.currentTransform$)); subs.push(textureProviderPrev$.pipe( switchMap( (provider: TextureProvider): Observable<[TileRegionOfInterest, TextureProvider]> => { return roiTriggerPrev$.pipe( map( ([camera, size, transform]: [RenderCamera, ViewportSize, Transform]): [TileRegionOfInterest, TextureProvider] => { return [ this._roiCalculator.computeRegionOfInterest(camera, size, transform), provider, ]; })); }), filter( (args: [TileRegionOfInterest, TextureProvider]): boolean => { return !args[1].disposed; }), withLatestFrom(this._navigator.stateService.currentState$)) .subscribe( ([[roi, provider], frame]: [[TileRegionOfInterest, TextureProvider], AnimationFrame]): void => { let shiftedRoi: TileRegionOfInterest = null; if (isSpherical(frame.state.previousImage.cameraType)) { if (isSpherical(frame.state.currentImage.cameraType)) { const currentViewingDirection: THREE.Vector3 = this._spatial.viewingDirection(frame.state.currentImage.rotation); const previousViewingDirection: THREE.Vector3 = this._spatial.viewingDirection(frame.state.previousImage.rotation); const directionDiff: number = this._spatial.angleBetweenVector2( currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y); const shift: number = directionDiff / (2 * Math.PI); const bbox: TileBoundingBox = { maxX: this._spatial.wrap(roi.bbox.maxX + shift, 0, 1), maxY: roi.bbox.maxY, minX: this._spatial.wrap(roi.bbox.minX + shift, 0, 1), minY: roi.bbox.minY, }; shiftedRoi = { bbox: bbox, pixelHeight: roi.pixelHeight, pixelWidth: roi.pixelWidth, }; } else { const currentViewingDirection: THREE.Vector3 = this._spatial.viewingDirection(frame.state.currentImage.rotation); const previousViewingDirection: THREE.Vector3 = this._spatial.viewingDirection(frame.state.previousImage.rotation); const directionDiff: number = this._spatial.angleBetweenVector2( currentViewingDirection.x, currentViewingDirection.y, previousViewingDirection.x, previousViewingDirection.y); const shiftX: number = directionDiff / (2 * Math.PI); const a1: number = this._spatial.angleToPlane(currentViewingDirection.toArray(), [0, 0, 1]); const a2: number = this._spatial.angleToPlane(previousViewingDirection.toArray(), [0, 0, 1]); const shiftY: number = (a2 - a1) / (2 * Math.PI); const currentTransform: Transform = frame.state.currentTransform; const size: number = Math.max(currentTransform.basicWidth, currentTransform.basicHeight); const hFov: number = size > 0 ? 2 * Math.atan(0.5 * currentTransform.basicWidth / (size * currentTransform.focal)) : Math.PI / 3; const vFov: number = size > 0 ? 2 * Math.atan(0.5 * currentTransform.basicHeight / (size * currentTransform.focal)) : Math.PI / 3; const spanningWidth: number = hFov / (2 * Math.PI); const spanningHeight: number = vFov / Math.PI; const basicWidth: number = (roi.bbox.maxX - roi.bbox.minX) * spanningWidth; const basicHeight: number = (roi.bbox.maxY - roi.bbox.minY) * spanningHeight; const pixelWidth: number = roi.pixelWidth * spanningWidth; const pixelHeight: number = roi.pixelHeight * spanningHeight; const zoomShiftX: number = (roi.bbox.minX + roi.bbox.maxX) / 2 - 0.5; const zoomShiftY: number = (roi.bbox.minY + roi.bbox.maxY) / 2 - 0.5; const minX: number = 0.5 + shiftX + spanningWidth * zoomShiftX - basicWidth / 2; const maxX: number = 0.5 + shiftX + spanningWidth * zoomShiftX + basicWidth / 2; const minY: number = 0.5 + shiftY + spanningHeight * zoomShiftY - basicHeight / 2; const maxY: number = 0.5 + shiftY + spanningHeight * zoomShiftY + basicHeight / 2; const bbox: TileBoundingBox = { maxX: this._spatial.wrap(maxX, 0, 1), maxY: maxY, minX: this._spatial.wrap(minX, 0, 1), minY: minY, }; shiftedRoi = { bbox: bbox, pixelHeight: pixelHeight, pixelWidth: pixelWidth, }; } } else { const currentBasicAspect: number = frame.state.currentTransform.basicAspect; const previousBasicAspect: number = frame.state.previousTransform.basicAspect; const [[cornerMinX, cornerMinY], [cornerMaxX, cornerMaxY]]: number[][] = this._getBasicCorners(currentBasicAspect, previousBasicAspect); const basicWidth: number = cornerMaxX - cornerMinX; const basicHeight: number = cornerMaxY - cornerMinY; const pixelWidth: number = roi.pixelWidth / basicWidth; const pixelHeight: number = roi.pixelHeight / basicHeight; const minX: number = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.minX / basicWidth; const maxX: number = (basicWidth - 1) / (2 * basicWidth) + roi.bbox.maxX / basicWidth; const minY: number = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.minY / basicHeight; const maxY: number = (basicHeight - 1) / (2 * basicHeight) + roi.bbox.maxY / basicHeight; const bbox: TileBoundingBox = { maxX: maxX, maxY: maxY, minX: minX, minY: minY, }; this._clipBoundingBox(bbox); shiftedRoi = { bbox: bbox, pixelHeight: pixelHeight, pixelWidth: pixelWidth, }; } provider.setRegionOfInterest(shiftedRoi); })); const hasTexturePrev$ = textureProviderPrev$.pipe( switchMap( (provider: TextureProvider): Observable<boolean> => { return provider.hasTexture$; }), startWith(false), publishReplay(1), refCount()); subs.push(hasTexturePrev$.subscribe(() => { /*noop*/ })); } protected _deactivate(): void { this._waitSubscription.unsubscribe(); this._navigator.stateService.state$.pipe( first()) .subscribe( (state: State): void => { if (state !== State.Traversing) { this._navigator.stateService.traverse(); } }); this._glRendererDisposer$.next(null); this._domRenderer.deactivate(); this._subscriptions.unsubscribe(); this.configure({ ids: null }); } protected _getDefaultConfiguration(): SliderConfiguration { return { initialPosition: 1, mode: SliderConfigurationMode.Motion, sliderVisible: true, }; } private _catchCacheImage$(imageId: string): Observable<Image> { return this._navigator.graphService.cacheImage$(imageId).pipe( catchError( (error: Error): Observable<Image> => { console.error(`Failed to cache slider image (${imageId})`, error); return observableEmpty(); })); } private _getBasicCorners(currentAspect: number, previousAspect: number): number[][] { let offsetX: number; let offsetY: number; if (currentAspect > previousAspect) { offsetX = 0.5; offsetY = 0.5 * currentAspect / previousAspect; } else { offsetX = 0.5 * previousAspect / currentAspect; offsetY = 0.5; } return [[0.5 - offsetX, 0.5 - offsetY], [0.5 + offsetX, 0.5 + offsetY]]; } private _clipBoundingBox(bbox: TileBoundingBox): void { bbox.minX = Math.max(0, Math.min(1, bbox.minX)); bbox.maxX = Math.max(0, Math.min(1, bbox.maxX)); bbox.minY = Math.max(0, Math.min(1, bbox.minY)); bbox.maxY = Math.max(0, Math.min(1, bbox.maxY)); } }
the_stack
import { en } from '../../src/locale'; import parse from '../../src/formatter/parse/parse'; import { NumerableLocale } from '../../src/locale/types/numerable-locale'; import { NumerableFormatter } from '../../src/core/types/numerable-formatter'; describe('parse', () => { it('should parse NaN, null, undefined as null', () => { expect(parse(NaN)).toBe(null); expect(parse(null as any)).toBe(null); expect(parse(undefined as any)).toBe(null); }); it('should transform to number (or null) if not input is not handled', () => { expect(parse([] as any)).toBe(0); expect(parse({} as any)).toBe(null); expect(parse(/s/ as any)).toBe(null); expect(parse(true as any)).toBe(1); expect(parse(false as any)).toBe(0); expect(parse((() => '') as any)).toBe(null); }); it('should properly parse a number', () => { const tests: any[] = [ [0, 0], [1.2323, 1.2323], [-1200500, -1200500], [5600800900700400, 5600800900700400], [0.0000000001, 0.0000000001], [-0.0000000001, -0.0000000001], [0, 0], [1, 1], [1.1, 1.1], [-0, 0], [-1, -1], [-1.1, -1.1], [Infinity, Infinity], ]; tests.forEach(([value, expectedResult]) => { expect([value, parse(value)]).toEqual([value, expectedResult]); }); }); it('should properly parse a string', () => { const tests: any[] = [ ['-0', -0], ['0', 0], ['0.123', 0.123], ['-500,000.23', -500000.23], ['1,234,567.8901', 1234567.8901], ['-0.0000000123', -0.0000000123], ['0.9990000000000000', 0.999], ['00000000009765,234,111.8900000', 9765234111.89], ['-00050.5000000', -50.5], ['(1.5)', -1.5], ['(00001.50000)', -1.5], ['+0.999', 0.999], ['0.999-', -0.999], ['0.999+', 0.999], ['10,000.123', 10000.123], ['(0.12345)', -0.12345], ['((--0.12345))', 0.12345], ['1.23T', 1230000000000], ['', null], ]; tests.forEach(([value, expectedResult]) => { expect([value, parse(value)]).toEqual([value, expectedResult]); }); }); it('should apply the locale during parsing', () => { const withDelimiters = ([thousands, decimal]: [thousands: string, decimal: string]): NumerableLocale => ({ ...en, delimiters: { thousands, decimal }, }); const withGroupingStyle = (groupingStyle: number[]): NumerableLocale => ({ ...en, digitGroupingStyle: groupingStyle }); const withAbbreviations = (abbreviations: string): NumerableLocale => ({ ...en, abbreviations }); const withNumeralSystem = (numeralSystem: string[]): NumerableLocale => ({ ...en, numeralSystem }); const withObject = (object: Partial<NumerableLocale>): NumerableLocale => ({ ...en, ...object }); const arabNumeralSystem = [ '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩', ].map(e => e + '\u200e'); const abcNumeralSystem = ['o', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; const tests: any[] = [ // Delimiters ['123 456 789,12', withDelimiters([' ', ',']), 123456789.12], ['123**789-12', withDelimiters(['**', '-']), 123789.12], ['1_234+33', withDelimiters(['_', '+']), 1234.33], ['-1٬234٫10', withDelimiters(['٬', '٫']), -1234.1], ['1"234^33', withDelimiters(['"', '^']), 1234.33], ['-1.234,33', withDelimiters(['.', ',']), -1234.33], ['(1.234,33)', withDelimiters(['.', ',']), -1234.33], ['1$234`33-', withDelimiters(['$', '`']), -1234.33], ['1\'234,33-', withDelimiters(['\'', ',']), -1234.33], ['+1\'000,19', withDelimiters(['\'', ',']), 1000.19], ['1\'000,19+', withDelimiters(['\'', ',']), 1000.19], // Grouping style ['1,23,456.789', withGroupingStyle([3, 2]), 123456.789], ['-1,23,456.789', withGroupingStyle([3, 2]), -123456.789], ['3,456.789', withGroupingStyle([3, 2]), 3456.789], ['9,8712,3456.789', withGroupingStyle([4]), 987123456.789], ['-9,8712,3456.789', withGroupingStyle([4]), -987123456.789], ['2,3456.789', withGroupingStyle([4]), 23456.789], ['(2,3456.789)', withGroupingStyle([4]), -23456.789], ['2,3456.789-', withGroupingStyle([4]), -23456.789], ['+2,3456.789', withGroupingStyle([4]), 23456.789], ['2,3456.789+', withGroupingStyle([4]), 23456.789], // Abbreviations (also with multiple characters) ['2.2K', withAbbreviations('|||K'), 2200], ['-2.2K', withAbbreviations('|||K'), -2200], ['10 M', withAbbreviations('|||K|||M'), 10000000], ['-23.8 M', withAbbreviations('|||K|||M'), -23800000], ['-1.25 B', withAbbreviations('|||K|||M|||B'), -1250000000], ['900.88 B', withAbbreviations('|||K|||M|||B'), 900880000000], ['5.198 T', withAbbreviations('|||K|||M|||B|||T'), 5198000000000], ['-23.504 T', withAbbreviations('|||K|||M|||B|||T'), -23504000000000], ['10,200 T', withAbbreviations('|||K|||M|||B|||T'), 10200000000000000], ['13 K', withAbbreviations('|||K|||M|||B|||T'), 13000], ['13 M', withAbbreviations('|||K|||M|||B|||T'), 13000000], ['-13 B', withAbbreviations('|||K|||M|||B|||T'), -13000000000], ['13', withAbbreviations('|||K|||M|||B|||T'), 13], ['-13', withAbbreviations('|||K|||M|||B|||T'), -13], ['2.62 Ka', withAbbreviations('|||Ka|||Ma|||Ba|||Ta'), 2620], ['2.62 Ma', withAbbreviations('|||Ka|||Ma|||Ba|||Ta'), 2620000], ['-2.62 Ba', withAbbreviations('|||Ka|||Ma|||Ba|||Ta'), -2620000000], ['2.62 Ta', withAbbreviations('|||Ka|||Ma|||Ba|||Ta'), 2620000000000], ['3.5 T', withAbbreviations('|||T||L||Cr|||TCr||LCr'), 3500], ['3.5 L', withAbbreviations('|||T||L||Cr|||TCr||LCr'), 350000], ['-3.5 Cr', withAbbreviations('|||T||L||Cr|||TCr||LCr'), -35000000], ['3.5 TCr', withAbbreviations('|||T||L||Cr|||TCr||LCr'), 35000000000], ['3.5 LCr', withAbbreviations('|||T||L||Cr|||TCr||LCr'), 3500000000000], ['4.256 mil', withAbbreviations('|||mil|||M|||mil M|||B'), 4256], ['-4.256 M', withAbbreviations('|||mil|||M|||mil M|||B'), -4256000], ['4.256 mil M', withAbbreviations('|||mil|||M|||mil M|||B'), 4256000000], ['4.256 B', withAbbreviations('|||mil|||M|||mil M|||B'), 4256000000000], ['-1.01 asd a', withAbbreviations('|||asd a|||asd b|||asd c|||asd d'), -1010], ['1.01asd b', withAbbreviations('|||asd a|||asd b|||asd c|||asd d'), 1010000], ['-1.01 asd c', withAbbreviations('|||asd a|||asd b|||asd c|||asd d'), -1010000000], ['1.01asd d', withAbbreviations('|||asd a|||asd b|||asd c|||asd d'), 1010000000000], ['6.19 万', withAbbreviations('||||万||||亿||||万亿'), 61900], ['6.19亿', withAbbreviations('||||万||||亿||||万亿'), 619000000], ['-6.19 万亿', withAbbreviations('||||万||||亿||||万亿'), -6190000000000], ['6,1900 万亿', withAbbreviations('||||万||||亿||||万亿'), 61900000000000000], ['(1.23 K)', withAbbreviations('|||K|||M|||B|||T'), -1230], ['+1.23 K', withAbbreviations('|||K|||M|||B|||T'), 1230], ['1.23- K', withAbbreviations('|||K|||M|||B|||T'), -1230], ['1.23+ K', withAbbreviations('|||K|||M|||B|||T'), 1230], ['1 ألف\u200e', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), 1000], ['-1 ألف\u200e', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), -1000], ['(1 ألف\u200e)', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), -1000], ['+1 ألف\u200e', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), 1000], ['1- ألف\u200e', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), -1000], ['1+ ألف\u200e', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), 1000], ['1 ألف', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), 1000], ['-1 ألف', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), -1000], ['(1 ألف)', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), -1000], ['+1 ألف', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), 1000], ['1- ألف', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), -1000], ['1+ ألف', withAbbreviations('|||ألف\u200e|||مليون\u200e|||مليار\u200e|||ترليون\u200e'), 1000], // Numeral system ['abc,def.ghioa', withNumeralSystem(abcNumeralSystem), 123456.78901], ['-abc,def.ghioa', withNumeralSystem(abcNumeralSystem), -123456.78901], ['f.oa', withNumeralSystem(abcNumeralSystem), 6.01], ['-f.oa', withNumeralSystem(abcNumeralSystem), -6.01], ['abc,def,ghi.oab', withNumeralSystem(abcNumeralSystem), 123456789.012], ['-abc,def,ghi.oab', withNumeralSystem(abcNumeralSystem), -123456789.012], ['i,hgf,edc,bao', withNumeralSystem(abcNumeralSystem), 9876543210], ['-i,hgf,edc,bao', withNumeralSystem(abcNumeralSystem), -9876543210], ['+f.oa', withNumeralSystem(abcNumeralSystem), 6.01], ['f.oa+', withNumeralSystem(abcNumeralSystem), 6.01], ['f.oa-', withNumeralSystem(abcNumeralSystem), -6.01], ['(f.oa)', withNumeralSystem(abcNumeralSystem), -6.01], ['٩\u200e٨\u200e٧\u200e٦\u200e٥\u200e٤\u200e٣\u200e٢\u200e١\u200e٠\u200e', withNumeralSystem(arabNumeralSystem), 9876543210], ['-٩\u200e٨\u200e٧\u200e٦\u200e٥\u200e٤\u200e٣\u200e٢\u200e١\u200e٠\u200e', withNumeralSystem(arabNumeralSystem), -9876543210], ['٩\u200e٨\u200e٧\u200e٦\u200e٥\u200e٤\u200e٣\u200e٢\u200e.١\u200e٠\u200e٩\u200e', withNumeralSystem(arabNumeralSystem), 98765432.109], ['+٩\u200e٨\u200e٧\u200e٦\u200e٥\u200e٤\u200e٣\u200e٢\u200e.١\u200e٠\u200e٩\u200e', withNumeralSystem(arabNumeralSystem), 98765432.109], ['٩\u200e٨\u200e٧\u200e٦\u200e٥\u200e٤\u200e٣\u200e٢\u200e.١\u200e٠\u200e٩\u200e-', withNumeralSystem(arabNumeralSystem), -98765432.109], ['٩\u200e٨\u200e٧\u200e٦\u200e٥\u200e٤\u200e٣\u200e٢\u200e.١\u200e٠\u200e٩\u200e+', withNumeralSystem(arabNumeralSystem), 98765432.109], ['٩٨٧٦٥٤٣٢.١٠٩', withNumeralSystem(arabNumeralSystem), 98765432.109], // - Numeral system with abbreviations ['abc.def K', withObject({ numeralSystem: abcNumeralSystem, abbreviations: '|||K|||M|||B' }), 123456], ['-abc.def K', withObject({ numeralSystem: abcNumeralSystem, abbreviations: '|||K|||M|||B' }), -123456], ['(abc.def M)', withObject({ numeralSystem: abcNumeralSystem, abbreviations: '|||K|||M|||B' }), -123456000], ['+abc.def B', withObject({ numeralSystem: abcNumeralSystem, abbreviations: '|||K|||M|||B' }), 123456000000], ['abc.def- B', withObject({ numeralSystem: abcNumeralSystem, abbreviations: '|||K|||M|||B' }), -123456000000], ['abc.def+ B', withObject({ numeralSystem: abcNumeralSystem, abbreviations: '|||K|||M|||B' }), 123456000000], // - Mixed ['a,bc,def', withObject({ numeralSystem: abcNumeralSystem, digitGroupingStyle: [3,2] }), 123456], ['ab,cdef.a', withObject({ numeralSystem: abcNumeralSystem, digitGroupingStyle: [4] }), 123456.1], ['abc*def_a', withObject({ numeralSystem: abcNumeralSystem, delimiters: { thousands: '*', decimal: '_'} }), 123456.1], ['ab\'cdef,a', withObject({ numeralSystem: abcNumeralSystem, delimiters: { thousands: '\'', decimal: ','}, digitGroupingStyle: [4], abbreviations: '|||K|||M' }), 123456.1], ]; tests.forEach(([value, locale, expectedResult]) => { expect([value, parse(value, { locale })]).toEqual([value, expectedResult]); }); }); it('should return 0 if the string matches with the zeroFormat', () => { expect(parse('N/A', { zeroFormat: 'N/A' })).toBe(0); expect(parse('{} TEST_ZERO_FORMAT {}', { zeroFormat: '{} TEST_ZERO_FORMAT {}' })).toBe(0); expect(parse('{} TEST_ZERO_FORMAT {}', { zeroFormat: '{} TEST_ZERO_FORMAT {}', nullFormat: 'NULL' })).toBe(0); }); it('should return null if the string matches with the nullFormat', () => { expect(parse('NULL', { nullFormat: 'NULL' })).toBe(null); expect(parse('2 NULL', { nullFormat: '2 NULL' })).toBe(null); expect(parse('', { nullFormat: '' })).toBe(null); }); describe('formatters', () => { const getTestFormatter = ( unformatMatcher: NumerableFormatter['regexps']['unformat'], unformatFunction: NumerableFormatter['unformat'], ): NumerableFormatter => ({ name: 'test-formatter', regexps: { // format: formatMatcher, format: /t/, unformat: unformatMatcher, }, format: () => '', unformat: unformatFunction, }); it('should unformat using the provided formatter', () => { // Should return the specified value const formatter1 = getTestFormatter(/\*\*/, () => 3333); expect(parse('test **', { formatters: [formatter1] })).toBe(3333); // Should receive the string const formatter2 = getTestFormatter(/eee/, (string) => string === 'eee' ? 33 : null); expect(parse('eee', { formatters: [formatter2] })).toBe(33); // Should Call the matcher function const formatter3 = getTestFormatter(pattern => pattern === '1987 &*', () => 57); expect(parse('1987 &*', { formatters: [formatter3] })).toBe(57); // Should avoid the formatter if matcher function returns false const avoidFormatSpy = jest.fn(); parse('1,200.000 &*', { formatters: [getTestFormatter(() => false, avoidFormatSpy)] }); expect(avoidFormatSpy).toHaveBeenCalledTimes(0); }); it('should call the formatters resolver if it is provided', () => { // Using percentage sign (it should be by default catched by built-in percentage formatter, but not in this case) const formatter = getTestFormatter(/%/, () => 50); expect(parse('1,2000.000 %', { formatters: builtInFormatters => [formatter, ...builtInFormatters] })).toBe(50); // Not applying percentage (no formatters) expect(parse('10 %', { formatters: () => [] })).toBe(10); }); it('should apply first the passed formatters (before the built-in ones)', () => { // Using percentage sign (it should be by default catched by the passed formatter) const formatter = getTestFormatter(/%/, () => 2000); expect(parse('100 %', { formatters: [formatter] })).toBe(2000); }); }); describe('option::nonBreakingSpace', () => { it('should properly parse an input with non-breaking spaces', () => { const tests: [string, number][] = [ ['100.00\u00A0%', 1], ['1000.00\u00A0%', 10], ['0.100\u00A0\u00A0\u00A0\u00A0%', 0.001], ['10.5\u00A0%', 0.105], ['%\u00A0\u00A0\u00A0\u00A01.00', 0.01], ['-100.00\u00A0%', -1], ['-1000.00\u00A0%', -10], ['-0.100\u00A0\u00A0\u00A0\u00A0%', -0.001], ]; tests.forEach(([number, expectedResult]) => { const result = parse(number); expect([number, result]).toEqual([number, expectedResult]); }); }); }); });
the_stack
import React from 'react'; import { render, cleanup } from '@testing-library/react-native'; import { Text, View } from 'react-native'; import { GestureHandlerRootView, PanGestureHandler, LongPressGestureHandler, RotationGestureHandler, Gesture, GestureDetector, State, PanGesture, TapGesture, } from '../index'; import { useAnimatedGestureHandler } from 'react-native-reanimated'; import { fireGestureHandler, getByGestureTestId } from '../jestUtils'; beforeEach(cleanup); const mockedEventHandlers = () => { return { begin: jest.fn(), start: jest.fn(), active: jest.fn(), end: jest.fn(), fail: jest.fn(), cancel: jest.fn(), finish: jest.fn(), }; }; interface EventHandlersProps { eventHandlers: ReturnType<typeof mockedEventHandlers>; } describe('Using RNGH v1 base API', () => { function SingleHandler({ eventHandlers }: EventHandlersProps) { const handlers = { onBegan: eventHandlers.begin, onActivated: eventHandlers.active, onEnded: eventHandlers.end, onCancelled: eventHandlers.cancel, onFailed: eventHandlers.fail, onGestureEvent: eventHandlers.active, }; return ( <GestureHandlerRootView> <PanGestureHandler testID="pan" {...handlers}> <Text>Pan handler</Text> </PanGestureHandler> </GestureHandlerRootView> ); } function NestedHandlers({ eventHandlers }: EventHandlersProps) { const handlers = { onBegan: eventHandlers.begin, onActivated: eventHandlers.active, onEnded: eventHandlers.end, onCancelled: eventHandlers.cancel, onFailed: eventHandlers.fail, onGestureEvent: eventHandlers.active, }; return ( <GestureHandlerRootView> <PanGestureHandler testID="pan" {...handlers}> <View> <Text>Pan handler</Text> <RotationGestureHandler testID="rotation" {...handlers}> <Text>Rotation handler</Text> </RotationGestureHandler> </View> </PanGestureHandler> </GestureHandlerRootView> ); } it('receives events', () => { const handlers = mockedEventHandlers(); const { getByTestId } = render(<SingleHandler eventHandlers={handlers} />); fireGestureHandler<PanGestureHandler>(getByTestId('pan'), [ { oldState: State.UNDETERMINED, state: State.BEGAN }, { oldState: State.BEGAN, state: State.ACTIVE }, { oldState: State.ACTIVE, state: State.ACTIVE }, { oldState: State.ACTIVE, state: State.END }, ]); expect(handlers.begin).toBeCalled(); expect(handlers.active).toBeCalled(); expect(handlers.end).toBeCalled(); expect(handlers.cancel).not.toBeCalled(); expect(handlers.fail).not.toBeCalled(); }); it('receives events correct number of times', () => { const handlers = mockedEventHandlers(); const { getByTestId } = render(<SingleHandler eventHandlers={handlers} />); fireGestureHandler<PanGestureHandler>(getByTestId('pan'), [ { oldState: State.UNDETERMINED, state: State.BEGAN }, { oldState: State.BEGAN, state: State.ACTIVE }, { oldState: State.ACTIVE, state: State.ACTIVE }, // gesture event { oldState: State.ACTIVE, state: State.END }, ]); expect(handlers.begin).toBeCalledTimes(1); expect(handlers.active).toBeCalledTimes(2); expect(handlers.end).toBeCalledTimes(1); expect(handlers.cancel).not.toBeCalled(); expect(handlers.fail).not.toBeCalled(); }); it('receives events with correct base fields (state, oldState, numberOfPointers, handlerTag)', () => { const handlers = mockedEventHandlers(); const { getByTestId } = render(<SingleHandler eventHandlers={handlers} />); const component = getByTestId('pan'); const COMMON_EVENT_DATA = { numberOfPointers: 3, handlerTag: component.props.handlerTag as number, }; fireGestureHandler<PanGestureHandler>(component, [ { ...COMMON_EVENT_DATA, oldState: State.UNDETERMINED, state: State.BEGAN, }, // BEGIN - state change { ...COMMON_EVENT_DATA, oldState: State.BEGAN, state: State.ACTIVE }, { ...COMMON_EVENT_DATA, state: State.ACTIVE }, // gesture event ]); // gesture state change expect(handlers.begin).lastCalledWith({ nativeEvent: expect.objectContaining({ ...COMMON_EVENT_DATA, oldState: State.UNDETERMINED, state: State.BEGAN, }), }); // last ACTIVE gesture event, without `oldState` expect(handlers.active).lastCalledWith({ nativeEvent: expect.objectContaining({ ...COMMON_EVENT_DATA, state: State.ACTIVE, }), }); expect(handlers.active).lastCalledWith({ nativeEvent: expect.not.objectContaining({ oldState: expect.any(Number), }), }); }); it.each([ [ 'pan', { translationY: 800, velocityY: 2, }, { translationX: 100, }, ], [ 'rotation', { anchorY: 0, rotation: 3.14, }, { numberOfPointers: 2 }, ], ])( 'receives additional properties depending on handler type ("%s")', ( handlerName: string, additionalEventData: Record<string, unknown>, defaultEventData: Record<string, unknown> ) => { const handlers = mockedEventHandlers(); const { getByTestId } = render( <NestedHandlers eventHandlers={handlers} /> ); fireGestureHandler(getByTestId(handlerName), [ { ...additionalEventData, oldState: State.UNDETERMINED, state: State.BEGAN, }, { ...additionalEventData, oldState: State.BEGAN, state: State.ACTIVE, }, ]); expect(handlers.begin).lastCalledWith({ nativeEvent: expect.objectContaining({ ...additionalEventData, ...defaultEventData, }), }); } ); }); describe('Using Reanimated 2 useAnimatedGestureHandler hook', () => { function UseAnimatedGestureHandler({ eventHandlers }: EventHandlersProps) { const eventHandler = useAnimatedGestureHandler({ onStart: eventHandlers.begin, }); return ( <LongPressGestureHandler testID="longPress" onHandlerStateChange={eventHandler}> <Text>Long press handler</Text> </LongPressGestureHandler> ); } it('calls callback with (event data, context)', () => { const handlers = mockedEventHandlers(); const { getByTestId } = render( <UseAnimatedGestureHandler eventHandlers={handlers} /> ); fireGestureHandler<LongPressGestureHandler>(getByTestId('longPress'), [ { state: State.BEGAN }, { state: State.ACTIVE }, { state: State.END }, ]); expect(handlers.begin).toBeCalledWith( expect.objectContaining({ state: State.BEGAN }), expect.any(Object) ); }); }); describe('Using RNGH v2 gesture API', () => { interface SingleHandlerProps { handlers: ReturnType<typeof mockedEventHandlers>; treatStartAsUpdate?: boolean; } function SingleHandler({ handlers, treatStartAsUpdate }: SingleHandlerProps) { const pan = Gesture.Pan() .onBegin(handlers.begin) .onStart(treatStartAsUpdate ? handlers.active : handlers.start) .onUpdate(handlers.active) .onEnd(handlers.end) .onFinalize(handlers.finish) .withTestId('pan'); return ( <GestureHandlerRootView> <GestureDetector gesture={pan}> <Text>v2 API test</Text> </GestureDetector> </GestureHandlerRootView> ); } interface RacingHandlersProps { tapHandlers: ReturnType<typeof mockedEventHandlers>; panHandlers: ReturnType<typeof mockedEventHandlers>; } function RacingHandlers({ tapHandlers, panHandlers }: RacingHandlersProps) { const tap = Gesture.Tap() .onBegin(tapHandlers.begin) .onEnd(tapHandlers.end) .withTestId('tap'); const pan = Gesture.Pan() .onBegin(panHandlers.begin) .onUpdate(panHandlers.active) .onEnd(panHandlers.end) .onFinalize(panHandlers.finish) .withTestId('pan'); return ( <GestureHandlerRootView> <GestureDetector gesture={Gesture.Race(tap, pan)}> <Text>v2 API test</Text> </GestureDetector> </GestureHandlerRootView> ); } it('sends events to handlers', () => { const tapHandlers = mockedEventHandlers(); const panHandlers = mockedEventHandlers(); render( <RacingHandlers tapHandlers={tapHandlers} panHandlers={panHandlers} /> ); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { state: State.BEGAN }, { state: State.ACTIVE }, { state: State.END }, ]); expect(panHandlers.begin).toBeCalledWith( expect.objectContaining({ state: State.BEGAN }) ); expect(panHandlers.finish).toBeCalled(); expect(tapHandlers.begin).not.toBeCalled(); }); it('sends events with additional data to handlers', () => { const panHandlers = mockedEventHandlers(); render(<SingleHandler handlers={panHandlers} treatStartAsUpdate />); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { state: State.BEGAN, translationX: 0 }, { state: State.ACTIVE, translationX: 10 }, { translationX: 20 }, { translationX: 20 }, { state: State.END, translationX: 30 }, ]); expect(panHandlers.active).toBeCalledTimes(3); expect(panHandlers.active).toHaveBeenLastCalledWith( expect.objectContaining({ translationX: 20 }) ); }); }); describe('Event list validation', () => { interface SingleHandlerProps { handlers: ReturnType<typeof mockedEventHandlers>; treatStartAsUpdate?: boolean; } function SingleHandler({ handlers, treatStartAsUpdate }: SingleHandlerProps) { const pan = Gesture.Pan() .onBegin(handlers.begin) .onStart(treatStartAsUpdate ? handlers.active : handlers.start) .onUpdate(handlers.active) .onEnd(handlers.end) .onFinalize(handlers.finish) .withTestId('pan'); return ( <GestureHandlerRootView> <GestureDetector gesture={pan}> <Text>v2 API test</Text> </GestureDetector> </GestureHandlerRootView> ); } it("throws error when oldState doesn't correspond to previous event's state", () => { const panHandlers = mockedEventHandlers(); render(<SingleHandler handlers={panHandlers} />); expect(() => { fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { oldState: State.UNDETERMINED, state: State.BEGAN, x: 0, y: 10 }, { oldState: State.UNDETERMINED, state: State.ACTIVE, x: 1, y: 11 }, ]); }).toThrow( "when state changes, oldState should be the same as previous event' state" ); }); it.each([[State.END], [State.FAILED], [State.CANCELLED]])( 'correctly handles events ending with state %s', (lastState) => { const panHandlers = mockedEventHandlers(); render(<SingleHandler handlers={panHandlers} />); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { state: State.BEGAN }, { state: State.ACTIVE }, { state: lastState }, ]); if (lastState === State.END) { expect(panHandlers.end).toBeCalled(); } else { expect(panHandlers.finish).toBeCalledWith(expect.any(Object), false); } } ); }); describe('Filling event list with defaults', () => { interface RacingTapAndPanProps { handlers: ReturnType<typeof mockedEventHandlers>; treatStartAsUpdate?: boolean; } function RacingTapAndPan({ handlers, treatStartAsUpdate, }: RacingTapAndPanProps) { const tap = Gesture.Tap() .onBegin(handlers.begin) .onEnd(handlers.end) .withTestId('tap'); const pan = Gesture.Pan() .onBegin(handlers.begin) .onStart(treatStartAsUpdate ? handlers.active : handlers.start) .onUpdate(handlers.active) .onEnd(handlers.end) .onFinalize(handlers.finish) .withTestId('pan'); return ( <GestureHandlerRootView> <GestureDetector gesture={Gesture.Exclusive(pan, tap)}> <Text>v2 API test</Text> </GestureDetector> </GestureHandlerRootView> ); } it('fills oldState if not passed', () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<PanGestureHandler>(getByGestureTestId('pan'), [ { state: State.BEGAN }, { state: State.ACTIVE }, { state: State.ACTIVE }, { state: State.ACTIVE }, { state: State.END }, ]); expect(handlers.begin).toBeCalledWith( expect.objectContaining({ oldState: State.UNDETERMINED }) ); expect(handlers.active).nthCalledWith( 1, expect.objectContaining({ oldState: State.BEGAN }) ); expect(handlers.active).lastCalledWith( expect.not.objectContaining({ oldState: expect.anything() }) ); expect(handlers.end).toBeCalledWith( expect.objectContaining({ oldState: State.ACTIVE }), true ); }); it('fills missing ACTIVE states', () => { const panHandlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={panHandlers} treatStartAsUpdate />); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { state: State.BEGAN, x: 0, y: 10 }, { state: State.ACTIVE, x: 1, y: 11 }, { x: 2, y: 12 }, { x: 3, y: 13 }, { state: State.END, x: 4, y: 14 }, ]); expect(panHandlers.active).toBeCalledTimes(3); expect(panHandlers.active).toHaveBeenLastCalledWith( expect.objectContaining({ x: 3, y: 13 }) ); }); it('fills BEGIN and END events for discrete handlers', () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<TapGesture>(getByGestureTestId('tap'), [{ x: 5 }]); expect(handlers.begin).toBeCalledTimes(1); expect(handlers.end).toBeCalledTimes(1); }); it('with FAILED event, fills BEGIN event for discrete handlers', () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<TapGesture>(getByGestureTestId('tap'), [ { state: State.FAILED }, ]); expect(handlers.begin).toBeCalledTimes(1); expect(handlers.end).toBeCalledTimes(1); expect(handlers.end).toBeCalledWith(expect.anything(), false); }); it('uses event data from first event in filled BEGIN, ACTIVE events', () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [{ x: 120 }]); expect(handlers.begin).toBeCalledWith(expect.objectContaining({ x: 120 })); expect(handlers.active).toHaveBeenNthCalledWith( 1, expect.objectContaining({ x: 120 }) ); }); it('uses event data from last event in filled END events', () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { x: 120, state: State.FAILED }, ]); expect(handlers.begin).toBeCalledTimes(1); expect(handlers.active).toBeCalledTimes(1); expect(handlers.end).toBeCalledWith( expect.objectContaining({ x: 120 }), false ); }); it('uses event data filled events', () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<PanGesture>(getByGestureTestId('pan'), [ { x: 5, y: 15 }, { x: 6, y: 16 }, { x: 7, y: 17 }, ]); expect(handlers.begin).toBeCalledWith( expect.objectContaining({ x: 5, y: 15 }) ); expect(handlers.active).toBeCalledTimes(3); expect(handlers.end).toBeCalledWith( expect.objectContaining({ x: 7, y: 17 }), true ); }); it("fills BEGIN and END events when they're not present, for discrete handlers", () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<TapGesture>(getByGestureTestId('tap')); expect(handlers.begin).toBeCalledTimes(1); expect(handlers.end).toHaveBeenCalledTimes(1); }); it("fills BEGIN, ACTIVE and END events when they're not present, for continuous handlers", () => { const handlers = mockedEventHandlers(); render(<RacingTapAndPan handlers={handlers} treatStartAsUpdate />); fireGestureHandler<PanGesture>(getByGestureTestId('pan')); expect(handlers.begin).toBeCalledTimes(1); expect(handlers.active).toBeCalledTimes(1); expect(handlers.end).toHaveBeenCalledTimes(1); }); });
the_stack
import { EMPTY, forkJoin, Observable, Observer, of, throwError } from 'rxjs'; import * as turf from '@turf/turf'; import * as GeoJSON from 'geojson'; import { Point } from 'geojson'; import { Actions, ofType } from '@ngrx/effects'; import { select, Store } from '@ngrx/store'; import { areCoordinatesNumeric, BaseImageryPlugin, CommunicatorEntity, getAngleDegreeBetweenPoints, IImageryMapPosition, ImageryPlugin, MapOrientation, toDegrees, toRadians } from '@ansyn/imagery'; import { MapActionTypes, PointToRealNorthAction, selectActiveMapId, selectMapPositionByMapId, PointToImageOrientationAction, } from '@ansyn/map-facade'; import { AutoSubscription } from 'auto-subscriptions'; import { OpenLayersMap, OpenLayersProjectionService } from '@ansyn/ol'; import { catchError, debounceTime, filter, map, mergeMap, retry, switchMap, take, tap, withLatestFrom } from 'rxjs/operators'; import OLMap from 'ol/Map'; import View from 'ol/View'; import ol_Layer from 'ol/layer/Layer'; import { LoggerService } from '../../../../core/services/logger.service'; import { ChangeOverlayPreviewRotationAction, DisplayOverlaySuccessAction, OverlaysActionTypes } from '../../../../overlays/actions/overlays.actions'; import { selectHoveredOverlay } from '../../../../overlays/reducers/overlays.reducer'; import { IOverlay } from '../../../../overlays/models/overlay.model'; import { BackToWorldSuccess, BackToWorldView, OverlayStatusActionsTypes } from '../../../../overlays/overlay-status/actions/overlay-status.actions'; import { CoreConfig } from '../../../../core/models/core.config'; import { Inject } from '@angular/core'; import { ICoreConfig } from '../../../../core/models/core.config.model'; import { selectMapOrientation } from '@ansyn/map-facade'; @ImageryPlugin({ supported: [OpenLayersMap], deps: [Actions, LoggerService, Store, CoreConfig, OpenLayersProjectionService] }) export class NorthCalculationsPlugin extends BaseImageryPlugin { communicator: CommunicatorEntity; isEnabled = true; protected maximumNumberOfRetries = 10; protected thresholdDegrees = 0.1; shadowMapObject: OLMap; shadowMapObjectView: View; @AutoSubscription hoveredOverlayPreview$: Observable<any> = this.store$.select(selectHoveredOverlay).pipe( withLatestFrom(this.store$.pipe(select(selectActiveMapId))), filter(([overlay, activeMapId]: [IOverlay, string]) => Boolean(overlay) && Boolean(this.communicator) && activeMapId === this.mapId), mergeMap(([{ projection }]: [IOverlay, string]) => { const view = this.communicator.ActiveMap.mapObject.getView(); const viewProjection = view.getProjection(); const sourceProjectionCode = viewProjection.getCode(); return this.getPreviewNorth(sourceProjectionCode, projection) .pipe(catchError(() => of(0))); }), tap((north: number) => { this.store$.dispatch(new ChangeOverlayPreviewRotationAction(-north)); }) ); @AutoSubscription pointToRealNorth$ = this.actions$.pipe( ofType<PointToRealNorthAction>(MapActionTypes.POINT_TO_REAL_NORTH), filter((action: PointToRealNorthAction) => action.payload === this.mapId), switchMap((action: PointToRealNorthAction) => { return this.setActualNorth(); }) ); @AutoSubscription pointToImageOrientation$ = this.actions$.pipe( ofType<PointToImageOrientationAction>(MapActionTypes.POINT_TO_IMAGE_ORIENTATION), filter((action: PointToImageOrientationAction) => action.payload.mapId === this.mapId), tap((action: PointToImageOrientationAction) => { this.setImageryOrientation(action.payload.overlay); }) ); constructor(protected actions$: Actions, public loggerService: LoggerService, public store$: Store<any>, @Inject(CoreConfig) public config: ICoreConfig, protected projectionService: OpenLayersProjectionService) { super(); } @AutoSubscription calcNorthAfterDisplayOverlaySuccess$ = () => this.actions$.pipe( ofType<DisplayOverlaySuccessAction>(OverlaysActionTypes.DISPLAY_OVERLAY_SUCCESS), filter((action: DisplayOverlaySuccessAction) => action.payload.mapId === this.mapId), withLatestFrom(this.store$.select(selectMapOrientation(this.mapId)), ({ payload }: DisplayOverlaySuccessAction, orientation: MapOrientation) => { return [payload.forceFirstDisplay, orientation , payload.overlay, payload.customOriantation]; }), switchMap(([forceFirstDisplay, orientation, overlay, customOriantation]: [boolean, MapOrientation, IOverlay, string]) => { // for 'Imagery Perspective' or 'User Perspective' return this.positionChangedCalcNorthAccurately$().pipe(take(1)).pipe( tap((virtualNorth: number) => { this.communicator.setVirtualNorth(virtualNorth); if (!forceFirstDisplay && (orientation === 'Imagery Perspective' || customOriantation === 'Imagery Perspective')) { this.setImageryOrientation(overlay); } // else if 'User Perspective' do nothing })); }) ); @AutoSubscription backToWorldSuccessSetNorth$ = () => this.actions$.pipe( ofType<BackToWorldSuccess>(OverlayStatusActionsTypes.BACK_TO_WORLD_SUCCESS), filter((action: BackToWorldSuccess) => action.payload.mapId === this.communicator.id), withLatestFrom(this.store$.select(selectMapOrientation(this.mapId))), tap(([action, orientation]: [BackToWorldView, MapOrientation]) => { if (this.shadowMapObject) { this.shadowMapObject.getLayers().clear(); } this.communicator.setVirtualNorth(0); if (orientation === 'Imagery Perspective') { this.communicator.setRotation(0); } }) ); setImageryOrientation(overlay: IOverlay) { if (!overlay) { return; } if (overlay.sensorLocation && !this.config.northCalcImagerySensorNamesIgnoreList.includes(overlay.sensorName)) { this.communicator.getCenter().pipe(take(1)).subscribe(point => { const brng = getAngleDegreeBetweenPoints(overlay.sensorLocation, point); const resultBearings = (360 - (brng + toDegrees(-this.communicator.getVirtualNorth()))) % 360; this.communicator.setRotation(toRadians(resultBearings)); }); } else { this.communicator.setRotation(overlay.azimuth); } } @AutoSubscription positionChangedCalcNorthAccurately$ = () => this.store$.select(selectMapPositionByMapId(this.mapId)).pipe( debounceTime(50), filter(Boolean), switchMap((position: IImageryMapPosition) => { const view = this.iMap.mapObject.getView(); const projection = view.getProjection(); if (projection.getUnits() === 'pixels' && position) { if (!position.projectedState) { return of(0); } return this.pointNorth(this.shadowMapObject).pipe(take(1)).pipe( map((calculatedNorthAngleAfterPointingNorth: number) => { const shRotation = this.shadowMapObjectView.getRotation(); let currentRotationDegrees = toDegrees(shRotation); if (currentRotationDegrees < 0) { currentRotationDegrees = 360 + currentRotationDegrees; } currentRotationDegrees = currentRotationDegrees % 360; return toRadians(currentRotationDegrees); }), catchError((error) => of(0)) // prevent's subscriber disappearance ); } return of(0); }) ); setActualNorth(): Observable<any> { return this.pointNorth(this.shadowMapObject).pipe(take(1)).pipe( tap((virtualNorth: number) => { this.communicator.setVirtualNorth(virtualNorth); this.communicator.setRotation(virtualNorth); }), catchError(reason => { return EMPTY; }) ); } pointNorth(mapObject: OLMap): Observable<any> { mapObject.updateSize(); mapObject.renderSync(); return this.getCorrectedNorth(mapObject).pipe( catchError(reason => { const error = `setCorrectedNorth failed ${reason}`; this.loggerService.warn(error, 'map', 'north_plugin'); return throwError(error); }) ); } getCorrectedNorth(mapObject: OLMap): Observable<any> { return this.getProjectedCenters(mapObject).pipe( map((projectedCenters: Point[]): any => { const projectedCenterView = projectedCenters[0].coordinates; const projectedCenterViewWithoffset = projectedCenters[1].coordinates; const northOffsetRad = Math.atan2((projectedCenterViewWithoffset[0] - projectedCenterView[0]), (projectedCenterViewWithoffset[1] - projectedCenterView[1])); const northOffsetDeg = toDegrees(northOffsetRad); const view = mapObject.getView(); const actualNorth = northOffsetRad + view.getRotation(); return { northOffsetRad, northOffsetDeg, actualNorth }; }), mergeMap((northData) => { const view = mapObject.getView(); view.setRotation(northData.actualNorth); mapObject.renderSync(); if (Math.abs(northData.northOffsetDeg) > this.thresholdDegrees) { return throwError({ result: northData.actualNorth }); } return of(northData.actualNorth); }), retry(this.maximumNumberOfRetries), catchError((e) => e.result ? of(e.result) : throwError(e)) ); } getPreviewNorth(sourceProjection: string, destProjection: string) { const mapObject = this.iMap.mapObject; return this.getProjectedCenters(mapObject, sourceProjection, destProjection).pipe( map((projectedCenters: Point[]): number => { const projectedCenterView = projectedCenters[0].coordinates; const projectedCenterViewWithOffset = projectedCenters[1].coordinates; const northOffsetRad = Math.atan2((projectedCenterViewWithOffset[0] - projectedCenterView[0]), (projectedCenterViewWithOffset[1] - projectedCenterView[1])); return northOffsetRad; }) ); } projectPoints(coordinates: [number, number][], sourceProjection: string, destProjection: string): Observable<Point[] | any> { return forkJoin(coordinates.map((coordinate) => { const point = <GeoJSON.Point>turf.geometry('Point', coordinate); if (sourceProjection && destProjection) { return this.projectionService.projectApproximatelyFromProjection(point, sourceProjection, destProjection); } return this.projectionService.projectAccurately(point, this.iMap.mapObject); })); } getProjectedCenters(mapObject: OLMap, sourceProjection?: string, destProjection?: string): Observable<Point[]> { return new Observable((observer: Observer<any>) => { const size = mapObject.getSize(); const olCenterView = mapObject.getCoordinateFromPixel([size[0] / 2, size[1] / 2]); if (!areCoordinatesNumeric(olCenterView)) { observer.error('no coordinate for pixel'); } const olCenterViewWithOffset = mapObject.getCoordinateFromPixel([size[0] / 2, (size[1] / 2) - 1]); if (!areCoordinatesNumeric(olCenterViewWithOffset)) { observer.error('no coordinate for pixel'); } observer.next([olCenterView, olCenterViewWithOffset]); }) .pipe(switchMap((centers: [number, number][]) => this.projectPoints(centers, sourceProjection, destProjection))); } onInit() { super.onInit(); this.createShadowMap(); } createShadowMap() { if (!this.shadowMapObject) { this.createShadowMapObject(); } const view = this.communicator.ActiveMap.mapObject.getView(); const projectedState = { ...(<any>view).getState(), center: (<any>view).getCenter() }; this.resetShadowMapView(projectedState); } onResetView(): Observable<boolean> { this.createShadowMap(); return of(true); } createShadowMapObject() { const renderer = 'canvas'; this.shadowMapObject = new OLMap({ target: (<any>this.iMap).shadowNorthElement, renderer, controls: [] }); } resetShadowMapView(projectedState) { const mainLayer = this.iMap.getMainLayer() as ol_Layer; const { center, zoom, rotation } = projectedState; this.shadowMapObjectView = new View({ projection: mainLayer.getSource().getProjection(), center, zoom, rotation }); this.shadowMapObject.setView(this.shadowMapObjectView); } }
the_stack
import { TxData, TxDataPayable } from "../../types"; import * as promisify from "tiny-promisify"; import { classUtils } from "../../../utils/class_utils"; import { Web3Utils } from "../../../utils/web3_utils"; import { BigNumber } from "../../../utils/bignumber"; import { TokenTransferProxy as ContractArtifacts } from "@dharmaprotocol/contracts"; import * as Web3 from "web3"; import { BaseContract, CONTRACT_WRAPPER_ERRORS } from "./base_contract_wrapper"; export class TokenTransferProxyContract extends BaseContract { public addAuthorizedTransferAgent = { async sendTransactionAsync(_agent: string, txData: TxData = {}): Promise<string> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.addAuthorizedTransferAgent.estimateGasAsync.bind(self, _agent), ); const txHash = await promisify<string>( self.web3ContractInstance.addAuthorizedTransferAgent, self.web3ContractInstance, )(_agent, txDataWithDefaults); return txHash; }, async estimateGasAsync(_agent: string, txData: TxData = {}): Promise<number> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.addAuthorizedTransferAgent.estimateGas, self.web3ContractInstance, )(_agent, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(_agent: string, txData: TxData = {}): string { const self = this as TokenTransferProxyContract; const abiEncodedTransactionData = self.web3ContractInstance.addAuthorizedTransferAgent.getData(); return abiEncodedTransactionData; }, }; public transferFrom = { async sendTransactionAsync( _token: string, _from: string, _to: string, _amount: BigNumber, txData: TxData = {}, ): Promise<string> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.transferFrom.estimateGasAsync.bind(self, _token, _from, _to, _amount), ); const txHash = await promisify<string>( self.web3ContractInstance.transferFrom, self.web3ContractInstance, )(_token, _from, _to, _amount, txDataWithDefaults); return txHash; }, async estimateGasAsync( _token: string, _from: string, _to: string, _amount: BigNumber, txData: TxData = {}, ): Promise<number> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.transferFromAsync.estimateGas, self.web3ContractInstance, )(_token, _from, _to, _amount, txDataWithDefaults); return gas; }, getABIEncodedTransactionData( _token: string, _from: string, _to: string, _amount: BigNumber, txData: TxData = {}, ): string { const self = this as TokenTransferProxyContract; const abiEncodedTransactionData = self.web3ContractInstance.transferFromAsync.getData(); return abiEncodedTransactionData; }, }; public unpause = { async sendTransactionAsync(txData: TxData = {}): Promise<string> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.unpause.estimateGasAsync.bind(self), ); const txHash = await promisify<string>( self.web3ContractInstance.unpause, self.web3ContractInstance, )(txDataWithDefaults); return txHash; }, async estimateGasAsync(txData: TxData = {}): Promise<number> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.unpause.estimateGas, self.web3ContractInstance, )(txDataWithDefaults); return gas; }, getABIEncodedTransactionData(txData: TxData = {}): string { const self = this as TokenTransferProxyContract; const abiEncodedTransactionData = self.web3ContractInstance.unpause.getData(); return abiEncodedTransactionData; }, }; public paused = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<boolean> { const self = this as TokenTransferProxyContract; const result = await promisify<boolean>( self.web3ContractInstance.paused.call, self.web3ContractInstance, )(); return result; }, }; public pause = { async sendTransactionAsync(txData: TxData = {}): Promise<string> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.pause.estimateGasAsync.bind(self), ); const txHash = await promisify<string>( self.web3ContractInstance.pause, self.web3ContractInstance, )(txDataWithDefaults); return txHash; }, async estimateGasAsync(txData: TxData = {}): Promise<number> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.pause.estimateGas, self.web3ContractInstance, )(txDataWithDefaults); return gas; }, getABIEncodedTransactionData(txData: TxData = {}): string { const self = this as TokenTransferProxyContract; const abiEncodedTransactionData = self.web3ContractInstance.pause.getData(); return abiEncodedTransactionData; }, }; public owner = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string> { const self = this as TokenTransferProxyContract; const result = await promisify<string>( self.web3ContractInstance.owner.call, self.web3ContractInstance, )(); return result; }, }; public revokeTransferAgentAuthorization = { async sendTransactionAsync(_agent: string, txData: TxData = {}): Promise<string> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.revokeTransferAgentAuthorization.estimateGasAsync.bind(self, _agent), ); const txHash = await promisify<string>( self.web3ContractInstance.revokeTransferAgentAuthorization, self.web3ContractInstance, )(_agent, txDataWithDefaults); return txHash; }, async estimateGasAsync(_agent: string, txData: TxData = {}): Promise<number> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.revokeTransferAgentAuthorization.estimateGas, self.web3ContractInstance, )(_agent, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(_agent: string, txData: TxData = {}): string { const self = this as TokenTransferProxyContract; const abiEncodedTransactionData = self.web3ContractInstance.revokeTransferAgentAuthorization.getData(); return abiEncodedTransactionData; }, }; public getAuthorizedTransferAgents = { async callAsync(defaultBlock?: Web3.BlockParam): Promise<string[]> { const self = this as TokenTransferProxyContract; const result = await promisify<string[]>( self.web3ContractInstance.getAuthorizedTransferAgents.call, self.web3ContractInstance, )(); return result; }, }; public transferOwnership = { async sendTransactionAsync(newOwner: string, txData: TxData = {}): Promise<string> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync( txData, self.transferOwnership.estimateGasAsync.bind(self, newOwner), ); const txHash = await promisify<string>( self.web3ContractInstance.transferOwnership, self.web3ContractInstance, )(newOwner, txDataWithDefaults); return txHash; }, async estimateGasAsync(newOwner: string, txData: TxData = {}): Promise<number> { const self = this as TokenTransferProxyContract; const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData); const gas = await promisify<number>( self.web3ContractInstance.transferOwnership.estimateGas, self.web3ContractInstance, )(newOwner, txDataWithDefaults); return gas; }, getABIEncodedTransactionData(newOwner: string, txData: TxData = {}): string { const self = this as TokenTransferProxyContract; const abiEncodedTransactionData = self.web3ContractInstance.transferOwnership.getData(); return abiEncodedTransactionData; }, }; constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) { super(web3ContractInstance, defaults); classUtils.bindAll(this, ["web3ContractInstance", "defaults"]); } public static async deployed( web3: Web3, defaults: Partial<TxData>, ): Promise<TokenTransferProxyContract> { const web3Utils = new Web3Utils(web3); const currentNetwork = await web3Utils.getNetworkIdAsync(); const { abi, networks }: { abi: any; networks: any } = ContractArtifacts; if (networks[currentNetwork]) { const { address: contractAddress } = networks[currentNetwork]; const contractExists = await web3Utils.doesContractExistAtAddressAsync(contractAddress); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(contractAddress); return new TokenTransferProxyContract(web3ContractInstance, defaults); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "TokenTransferProxy", currentNetwork, ), ); } } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "TokenTransferProxy", currentNetwork, ), ); } } public static async at( address: string, web3: Web3, defaults: Partial<TxData>, ): Promise<TokenTransferProxyContract> { const web3Utils = new Web3Utils(web3); const { abi }: { abi: any } = ContractArtifacts; const contractExists = await web3Utils.doesContractExistAtAddressAsync(address); const currentNetwork = await web3Utils.getNetworkIdAsync(); if (contractExists) { const web3ContractInstance = web3.eth.contract(abi).at(address); return new TokenTransferProxyContract(web3ContractInstance, defaults); } else { throw new Error( CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK( "TokenTransferProxy", currentNetwork, ), ); } } } // tslint:disable:max-file-line-count
the_stack
import "../../../Operator" import * as Cause from "../../../Cause" import type * as T from "../../../Effect" import type * as Exit from "../../../Exit" import { identity } from "../../../Function" import * as P from "./_internal/primitives" import type * as PR from "./_internal/producer" export type { SingleProducerAsyncInput, AsyncInputProducer, AsyncInputConsumer } from "./_internal/producer" export { makeSingleProducerAsyncInput } from "./_internal/producer" export * from "./_internal/primitives" /** * Pipe the output of a channel into the input of another */ export function pipeTo_< Env, Env2, InErr, InElem, InDone, OutErr, OutElem, OutDone, OutErr2, OutElem2, OutDone2 >( left: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, right: P.Channel<Env2, OutErr, OutElem, OutDone, OutErr2, OutElem2, OutDone2> ): P.Channel<Env & Env2, InErr, InElem, InDone, OutErr2, OutElem2, OutDone2> { return new P.PipeTo< Env & Env2, InErr, InElem, InDone, OutErr2, OutElem2, OutDone2, OutErr, OutElem, OutDone >( () => left, () => right ) } /** * Pipe the output of a channel into the input of another * * @ets_data_first pipeTo_ */ export function pipeTo<Env2, OutErr, OutElem, OutDone, OutErr2, OutElem2, OutDone2>( right: P.Channel<Env2, OutErr, OutElem, OutDone, OutErr2, OutElem2, OutDone2> ): <Env, InErr, InElem, InDone>( left: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ) => P.Channel<Env & Env2, InErr, InElem, InDone, OutErr2, OutElem2, OutDone2> { return (left) => pipeTo_(left, right) } /** * Reads an input and continue exposing both full error cause and completion */ export function readWithCause< Env, Env1, Env2, InErr, InElem, InDone, OutErr, OutErr1, OutErr2, OutElem, OutElem1, OutElem2, OutDone, OutDone1, OutDone2 >( inp: (i: InElem) => P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, halt: ( e: Cause.Cause<InErr> ) => P.Channel<Env1, InErr, InElem, InDone, OutErr1, OutElem1, OutDone1>, done: ( d: InDone ) => P.Channel<Env2, InErr, InElem, InDone, OutErr2, OutElem2, OutDone2> ): P.Channel< Env & Env1 & Env2, InErr, InElem, InDone, OutErr | OutErr1 | OutErr2, OutElem | OutElem1 | OutElem2, OutDone | OutDone1 | OutDone2 > { return new P.Read< Env & Env1 & Env2, InErr, InElem, InDone, OutErr | OutErr1 | OutErr2, OutElem | OutElem1 | OutElem2, OutDone | OutDone1 | OutDone2, InErr, InDone >( inp, new P.ContinuationK< Env & Env1 & Env2, InErr, InElem, InDone, InErr, OutErr | OutErr1 | OutErr2, OutElem | OutElem1 | OutElem2, InDone, OutDone | OutDone1 | OutDone2 >(done, halt) ) } /** * End a channel with the specified result */ export function endWith<OutDone>( result: () => OutDone ): P.Channel<unknown, unknown, unknown, unknown, never, never, OutDone> { return new P.Done(result) } /** * End a channel with the specified result */ export function end<OutDone>( result: OutDone ): P.Channel<unknown, unknown, unknown, unknown, never, never, OutDone> { return new P.Done(() => result) } /** * Halt a channel with the specified cause */ export function failCauseWith<E>( result: () => Cause.Cause<E> ): P.Channel<unknown, unknown, unknown, unknown, E, never, never> { return new P.Halt(result) } /** * Halt a channel with the specified cause */ export function failCause<E>( result: Cause.Cause<E> ): P.Channel<unknown, unknown, unknown, unknown, E, never, never> { return new P.Halt(() => result) } /** * Halt a channel with the specified error */ export function failWith<E>( error: () => E ): P.Channel<unknown, unknown, unknown, unknown, E, never, never> { return new P.Halt(() => Cause.fail(error())) } /** * Halt a channel with the specified error */ export function fail<E>( error: E ): P.Channel<unknown, unknown, unknown, unknown, E, never, never> { return new P.Halt(() => Cause.fail(error)) } /** * Halt a channel with the specified exception */ export function die( defect: unknown ): P.Channel<unknown, unknown, unknown, unknown, never, never, never> { return new P.Halt(() => Cause.die(defect)) } /** * Halt a channel with the specified exception */ export function dieWith( defect: () => unknown ): P.Channel<unknown, unknown, unknown, unknown, never, never, never> { return new P.Halt(() => Cause.die(defect())) } /** * Writes an output to the channel */ export function writeWith<OutElem>( out: () => OutElem ): P.Channel<unknown, unknown, unknown, unknown, never, OutElem, void> { return new P.Emit(out) } /** * Writes an output to the channel */ export function write<OutElem>( out: OutElem ): P.Channel<unknown, unknown, unknown, unknown, never, OutElem, void> { return new P.Emit(() => out) } /** * Returns a new channel with an attached finalizer. The finalizer is guaranteed to be executed * so long as the channel begins execution (and regardless of whether or not it completes). */ export function ensuringWith_< Env, Env2, InErr, InElem, InDone, OutErr, OutElem, OutDone >( channel: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, finalizer: (e: Exit.Exit<OutErr, OutDone>) => T.Effect<Env2, never, unknown> ): P.Channel<Env & Env2, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return new P.Ensuring<Env & Env2, InErr, InElem, InDone, OutErr, OutElem, OutDone>( channel, finalizer ) } /** * Returns a new channel with an attached finalizer. The finalizer is guaranteed to be executed * so long as the channel begins execution (and regardless of whether or not it completes). * * @ets_data_first ensuringWith_ */ export function ensuringWith<Env2, OutErr, OutDone>( finalizer: (e: Exit.Exit<OutErr, OutDone>) => T.Effect<Env2, never, unknown> ): <Env, InErr, InElem, InDone, OutElem>( channel: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ) => P.Channel<Env & Env2, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return (channel) => ensuringWith_(channel, finalizer) } /** * Returns a new channel whose outputs are fed to the specified factory function, which creates * new channels in response. These new channels are sequentially concatenated together, and all * their outputs appear as outputs of the newly returned channel. The provided merging function * is used to merge the terminal values of all channels into the single terminal value of the * returned channel. */ export function concatMapWith_< Env, InErr, InElem, InDone, OutErr, OutElem, OutElem2, OutDone, OutDone2, OutDone3, Env2, InErr2, InElem2, InDone2, OutErr2 >( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone2>, f: ( o: OutElem ) => P.Channel<Env2, InErr2, InElem2, InDone2, OutErr2, OutElem2, OutDone>, g: (o: OutDone, o1: OutDone) => OutDone, h: (o: OutDone, o2: OutDone2) => OutDone3 ): P.Channel< Env & Env2, InErr & InErr2, InElem & InElem2, InDone & InDone2, OutErr | OutErr2, OutElem2, OutDone3 > { return new P.ConcatAll< Env & Env2, InErr & InErr2, InElem & InElem2, InDone & InDone2, OutErr | OutErr2, OutElem2, OutDone3, OutElem, OutDone, OutDone2 >(g, h, self, f) } /** * Returns a new channel whose outputs are fed to the specified factory function, which creates * new channels in response. These new channels are sequentially concatenated together, and all * their outputs appear as outputs of the newly returned channel. The provided merging function * is used to merge the terminal values of all channels into the single terminal value of the * returned channel. * * @ets_data_first concatMapWith_ */ export function concatMapWith< OutDone, OutElem, Env2, InErr2, InElem2, InDone2, OutErr2, OutElem2, OutDone2, OutDone3 >( f: ( o: OutElem ) => P.Channel<Env2, InErr2, InElem2, InDone2, OutErr2, OutElem2, OutDone>, g: (o: OutDone, o1: OutDone) => OutDone, h: (o: OutDone, o2: OutDone2) => OutDone3 ): <Env, InErr, InElem, InDone, OutErr>( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone2> ) => P.Channel< Env & Env2, InErr & InErr2, InElem & InElem2, InDone & InDone2, OutErr | OutErr2, OutElem2, OutDone3 > { return (self) => concatMapWith_(self, f, g, h) } /** * Concat sequentially a channel of channels */ export function concatAllWith_< Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, OutDone2, OutDone3, Env2, InErr2, InElem2, InDone2, OutErr2 >( channels: P.Channel< Env, InErr, InElem, InDone, OutErr, P.Channel<Env2, InErr2, InElem2, InDone2, OutErr2, OutElem, OutDone>, OutDone2 >, f: (o: OutDone, o1: OutDone) => OutDone, g: (o: OutDone, o2: OutDone2) => OutDone3 ): P.Channel< Env & Env2, InErr & InErr2, InElem & InElem2, InDone & InDone2, OutErr | OutErr2, OutElem, OutDone3 > { return new P.ConcatAll< Env & Env2, InErr & InErr2, InElem & InElem2, InDone & InDone2, OutErr | OutErr2, OutElem, OutDone3, P.Channel<Env2, InErr2, InElem2, InDone2, OutErr2, OutElem, OutDone>, OutDone, OutDone2 >(f, g, channels, identity) } /** * Concat sequentially a channel of channels * * @ets_data_first concatAllWith_ */ export function concatAllWith<OutDone, OutDone2, OutDone3>( f: (o: OutDone, o1: OutDone) => OutDone, g: (o: OutDone, o2: OutDone2) => OutDone3 ): < Env, InErr, InElem, InDone, OutErr, OutElem, Env2, InErr2, InElem2, InDone2, OutErr2 >( channels: P.Channel< Env, InErr, InElem, InDone, OutErr, P.Channel<Env2, InErr2, InElem2, InDone2, OutErr2, OutElem, OutDone>, OutDone2 > ) => P.Channel< Env & Env2, InErr & InErr2, InElem & InElem2, InDone & InDone2, OutErr | OutErr2, OutElem, OutDone3 > { return (channels) => concatAllWith_(channels, f, g) } /** * Fold the channel exposing success and full error cause */ export function foldCauseChannel_< Env, Env1, Env2, InErr, InErr1, InErr2, InElem, InElem1, InElem2, InDone, InDone1, InDone2, OutErr, OutErr2, OutErr3, OutElem, OutElem1, OutElem2, OutDone, OutDone2, OutDone3 >( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, onErr: ( c: Cause.Cause<OutErr> ) => P.Channel<Env1, InErr1, InElem1, InDone1, OutErr2, OutElem1, OutDone2>, onSucc: ( o: OutDone ) => P.Channel<Env2, InErr2, InElem2, InDone2, OutErr3, OutElem2, OutDone3> ): P.Channel< Env & Env1 & Env2, InErr & InErr1 & InErr2, InElem & InElem1 & InElem2, InDone & InDone1 & InDone2, OutErr2 | OutErr3, OutElem | OutElem1 | OutElem2, OutDone2 | OutDone3 > { return new P.Fold< Env & Env1 & Env2, InErr & InErr1 & InErr2, InElem & InElem1 & InElem2, InDone & InDone1 & InDone2, OutErr2 | OutErr3, OutElem | OutElem1 | OutElem2, OutDone2 | OutDone3, OutErr, OutDone >( self, new P.ContinuationK< Env & Env1 & Env2, InErr & InErr1 & InErr2, InElem & InElem1 & InElem2, InDone & InDone1 & InDone2, OutErr, OutErr2 | OutErr3, OutElem | OutElem1 | OutElem2, OutDone, OutDone2 | OutDone3 >(onSucc, onErr) ) } /** * Fold the channel exposing success and full error cause * * @ets_data_first foldCauseChannel_ */ export function foldCauseChannel< Env1, Env2, InErr1, InErr2, InElem1, InElem2, InDone1, InDone2, OutErr, OutErr2, OutErr3, OutElem1, OutElem2, OutDone, OutDone2, OutDone3 >( onErr: ( c: Cause.Cause<OutErr> ) => P.Channel<Env1, InErr1, InElem1, InDone1, OutErr2, OutElem1, OutDone2>, onSucc: ( o: OutDone ) => P.Channel<Env2, InErr2, InElem2, InDone2, OutErr3, OutElem2, OutDone3> ): <Env, InErr, InElem, InDone, OutElem>( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ) => P.Channel< Env & Env1 & Env2, InErr & InErr1 & InErr2, InElem & InElem1 & InElem2, InDone & InDone1 & InDone2, OutErr2 | OutErr3, OutElem | OutElem1 | OutElem2, OutDone2 | OutDone3 > { return (self) => foldCauseChannel_(self, onErr, onSucc) } /** * Embed inputs from continuos pulling of a producer */ export function embedInput_<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>( self: P.Channel<Env, unknown, unknown, unknown, OutErr, OutElem, OutDone>, input: PR.AsyncInputProducer<InErr, InElem, InDone> ): P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return new P.Bridge(input, self) } /** * Embed inputs from continuos pulling of a producer * * @ets_data_first embedInput_ */ export function embedInput<InErr, InElem, InDone>( input: PR.AsyncInputProducer<InErr, InElem, InDone> ): <Env, OutErr, OutElem, OutDone>( self: P.Channel<Env, unknown, unknown, unknown, OutErr, OutElem, OutDone> ) => P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return (self) => embedInput_(self, input) } /** * Construct a resource Channel with Acquire / Release */ export function acquireReleaseOutExitWith_<R, R2, E, Z>( self: T.Effect<R, E, Z>, release: (z: Z, e: Exit.Exit<unknown, unknown>) => T.RIO<R2, unknown> ): P.Channel<R & R2, unknown, unknown, unknown, E, Z, void> { return new P.BracketOut<R & R2, E, Z, void>(self, release) } /** * Construct a resource Channel with Acquire / Release * * @ets_data_first acquireReleaseOutExitWith_ */ export function acquireReleaseOutExitWith<R2, Z>( release: (z: Z, e: Exit.Exit<unknown, unknown>) => T.RIO<R2, unknown> ): <R, E>( self: T.Effect<R, E, Z> ) => P.Channel<R & R2, unknown, unknown, unknown, E, Z, void> { return (self) => acquireReleaseOutExitWith_(self, release) } /** * Provides the channel with its required environment, which eliminates * its dependency on `Env`. */ export function provideAll_<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, env: Env ): P.Channel<unknown, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return new P.Provide(env, self) } /** * Provides the channel with its required environment, which eliminates * its dependency on `Env`. * * @ets_data_first provideAll_ */ export function provideAll<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>( env: Env ): ( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ) => P.Channel<unknown, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return (self) => provideAll_(self, env) } /** * Returns a new channel, which sequentially combines this channel, together with the provided * factory function, which creates a second channel based on the terminal value of this channel. * The result is a channel that will first perform the functions of this channel, before * performing the functions of the created channel (including yielding its terminal value). */ export function chain_< Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone2 >( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, f: ( d: OutDone ) => P.Channel<Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone2> ): P.Channel< Env & Env1, InErr & InErr1, InElem & InElem1, InDone & InDone1, OutErr | OutErr1, OutElem | OutElem1, OutDone2 > { return new P.Fold< Env & Env1, InErr & InErr1, InElem & InElem1, InDone & InDone1, OutErr | OutErr1, OutElem | OutElem1, OutDone2, OutErr | OutErr1, OutDone >(self, new P.ContinuationK(f, failCause)) } /** * Returns a new channel, which sequentially combines this channel, together with the provided * factory function, which creates a second channel based on the terminal value of this channel. * The result is a channel that will first perform the functions of this channel, before * performing the functions of the created channel (including yielding its terminal value). * * @ets_data_first chain_ */ export function chain< OutDone, Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone2 >( f: ( d: OutDone ) => P.Channel<Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone2> ): <Env, InErr, InElem, InDone, OutErr, OutElem>( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ) => P.Channel< Env & Env1, InErr & InErr1, InElem & InElem1, InDone & InDone1, OutErr | OutErr1, OutElem | OutElem1, OutDone2 > { return (self) => chain_(self, f) } export function suspend<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>( effect: () => P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ): P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> { return new P.EffectSuspendTotal(effect) } /** * Use an effect to end a channel */ export function fromEffect<R, E, A>( self: T.Effect<R, E, A> ): P.Channel<R, unknown, unknown, unknown, E, never, A> { return new P.Effect(self) } export function succeedWith<OutDone>( effect: () => OutDone ): P.Channel<unknown, unknown, unknown, unknown, never, never, OutDone> { return new P.EffectTotal(effect) } export function readOrFail<In, E>( e: E ): P.Channel<unknown, unknown, In, unknown, E, never, In> { return new P.Read<unknown, unknown, In, unknown, E, never, In, never, In>( (in_) => end(in_), new P.ContinuationK( (_) => fail(e), (_) => fail(e) ) ) } /** * Returns a new channel that is the same as this one, except if this channel errors for any * typed error, then the returned channel will switch over to using the fallback channel returned * by the specified error handler. */ export function catchAllCause_< Env, Env1, InErr, InErr1, InElem, InElem1, InDone, InDone1, OutErr, OutErr1, OutElem, OutElem1, OutDone, OutDone1 >( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>, f: ( cause: Cause.Cause<OutErr> ) => P.Channel<Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone1> ): P.Channel< Env & Env1, InErr & InErr1, InElem & InElem1, InDone & InDone1, OutErr1, OutElem | OutElem1, OutDone | OutDone1 > { return new P.Fold< Env & Env1, InErr & InErr1, InElem & InElem1, InDone & InDone1, OutErr1, OutElem | OutElem1, OutDone | OutDone1, OutErr, OutDone | OutDone1 >(self, new P.ContinuationK((_) => end(_), f)) } /** * Returns a new channel that is the same as this one, except if this channel errors for any * typed error, then the returned channel will switch over to using the fallback channel returned * by the specified error handler. * * @ets_data_first catchAllCause_ */ export function catchAllCause< Env1, InErr1, InElem1, InDone1, OutErr, OutErr1, OutElem1, OutDone1 >( f: ( cause: Cause.Cause<OutErr> ) => P.Channel<Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone1> ) { return <Env, InErr, InElem, InDone, OutElem, OutDone>( self: P.Channel<Env, InErr, InElem, InDone, OutErr, OutElem, OutDone> ) => catchAllCause_(self, f) }
the_stack
import { assign } from 'lodash-es'; import { CustomChannelDef, DataTransform, DataTransformWithBase, GoslingSpec, OverlaidTracks, TemplateTrackDef, TemplateTrackMappingDef, Track } from '../gosling.schema'; import { IsTemplateTrack } from '../gosling.schema.guards'; import { traverseTracks } from './spec-preprocess'; /** * Track templates officially supported by Gosling.js. */ export const GoslingTemplates: TemplateTrackDef[] = [ { name: 'gene', channels: [ { name: 'startPosition', type: 'genomic', required: true }, { name: 'endPosition', type: 'genomic', required: true }, { name: 'strandColor', type: 'nominal', required: true }, { name: 'strandRow', type: 'nominal', required: true }, { name: 'opacity', type: 'value', required: false }, { name: 'geneHeight', type: 'value', required: false }, { name: 'geneLabel', type: 'nominal', required: true }, { name: 'geneLabelColor', type: 'nominal', required: true }, { name: 'geneLabelFontSize', type: 'value', required: false }, { name: 'geneLabelStroke', type: 'value', required: false }, { name: 'geneLabelStrokeThickness', type: 'value', required: false }, { name: 'geneLabelOpacity', type: 'value', required: false }, { name: 'type', type: 'nominal', required: true } // either 'gene' or 'exon' ], mapping: [ { dataTransform: [ { type: 'filter', base: 'type', oneOf: ['gene'] }, { type: 'filter', base: 'strandColor', oneOf: ['-'] } ], mark: 'triangleLeft', x: { base: 'startPosition', type: 'genomic' }, size: { base: 'geneHeight', value: 12 }, row: { base: 'strandRow', type: 'nominal', domain: ['+', '-'] }, color: { base: 'strandColor', type: 'nominal', domain: ['+', '-'], range: ['blue', 'red'] }, opacity: { base: 'opacity', value: 0.4 }, style: { align: 'right' } }, { dataTransform: [ { type: 'filter', base: 'type', oneOf: ['gene'] }, { type: 'filter', base: 'strandColor', oneOf: ['+'] } ], mark: 'triangleRight', x: { base: 'endPosition', type: 'genomic' }, size: { base: 'geneHeight', value: 12 }, row: { base: 'strandRow', type: 'nominal', domain: ['+', '-'] }, color: { base: 'strandColor', type: 'nominal', domain: ['+', '-'], range: ['blue', 'red'] }, opacity: { base: 'opacity', value: 0.4 }, style: { align: 'left' } }, { dataTransform: [{ type: 'filter', base: 'type', oneOf: ['exon'] }], mark: 'rect', x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, size: { base: 'geneHeight', value: 12 }, row: { base: 'strandRow', type: 'nominal', domain: ['+', '-'] }, color: { base: 'strandColor', type: 'nominal', domain: ['+', '-'], range: ['blue', 'red'] }, opacity: { base: 'opacity', value: 0.4 } }, { dataTransform: [ { type: 'filter', base: 'type', oneOf: ['gene'] }, { type: 'filter', base: 'strandColor', oneOf: ['+'] } ], mark: 'rect', x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, row: { base: 'strandRow', type: 'nominal', domain: ['+', '-'] }, color: { base: 'strandColor', type: 'nominal', domain: ['+', '-'], range: ['blue', 'red'] }, opacity: { base: 'opacity', value: 0.4 }, size: { value: 3 } // style: { // linePattern: { type: 'triangleRight', size: 5 } // } }, { dataTransform: [ { type: 'filter', base: 'type', oneOf: ['gene'] }, { type: 'filter', base: 'strandColor', oneOf: ['-'] } ], mark: 'rect', x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, row: { base: 'strandRow', type: 'nominal', domain: ['+', '-'] }, color: { base: 'strandColor', type: 'nominal', domain: ['+', '-'], range: ['blue', 'red'] }, opacity: { base: 'opacity', value: 0.4 }, size: { value: 3 } // style: { // linePattern: { type: 'triangleLeft', size: 5 } // } }, { dataTransform: [{ type: 'filter', base: 'type', oneOf: ['gene'] }], mark: 'text', text: { base: 'geneLabel', type: 'nominal' }, // TODO: add dy here x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, row: { base: 'strandRow', type: 'nominal', domain: ['+', '-'] }, color: { base: 'geneLabelColor', type: 'nominal', domain: ['+', '-'], range: ['blue', 'red'] }, opacity: { base: 'opacity', value: 1 }, size: { base: 'geneLabelFontSize', value: 18 }, stroke: { base: 'geneLabelStroke', value: 'white' }, strokeWidth: { base: 'geneLabelStrokeThickness', value: 2 }, // TODO: how to redefine style from the users' side? (e.g., dy: -30) visibility: [ { operation: 'less-than', measure: 'width', threshold: '|xe-x|', transitionPadding: 10, target: 'mark' } ] } ] }, { name: 'ideogram', channels: [ { name: 'startPosition', type: 'genomic', required: true }, { name: 'endPosition', type: 'genomic', required: true }, { name: 'chrHeight', type: 'value', required: false }, // https://eweitz.github.io/ideogram/ { name: 'name', type: 'nominal', required: true }, { name: 'stainBackgroundColor', type: 'nominal', required: true }, { name: 'stainLabelColor', type: 'nominal', required: true }, { name: 'stainStroke', type: 'value', required: false }, { name: 'stainStrokeWidth', type: 'value', required: false } ], mapping: [ { mark: 'rect', dataTransform: [{ type: 'filter', base: 'stainBackgroundColor', oneOf: ['acen'], not: true }], color: { base: 'stainBackgroundColor', type: 'nominal', domain: ['gneg', 'gpos25', 'gpos50', 'gpos75', 'gpos100', 'gvar', 'acen'], range: ['white', 'lightgray', 'gray', 'gray', 'black', '#7B9CC8', '#DC4542'] }, size: { base: 'chrHeight', value: 18 }, x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, stroke: { base: 'stainStroke', value: 'gray' }, strokeWidth: { base: 'stainStrokeWidth', value: 0.3 } }, { mark: 'triangleRight', dataTransform: [ { type: 'filter', base: 'stainBackgroundColor', oneOf: ['acen'] }, { type: 'filter', base: 'name', include: 'q' } ], color: { base: 'stainBackgroundColor', type: 'nominal', domain: ['gneg', 'gpos25', 'gpos50', 'gpos75', 'gpos100', 'gvar', 'acen'], range: ['white', 'lightgray', 'gray', 'gray', 'black', '#7B9CC8', '#DC4542'] }, size: { base: 'chrHeight', value: 18 }, x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, stroke: { base: 'stainStroke', value: 'gray' }, strokeWidth: { base: 'stainStrokeWidth', value: 0.3 } }, { mark: 'triangleLeft', dataTransform: [ { type: 'filter', base: 'stainBackgroundColor', oneOf: ['acen'] }, { type: 'filter', base: 'name', include: 'p' } ], color: { base: 'stainBackgroundColor', type: 'nominal', domain: ['gneg', 'gpos25', 'gpos50', 'gpos75', 'gpos100', 'gvar', 'acen'], range: ['white', 'lightgray', 'gray', 'gray', 'black', '#7B9CC8', '#DC4542'] }, size: { base: 'chrHeight', value: 18 }, x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, stroke: { base: 'stainStroke', value: 'gray' }, strokeWidth: { base: 'stainStrokeWidth', value: 0.3 } }, { mark: 'text', dataTransform: [{ type: 'filter', base: 'stainLabelColor', oneOf: ['acen'], not: true }], color: { base: 'stainLabelColor', type: 'nominal', domain: ['gneg', 'gpos25', 'gpos50', 'gpos75', 'gpos100', 'gvar'], range: ['black', 'black', 'black', 'black', 'white', 'black'] }, text: { base: 'name', type: 'nominal' }, x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, visibility: [ { operation: 'less-than', measure: 'width', threshold: '|xe-x|', transitionPadding: 10, target: 'mark' } ] } ] }, { name: 'sequence', channels: [ { name: 'startPosition', type: 'genomic', required: true }, { name: 'endPosition', type: 'genomic', required: true }, { name: 'barLength', type: 'quantitative', required: true }, { name: 'baseBackground', type: 'nominal', required: true }, { name: 'baseLabelColor', type: 'nominal', required: true }, { name: 'baseLabelFontSize', type: 'value', required: false } ], mapping: [ { mark: 'bar', // x: { base: 'position', type: 'genomic' }, x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, y: { base: 'barLength', type: 'quantitative', axis: 'none' }, color: { base: 'baseBackground', type: 'nominal', domain: ['A', 'T', 'G', 'C'] } }, { dataTransform: [{ type: 'filter', base: 'barLength', oneOf: [0], not: true }], mark: 'text', x: { base: 'startPosition', type: 'genomic' }, xe: { base: 'endPosition', type: 'genomic' }, color: { base: 'baseLabelColor', type: 'nominal', domain: ['A', 'T', 'G', 'C'], range: ['white'] }, text: { base: 'baseBackground', type: 'nominal' }, size: { base: 'baseLabelFontSize', value: 18 }, visibility: [ { operation: 'less-than', measure: 'width', threshold: '|xe-x|', transitionPadding: 30, target: 'mark' }, { operation: 'LT', measure: 'zoomLevel', threshold: 10, target: 'track' } ] } ] } ]; /** * Replace track templetes to low-level gosling specs. * @param spec */ export function replaceTrackTemplates(spec: GoslingSpec, templates: TemplateTrackDef[]) { traverseTracks(spec, (t, i, ts) => { if (!IsTemplateTrack(t)) { // If this is not a template track, no point to replace templates. return; } const { template: name } = t; const templateDef = templates.find(d => d.name === name); /* Validation */ if (!templateDef) { // No idea what this template is, so set a flag and remove it from the spec when compiling. t._invalidTrack = true; console.warn(`There is no track template named '${name}'`); return; } let isValid = true; templateDef.channels.forEach((d: CustomChannelDef) => { if (d.required && (!t.encoding || !(d.name in t.encoding))) { // Required channels are not defined isValid = false; console.warn(`A template spec ('${name}') does not contain a required channel, ${d.name}`); } }); if (!isValid) { // The template spec is not valid for given template definition t._invalidTrack = true; return; } /* conversion */ const viewBase = JSON.parse(JSON.stringify(t)); if ('encoding' in viewBase) { delete viewBase.encoding; } const convertedView: OverlaidTracks = { ...viewBase, alignment: 'overlay', tracks: [], width: t.width ?? 100, height: t.height ?? 100 }; templateDef.mapping.forEach((singleTrackMappingDef: TemplateTrackMappingDef) => { // Set required properties const convertedTrack: Partial<Track> = { data: t.data, mark: singleTrackMappingDef.mark }; // Handle data transform const { dataTransform } = singleTrackMappingDef; if (dataTransform) { const newDataTransform: DataTransform[] = []; dataTransform.map((dataTramsformMap: DataTransformWithBase) => { const baseChannelName = dataTramsformMap.base; if ( baseChannelName && t.encoding && baseChannelName in t.encoding && 'field' in t.encoding[baseChannelName] ) { delete dataTramsformMap.base; (dataTramsformMap as any).field = (t.encoding[baseChannelName] as any).field; newDataTransform.push(dataTramsformMap as DataTransform); } else { // TODO: JUST ADD? } }); } // Handle encoding const encodingSpec = t.encoding; if (!encodingSpec) { // This means we do not need to override anything, so use default encodings Object.keys(singleTrackMappingDef) .filter(k => k !== 'mark') .forEach(channelKey => { // Iterate all channels const channelMap = JSON.parse(JSON.stringify((singleTrackMappingDef as any)[channelKey])); if ('base' in channelMap) { delete channelMap.base; } // @ts-ignore convertedTrack[channelKey as keyof TemplateTrackMappingDef] = channelMap; }); } else { Object.keys(singleTrackMappingDef) .filter(k => k !== 'mark') .forEach(channelKey => { // Iterate all channels const channelMap = JSON.parse(JSON.stringify((singleTrackMappingDef as any)[channelKey])); if ('base' in channelMap) { const baseChannelName = channelMap.base; if (baseChannelName in encodingSpec) { // This means we need to override a user's spec for this channel const base = JSON.parse(JSON.stringify(encodingSpec[baseChannelName])); delete channelMap.base; const newChannelSpec = assign(channelMap, JSON.parse(JSON.stringify(base))); convertedTrack[channelKey as keyof TemplateTrackMappingDef] = newChannelSpec; } else { // This means a user did not specify a optional custom channel, so just remove a `base` property. delete channelMap.base; convertedTrack[channelKey as keyof TemplateTrackMappingDef] = channelMap; } } else { // This means we use encoding that is constant. convertedTrack[channelKey as keyof TemplateTrackMappingDef] = channelMap; } }); } convertedView.tracks.push(convertedTrack); }); ts[i] = convertedView; }); // DEBUG // console.log('After replaceTrackTemplates()', JSON.parse(JSON.stringify(spec))); }
the_stack
import { AbstractClassType, ClassType, getClassName, getParentClass, indent, isArray } from '@deepkit/core'; import { TypeNumberBrand } from '@deepkit/type-spec'; import { getProperty, ReceiveType, reflect, ReflectionClass, resolveReceiveType, toSignature } from './reflection.js'; import { isExtendable } from './extends.js'; import { isClass } from '@deepkit/core'; export enum ReflectionVisibility { public, protected, private, } export enum ReflectionKind { never, any, unknown, void, object, string, number, boolean, symbol, bigint, null, undefined, regexp, literal, templateLiteral, property, method, function, parameter, promise, /** * Uint8Array, Date, custom classes, Set, Map, etc */ class, typeParameter, enum, union, intersection, array, tuple, tupleMember, enumMember, rest, objectLiteral, indexSignature, propertySignature, methodSignature, infer, } export type TypeDecorator = (annotations: Annotations, decorator: TypeObjectLiteral) => boolean; export type Annotations = any; //actual { [name: symbol]: any[] };, but not support in older TS /** * @reflection never */ export interface TypeAnnotations { /** * If the type was created by a type function, this contains the alias name. */ typeName?: string; /** * If the type was created by a type function, this contains the arguments passed the function. */ typeArguments?: Type[]; /** * Set for index access expressions, e.g. Config['property']. */ indexAccessOrigin?: { container: TypeClass | TypeObjectLiteral, index: Type }; annotations?: Annotations; //parsed decorator types as annotations decorators?: Type[]; //original decorator type scheduleDecorators?: TypeObjectLiteral[]; /** * A place where arbitrary jit functions and its cache data is stored. */ jit?: JitContainer; } export function applyScheduledAnnotations(type: Type) { if (isWithAnnotations(type) && type.scheduleDecorators) { type.annotations = type.annotations ? { ...type.annotations } : {}; type.decorators = type.decorators ? type.decorators.slice() : []; type.decorators.push(...type.scheduleDecorators); for (const scheduledDecorator of type.scheduleDecorators) { for (const decorator of typeDecorators) { decorator(type.annotations, scheduledDecorator); } } type.scheduleDecorators = undefined; } } export function hasTypeInformation(object: ClassType | Function): boolean { return '__type' in object && isArray((object as any).__type); } /** * Object to hold runtime jit data. */ export type JitContainer = any; //actual { [name: string | symbol]: any }; but not supported in older TS export function getTypeJitContainer(type: Type): JitContainer { if (!type.jit) type.jit = {}; return type.jit; } export function clearTypeJitContainer(type: Type): void { type.jit = {}; } export interface TypeNever extends TypeAnnotations { kind: ReflectionKind.never, parent?: Type; } export interface TypeAny extends TypeAnnotations { kind: ReflectionKind.any, parent?: Type; } export interface TypeUnknown extends TypeAnnotations { kind: ReflectionKind.unknown, parent?: Type; } export interface TypeVoid extends TypeAnnotations { kind: ReflectionKind.void, parent?: Type; } export interface TypeObject extends TypeAnnotations { kind: ReflectionKind.object, parent?: Type; } export interface TypeOrigin { origin?: Type; } export interface TypeString extends TypeOrigin, TypeAnnotations { kind: ReflectionKind.string, parent?: Type; } export function isIntegerType(type: Type): type is TypeNumber { return type.kind === ReflectionKind.number && type.brand !== undefined && type.brand >= TypeNumberBrand.integer && type.brand <= TypeNumberBrand.uint32; } export interface TypeNumber extends TypeOrigin, TypeAnnotations { kind: ReflectionKind.number, brand?: TypeNumberBrand; //built in brand parent?: Type; } export interface TypeBoolean extends TypeOrigin, TypeAnnotations { kind: ReflectionKind.boolean, parent?: Type; } export interface TypeBigInt extends TypeOrigin, TypeAnnotations { kind: ReflectionKind.bigint, parent?: Type; } export interface TypeSymbol extends TypeOrigin, TypeAnnotations { kind: ReflectionKind.symbol, parent?: Type; } export interface TypeNull extends TypeAnnotations { kind: ReflectionKind.null, parent?: Type; } export interface TypeUndefined extends TypeAnnotations { kind: ReflectionKind.undefined, parent?: Type; } export interface TypeLiteral extends TypeAnnotations { kind: ReflectionKind.literal, literal: symbol | string | number | boolean | bigint | RegExp; parent?: Type; } export interface TypeTemplateLiteral extends TypeAnnotations { kind: ReflectionKind.templateLiteral, types: (TypeString | TypeAny | TypeNumber | TypeLiteral | TypeInfer)[] parent?: Type; } export interface TypeRegexp extends TypeOrigin, TypeAnnotations { kind: ReflectionKind.regexp; parent?: Type; } export interface TypeBaseMember extends TypeAnnotations { visibility: ReflectionVisibility, abstract?: true; optional?: true, readonly?: true; } export interface TypeParameter extends TypeAnnotations { kind: ReflectionKind.parameter, name: string; type: Type; parent: TypeFunction | TypeMethod | TypeMethodSignature; //parameter could be a property as well if visibility is set visibility?: ReflectionVisibility, readonly?: true; optional?: true, /** * Set when the parameter has a default value aka initializer. */ default?: () => any } export interface TypeMethod extends TypeBaseMember { kind: ReflectionKind.method, parent: TypeClass; visibility: ReflectionVisibility, name: number | string | symbol; parameters: TypeParameter[]; optional?: true, abstract?: true; return: Type; } export interface TypeProperty extends TypeBaseMember { kind: ReflectionKind.property, parent: TypeClass; visibility: ReflectionVisibility, name: number | string | symbol; optional?: true, readonly?: true; abstract?: true; description?: string; type: Type; /** * Set when the property has a default value aka initializer. */ default?: () => any } export interface TypeFunction extends TypeAnnotations { kind: ReflectionKind.function, parent?: Type; name?: number | string | symbol, function?: Function; //reference to the real function if available parameters: TypeParameter[]; return: Type; } export interface TypePromise extends TypeAnnotations { kind: ReflectionKind.promise, parent?: Type; type: Type; } export interface TypeClass extends TypeAnnotations { kind: ReflectionKind.class, parent?: Type; classType: ClassType; /** * When the class extends another class and uses on it generic type arguments, then those arguments * are in this array. * For example `class A extends B<string, boolean> {}` then extendsArguments = [string, boolean]. */ extendsArguments?: Type[]; /** * When class has generic type arguments, e.g. MyClass<string>, it contains * all type arguments. If no type arguments are given, it's undefined. */ arguments?: Type[]; /** * properties/methods. */ types: (TypeIndexSignature | TypeProperty | TypeMethod)[]; } export interface TypeEnum extends TypeAnnotations { kind: ReflectionKind.enum, parent?: Type; enum: { [name: string]: string | number | undefined | null }; values: (string | number | undefined | null)[]; indexType: Type; } export interface TypeEnumMember extends TypeAnnotations { kind: ReflectionKind.enumMember, parent: TypeEnum; name: string; default?: () => string | number; } export interface TypeTypeParameter extends TypeAnnotations { kind: ReflectionKind.typeParameter, parent?: Type; name: string, } export interface TypeUnion extends TypeAnnotations { kind: ReflectionKind.union, parent?: Type; types: Type[]; } export interface TypeIntersection extends TypeAnnotations { kind: ReflectionKind.intersection, parent?: Type; types: Type[]; } export interface TypeArray extends TypeAnnotations { kind: ReflectionKind.array, parent?: Type; type: Type; } export interface TypePropertySignature extends TypeAnnotations { kind: ReflectionKind.propertySignature, parent: TypeObjectLiteral; name: number | string | symbol; optional?: true; readonly?: true; description?: string; type: Type; } export interface TypeMethodSignature extends TypeAnnotations { kind: ReflectionKind.methodSignature, parent: TypeObjectLiteral; name: number | string | symbol; optional?: true; parameters: TypeParameter[]; return: Type; } /** * Object literals or interfaces. */ export interface TypeObjectLiteral extends TypeAnnotations { kind: ReflectionKind.objectLiteral, parent?: Type; types: (TypeIndexSignature | TypePropertySignature | TypeMethodSignature)[]; } export interface TypeIndexSignature extends TypeAnnotations { kind: ReflectionKind.indexSignature, parent: TypeClass | TypeObjectLiteral; index: Type; type: Type; } export interface TypeInfer extends TypeAnnotations { kind: ReflectionKind.infer, parent?: Type; set(type: Type): void; } export interface TypeTupleMember extends TypeAnnotations { kind: ReflectionKind.tupleMember, parent: TypeTuple; type: Type; optional?: true; name?: string; } export interface TypeTuple extends TypeAnnotations { kind: ReflectionKind.tuple, parent?: Type; types: TypeTupleMember[] } export interface TypeRest extends TypeAnnotations { kind: ReflectionKind.rest, parent: TypeTypeParameter | TypeTupleMember; type: Type } /** * @reflection never */ export type Type = TypeNever | TypeAny | TypeUnknown | TypeVoid | TypeObject | TypeString | TypeNumber | TypeBoolean | TypeBigInt | TypeSymbol | TypeNull | TypeUndefined | TypeLiteral | TypeTemplateLiteral | TypeParameter | TypeFunction | TypeMethod | TypeProperty | TypePromise | TypeClass | TypeEnum | TypeEnumMember | TypeUnion | TypeIntersection | TypeArray | TypeObjectLiteral | TypeIndexSignature | TypePropertySignature | TypeMethodSignature | TypeTypeParameter | TypeInfer | TypeTuple | TypeTupleMember | TypeRest | TypeRegexp ; export type Widen<T> = T extends string ? string : T extends number ? number : T extends bigint ? bigint : T extends boolean ? boolean : T extends symbol ? symbol : T; export type FindType<T extends Type, LOOKUP extends ReflectionKind> = T extends { kind: infer K } ? K extends LOOKUP ? T : never : never; /** * Merge dynamic runtime types with static types. In the type-system resolves as any, in runtime as the correct type. * * ```typescript * const stringType = {kind: ReflectionKind.string}; * type t = {a: InlineRuntimeType<typeof stringType>} * * const value = 34; * type t = {a: InlineRuntimeType<typeof value>} * ``` */ export type InlineRuntimeType<T extends ReflectionClass<any> | Type | number | string | boolean | bigint> = T extends ReflectionClass<infer K> ? K : any; export function isType(entry: any): entry is Type { return 'object' === typeof entry && entry.constructor === Object && 'kind' in entry && 'number' === typeof entry.kind; } export function isBinary(type: Type): boolean { return type.kind === ReflectionKind.class && binaryTypes.includes(type.classType); } export function isPrimitive<T extends Type>(type: T): boolean { return type.kind === ReflectionKind.string || type.kind === ReflectionKind.number || type.kind === ReflectionKind.bigint || type.kind === ReflectionKind.boolean || type.kind === ReflectionKind.literal || type.kind === ReflectionKind.null || type.kind === ReflectionKind.undefined; } export function isPropertyType(type: Type): type is TypePropertySignature | TypeProperty { return type.kind === ReflectionKind.property || type.kind === ReflectionKind.propertySignature; } /** * Return all properties created in the constructor (via `constructor(public title: string)`) * * If a non-property parameter is in the constructor, the type is given instead, e.g. `constructor(public title: string, anotherOne:number)` => [TypeProperty, TypeNumber] */ export function getConstructorProperties(type: TypeClass | TypeObjectLiteral): { parameters: (TypeProperty | Type)[], properties: TypeProperty[] } { const result: { parameters: (TypeProperty | Type)[], properties: TypeProperty[] } = { parameters: [], properties: [] }; if (type.kind === ReflectionKind.objectLiteral) return result; const constructor = findMember('constructor', type) as TypeMethod | undefined; if (!constructor) return result; for (const parameter of constructor.parameters) { const property = findMember(parameter.name, type); if (property && property.kind === ReflectionKind.property) { result.properties.push(property); result.parameters.push(property); } else { result.parameters.push(parameter.type as Type); } } return result; } export type WithAnnotations = TypeAny | TypeUnknown | TypeString | TypeNumber | TypeBigInt | TypeBoolean | TypeArray | TypeTuple | TypeLiteral | TypeNull | TypeUndefined | TypeClass | TypeObjectLiteral | TypeObject | TypeTemplateLiteral | TypeRegexp | TypeSymbol; export function isWithAnnotations(type: ParentLessType): type is WithAnnotations { return type.kind === ReflectionKind.any || type.kind === ReflectionKind.unknown || type.kind === ReflectionKind.string || type.kind === ReflectionKind.number || type.kind === ReflectionKind.bigint || type.kind === ReflectionKind.boolean || type.kind === ReflectionKind.union || type.kind === ReflectionKind.array || type.kind === ReflectionKind.tuple || type.kind === ReflectionKind.literal || type.kind === ReflectionKind.null || type.kind === ReflectionKind.undefined || type.kind === ReflectionKind.class || type.kind === ReflectionKind.objectLiteral || type.kind === ReflectionKind.object || type.kind === ReflectionKind.templateLiteral || type.kind === ReflectionKind.regexp || type.kind === ReflectionKind.symbol; } export function getAnnotations(type: WithAnnotations): Annotations { return type.annotations ||= {}; } type StackEntry = { left: Type, right: Type, } function hasStack(stack: StackEntry[], left: Type, right: Type): boolean { for (const entry of stack) { if (entry.left === left && entry.right === right) return true; } return false; } /** * Checks if the structure of a and b are identical. */ export function isSameType(a: Type, b: Type, stack: StackEntry[] = []): boolean { if (a === b) return true; if (hasStack(stack, a, b)) return true; stack.push({ left: a, right: b }); try { if (a.kind !== b.kind) return false; if (a.kind === ReflectionKind.infer || b.kind === ReflectionKind.infer) return false; if (a.kind === ReflectionKind.literal) return a.literal === (b as TypeLiteral).literal; if (a.kind === ReflectionKind.templateLiteral && b.kind === ReflectionKind.templateLiteral) { if (a.types.length !== b.types.length) return false; for (let i = 0; a.types.length; i++) { if (!isSameType(a.types[i], b.types[i], stack)) return false; } return true; } if (a.kind === ReflectionKind.class && b.kind === ReflectionKind.class) { return a.classType === b.classType; // if (a.classType !== b.classType) return false; // if (!a.arguments && !b.arguments) return true; // if (!a.arguments || !b.arguments) return false; // // if (a.arguments && !b.arguments) return false; // if (!a.arguments && b.arguments) return false; // // for (let i = 0; a.arguments.length; i++) { // if (!a.arguments[i] || !b.arguments[i]) return false; // const aMember = a.arguments[i]; // const bMember = b.arguments[i]; // if (aMember === bMember) continue; // // if (aMember.kind === ReflectionKind.property) { // if (bMember.kind === ReflectionKind.property) { // if (aMember.name !== bMember.name) return false; // if (aMember.readonly !== bMember.readonly) return false; // if (aMember.optional !== bMember.optional) return false; // if (aMember.abstract !== bMember.abstract) return false; // if (aMember.visibility !== bMember.visibility) return false; // if (!isSameType(aMember.type, bMember.type, stack)) return false; // } else { // return false; // } // } else { // if (!isSameType(aMember, bMember)) return false; // } // } // return true; } if (a.kind === ReflectionKind.objectLiteral && b.kind === ReflectionKind.objectLiteral) { if (a.types.length !== b.types.length) return false; for (const aMember of a.types) { //todo: call signature if (aMember.kind === ReflectionKind.indexSignature) { const valid = b.types.some(v => { if (v.kind !== ReflectionKind.indexSignature) return false; const sameIndex = isSameType(aMember.index, v.index, stack); const sameType = isSameType(aMember.type, v.type, stack); return sameIndex && sameType; }); if (!valid) return false; } else if (aMember.kind === ReflectionKind.propertySignature || aMember.kind === ReflectionKind.methodSignature) { const bMember = findMember(aMember.name, b); if (!bMember) return false; if (aMember === bMember) continue; if (aMember.kind === ReflectionKind.propertySignature) { if (bMember.kind === ReflectionKind.propertySignature) { if (aMember.name !== bMember.name) return false; if (aMember.readonly !== bMember.readonly) return false; if (aMember.optional !== bMember.optional) return false; if (aMember.type === bMember.type) continue; if (!isSameType(aMember.type, bMember.type, stack)) return false; } else { return false; } } else { if (!isSameType(aMember, bMember, stack)) return false; } } } return true; } if (a.kind === ReflectionKind.tupleMember) { if (b.kind !== ReflectionKind.tupleMember) return false; return a.optional === b.optional && a.name === b.name && isSameType(a.type, b.type, stack); } if (a.kind === ReflectionKind.array) { if (b.kind !== ReflectionKind.array) return false; return isSameType(a.type, b.type, stack); } if (a.kind === ReflectionKind.tuple) { if (b.kind !== ReflectionKind.tuple) return false; if (a.types.length !== b.types.length) return false; for (let i = 0; i < a.types.length; i++) { if (!isSameType(a.types[i], b.types[i], stack)) return false; } return true; } if (a.kind === ReflectionKind.parameter) { if (b.kind !== ReflectionKind.parameter) return false; return a.name === b.name && a.optional === b.optional && isSameType(a.type, b.type, stack); } if (a.kind === ReflectionKind.function || a.kind === ReflectionKind.method || a.kind === ReflectionKind.methodSignature) { if (b.kind !== ReflectionKind.function && b.kind !== ReflectionKind.method && b.kind !== ReflectionKind.methodSignature) return false; if (a.parameters.length !== b.parameters.length) return false; for (let i = 0; i < a.parameters.length; i++) { if (!isSameType(a.parameters[i], b.parameters[i], stack)) return false; } return isSameType(a.return, b.return, stack); } if (a.kind === ReflectionKind.union) { if (b.kind !== ReflectionKind.union) return false; if (a.types.length !== b.types.length) return false; for (let i = 0; i < a.types.length; i++) { const left = a.types[i]; const right = b.types[i]; if (!left || !right) return false; if (left === right) continue; const same = isSameType(left, right, stack); if (!same) return false; } } return a.kind === b.kind; } finally { // stack.pop(); } } export function addType<T extends Type>(container: T, type: Type): T { if (container.kind === ReflectionKind.tuple) { if (type.kind === ReflectionKind.tupleMember) { container.types.push({ ...type, parent: container }); } else { container.types.push({ kind: ReflectionKind.tupleMember, parent: container, type: type as Type }); } } else if (container.kind === ReflectionKind.union) { if (type.kind === ReflectionKind.union) { for (const t of flatten(type).types) { addType(container, t); } } else if (type.kind === ReflectionKind.tupleMember) { if (type.optional && !isTypeIncluded(container.types, { kind: ReflectionKind.undefined })) { container.types.push({ kind: ReflectionKind.undefined, parent: container }); } addType(container, type.type); } else if (type.kind === ReflectionKind.rest) { addType(container, type.type); } else { if (!isTypeIncluded(container.types, type)) { container.types.push({ ...type as any, parent: container }); } } } return container; } export function isTypeIncluded(types: Type[], type: Type, stack: StackEntry[] = []): boolean { for (const t of types) { if (isSameType(t, type, stack)) return true; } return false; } /** * `true | (string | number)` => `true | string | number` */ export function flatten<T extends Type>(type: T): T { if (type.kind === ReflectionKind.union) { type.types = flattenUnionTypes(type.types); } return type; } /** * Flatten nested union types. */ export function flattenUnionTypes(types: Type[]): Type[] { const result: Type[] = []; for (const type of types) { if (type.kind === ReflectionKind.union) { for (const s of flattenUnionTypes(type.types)) { if (!isTypeIncluded(result, s)) result.push(s); } } else { if (!isTypeIncluded(result, type)) result.push(type); } } return result; } /** * empty union => never * union with one member => member * otherwise the union is returned */ export function unboxUnion(union: TypeUnion): Type { if (union.types.length === 0) return { kind: ReflectionKind.never }; if (union.types.length === 1) return union.types[0] as Type; // //convert union of {a: string} | {b: number} | {c: any} to {a?: string, b?: number, c?: any}; // //this does work: {a?: string, b?: string} | {b2?: number} | {c: any} to {a?: string, b?: number, c?: any}; // //this does not work: {a?: string, b?: string} | {b?: number} | {c: any} to {a?: string, b?: number, c?: any}; // if (union.types.length > 1) { // //if a property is known already, don't merge it // const known: string[] = []; // // for (const member of union.types) { // if (member.kind !== ReflectionKind.objectLiteral) return union; // if (member.decorators) return union; //if one member has a decorators, we do not merge // const needsOptional = member.types.length > 1; // for (const t of member.types) { // if (t.kind === ReflectionKind.indexSignature) return union; // const name = memberNameToString(t.name); // if (known.includes(name)) return union; // known.push(name); // if (needsOptional && !isOptional(t)) return union; // } // } // const bl: {[index: string]: boolean} = {}; // // const big: TypeObjectLiteral = { kind: ReflectionKind.objectLiteral, types: [] }; // for (const member of union.types) { // if (member.kind !== ReflectionKind.objectLiteral) continue; // for (const t of member.types) { // if (t.kind === ReflectionKind.indexSignature) return union; // big.types.push(t); // t.parent = big; // t.optional = true; // } // } // big.parent = union.parent; // return big; // } return union; } export function findMember( index: string | number | symbol | TypeTemplateLiteral, type: { types: Type[] } ): TypePropertySignature | TypeMethodSignature | TypeMethod | TypeProperty | TypeIndexSignature | undefined { const indexType = typeof index; for (const member of type.types) { if (member.kind === ReflectionKind.propertySignature && member.name === index) return member; if (member.kind === ReflectionKind.methodSignature && member.name === index) return member; if (member.kind === ReflectionKind.property && member.name === index) return member; if (member.kind === ReflectionKind.method && member.name === index) return member; if (member.kind === ReflectionKind.indexSignature) { if (member.index.kind === ReflectionKind.string && 'string' === indexType) return member; if (member.index.kind === ReflectionKind.number && 'number' === indexType) return member; if (member.index.kind === ReflectionKind.symbol && 'symbol' === indexType) return member; //todo: union needs to match depending on union and indexType } } return; } function resolveObjectIndexType(type: TypeObjectLiteral | TypeClass, index: Type): Type { if (index.kind === ReflectionKind.literal && ('string' === typeof index.literal || 'number' === typeof index.literal || 'symbol' === typeof index.literal)) { const member = findMember(index.literal, type); if (member) { if (member.kind === ReflectionKind.indexSignature) { //todo: check if index type matches literal type return member.type; } else if (member.kind === ReflectionKind.method || member.kind === ReflectionKind.methodSignature) { return member; } else if (member.kind === ReflectionKind.property || member.kind === ReflectionKind.propertySignature) { return member.type; } else { return { kind: ReflectionKind.never }; } } else { return { kind: ReflectionKind.never }; } } else if (index.kind === ReflectionKind.string || index.kind === ReflectionKind.number || index.kind === ReflectionKind.symbol) { //check if index signature match for (const member of type.types) { if (member.kind === ReflectionKind.indexSignature) { if (isExtendable(index, member.index)) return member.type; } } } return { kind: ReflectionKind.never }; } interface CStack { iterator: Type[]; i: number; round: number; } export function emptyObject(type: Type): boolean { return (type.kind === ReflectionKind.objectLiteral || type.kind === ReflectionKind.class) && type.types.length === 0; } export class CartesianProduct { protected stack: CStack[] = []; private current(s: CStack): Type { return s.iterator[s.i]; } private next(s: CStack): boolean { return (++s.i === s.iterator.length) ? (s.i = 0, false) : true; } toGroup(type: Type): Type[] { if (type.kind === ReflectionKind.boolean) { return [{ kind: ReflectionKind.literal, literal: 'false' }, { kind: ReflectionKind.literal, literal: 'true' }]; } else if (type.kind === ReflectionKind.null) { return [{ kind: ReflectionKind.literal, literal: 'null' }]; } else if (type.kind === ReflectionKind.undefined) { return [{ kind: ReflectionKind.literal, literal: 'undefined' }]; // } else if (type.kind === ReflectionKind.templateLiteral) { // // //todo: this is wrong // // return type.types; // const result: Type[] = []; // for (const s of type.types) { // const g = this.toGroup(s); // result.push(...g); // } // // return result; } else if (type.kind === ReflectionKind.union) { const result: Type[] = []; for (const s of type.types) { const g = this.toGroup(s); result.push(...g); } return result; } else { return [type]; } } add(item: Type) { this.stack.push({ iterator: this.toGroup(item), i: 0, round: 0 }); } calculate(): Type[][] { const result: Type[][] = []; outer: while (true) { const row: Type[] = []; for (const s of this.stack) { const item = this.current(s); if (item.kind === ReflectionKind.templateLiteral) { row.push(...item.types); } else { row.push(item); } } result.push(row); for (let i = this.stack.length - 1; i >= 0; i--) { const active = this.next(this.stack[i]); //when that i stack is active, continue in main loop if (active) continue outer; //i stack was rewinded. If its the first, it means we are done if (i === 0) break outer; } break; } return result; } } /** * Query a container type and return the result. * * container[index] * * e.g. {a: string}['a'] => string * e.g. {a: string, b: number}[keyof T] => string | number * e.g. [string, number][0] => string * e.g. [string, number][number] => string | number */ export function indexAccess(container: Type, index: Type): Type { if (container.kind === ReflectionKind.array) { if ((index.kind === ReflectionKind.literal && 'number' === typeof index.literal) || index.kind === ReflectionKind.number) return container.type; if (index.kind === ReflectionKind.literal && index.literal === 'length') return { kind: ReflectionKind.number }; } else if (container.kind === ReflectionKind.tuple) { if (index.kind === ReflectionKind.literal && index.literal === 'length') return { kind: ReflectionKind.literal, literal: container.types.length }; if (index.kind === ReflectionKind.literal && 'number' === typeof index.literal && index.literal < 0) { index = { kind: ReflectionKind.number }; } if (index.kind === ReflectionKind.literal && 'number' === typeof index.literal) { type b0 = [string, boolean?][0]; //string type b1 = [string, boolean?][1]; //boolean|undefined type a0 = [string, ...number[], boolean][0]; //string type a1 = [string, ...number[], boolean][1]; //number|boolean type a2 = [string, ...number[], boolean][2]; //number|boolean type a22 = [string, ...number[], boolean][3]; //number|boolean // type a23 = [string, number, boolean][4]; //number|boolean type a3 = [string, number, ...number[], boolean][1]; //number type a4 = [string, number, ...number[], boolean][-2]; //string|number|boolean, minus means all type a5 = [string, number, ...number[], boolean][number]; //string|number|boolean let restPosition = -1; for (let i = 0; i < container.types.length; i++) { if (container.types[i].type.kind === ReflectionKind.rest) { restPosition = i; break; } } if (restPosition === -1 || index.literal < restPosition) { const sub = container.types[index.literal]; if (!sub) return { kind: ReflectionKind.undefined }; if (sub.optional) return { kind: ReflectionKind.union, types: [sub.type, { kind: ReflectionKind.undefined }] }; return sub.type; } //index beyond a rest, return all beginning from there as big enum const result: TypeUnion = { kind: ReflectionKind.union, types: [] }; for (let i = restPosition; i < container.types.length; i++) { const member = container.types[i]; const type = member.type.kind === ReflectionKind.rest ? member.type.type : member.type; if (!isTypeIncluded(result.types, type)) result.types.push(type); if (member.optional && !isTypeIncluded(result.types, { kind: ReflectionKind.undefined })) result.types.push({ kind: ReflectionKind.undefined }); } return unboxUnion(result); } else if (index.kind === ReflectionKind.number) { const union: TypeUnion = { kind: ReflectionKind.union, types: [] }; for (const sub of container.types) { if (sub.type.kind === ReflectionKind.rest) { if (isTypeIncluded(union.types, sub.type.type)) continue; union.types.push(sub.type.type); } else { if (isTypeIncluded(union.types, sub.type)) continue; union.types.push(sub.type); } } return unboxUnion(union); } else { return { kind: ReflectionKind.never }; } } else if (container.kind === ReflectionKind.objectLiteral || container.kind === ReflectionKind.class) { if (index.kind === ReflectionKind.literal) { return resolveObjectIndexType(container, index); } else if (index.kind === ReflectionKind.union) { const union: TypeUnion = { kind: ReflectionKind.union, types: [] }; for (const t of index.types) { const result = resolveObjectIndexType(container, t); if (result.kind === ReflectionKind.never) continue; if (result.kind === ReflectionKind.union) { for (const resultT of result.types) { if (isTypeIncluded(union.types, resultT)) continue; union.types.push(resultT); } } else { if (isTypeIncluded(union.types, result)) continue; union.types.push(result); } } return unboxUnion(union); } else { return { kind: ReflectionKind.never }; } } else if (container.kind === ReflectionKind.any) { return container; } return { kind: ReflectionKind.never }; } export function merge(types: (TypeObjectLiteral | TypeClass)[]): TypeObjectLiteral { const type: TypeObjectLiteral = { kind: ReflectionKind.objectLiteral, types: [] }; for (const subType of types) { for (const member of subType.types) { if (member.kind === ReflectionKind.indexSignature) { member.parent = type; type.types.push(member); } else if (!isMember(member)) { continue; } else if (!hasMember(type, member.name)) { const t = toSignature(member); t.parent = type; type.types.push(t); } } } return type; } export function narrowOriginalLiteral(type: Type): Type { if ((type.kind === ReflectionKind.string || type.kind === ReflectionKind.number || type.kind === ReflectionKind.boolean || type.kind === ReflectionKind.bigint) && type.origin) { return type.origin; } return type; } type GetArrayElement<T extends any[]> = [T] extends [Array<infer K>] ? K : never; type RemoveParent<T, K extends keyof T> = { [P in K]: T[P] extends Type[] ? RemoveParentHomomorphic<GetArrayElement<T[P]>>[] : T[P] extends Type ? RemoveParentHomomorphic<T[P]> : T[P] }; type RemoveParentHomomorphic<T> = RemoveParent<T, Exclude<keyof T, 'parent'>>; type RemoveDeepParent<T extends Type> = T extends infer K ? RemoveParentHomomorphic<K> : never; export type ParentLessType = RemoveDeepParent<Type>; /** * This function does not do a deep copy, only shallow. A deep copy makes it way to inefficient, so much that router.spec.ts takes up to 20-30seconds * to complete instead of barely 30ms. */ export function copyAndSetParent<T extends ParentLessType>(inc: T, parent?: Type): FindType<Type, T['kind']> { const type = parent ? { ...inc, parent: parent } as Type : { ...inc } as Type; if (isWithAnnotations(type) && isWithAnnotations(inc)) { if (inc.annotations) type.annotations = { ...inc.annotations }; if (inc.decorators) type.decorators = inc.decorators.slice(); if (inc.indexAccessOrigin) type.indexAccessOrigin = { ...inc.indexAccessOrigin }; if (inc.typeArguments) type.typeArguments = inc.typeArguments.slice(); type.jit = {}; } switch (type.kind) { case ReflectionKind.objectLiteral: case ReflectionKind.tuple: case ReflectionKind.union: case ReflectionKind.class: case ReflectionKind.intersection: case ReflectionKind.templateLiteral: type.types = type.types.slice(); break; case ReflectionKind.string: case ReflectionKind.number: case ReflectionKind.bigint: case ReflectionKind.symbol: case ReflectionKind.regexp: case ReflectionKind.boolean: // if (type.origin) type.origin = copyAndSetParent(type.origin, type, stack); break; case ReflectionKind.function: case ReflectionKind.method: case ReflectionKind.methodSignature: // type.return = copyAndSetParent(type.return, type, stack); // type.parameters = type.parameters.map(member => copyAndSetParent(member, type, stack)); break; case ReflectionKind.propertySignature: case ReflectionKind.property: case ReflectionKind.array: case ReflectionKind.promise: case ReflectionKind.parameter: case ReflectionKind.tupleMember: case ReflectionKind.rest: // type.type = copyAndSetParent(type.type, type, stack); break; case ReflectionKind.indexSignature: // type.index = copyAndSetParent(type.index, type, stack); // type.type = copyAndSetParent(type.type, type, stack); break; } return type as any; } export function widenLiteral(type: Type): Type { if (type.kind === ReflectionKind.literal) { if ('number' === typeof type.literal) return copyAndSetParent({ kind: ReflectionKind.number, origin: type }); if ('boolean' === typeof type.literal) return copyAndSetParent({ kind: ReflectionKind.boolean, origin: type }); if ('bigint' === typeof type.literal) return copyAndSetParent({ kind: ReflectionKind.bigint, origin: type }); if ('symbol' === typeof type.literal) return copyAndSetParent({ kind: ReflectionKind.symbol, origin: type }); if ('string' === typeof type.literal) return copyAndSetParent({ kind: ReflectionKind.string, origin: type }); if (type.literal instanceof RegExp) return copyAndSetParent({ kind: ReflectionKind.regexp, origin: type }); } return type; } export function assertType<K extends ReflectionKind, T>(t: Type | undefined, kind: K): asserts t is FindType<Type, K> { if (!t || t.kind !== kind) throw new Error(`Invalid type ${t ? t.kind : undefined}, expected ${kind}`); } export function getClassType(type: Type): ClassType { if (type.kind !== ReflectionKind.class) throw new Error(`Type needs to be TypeClass, but ${type.kind} given.`); return type.classType; } export function isMember(type: Type): type is TypePropertySignature | TypeProperty | TypeMethodSignature | TypeMethod { return type.kind === ReflectionKind.propertySignature || type.kind === ReflectionKind.property || type.kind === ReflectionKind.methodSignature || type.kind === ReflectionKind.method; } export function hasMember(type: TypeObjectLiteral | TypeClass, memberName: number | string | symbol, memberType?: Type): boolean { return type.types.some(v => isMember(v) && v.name === memberName && (!memberType || isExtendable(v.kind === ReflectionKind.propertySignature || v.kind === ReflectionKind.property ? v.type : v, memberType))); } export function getMember(type: TypeObjectLiteral | TypeClass, memberName: number | string | symbol): TypeMethodSignature | TypeMethod | TypePropertySignature | TypeProperty | void { return (type.types as (TypeIndexSignature | TypeMethodSignature | TypeMethod | TypePropertySignature | TypeProperty)[]).find(v => isMember(v) && v.name === memberName) as TypeMethodSignature | TypeMethod | TypePropertySignature | TypeProperty | void; } export function getTypeObjectLiteralFromTypeClass<T extends Type>(type: T): T extends TypeClass ? TypeObjectLiteral : T { if (type.kind === ReflectionKind.class) { const objectLiteral: TypeObjectLiteral = { kind: ReflectionKind.objectLiteral, types: [] }; for (const member of type.types) { if (member.kind === ReflectionKind.indexSignature) { objectLiteral.types.push(member); member.parent = objectLiteral; } else if (member.kind === ReflectionKind.property) { const m = { ...member, kind: ReflectionKind.propertySignature } as any as TypePropertySignature; m.parent = objectLiteral; objectLiteral.types.push(m); } else if (member.kind === ReflectionKind.method) { const m = { ...member, kind: ReflectionKind.methodSignature } as any as TypeMethodSignature; m.parent = objectLiteral; objectLiteral.types.push(m); } } return objectLiteral as any; } return type as any; } /** * Checks whether `undefined` is allowed as type. */ export function isOptional(type: Type): boolean { if (isMember(type) && type.optional === true) return true; if (type.kind === ReflectionKind.parameter) return type.optional || isOptional(type.type); if (type.kind === ReflectionKind.tupleMember) return type.optional || isOptional(type.type); if (type.kind === ReflectionKind.property || type.kind === ReflectionKind.propertySignature || type.kind === ReflectionKind.indexSignature) return isOptional(type.type); return type.kind === ReflectionKind.any || type.kind === ReflectionKind.undefined || (type.kind === ReflectionKind.union && type.types.some(isOptional)); } /** * Whether a property has an initializer/default value. */ export function hasDefaultValue(type: Type): boolean { return type.kind === ReflectionKind.property && type.default !== undefined; } /** * Checks whether `null` is allowed as type. */ export function isNullable(type: Type): boolean { if (type.kind === ReflectionKind.property || type.kind === ReflectionKind.propertySignature || type.kind === ReflectionKind.indexSignature) return isNullable(type.type); return type.kind === ReflectionKind.null || (type.kind === ReflectionKind.union && type.types.some(isNullable)); } /** * Integer */ export type integer = number; /** * Integer 8 bit. * Min value -127, max value 128 */ export type int8 = number; /** * Unsigned integer 8 bit. * Min value 0, max value 255 */ export type uint8 = number; /** * Integer 16 bit. * Min value -32768, max value 32767 */ export type int16 = number; /** * Unsigned integer 16 bit. * Min value 0, max value 65535 */ export type uint16 = number; /** * Integer 8 bit. * Min value -2147483648, max value 2147483647 */ export type int32 = number; /** * Unsigned integer 32 bit. * Min value 0, max value 4294967295 */ export type uint32 = number; /** * Float (same as number, but different semantic for databases). */ export type float = number; /** * Float 32 bit. */ export type float32 = number; /** * Float 64 bit. */ export type float64 = number; export class AnnotationDefinition<T = true> { public symbol: symbol; constructor(public readonly id: string) { this.symbol = Symbol(id); } register(annotations: Annotations, data: T) { annotations[this.symbol] ||= []; annotations[this.symbol].push(data); } reset(annotations: Annotations) { annotations[this.symbol] = undefined; } registerType<TType extends Type>(type: TType, data: T): TType { type.annotations ||= {}; this.register(type.annotations, data); return type; } replace(annotations: Annotations, annotation: T[]) { annotations[this.symbol] = annotation; } replaceType(type: Type, annotation: T[]) { type.annotations ||= {}; type.annotations[this.symbol] = annotation; } getAnnotations(type: Type): T[] { if (type.annotations) return type.annotations[this.symbol] || []; return []; } getFirst(type: Type): T | undefined { return this.getAnnotations(type)[0]; } hasAnnotations(type: Type): boolean { return this.getAnnotations(type).length > 0; } } export type AnnotationType<T extends AnnotationDefinition<any>> = T extends AnnotationDefinition<infer K> ? K : never; export type ReferenceActions = 'RESTRICT' | 'NO ACTION' | 'CASCADE' | 'SET NULL' | 'SET DEFAULT'; export interface ReferenceOptions { /** * Default is CASCADE. */ onDelete?: ReferenceActions, /** * Default is CASCADE. */ onUpdate?: ReferenceActions } /** * note: if this is adjusted, make sure to adjust ReflectionClass, entityAnnotation, and type serializer accordingly. */ export interface EntityOptions { name?: string; description?: string; collection?: string; database?: string; singleTableInheritance?: boolean; indexes?: { names: string[], options: IndexOptions }[]; } /** * Type to decorate an interface/object literal with entity information. * * ```typescript * interface User extends Entity<{name: 'user'}> { * id: number & PrimaryKey & AutoIncrement; * username: string & Unique; * } * ``` */ export type Entity<T extends EntityOptions> = { __meta?: ['entity', T] } /** * Marks a property as primary key. * ```typescript * class Entity { * id: number & Primary = 0; * } * ``` */ export type PrimaryKey = { __meta?: ['primaryKey'] }; type TypeKeyOf<T> = T[keyof T]; export type PrimaryKeyFields<T> = any extends T ? any : { [P in keyof T]: Required<T[P]> extends Required<PrimaryKey> ? T[P] : never }; export type PrimaryKeyType<T> = any extends T ? any : TypeKeyOf<PrimaryKeyFields<T>>; export type ReferenceFields<T> = { [P in keyof T]: Required<T[P]> extends Required<Reference> | Required<BackReference> ? T[P] : never }; /** * Marks a primary property key as auto-increment. * * ```typescript * class Entity { * id: number & Primary & AutoIncrement = 0; * } * ``` */ export type AutoIncrement = { __meta?: ['autoIncrement'] }; /** * UUID v4, as string, serialized as string in JSON, and binary in database. * Use `uuid()` as handy initializer. * * ```typescript * class Entity { * id: UUID = uuid(); * } * ``` */ export type UUID = string & { __meta?: ['UUIDv4'] }; /** * MongoDB's ObjectID type. serialized as string in JSON, ObjectID in database. */ export type MongoId = string & { __meta?: ['mongoId'] }; /** * Same as `bigint` but serializes to unsigned binary with unlimited size (instead of 8 bytes in most databases). * Negative values will be converted to positive (abs(x)). * * ```typescript * class Entity { * id: BinaryBigInt = 0n; * } * ``` */ export type BinaryBigInt = bigint & { __meta?: ['binaryBigInt'] }; /** * Same as `bigint` but serializes to signed binary with unlimited size (instead of 8 bytes in most databases). * The binary has an additional leading sign byte and is represented as an uint: 255 for negative, 0 for zero, or 1 for positive. * * ```typescript * class Entity { * id: SignedBinaryBigInt = 0n; * } * ``` */ export type SignedBinaryBigInt = bigint & { __meta?: ['signedBinaryBigInt'] }; export interface BackReferenceOptions { /** * Necessary for normalised many-to-many relations. This defines the class of the pivot table/collection. */ via?: ClassType | {}; /** * A reference/backReference can define which reference on the other side * reference back. This is necessary when there are multiple outgoing references * to the same entity. */ mappedBy?: string, } export type Reference<Options extends ReferenceOptions = {}> = { __meta?: ['reference', Options] }; export type BackReference<Options extends BackReferenceOptions = {}> = { __meta?: ['backReference', Options] }; export type EmbeddedMeta<Options> = { __meta?: ['embedded', Options] }; export type Embedded<T, Options extends { prefix?: string } = {}> = T & EmbeddedMeta<Options>; export type MapName<Alias extends string, ForSerializer extends string = ''> = { __meta?: ['mapName', Alias, ForSerializer] }; export const referenceAnnotation = new AnnotationDefinition<ReferenceOptions>('reference'); export const entityAnnotation = new AnnotationDefinition<EntityOptions>('entity'); export const mapNameAnnotation = new AnnotationDefinition<{ name: string, serializer?: string }>('entity'); export const autoIncrementAnnotation = new AnnotationDefinition('autoIncrement'); export const primaryKeyAnnotation = new class extends AnnotationDefinition { isPrimaryKey(type: Type): boolean { return this.getAnnotations(type).length > 0; } }('primaryKey'); export interface BackReferenceOptionsResolved { /** * Necessary for normalised many-to-many relations. This defines the class of the pivot table/collection. */ via?: TypeClass | TypeObjectLiteral; /** * A reference/backReference can define which reference on the other side * reference back. This is necessary when there are multiple outgoing references * to the same entity. */ mappedBy?: string, } export const backReferenceAnnotation = new AnnotationDefinition<BackReferenceOptionsResolved>('backReference'); export const validationAnnotation = new AnnotationDefinition<{ name: string, args: Type[] }>('validation'); export const UUIDAnnotation = new AnnotationDefinition('UUID'); export const mongoIdAnnotation = new AnnotationDefinition('mongoID'); export const uuidAnnotation = new AnnotationDefinition('uuid'); export const defaultAnnotation = new AnnotationDefinition('default'); export function isUUIDType(type: Type): boolean { return uuidAnnotation.getFirst(type) !== undefined; } export function isPrimaryKeyType(type: Type): boolean { return primaryKeyAnnotation.isPrimaryKey(type); } export function isAutoIncrementType(type: Type): boolean { return autoIncrementAnnotation.getFirst(type) !== undefined; } export function isMongoIdType(type: Type): boolean { return mongoIdAnnotation.getFirst(type) !== undefined; } export function isBinaryBigIntType(type: Type): boolean { return binaryBigIntAnnotation.getFirst(type) !== undefined; } export function isReferenceType(type: Type): boolean { return referenceAnnotation.getFirst(type) !== undefined; } export function getReferenceType(type: Type): ReferenceOptions | undefined { return referenceAnnotation.getFirst(type); } export function isBackReferenceType(type: Type): boolean { return backReferenceAnnotation.getFirst(type) !== undefined; } export function getBackReferenceType(type: Type): BackReferenceOptionsResolved { const options = backReferenceAnnotation.getFirst(type); if (!options) throw new Error('No back reference'); return options; } export function isDateType(type: Type): boolean { return type.kind === ReflectionKind.class && type.classType === Date; } export function isSetType(type: Type): boolean { return type.kind === ReflectionKind.class && type.classType === Set; } export function isMapType(type: Type): boolean { return type.kind === ReflectionKind.class && type.classType === Map; } /** * Get the key type of a Map or object literal with index signatures. */ export function getKeyType(type: Type): Type { if (type.kind === ReflectionKind.class && type.classType === Map && type.typeArguments) return type.typeArguments[0] || { kind: ReflectionKind.any }; if (type.kind === ReflectionKind.objectLiteral) { const type: TypeUnion = { kind: ReflectionKind.union, types: [] }; for (const t of type.types) { if (t.kind === ReflectionKind.indexSignature) type.types.push(t.index); } if (type.types.length === 1) return type.types[0]; if (type.types.length === 0) return { kind: ReflectionKind.any }; return type; } return { kind: ReflectionKind.any }; } /** * Get the value type of a Map or object literal with index signatures. */ export function getValueType(type: Type): Type { if (type.kind === ReflectionKind.class && type.classType === Map && type.typeArguments) return type.typeArguments[1] || { kind: ReflectionKind.any }; if (type.kind === ReflectionKind.objectLiteral) { const type: TypeUnion = { kind: ReflectionKind.union, types: [] }; for (const t of type.types) { if (t.kind === ReflectionKind.indexSignature) type.types.push(t.type); } if (type.types.length === 1) return type.types[0]; if (type.types.length === 0) return { kind: ReflectionKind.any }; return type; } return { kind: ReflectionKind.any }; } export interface EmbeddedOptions { prefix?: string; } export const embeddedAnnotation = new AnnotationDefinition<EmbeddedOptions>('embedded'); export function hasEmbedded(type: Type): boolean { if (type.kind === ReflectionKind.propertySignature || type.kind === ReflectionKind.property) return hasEmbedded(type.type); if (type.kind === ReflectionKind.union) return type.types.some(hasEmbedded); return embeddedAnnotation.getFirst(type) !== undefined; } //`never` is here to allow using a decorator multiple times on the same type without letting the TS complaining about incompatible types. export type Group<Name extends string> = { __meta?: ['group', never & Name] }; export type Excluded<Name extends string = '*'> = { __meta?: ['excluded', never & Name] }; export type Data<Name extends string, Value> = { __meta?: ['data', never & Name, never & Value] }; /** * Resets an already set decorator to undefined. * * The required Name is the name of the type decorator (its first tuple entry). * * ```typescript * type Password = string & MinLength<6> & Excluded; * * interface UserCreationPayload { * password: Password & ResetDecorator<'excluded'> * } * ``` */ export type ResetDecorator<Name extends string> = { __meta?: ['reset', Name] }; export type IndexOptions = { name?: string; //index size. Necessary for blob/longtext, etc. size?: number, unique?: boolean, spatial?: boolean, sparse?: boolean, //only in mongodb fulltext?: boolean, where?: string, }; export type Unique<Options extends IndexOptions = {}> = { __meta?: ['index', never & Options & { unique: true }] }; export type Index<Options extends IndexOptions = {}> = { __meta?: ['index', never & Options] }; export interface DatabaseFieldOptions { /** * * e.g. `field: string & MySQL<{type: 'VARCHAR(255)'}>` */ type?: string; /** * If the property is on a class, its initializer/default value is per default used. * This can be overridden using this option. * e.g. `field: string & MySQL<{default: 'abc'}>` */ default?: any; /** * e.g. `field: string & MySQL<{defaultExpr: 'NOW()'}>` */ defaultExpr?: any; /** * If true no default column value is inferred from the property initializer/default value. * e.g. `field: string & MySQL<{noDefault: true}> = ''` */ noDefault?: true; } export interface MySQLOptions extends DatabaseFieldOptions { } export interface PostgresOptions extends DatabaseFieldOptions { } export interface SqliteOptions extends DatabaseFieldOptions { } type Database<Name extends string, Options extends { [name: string]: any }> = { __meta?: ['database', never & Name, never & Options] }; export type MySQL<Options extends MySQLOptions> = Database<'mysql', Options>; export type Postgres<Options extends PostgresOptions> = Database<'postgres', Options>; export type SQLite<Options extends SqliteOptions> = Database<'sqlite', Options>; export type DatabaseField<Options extends DatabaseFieldOptions, Name extends string = '*'> = Database<Name, Options>; export const enum BinaryBigIntType { unsigned, signed } export const binaryBigIntAnnotation = new AnnotationDefinition<BinaryBigIntType>('binaryBigInt'); export const groupAnnotation = new AnnotationDefinition<string>('group'); export const excludedAnnotation = new class extends AnnotationDefinition<string> { isExcluded(type: Type, name: string): boolean { const excluded = this.getAnnotations(type); return excluded.includes('*') || excluded.includes(name); } }('excluded'); export const dataAnnotation = new AnnotationDefinition<{ [name: string]: any }>('data'); export const metaAnnotation = new class extends AnnotationDefinition<{ name: string, options: Type[] }> { getForName(type: Type, metaName: string): Type[] | undefined { for (const v of this.getAnnotations(type)) { if (v.name === metaName) return v.options; } return; } }('meta'); export const indexAnnotation = new AnnotationDefinition<IndexOptions>('index'); export const databaseAnnotation = new class extends AnnotationDefinition<{ name: string, options: { [name: string]: any } }> { getDatabase<T extends DatabaseFieldOptions>(type: Type, name: string): T | undefined { let options: T | undefined = undefined; for (const annotation of this.getAnnotations(type)) { if (annotation.name === '*' || annotation.name === name) { if (!options) options = {} as T; Object.assign(options, annotation.options as T); } } return options as any; }; }('database'); export function registerTypeDecorator(decorator: TypeDecorator) { typeDecorators.push(decorator); } export const typeDecorators: TypeDecorator[] = [ (annotations: Annotations, decorator: TypeObjectLiteral) => { const meta = getProperty(decorator, '__meta'); if (!meta || meta.type.kind !== ReflectionKind.tuple) return false; const id = meta.type.types[0]; if (!id || id.type.kind !== ReflectionKind.literal) return false; switch (id.type.literal) { case 'reference': { const optionsType = meta.type.types[1]; if (!optionsType || optionsType.type.kind !== ReflectionKind.objectLiteral) return false; const options = typeToObject(optionsType.type); referenceAnnotation.replace(annotations, [options]); return true; } case 'entity': { const optionsType = meta.type.types[1]; if (!optionsType || optionsType.type.kind !== ReflectionKind.objectLiteral) return false; const options = typeToObject(optionsType.type); entityAnnotation.replace(annotations, [options]); return true; } case 'mapName': { const name = typeToObject(meta.type.types[1].type); const serializer = meta.type.types[2] ? typeToObject(meta.type.types[2].type) : undefined; if ('string' === typeof name && (!serializer || 'string' === typeof serializer)) { mapNameAnnotation.replace(annotations, [{ name, serializer }]); } return true; } case 'autoIncrement': autoIncrementAnnotation.register(annotations, true); return true; case 'binaryBigInt': binaryBigIntAnnotation.replace(annotations, [BinaryBigIntType.unsigned]); return true; case 'signedBinaryBigInt': binaryBigIntAnnotation.replace(annotations, [BinaryBigIntType.signed]); return true; case 'primaryKey': primaryKeyAnnotation.register(annotations, true); return true; case 'mongoId': mongoIdAnnotation.register(annotations, true); return true; case 'UUIDv4': uuidAnnotation.register(annotations, true); return true; case 'embedded': { const optionsType = meta.type.types[1]; if (!optionsType || optionsType.type.kind !== ReflectionKind.objectLiteral) return false; const options = typeToObject(optionsType.type); embeddedAnnotation.replace(annotations, [options]); return true; } case 'group': { const nameType = meta.type.types[1]; if (!nameType || nameType.type.kind !== ReflectionKind.literal || 'string' !== typeof nameType.type.literal) return false; groupAnnotation.register(annotations, nameType.type.literal); return true; } case 'index': { const optionsType = meta.type.types[1]; if (!optionsType || optionsType.type.kind !== ReflectionKind.objectLiteral) return false; const options = typeToObject(optionsType.type); indexAnnotation.replace(annotations, [options]); return true; } case 'database': { const nameType = meta.type.types[1]; if (!nameType || nameType.type.kind !== ReflectionKind.literal || 'string' !== typeof nameType.type.literal) return false; const optionsType = meta.type.types[2]; if (!optionsType || optionsType.type.kind !== ReflectionKind.objectLiteral) return false; const options = typeToObject(optionsType.type); databaseAnnotation.register(annotations, { name: nameType.type.literal, options }); return true; } case 'excluded': { const nameType = meta.type.types[1]; if (!nameType || nameType.type.kind !== ReflectionKind.literal || 'string' !== typeof nameType.type.literal) return false; excludedAnnotation.register(annotations, nameType.type.literal); return true; } case 'reset': { const name = typeToObject(meta.type.types[1].type); if ('string' !== typeof name) return false; const map: { [name: string]: AnnotationDefinition<any> } = { excluded: excludedAnnotation, database: databaseAnnotation, index: indexAnnotation, data: dataAnnotation, group: groupAnnotation, embedded: excludedAnnotation, mapName: mapNameAnnotation, reference: referenceAnnotation, backReference: backReferenceAnnotation, validator: validationAnnotation, }; const annotation = map[name] || metaAnnotation; annotation.reset(annotations); return true; } case 'data': { const nameType = meta.type.types[1]; if (!nameType || nameType.type.kind !== ReflectionKind.literal || 'string' !== typeof nameType.type.literal) return false; const dataType = meta.type.types[2]; if (!dataType) return false; annotations[dataAnnotation.symbol] ||= []; let data: { [name: string]: any } = {}; if (annotations[dataAnnotation.symbol].length) { data = annotations[dataAnnotation.symbol][0]; } else { annotations[dataAnnotation.symbol].push(data); } data[nameType.type.literal] = dataType.type.kind === ReflectionKind.literal ? dataType.type.literal : dataType.type; return true; } case 'backReference': { const optionsType = meta.type.types[1]; if (!optionsType || optionsType.type.kind !== ReflectionKind.objectLiteral) return false; const options = typeToObject(optionsType.type); const member = findMember('via', optionsType.type); backReferenceAnnotation.register(annotations, { mappedBy: options.mappedBy, via: member && member.kind === ReflectionKind.propertySignature && (member.type.kind === ReflectionKind.objectLiteral || member.type.kind === ReflectionKind.class) ? member.type : undefined, }); return true; } case 'validator': { const nameType = meta.type.types[1]; if (!nameType || nameType.type.kind !== ReflectionKind.literal || 'string' !== typeof nameType.type.literal) return false; const name = nameType.type.literal; const argsType = meta.type.types[2]; if (!argsType || argsType.type.kind !== ReflectionKind.tuple) return false; const args: Type[] = argsType.type.types.map(v => v.type); const options: AnnotationType<typeof validationAnnotation> = { name, args }; validationAnnotation.register(annotations, options); return true; } default: { const optionsType = meta.type.types.slice(1).map(v => v.type) as Type[]; metaAnnotation.register(annotations, { name: id.type.literal as string, options: optionsType }); return true; } } } ]; export function typeToObject(type?: Type, state: { stack: Type[] } = { stack: [] }): any { if (!type) return; if (state.stack.includes(type)) return undefined; state.stack.push(type); try { switch (type.kind) { case ReflectionKind.any: case ReflectionKind.void: case ReflectionKind.never: case ReflectionKind.undefined: return undefined; case ReflectionKind.null: return null; case ReflectionKind.string: return ''; case ReflectionKind.number: return 0; case ReflectionKind.bigint: return BigInt(0); case ReflectionKind.regexp: return; //; case ReflectionKind.boolean: return true; case ReflectionKind.literal: return type.literal; case ReflectionKind.promise: return typeToObject(type.type); case ReflectionKind.templateLiteral: return ''; case ReflectionKind.class: { return type.classType; } case ReflectionKind.objectLiteral: { const res: { [name: string | number | symbol]: any } = {}; for (const t of type.types) { if (t.kind === ReflectionKind.propertySignature) { res[String(t.name)] = typeToObject(t.type); } else if (t.kind === ReflectionKind.methodSignature) { } } return res; } case ReflectionKind.union: case ReflectionKind.intersection: return typeToObject(type.types[0]); case ReflectionKind.function: return type.function; case ReflectionKind.array: return [typeToObject(type.type)]; case ReflectionKind.tuple: return type.types.map(v => typeToObject(v.type, state)); } return undefined; } finally { state.stack.pop(); } } export function memberNameToString(name: number | string | symbol): string { if (isType(name)) { return stringifyResolvedType(name); } return String(name); } export const binaryTypes: ClassType[] = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, ArrayBuffer, ]; /** * TypeClass has in its `types` only the properties/methods of the class itself and not its super classes, * while TypeObjectLiteral has all resolved properties in its types already. * * It's thus necessary to resolve super class properties as well. This function does this and caches the result. */ export function resolveTypeMembers(type: TypeClass | TypeObjectLiteral): (TypeProperty | TypePropertySignature | TypeMethodSignature | TypeMethod | TypeIndexSignature)[] { if (type.kind === ReflectionKind.objectLiteral) return type.types; const jit = getTypeJitContainer(type); if (jit.collapsedInheritance) return jit.collapsedInheritance; const types = type.types.slice(); let current = getParentClass(type.classType); while (current) { try { const parentType = reflect(current); if (parentType.kind === ReflectionKind.objectLiteral || parentType.kind === ReflectionKind.class) { for (const property of parentType.types) { if (property.kind === ReflectionKind.indexSignature) { types.unshift(property); } else { if (!findMember(property.name, { types })) { if (property.kind === ReflectionKind.property || property.kind === ReflectionKind.method) { types.unshift(property); } else if (property.kind === ReflectionKind.propertySignature) { types.unshift({ ...property, parent: type, visibility: ReflectionVisibility.public, kind: ReflectionKind.property } as TypeProperty); } else if (property.kind === ReflectionKind.methodSignature) { types.unshift({ ...property, parent: type, visibility: ReflectionVisibility.public, kind: ReflectionKind.method } as TypeMethod); } } } } } } catch { } current = getParentClass(current); } return jit.collapsedInheritance = types; } export function stringifyResolvedType(type: Type): string { return stringifyType(type, { showNames: false, showFullDefinition: true }); } export function stringifyShortResolvedType(type: Type, stateIn: Partial<StringifyTypeOptions> = {}): string { return stringifyType(type, { ...stateIn, showNames: false, showFullDefinition: false, }); } interface StringifyTypeOptions { //show type alias names showNames: boolean; showFullDefinition: boolean; showDescription: boolean; defaultIsOptional: boolean; showHeritage: boolean; showDefaults: boolean; defaultValues: any; stringify?: (type: Type) => string | undefined; } let stringifyTypeId: number = 1; export function stringifyType(type: Type, stateIn: Partial<StringifyTypeOptions> = {}): string { const state: StringifyTypeOptions = { showNames: true, defaultIsOptional: false, showDefaults: false, defaultValues: undefined, showDescription: false, showHeritage: false, showFullDefinition: false, ...stateIn }; const stack: { type?: Type, defaultValue?: any, before?: string, after?: string, depth?: number }[] = []; stack.push({ type, defaultValue: state.defaultValues, depth: 1 }); const stackId: number = stringifyTypeId++; const result: string[] = []; while (stack.length) { const entry = stack.pop(); if (!entry) break; const type = entry.type; const depth = entry.depth || 1; if (type && stateIn.stringify) { const manual = stateIn.stringify(type); if ('string' === typeof manual) { if (manual !== '') { if (entry.before) { result.push(entry.before); } result.push(manual); if (entry.after) { result.push(entry.after); } } continue; } } if (entry.before) { result.push(entry.before); } if (type) { const jit = getTypeJitContainer(type); if (entry.depth !== undefined && jit.visitStack && jit.visitStack.id === stackId && jit.visitStack.depth < entry.depth) { result.push((type.typeName ? type.typeName : '* Recursion *')); continue; } jit.visitStack = { id: stackId, depth }; const manual = stateIn.stringify ? stateIn.stringify(type) : undefined; if ('string' === typeof manual) { result.push(jit.stringifyTypeResult = manual); continue; } if (state.showNames && type.typeName && !state.showFullDefinition) { if (type.typeArguments && type.typeArguments.length) { stack.push({ before: '>' }); for (let i = type.typeArguments.length - 1; i >= 0; i--) { stack.push({ type: type.typeArguments[i], before: i === 0 ? undefined : ', ', depth }); } stack.push({ before: '<' }); } result.push(type.typeName); continue; } switch (type.kind) { case ReflectionKind.never: result.push(`never`); break; case ReflectionKind.any: result.push(`any`); break; case ReflectionKind.unknown: result.push(`unknown`); break; case ReflectionKind.void: result.push(`void`); break; case ReflectionKind.undefined: result.push(`undefined`); break; case ReflectionKind.null: result.push(`null`); break; case ReflectionKind.string: result.push('string'); break; case ReflectionKind.number: result.push('number'); break; case ReflectionKind.bigint: result.push('bigint'); break; case ReflectionKind.regexp: result.push('RegExp'); break; case ReflectionKind.boolean: result.push('boolean'); break; case ReflectionKind.symbol: result.push('symbol'); break; case ReflectionKind.literal: if ('number' === typeof type.literal) { result.push(type.literal + ''); } else if ('boolean' === typeof type.literal) { result.push(type.literal + ''); } else { result.push(`'${String(type.literal).replace(/'/g, '\\\'')}'`); } break; case ReflectionKind.promise: result.push('Promise<'); stack.push({ before: '>' }); stack.push({ type: type.type, depth: depth + 1 }); break; case ReflectionKind.templateLiteral: stack.push({ before: '`' }); for (let i = type.types.length - 1; i >= 0; i--) { const sub = type.types[i]; if (sub.kind === ReflectionKind.literal) { stack.push({ before: String(sub.literal) }); } else { stack.push({ type: sub, before: '${', after: '}', depth: depth + 1 }); } } stack.push({ before: '`' }); break; case ReflectionKind.class: { if (type.classType === Date) { result.push(`Date`); break; } if (type.classType === Set) { result.push('Set<'); stack.push({ before: '>' }); stack.push({ type: type.arguments![0], depth: depth + 1 }); break; } if (type.classType === Map) { result.push('Map<'); stack.push({ before: '>' }); stack.push({ type: type.arguments![1], depth: depth + 1 }); stack.push({ before: ', ' }); stack.push({ type: type.arguments![0], depth: depth + 1 }); break; } if (binaryTypes.includes(type.classType)) { result.push(getClassName(type.classType)); break; } const typeName = type.typeName || getClassName(type.classType); const superClass = getParentClass(type.classType); if (state.showFullDefinition) { const types = state.showHeritage ? type.types : resolveTypeMembers(type); stack.push({ before: '}' }); for (let i = types.length - 1; i >= 0; i--) { const sub = types[i]; const showDescription = stateIn.showDescription && sub.kind === ReflectionKind.property && sub.description; const withIndentation = types.length > 1 || showDescription; if (withIndentation && i === types.length - 1) { stack.push({ before: '\n' + (' '.repeat((depth - 1) * 2)) }); } if (state.stringify) { const manual = state.stringify(sub); if ('string' === typeof manual) { if (manual !== '') { stack.push({ before: manual }); } continue; } } if (showDescription || (types.length > 1 && (withIndentation || i !== types.length - 1))) { stack.push({ before: withIndentation ? ';' : '; ' }); } const defaultValue = entry.defaultValue && (sub.kind === ReflectionKind.property) ? entry.defaultValue[sub.name] : undefined; const showDefault = sub.kind === ReflectionKind.property && sub.type.kind !== ReflectionKind.class && sub.type.kind !== ReflectionKind.objectLiteral; if (state.showDefaults && showDefault) { if (defaultValue !== undefined) { stack.push({ before: ' = ' + JSON.stringify(defaultValue) }); } else if (sub.kind === ReflectionKind.property && sub.default) { try { stack.push({ before: ' = ' + JSON.stringify(sub.default()) }); } catch { } } } stack.push({ type: sub, defaultValue, depth: depth + 1 }); if (withIndentation) { stack.push({ before: '\n' + (' '.repeat(depth * 2)) }); } if (showDescription) { const indentation = indent(depth * 2, ' * '); stack.push({ before: '\n' + indentation('/* ' + sub.description + ' */') }); } } stack.push({ before: ' {' }); } if (superClass && state.showHeritage) { try { const superClassType = reflect(superClass); if (superClassType.kind === ReflectionKind.class) { if (type.extendsArguments && type.extendsArguments.length) { stack.push({ before: '>' }); for (let i = type.extendsArguments.length - 1; i >= 0; i--) { stack.push({ type: type.extendsArguments[i], before: i === 0 ? undefined : ', ', depth: depth + 1 }); } stack.push({ before: '<' }); } stack.push({ before: ' extends ' + (superClassType.typeName || superClass.name) }); } } catch { stack.push({ before: ' extends ' + (superClass.name) }); } } const typeArguments = type.arguments || type.typeArguments; if ((!state.showFullDefinition || type.types.length === 0) && typeArguments && typeArguments.length) { stack.push({ before: '>' }); for (let i = typeArguments.length - 1; i >= 0; i--) { stack.push({ type: typeArguments[i], before: i === 0 ? undefined : ', ', depth: depth + 1 }); } stack.push({ before: '<' }); } stack.push({ before: typeName }); break; } case ReflectionKind.objectLiteral: { const typeName = type.typeName || ''; result.push(typeName); if (!typeName || state.showFullDefinition) { result.push(typeName ? ' {' : '{'); stack.push({ before: '}' }); for (let i = type.types.length - 1; i >= 0; i--) { const sub = type.types[i]; const showDescription = stateIn.showDescription && sub.kind === ReflectionKind.propertySignature && sub.description; const withIndentation = type.types.length > 1 || showDescription; if (state.stringify) { const manual = state.stringify(sub); if ('string' === typeof manual) { if (manual !== '') { stack.push({ before: manual }); } continue; } } if (withIndentation && i === type.types.length - 1) { stack.push({ before: '\n' + (' '.repeat((depth - 1) * 2)) }); } if (state.stringify) { const manual = state.stringify(sub); if ('string' === typeof manual) { if (manual !== '') { stack.push({ before: manual }); } continue; } } if (showDescription || (type.types.length > 1 && (withIndentation || i !== type.types.length - 1))) { stack.push({ before: withIndentation ? ';' : '; ' }); } const defaultValue = entry.defaultValue && (sub.kind === ReflectionKind.propertySignature) ? entry.defaultValue[sub.name] : undefined; const showDefault = sub.kind === ReflectionKind.propertySignature && sub.type.kind !== ReflectionKind.class && sub.type.kind !== ReflectionKind.objectLiteral; if (state.showDefaults && showDefault) { if (defaultValue !== undefined) { stack.push({ before: ' = ' + JSON.stringify(defaultValue) }); } } stack.push({ type: sub, defaultValue, depth: depth + 1 }); if (withIndentation) { stack.push({ before: '\n' + (' '.repeat(depth * 2)) }); } if (showDescription) { const indentation = indent(depth * 2, ' * '); stack.push({ before: '\n' + indentation('/* ' + sub.description + ' */') }); } } } break; } case ReflectionKind.union: for (let i = type.types.length - 1; i >= 0; i--) { stack.push({ type: type.types[i], before: i === 0 ? undefined : ' | ', depth: depth + 1 }); } break; case ReflectionKind.intersection: for (let i = type.types.length - 1; i >= 0; i--) { stack.push({ type: type.types[i], before: i === 0 ? undefined : ' & ', depth: depth + 1 }); } break; case ReflectionKind.parameter: { const visibility = type.visibility ? ReflectionVisibility[type.visibility] + ' ' : ''; const dotdotdot = type.type.kind === ReflectionKind.rest ? '...' : ''; result.push(`${type.readonly ? 'readonly ' : ''}${visibility}${dotdotdot}${type.name}${type.optional ? '?' : ''}: `); stack.push({ type: type.type, depth: depth + 1 }); break; } case ReflectionKind.function: stack.push({ type: type.return, depth: depth + 1 }); stack.push({ before: ') => ' }); for (let i = type.parameters.length - 1; i >= 0; i--) { stack.push({ type: type.parameters[i], before: i === 0 ? undefined : ', ', depth: depth + 1 }); } stack.push({ before: '(' }); break; case ReflectionKind.enum: const members = Object.entries(type.enum).map(([label, value]) => `${label}: ${value}`).join(', '); stack.push({ before: `${type.typeName ? type.typeName : 'Enum'} {` + (members) + '}' }); break; case ReflectionKind.array: stack.push({ before: '>' }); stack.push({ type: type.type, before: 'Array<', depth: depth + 1 }); break; case ReflectionKind.typeParameter: stack.push({ before: type.name }); break; case ReflectionKind.rest: stack.push({ before: '[]' }); stack.push({ type: type.type, depth: depth + 1 }); if (type.parent && type.parent.kind === ReflectionKind.tupleMember && !type.parent.name) { stack.push({ before: '...' }); } break; case ReflectionKind.tupleMember: if (type.name) { const dotdotdot = type.type.kind === ReflectionKind.rest ? '...' : ''; result.push(`${dotdotdot}${type.name}${type.optional ? '?' : ''}: `); stack.push({ type: type.type, depth: depth + 1 }); break; } if (type.optional) { stack.push({ before: '?' }); } stack.push({ type: type.type, depth: depth + 1 }); break; case ReflectionKind.tuple: stack.push({ before: ']' }); for (let i = type.types.length - 1; i >= 0; i--) { stack.push({ type: type.types[i], before: i === 0 ? undefined : ', ', depth: depth + 1 }); } stack.push({ before: '[' }); break; case ReflectionKind.indexSignature: stack.push({ type: type.type, depth: depth + 1 }); stack.push({ before: ']: ' }); stack.push({ type: type.index, depth: depth + 1 }); stack.push({ before: '[index: ' }); // name = `{[index: ${stringifyType(type.index, state)}]: ${stringifyType(type.type, state)}`; break; case ReflectionKind.propertySignature: result.push(`${type.readonly ? 'readonly ' : ''}${memberNameToString(type.name)}${type.optional ? '?' : ''}: `); stack.push({ type: type.type, defaultValue: entry.defaultValue, depth }); break; case ReflectionKind.property: { const visibility = type.visibility ? ReflectionVisibility[type.visibility] + ' ' : ''; const optional = type.optional || (stateIn.defaultIsOptional && type.default !== undefined); result.push(`${type.readonly ? 'readonly ' : ''}${visibility}${memberNameToString(type.name)}${optional ? '?' : ''}: `); stack.push({ type: type.type, defaultValue: entry.defaultValue, depth }); break; } case ReflectionKind.methodSignature: stack.push({ type: type.return, depth }); stack.push({ before: '): ' }); for (let i = type.parameters.length - 1; i >= 0; i--) { stack.push({ type: type.parameters[i], before: i === 0 ? undefined : ', ', depth }); } stack.push({ before: `${memberNameToString(type.name)}${type.optional ? '?' : ''}(` }); break; case ReflectionKind.method: { const visibility = type.visibility ? ReflectionVisibility[type.visibility] + ' ' : ''; const abstract = type.abstract ? 'abstract ' : ''; if (type.name === 'constructor') { stack.push({ before: ')' }); } else { stack.push({ type: type.return, depth }); stack.push({ before: '): ' }); } for (let i = type.parameters.length - 1; i >= 0; i--) { stack.push({ type: type.parameters[i], before: i === 0 ? undefined : ', ', depth }); } stack.push({ before: `${abstract}${visibility}${memberNameToString(type.name)}${type.optional ? '?' : ''}(` }); break; } } } if (entry.after) { result.push(entry.after); } } return result.join(''); } export function annotateClass<T>(clazz: ClassType | AbstractClassType, type?: ReceiveType<T>) { (clazz as any).__type = isClass(type) ? (type as any).__type || [] : []; type = resolveReceiveType(type); (clazz as any).__type.__type = type; type.typeName = getClassName(clazz); }
the_stack
import * as React from 'react'; import JqxCheckBox from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxcheckbox'; import JqxMenu from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxmenu'; class App extends React.PureComponent<{}> { private myMenu = React.createRef<JqxMenu>(); constructor(props: {}) { super(props); this.animationOnChange = this.animationOnChange.bind(this); this.disabledOnChange = this.disabledOnChange.bind(this); this.hoverOnChange = this.hoverOnChange.bind(this); this.openOnChange = this.openOnChange.bind(this); this.topLevelArrowsOnChange = this.topLevelArrowsOnChange.bind(this); } public render() { return ( <div style={{ height: '300px' }}> <JqxMenu theme={'material-purple'} ref={this.myMenu} width={600} height={30}> <ul> <li><a href="#Home">Home</a></li> <li> Solutions <ul style={{ width: '250px' }}> <li><a href="#Education">Education</a></li> <li><a href="#Financial">Financial services</a></li> <li><a href="#Government">Government</a></li> <li><a href="#Manufacturing">Manufacturing</a></li> {/* // @ts-ignore */} <li type="separator" /> <li> Software Solutions <ul style={{ width: '220px' }}> <li><a href="#ConsumerPhoto">Consumer photo and video</a></li> <li><a href="#Mobile">Mobile</a></li> <li><a href="#RIA">Rich Internet applications</a></li> <li><a href="#TechnicalCommunication">Technical communication</a></li> <li><a href="#Training">Training and eLearning</a></li> <li><a href="#WebConferencing">Web conferencing</a></li> </ul> </li> <li><a href="#">All industries and solutions</a></li> </ul> </li> <li> Products <ul> <li><a href="#PCProducts">PC products</a></li> <li><a href="#MobileProducts">Mobile products</a></li> <li><a href="#AllProducts">All products</a></li> </ul> </li> <li> Support <ul style={{ width: '200px' }}> <li><a href="#SupportHome">Support home</a></li> <li><a href="#CustomerService">Customer Service</a></li> <li><a href="#KB">Knowledge base</a></li> <li><a href="#Books">Books</a></li> <li><a href="#Training">Training and certification</a></li> <li><a href="#SupportPrograms">Support programs</a></li> <li><a href="#Forums">Forums</a></li> <li><a href="#Documentation">Documentation</a></li> <li><a href="#Updates">Updates</a></li> </ul> </li> <li> Communities <ul style={{ width: '200px' }}> <li><a href="#Designers">Designers</a></li> <li><a href="#Developers">Developers</a></li> <li><a href="#Educators">Educators and students</a></li> <li><a href="#Partners">Partners</a></li> {/* // @ts-ignore */} <li type="separator" /> <li> By resource <ul> <li><a href="#Labs">Labs</a></li> <li><a href="#TV">TV</a></li> <li><a href="#Forums">Forums</a></li> <li><a href="#Exchange">Exchange</a></li> <li><a href="#Blogs">Blogs</a></li> <li><a href="#Experience Design">Experience Design</a></li> </ul> </li> </ul> </li> <li> Company <ul style={{ width: '180px' }}> <li><a href="#About">About Us</a></li> <li><a href="#Press">Press</a></li> <li><a href="#Investor">Investor Relations</a></li> <li><a href="#CorporateAffairs">Corporate Affairs</a></li> <li><a href="#Careers">Careers</a></li> <li><a href="#Showcase">Showcase</a></li> <li><a href="#Events">Events</a></li> <li><a href="#ContactUs">Contact Us</a></li> <li><a href="#Become an affiliate">Become an affiliate</a></li> </ul> </li> </ul> </JqxMenu> <br /> <div style={{ marginLeft: '60px', marginTop: '120px' }}> <div style={{ fontSize: '16px', fontFamily: 'Verdana Arial' }}> Settings </div> <div style={{ marginTop: '20px', fontSize: '14px', fontFamily: 'Verdana Arial', float: 'left' }}> <JqxCheckBox theme={'material-purple'} onChange={this.animationOnChange} width={150} height={20} checked={true}> Enable Animation </JqxCheckBox> <div style={{ marginTop: '20px' }}> <JqxCheckBox theme={'material-purple'} style={{ marginTop: '20px' }} onChange={this.disabledOnChange} width={150} height={20} checked={false}> Disabled </JqxCheckBox> </div> </div> <div style={{ marginTop: '20px', marginLeft: '60px', fontSize: '14px', fontFamily: 'Verdana Arial', float: 'left' }}> <JqxCheckBox theme={'material-purple'} onChange={this.hoverOnChange} width={150} height={20} checked={true}> Enable Hover </JqxCheckBox> <div style={{ marginTop: '20px' }}> <JqxCheckBox theme={'material-purple'} onChange={this.openOnChange} width={150} height={20} checked={true}> Auto Open </JqxCheckBox> </div> </div> <div style={{ marginTop: '20px', marginLeft: '60px', fontSize: '14px', fontFamily: 'Verdana Arial', float: 'left' }}> <JqxCheckBox theme={'material-purple'} onChange={this.topLevelArrowsOnChange} width={200} height={20}> Show Top-Level Arrows </JqxCheckBox> </div> </div> </div> ); } private animationOnChange(event: any): void { const value = event.args.checked; // enable or disable the menu's animation. if (!value) { this.myMenu.current!.setOptions ({ animationHideDuration: 0, animationShowDelay: 0, animationShowDuration: 0 }); } else { this.myMenu.current!.setOptions ({ animationHideDuration: 200, animationShowDelay: 200, animationShowDuration: 300 }); } } private disabledOnChange(event: any): void { const value = event.args.checked; // enable or disable the menu if (!value) { this.myMenu.current!.setOptions({ disabled: false }); } else { this.myMenu.current!.setOptions({ disabled: true }); } } private hoverOnChange(event: any): void { const value = event.args.checked; // enable or disable the menu's hover effect. if (!value) { this.myMenu.current!.setOptions({ enableHover: false }); } else { this.myMenu.current!.setOptions({ enableHover: true }); } } private openOnChange(event: any): void { const value = event.args.checked; // enable or disable the opening of the top level menu items when the user hovers them. if (!value) { this.myMenu.current!.setOptions({ autoOpen: false }); } else { this.myMenu.current!.setOptions({ autoOpen: true }); } } private topLevelArrowsOnChange(event: any): void { const value = event.args.checked; // enable or disable the top level arrows. if (!value) { this.myMenu.current!.setOptions({ showTopLevelArrows: false }); } else { this.myMenu.current!.setOptions({ showTopLevelArrows: true }); } } } export default App;
the_stack
import { API_URLS } from './config'; import { Got } from 'got'; import { accounts, accountsDelegations, accountsDelegationsAll, accountsRegistrations, accountsRegistrationsAll, accountsRewards, accountsRewardsAll, accountsHistory, accountsHistoryAll, accountsWithdrawals, accountsWithdrawalsAll, accountsMirs, accountsMirsAll, accountsAddresses, accountsAddressesAll, accountsAddressesAssets, accountsAddressesTotal, accountsAddressesAssetsAll, } from './endpoints/api/accounts'; import { addresses, addressesTotal, addressesExtended, addressesTransactions, addressesTransactionsAll, addressesUtxos, addressesUtxosAll, } from './endpoints/api/addresses'; import { assets, assetsById, assetsHistory, assetsHistoryAll, assetsTransactions, assetsAddresses, assetsPolicyById, assetsPolicyByIdAll, } from './endpoints/api/assets'; import { blocks, blocksLatest, blocksLatestTxs, blocksLatestTxsAll, blocksNext, blocksPrevious, blocksTxs, blocksTxsAll, blocksAddresses, blocksAddressesAll, } from './endpoints/api/blocks'; import { epochs, epochsBlocks, epochsBlocksAll, epochsBlocksByPoolId, epochsBlocksByPoolIdAll, epochsLatest, epochsNext, epochsParameters, epochsPrevious, epochsStakes, epochsStakesAll, epochsStakesByPoolId, epochsStakesByPoolIdAll, } from './endpoints/api/epochs'; import { pools, poolsAll, poolMetadata, poolsById, poolsByIdBlocks, poolsByIdDelegators, poolsByIdHistory, poolsByIdRelays, poolsByIdUpdates, poolsRetired, poolsRetiring, poolsExtended, poolsExtendedAll, } from './endpoints/api/pools'; import { genesis } from './endpoints/api/ledger'; import { root } from './endpoints/api/root'; import { metadataTxsLabel, metadataTxsLabelCbor, metadataTxsLabels, } from './endpoints/api/metadata'; import { health, healthClock } from './endpoints/api/health'; import { metrics, metricsEndpoints } from './endpoints/api/metrics'; import { txs, txsDelegations, txsMetadataCbor, txsPoolRetires, txsPoolUpdates, txsStakes, txsUtxos, txsWithdrawals, txsMirs, txsMetadata, txsRedeemers, txSubmit, } from './endpoints/api/txs'; import { scripts, scriptsByHash, scriptsDatum, scriptsRedeemers, scriptsJson, scriptsCbor, } from './endpoints/api/scripts'; import { nutlinkAddress, nutlinkAddressTicker, nutlinkAddressTickers, nutlinkAddressTickersAll, nutlinkAddressTickerAll, nutlinkTickers, nutlinkTickersAll, } from './endpoints/api/nutlink'; import { network } from './endpoints/api/network'; import { Options, ValidatedOptions } from './types'; import { validateOptions } from './utils'; import { getInstance } from './utils/got'; // eslint-disable-next-line @typescript-eslint/no-var-requires const packageJson = require('../package.json'); class BlockFrostAPI { apiUrl: string; projectId?: string; userAgent?: string; options: ValidatedOptions; instance: Got; constructor(options?: Options) { this.options = validateOptions(options); let apiBase = API_URLS.mainnet; if (this.options.isTestnet) { apiBase = API_URLS.testnet; } this.apiUrl = this.options?.customBackend || `${apiBase}/v${this.options.version}`; this.projectId = this.options.projectId; this.userAgent = options?.userAgent ?? `${packageJson.name}@${packageJson.version}`; this.instance = getInstance(this.apiUrl, this.options, this.userAgent); } /** * accounts - Obtain information about a specific stake account. * * @param stakeAddress - Bech32 stake address * @returns Information about a specific stake account. * */ accounts = accounts; /** * accountsDelegations - Obtain information about the delegation of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the delegation of a specific account. * */ accountsDelegations = accountsDelegations; /** * accountsDelegationsAll - Obtain information about all delegations of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the delegation of a specific account. * */ accountsDelegationsAll = accountsDelegationsAll; /** * accountsRegistrations - Obtain information about the registrations and deregistrations of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the registrations and deregistrations of a specific account. * */ accountsRegistrations = accountsRegistrations; /** * accountsRegistrationsAll - Obtain information about all registrations and deregistrations of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the registrations and deregistrations of a specific account. * */ accountsRegistrationsAll = accountsRegistrationsAll; /** * accountsRewards - Obtain information about the history of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the history of a specific account. * */ accountsRewards = accountsRewards; /** * accountsRewardsAll - Obtain information about whole history of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the history of a specific account. * */ accountsRewardsAll = accountsRewardsAll; /** * accountsHistory - Obtain information about the history of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the history of a specific account. * */ accountsHistory = accountsHistory; /** * accountsHistoryAll - Obtain information about whole history of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the history of a specific account. * */ accountsHistoryAll = accountsHistoryAll; /** * accountsWithdrawals - Obtain information about the withdrawals of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the withdrawals of a specific account. * */ accountsWithdrawals = accountsWithdrawals; /** * accountsWithdrawalsAll - Obtain information about all withdrawals of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the withdrawals of a specific account. * */ accountsWithdrawalsAll = accountsWithdrawalsAll; /** * accountsMirs - Obtain information about the MIRs of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the MIRs of a specific account. * */ accountsMirs = accountsMirs; /** * accountsMirsAll - Obtain information about all MIRs of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the MIRs of a specific account. * */ accountsMirsAll = accountsMirsAll; /** * accountsAddresses - Obtain information about the addresses of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the addresses of a specific account. * */ accountsAddresses = accountsAddresses; /** * accountsAddressesAll - Obtain information about all addresses of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Information about the addresses of a specific account. * */ accountsAddressesAll = accountsAddressesAll; /** * accountsAddressesAssets - Obtain information about assets associated with addresses of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Assets associated with the account addresses * */ accountsAddressesAssets = accountsAddressesAssets; /** * accountsAddressesAssets - Obtain information about assets associated with addresses of a specific account. * * @param stakeAddress - Bech32 stake address * @returns Assets associated with the account addresses * */ accountsAddressesAssetsAll = accountsAddressesAssetsAll; /** * accountsAddressesTotal - Obtain summed details aboutof all addresses associated with a given account. * * @param stakeAddress - Bech32 stake address * @returns Assets associated with the account addresses * */ accountsAddressesTotal = accountsAddressesTotal; /** * assets - List of assets. * * @returns List of assets. * */ assets = assets; /** * assetsById - Information about a specific asset. * * @param asset - Concatenation of the policy_id and hex-encoded asset_name * @returns Information about a specific asset. * */ assetsById = assetsById; /** * assetsHistory - History of a specific asset. * * @param asset - Concatenation of the policy_id and hex-encoded asset_name * @returns History of a specific asset. * */ assetsHistory = assetsHistory; /** * assetsHistoryAll - Whole history of a specific asset. * * @param asset - Concatenation of the policy_id and hex-encoded asset_name * @returns History of a specific asset. * */ assetsHistoryAll = assetsHistoryAll; /** * assetsTransactions - List of a specific asset transactions. * * @param asset - Concatenation of the policy_id and hex-encoded asset_name * @returns List of a specific asset transactions. * */ assetsTransactions = assetsTransactions; /** * assetsAddresses - List of a addresses containing a specific asset. * * @param asset - Concatenation of the policy_id and hex-encoded asset_name * @returns List of a addresses containing a specific asset. * */ assetsAddresses = assetsAddresses; /** * assetsPolicyById - List of asset minted under a specific policy. * * @param policyId - Specific policy_id * @returns List of asset minted under a specific policy. * */ assetsPolicyById = assetsPolicyById; /** * assetsPolicyByIdAll - List of all assets minted under a specific policy. * * @param policyId - Specific policy_id * @returns List of asset minted under a specific policy. * */ assetsPolicyByIdAll = assetsPolicyByIdAll; /** * addresses * * @param address * @returns xxx * */ addresses = addresses; /** * addressesTotal * * @param address * @returns xxx * */ addressesTotal = addressesTotal; /** * addressesExtended * * @param address * @returns xxx * */ addressesExtended = addressesExtended; /** * addressesTransactions * * @param address * @returns xxx * */ addressesTransactions = addressesTransactions; /** * addressesTransactionsAll * * @param address * @returns xxx * */ addressesTransactionsAll = addressesTransactionsAll; /** * addressesUtxos * * @param address * @returns xxx * */ addressesUtxos = addressesUtxos; /** * addressesUtxosAll * * @param address * @returns xxx * */ addressesUtxosAll = addressesUtxosAll; /** * addressesUtxos * * @param address * @returns xxx * */ blocks = blocks; /** * blocksLatest * * @returns xxx * */ blocksLatest = blocksLatest; blocksLatestTxs = blocksLatestTxs; blocksLatestTxsAll = blocksLatestTxsAll; /** * blocksNext * * @param address * @returns xxx * */ blocksNext = blocksNext; /** * blockPrevious * * @param address * @returns xxx * */ blocksPrevious = blocksPrevious; /** * addressesUtxos * * @param blocksTxs * @returns xxx * */ blocksTxs = blocksTxs; /** * blocksTxsAll * * @param blocksTxsAll * @returns xxx * */ blocksTxsAll = blocksTxsAll; blocksAddresses = blocksAddresses; blocksAddressesAll = blocksAddressesAll; /** * epochs * * @param number * @returns xxx * */ epochs = epochs; /** * epochsBlocks * * @param number * @returns xxx * */ epochsBlocks = epochsBlocks; /** * epochsBlocksAll * * @param number * @returns xxx * */ epochsBlocksAll = epochsBlocksAll; /** * epochsBlocksByPoolId * * @param number * @param poolId * @returns xxx * */ epochsBlocksByPoolId = epochsBlocksByPoolId; /** * epochsBlocksByPoolIdAll * * @param number * @param poolId * @returns xxx * */ epochsBlocksByPoolIdAll = epochsBlocksByPoolIdAll; /** * epochsLatest * * @returns xxx * */ epochsLatest = epochsLatest; /** * epochsNext * * @param number * @returns xxx * */ epochsNext = epochsNext; /** * epochsParameters * * @param number * @returns xxx * */ epochsParameters = epochsParameters; /** * epochsPrevious * * @param number * @returns xxx * */ epochsPrevious = epochsPrevious; /** * epochsStakes * * @param number * @returns xxx * */ epochsStakes = epochsStakes; /** * epochsStakesAll * * @param number * @returns xxx * */ epochsStakesAll = epochsStakesAll; /** * epochsStakesByPoolId * * @param number * @param poolId * @returns xxx * */ epochsStakesByPoolId = epochsStakesByPoolId; /** * epochsStakesByPoolIdAll * * @param number * @param poolId * @returns xxx * */ epochsStakesByPoolIdAll = epochsStakesByPoolIdAll; /** * health * * @returns xxx * */ health = health; /** * healthClock * * @returns xxx * */ healthClock = healthClock; /** * ledger * * @returns xxx * */ genesis = genesis; /** * metadataTxsLabel * * @param label * @returns xxx * */ metadataTxsLabel = metadataTxsLabel; /** * metadataTxsLabelCbor * * @param label * @returns xxx * */ metadataTxsLabelCbor = metadataTxsLabelCbor; /** * metadataTxsLabels * * @returns xxx * */ metadataTxsLabels = metadataTxsLabels; /** * metrics * * @returns xxx * */ metrics = metrics; /** * metricsEndpoints * * @returns xxx * */ metricsEndpoints = metricsEndpoints; /** * nutlinkAddress * * @returns xxx * */ nutlinkAddress = nutlinkAddress; /** * nutlinkAddressTicker * * @returns xxx * */ nutlinkAddressTicker = nutlinkAddressTicker; /** * nutlinkAddressTickers * * @returns xxx * */ nutlinkAddressTickers = nutlinkAddressTickers; /** * nutlinkAddressTickersAll * * @returns xxx * */ nutlinkAddressTickersAll = nutlinkAddressTickersAll; /** * nutlinkAddressTickerAll * * @returns xxx * */ nutlinkAddressTickerAll = nutlinkAddressTickerAll; /** * nutlinkTickers * * @returns xxx * */ nutlinkTickers = nutlinkTickers; /** * nutlinkTickersAll * * @returns xxx * */ nutlinkTickersAll = nutlinkTickersAll; /** * pools * * @returns xxx * */ pools = pools; /** * poolsAll * * @returns xxx * */ poolsAll = poolsAll; /** * poolMetadata * * @param poolId * @returns xxx * */ poolMetadata = poolMetadata; /** * poolsById * * @param poolId * @returns xxx * */ poolsById = poolsById; /** * poolsByIdBlocks * * @param poolId * @returns xxx * */ poolsByIdBlocks = poolsByIdBlocks; /** * poolsByIdDelegators * * @param poolId * @returns xxx * */ poolsByIdDelegators = poolsByIdDelegators; /** * poolsByIdHistory * * @param poolId * @returns xxx * */ poolsByIdHistory = poolsByIdHistory; /** * poolsByIdRelays * * @param poolId * @returns xxx * */ poolsByIdRelays = poolsByIdRelays; /** * poolsByIdUpdates * * @param poolId * @returns xxx * */ poolsByIdUpdates = poolsByIdUpdates; /** * poolsRetired * * @returns xxx * */ poolsRetired = poolsRetired; /** * poolsRetiring * * @returns xxx * */ poolsRetiring = poolsRetiring; poolsExtended = poolsExtended; poolsExtendedAll = poolsExtendedAll; /** * root * * @returns xxx * */ root = root; /** * List scripts * * @returns List of script hashes * */ scripts = scripts; /** * Information about a specific script * * @returns Information about a specific script * */ scriptsByHash = scriptsByHash; /** * */ scriptsJson = scriptsJson; /** * */ scriptsCbor = scriptsCbor; /** * */ scriptsDatum = scriptsDatum; /** * List of redeemers of a specific script * * @returns List the information about redeemers of a specific script * */ scriptsRedeemers = scriptsRedeemers; /** * txs * * @param hash * @returns xxx * */ txs = txs; /** * txsMetadataCbor * * @param hash * @returns xxx * */ txsMetadataCbor = txsMetadataCbor; /** * txsDelegations * * @param hash * @returns xxx * */ txsDelegations = txsDelegations; /** * txsPoolRetires * * @param hash * @returns xxx * */ txsPoolRetires = txsPoolRetires; /** * txsPoolUpdates * * @param hash * @returns xxx * */ txsPoolUpdates = txsPoolUpdates; /** * txsStakes * * @param hash * @returns xxx * */ txsStakes = txsStakes; /** * txsUtxos * * @param hash * @returns xxx * */ txsUtxos = txsUtxos; /** * txsWithdrawals * * @param hash * @returns xxx * */ txsWithdrawals = txsWithdrawals; /** * txsMirs * * @param hash * @returns xxx * */ txsMirs = txsMirs; /** * txsMetadata * * @param hash * @returns xxx * */ txsMetadata = txsMetadata; // XXX: txsRedeemers = txsRedeemers; /** * txSubmit * * @param hash * @returns xxx * */ txSubmit = txSubmit; /** * network * * @returns Detailed network information. * */ network = network; } export { BlockFrostAPI };
the_stack
import { when } from 'jest-when'; import { Store } from 'redux'; import { resetSettings, updateSetting } from '../../src/redux/Actions'; import { initialState } from '../../src/redux/State'; // tslint:disable-next-line: import-name import createStore from '../../src/redux/Store'; import { ReduxAction, ReduxConstants } from '../../src/typings/ReduxConstants'; import AlarmEvents from '../../src/services/AlarmEvents'; import * as BrowserActionService from '../../src/services/BrowserActionService'; import * as Lib from '../../src/services/Libs'; import TabEvents from '../../src/services/TabEvents'; import StoreUser from '../../src/services/StoreUser'; jest.requireActual('../../src/services/AlarmEvents'); const spyAlarmEvents: JestSpyObject = global.generateSpies(AlarmEvents); const spyBrowserActions: JestSpyObject = global.generateSpies( BrowserActionService, ); jest.requireActual('../../src/services/Libs'); const spyLib: JestSpyObject = global.generateSpies(Lib); jest.requireActual('../../src/services/TabEvents'); const spyTabEvents: JestSpyObject = global.generateSpies(TabEvents); jest.requireActual('../../src/services/StoreUser'); jest.useFakeTimers(); const store: Store<State, ReduxAction> = createStore(initialState); StoreUser.init(store); class TestStore extends StoreUser { public static addCache(payload: any) { StoreUser.store.dispatch({ payload, type: ReduxConstants.ADD_CACHE, }); } public static changeSetting( name: SettingID, value: string | boolean | number, ) { StoreUser.store.dispatch(updateSetting({ name, value })); } public static resetSetting() { StoreUser.store.dispatch(resetSettings()); } } class TestTabEvents extends TabEvents { public static getTabToDomain() { return TabEvents.tabToDomain; } public static getOnTabUpdateDelay() { return TabEvents.onTabUpdateDelay; } } const sampleChangeInfo: browser.tabs.TabChangeInfo = { discarded: false, favIconUrl: 'sample', status: 'loading|complete', title: 'newTitle', url: 'sampleURL', }; const sampleTab: browser.tabs.Tab = { active: true, cookieStoreId: 'firefox-default', discarded: false, hidden: false, highlighted: false, incognito: false, index: 0, isArticle: false, isInReaderMode: false, lastAccessed: 12345678, pinned: false, selected: true, url: 'https://www.example.com', windowId: 1, }; describe('TabEvents', () => { beforeAll(() => { when(global.browser.runtime.getManifest) .calledWith() .mockReturnValue({ version: '0.12.34' } as never); when(global.browser.cookies.getAll) .calledWith(expect.any(Object)) .mockResolvedValue([] as never); // Required so the actual cleaning functions being awaited won't run. when(spyAlarmEvents.createActiveModeAlarm) .calledWith() .mockResolvedValue(undefined as never); }); afterEach(() => { jest.runAllTimers(); jest.clearAllTimers(); TestStore.resetSetting(); }); describe('getAllCookieActions', () => { beforeAll(() => { when(global.browser.cookies.getAll) .calledWith({ domain: '' }) .mockResolvedValue([] as never); when(global.browser.cookies.getAll) .calledWith({ domain: 'domain.com', storeId: 'firefox-default' }) .mockResolvedValue([testCookie] as never); }); const testCookie: browser.cookies.Cookie = { domain: 'domain.com', hostOnly: true, httpOnly: true, name: 'blah', path: '/', sameSite: 'no_restriction', secure: true, session: true, storeId: 'firefox-default', value: 'test value', }; it('should do nothing if url is undefined', async () => { await TabEvents.getAllCookieActions({ ...sampleTab, url: undefined }); expect(spyLib.getAllCookiesForDomain).not.toHaveBeenCalled(); }); it('should do nothing if url is empty string', async () => { await TabEvents.getAllCookieActions({ ...sampleTab, url: '' }); expect(spyLib.getAllCookiesForDomain).not.toHaveBeenCalled(); }); it('should do nothing if url is an internal page', async () => { await TabEvents.getAllCookieActions({ ...sampleTab, url: 'about:home' }); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'chrome:newtab', }); expect(spyLib.getAllCookiesForDomain).not.toHaveBeenCalled(); }); it('should do nothing if url is not valid', async () => { await TabEvents.getAllCookieActions({ ...sampleTab, url: 'bad' }); expect(global.browser.cookies.getAll).not.toHaveBeenCalled(); }); it('should work on regular domains', async () => { await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://domain.com', }); expect(spyBrowserActions.checkIfProtected.mock.calls[0][2]).toBe(1); }); it('should create a cookie if clean cache was enabled and no CAD cookie was found', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([] as never); TestStore.changeSetting(SettingID.CLEANUP_CACHE, true); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(global.browser.cookies.set).toHaveBeenCalledTimes(1); }); it('should create a cookie if clean indexedDB was enabled and no CAD cookie was found', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([] as never); TestStore.changeSetting(SettingID.CLEANUP_INDEXEDDB, true); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(global.browser.cookies.set).toHaveBeenCalledTimes(1); }); it('should create a cookie if clean localStorage was enabled and no CAD cookie was found', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([] as never); TestStore.changeSetting(SettingID.CLEANUP_LOCALSTORAGE, true); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(global.browser.cookies.set).toHaveBeenCalledTimes(1); }); it('should create a cookie if clean plugin data was enabled and no CAD cookie was found', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([] as never); TestStore.changeSetting(SettingID.CLEANUP_PLUGIN_DATA, true); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(global.browser.cookies.set).toHaveBeenCalledTimes(1); }); it('should create a cookie if clean service workers was enabled and no CAD cookie was found', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([] as never); TestStore.changeSetting(SettingID.CLEANUP_SERVICE_WORKERS, true); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(global.browser.cookies.set).toHaveBeenCalledTimes(1); }); it('should filter out CAD browsingDataCleanup cookie from total cookie count', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([ { ...testCookie, name: Lib.CADCOOKIENAME }, ] as never); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(spyBrowserActions.checkIfProtected.mock.calls[0][2]).toBe(0); }); it('should not show cookie count in non-existent icon in Firefox Android', async () => { TestStore.addCache({ key: 'platformOs', value: 'android' }); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://domain.com', }); expect( spyBrowserActions.showNumberOfCookiesInIcon, ).not.toHaveBeenCalled(); }); it('should create a cookie with firstPartyDomain if FPI is enabled', async () => { when(global.browser.cookies.getAll) .calledWith({ domain: 'cookie.net', storeId: 'firefox-default' }) .mockResolvedValue([] as never); when(global.browser.cookies.getAll) .calledWith({ domain: '' }) .mockResolvedValueOnce([] as never) .mockRejectedValue(new Error('firstPartyDomain') as never); TestStore.changeSetting(SettingID.CLEANUP_CACHE, true); TestStore.addCache({ key: 'browserDetect', value: browserName.Firefox }); await TabEvents.getAllCookieActions({ ...sampleTab, url: 'http://cookie.net', }); expect(global.browser.cookies.set).toHaveBeenCalledTimes(1); expect(global.browser.cookies.set.mock.calls[0][0]).toHaveProperty( 'firstPartyDomain', ); }); }); describe('onTabDiscarded', () => { it('should do nothing if clean discarded tabs setting is not enabled', () => { TestStore.changeSetting(SettingID.CLEAN_DISCARDED, false); TabEvents.onTabDiscarded(0, sampleChangeInfo, sampleTab); expect(spyLib.createPartialTabInfo).not.toHaveBeenCalled(); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should do nothing if the tab that was updated is not discarded, even if discardedCleanup was true', () => { TestStore.changeSetting(SettingID.CLEAN_DISCARDED, true); TabEvents.onTabDiscarded(0, sampleChangeInfo, sampleTab); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should trigger cleaning if clean discarded tabs is enabled and changeInfo was discarded', () => { TestStore.changeSetting(SettingID.CLEAN_DISCARDED, true); TabEvents.onTabDiscarded( 0, { ...sampleChangeInfo, discarded: true }, sampleTab, ); expect(spyTabEvents.cleanFromTabEvents).toHaveBeenCalledTimes(1); }); it('should sanitize favIconUrl if debug was enabled', () => { TestStore.changeSetting(SettingID.CLEAN_DISCARDED, true); TestStore.changeSetting(SettingID.DEBUG_MODE, true); TabEvents.onTabDiscarded(0, { ...sampleChangeInfo }, sampleTab); expect(spyLib.cadLog.mock.calls[0][0].x.changeInfo.favIconUrl).toBe( '***', ); }); }); describe('onTabUpdate', () => { beforeAll(() => { when(spyTabEvents.getAllCookieActions) .calledWith() .mockResolvedValue(undefined as any); }); afterAll(() => { spyTabEvents.getAllCookieActions.mockRestore(); }); it('should do nothing if tab status is not "complete"', () => { TabEvents.onTabUpdate(0, sampleChangeInfo, { ...sampleTab, status: 'loading', }); expect(spyTabEvents.getAllCookieActions).not.toHaveBeenCalled(); }); it('should trigger getAllCookieActions', () => { TabEvents.onTabUpdate(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); jest.runAllTimers(); expect(spyTabEvents.getAllCookieActions).toHaveBeenCalledTimes(1); }); it('should sanitize favIconUrl if status=complete and debug is true', () => { TestStore.changeSetting(SettingID.DEBUG_MODE, true); TabEvents.onTabUpdate(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(spyLib.cadLog.mock.calls[0][0].x.changeInfo.favIconUrl).toBe( '***', ); }); it('should not queue getAllCookieActions if one is pending already', () => { TestStore.changeSetting(SettingID.DEBUG_MODE, true); expect(TestTabEvents.getOnTabUpdateDelay()).toBe(false); TabEvents.onTabUpdate(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(TestTabEvents.getOnTabUpdateDelay()).toBe(true); TabEvents.onTabUpdate(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); jest.runAllTimers(); expect(spyTabEvents.getAllCookieActions).toHaveBeenCalledTimes(1); }); }); describe('onDomainChange', () => { // Do not change any of the test order as each test relies on the previous actions. it('should do nothing if tab.status is not complete', () => { TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'loading', }); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should set mainDomain on first encounter', () => { expect(Object.keys(TestTabEvents.getTabToDomain()).length).toBe(0); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should truncate favIconUrl if debug=true', () => { TestStore.changeSetting(SettingID.DEBUG_MODE, true); expect(Object.keys(TestTabEvents.getTabToDomain()).length).toBe(1); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(spyLib.cadLog.mock.calls[0][0].x.changeInfo.favIconUrl).toBe( '***', ); }); it('should not do anything if mainDomain has not changed yet', () => { TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should not trigger clean if cleanOnDomainChange was not enabled', () => { expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', url: 'http://domain.cad', }); expect(TestTabEvents.getTabToDomain()[0]).toBe('domain.cad'); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should trigger clean if mainDomain was changed and domainChangeCleanup is enabled', () => { TestStore.changeSetting(SettingID.CLEAN_DOMAIN_CHANGE, true); // reuse previous tabId to change domain expect(TestTabEvents.getTabToDomain()[0]).toBe('domain.cad'); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); expect(spyTabEvents.cleanFromTabEvents).toHaveBeenCalledTimes(1); }); it('should trigger clean if mainDomain was changed to a home/blank/new tab and domainChangeCleanup is enabled', () => { TestStore.changeSetting(SettingID.CLEAN_DOMAIN_CHANGE, true); // reuse previous tabId to change domain to blank expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', url: 'about:blank', }); expect(TestTabEvents.getTabToDomain()[0]).toBe(''); expect(spyTabEvents.cleanFromTabEvents).toHaveBeenCalledTimes(1); }); it('should not trigger cleaning if previous domain was a new/blank/home tab with domainChangeCleanup enabled', () => { TestStore.changeSetting(SettingID.CLEAN_DOMAIN_CHANGE, true); // reuse previous tabId of blank tab to new domain. expect(TestTabEvents.getTabToDomain()[0]).toBe(''); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', }); expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); it('should not trigger if next domain is an empty string (highly unlikely scenario)', () => { TestStore.changeSetting(SettingID.CLEAN_DOMAIN_CHANGE, true); // reuse previous tabId to go from domain to empty string...which usually doesn't happen expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); TabEvents.onDomainChange(0, sampleChangeInfo, { ...sampleTab, status: 'complete', url: '', }); // Treat as mainDomain unchanged per current logic. expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); expect(spyTabEvents.cleanFromTabEvents).not.toHaveBeenCalled(); }); }); describe('onDomainChangeRemove', () => { // This function doesn't throw any errors when tabId does not exist, so one test covers all. it('should remove old mainDomain from closed tabId', () => { expect(TestTabEvents.getTabToDomain()[0]).toBe('example.com'); TabEvents.onDomainChangeRemove(0, { windowId: 1, isWindowClosing: false, }); expect(TestTabEvents.getTabToDomain()[0]).toBe(undefined); }); }); describe('cleanFromTabEvents', () => { afterAll(() => { global.browser.alarms.get.mockRestore(); }); it('should do nothing if activeMode is disabled', async () => { await TabEvents.cleanFromTabEvents(); expect(spyAlarmEvents.createActiveModeAlarm).not.toHaveBeenCalled(); }); it('should create an "alarm" for cleaning when activeMode is enabled', async () => { when(global.browser.alarms.get) .calledWith('activeModeAlarm') .mockResolvedValue(undefined as never); TestStore.changeSetting(SettingID.ACTIVE_MODE, true); TestStore.changeSetting(SettingID.CLEAN_DELAY, 1); await TabEvents.cleanFromTabEvents(); expect(spyAlarmEvents.createActiveModeAlarm).toHaveBeenCalledTimes(1); }); it('should not create an alarm if one exists already when activeMode is enabled', async () => { when(global.browser.alarms.get) .calledWith('activeModeAlarm') .mockResolvedValue({ name: 'activeModeAlarm' } as never); TestStore.changeSetting(SettingID.ACTIVE_MODE, true); await TabEvents.cleanFromTabEvents(); expect(spyAlarmEvents.createActiveModeAlarm).not.toHaveBeenCalled(); }); }); });
the_stack
import '../time-slider/define'; import '../seekable-progress-bar/define'; import { CSSResultGroup, html, LitElement, PropertyValues, TemplateResult } from 'lit'; import { property } from 'lit/decorators.js'; import { createRef, ref } from 'lit/directives/ref.js'; import { provideContextRecord, watchContext } from '../../base/context'; import { ifNonEmpty } from '../../base/directives'; import { WithFocus } from '../../base/elements'; import { DisposalBin, eventListener, listen, redispatchEvent } from '../../base/events'; import { ElementLogger } from '../../base/logger'; import { DEV_MODE } from '../../global/env'; import { mediaContext } from '../../media'; import { buildExportPartsAttr, setAttribute } from '../../utils/dom'; import { isNil } from '../../utils/unit'; import { ScrubberPreviewConnectEvent, ScrubberPreviewElement, ScrubberPreviewHideEvent, ScrubberPreviewShowEvent, ScrubberPreviewTimeUpdateEvent } from '../scrubber-preview'; import { SeekableProgressBarElement } from '../seekable-progress-bar'; import { SliderDragEndEvent, SliderDragStartEvent, SliderValueChangeEvent } from '../slider/events'; import { TimeSliderElement } from '../time-slider'; import { scrubberContext } from './context'; import { scrubberElementStyles } from './styles'; export const SCRUBBER_ELEMENT_TAG_NAME = 'vds-scrubber'; /** * A control that displays the progression of playback and the amount seekable on a slider. This * control can be used to update the current playback time by interacting with the slider. * * 💡 The following attributes are updated for your styling needs: * * - `media-can-play`: Applied when media can begin playback. * - `media-waiting`: Applied when playback has stopped because of a lack of temporary data. * * 💡 See the `<vds-scrubber-preview>` element if you'd like to include previews. * * @tagname vds-scrubber * @csspart time-slider - The time slider (`<vds-time-slider>`). * @csspart time-slider-* - All `vds-time-slider` parts re-exported with the `time-slider` prefix. * @csspart progress-bar - The progress bar (`<vds-seekable-progress-bar>`). * @csspart progress-bar-* - All `vds-seekable-progress-bar` parts re-exported with the `progress-bar` prefix. * @slot Used to pass content into the slider. * @slot progress-bar - Used to pass content into the progress bar. */ export class ScrubberElement extends WithFocus(LitElement) { static override get styles(): CSSResultGroup { return [scrubberElementStyles]; } static get parts(): string[] { const timeSliderExports = TimeSliderElement.parts.map( (part) => `time-slider-${part}` ); const seekableProgressBarExports = SeekableProgressBarElement.parts.map( (part) => `progress-bar-${part}` ); return [ 'time-slider', 'progress-bar', ...timeSliderExports, ...seekableProgressBarExports ]; } // ------------------------------------------------------------------------------------------- // Properties // ------------------------------------------------------------------------------------------- /* c8 ignore next */ protected readonly _logger = DEV_MODE && new ElementLogger(this); protected readonly ctx = provideContextRecord(this, scrubberContext); /** * Whether the scrubber should be disabled (not-interactable). */ @property({ type: Boolean, reflect: true }) disabled = false; /** * Whether the scrubber should be hidden. */ @property({ type: Boolean, reflect: true }) override hidden = false; /** * ♿ **ARIA:** The `aria-label` for the time slider. */ @property({ reflect: true }) label = 'Media time slider'; /** * The time slider orientation. */ @property({ reflect: true }) orientation = 'horizontal'; /** * ♿ **ARIA:** The `aria-label` for the progress bar. */ @property({ attribute: 'progress-label', reflect: true }) progressLabel = 'Amount of seekable media'; /** * ♿ **ARIA:** Human-readable text alternative for the progress bar value. If you pass * in a string containing `{seekableAmount}` or `{duration}` templates they'll be replaced with * the spoken form such as `1 hour 30 minutes`. */ @property({ attribute: 'progress-value-text' }) progressValueText = '{seekableAmount} out of {duration}'; /** * Whether the scrubber should request playback to pause while the user is dragging the * thumb. If the media was playing before the dragging starts, the state will be restored by * dispatching a user play request once the dragging ends. */ @property({ attribute: 'pause-while-dragging', type: Boolean }) pauseWhileDragging = false; /** * A number that specifies the granularity that the time slider value must adhere to in seconds. * For example, a step with the value `1` indicates a granularity of 1 second increments. */ @property({ type: Number }) step = 0.25; /** * ♿ **ARIA:** A number that specifies the number of steps taken when interacting with * the time slider via keyboard. Think of it as `step * keyboardStep`. */ @property({ attribute: 'keyboard-step', type: Number }) keyboardStep = 20; /** * ♿ **ARIA:** A number that will be used to multiply the `keyboardStep` when the `Shift` key * is held down and the slider value is changed by pressing `LeftArrow` or `RightArrow`. Think * of it as `keyboardStep * shiftKeyMultiplier`. */ @property({ attribute: 'shift-key-multiplier', type: Number }) shiftKeyMultiplier = 2; /** * The amount of milliseconds to throttle media seeking request events being dispatched. */ @property({ attribute: 'seeking-request-throttle', type: Number }) seekingRequestThrottle = 100; /** * ♿ **ARIA:** Human-readable text alternative for the time slider value. If you pass * in a string containing `{currentTime}` or `{duration}` templates they'll be replaced with * the spoken form such as `1 hour 30 minutes`. */ @property({ attribute: 'value-text' }) valueText = '{currentTime} out of {duration}'; @watchContext(mediaContext.canPlay) protected _handleCanPlayContextUpdate(canPlay: boolean) { setAttribute(this, 'media-can-play', canPlay); } @watchContext(mediaContext.waiting) protected _handleWaitingContextUpdate(waiting: boolean) { setAttribute(this, 'media-waiting', waiting); } // ------------------------------------------------------------------------------------------- // Lifecycle // ------------------------------------------------------------------------------------------- protected override update(changedProperties: PropertyValues) { if (changedProperties.has('disabled')) { if (this.disabled) { this.scrubberPreviewElement?.hidePreview(); } if (!isNil(this.scrubberPreviewElement)) { this.scrubberPreviewElement.disabled = this.disabled; } } if (changedProperties.has('hidden')) { if (!isNil(this.scrubberPreviewElement)) { this.scrubberPreviewElement.hidden = this.hidden; } } super.update(changedProperties); } protected override render(): TemplateResult { return html`${this._renderTimeSlider()}`; } // ------------------------------------------------------------------------------------------- // Pointer Events // ------------------------------------------------------------------------------------------- protected _handlePointerEnter(event: PointerEvent) { if (this.disabled) return; this.ctx.pointing = true; this.setAttribute('pointing', ''); /* c8 ignore start */ if (DEV_MODE) { this._logger .debugGroup('pointer enter') .appendWithLabel('Event', event) .end(); } /* c8 ignore stop */ this.scrubberPreviewElement?.showPreview(event); } protected _handlePointerMove(event: PointerEvent) { if (this.disabled || this.ctx.dragging) return; this.scrubberPreviewElement?.updatePreviewPosition(event); } protected _handlePointerLeave(event: PointerEvent) { if (this.disabled) return; this.ctx.pointing = false; this.removeAttribute('pointing'); /* c8 ignore start */ if (DEV_MODE) { this._logger .debugGroup('pointer leave') .appendWithLabel('Event', event) .end(); } /* c8 ignore stop */ if (!this.ctx.dragging) { this.scrubberPreviewElement?.hidePreview(event); } } // ------------------------------------------------------------------------------------------- // Time Slider // ------------------------------------------------------------------------------------------- protected readonly _timeSliderRef = createRef<TimeSliderElement>(); /** * Returns the underlying `vds-time-slider` component. */ get timeSliderElement() { return this._timeSliderRef.value; } protected _renderTimeSlider(): TemplateResult { return html` <vds-time-slider id="time-slider" exportparts=${buildExportPartsAttr( TimeSliderElement.parts, 'time-slider' )} label=${ifNonEmpty(this.label)} orientation=${this.orientation} part="time-slider" step=${this.step} keyboard-step=${this.keyboardStep} shift-key-multiplier=${this.shiftKeyMultiplier} value-text=${this.valueText} ?disabled=${this.disabled} ?hidden=${this.hidden} ?pause-while-dragging=${this.pauseWhileDragging} @pointerenter=${this._handlePointerEnter} @pointermove=${this._handlePointerMove} @pointerleave=${this._handlePointerLeave} @vds-slider-drag-start=${this._handleSliderDragStart} @vds-slider-value-change=${this._handleSliderValueChange} @vds-slider-drag-end=${this._handleSliderDragEnd} ${ref(this._timeSliderRef)} > ${this._renderTimeSliderChildren()} </vds-time-slider> `; } protected _renderTimeSliderChildren(): TemplateResult { return html`${this._renderDefaultSlot()}${this._renderProgressBar()}`; } protected _renderDefaultSlot(): TemplateResult { return html`<slot></slot>`; } protected _handleSliderDragStart(event: SliderDragStartEvent) { if (this.disabled) return; this.ctx.dragging = true; this.setAttribute('dragging', ''); this.scrubberPreviewElement?.showPreview(event); redispatchEvent(this, event); } protected _handleSliderValueChange(event: SliderValueChangeEvent) { if (this.disabled) return; this.scrubberPreviewElement?.updatePreviewPosition(event); redispatchEvent(this, event); } protected _handleSliderDragEnd(event: SliderDragEndEvent) { if (this.disabled) return; this.ctx.dragging = false; this.removeAttribute('dragging'); if (!this.ctx.pointing) this.scrubberPreviewElement?.hidePreview(event); redispatchEvent(this, event); } // ------------------------------------------------------------------------------------------- // Seekable Progress Bar // ------------------------------------------------------------------------------------------- protected readonly _progressBarRef = createRef<SeekableProgressBarElement>(); /** * Returns the underlying `<vds-seekable-progress-bar>` component. */ get progressBarElement() { return this._progressBarRef.value; } protected _renderProgressBar(): TemplateResult { return html` <vds-seekable-progress-bar id="progress-bar" part="progress-bar" exportparts=${buildExportPartsAttr( SeekableProgressBarElement.parts, 'progress-bar' )} label=${this.progressLabel} value-text=${this.progressValueText} ${ref(this._progressBarRef)} > ${this._renderProgressBarChildren()} </vds-seekable-progress-bar> `; } protected _renderProgressBarChildren(): TemplateResult { return this._renderProgressBarSlot(); } protected _renderProgressBarSlot(): TemplateResult { return html`<slot name="progress-bar"></slot>`; } // ------------------------------------------------------------------------------------------- // Scrubber Preview // ------------------------------------------------------------------------------------------- protected _scrubberPreviewElement: ScrubberPreviewElement | undefined; /** * The scrubber preview element `<vds-scrubber-preview>` (if given). */ get scrubberPreviewElement() { return this._scrubberPreviewElement; } protected readonly _scrubberPreviewDisconnectDisposal = new DisposalBin(); @eventListener('vds-scrubber-preview-connect') protected _handlePreviewConnect(event: ScrubberPreviewConnectEvent) { event.stopPropagation(); const { element, onDisconnect } = event.detail; this._scrubberPreviewElement = element; this.setAttribute('previewable', ''); this._scrubberPreviewDisconnectDisposal.add( listen( element, 'vds-scrubber-preview-show', this._handlePreviewShow.bind(this) ), listen( element, 'vds-scrubber-preview-time-update', this._handlePreviewTimeUpdate.bind(this) ), listen( element, 'vds-scrubber-preview-hide', this._handlePreviewHide.bind(this) ) ); onDisconnect(() => { this._scrubberPreviewDisconnectDisposal.empty(); this._scrubberPreviewElement = undefined; this.removeAttribute('previewable'); }); } protected _handlePreviewShow(event: ScrubberPreviewShowEvent) { event.stopPropagation(); this.setAttribute('previewing', ''); } protected _handlePreviewTimeUpdate(event: ScrubberPreviewTimeUpdateEvent) { event.stopPropagation(); } protected _handlePreviewHide(event: ScrubberPreviewHideEvent) { event.stopPropagation(); this.removeAttribute('previewing'); } }
the_stack
import { defineConfig, notEqual } from '@agile-ts/utils'; import { logCodeManager } from '../logCodeManager'; import { Agile } from '../agile'; import { Persistent } from './persistent'; import { Storage, StorageItemKey, StorageKey } from './storage'; export class Storages { // Agile Instance the Storages belongs to public agileInstance: () => Agile; public config: StoragesConfigInterface; // Registered Storages public storages: { [key: string]: Storage } = {}; // Persistent from Instances (for example States) that were persisted public persistentInstances: { [key: string]: Persistent } = {}; /** * The Storages Class manages all external Storages for an Agile Instance * and provides an interface to easily store, * load and remove values from multiple Storages at once. * * @internal * @param agileInstance - Instance of Agile the Storages belongs to. * @param config - Configuration object */ constructor( agileInstance: Agile, config: CreateStoragesConfigInterface = {} ) { this.agileInstance = () => agileInstance; config = defineConfig(config, { localStorage: false, defaultStorageKey: null as any, }); this.config = { defaultStorageKey: config.defaultStorageKey as any }; if (config.localStorage) this.instantiateLocalStorage(); } /** * Instantiates and registers the * [Local Storage](https://developer.mozilla.org/de/docs/Web/API/Window/localStorage). * * Note that the Local Storage is only available in a web environment. * * @internal */ public instantiateLocalStorage(): boolean { if (!Storages.localStorageAvailable()) { logCodeManager.log('11:02:00'); return false; } const _localStorage = new Storage({ key: 'localStorage', async: false, methods: { get: localStorage.getItem.bind(localStorage), set: localStorage.setItem.bind(localStorage), remove: localStorage.removeItem.bind(localStorage), }, }); return this.register(_localStorage, { default: true }); } /** * Registers the specified Storage with AgileTs * and updates the Persistent Instances that have already attempted * to use the previously unregistered Storage. * * @public * @param storage - Storage to be registered with AgileTs. * @param config - Configuration object */ public register( storage: Storage, config: RegisterConfigInterface = {} ): boolean { const hasRegisteredAnyStorage = notEqual(this.storages, {}); // Check if Storage already exists if (Object.prototype.hasOwnProperty.call(this.storages, storage.key)) { logCodeManager.log('11:03:00', { replacers: [storage.key] }); return false; } // Assign Storage as default Storage if it is the first one added if (!hasRegisteredAnyStorage && config.default === false) logCodeManager.log('11:02:01'); if (!hasRegisteredAnyStorage) config.default = true; // Register Storage this.storages[storage.key] = storage; if (config.default) this.config.defaultStorageKey = storage.key; for (const persistentKey of Object.keys(this.persistentInstances)) { const persistent = this.persistentInstances[persistentKey]; if (persistent == null) continue; // Revalidate Persistent, which contains key/name identifier of the newly registered Storage if (persistent.storageKeys.includes(storage.key)) { const isValid = persistent.validatePersistent(); if (isValid) persistent.initialLoading(); continue; } // If Persistent has no default Storage key, // reassign Storage keys since the now registered Storage // might be tagged as default Storage of AgileTs if (persistent.config.defaultStorageKey == null) { persistent.assignStorageKeys(); const isValid = persistent.validatePersistent(); if (isValid) persistent.initialLoading(); } } logCodeManager.log('13:00:00', { replacers: [storage.key] }, storage); return true; } /** * Retrieves a single Storage with the specified key/name identifier * from the Storages Class. * * If the to retrieve Storage doesn't exist, `undefined` is returned. * * @public * @param storageKey - Key/Name identifier of the Storage. */ public getStorage( storageKey: StorageKey | undefined | null ): Storage | undefined { if (!storageKey) return undefined; const storage = this.storages[storageKey]; if (!storage) { logCodeManager.log('11:03:01', { replacers: [storageKey] }); return undefined; } if (!storage.ready) { logCodeManager.log('11:03:02', { replacers: [storageKey] }); return undefined; } return storage; } /** * Retrieves the stored value at the specified Storage Item key * from the defined external Storage (`storageKey`). * * When no Storage has been specified, * the value is retrieved from the default Storage. * * @public * @param storageItemKey - Key/Name identifier of the value to be retrieved. * @param storageKey - Key/Name identifier of the external Storage * from which the value is to be retrieved. */ public get<GetType = any>( storageItemKey: StorageItemKey, storageKey?: StorageKey ): Promise<GetType | undefined> { if (!this.hasStorage()) { logCodeManager.log('11:03:03'); return Promise.resolve(undefined); } // Call get method on specified Storage if (storageKey) { const storage = this.getStorage(storageKey); if (storage) return storage.get<GetType>(storageItemKey); } // Call get method on default Storage const defaultStorage = this.getStorage(this.config.defaultStorageKey); return ( defaultStorage?.get<GetType>(storageItemKey) || Promise.resolve(undefined) ); } /** * Stores or updates the value at the specified Storage Item key * in the defined external Storages (`storageKeys`). * * When no Storage has been specified, * the value is stored/updated in the default Storage. * * @public * @param storageItemKey - Key/Name identifier of the value to be stored. * @param value - Value to be stored in an external Storage. * @param storageKeys - Key/Name identifier of the external Storage * where the value is to be stored. */ public set( storageItemKey: StorageItemKey, value: any, storageKeys?: StorageKey[] ): void { if (!this.hasStorage()) { logCodeManager.log('11:03:04'); return; } // Call set method on specified Storages if (storageKeys != null) { for (const storageKey of storageKeys) this.getStorage(storageKey)?.set(storageItemKey, value); return; } // Call set method on default Storage const defaultStorage = this.getStorage(this.config.defaultStorageKey); defaultStorage?.set(storageItemKey, value); } /** * Removes the value at the specified Storage Item key * from the defined external Storages (`storageKeys`). * * When no Storage has been specified, * the value is removed from the default Storage. * * @public * @param storageItemKey - Key/Name identifier of the value to be removed. * @param storageKeys - Key/Name identifier of the external Storage * from which the value is to be removed. */ public remove( storageItemKey: StorageItemKey, storageKeys?: StorageKey[] ): void { if (!this.hasStorage()) { logCodeManager.log('11:03:05'); return; } // Call remove method on specified Storages if (storageKeys) { for (const storageKey of storageKeys) this.getStorage(storageKey)?.remove(storageItemKey); return; } // Call remove method on default Storage const defaultStorage = this.getStorage(this.config.defaultStorageKey); defaultStorage?.remove(storageItemKey); } /** * Returns a boolean indicating whether any Storage * has been registered with the Agile Instance or not. * * @public */ public hasStorage(): boolean { return notEqual(this.storages, {}); } /** * Returns a boolean indication whether the * [Local Storage](https://developer.mozilla.org/de/docs/Web/API/Window/localStorage) * is available in the current environment. * * @public */ static localStorageAvailable(): boolean { try { localStorage.setItem('_myDummyKey_', 'myDummyValue'); localStorage.removeItem('_myDummyKey_'); return true; } catch (e) { return false; } } } export interface CreateStoragesConfigInterface { /** * Whether to register the Local Storage by default. * Note that the Local Storage is only available in a web environment. * @default false */ localStorage?: boolean; /** * Key/Name identifier of the default Storage. * * The default Storage represents the default Storage of the Storages Class, * on which executed actions are performed if no specific Storage was specified. * * Also, the persisted value is loaded from the default Storage by default, * since only one persisted value can be applied. * If the loading of the value from the default Storage failed, * an attempt is made to load the value from the remaining Storages. * * @default undefined */ defaultStorageKey?: StorageKey; } export interface StoragesConfigInterface { /** * Key/Name identifier of the default Storage. * * The default Storage represents the default Storage of the Storages Class, * on which executed actions are performed if no specific Storage was specified. * * Also, the persisted value is loaded from the default Storage by default, * since only one persisted value can be applied. * If the loading of the value from the default Storage failed, * an attempt is made to load the value from the remaining Storages. * * @default undefined */ defaultStorageKey: StorageKey | null; } export interface RegisterConfigInterface { /** * Whether the to register Storage should become the default Storage. * * The default Storage represents the default Storage of the Storages Class, * on which executed actions are performed if no specific Storage was specified. * * Also, the persisted value is loaded from the default Storage by default, * since only one persisted value can be applied. * If the loading of the value from the default Storage failed, * an attempt is made to load the value from the remaining Storages. * * @default false */ default?: boolean; }
the_stack
import invariant from 'invariant'; import { action, computed, makeObservable, observable } from 'mobx'; import React, { useLayoutEffect } from 'react'; import { composeState, keyToValueShape, observableGetIn, observableSetIn, splitToPath } from './common-utils'; type valueOf<T> = T[keyof T]; export type DottedObjectKeyPath<D> = D extends any[] ? never : D extends object ? valueOf<{ [K in keyof D & string]: `${K}` | `${K}.${DottedObjectKeyPath<D[K]>}` }> : never; type XName<D> = D extends any[] ? number : DottedObjectKeyPath<D>; type ResolveXName<D, Path extends string | number> = // 只有 Path 为 any 的情况下这个判断才会成立 // 这里这么做是为了将 any 传染出去,不然会变成「any 进来,unknown 出去」 0 extends Path & 1 ? any : string extends Path ? unknown : Path extends number ? D extends Array<infer U> ? U : unknown : Path extends keyof D ? D[Path] : Path extends `${infer K}.${infer R}` ? K extends keyof D ? ResolveXName<D[K], R> : unknown : unknown; export type ValueShape = 'array' | 'object'; export type FieldValidateTrigger = '*' | 'blur' | 'change' | 'mount'; export interface FieldConfig<D = unknown> { label: React.ReactNode; help?: React.ReactNode; tip?: React.ReactNode; asterisk?: boolean; fallbackValue?: any; isEmpty?(value: any): boolean; required?: boolean; requiredMessage?: string; validate?(value: any, field: Field<D>, trigger: FieldValidateTrigger): string | Promise<any>; validateOnMount?: boolean; validateOnChange?: boolean; validateOnBlur?: boolean; disabled?: boolean; readOnly?: boolean; status?: string; // 其他更多字段由上层自定义(TS 层面可以使用 interface merge) } export interface IModel<D = unknown> { // model navigation readonly root: FormModel; readonly path: string[]; readonly parent: IModel; /** model 级别的状态 */ state: any; // value manipulation values: D; getValue<N extends XName<D>>(name: N, defaultValue?: ResolveXName<D, N>): ResolveXName<D, N>; setValue<N extends XName<D>>(name: N, value: ResolveXName<D, N>): void; getSubModel<N extends XName<D>>(name: N): SubModel<ResolveXName<D, N>>; getField<N extends XName<D>>(name: N): Field<ResolveXName<D, N>>; getTupleField<NS extends (keyof D & string)[]>( ...tupleParts: NS ): Field<{ [Index in keyof NS]: NS[Index] extends keyof D ? D[NS[Index]] : never }>; // internals readonly _proxy: SubModelProxy; _asField(): Field<D>; } export class SubModelProxy<D = unknown> { readonly model: IModel<D>; readonly fieldMap = new Map<string, Field>(); valueShape: 'auto' | ValueShape; subModels: { [key: string]: SubModel }; constructor(model: IModel<D>) { this.model = model; this.valueShape = 'auto'; } _updateValueShape(valueShape: 'array' | 'object') { if (this.valueShape === 'auto') { this.valueShape = valueShape; this.subModels = valueShape === 'object' ? {} : ([] as any); } else { invariant( this.valueShape === valueShape, '[xform] Model 的结构需要在使用过程中保持一致,一个数据索引对应的结构不能从数组变为对象,也不能从对象变为数组', ); } } /** 递归前序遍历该 proxy 下(不包含 proxy 本身)所有存在的 model 对象 */ iterateModels(iteratee: (mod: SubModel) => void) { const dfs = (proxy: SubModelProxy) => { if (proxy.subModels != null) { for (const mod of Object.values(proxy.subModels)) { iteratee(mod); dfs(mod._proxy); } } }; dfs(this); } /** 递归遍历该 proxy 下(包括 proxy 本身)所有存在的 field 对象(包括 fork field) */ iterateFields(iteratee: (fd: Field) => void) { this.fieldMap.forEach((fd) => { fd._forkMap.forEach(iteratee); }); this.iterateModels((mod) => { mod._proxy.fieldMap.forEach((fd) => { fd._forkMap.forEach(iteratee); }); }); } getSubModel(longName: string | string[]): SubModel<any> { const path = Array.isArray(longName) ? longName : splitToPath(longName); let mod: IModel = this.model; for (let i = 0; i < path.length - 1; i++) { mod = mod._proxy._getSubModel(path[i]); } return mod._proxy._getSubModel(path[path.length - 1]); } _getSubModel(name: string): SubModel<any> { this._updateValueShape(keyToValueShape(name)); let subModel = this.subModels[name]; if (subModel == null) { subModel = new SubModel(this.model, name); this.subModels[name] = subModel; } return subModel; } getField(longName: string | string[]): Field<any> { const path = Array.isArray(longName) ? longName : splitToPath(longName); if (path.length > 1) { const lastName = path[path.length - 1]; const subModel = this.getSubModel(path.slice(0, -1)); return subModel._proxy.getField([lastName]); } const name = path[0]; this._updateValueShape(keyToValueShape(name)); return this.ensureField(name); } ensureField(name: string, forkName?: string, tupleParts?: string[]): Field<any> { let field = this.fieldMap.get(name); if (field == null) { field = new Field(this.model, name, forkName, tupleParts); this.fieldMap.set(name, field); } return field; } getTupleField(...tupleParts: any[]): Field<any> { this._updateValueShape('object'); const name = tupleParts.join('...'); return this.ensureField(name, Field.ORIGINAL, tupleParts); } } const EMPTY_PATH = [] as string[]; export class FormModel<D extends { [key: string]: any } = unknown> implements IModel<D> { private _nextModelId = 1; getNextModelId() { return `Model_${this._nextModelId++}`; } private _nextFieldId = 1; getNextFieldId() { return `Field_${this._nextFieldId++}`; } public values: D; public state: any = {}; public readonly root = this; public readonly parent = this as IModel<any>; public readonly path = EMPTY_PATH; readonly _proxy: SubModelProxy<D> = new SubModelProxy(this); constructor(values: D = {} as any) { this.values = values; makeObservable(this, { values: observable, state: observable, setValue: action, }); } getValue<N extends XName<D>>(name: N, defaultValue?: ResolveXName<D, N>): ResolveXName<D, N> { return observableGetIn(this.values, String(name), defaultValue); } setValue<N extends XName<D>>(name: N, value: ResolveXName<D, N>) { observableSetIn(this.values, name, value); } getSubModel<N extends XName<D>>(name: N): SubModel<ResolveXName<D, N>> { return this._proxy.getSubModel(String(name)); } getField<N extends XName<D>>(name: N): Field<ResolveXName<D, N>> { return this._proxy.getField(name); } getTupleField<NS extends (keyof D & string)[]>( ...tupleParts: NS ): Field<{ [Index in keyof NS]: NS[Index] extends keyof D ? D[NS[Index]] : never }> { return this._proxy.getTupleField(...tupleParts); } _asField(): never { throw new Error('FormModel 下不支持使用 name=& 的 Field'); } } export class SubModel<D = unknown> implements IModel<D> { readonly root: FormModel<any>; readonly parent: IModel<any>; public state = {}; readonly id: string; public name: string; readonly _proxy: SubModelProxy<D>; constructor(parent: IModel, name: string) { invariant(!name.includes('.'), 'name 中不能包含 .'); this.root = parent.root; this.parent = parent; this.name = name; this._proxy = new SubModelProxy<D>(this); this.id = this.root.getNextModelId(); makeObservable( this, { values: computed, state: observable, setValue: action, // 注意 name 是可以变化的;在数组元素调换位置的情况下 name 会进行变更 name: observable, }, { name: `${this.id}(${this.name})` }, ); } get path(): string[] { return [...this.parent.path, this.name]; } getSubModel<N extends XName<D>>(name: N): SubModel<ResolveXName<D, N>> { return this._proxy.getSubModel(String(name)); } getField<N extends XName<D>>(name: N): Field<ResolveXName<D, N>> { return this._proxy.getField(String(name)); } getTupleField<NS extends (keyof D & string)[]>( ...tupleParts: NS ): Field<{ [Index in keyof NS]: NS[Index] extends keyof D ? D[NS[Index]] : never }> { return this._proxy.getTupleField(...tupleParts); } get values() { return this.parent.getValue(this.name) as D; } set values(nextValues: D) { this.parent.setValue(this.name, nextValues); } getValue<N extends XName<D>>(name: N, defaultValue?: ResolveXName<D, N>): ResolveXName<D, N> { return observableGetIn(this.values, String(name), defaultValue); } setValue<N extends XName<D>>(name: N, value: ResolveXName<D, N>): void { if (this.values == null) { this._proxy._updateValueShape(keyToValueShape(splitToPath(String(name))[0])); this.values = (this._proxy.valueShape === 'array' ? [] : {}) as D; } observableSetIn(this.values, String(name), value); } _asField() { return this.parent.getField(this.name) as Field<D>; } } export interface FieldState { error?: any; validating?: boolean; cancelValidation?(): void; [key: string]: any; } export class Field<V = unknown> { static ORIGINAL = 'original'; /** 字段配置的最新缓存(注意不要修改该值)*/ config?: FieldConfig<V> = null; /** 字段是否在视图中被渲染 */ isMounted = false; readonly parent: IModel<any>; readonly name: string; readonly forkName: string; readonly tupleParts: string[]; readonly id: string; readonly _forkMap: Map<string, Field>; state: FieldState = {}; get value(): V { if (this.tupleParts) { return this.tupleParts.map((part) => this.parent.getValue(part)) as any; } return this.parent.getValue(this.name) as any; } set value(value: V) { if (this.tupleParts) { this.tupleParts.forEach((part, index) => { this.parent.setValue(part, value[index]); }); return; } this.parent.setValue(this.name, value); } get path() { return this.parent.path.concat([this.name]); } constructor(parent: IModel, name: string, forkName = Field.ORIGINAL, tupleParts?: string[]) { this.parent = parent; this.name = name; this.forkName = forkName; this.tupleParts = tupleParts; this.id = this.parent.root.getNextFieldId(); makeObservable( this, { state: observable, value: computed, path: computed, validate: action, handleBlur: action, handleChange: action, }, { name: `${this.id}(${name}${forkName === Field.ORIGINAL ? '' : '#' + forkName})` }, ); if (forkName === Field.ORIGINAL) { this._forkMap = new Map(); } else { const original = this.parent.getField(name); this._forkMap = original._forkMap; } this._forkMap.set(forkName, this); } _useTrack(config: FieldConfig<V>) { // eslint-disable-next-line react-hooks/rules-of-hooks useLayoutEffect(() => { if (this.isMounted) { console.warn(`[xform] field \`${this.path.join('.')}\` 已在视图中被加载,你需要 fork 该字段来进行多次加载.`); return; } this.config = config; this.isMounted = true; return () => { this.config = null; this.isMounted = false; }; }, [config]); } getFork(forkName: string): Field<V> { if (this._forkMap.has(forkName)) { return this._forkMap.get(forkName) as Field<V>; } else { return new Field<V>(this.parent, this.name, forkName, this.tupleParts); } } async validate(trigger: FieldValidateTrigger = '*') { if (!this.isMounted) { return; } const { validate, fallbackValue, isEmpty, required, requiredMessage = '该字段为必填项', validateOnMount, validateOnBlur, validateOnChange, } = this.config; const value = composeState(this.value, fallbackValue); const needValidate = trigger === '*' || (validateOnBlur && trigger === 'blur') || (validateOnMount && trigger === 'mount') || (validateOnChange && trigger === 'change'); if (!needValidate) { return; } const actualValidate = async () => { if (required && isEmpty(value)) { return requiredMessage; } if (validate) { return validate(value, this, trigger); } return null; }; let cancelled = false; this.state.cancelValidation?.(); this.state.validating = true; this.state.cancelValidation = action(() => { cancelled = true; this.state.cancelValidation = null; this.state.validating = false; }); return actualValidate().then( action((error) => { if (cancelled) { return; } this.state.cancelValidation = null; this.state.validating = false; this.state.error = error; return error; }), ); } handleBlur = () => { return this.validate('blur'); }; handleChange = (nextValue: any) => { this.value = composeState(nextValue, this.config?.fallbackValue); return this.validate('change'); }; }
the_stack
import {MemoryFile} from "../../../src/files/memory_file"; import {expect} from "chai"; import {Renamer} from "../../../src/objects/rename/renamer"; import {Registry} from "../../../src/registry"; describe("Rename Data Element", () => { it("DTEL, no references, just the object", () => { const xml = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZBAR</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const reg = new Registry().addFiles([ new MemoryFile("zbar.dtel.xml", xml), ]).parse(); new Renamer(reg).rename("DTEL", "zbar", "foo"); expect(reg.getObjectCount()).to.equal(1); for (const f of reg.getFiles()) { expect(f.getFilename()).to.equal("foo.dtel.xml"); expect(f.getRaw().includes("<ROLLNAME>FOO</ROLLNAME>")).to.equal(true); } }); it("DTEL, referenced from PROG", () => { const xml = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZBARBAR</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const prog = `REPORT zprog_rename_dtel. CONSTANTS c1 TYPE zbarbar VALUE 'A'. "#EC NOTEXT CONSTANTS c2 TYPE zbarbar VALUE 'A'. "#EC NOTEXT DATA bar1 TYPE zbarbar. DATA bar2 TYPE zbarbar.`; const reg = new Registry().addFiles([ new MemoryFile("zbarbar.dtel.xml", xml), new MemoryFile("zprog_rename_dtel.prog.abap", prog), ]).parse(); reg.findIssues(); // hmm, this builds the ddic references new Renamer(reg).rename("DTEL", "zbarbar", "foo"); expect(reg.getObjectCount()).to.equal(2); for (const f of reg.getFiles()) { if (f.getFilename() === "foo.dtel.xml") { expect(f.getRaw().includes("<ROLLNAME>FOO</ROLLNAME>")).to.equal(true); } else if (f.getFilename() === "zprog_rename_dtel.prog.abap") { expect(f.getRaw()).to.equal(`REPORT zprog_rename_dtel. CONSTANTS c1 TYPE foo VALUE 'A'. "#EC NOTEXT CONSTANTS c2 TYPE foo VALUE 'A'. "#EC NOTEXT DATA bar1 TYPE foo. DATA bar2 TYPE foo.`); } else { expect(1).to.equal(f.getFilename(), "unexpected file"); } } }); it("DTEL, referenced from TABL", () => { const xml = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZBAR</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const tabl = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_TABL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD02V> <TABNAME>ZTABL</TABNAME> <DDLANGUAGE>E</DDLANGUAGE> <TABCLASS>INTTAB</TABCLASS> <DDTEXT>Stypemapping</DDTEXT> <EXCLASS>4</EXCLASS> </DD02V> <DD03P_TABLE> <DD03P> <FIELDNAME>DYNAMIC_STYLE_GUID</FIELDNAME> <ROLLNAME>ZBAR</ROLLNAME> <ADMINFIELD>0</ADMINFIELD> <COMPTYPE>E</COMPTYPE> </DD03P> </DD03P_TABLE> </asx:values> </asx:abap> </abapGit>`; const reg = new Registry().addFiles([ new MemoryFile("zbar.dtel.xml", xml), new MemoryFile("ztabl.tabl.xml", tabl), ]).parse(); reg.findIssues(); // hmm, this builds the ddic references new Renamer(reg).rename("DTEL", "zbar", "foo"); expect(reg.getObjectCount()).to.equal(2); for (const f of reg.getFiles()) { if (f.getFilename() === "foo.dtel.xml") { expect(f.getRaw().includes("<ROLLNAME>FOO</ROLLNAME>")).to.equal(true); } else if (f.getFilename() === "ztabl.tabl.xml") { expect(f.getRaw()).to.include(`<ROLLNAME>FOO</ROLLNAME>`); } else { expect(1).to.equal(f.getFilename(), "unexpected file"); } } }); it("DTEL, referenced from TTYP", () => { const xml = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZBAR</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const ttyp = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_TTYP" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD40V> <TYPENAME>ZEXCEL_T_STYLE_COLOR_ARGB</TYPENAME> <DDLANGUAGE>E</DDLANGUAGE> <ROWTYPE>ZBAR</ROWTYPE> <ROWKIND>E</ROWKIND> <DATATYPE>CHAR</DATATYPE> <LENG>000008</LENG> <ACCESSMODE>T</ACCESSMODE> <KEYDEF>D</KEYDEF> <KEYKIND>N</KEYKIND> <DDTEXT>Table of RGB colors</DDTEXT> </DD40V> </asx:values> </asx:abap> </abapGit>`; const reg = new Registry().addFiles([ new MemoryFile("zbar.dtel.xml", xml), new MemoryFile("zttyp.ttyp.xml", ttyp), ]).parse(); reg.findIssues(); // hmm, this builds the ddic references new Renamer(reg).rename("DTEL", "zbar", "foo"); expect(reg.getObjectCount()).to.equal(2); for (const f of reg.getFiles()) { if (f.getFilename() === "foo.dtel.xml") { expect(f.getRaw().includes("<ROLLNAME>FOO</ROLLNAME>")).to.equal(true); } else if (f.getFilename() === "zttyp.ttyp.xml") { expect(f.getRaw()).to.include(`<ROWTYPE>FOO</ROWTYPE>`); } else { expect(1).to.equal(f.getFilename(), "unexpected file"); } } }); it("DTEL, referenced from class in PROG", () => { const xml = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZBARBAR</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const prog = `REPORT zprog_rename_dtel. CLASS lcl_bar DEFINITION. PUBLIC SECTION. CONSTANTS c1 TYPE zbarbar VALUE 'A'. "#EC NOTEXT DATA bar1 TYPE zbarbar. CONSTANTS c2 TYPE zbarbar VALUE 'A'. "#EC NOTEXT DATA bar2 TYPE zbarbar. ENDCLASS. CLASS lcl_bar IMPLEMENTATION. ENDCLASS.`; const reg = new Registry().addFiles([ new MemoryFile("zbarbar.dtel.xml", xml), new MemoryFile("zprog_rename_dtel.prog.abap", prog), ]).parse(); reg.findIssues(); // hmm, this builds the ddic references new Renamer(reg).rename("DTEL", "zbarbar", "foo"); expect(reg.getObjectCount()).to.equal(2); for (const f of reg.getFiles()) { if (f.getFilename() === "foo.dtel.xml") { expect(f.getRaw().includes("<ROLLNAME>FOO</ROLLNAME>")).to.equal(true); } else if (f.getFilename() === "zprog_rename_dtel.prog.abap") { expect(f.getRaw()).to.equal(`REPORT zprog_rename_dtel. CLASS lcl_bar DEFINITION. PUBLIC SECTION. CONSTANTS c1 TYPE foo VALUE 'A'. "#EC NOTEXT DATA bar1 TYPE foo. CONSTANTS c2 TYPE foo VALUE 'A'. "#EC NOTEXT DATA bar2 TYPE foo. ENDCLASS. CLASS lcl_bar IMPLEMENTATION. ENDCLASS.`); } else { expect(1).to.equal(f.getFilename(), "unexpected file"); } } }); it("two DTEL, referenced from INTF", () => { const xmlbarbar = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZBARBAR</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const xmlfoofoo = `<?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DTEL" serializer_version="v1.0.0"> <asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"> <asx:values> <DD04V> <ROLLNAME>ZFOOFOO</ROLLNAME> <DDLANGUAGE>E</DDLANGUAGE> <HEADLEN>55</HEADLEN> <SCRLEN1>10</SCRLEN1> <SCRLEN2>20</SCRLEN2> <SCRLEN3>40</SCRLEN3> <DDTEXT>testing</DDTEXT> <REPTEXT>testing</REPTEXT> <SCRTEXT_S>testing</SCRTEXT_S> <SCRTEXT_M>testing</SCRTEXT_M> <SCRTEXT_L>testing</SCRTEXT_L> <DTELMASTER>E</DTELMASTER> <DATATYPE>CHAR</DATATYPE> <LENG>000001</LENG> <OUTPUTLEN>000001</OUTPUTLEN> </DD04V> </asx:values> </asx:abap> </abapGit>`; const intf = `INTERFACE zif_excel_sheet_properties PUBLIC. DATA hidden TYPE zbarbar. DATA show_zeros TYPE zfoofoo. ENDINTERFACE.`; const reg = new Registry().addFiles([ new MemoryFile("zbarbar.dtel.xml", xmlbarbar), new MemoryFile("zfoofoo.dtel.xml", xmlfoofoo), new MemoryFile("zif_excel_sheet_properties.intf.abap", intf), ]).parse(); reg.findIssues(); // hmm, this builds the ddic references const renamer = new Renamer(reg); renamer.rename("DTEL", "zfoofoo", "foo"); renamer.rename("DTEL", "zbarbar", "bar"); expect(reg.getObjectCount()).to.equal(3); for (const f of reg.getFiles()) { if (f.getFilename() === "foo.dtel.xml") { expect(f.getRaw().includes("<ROLLNAME>FOO</ROLLNAME>")).to.equal(true); } else if (f.getFilename() === "bar.dtel.xml") { expect(f.getRaw().includes("<ROLLNAME>BAR</ROLLNAME>")).to.equal(true); } else if (f.getFilename() === "zif_excel_sheet_properties.intf.abap") { expect(f.getRaw()).to.equal(`INTERFACE zif_excel_sheet_properties PUBLIC. DATA hidden TYPE bar. DATA show_zeros TYPE foo. ENDINTERFACE.`); } else { expect(1).to.equal(f.getFilename(), "unexpected file"); } } }); });
the_stack
declare class SimpleSchema {} /** * This is the base class for OnePay's domestic and intl payment gateways * which bear the common hashing algorithym. * It should not be used alone. * * _Đây là class cơ sở cho OnePayDomestic và OnePayInternational, chỉ chứa các thuật toán mã hóa chung. * Lớp này không nên được sử dụng để khai báo._ * @private */ declare class OnePay { /** * OnePay configSchema * @type {SimpleSchema} */ static configSchema: SimpleSchema; /** * '2' * @type {string} */ static VERSION: string; /** * 'pay' * @type {string} */ static COMMAND: string; /** * onepay only support 'VND' * @type {string} */ static CURRENCY_VND: string; /** * 'en' * @type {string} */ static LOCALE_EN: string; /** * 'vn' * @type {string} */ static LOCALE_VN: string; /** * Instantiate a OnePay checkout helper * * _Khởi tạo class thanh toán OnePay_ * @param {OnePayConfig} config check OnePay.configSchema for data type requirements * @return {void} */ constructor(config: onepay.OnePayConfig, type?: string); /** * Build checkout URL to redirect to the payment gateway. * * _Hàm xây dựng url để redirect qua OnePay gateway, trong đó có tham số mã hóa (còn gọi là public key)._ * * @param {OnePayCheckoutPayload} payload Object that contains needed data for the URL builder. _Đối tượng chứa các dữ liệu cần thiết để thiết lập đường dẫn._ * @return {Promise<URL>} buildCheckoutUrl promise */ buildCheckoutUrl(payload: onepay.OnePayCheckoutPayload): Promise<URL>; /** * Validate checkout payload against specific schema. Throw ValidationErrors if invalid against checkoutSchema * Build the schema in subclass. * * _Kiểm tra tính hợp lệ của dữ liệu thanh toán dựa trên schema đã được đồng bộ với tài liệu của nhà cung cấp. * Hiển thị lỗi nếu không hợp lệ với checkoutSchema. * Schema sẽ được tạo trong class con._ * @param {OnePayCheckoutPayload} payload */ validateCheckoutPayload(payload: onepay.OnePayCheckoutPayload): void; /** * Return default checkout Payloads * * _Lấy checkout payload mặc định cho cổng thanh toán này_ * @type {OnePayCheckoutPayload} */ checkoutPayloadDefaults: onepay.OnePayCheckoutPayload; /** * Verify return query string from OnePay using enclosed vpc_SecureHash string * * _Hàm thực hiện xác minh tính đúng đắn của các tham số trả về từ OnePay Payment_ * * @param {object} query Query data object from GET handler (`response.query`). <br> _Object query trả về từ GET handler_ * @return {Promise<OnePayDomesticReturnObject>} Promise object which resolved with normalized returned data object, with additional fields like isSuccess. <br> _Promise khi hoàn thành sẽ trả về object data từ cổng thanh toán, được chuẩn hóa tên theo camelCase và đính kèm thuộc tính isSuccess_ */ verifyReturnUrl(query: object): Promise<onepay.OnePayDomesticReturnObject>; } /** * OnePay Domestic payment gateway helper. * Supports VN domestic ATM cards. * * _Class hỗ trợ cổng thanh toán nội địa OnePay._ * _Hỗ trợ thẻ ATM nội địa._ * * @extends OnePay */ declare class OnePayDomestic extends OnePay { /** * OnePayDomestic test configs * * _Config test thử OnePay Domestic._ */ static TEST_CONFIG: object; /** * Get error status as string from response code. * * _Lấy chuỗi chứa trạng thái lỗi tương đương với mã response code_ * * @param {*} responseCode Responde code from gateway <br> _Mã trả về từ cổng thanh toán._ * @param {*} locale Same locale at the buildCheckoutUrl. Note, 'vn' for Vietnamese. <br> _Cùng nơi với hàm buildCheckoutUrl. Lưu ý, Việt Nam là 'vn'_ * @return {string} A string contains error status converted from response code. <br> _Một chuỗi chứa trạng thái lỗi được chuyển lại từ response code_ */ static getReturnUrlStatus(responseCode: Object, locale: string): string; /** * Instantiate a OnePayDomestic checkout helper * * _Khởi tạo instance thanh toán OnePayDomestic_ * @param {Object} config check OnePay.configSchema for data type requirements. <br> _Xem OnePay.configSchema để biết yêu cầu kiểu dữ liệu_ * @return {void} */ constructor(config: onepay.OnePayConfig); /** * Validate checkout payload against specific schema. Throw **ValidationErrors** if invalid against checkoutSchema. * Called internally by **buildCheckoutUrl** * * _Kiểm tra tính hợp lệ của dữ liệu thanh toán dựa trên schema đã được đồng bộ với tài liệu của nhà cung cấp. * Hiển thị lỗi nếu không hợp lệ với **checkoutSchema**. Được gọi bên trong **buildCheckoutUrl**_ * @param {OnePayCheckoutPayload} payload * @override */ validateCheckoutPayload(payload: onepay.OnePayCheckoutPayload): void; /** * Default checkout payload object * * _Checkout payload mặc định cho cổng thanh toán này_ * @type {OnePayCheckoutPayload} */ checkoutPayloadDefaults: onepay.OnePayCheckoutPayload; /** * Verify return query string from OnePay using enclosed vpc_SecureHash string * * _Hàm thực hiện xác minh tính đúng đắn của các tham số trả về từ cổng thanh toán_ * * @param {*} query Query data object from GET handler (`response.query`). <br> _Object query trả về từ GET handler_ * @returns { Promise<OnePayDomesticReturnObject> } Promise object which resolved with normalized returned data object, with additional fields like isSuccess. <br> _Promise khi hoàn thành sẽ trả về object data từ cổng thanh toán, được chuẩn hóa tên theo camelCase và đính kèm thuộc tính isSuccess_ */ verifyReturnUrl(query: Promise<onepay.OnePayDomesticReturnObject>): Promise<onepay.OnePayDomesticReturnObject>; } export { OnePayDomestic }; declare class OnePayInternational extends OnePay { /** * OnePayDomestic test configs * * _Config test thử OnePay Domestic._ */ static TEST_CONFIG: object; /** * Get error status as string from response code. * * _Lấy chuỗi chứa trạng thái lỗi tương đương với mã response code_ * @param {*} responseCode Responde code from gateway * @param {*} locale Same locale at the buildCheckoutUrl. Note, 'vn' for Vietnamese * @return {string} Localized status string from the response code */ static getReturnUrlStatus(responseCode: Object, locale: string): string; /** * Instantiate a OnePayInternational checkout helper * * _Khởi tạo instance thanh toán OnePayInternational_ * @param {Object} config check OnePay.configSchema for data type requirements. <br> _Xem OnePay.configSchema để biết yêu cầu kiểu dữ liệu_ * @return {void} */ constructor(config: onepay.OnePayConfig); /** * Validate checkout payload against specific schema. Throw **ValidationErrors** if invalid against checkoutSchema. * Called internally by **buildCheckoutUrl** * * _Kiểm tra tính hợp lệ của dữ liệu thanh toán dựa trên schema đã được đồng bộ với tài liệu của nhà cung cấp. * Hiển thị lỗi nếu không hợp lệ với **checkoutSchema**. Được gọi bên trong **buildCheckoutUrl**_ * @param {OnePayCheckoutPayload} payload * @override */ validateCheckoutPayload(payload: onepay.OnePayCheckoutPayload): void; /** * Return default checkout Payloads * * _Lấy checkout payload mặc định cho cổng thanh toán này_ * @return {OnePayCheckoutPayload} default payload object <br> _Dữ liệu mặc định của đối tượng_ */ checkoutPayloadDefaults: onepay.OnePayCheckoutPayload; /** * Verify return query string from OnePay using enclosed vpc_SecureHash string * * _Hàm thực hiện xác minh tính đúng đắn của các tham số trả về từ onepay Payment_ * * @param {*} query * @returns { Promise<OnePayInternationalReturnObject> } Promise object which resolved with normalized returned data object, with additional fields like isSuccess. <br> _Promise khi hoàn thành sẽ trả về object data từ cổng thanh toán, được chuẩn hóa tên theo camelCase và đính kèm thuộc tính isSuccess_ */ verifyReturnUrl(query: onepay.OnePayInternationalReturnObject): Promise<onepay.OnePayInternationalReturnObject>; } export { OnePayInternational }; declare namespace onepay { export interface OnePayConfig { /** * Merchant access code */ accessCode: string; /** * Unique merchant code assigned by OnePay */ merchant: string; /** * Gateway URL to redirect provided by payment provider */ paymentGateway: string; /** * Merchant's secure secret */ secureSecret: string; } export interface OnePayCheckoutPayload { /** * optional: true, max: 64, regEx: urlRegExp */ againLink?: string; /** * The amount to be paid. max: 9999999999. <br> _Khoản tiền cần thanh toán_ */ amount: number; /** * optional: true, max: 64 */ billingCity?: string; /** * optional: true, max: 2 */ billingCountry?: string; /** * optional: true, max: 64 */ billingPostCode?: string; /** * optional: true, max: 64 */ billingStateProvince?: string; /** * optional: true, max: 64 */ billingStreet?: string; /** * max: 15 */ clientIp: string; /** * allowedValues: ['VND'] */ currency: string; /** * optional: true, max: 24, regEx: SimpleSchema.RegEx.Email */ customerEmail?: string; /** * optional: true, max: 64 */ customerId?: string; /** * optional: true, max: 16 */ customerPhone?: string; /** * optional: true, max: 64 */ deliveryAddress?: string; /** * optional: true, max: 64 */ deliveryCity?: string; /** * optional: true, max: 8 */ deliveryCountry?: string; /** * optional: true, max: 64 */ deliveryProvince?: string; /** * allowedValues: ['vn', 'en'] */ locale: string; /** * max: 32 */ orderId: string; /** * max: 255, regEx: urlRegExp. <br> * NOTE: returnURL is documented with 64 chars limit but seem not a hard limit, and 64 is too few in some scenar */ returnUrl: string; /** * optional: true, max: 255. <br> * NOTE: no max limit documented for this field, this is just a safe val */ title?: string; /** * max: 34 */ transactionId: string; /** * max: 8 */ vpcAccessCode?: string; /** * max: 16 */ vpcCommand: string; /** * max: 16 */ vpcMerchant?: string; /** * max: 2 */ vpcVersion?: string; } export interface OnePayDomesticReturnObject { /** * whether the payment succeeded or not */ isSuccess: boolean; /** * amount paid by customer, already divided by 100 */ amount: number; /** * should be same with checkout request */ command: string; /** * currency code, should be same with checkout request */ currencyCode: string; /** * Gateway's own transaction ID, used to look up at Gateway's side */ gatewayTransactionNo: string; /** * locale code, should be same with checkout request */ locale: string; /** * merchant ID, should be same with checkout request */ merchant: string; /** * Approve or error message based on response code */ message: string; /** * merchant's order ID, should be same with checkout request */ orderId: string; /** * response code, payment has errors if it is non-zero */ responseCode: string; /** * checksum of the returned data, used to verify data integrity */ secureHash: string; /** * merchant's transaction ID, should be same with checkout request */ transactionId: string; /** * should be same with checkout request */ version: string; /** * e.g: 970436 */ vpc_AdditionData?: string; /** * e.g: 1000000 */ vpc_Amount?: string; /** * e.g: pay */ vpc_Command?: string; /** * e.g: VND */ vpc_CurrencyCode?: string; /** * e.g: vn */ vpc_Locale?: string; /** * e.g: ONEPAY */ vpc_Merchant?: string; /** * e.g: TEST_15160802610161733380665 */ vpc_MerchTxnRef?: string; /** * e.g: TEST_15160802610161733380665 */ vpc_OrderInfo?: string; /** * e.g: B5CD330E2DC1B1C116A068366F69717F54AD77E1BE0C40E4E3700551BE9D5004 */ vpc_SecureHash?: string; /** * e.g: 1618136 */ vpc_TransactionNo?: string; /** * e.g: 0 */ vpc_TxnResponseCode?: string; /** * e.g: 2 */ vpc_Version?: string; } export interface OnePayInternationalReturnObject { /** * whether the payment succeeded or not */ isSuccess: boolean; /** * amount paid by customer, already divided by 100 */ amount: number; /** * should be same with checkout request */ command: string; /** * currency code, should be same with checkout request */ currencyCode: string; /** * Gateway's own transaction ID, used to look up at Gateway's side */ gatewayTransactionNo: string; /** * locale code, should be same with checkout request */ locale: string; /** * merchant ID, should be same with checkout request */ merchant: string; /** * Approve or error message based on response code */ message: string; /** * merchant's order ID, should be same with checkout request */ orderId: string; /** * response code, payment has errors if it is non-zero */ responseCode: string; /** * checksum of the returned data, used to verify data integrity */ secureHash: string; /** * merchant's transaction ID, should be same with checkout request */ transactionId: string; /** * should be same with checkout request */ version: string; /** * e.g: 970436 */ vpc_AdditionData?: string; /** * e.g: 1000000 */ vpc_Amount?: string; /** * e.g: pay */ vpc_Command?: string; /** * e.g: vn */ vpc_Locale?: string; /** * e.g: ONEPAY */ vpc_Merchant?: string; /** * e.g: TEST_15160802610161733380665 */ vpc_MerchTxnRef?: string; /** * e.g: TEST_15160802610161733380665 */ vpc_OrderInfo?: string; /** * e.g: B5CD330E2DC1B1C116A068366F69717F54AD77E1BE0C40E4E3700551BE9D5004 */ vpc_SecureHash?: string; /** * e.g: 1618136 */ vpc_TransactionNo?: string; /** * e.g: 0 */ vpc_TxnResponseCode?: string; /** * e.g: 2 */ vpc_Version?: string; /** * billing address' city */ billingCity: string; /** * billing address' country */ billingCountry: string; /** * billing address' post code */ billingPostCode: string; /** * billing address' state or province */ billingStateProvince: string; /** * billing address and street name */ billingStreet: string; /** * type of card used to pay, VC, MC, JC, AE */ card: string; /** * e.g: 06 */ vpc_3DSECI: string; /** * e.g: N */ vpc_3DSenrolled: string; /** * e.g: zklRMXTS2puX%2Btj0DwOJyq6T6s8%3D */ vpc_3DSXID: string; /** * e.g: Unsupported */ vpc_AcqAVSRespCode: string; /** * e.g: Unsupported */ vpc_AcqCSCRespCode: string; /** * e.g: 00 */ vpc_AcqResponseCode: string; /** * e.g: 523190 */ vpc_AuthorizeId: string; /** * e.g: Hanoi */ vpc_AVS_City: string; /** * e.g: VNM */ vpc_AVS_Country: string; /** * e.g: 10000 */ vpc_AVS_PostCode: string; /** * e.g: Hoan+Kiem */ vpc_AVS_StateProv: string; /** * e.g: 194+Tran+Quang+Khai */ vpc_AVS_Street01: string; /** * e.g: Z */ vpc_AVSRequestCode: string; /** * e.g: Unsupported */ vpc_AVSResultCode: string; /** * e.g: 20180116 */ vpc_BatchNo: string; /** * e.g: VC */ vpc_Card: string; /** * e.g: 88 */ vpc_CardLevelIndicator: string; /** * e.g: 400555xxxxxx0001 */ vpc_CardNum: string; /** * e.g: U */ vpc_CommercialCard: string; /** * e.g: 3 */ vpc_CommercialCardIndicator: string; /** * e.g: Unsupported */ vpc_CSCResultCode: string; /** * e.g: 8 */ vpc_MarketSpecificData: string; /** * e.g: Approved */ vpc_Message: string; /** * e.g: 801615523190 */ vpc_ReceiptNo: string; /** * e.g: 8 */ vpc_ReturnACI: string; /** * e.g: ACC */ vpc_RiskOverallResult: string; /** * e.g: 1234567890123456789 */ vpc_TransactionIdentifier: string; /** * e.g: 06 */ vpc_VerSecurityLevel: string; /** * e.g: E */ vpc_VerStatus: string; /** * e.g: 3DS */ vpc_VerType: string; } } /** * Ngan Luong payment gateway helper. * * _Class hỗ trợ thanh toán qua Ngân Lượng._ * */ declare class NganLuong { /** * NganLuong configSchema */ static configSchema: SimpleSchema; /** * NganLuong dataSchema */ static dataSchema: SimpleSchema; /** * NganLuong API Version */ static VERSION: string; /** * NganLuong API command string */ static COMMAND: string; /** * NganLuong VND currency code */ static CURRENCY_VND: string; /** * NganLuong English locale code */ static LOCALE_EN: string; /** * NganLuong Vietnamese locale code */ static LOCALE_VN: string; /** * NganLuong test configs * * _Config test thử Ngân Lượng_ */ static TEST_CONFIG: object; /** * Instantiate a NganLuong checkout helper * * _Khởi tạo instance thanh toán NganLuong_ * * @param {Object} config check NganLuong.configSchema for data type requirements. <br> _Xem NganLuong.configSchema để biết yêu cầu kiểu dữ liệu_ * @return {void} */ constructor(config: nganluong.NganLuongConfig); /** * Build checkoutUrl to redirect to the payment gateway * * _Hàm xây dựng url để redirect qua NganLuong gateway, trong đó có tham số mã hóa (còn gọi là public key)_ * * @param {NganLuongCheckoutPayload} payload Object that contains needed data for the URL builder, refer to typeCheck object above. <br> _Đối tượng chứa các dữ liệu cần thiết để thiết lập đường dẫn._ * @return {Promise<URL>} buildCheckoutUrl promise */ buildCheckoutUrl(payload: nganluong.NganLuongCheckoutPayload): Promise<URL>; /** * Validate checkout payload against specific schema. Throw ValidationErrors if invalid against checkoutSchema * * _Kiểm tra tính hợp lệ của dữ liệu thanh toán dựa trên một cấu trúc dữ liệu cụ thể. Hiển thị lỗi nếu không hợp lệ với checkoutSchema._ * * @param {NganLuongCheckoutPayload} payload */ validateCheckoutPayload(payload: nganluong.NganLuongCheckoutPayload): void; /** * default payload object * * _checkout payload mặc định_ * @type {NganLuongCheckoutPayload} */ checkoutPayloadDefaults: nganluong.NganLuongCheckoutPayload; /** * Verify return query string from NganLuong using enclosed vnp_SecureHash string * * _Hàm thực hiện xác minh tính đúng đắn của các tham số trả về từ cổng thanh toán_ * * @param {Object} query Query data object from GET handler (`response.query`). <br> _Dữ liệu được trả về từ GET handler (`response.query`)_ * @return {Promise<nganluong.NganLuongReturnObject>} */ verifyReturnUrl(query: object): Promise<nganluong.NganLuongReturnObject>; } export { NganLuong }; declare namespace nganluong { export interface NganLuongConfig { /** * NganLuong payment gateway (API Url to send payment request) * */ paymentGateway: string; /** * NganLuong merchant id */ merchant: string; /** * NganLuong receiver email, who will receive the money (usually is merchant email) */ receiverEmail: string; /** * NganLuong merchant secret string */ secureSecret: string; } export interface NganLuongCheckoutPayload { /** * optional: true */ createdDate?: string; /** * The payment mount */ amount: number; /** * optional: true, max: 16 */ clientIp?: string; /** * allowedValues: ['vnd', 'VND', 'USD', 'usd'] */ currency: string; /** * optional: true, max: 255 */ billingCity?: string; /** * optional: true, max: 255 */ billingCountry?: string; /** * optional: true, max: 255 */ billingPostCode?: string; /** * optional: true, max: 255 */ billingStateProvince?: string; /** * optional: true, max: 255 */ billingStreet?: string; /** * optional: true, max: 255 */ customerId?: string; /** * optional: true, max: 255 */ deliveryAddress?: string; /** * optional: true, max: 255 */ deliveryCity?: string; /** * optional: true, max: 255 */ deliveryCountry?: string; /** * optional: true, max: 255 */ deliveryProvince?: string; /** * allowedValues: ['vi', 'en'] */ locale: string; /** * max: 34 */ orderId: string; /** * max: 255, regEx: SimpleSchema.RegEx.Email */ receiverEmail: string; /** * allowedValues: ['NL', 'VISA', 'MASTER', 'JCB', 'ATM_ONLINE', 'ATM_OFFLINE', 'NH_OFFLINE', 'TTVP', 'CREDIT_CARD_PREPAID', 'IB_ONLINE'] */ paymentMethod: string; /** * optional: true, max: 50 (required with method ATM_ONLINE, ATM_OFFLINE, NH_OFFLINE, CREDIT_CARD_PREPAID) */ bankCode?: string; /** * optional: true, allowedValues: ['1', '2'] */ paymentType?: string; /** * optional: true, max: 500 */ orderInfo?: string; /** * Integer, optional: true */ taxAmount?: number; /** * Integer, optional: true */ discountAmount?: number; /** * Integer, optional: true */ feeShipping?: number; /** * max: 255, regEx: SimpleSchema.RegEx.Email */ customerEmail: string; /** * max: 255 */ customerPhone: string; /** * max: 255 */ customerName: string; /** * max: 255 */ returnUrl: string; /** * max: 255, optional: true */ cancelUrl?: string; /** * Integer, optional: true; minutes */ timeLimit?: number; /** * max: 255, optional: true */ affiliateCode?: string; /** * optional: true */ totalItem?: string; /** * max: 40 */ transactionId: string; /** * max: 32 */ nganluongSecretKey: string; /** * max: 16 */ nganluongMerchant: string; /** * max: 32 */ nganluongCommand: string; /** * max: 3 */ nganluongVersion: string; /** * regEx: SimpleSchema.RegEx.Url */ paymentGateway: string; /** * */ merchant: string; /** * */ secureSecret: string; } export interface NganLuongReturnObject { /** * whether the payment succeeded or not */ isSuccess: boolean; /** * Approve or error message based on response code */ message: string; /** * merchant ID, should be same with checkout request */ merchant: string; /** * merchant's transaction ID, should be same with checkout request */ transactionId: string; /** * amount paid by customer */ amount: string; /** * order info, should be same with checkout request */ orderInfo: string; /** * response code, payment has errors if it is non-zero */ responseCode: string; /** * bank code of the bank where payment was occurred */ bankCode: string; /** * Gateway's own transaction ID, used to look up at Gateway's side */ gatewayTransactionNo: string; /** * e.g: '00' */ error_code: string; /** * e.g: '43614-fc2a3698ee92604d5000434ed129d6a8' */ token: string; /** * e.g: '' */ description: string; /** * e.g: '00' */ transaction_status: string; /** * e.g: 'tung.tran@naustud.io' */ receiver_email: string; /** * e.g: 'adidas' */ order_code: string; /** * e.g: '90000' */ total_amount: string; /** * e.g: 'ATM_ONLINE' */ payment_method: string; /** * e.g: 'BAB' */ bank_code: string; /** * e.g: '2' */ payment_type: string; /** * e.g: 'Test' */ order_description: string; /** * e.g: '0' */ tax_amount: string; /** * e.g: '0' */ discount_amount: string; /** * e.g: '0' */ fee_shipping: string; /** * e.g: 'http%3A%2F%2Flocalhost%3A8080%2Fpayment%2Fnganluong%2Fcallback' */ return_url: string; /** * e.g: 'http%3A%2F%2Flocalhost%3A8080%2F' */ cancel_url: string; /** * e.g: 'Nguyen Hue' */ buyer_fullname: string; /** * e.g: 'tu.nguyen@naustud.io' */ buyer_email: string; /** * e.g: '0948231723' */ buyer_mobile: string; /** * e.g: 'Test' */ buyer_address: string; /** * e.g: '' */ affiliate_code: string; /** * e.g: '19563733' */ transaction_id: string; } } /** * SohaPay payment gateway helper. * * _Class hỗ trợ thanh toán qua SohaPay_ * */ declare class SohaPay { /** * SohaPay configSchema */ static configSchema: SimpleSchema; /** * SohaPay dataSchema */ static checkoutSchema: SimpleSchema; /** * SohaPay API Version */ static VERSION: string; /** * SohaPay English locale code */ static LOCALE_EN: string; /** * SohaPay Vietnamese locale code */ static LOCALE_VN: string; /** * SohaPay test configs * * _Config test thử SohaPay_ */ static TEST_CONFIG: object; /** * Instantiate a SohaPay checkout helper * * _Khởi tạo instance thanh toán SohaPay_ * * @param {Object} config check SohaPay.configSchema for data type requirements. <br> _Xem SohaPay.configSchema để biết yêu cầu kiểu dữ liệu._ * @return {void} */ constructor(config: sohapay.SohaPayConfig); /** * Build checkoutUrl to redirect to the payment gateway * * _Hàm xây dựng url để redirect qua SohaPay gateway, trong đó có tham số mã hóa (còn gọi là public key)_ * * @param {NganLuongCheckoutPayload} payload Object that contains needed data for the URL builder, refer to typeCheck object above. <br> _Đối tượng chứa các dữ liệu cần thiết để thiết lập đường dẫn._ * @return {Promise<URL>} buildCheckoutUrl promise */ buildCheckoutUrl(payload: sohapay.SohaPayCheckoutPayload): Promise<URL>; /** * Validate checkout payload against checkoutSchema. Throw ValidationErrors if invalid. * * _Kiểm tra tính hợp lệ của dữ liệu thanh toán dựa trên một cấu trúc dữ liệu cụ thể. Hiển thị lỗi nếu không hợp lệ._ * @param {SohaPayCheckoutPayload} payload */ validateCheckoutPayload(payload: sohapay.SohaPayCheckoutPayload): Promise<URL>; /** * default payload object * * _checkout payload mặc định_ * @type {SohaPayCheckoutPayload} */ checkoutPayloadDefaults: sohapay.SohaPayCheckoutPayload; /** * Verify return query string from SohaPay using enclosed secureCode string * * _Hàm thực hiện xác minh tính đúng đắn của các tham số trả về từ cổng thanh toán_ * * @param {Object} query Query data object from GET handler (`response.query`). <br> _Dữ liệu được trả về từ GET handler (`response.query`)_ * @return {Promise<sohapay.SohaPayReturnObject>} */ verifyReturnUrl(query: object): Promise<sohapay.SohaPayReturnObject>; } export { SohaPay }; declare namespace sohapay { export interface SohaPayConfig { /** * SohaPay merchant id */ merchantCode: string; /** * SohaPay payment gateway (API Url to send payment request) */ paymentGateway: string; /** * SohaPay merchant secret string */ secureSecret: string; } export interface SohaPayCheckoutPayload { /** * max: 16 */ language: string; /** * max: 34 */ orderId: string; /** * regEx: SimpleSchema.RegEx.Url * max: 24 */ customerEmail: string; /** * max: 15 */ customerPhone: string; /** * max: 255 */ returnUrl: string; /** * max: 9999999999 */ amount: number; /** * max: 1 */ paymentType: string; /** * max: 8 */ siteCode: string; /** * max: 255 */ transactionInfo: string; /** * max: 1 */ version: string; /** * optional: true * max: 2 */ locale?: string; /** * optional: true * max: 4 */ currency?: string; /** * optional: true * max: 64 */ billingCity?: string; /** * optional: true * max: 2 */ billingCountry?: string; /** * optional: true * max: 64 */ billingPostCode?: string; /** * optional: true * max: 64 */ billingStateProvince?: string; /** * optional: true * max: 64 */ billingStreet?: string; /** * optional: true * max: 255 */ deliveryAddress?: string; /** * optional: true * max: 255 */ deliveryCity?: string; /** * optional: true * max: 255 */ deliveryCountry?: string; /** * optional: true * max: 255 */ deliveryProvince?: string; /** * optional: true * max: 15 */ clientIp?: string; /** * optional: true * max: 40 */ transactionId?: string; /** * optional: true * max: 40 */ customerId?: string; } export interface SohaPayReturnObject { /** * whether the payment succeeded or not */ isSuccess: boolean; /** * */ message: string; /** * transaction id */ transactionId: string; /** * customer email */ orderEmail: string; /** * session token came from SohaPay */ orderSession: string; /** * amount paid by customer */ amount: string; /** * unique code assigned by SohaPay for merchant */ siteCode: string; /** * response status code of SohaPay */ responseCode: string; /** * description of the payment */ transactionInfo: string; /** * response message from SohaPay */ responseMessage: string; /** * checksum of the returned data, used to verify data integrity */ secureCode: string; /** * Error text returned from SohaPay Gateway * * e.g: 'Giao dịch thanh toán bị huỷ bỏ' */ error_text: string; /** * e.g: 'node-2018-01-19T131933.811Z' */ order_code: string; /** * e.g: 'dev@naustud.io' */ order_email: string; /** * e.g: 'd3bdef93fa01cd37f7e426fa25f5d1a0' */ order_session: string; /** * e.g: '90000' */ price: string; /** * e.g: 'test' */ site_code: string; /** * e.g: 'Thanh toan giay adidas' */ transaction_info: string; /** * e.g: FC5283C6B93C1D8F9A9329293DA38FFC3204FA6CE75661972419DAA6E5A1B7B5 */ secure_code: string; } } /** * VNPay payment gateway helper * * _Class hỗ trợ thanh toán qua VNPay_ * */ declare class VNPay { /** * VNPay configSchema * @type {SimpleSchema} */ static configSchema: SimpleSchema; /** * The schema is based on field data requirements from VNPay's dev document * * _Cấu trúc dữ liệu được dựa trên các yêu cầu của tài liệu VNPay_ * @type {SimpleSchema} */ static checkoutSchema: SimpleSchema; /** * VNPay API version */ static VERSION: string; /** * VNPay API command string for one time payment */ static COMMAND: string; /** * VNPay VND currency code */ static CURRENCY_VND: string; /** * English locale code */ static LOCALE_EN: string; /** * Vietnamese locale code */ static LOCALE_VN: string; /** * VNPay test configs * * _Config test thử VNPay_ */ static TEST_CONFIG: object; /** * Instantiate a VNPay checkout helper * * _Khởi tạo instance thanh toán VNPay_ * @param {Object} config check VNPay.configSchema for data type requirements <br> Xem VNPay.configSchema để biết yêu cầu kiểu dữ liệu * @return {void} */ constructor(config: vnpay.VNPayConfig); /** * Build checkoutUrl to redirect to the payment gateway * * _Hàm xây dựng url để redirect qua VNPay gateway, trong đó có tham số mã hóa (còn gọi là public key)_ * * @param {VNPayCheckoutPayload} payload Object that contains needed data for the URL builder, refer to typeCheck object above <br> Đối tượng chứa các dữ liệu cần thiết để thiết lập đường dẫn. * @return {Promise<URL>} buildCheckoutUrl promise */ buildCheckoutUrl(payload: vnpay.VNPayCheckoutPayload): Promise<URL>; /** * Validate checkout payload against specific schema. Throw ValidationErrors if invalid against checkoutSchema * * _Kiểm tra tính hợp lệ của dữ liệu thanh toán dựa trên một cấu trúc dữ liệu cụ thể. Hiển thị lỗi nếu không hợp lệ với checkoutSchema._ * * @param {VNPayCheckoutPayload} payload */ validateCheckoutPayload(payload: vnpay.VNPayCheckoutPayload): void; /** * default payload object * * _checkout payload mặc định_ * @type {VNPayCheckoutPayload} */ checkoutPayloadDefaults: vnpay.VNPayCheckoutPayload; /** * Verify return query string from VNPay using enclosed vnp_SecureHash string * * _Hàm thực hiện xác minh tính đúng đắn của các tham số trả về từ cổng thanh toán_ * * @param {Object} query Query data object from GET handler (`response.query`) <br> Dữ liệu được trả về từ GET handler (`response.query`) * @return {Promise<VNPayReturnObject>} */ verifyReturnUrl(query: object): Promise<vnpay.VNPayReturnObject>; } export { VNPay }; declare namespace vnpay { export interface VNPayConfig { /** * VNPay payment Gateway (API Url to send payment request) */ paymentGateway: string; /** * VNPay merchant code */ merchant: string; /** * VNPay merchant secure code */ secureSecret: string; } export interface VNPayCheckoutPayload { /** * optional: true */ createdDate?: string; /** * The pay amount, Integer, max: 9999999999 */ amount: number; /** * max: 16 */ clientIp: string; /** * allowedValues: ['VND'] */ currency: string; /** * optional: true, max: 255 */ billingCity?: string; /** * optional: true, max: 255 */ billingCountry?: string; /** * optional: true, max: 255 */ billingPostCode?: string; /** * optional: true, max: 255 */ billingStateProvince?: string; /** * optional: true, max: 255 */ billingStreet?: string; /** * optional: true, max: 255, regEx: SimpleSchema.RegEx.Email */ customerEmail?: string; /** * optional: true, max: 255 */ customerId?: string; /** * optional: true, max: 255 */ customerPhone?: string; /** * optional: true, max: 255 */ deliveryAddress?: string; /** * optional: true, max: 255 */ deliveryCity?: string; /** * optional: true, max: 255 */ deliveryCountry?: string; /** * optional: true, max: 255 */ deliveryProvince?: string; /** * optional: true, max: 50 */ bankCode?: string; /** * allowedValues: ['vn', 'en'] */ locale: string; /** * max: 34 */ orderId: string; /** * max: 255 */ orderInfo: string; /** * max: 40 */ orderType: string; /** * max: 255 */ returnUrl: string; /** * max: 40 */ transactionId: string; /** * max: 32 */ vnpSecretKey: string; /** * max: 16 */ vnpMerchant: string; /** * max: 16 */ vnpCommand: string; /** * max: 2 */ vnpVersion: string; /** * regEx: SimpleSchema.RegEx.Url */ paymentGateway: string; /** * */ merchant: string; /** * */ secureSecret: string; } export interface VNPayReturnObject { /** * whether the payment succeeded or not */ isSuccess: string; /** * Approve or error message based on response code */ message: string; /** * merchant ID, should be same with checkout request */ merchant: string; /** * merchant's transaction ID, should be same with checkout request */ transactionId: string; /** * amount paid by customer, already divided by 100 */ amount: number; /** * order info, should be same with checkout request */ orderInfo: string; /** * response code, payment has errors if it is non-zero */ responseCode: string; /** * bank code of the bank where payment was occurred */ bankCode: string; /** * bank transaction ID, used to look up at Bank's side */ bankTranNo: string; /** * type of card */ cardType: string; /** * date when transaction occurred */ payDate: string; /** * Gateway's own transaction ID, used to look up at Gateway's side */ gatewayTransactionNo: string; /** * checksum of the returned data, used to verify data integrity */ secureHash: string; /** * e.g: COCOSIN */ vnp_TmnCode: string; /** * e.g: node-2018-01-15T10:04:36.540Z */ vnp_TxnRef: string; /** * e.g: 90000000 */ vnp_Amount: string; /** * e.g: Thanh toan giay adidas */ vnp_OrderInfo: string; /** * e.g: 00 */ vnp_ResponseCode: string; /** * e.g: NCB */ vnp_BankCode: string; /** * e.g: 20180115170515 */ vnp_BankTranNo: string; /** * e.g: ATM */ vnp_CardType: string; /** * e.g: 20180115170716 */ vnp_PayDate: string; /** * e.g: 13008888 */ vnp_TransactionNo: string; /** * e.g: 115ad37de7ae4d28eb819ca3d3d85b20 */ vnp_SecureHash: string; } }
the_stack
import { config } from './config'; import { Task } from './Task'; import { worklet } from './worklet'; // Utilities import { assert } from '../utilities'; // Types import { TVoidable } from '../types'; import { IThread } from './types'; /** * Manage the task queue and interact with the RPC's */ export class TaskManager { private static walkTaskArgs = ( obj: any[], walker: (value: Task, i: string, obj: any[]) => void ): void => { // tslint:disable-next-line:forin for (const i in obj) { const value = obj[i]; if (typeof value === 'object' && value) { if (value instanceof Task) { walker(value, i, obj); } } } }; public workers: IThread[] = []; private size: number; private worklets: string[] = []; private tasks: { [id: number]: Task } = {}; private results: { [id: number]: any } = {}; private workerTaskAssignments: { [id: number]: any } = {}; /** * Sets various configuration options * * @param size Maximum amount of threads to use */ constructor(size?: number) { this.size = size || config.THREAD_POOL_SIZE; } /** * Execute a task * * @param task Task to execute * @param taskName Name of the task to execute * @param args Any arguments that have been passed along with the task (including dependencies) */ public exec(task: Task, taskName: string, args: any): void { const worker = this.getTaskWorker(taskName, args) || this.getNextWorker(); this.workerTaskAssignments[task.id] = worker.id; this.tasks[task.id] = task; task.state = 'scheduled'; worker.isPending++; const resultController: any = (this.results[task.id] = { isCancelled: false, // Has the task been cancelled? isCompleted: false, // Has the task been marked as completed by its worker? isFulfilled: false, // Has the task result been obtained from the worker? isPending: true, // Is the task waiting to be sent to a worker? isRequested: false, // Has the task result been requested from the worker? }); resultController.result = new Promise((resolve, reject): void => { resultController[0] = resolve; resultController[1] = reject; }); const tasksToResolveIndices: any[] = []; const tasksToResolve: Array<Promise<any>> = []; const tasks: Task[] = []; // TODO: it would be better to serialize tasks to their $$TASK_IDENTIFIER // String representation here. However doing so cannot mutate args in-place, // as it would reveal the identifier secret. TaskManager.walkTaskArgs(args, (value: any) => { if (this.getWorkerForTask(value.id) !== worker) { const controller = this.results[value.id]; console.warn( `ThreadPool -> Task#${value.id} passed to ${taskName}[${ task.id }] was invoked in a different context. The result will be ${ controller.isFulfilled ? '' : 'materialized & ' }transferred.` ); tasksToResolveIndices.push(tasks.length); tasksToResolve.push(controller.result); } tasks.push(value); }); // also wait for the worker to be loaded (async module resolution, etc) tasksToResolve.push(worker.ready); Promise.all(tasksToResolve) .then(taskValues => { resultController.isPending = false; if (resultController.isCancelled) { return undefined; } for (let i = tasks.length; i--; ) { const activeTask = tasks[i]; activeTask.$$TASK_IDENTIFIER = `${config.UNIQUE_ID}:${activeTask.id}`; } for (let i = tasksToResolveIndices.length; i--; ) { const activeTask = tasks[tasksToResolveIndices[i]]; activeTask.$$TASK_RESULT = taskValues[i]; } let options = 0; // If we need a result right away, mark the task as requiring a return // value. This handles common cases like `await casket.addTask().result`. if (resultController.isRequested) { options |= 1; } worker.call('$$task', [task.id, options, taskName].concat(args)); }) .then(() => { for (const activeTask of tasks) { delete activeTask.$$TASK_IDENTIFIER; delete activeTask.$$TASK_RESULT; } }); } /** * Add a compute module to the task pool * * @param code Compute module source code */ public addWorklet(code: string): Promise<Task[]> { this.worklets.push(code); return Promise.all(this.workers.map(worker => worker.call('$$eval', [code]))); } /** * Cancel a task * * Cancellation isn't guaranteed, however cancellation of a task * known to have been already completed will return `false`. * * @param taskId Id of task to cancel */ public cancelTask(taskId: any): TVoidable<boolean> { const task: any = this.tasks[taskId]; const resultController = this.results[taskId]; if (resultController.isCompleted || task.state === 'completed') { return false; } task.state = 'cancelled'; resultController.isCancelled = true; if (!resultController.isPending) { const workerId = this.workerTaskAssignments[taskId]; const worker = this.getWorker(workerId); if (worker) { worker.call('$$cancel', [taskId]); } } } /** * Get a task result * * @param taskId Id of task to get result of */ public getTaskResult(taskId: any): any { const resultController = this.results[taskId]; assert(resultController, `ThreadPool -> Unknown result for Task: ${taskId}`); if (resultController.isPending === true) { resultController.isRequested = true; } else if (resultController.isFulfilled === false && resultController.isRequested === false) { resultController.isRequested = true; const workerId = this.workerTaskAssignments[taskId]; const worker = this.getWorker(workerId); if (worker) { worker.call('$$getResult', [taskId]); } } return resultController.result; } /** * Status of the thread (communicates with the individual thread) * * @param worker Active thread * @param statuses Any statusses to report */ private statusReceived(worker: any, statuses: any): void { for (const status of statuses) { const id = status[0]; const task = this.tasks[id]; const resultController = this.results[id]; if (task.state === 'scheduled') { const workerId = this.workerTaskAssignments[id]; const scheduledWorker = this.getWorker(workerId); this.freeWorkerTask(scheduledWorker); } // current only a fulfillment triggers status updates, so we assume an // update fulfills its task: task.state = 'completed'; resultController.isCompleted = true; // [id,status,data] denotes a task with an eager return value // (forced | numbers | booleans): if (status.length === 3 && status[2]) { task.state = 'fulfilled'; // resolve | reject the status resultController.isFulfilled = true; resultController[status[1]](status[2]); } } } /** * Mark a thread as free for new computation * * @param worker Thread to mark as free */ private freeWorkerTask(worker: any): void { if (--worker.isPending === 0) { // TODO: the worker now has no pending tasks. // Should we reallocate any pending idempotent tasks from other workers in // the pool? This may be impossible since tasks are scheduled by we don't // know their instantaneous queuing status at any given point in time. } } /** * Get an active thread by id * * @param id Id of the thread to get */ private getWorker(id: any): TVoidable<IThread> { for (const worker of this.workers) { if (worker.id === id) { return worker; } } } /** * Add a thread to the thread pool */ private addWorker(): IThread { const worker: any = new Worker(worklet); worker.url = worklet; worker.id = config.ID_COUNT++; worker.isPending = 0; const callbacks: any = {}; worker.onmessage = (event: MessageEvent): any => { const [type, id, data] = event.data; const typeReceived = `${type}Received`; if ((this as any)[typeReceived]) { return (this as any)[typeReceived](worker, data); } callbacks[id][type](data); delete callbacks[id]; }; let casket: any[] = []; const resolved = Promise.resolve(); function process(): void { worker.postMessage(casket); casket = []; } worker.call = (method: string, params: any[]): Promise<void> => // tslint:disable-next-line:only-arrow-functions new Promise(function(): void { const id = config.ID_COUNT++; callbacks[id] = arguments; if (casket.push([method, id].concat(params)) === 1) { resolved.then(process); } }); this.workers.push(worker); worker.ready = worker.call('$$init', [config.UNIQUE_ID, this.worklets]); return worker; } /** * Get the most suitable worker for this task (keep dependencies in mind) * * @param taskId Id of the task */ private getWorkerForTask(taskId: number): TVoidable<IThread> { const workerId = this.workerTaskAssignments[taskId]; for (const worker of this.workers) { if (worker.id === workerId) { return worker; } } } /** * Get and collect any dependencies of a task * * @param args Task dependencies */ private getTaskDependencies(args: any[]): Task[] { const tasks: Task[] = []; TaskManager.walkTaskArgs(args, (task: Task) => { tasks.push(task); }); return tasks; } /** * Get the most suitable worker for this task (keep dependencies in mind) * * @param taskName Name of the task * @param args Any arguments that have been passed along with the task (including dependencies) */ private getTaskWorker(taskName: string, args: any[]): TVoidable<IThread> { const tasks = this.getTaskDependencies(args); const usage: any = {}; let highest = 0; let bestWorkerId = null; for (const task of tasks) { const workerId = this.workerTaskAssignments[task.id]; const current = (usage[workerId] = (usage[workerId] || 0) + 1); if (current > highest) { highest = current; bestWorkerId = workerId; } } if (bestWorkerId !== null) { return this.getWorker(bestWorkerId); } } /** * If no suitable worker for the task was found get the next available one */ private getNextWorker(): IThread { const size = this.workers.length; if (size === 0) { return this.addWorker(); } let bestWorker = this.workers[0]; for (let i = 1; i < size; i++) { const worker = this.workers[i]; if (worker.isPending < bestWorker.isPending) { bestWorker = worker; } } if (bestWorker.isPending && size < this.size) { return this.addWorker(); } return bestWorker; } }
the_stack
const Table = (function () { "use strict"; let viewModel = null; let showExtra = false; const column = function (id, label, columnClass) { return { id: id, label: label, class: columnClass }; }; const visibilityBindings = [ ["#lineBreak", function () { return viewModel.hasData; }], ["#response", function () { return viewModel.hasData; }], ["#status", function () { return viewModel.status; }], [".extraCol", function () { return showExtra; }], ["#clearButton", function () { return viewModel.hasData; }], ["#copyButton", function () { return viewModel.hasData; }] ]; // Adjusts response under our lineBreak function positionResponse() { const responseTop = $("#lineBreak")[0].offsetTop + $("#lineBreak").height(); $("#response").css("top", responseTop + 15); } function toggleCollapse(object) { $(".collapsibleElement", $(object).parents(".collapsibleWrapper")).toggle(); positionResponse(); } // Wraps an element into a collapsible pane with a title function makeResizablePane(id, title, visibility) { const pane = $("#" + id); if (pane.hasClass("collapsibleElement")) { return; } const hidden = pane.hasClass("hiddenElement"); pane.addClass("collapsibleElement"); const wrap = $(document.createElement("div")); wrap.addClass("collapsibleWrapper"); if (visibility) { wrap.attr("id", id + "Wrapper"); visibilityBindings.push(["#" + id + "Wrapper", visibility]); } const header = $(document.createElement("div")); header.addClass("sectionHeader"); header.bind("click", function () { toggleCollapse(this); }); header.text(title); const moreSpan = $(document.createElement("span")); moreSpan.addClass("collapsibleSwitch"); moreSpan.addClass("collapsibleElement"); moreSpan.html("+&nbsp;"); const lessSpan = $(document.createElement("span")); lessSpan.addClass("collapsibleSwitch"); lessSpan.addClass("collapsibleElement"); lessSpan.html("&ndash;&nbsp;"); // Now that everything is built, put it together pane.wrap(wrap); pane.before(header); header.append(moreSpan); header.append(lessSpan); if (hidden) { lessSpan.hide(); } else { moreSpan.hide(); } } function makeVisible(id, visible) { if (visible) { $(id).removeClass("hiddenElement"); } else { $(id).addClass("hiddenElement"); } } function makeSummaryTable(summaryName, rows, tag) { const summaryList = $(summaryName); if (summaryList) { summaryList.addClass("summaryList"); for (let i = 0; i < rows.length; i++) { const id = rows[i].header + tag; const row = document.createElement("tr"); if (row !== null) { row.id = id; summaryList.append(row); // Must happen before we append cells to appease IE7 const headerCell = $(row.insertCell(-1)); if (headerCell) { if (rows[i].url) { headerCell.html(rows[i].url); } else { headerCell.text(rows[i].label); } headerCell.addClass("summaryHeader"); } const valCell = $(row.insertCell(-1)); if (valCell) { valCell.attr("id", id + "Val"); } makeVisible("#" + id, false); } } } } function setArrows(table, colName, sortOrder) { $("#" + table + " .tableHeader .downArrow").addClass("hiddenElement"); $("#" + table + " .tableHeader .upArrow").addClass("hiddenElement"); if (sortOrder === 1) { $("#" + table + " .tableHeader #" + colName + " .downArrow").removeClass("hiddenElement"); } else { $("#" + table + " .tableHeader #" + colName + " .upArrow").removeClass("hiddenElement"); } } function setRowValue(row, type) { const headerVal = $("#" + row.header + type + "Val"); if (headerVal) { if (row.value) { if (row.valueUrl) { headerVal.html(row.valueUrl); } else { headerVal.text(row.value); } makeVisible("#" + row.header + type, true); } else { headerVal.text(null); makeVisible("#" + row.header + type, false); } } } function appendCell(row, text, html, cellClass) { const cell = $(row.insertCell(-1)); if (text) { cell.text(text); } if (html) { cell.html(html); } if (cellClass) { cell.addClass(cellClass); } } // Restores table to empty state so we can repopulate it function emptyTableUI(id) { $("#" + id + " tbody tr").remove(); // Remove the rows $("#" + id + " th").removeClass("emptyColumn"); // Restore header visibility $("#" + id + " th").removeClass("hiddenElement"); // Restore header visibility } function recalculateVisibility() { for (let i = 0; i < visibilityBindings.length; i++) { makeVisible(visibilityBindings[i][0], visibilityBindings[i][1]()); } positionResponse(); } function hideEmptyColumns(id) { $("#" + id + " th").each(function (i) { let keep = 0; // Find a child cell which has data const children = $(this).parents("table").find("tr td:nth-child(" + (i + 1).toString() + ")"); children.each(function () { if (this.innerHTML !== "") { keep++; } }); if (keep === 0) { $(this).addClass("emptyColumn"); children.addClass("emptyColumn"); } else { $(this).removeClass("emptyColumn"); children.removeClass("emptyColumn"); } }); } // Rebuilds content and recalculates what sections should be displayed function rebuildSections(_viewModel) { viewModel = _viewModel; let i; let row; // Summary for (i = 0; i < viewModel.summary.summaryRows.length; i++) { setRowValue(viewModel.summary.summaryRows[i], "SUM"); } // Received emptyTableUI("receivedHeaders"); for (i = 0; i < viewModel.receivedHeaders.receivedRows.length; i++) { row = document.createElement("tr"); $("#receivedHeaders").append(row); // Must happen before we append cells to appease IE7 appendCell(row, viewModel.receivedHeaders.receivedRows[i].hop, null, null); appendCell(row, viewModel.receivedHeaders.receivedRows[i].from, null, null); appendCell(row, viewModel.receivedHeaders.receivedRows[i].by, null, null); appendCell(row, viewModel.receivedHeaders.receivedRows[i].date, null, null); let labelClass = "hotBarLabel"; if (viewModel.receivedHeaders.receivedRows[i].delaySort < 0) { labelClass += " negativeCell"; } const hotBar = "<div class='hotBarContainer'>" + " <div class='" + labelClass + "'>" + viewModel.receivedHeaders.receivedRows[i].delay + "</div>" + " <div class='hotBarBar' style='width:" + viewModel.receivedHeaders.receivedRows[i].percent + "%'></div>" + "</div>"; appendCell(row, null, hotBar, "hotBarCell"); appendCell(row, viewModel.receivedHeaders.receivedRows[i].with, null, null); appendCell(row, viewModel.receivedHeaders.receivedRows[i].id, null, "extraCol"); appendCell(row, viewModel.receivedHeaders.receivedRows[i].for, null, "extraCol"); appendCell(row, viewModel.receivedHeaders.receivedRows[i].via, null, "extraCol"); } // Calculate heights for the hotbar cells (progress bars in Delay column) // Not clear why we need to do this $(".hotBarCell").each(function () { $(this).find(".hotBarContainer").height($(this).height()); }); $("#receivedHeaders tbody tr:odd").addClass("oddRow"); hideEmptyColumns("receivedHeaders"); // Forefront AntiSpam Report for (i = 0; i < viewModel.forefrontAntiSpamReport.forefrontAntiSpamRows.length; i++) { setRowValue(viewModel.forefrontAntiSpamReport.forefrontAntiSpamRows[i], "FFAS"); } // AntiSpam Report for (i = 0; i < viewModel.antiSpamReport.antiSpamRows.length; i++) { setRowValue(viewModel.antiSpamReport.antiSpamRows[i], "AS"); } // Other emptyTableUI("otherHeaders"); for (i = 0; i < viewModel.otherHeaders.otherRows.length; i++) { row = document.createElement("tr"); $("#otherHeaders").append(row); // Must happen before we append cells to appease IE7 appendCell(row, viewModel.otherHeaders.otherRows[i].number, null, null); appendCell(row, viewModel.otherHeaders.otherRows[i].header, viewModel.otherHeaders.otherRows[i].url, null); appendCell(row, viewModel.otherHeaders.otherRows[i].value, null, "allowBreak"); } $("#otherHeaders tbody tr:odd").addClass("oddRow"); // Original headers $("#originalHeaders").text(viewModel.originalHeaders); recalculateVisibility(); } function makeSortableColumn(table, id) { const header = $("#" + id); header.bind("click", function () { viewModel[table].doSort(id); setArrows(viewModel[table].tableName, viewModel[table].sortColumn, viewModel[table].sortOrder); rebuildSections(viewModel); }); const downSpan = $(document.createElement("span")); downSpan.addClass("downArrow"); downSpan.addClass("hiddenElement"); downSpan.html("&darr;"); const upSpan = $(document.createElement("span")); upSpan.addClass("upArrow"); upSpan.addClass("hiddenElement"); upSpan.html("&uarr;"); // Now that everything is built, put it together header.append(downSpan); header.append(upSpan); } function addColumns(tableName, columns) { const tableHeader = $(document.createElement("thead")); if (tableHeader !== null) { $("#" + tableName).append(tableHeader); const headerRow = $(document.createElement("tr")); if (headerRow !== null) { headerRow.addClass("tableHeader"); tableHeader.append(headerRow); // Must happen before we append cells to appease IE7 for (let i = 0; i < columns.length; i++) { const headerCell = $(document.createElement("th")); if (headerCell !== null) { headerCell.attr("id", columns[i].id); headerCell.text(columns[i].label); if (columns[i].class !== null) { headerCell.addClass(columns[i].class); } headerRow.append(headerCell); } makeSortableColumn(tableName, columns[i].id); } } } } // Wraps a table into a collapsible table with a title function makeResizableTable(id, title, visibility) { const pane = $("#" + id); if (pane.hasClass("collapsibleElement")) { return; } pane.addClass("collapsibleElement"); const wrap = $(document.createElement("div")); wrap.addClass("collapsibleWrapper"); if (visibility) { wrap.attr("id", id + "Wrapper"); visibilityBindings.push(["#" + id + "Wrapper", visibility]); } const header = $(document.createElement("div")); header.addClass("tableCaption"); header.bind("click", function () { toggleCollapse(this); }); header.text(title); const moreSpan = $(document.createElement("span")); moreSpan.addClass("collapsibleSwitch"); moreSpan.html("+&nbsp;"); header.append(moreSpan); header.addClass("collapsibleElement"); const captionDiv = $(document.createElement("div")); captionDiv.addClass("tableCaption"); captionDiv.bind("click", function () { toggleCollapse(this); }); captionDiv.text(title); const lessSpan = $(document.createElement("span")); lessSpan.addClass("collapsibleSwitch"); lessSpan.html("&ndash;&nbsp;"); captionDiv.append(lessSpan); const tbody = $(document.createElement("tbody")); // Now that everything is built, put it together pane.wrap(wrap); pane.before(header); pane.append(tbody); const caption = $(pane[0].createCaption()); caption.prepend(captionDiv); header.hide(); } function hideExtraColumns() { showExtra = false; $("#leftArrow").addClass("hiddenElement"); $("#rightArrow").removeClass("hiddenElement"); } function showExtraColumns() { showExtra = true; $("#rightArrow").addClass("hiddenElement"); $("#leftArrow").removeClass("hiddenElement"); } function toggleExtraColumns() { if (showExtra) { hideExtraColumns(); } else { showExtraColumns(); } recalculateVisibility(); } function resetArrows() { setArrows("receivedHeaders", "hop", 1); setArrows("otherHeaders", "number", 1); } // Initializes the UI with a viewModel function initializeTableUI(_viewModel) { viewModel = _viewModel; // Headers makeResizablePane("originalHeaders", mhaStrings.mhaOriginalHeaders, function () { return viewModel.originalHeaders.length; }); $(".collapsibleElement", $("#originalHeaders").parents(".collapsibleWrapper")).toggle(); // Summary makeResizablePane("summary", mhaStrings.mhaSummary, function () { return viewModel.summary.exists(); }); makeSummaryTable("#summary", viewModel.summary.summaryRows, "SUM"); // Received makeResizableTable("receivedHeaders", mhaStrings.mhaReceivedHeaders, function () { return viewModel.receivedHeaders.exists(); }); const receivedColumns = [ column("hop", mhaStrings.mhaReceivedHop, null), column("from", mhaStrings.mhaReceivedSubmittingHost, null), column("by", mhaStrings.mhaReceivedReceivingHost, null), column("date", mhaStrings.mhaReceivedTime, null), column("delay", mhaStrings.mhaReceivedDelay, null), column("with", mhaStrings.mhaReceivedType, null), column("id", mhaStrings.mhaReceivedId, "extraCol"), column("for", mhaStrings.mhaReceivedFor, "extraCol"), column("via", mhaStrings.mhaReceivedVia, "extraCol") ]; addColumns(viewModel.receivedHeaders.tableName, receivedColumns); const withColumn = $("#receivedHeaders #with"); if (withColumn !== null) { const leftSpan = $(document.createElement("span")); leftSpan.attr("id", "leftArrow"); leftSpan.addClass("collapsibleArrow"); leftSpan.addClass("hiddenElement"); leftSpan.html("&lArr;"); const rightSpan = $(document.createElement("span")); rightSpan.attr("id", "rightArrow"); rightSpan.addClass("collapsibleArrow"); rightSpan.html("&rArr;"); withColumn.append(leftSpan); withColumn.append(rightSpan); } $("#receivedHeaders .collapsibleArrow").bind("click", function (eventObject) { toggleExtraColumns(); eventObject.stopPropagation(); }); // FFAS makeResizablePane("forefrontAntiSpamReport", mhaStrings.mhaForefrontAntiSpamReport, function () { return viewModel.forefrontAntiSpamReport.exists(); }); makeSummaryTable("#forefrontAntiSpamReport", viewModel.forefrontAntiSpamReport.forefrontAntiSpamRows, "FFAS"); // AntiSpam makeResizablePane("antiSpamReport", mhaStrings.mhaAntiSpamReport, function () { return viewModel.antiSpamReport.exists(); }); makeSummaryTable("#antiSpamReport", viewModel.antiSpamReport.antiSpamRows, "AS"); // Other makeResizableTable("otherHeaders", mhaStrings.mhaOtherHeaders, function () { return viewModel.otherHeaders.otherRows.length; }); const otherColumns = [ column("number", mhaStrings.mhaNumber, null), column("header", mhaStrings.mhaHeader, null), column("value", mhaStrings.mhaValue, null) ]; addColumns(viewModel.otherHeaders.tableName, otherColumns); resetArrows(); rebuildSections(viewModel); } // Rebuilds the UI with a new viewModel function rebuildTables(_viewModel) { viewModel = _viewModel; rebuildSections(viewModel); hideExtraColumns(); } return { initializeTableUI: initializeTableUI, // Initialize UI with an empty viewModel makeResizablePane: makeResizablePane, rebuildSections: rebuildSections, // Repopulate the UI with the current viewModel rebuildTables: rebuildTables, // Used by Standalone.js and Default.js to rebuild with new viewModel recalculateVisibility: recalculateVisibility, // Recompute visibility with the current viewModel. Does not repopulate. resetArrows: resetArrows }; })();
the_stack
import * as t from 'io-ts' import { Discojs, FolderIdsEnum, SortOrdersEnum, UserSortEnum } from '.' import { AddToFolderResponseIO, AddToWantlistResponseIO, CustomFieldsResponseIO, FolderReleasesResponseIO, FoldersResponseIO, UserListItemsResponseIO, UserListsResponseIO, UserSubmissionsResponseIO, UserContributionsResponseIO, WantlistResponseIO, } from '../models/api' import { CollectionValueIO, FolderIO } from '../models/folder' import { IdentityIO, UserIO } from '../models/user' declare const client: Discojs const rodneyfool = 'rodneyfool' const pagination = { page: 1, perPage: 1 } describe('User', () => { describe('Identity', () => { it('getIdentity', async () => { const apiResponse = await client.getIdentity() expect(t.exact(IdentityIO).is(apiResponse)).toBeTruthy() }) }) describe('Profile', () => { it('getProfileForUser', async () => { const apiResponse = await client.getProfileForUser(rodneyfool) expect(t.exact(UserIO).is(apiResponse)).toBeTruthy() }) it('getProfile', async () => { const apiResponse = await client.getProfile() expect(t.exact(UserIO).is(apiResponse)).toBeTruthy() }) it('editProfile', async () => { const input = { name: Math.random().toString(), homePage: 'https://discojs', location: `Planet ${Math.random()}`, profile: 'Test', } const apiResponse = await client.editProfile(input) expect(t.exact(UserIO).is(apiResponse)).toBeTruthy() }) }) describe('Submissions', () => { it('getSubmissionsForUser', async () => { const apiResponse = await client.getSubmissionsForUser(rodneyfool) expect(t.exact(UserSubmissionsResponseIO).is(apiResponse)).toBeTruthy() }) it('getSubmissionsForUser - with pagination', async () => { const apiResponse = await client.getSubmissionsForUser(rodneyfool, pagination) expect(apiResponse.pagination).toHaveProperty('page', pagination.page) expect(apiResponse.pagination).toHaveProperty('per_page', pagination.perPage) }) it('getSubmissions', async () => { const apiResponse = await client.getSubmissions(pagination) expect(t.exact(UserSubmissionsResponseIO).is(apiResponse)).toBeTruthy() }) }) describe('Contributions', () => { const username = 'shooezgirl' it('getContributionsForUser', async () => { const apiResponse = await client.getContributionsForUser(username) expect(t.exact(UserContributionsResponseIO).is(apiResponse)).toBeTruthy() }) it('getContributionsForUser - with sort', async () => { const by = UserSortEnum.TITLE const firstApiResponse = await client.getContributionsForUser(username, { by, order: SortOrdersEnum.ASC }) // Check if there are at least 2 contributions. expect(firstApiResponse.contributions.length).toBeGreaterThanOrEqual(2) const firstId = firstApiResponse.contributions[0].id const secondApiResponse = await client.getContributionsForUser(username, { by, order: SortOrdersEnum.DESC }) const secondId = secondApiResponse.contributions[0].id expect(firstId).not.toEqual(secondId) }) it('getSubmissionsForUser - with pagination', async () => { const apiResponse = await client.getContributionsForUser(username, undefined, pagination) expect(apiResponse.pagination).toHaveProperty('page', pagination.page) expect(apiResponse.pagination).toHaveProperty('per_page', pagination.perPage) }) it('getContributions', async () => { const apiResponse = await client.getContributions() expect(t.exact(UserContributionsResponseIO).is(apiResponse)).toBeTruthy() }) }) describe('Collection', () => { let folderId: number let instanceId: number it('listFoldersForUser', async () => { const apiResponse = await client.listFoldersForUser(rodneyfool) expect(t.exact(FoldersResponseIO).is(apiResponse)).toBeTruthy() }) it('listFolders', async () => { const apiResponse = await client.listFolders() expect(t.exact(FoldersResponseIO).is(apiResponse)).toBeTruthy() }) it('createFolder', async () => { const name = `Test-${Math.random()}` const apiResponse = await client.createFolder(name) expect(t.exact(FolderIO).is(apiResponse)).toBeTruthy() expect(apiResponse).toHaveProperty('name', name) // Set folderId for upcoming tests folderId = apiResponse.id }) it('getFolderForUser', async () => { const apiResponse = await client.getFolderForUser(rodneyfool, FolderIdsEnum.ALL) expect(t.exact(FolderIO).is(apiResponse)).toBeTruthy() }) it('getFolder', async () => { const apiResponse = await client.getFolder(folderId) expect(t.exact(FolderIO).is(apiResponse)).toBeTruthy() }) it('editFolder', async () => { const name = `Another-test-${Math.random()}` const apiResponse = await client.editFolder(folderId, name) expect(t.exact(FolderIO).is(apiResponse)).toBeTruthy() expect(apiResponse).toHaveProperty('name', name) }) it('deleteFolder', async () => { const apiResponse = await client.deleteFolder(folderId) // Empty response has 0 keys expect(Object.keys(apiResponse).length).toEqual(0) }) it('listItemsByReleaseForUser', async () => { const username = 'susan.salkeld' const releaseId = 7781525 const apiResponse = await client.listItemsByReleaseForUser(username, releaseId) expect(t.exact(FolderReleasesResponseIO).is(apiResponse)).toBeTruthy() }) it('listItemsByReleaseForUser - with pagination', async () => { const username = 'susan.salkeld' const releaseId = 7781525 const apiResponse = await client.listItemsByReleaseForUser(username, releaseId, pagination) expect(apiResponse.pagination).toHaveProperty('page', pagination.page) expect(apiResponse.pagination).toHaveProperty('per_page', pagination.perPage) }) // TODO: If folder_id is not 0, or the collection has been made private by its owner, authentication as the collection owner is required. it('listItemsInFolderForUser', async () => { const apiResponse = await client.listItemsInFolderForUser(rodneyfool, FolderIdsEnum.ALL) expect(t.exact(FolderReleasesResponseIO).is(apiResponse)).toBeTruthy() }) it('listItemsInFolderForUser - with sort', async () => { const by = UserSortEnum.TITLE const firstApiResponse = await client.listItemsInFolderForUser(rodneyfool, FolderIdsEnum.ALL, { by, order: SortOrdersEnum.ASC, }) // Check if there are at least 2 releases. expect(firstApiResponse.releases.length).toBeGreaterThanOrEqual(2) const firstId = firstApiResponse.releases[0].id const secondApiResponse = await client.listItemsInFolderForUser(rodneyfool, FolderIdsEnum.ALL, { by, order: SortOrdersEnum.DESC, }) const secondId = secondApiResponse.releases[0].id expect(firstId).not.toEqual(secondId) }) it('listItemsInFolderForUser - with pagination', async () => { const apiResponse = await client.listItemsInFolderForUser(rodneyfool, FolderIdsEnum.ALL, undefined, pagination) expect(apiResponse.pagination).toHaveProperty('page', pagination.page) expect(apiResponse.pagination).toHaveProperty('per_page', pagination.perPage) }) it('addReleaseToFolder', async () => { const releaseId = 3124045 const apiResponse = await client.addReleaseToFolder(releaseId) expect(t.exact(AddToFolderResponseIO).is(apiResponse)).toBeTruthy() // Set instanceId for upcoming tests instanceId = apiResponse.instance_id }) // TODO: Add listItemsByRelease it('editReleaseInstanceRating', async () => { const releaseId = 3124045 const apiResponse = await client.editReleaseInstanceRating(FolderIdsEnum.UNCATEGORIZED, releaseId, instanceId, 4) // Empty response has 0 keys expect(Object.keys(apiResponse).length).toEqual(0) }) // TODO: Cannot test moveReleaseInstanceToFolder because we cannot create folder via API // wrong it('deleteReleaseInstanceFromFolder', async () => { const releaseId = 3124045 const apiResponse = await client.deleteReleaseInstanceFromFolder( FolderIdsEnum.UNCATEGORIZED, releaseId, instanceId, ) // Empty response has 0 keys expect(Object.keys(apiResponse).length).toEqual(0) }) it('listCustomFieldsForUser', async () => { const apiResponse = await client.listCustomFieldsForUser(rodneyfool) expect(t.exact(CustomFieldsResponseIO).is(apiResponse)).toBeTruthy() }) it('listCustomFields', async () => { const apiResponse = await client.listCustomFields() expect(t.exact(CustomFieldsResponseIO).is(apiResponse)).toBeTruthy() }) it('getCollectionValue', async () => { const apiResponse = await client.getCollectionValue() expect(t.exact(CollectionValueIO).is(apiResponse)).toBeTruthy() }) }) describe('Wantlist', () => { const releaseId = 3124045 it('getWantlistForUser', async () => { const apiResponse = await client.getWantlistForUser(rodneyfool) expect(t.exact(WantlistResponseIO).is(apiResponse)).toBeTruthy() }) it('getWantlistForUser - with pagination', async () => { const apiResponse = await client.getWantlistForUser(rodneyfool, pagination) expect(apiResponse.pagination).toHaveProperty('page', pagination.page) expect(apiResponse.pagination).toHaveProperty('per_page', pagination.perPage) }) it('getWantlist', async () => { const apiResponse = await client.getWantlist() expect(t.exact(WantlistResponseIO).is(apiResponse)).toBeTruthy() }) it('addToWantlist', async () => { const notes = `Test-${Math.random()}` const apiResponse = await client.addToWantlist(releaseId, notes, 4) expect(t.exact(AddToWantlistResponseIO).is(apiResponse)).toBeTruthy() }) it('removeFromWantlist', async () => { const apiResponse = await client.removeFromWantlist(releaseId) // Empty response has 0 keys expect(Object.keys(apiResponse).length).toEqual(0) }) }) describe('Lists', () => { it('getListsForUser', async () => { const apiResponse = await client.getListsForUser(rodneyfool) expect(t.exact(UserListsResponseIO).is(apiResponse)).toBeTruthy() }) it('getListsForUser - with pagination', async () => { const apiResponse = await client.getListsForUser(rodneyfool, pagination) expect(apiResponse.pagination).toHaveProperty('page', pagination.page) expect(apiResponse.pagination).toHaveProperty('per_page', pagination.perPage) }) it('getLists', async () => { const apiResponse = await client.getLists() expect(t.exact(UserListsResponseIO).is(apiResponse)).toBeTruthy() }) it('getListItems', async () => { const listId = 515576 const apiResponse = await client.getListItems(listId) expect(t.exact(UserListItemsResponseIO).is(apiResponse)).toBeTruthy() }) }) })
the_stack
export default { $schema: 'vscode://schemas/color-theme', name: 'Cobalt', type: 'dark', colors: { // activityBar 'activityBar.background': '#122738', 'activityBar.border': '#0d3a58', 'activityBar.dropBackground': '#0d3a58', 'activityBar.foreground': '#fff', 'activityBarBadge.background': '#ffc600', 'activityBarBadge.foreground': '#000', // badge 'badge.background': '#ffc600', 'badge.foreground': '#000', // button 'button.background': '#0088ff', 'button.foreground': '#fff', 'button.hoverBackground': '#ff9d00', // contrast contrastActiveBorder: null, contrastBorder: '#ffffff00', // debug 'debugExceptionWidget.background': '#193549', 'debugExceptionWidget.border': '#aaa', 'debugToolBar.background': '#193549', // description descriptionForeground: '#aaa', // diff 'diffEditor.insertedTextBackground': '#3ad90033', 'diffEditor.insertedTextBorder': '#3ad90055', 'diffEditor.removedTextBackground': '#ee3a4333', 'diffEditor.removedTextBorder': '#ee3a4355', // dropdown 'dropdown.background': '#193549', 'dropdown.border': '#15232d', 'dropdown.foreground': '#fff', // editor // This is the main background color 'editor.background': '#193549', // this is the main text colour 'editor.foreground': '#fff', // Okay this part is confusing as heck! // Currently found item 'editor.findMatchBackground': '#FF720066', // Other Found Items int the document 'editor.findMatchHighlightBackground': '#CAD40F66', // WTF is this one for? I don't know 'editor.findRangeHighlightBackground': '#243E51', // When you hover over something and a popup shows, this highlights that thing 'editor.hoverHighlightBackground': '#ffc60033', // when you have something selected, but have lost focus on the editor 'editor.inactiveSelectionBackground': '#003b8b', // current line styles 'editor.lineHighlightBackground': '#1F4662', 'editor.lineHighlightBorder': '#234E6D', 'editor.rangeHighlightBackground': '#1F4662', // selected Text colours // This is the standard Select colour 'editor.selectionBackground': '#0050A4', // This is the colour of the other matching elements 'editor.selectionHighlightBackground': '#0050A480', // if you tab away you can colour it differently, but ill leave this one out // "editor.inactiveSelectionBackground": "", // Word Highlights! This happens when you move your cursor inside a variable // Strong is the one where your cursor currently is 'editor.wordHighlightStrongBackground': '#ffffff21', // and this one is the rest of them 'editor.wordHighlightBackground': '#ffffff21', 'editorBracketMatch.background': '#0d3a58', 'editorBracketMatch.border': '#ffc60080', 'editorCodeLens.foreground': '#aaa', 'editorCursor.foreground': '#ffc600', 'editorError.border': '#0d3a58', 'editorError.foreground': '#A22929', // gutter 'editorGutter.background': '#12273866', 'editorGutter.addedBackground': '#3C9F4A', 'editorGutter.deletedBackground': '#A22929', 'editorGutter.modifiedBackground': '#26506D', // editorGroup 'editorGroup.background': '#A22929', 'editorGroup.border': '#122738', 'editorGroup.dropBackground': '#12273899', // editorGroupHeader 'editorGroupHeader.noTabsBackground': '#193549', 'editorGroupHeader.tabsBackground': '#193549', 'editorGroupHeader.tabsBorder': '#15232d', // editorHoverWidget 'editorHoverWidget.background': '#15232d', 'editorHoverWidget.border': '#0d3a58', 'editorIndentGuide.background': '#3B5364', 'editorLineNumber.foreground': '#aaa', 'editorLink.activeForeground': '#aaa', // editorMarkerNavigation 'editorMarkerNavigation.background': '#3B536433', 'editorMarkerNavigationError.background': '#A22929', 'editorMarkerNavigationWarning.background': '#ffc600', // ruler 'editorOverviewRuler.border': '#0d3a58', 'editorOverviewRuler.commonContentForeground': '#ffc60055', 'editorOverviewRuler.currentContentForeground': '#ee3a4355', 'editorOverviewRuler.incomingContentForeground': '#3ad90055', 'editorRuler.foreground': '#1F4662', // editorSuggestWidget 'editorSuggestWidget.background': '#15232d', 'editorSuggestWidget.border': '#15232d', 'editorSuggestWidget.foreground': '#aaa', 'editorSuggestWidget.highlightForeground': '#ffc600', 'editorSuggestWidget.selectedBackground': '#193549', // editorWarning 'editorWarning.border': '#ffffff00', 'editorWarning.foreground': '#ffc600', 'editorWhitespace.foreground': '#ffffff1a', 'editorWidget.background': '#15232d', 'editorWidget.border': '#0d3a58', errorForeground: '#A22929', // extensionButton 'extensionButton.prominentBackground': '#0088ff', 'extensionButton.prominentForeground': '#fff', 'extensionButton.prominentHoverBackground': '#ff9d00', focusBorder: '#0d3a58', foreground: '#aaa', // input 'input.background': '#193549', 'input.border': '#0d3a58', 'input.foreground': '#ffc600', 'input.placeholderForeground': '#aaa', 'inputOption.activeBorder': '#8dffff', 'inputValidation.errorBackground': '#193549', 'inputValidation.errorBorder': '#ffc600', 'inputValidation.infoBackground': '#193549', 'inputValidation.infoBorder': '#0D3A58', 'inputValidation.warningBackground': '#193549', 'inputValidation.warningBorder': '#ffc600', // list 'list.activeSelectionBackground': '#193549', 'list.activeSelectionForeground': '#aaa', 'list.dropBackground': '#0d3a58', 'list.focusBackground': '#0d3a58', 'list.focusForeground': '#aaa', 'list.highlightForeground': '#ffc600', 'list.hoverBackground': '#193549', 'list.hoverForeground': '#aaa', 'list.inactiveSelectionBackground': '#0d3a58', 'list.inactiveSelectionForeground': '#aaa', // menu 'menu.background': '#122738', // merge 'merge.border': '#ffffff00', 'merge.commonContentBackground': '#c97d0c', 'merge.commonHeaderBackground': '#c97d0c', 'merge.currentContentBackground': '#2F7366', 'merge.currentHeaderBackground': '#2F7366', 'merge.incomingContentBackground': '#185294', 'merge.incomingHeaderBackground': '#185294', // notification colors - The colors below only apply for VS Code versions 1.21 and higher. 'notificationCenter.border': '#ffc600', 'notificationCenterHeader.foreground': '#aaa', 'notificationCenterHeader.background': '#122738', 'notificationToast.border': '#ffc600', 'notifications.foreground': '#aaa', 'notifications.background': '#122738', 'notifications.border': '#ffc600', 'notificationLink.foreground': '#ffc600', // notification - If you target VS Code versions before the 1.21 (February 2018) release, these are the old (no longer supported) colors: 'notification.background': '#ffc600', 'notification.buttonBackground': '#0088ff', 'notification.buttonForeground': '#fff', 'notification.buttonHoverBackground': '#ff9d00', 'notification.errorBackground': '#A22929', 'notification.errorForeground': '#fff', 'notification.foreground': '#000', 'notification.infoBackground': '#0088ff', 'notification.infoForeground': '#fff', 'notification.warningBackground': '#ff9d00', 'notification.warningForeground': '#000', // panel 'panel.background': '#122738', 'panel.border': '#ffc600', 'panelTitle.activeBorder': '#ffc600', 'panelTitle.activeForeground': '#ffc600', 'panelTitle.inactiveForeground': '#aaa', // "peekView 'peekView.border': '#ffc600', 'peekViewEditor.background': '#193549', 'peekViewEditor.matchHighlightBackground': '#19354900', 'peekViewEditorGutter.background': '#122738', 'peekViewResult.background': '#15232d', 'peekViewResult.fileForeground': '#aaa', 'peekViewResult.lineForeground': '#fff', 'peekViewResult.matchHighlightBackground': '#0d3a58', 'peekViewResult.selectionBackground': '#0d3a58', 'peekViewResult.selectionForeground': '#fff', 'peekViewTitle.background': '#15232d', 'peekViewTitleDescription.foreground': '#aaa', 'peekViewTitleLabel.foreground': '#ffc600', // picker 'pickerGroup.border': '#0d3a58', 'pickerGroup.foreground': '#aaa', // progressBar 'progressBar.background': '#ffc600', // scrollbar 'scrollbar.shadow': '#00000000', 'scrollbarSlider.activeBackground': '#355166cc', 'scrollbarSlider.background': '#1F466280', 'scrollbarSlider.hoverBackground': '#406179cc', // selection 'selection.background': '#027dff', // sidebar 'sideBar.background': '#15232d', 'sideBar.border': '#0d3a58', 'sideBar.foreground': '#aaa', 'sideBarSectionHeader.background': '#193549', 'sideBarSectionHeader.foreground': '#aaaaaa', 'sideBarTitle.foreground': '#aaaaaa', // statusBar 'statusBar.background': '#15232d', 'statusBar.border': '#0d3a58', 'statusBar.debuggingBackground': '#15232d', 'statusBar.debuggingBorder': '#ffc600', 'statusBar.debuggingForeground': '#ffc600', 'statusBar.foreground': '#aaa', 'statusBar.noFolderBackground': '#15232d', 'statusBar.noFolderBorder': '#0d3a58', 'statusBar.noFolderForeground': '#aaa', 'statusBarItem.activeBackground': '#0088ff', 'statusBarItem.hoverBackground': '#0d3a58', 'statusBarItem.prominentBackground': '#15232d', 'statusBarItem.prominentHoverBackground': '#0d3a58', // tab 'tab.activeBackground': '#122738', 'tab.activeForeground': '#fff', 'tab.border': '#15232D', 'tab.activeBorder': '#ffc600', 'tab.inactiveBackground': '#193549', 'tab.inactiveForeground': '#aaa', 'tab.unfocusedActiveForeground': '#aaa', 'tab.unfocusedInactiveForeground': '#aaa', // --- workbench: terminal 'terminal.ansiBlack': '#000000', 'terminal.ansiRed': '#ff628c', 'terminal.ansiGreen': '#3ad900', 'terminal.ansiYellow': '#ffc600', 'terminal.ansiBlue': '#0088ff', 'terminal.ansiMagenta': '#fb94ff', 'terminal.ansiCyan': '#80fcff', 'terminal.ansiWhite': '#ffffff', 'terminal.ansiBrightBlack': '#0050A4', 'terminal.ansiBrightRed': '#ff628c', 'terminal.ansiBrightGreen': '#3ad900', 'terminal.ansiBrightYellow': '#ffc600', 'terminal.ansiBrightBlue': '#0088ff', 'terminal.ansiBrightMagenta': '#fb94ff', 'terminal.ansiBrightCyan': '#80fcff', 'terminal.ansiBrightWhite': '#193549', 'terminal.background': '#122738', 'terminal.foreground': '#ffffff', 'terminalCursor.background': '#ffc600', 'terminalCursor.foreground': '#ffc600', // Git status colors in File Explorer 'gitDecoration.modifiedResourceForeground': '#ffc600', 'gitDecoration.deletedResourceForeground': '#ff628c', 'gitDecoration.untrackedResourceForeground': '#3ad900', 'gitDecoration.ignoredResourceForeground': '#808080', 'gitDecoration.conflictingResourceForeground': '#FF7200', // textBlockQuote 'textBlockQuote.background': '#193549', 'textBlockQuote.border': '#0088ff', 'textCodeBlock.background': '#193549', 'textLink.activeForeground': '#0088ff', 'textLink.foreground': '#0088ff', 'textPreformat.foreground': '#ffc600', 'textSeparator.foreground': '#0d3a58', 'titleBar.activeBackground': '#15232D', 'titleBar.activeForeground': '#ffffff', 'titleBar.inactiveBackground': '#193549', 'titleBar.inactiveForeground': '#ffffff33', 'walkThrough.embeddedEditorBackground': '#0d3a58', 'welcomePage.buttonBackground': '#193549', 'welcomePage.buttonHoverBackground': '#0d3a58', 'widget.shadow': '#00000026', }, tokenColors: [ { name: 'Comment', scope: ['comment', 'punctuation.definition.comment'], settings: { fontStyle: 'italic', foreground: '#0088ff', }, }, { name: 'Constant', scope: 'constant', settings: { foreground: '#ff628c', }, }, { name: 'Entity', scope: 'entity', settings: { foreground: '#ffc600', }, }, { name: 'Invalid', scope: 'invalid', settings: { foreground: '#f44542', }, }, { name: 'Storage Type Function', scope: 'storage.type.function', settings: { foreground: '#ff9d00', }, }, { name: 'Keyword', scope: 'keyword, storage.type.class', settings: { foreground: '#ff9d00', }, }, { name: 'Meta', scope: 'meta', settings: { foreground: '#9effff', }, }, { name: 'Meta JSX', scope: [ 'meta.jsx.children', 'meta.jsx.children.js', 'meta.jsx.children.tsx', ], settings: { foreground: '#fff', }, }, { name: 'Meta Brace', scope: 'meta.brace', settings: { foreground: '#e1efff', }, }, { name: 'Punctuation', scope: 'punctuation', settings: { foreground: '#e1efff', }, }, { name: 'Punctuation Parameters', scope: 'punctuation.definition.parameters', settings: { foreground: '#ffee80', }, }, { name: 'Punctuation Template Expression', scope: 'punctuation.definition.template-expression', settings: { foreground: '#ffee80', }, }, { name: 'Storage', scope: 'storage', settings: { foreground: '#ffc600', }, }, { name: 'Storage Type Arrow Function', scope: 'storage.type.function.arrow', settings: { foreground: '#ffc600', }, }, { name: 'String', scope: ['string', 'punctuation.definition.string'], settings: { foreground: '#a5ff90', }, }, { name: 'String Template', scope: ['string.template', 'punctuation.definition.string.template'], settings: { foreground: '#3ad900', }, }, { name: 'Support', scope: 'support', settings: { foreground: '#80ffbb', }, }, { name: 'Support Function', scope: 'support.function', settings: { foreground: '#ff9d00', }, }, { name: 'Support Variable Property DOM', scope: 'support.variable.property.dom', settings: { foreground: '#e1efff', }, }, { name: 'Variable', scope: 'variable', settings: { foreground: '#e1efff', }, }, { name: '[CSS] - Entity', scope: ['source.css entity', 'source.stylus entity'], settings: { foreground: '#3ad900', }, }, { name: '[CSS] - ID Selector', scope: 'entity.other.attribute-name.id.css', settings: { foreground: '#FFB454', }, }, { name: '[CSS] - Element Selector', scope: 'entity.name.tag', settings: { foreground: '#9EFFFF', }, }, { name: '[CSS] - Support', scope: ['source.css support', 'source.stylus support'], settings: { foreground: '#a5ff90', }, }, { name: '[CSS] - Constant', scope: [ 'source.css constant', 'source.css support.constant', 'source.stylus constant', 'source.stylus support.constant', ], settings: { foreground: '#ffee80', }, }, { name: '[CSS] - String', scope: [ 'source.css string', 'source.css punctuation.definition.string', 'source.stylus string', 'source.stylus punctuation.definition.string', ], settings: { foreground: '#ffee80', }, }, { name: '[CSS] - Variable', scope: ['source.css variable', 'source.stylus variable'], settings: { foreground: '#9effff', }, }, { name: '[HTML] - Entity Name', scope: 'text.html.basic entity.name', settings: { foreground: '#9effff', }, }, { name: '[HTML] - ID value', scope: 'meta.toc-list.id.html', settings: { foreground: '#A5FF90', }, }, { name: '[HTML] - Entity Other', scope: 'text.html.basic entity.other', settings: { fontStyle: 'italic', foreground: '#ffc600', }, }, { name: '[HTML] - Script Tag', scope: 'meta.tag.metadata.script.html entity.name.tag.html', settings: { foreground: '#ffc600', }, }, { name: '[HTML] - Quotes. these are a slightly different colour because expand selection will then not include quotes', scope: 'punctuation.definition.string.begin, punctuation.definition.string.end', settings: { foreground: '#92fc79', }, }, { name: '[INI] - Entity', scope: 'source.ini entity', settings: { foreground: '#e1efff', }, }, { name: '[INI] - Keyword', scope: 'source.ini keyword', settings: { foreground: '#ffc600', }, }, { name: '[INI] - Punctuation Definition', scope: 'source.ini punctuation.definition', settings: { foreground: '#ffee80', }, }, { name: '[INI] - Punctuation Separator', scope: 'source.ini punctuation.separator', settings: { foreground: '#ff9d00', }, }, { name: '[JAVASCRIPT] - Storage Type Function', scope: 'source.js storage.type.function', settings: { foreground: '#fb94ff', }, }, { name: '[JAVASCRIPT] - Variable Language', scope: 'variable.language, entity.name.type.class.js', settings: { foreground: '#fb94ff', }, }, { name: '[JAVASCRIPT] - Inherited Component', scope: 'entity.other.inherited-class.js', settings: { foreground: '#ccc', }, }, { name: '[PYTHON] - Self Argument', scope: 'variable.parameter.function.language.special.self.python', settings: { foreground: '#fb94ff', }, }, { name: '[JSON] - Support', scope: 'source.json support', settings: { foreground: '#ffc600', }, }, { name: '[JSON] - String', scope: [ 'source.json string', 'source.json punctuation.definition.string', ], settings: { foreground: '#e1efff', }, }, { name: '[MARKDOWN] - Heading Punctuation', scope: 'punctuation.definition.heading.markdown', settings: { foreground: '#e1efff', }, }, { name: '[MARKDOWN] - Heading Name Section', scope: [ 'entity.name.section.markdown', 'markup.heading.setext.1.markdown', 'markup.heading.setext.2.markdown', ], settings: { foreground: '#ffc600', fontStyle: 'bold', }, }, { name: '[MARKDOWN] - Paragraph', scope: 'meta.paragraph.markdown', settings: { foreground: '#e1efff', }, }, { name: '[MARKDOWN] - Quote Punctuation', scope: 'beginning.punctuation.definition.quote.markdown', settings: { foreground: '#ffc600', }, }, { name: '[MARKDOWN] - Quote Paragraph', scope: 'markup.quote.markdown meta.paragraph.markdown', settings: { fontStyle: 'italic', foreground: '#9effff', }, }, { name: '[MARKDOWN] - Separator', scope: 'meta.separator.markdown', settings: { foreground: '#ffc600', }, }, { name: '[MARKDOWN] - Emphasis Bold', scope: 'markup.bold.markdown', settings: { fontStyle: 'bold', foreground: '#9effff', }, }, { name: '[MARKDOWN] - Emphasis Italic', scope: 'markup.italic.markdown', settings: { fontStyle: 'italic', foreground: '#9effff', }, }, { name: '[MARKDOWN] - Lists', scope: 'beginning.punctuation.definition.list.markdown', settings: { foreground: '#ffc600', }, }, { name: '[MARKDOWN] - Link Title', scope: 'string.other.link.title.markdown', settings: { foreground: '#a5ff90', }, }, { name: '[MARKDOWN] - Link/Image Title', scope: [ 'string.other.link.title.markdown', 'string.other.link.description.markdown', 'string.other.link.description.title.markdown', ], settings: { foreground: '#a5ff90', }, }, { name: '[MARKDOWN] - Link Address', scope: [ 'markup.underline.link.markdown', 'markup.underline.link.image.markdown', ], settings: { foreground: '#9effff', }, }, { name: '[MARKDOWN] - Inline Code', scope: ['fenced_code.block.language', 'markup.inline.raw.markdown'], settings: { foreground: '#9effff', }, }, { name: '[MARKDOWN] - Code Block', scope: ['fenced_code.block.language', 'markup.inline.raw.markdown'], settings: { foreground: '#9effff', }, }, { name: '[PUG] - Entity Name', scope: 'text.jade entity.name', settings: { foreground: '#9effff', }, }, { name: '[PUG] - Entity Attribute Name', scope: 'text.jade entity.other.attribute-name.tag', settings: { fontStyle: 'italic', }, }, { name: '[PUG] - String Interpolated', scope: 'text.jade string.interpolated', settings: { foreground: '#ffee80', }, }, { name: '[TYPESCRIPT] - Entity Name Type', scope: 'source.ts entity.name.type', settings: { foreground: '#80ffbb', }, }, { name: '[TYPESCRIPT] - Keyword', scope: 'source.ts keyword', settings: { foreground: '#ffc600', }, }, { name: '[TYPESCRIPT] - Punctuation Parameters', scope: 'source.ts punctuation.definition.parameters', settings: { foreground: '#e1efff', }, }, { name: '[TYPESCRIPT] - Punctuation Arrow Parameters', scope: 'meta.arrow.ts punctuation.definition.parameters', settings: { foreground: '#ffee80', }, }, { name: '[TYPESCRIPT] - Storage', scope: 'source.ts storage', settings: { foreground: '#9effff', }, }, { name: '[TYPESCRIPT] - Variable Language', scope: 'variable.language, entity.name.type.class.ts, entity.name.type.class.tsx', settings: { foreground: '#fb94ff', }, }, { name: '[TYPESCRIPT] - Inherited Component', scope: 'entity.other.inherited-class.ts, entity.other.inherited-class.tsx', settings: { foreground: '#ccc', }, }, { name: '[PHP] - Entity', scope: 'source.php entity', settings: { foreground: '#9effff', }, }, { name: '[PHP] - Variables', scope: 'variable.other.php', settings: { foreground: '#ffc600', }, }, { name: '[C#] - Annotations', scope: 'storage.type.cs', settings: { foreground: '#9effff', }, }, { name: '[C#] - Properties', scope: 'entity.name.variable.property.cs', settings: { foreground: '#9effff', }, }, { name: '[C#] - Storage modifiers', scope: 'storage.modifier.cs', settings: { foreground: '#80ffbb', }, }, { name: 'Italicsify for Operator Mono', scope: [ 'modifier', 'this', 'comment', 'storage.modifier.js', 'storage.modifier.ts', 'storage.modifier.tsx', 'entity.other.attribute-name.js', 'entity.other.attribute-name.ts', 'entity.other.attribute-name.tsx', 'entity.other.attribute-name.html', ], settings: { fontStyle: 'italic', }, }, { name: '[CSHARP] - Modifiers and keyword types', scope: 'storage.modifier.cs, keyword.type.cs', settings: { foreground: '#fb94ff', }, }, { name: '[CSHARP] - Storage types', scope: 'storage.type.cs', settings: { foreground: '#80ffbb', }, }, { name: '[CSHARP] - Namespaces, parameters, field variables, properties', scope: 'entity.name.type.namespace.cs, entity.name.variable.parameter.cs, entity.name.variable.field.cs, entity.name.variable.property.cs', settings: { foreground: '#e1efff', }, }, ], };
the_stack
import { PdfColorSpace } from './../enum'; import { PdfColor } from './../pdf-color'; import { PdfBrush } from './pdf-brush'; import { PdfFunction } from './../../general/functions/pdf-function'; import { PdfSampledFunction} from './../../general/functions/pdf-sampled-function'; import { PdfBlend } from './pdf-blend'; /** * `PdfColorBlend` Represents the arrays of colors and positions used for * interpolating color blending in a multicolor gradient. * @private */ export class PdfColorBlend extends PdfBlend { //Fields /** * Array of colors. * @private */ private mcolors: PdfColor[]; /** * Local variable to store the brush. */ private mbrush: PdfBrush; //Constructor /** * Initializes a new instance of the `PdfColorBlend` class. * @public */ public constructor() /** * Initializes a new instance of the `PdfColorBlend` class. * @public */ public constructor(count: number) public constructor(count?: number) { super(); if (typeof count === 'number') { super(count); } } //Properties /** * Gets or sets the array of colors. * @public */ public get colors(): PdfColor[] { return this.mcolors; } public set colors(value: PdfColor[]) { if ((value == null)) { throw new Error('ArgumentNullException : Colors'); } this.mcolors = value; } //Implementation /** * Gets the function. * @param colorSpace The color space. * @public */ public getFunction(colorSpace: PdfColorSpace): PdfFunction { let domain: number[] = [ 0, 1]; let colourComponents: number = this.getColorComponentsCount(colorSpace); let maxComponentValue: number = this.getMaxComponentValue(colorSpace); let range: number[] = this.setRange(colourComponents, maxComponentValue); let func: PdfSampledFunction = null; if ((this.mbrush == null && typeof this.mbrush === 'undefined')) { let sizes: number[] = [1]; let samplesCount: number; let step: number = 1; if (this.positions.length === 2) { samplesCount = 2; } else { let positions: number[] = this.positions; let intervals: number[] = this.getIntervals(positions); let gcd: number = this.gcd(intervals); step = gcd; samplesCount = ((<number>((1 / gcd))) + 1); } sizes[0] = samplesCount; let samples: number[] = this.getSamplesValues(colorSpace, samplesCount, maxComponentValue, step); func = new PdfSampledFunction(domain, range, sizes, samples); return func; } return func; } /** * 'cloneColorBlend' Clones this instance. * @public */ public cloneColorBlend(): PdfColorBlend { let cBlend: PdfColorBlend = this; if ((this.mcolors != null && typeof this.mcolors !== 'undefined')) { cBlend.colors = (<PdfColor[]>(this.mcolors)); } if ((this.positions != null && typeof this.positions !== 'undefined')) { cBlend.positions = (<number[]>(this.positions)); } return cBlend; } /** * Sets the range. * @param colourComponents The colour components. * @param maxValue The max value. */ private setRange(colourComponents: number, maxValue: number): number[] { let range: number[] = [(colourComponents * 2)]; for (let i: number = 0; (i < colourComponents); ++i) { range[(i * 2)] = 0; range[((i * 2) + 1)] = 1; } return range; } /** * Calculates the color components count according to colour space. * @param colorSpace The color space. */ private getColorComponentsCount(colorSpace: PdfColorSpace): number { let count: number = 0; switch (colorSpace) { case PdfColorSpace.Rgb: count = 3; break; case PdfColorSpace.Cmyk: count = 4; break; case PdfColorSpace.GrayScale: count = 1; break; default: throw new Error('ArgumentException - Unsupported color space: ' + colorSpace + ' colorSpace'); } return count; } /** * Gets samples values for specified colour space. * @param colorSpace The color space. * @param sampleCount The sample count. * @param maxComponentValue The max component value. * @param step The step. */ private getSamplesValues(colorSpace: PdfColorSpace, sampleCount: number, maxComponentValue: number, step: number): number[] { let values: number[]; switch (colorSpace) { case PdfColorSpace.GrayScale: values = this.getGrayscaleSamples(sampleCount, maxComponentValue, step); break; case PdfColorSpace.Cmyk: values = this.getCmykSamples(sampleCount, maxComponentValue, step); break; case PdfColorSpace.Rgb: values = this.getRgbSamples(sampleCount, maxComponentValue, step); break; default: throw new Error('ArgumentException - Unsupported color space: ' + colorSpace + ' colorSpace'); } return values; } /** * Gets the grayscale samples. * @param sampleCount The sample count. * @param maxComponentValue The max component value. * @param step The step. */ private getGrayscaleSamples(sampleCount: number, maxComponentValue: number, step: number): number[] { let values: number[] = [(sampleCount * 2)]; for (let i: number = 0; (i < sampleCount); ++i) { let color: PdfColor = this.getNextColor(i, step, PdfColorSpace.GrayScale); let index: number = (i * 2); } return values; } /** * Gets the RGB samples. * @param sampleCount The sample count. * @param maxComponentValue The max component value. * @param step The step. */ private getRgbSamples(sampleCount: number, maxComponentValue: number, step: number): number[] { let values: number[] = [(sampleCount * 3)]; for (let i: number = 0; (i < sampleCount); ++i) { let color: PdfColor = this.getNextColor(i, step, PdfColorSpace.Rgb); let index: number = (i * 3); values[index] = color.r; values[(index + 1)] = color.g; values[(index + 2)] = color.b; } return values; } /** * Gets the CMYK samples. * @param sampleCount The sample count. * @param maxComponentValue The max component value. * @param step The step. */ private getCmykSamples(sampleCount: number, maxComponentValue: number, step: number): number[] { let values: number[] = [(sampleCount * 4)]; for (let i: number = 0; (i < sampleCount); i++) { let color: PdfColor = this.getNextColor(i, step, PdfColorSpace.Cmyk); let index: number = (i * 4); values[index] = (<number>((color.c * maxComponentValue))); values[(index + 1)] = (<number>((color.m * maxComponentValue))); values[(index + 2)] = (<number>((color.y * maxComponentValue))); values[(index + 3)] = (<number>((color.k * maxComponentValue))); } return values; } /** * Calculates the color that should be at the specified index. * @param index The index. * @param step The step. * @param colorSpace The color space. */ private getNextColor(index: number, step: number, colorSpace: PdfColorSpace): PdfColor { let position: number = (step * index); let indexHi: number; let indexLow: number; let result : { indexLow : number, indexHi : number} = this.getIndices(position, indexLow, indexHi); indexLow = result.indexLow; indexHi = result.indexHi; let color: PdfColor; if (indexLow === indexHi) { color = this.mcolors[indexLow]; } else { let positionLow: number = this.positions[indexLow]; let positionHi: number = this.positions[indexHi]; let colorLow: PdfColor = this.mcolors[indexLow]; let colorHi: PdfColor = this.mcolors[indexHi]; let t: number = ((position - positionLow) / (positionHi - positionLow)); color = this.interpolate(t, colorLow, colorHi, colorSpace); } return color; } /** * Gets the indices. * @param position The position. * @param indexLow The index low. * @param indexHi The index hi. */ private getIndices(position: number, indexLow: number, indexHi: number) : { indexLow : number, indexHi : number} { let positions: number[] = this.positions; indexLow = 0; indexHi = 0; for (let i: number = 0; (i < this.mcolors.length); ++i) { let currPos: number = positions[i]; if ((currPos === position)) { indexHi = i; indexLow = i; break; } else if ((currPos > position)) { indexHi = i; break; } indexLow = i; indexHi = i; } return { indexLow : indexLow, indexHi : indexHi }; } /** * Calculates the max component value. * @param colorSpace The color space. */ private getMaxComponentValue(colorSpace: PdfColorSpace) : number { let result: number = 0; switch (colorSpace) { case PdfColorSpace.Cmyk: case PdfColorSpace.Rgb: result = 255; break; case PdfColorSpace.GrayScale: result = 65535; break; default: throw new Error('ArgumentException - Unsupported color space: ' + colorSpace + 'colorSpace'); } return result; } /** * Gets an intervals array from the positions array. * @param positions The positions array. */ private getIntervals(positions: number[]): number[] { let count: number = positions.length; let intervals: number[] = [(count - 1)]; let prev: number = positions[0]; for (let i: number = 1; (i < count); ++i) { let v: number = positions[i]; intervals[(i - 1)] = (v - prev); prev = v; } return intervals; } }
the_stack
import { Action, Event, EventObject, SingleOrArray, SendAction, SendActionOptions, CancelAction, ActionObject, ActionType, Assigner, PropertyAssigner, AssignAction, ActionFunction, ActionFunctionMap, ActivityActionObject, ActionTypes, ActivityDefinition, SpecialTargets, RaiseAction, RaiseActionObject, DoneEvent, ErrorPlatformEvent, DoneEventObject, SendExpr, SendActionObject, PureAction, LogExpr, LogAction, LogActionObject, DelayFunctionMap, SCXML, ExprWithMeta, ChooseConditon, ChooseAction, AnyEventObject, Expr } from './types'; import * as actionTypes from './actionTypes'; import { getEventType, isFunction, isString, toEventObject, toSCXMLEvent, partition, flatten, updateContext, warn, toGuard, evaluateGuard, toArray, isArray } from './utils'; import { State } from './State'; import { StateNode } from './StateNode'; import { IS_PRODUCTION } from './environment'; import { StopAction, StopActionObject } from '.'; export { actionTypes }; export const initEvent = toSCXMLEvent({ type: actionTypes.init }); export function getActionFunction<TContext, TEvent extends EventObject>( actionType: ActionType, actionFunctionMap?: ActionFunctionMap<TContext, TEvent> ): | ActionObject<TContext, TEvent> | ActionFunction<TContext, TEvent> | undefined { return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined; } export function toActionObject<TContext, TEvent extends EventObject>( action: Action<TContext, TEvent>, actionFunctionMap?: ActionFunctionMap<TContext, TEvent> ): ActionObject<TContext, TEvent> { let actionObject: ActionObject<TContext, TEvent>; if (isString(action) || typeof action === 'number') { const exec = getActionFunction(action, actionFunctionMap); if (isFunction(exec)) { actionObject = { type: action, exec }; } else if (exec) { actionObject = exec; } else { actionObject = { type: action, exec: undefined }; } } else if (isFunction(action)) { actionObject = { // Convert action to string if unnamed type: action.name || action.toString(), exec: action }; } else { const exec = getActionFunction(action.type, actionFunctionMap); if (isFunction(exec)) { actionObject = { ...action, exec }; } else if (exec) { const actionType = exec.type || action.type; actionObject = { ...exec, ...action, type: actionType } as ActionObject<TContext, TEvent>; } else { actionObject = action as ActionObject<TContext, TEvent>; } } return actionObject; } export const toActionObjects = <TContext, TEvent extends EventObject>( action?: SingleOrArray<Action<TContext, TEvent>> | undefined, actionFunctionMap?: ActionFunctionMap<TContext, TEvent> ): Array<ActionObject<TContext, TEvent>> => { if (!action) { return []; } const actions = isArray(action) ? action : [action]; return actions.map((subAction) => toActionObject(subAction, actionFunctionMap) ); }; export function toActivityDefinition<TContext, TEvent extends EventObject>( action: string | ActivityDefinition<TContext, TEvent> ): ActivityDefinition<TContext, TEvent> { const actionObject = toActionObject(action); return { id: isString(action) ? action : actionObject.id, ...actionObject, type: actionObject.type }; } /** * Raises an event. This places the event in the internal event queue, so that * the event is immediately consumed by the machine in the current step. * * @param eventType The event to raise. */ export function raise<TContext, TEvent extends EventObject>( event: Event<TEvent> ): RaiseAction<TEvent> | SendAction<TContext, AnyEventObject, TEvent> { if (!isString(event)) { return send(event, { to: SpecialTargets.Internal }); } return { type: actionTypes.raise, event }; } export function resolveRaise<TEvent extends EventObject>( action: RaiseAction<TEvent> ): RaiseActionObject<TEvent> { return { type: actionTypes.raise, _event: toSCXMLEvent(action.event) }; } /** * Sends an event. This returns an action that will be read by an interpreter to * send the event in the next step, after the current step is finished executing. * * @param event The event to send. * @param options Options to pass into the send event: * - `id` - The unique send event identifier (used with `cancel()`). * - `delay` - The number of milliseconds to delay the sending of the event. * - `to` - The target of this event (by default, the machine the event was sent from). */ export function send< TContext, TEvent extends EventObject, TSentEvent extends EventObject = AnyEventObject >( event: Event<TSentEvent> | SendExpr<TContext, TEvent, TSentEvent>, options?: SendActionOptions<TContext, TEvent> ): SendAction<TContext, TEvent, TSentEvent> { return { to: options ? options.to : undefined, type: actionTypes.send, event: isFunction(event) ? event : toEventObject<TSentEvent>(event), delay: options ? options.delay : undefined, id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : (getEventType<TSentEvent>(event) as string) }; } export function resolveSend< TContext, TEvent extends EventObject, TSentEvent extends EventObject >( action: SendAction<TContext, TEvent, TSentEvent>, ctx: TContext, _event: SCXML.Event<TEvent>, delaysMap?: DelayFunctionMap<TContext, TEvent> ): SendActionObject<TContext, TEvent, TSentEvent> { const meta = { _event }; // TODO: helper function for resolving Expr const resolvedEvent = toSCXMLEvent( isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event ); let resolvedDelay: number | undefined; if (isString(action.delay)) { const configDelay = delaysMap && delaysMap[action.delay]; resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay; } else { resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay; } const resolvedTarget = isFunction(action.to) ? action.to(ctx, _event.data, meta) : action.to; return { ...action, to: resolvedTarget, _event: resolvedEvent, event: resolvedEvent.data, delay: resolvedDelay }; } /** * Sends an event to this machine's parent. * * @param event The event to send to the parent machine. * @param options Options to pass into the send event. */ export function sendParent< TContext, TEvent extends EventObject, TSentEvent extends EventObject = AnyEventObject >( event: Event<TSentEvent> | SendExpr<TContext, TEvent, TSentEvent>, options?: SendActionOptions<TContext, TEvent> ): SendAction<TContext, TEvent, TSentEvent> { return send<TContext, TEvent, TSentEvent>(event, { ...options, to: SpecialTargets.Parent }); } /** * Sends an update event to this machine's parent. */ export function sendUpdate<TContext, TEvent extends EventObject>(): SendAction< TContext, TEvent, { type: ActionTypes.Update } > { return sendParent<TContext, TEvent, { type: ActionTypes.Update }>( actionTypes.update ); } /** * Sends an event back to the sender of the original event. * * @param event The event to send back to the sender * @param options Options to pass into the send event */ export function respond< TContext, TEvent extends EventObject, TSentEvent extends EventObject = AnyEventObject >( event: Event<TEvent> | SendExpr<TContext, TEvent, TSentEvent>, options?: SendActionOptions<TContext, TEvent> ) { return send<TContext, TEvent>(event, { ...options, to: (_, __, { _event }) => { return _event.origin!; // TODO: handle when _event.origin is undefined } }); } const defaultLogExpr = <TContext, TEvent extends EventObject>( context: TContext, event: TEvent ) => ({ context, event }); /** * * @param expr The expression function to evaluate which will be logged. * Takes in 2 arguments: * - `ctx` - the current state context * - `event` - the event that caused this action to be executed. * @param label The label to give to the logged expression. */ export function log<TContext, TEvent extends EventObject>( expr: string | LogExpr<TContext, TEvent> = defaultLogExpr, label?: string ): LogAction<TContext, TEvent> { return { type: actionTypes.log, label, expr }; } export const resolveLog = <TContext, TEvent extends EventObject>( action: LogAction<TContext, TEvent>, ctx: TContext, _event: SCXML.Event<TEvent> ): LogActionObject<TContext, TEvent> => ({ // TODO: remove .expr from resulting object ...action, value: isString(action.expr) ? action.expr : action.expr(ctx, _event.data, { _event }) }); /** * Cancels an in-flight `send(...)` action. A canceled sent action will not * be executed, nor will its event be sent, unless it has already been sent * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`). * * @param sendId The `id` of the `send(...)` action to cancel. */ export const cancel = (sendId: string | number): CancelAction => { return { type: actionTypes.cancel, sendId }; }; /** * Starts an activity. * * @param activity The activity to start. */ export function start<TContext, TEvent extends EventObject>( activity: string | ActivityDefinition<TContext, TEvent> ): ActivityActionObject<TContext, TEvent> { const activityDef = toActivityDefinition(activity); return { type: ActionTypes.Start, activity: activityDef, exec: undefined }; } /** * Stops an activity. * * @param actorRef The activity to stop. */ export function stop<TContext, TEvent extends EventObject>( actorRef: | string | ActivityDefinition<TContext, TEvent> | Expr<TContext, TEvent, string | { id: string }> ): StopAction<TContext, TEvent> { const activity = isFunction(actorRef) ? actorRef : toActivityDefinition(actorRef); return { type: ActionTypes.Stop, activity, exec: undefined }; } export function resolveStop<TContext, TEvent extends EventObject>( action: StopAction<TContext, TEvent>, context: TContext, _event: SCXML.Event<TEvent> ): StopActionObject { const actorRefOrString = isFunction(action.activity) ? action.activity(context, _event.data) : action.activity; const resolvedActorRef = typeof actorRefOrString === 'string' ? { id: actorRefOrString } : actorRefOrString; const actionObject = { type: ActionTypes.Stop as const, activity: resolvedActorRef }; return actionObject; } /** * Updates the current context of the machine. * * @param assignment An object that represents the partial context to update. */ export const assign = <TContext, TEvent extends EventObject = EventObject>( assignment: Assigner<TContext, TEvent> | PropertyAssigner<TContext, TEvent> ): AssignAction<TContext, TEvent> => { return { type: actionTypes.assign, assignment }; }; export function isActionObject<TContext, TEvent extends EventObject>( action: Action<TContext, TEvent> ): action is ActionObject<TContext, TEvent> { return typeof action === 'object' && 'type' in action; } /** * Returns an event type that represents an implicit event that * is sent after the specified `delay`. * * @param delayRef The delay in milliseconds * @param id The state node ID where this event is handled */ export function after(delayRef: number | string, id?: string) { const idSuffix = id ? `#${id}` : ''; return `${ActionTypes.After}(${delayRef})${idSuffix}`; } /** * Returns an event that represents that a final state node * has been reached in the parent state node. * * @param id The final state node's parent state node `id` * @param data The data to pass into the event */ export function done(id: string, data?: any): DoneEventObject { const type = `${ActionTypes.DoneState}.${id}`; const eventObject = { type, data }; eventObject.toString = () => type; return eventObject as DoneEvent; } /** * Returns an event that represents that an invoked service has terminated. * * An invoked service is terminated when it has reached a top-level final state node, * but not when it is canceled. * * @param id The final state node ID * @param data The data to pass into the event */ export function doneInvoke(id: string, data?: any): DoneEvent { const type = `${ActionTypes.DoneInvoke}.${id}`; const eventObject = { type, data }; eventObject.toString = () => type; return eventObject as DoneEvent; } export function error(id: string, data?: any): ErrorPlatformEvent & string { const type = `${ActionTypes.ErrorPlatform}.${id}`; const eventObject = { type, data }; eventObject.toString = () => type; return eventObject as ErrorPlatformEvent & string; } export function pure<TContext, TEvent extends EventObject>( getActions: ( context: TContext, event: TEvent ) => SingleOrArray<ActionObject<TContext, TEvent>> | undefined ): PureAction<TContext, TEvent> { return { type: ActionTypes.Pure, get: getActions }; } /** * Forwards (sends) an event to a specified service. * * @param target The target service to forward the event to. * @param options Options to pass into the send action creator. */ export function forwardTo<TContext, TEvent extends EventObject>( target: Required<SendActionOptions<TContext, TEvent>>['to'], options?: SendActionOptions<TContext, TEvent> ): SendAction<TContext, TEvent, AnyEventObject> { return send<TContext, TEvent>((_, event) => event, { ...options, to: target }); } /** * Escalates an error by sending it as an event to this machine's parent. * * @param errorData The error data to send, or the expression function that * takes in the `context`, `event`, and `meta`, and returns the error data to send. * @param options Options to pass into the send action creator. */ export function escalate< TContext, TEvent extends EventObject, TErrorData = any >( errorData: TErrorData | ExprWithMeta<TContext, TEvent, TErrorData>, options?: SendActionOptions<TContext, TEvent> ): SendAction<TContext, TEvent, AnyEventObject> { return sendParent<TContext, TEvent>( (context, event, meta) => { return { type: actionTypes.error, data: isFunction(errorData) ? errorData(context, event, meta) : errorData }; }, { ...options, to: SpecialTargets.Parent } ); } export function choose<TContext, TEvent extends EventObject>( conds: Array<ChooseConditon<TContext, TEvent>> ): ChooseAction<TContext, TEvent> { return { type: ActionTypes.Choose, conds }; } export function resolveActions<TContext, TEvent extends EventObject>( machine: StateNode<TContext, any, TEvent, any>, currentState: State<TContext, TEvent> | undefined, currentContext: TContext, _event: SCXML.Event<TEvent>, actions: Array<ActionObject<TContext, TEvent>>, preserveActionOrder: boolean = false ): [Array<ActionObject<TContext, TEvent>>, TContext] { const [assignActions, otherActions] = preserveActionOrder ? [[], actions] : partition( actions, (action): action is AssignAction<TContext, TEvent> => action.type === actionTypes.assign ); let updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext; const preservedContexts: TContext[] | undefined = preserveActionOrder ? [currentContext] : undefined; const resolvedActions = flatten( otherActions .map((actionObject) => { switch (actionObject.type) { case actionTypes.raise: return resolveRaise(actionObject as RaiseAction<TEvent>); case actionTypes.send: const sendAction = resolveSend( actionObject as SendAction<TContext, TEvent, AnyEventObject>, updatedContext, _event, machine.options.delays ) as ActionObject<TContext, TEvent>; // TODO: fix ActionTypes.Init if (!IS_PRODUCTION) { // warn after resolving as we can create better contextual message here warn( !isString(actionObject.delay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length `No delay reference for delay expression '${actionObject.delay}' was found on machine '${machine.id}'` ); } return sendAction; case actionTypes.log: return resolveLog( actionObject as LogAction<TContext, TEvent>, updatedContext, _event ); case actionTypes.choose: { const chooseAction = actionObject as ChooseAction<TContext, TEvent>; const matchedActions = chooseAction.conds.find((condition) => { const guard = toGuard(condition.cond, machine.options.guards); return ( !guard || evaluateGuard( machine, guard, updatedContext, _event, currentState as any ) ); })?.actions; if (!matchedActions) { return []; } const [ resolvedActionsFromChoose, resolvedContextFromChoose ] = resolveActions( machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions), machine.options.actions), preserveActionOrder ); updatedContext = resolvedContextFromChoose; preservedContexts?.push(updatedContext); return resolvedActionsFromChoose; } case actionTypes.pure: { const matchedActions = (actionObject as PureAction< TContext, TEvent >).get(updatedContext, _event.data); if (!matchedActions) { return []; } const [resolvedActionsFromPure, resolvedContext] = resolveActions( machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions), machine.options.actions), preserveActionOrder ); updatedContext = resolvedContext; preservedContexts?.push(updatedContext); return resolvedActionsFromPure; } case actionTypes.stop: { return resolveStop( actionObject as StopAction<TContext, TEvent>, updatedContext, _event ); } case actionTypes.assign: { updatedContext = updateContext( updatedContext, _event, [actionObject as AssignAction<TContext, TEvent>], currentState ); preservedContexts?.push(updatedContext); break; } default: let resolvedActionObject = toActionObject( actionObject, machine.options.actions ); const { exec } = resolvedActionObject; if (exec && preservedContexts) { const contextIndex = preservedContexts.length - 1; resolvedActionObject = { ...resolvedActionObject, exec: (_ctx, ...args) => { exec(preservedContexts[contextIndex], ...args); } }; } return resolvedActionObject; } }) .filter((a): a is ActionObject<TContext, TEvent> => !!a) ); return [resolvedActions, updatedContext]; }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreGradesFormattedItem, CoreGradesFormattedRow, CoreGradesHelper } from '@features/grades/services/grades-helper'; import { CorePushNotifications } from '@features/pushnotifications/services/pushnotifications'; import { CoreQuestion, CoreQuestionQuestionParsed, CoreQuestionQuestionWSData, CoreQuestionsAnswers, } from '@features/question/services/question'; import { CoreQuestionDelegate } from '@features/question/services/question-delegate'; import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; import { CoreUtils } from '@services/utils/utils'; import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; import { CoreLogger } from '@singletons/logger'; import { AddonModQuizAccessRuleDelegate } from './access-rules-delegate'; import { AddonModQuizAttempt } from './quiz-helper'; import { AddonModQuizOffline, AddonModQuizQuestionsWithAnswers } from './quiz-offline'; import { AddonModQuizAutoSyncData, AddonModQuizSyncProvider } from './quiz-sync'; const ROOT_CACHE_KEY = 'mmaModQuiz:'; 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 { [AddonModQuizProvider.ATTEMPT_FINISHED_EVENT]: AddonModQuizAttemptFinishedData; [AddonModQuizSyncProvider.AUTO_SYNCED]: AddonModQuizAutoSyncData; } } /** * Service that provides some features for quiz. */ @Injectable({ providedIn: 'root' }) export class AddonModQuizProvider { static readonly COMPONENT = 'mmaModQuiz'; static readonly ATTEMPT_FINISHED_EVENT = 'addon_mod_quiz_attempt_finished'; // Grade methods. static readonly GRADEHIGHEST = 1; static readonly GRADEAVERAGE = 2; static readonly ATTEMPTFIRST = 3; static readonly ATTEMPTLAST = 4; // Question options. static readonly QUESTION_OPTIONS_MAX_ONLY = 1; static readonly QUESTION_OPTIONS_MARK_AND_MAX = 2; // Attempt state. static readonly ATTEMPT_IN_PROGRESS = 'inprogress'; static readonly ATTEMPT_OVERDUE = 'overdue'; static readonly ATTEMPT_FINISHED = 'finished'; static readonly ATTEMPT_ABANDONED = 'abandoned'; // Show the countdown timer if there is less than this amount of time left before the the quiz close date. static readonly QUIZ_SHOW_TIME_BEFORE_DEADLINE = 3600; protected logger: CoreLogger; constructor() { this.logger = CoreLogger.getInstance('AddonModQuizProvider'); } /** * Formats a grade to be displayed. * * @param grade Grade. * @param decimals Decimals to use. * @return Grade to display. */ formatGrade(grade?: number | null, decimals?: number): string { if (grade === undefined || grade == -1 || grade === null || isNaN(grade)) { return Translate.instant('addon.mod_quiz.notyetgraded'); } return CoreUtils.formatFloat(CoreTextUtils.roundToDecimals(grade, decimals)); } /** * Get attempt questions. Returns all of them or just the ones in certain pages. * * @param quiz Quiz. * @param attempt Attempt. * @param preflightData Preflight required data (like password). * @param options Other options. * @return Promise resolved with the questions. */ async getAllQuestionsData( quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData, preflightData: Record<string, string>, options: AddonModQuizAllQuestionsDataOptions = {}, ): Promise<Record<number, CoreQuestionQuestionParsed>> { const questions: Record<number, CoreQuestionQuestionParsed> = {}; const isSequential = this.isNavigationSequential(quiz); const pages = options.pages || this.getPagesFromLayout(attempt.layout); await Promise.all(pages.map(async (page) => { if (isSequential && page < (attempt.currentpage || 0)) { // Sequential quiz, cannot get pages before the current one. return; } // Get the questions in the page. const data = await this.getAttemptData(attempt.id, page, preflightData, options); // Add the questions to the result object. data.questions.forEach((question) => { questions[question.slot] = question; }); })); return questions; } /** * Get cache key for get attempt access information WS calls. * * @param quizId Quiz ID. * @param attemptId Attempt ID. * @return Cache key. */ protected getAttemptAccessInformationCacheKey(quizId: number, attemptId: number): string { return this.getAttemptAccessInformationCommonCacheKey(quizId) + ':' + attemptId; } /** * Get common cache key for get attempt access information WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getAttemptAccessInformationCommonCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'attemptAccessInformation:' + quizId; } /** * Get access information for an attempt. * * @param quizId Quiz ID. * @param attemptId Attempt ID. 0 for user's last attempt. * @param options Other options. * @return Promise resolved with the access information. */ async getAttemptAccessInformation( quizId: number, attemptId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise<AddonModQuizGetAttemptAccessInformationWSResponse> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetAttemptAccessInformationWSParams = { quizid: quizId, attemptid: attemptId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAttemptAccessInformationCacheKey(quizId, attemptId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_attempt_access_information', params, preSets); } /** * Get cache key for get attempt data WS calls. * * @param attemptId Attempt ID. * @param page Page. * @return Cache key. */ protected getAttemptDataCacheKey(attemptId: number, page: number): string { return this.getAttemptDataCommonCacheKey(attemptId) + ':' + page; } /** * Get common cache key for get attempt data WS calls. * * @param attemptId Attempt ID. * @return Cache key. */ protected getAttemptDataCommonCacheKey(attemptId: number): string { return ROOT_CACHE_KEY + 'attemptData:' + attemptId; } /** * Get an attempt's data. * * @param attemptId Attempt ID. * @param page Page number. * @param preflightData Preflight required data (like password). * @param options Other options. * @return Promise resolved with the attempt data. */ async getAttemptData( attemptId: number, page: number, preflightData: Record<string, string>, options: CoreCourseCommonModWSOptions = {}, ): Promise<AddonModQuizGetAttemptDataResponse> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetAttemptDataWSParams = { attemptid: attemptId, page: page, preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', true, ), }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAttemptDataCacheKey(attemptId, page), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const result = await site.read<AddonModQuizGetAttemptDataWSResponse>('mod_quiz_get_attempt_data', params, preSets); result.questions = CoreQuestion.parseQuestions(result.questions); return result; } /** * Get an attempt's due date. * * @param quiz Quiz. * @param attempt Attempt. * @return Attempt's due date, 0 if no due date or invalid data. */ getAttemptDueDate(quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData): number { const deadlines: number[] = []; if (quiz.timelimit && attempt.timestart) { deadlines.push(attempt.timestart + quiz.timelimit); } if (quiz.timeclose) { deadlines.push(quiz.timeclose); } if (!deadlines.length) { return 0; } // Get min due date. const dueDate: number = Math.min.apply(null, deadlines); if (!dueDate) { return 0; } switch (attempt.state) { case AddonModQuizProvider.ATTEMPT_IN_PROGRESS: return dueDate * 1000; case AddonModQuizProvider.ATTEMPT_OVERDUE: return (dueDate + quiz.graceperiod!) * 1000; default: this.logger.warn('Unexpected state when getting due date: ' + attempt.state); return 0; } } /** * Get an attempt's warning because of due date. * * @param quiz Quiz. * @param attempt Attempt. * @return Attempt's warning, undefined if no due date. */ getAttemptDueDateWarning(quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData): string | undefined { const dueDate = this.getAttemptDueDate(quiz, attempt); if (attempt.state === AddonModQuizProvider.ATTEMPT_OVERDUE) { return Translate.instant( 'addon.mod_quiz.overduemustbesubmittedby', { $a: CoreTimeUtils.userDate(dueDate) }, ); } else if (dueDate) { return Translate.instant('addon.mod_quiz.mustbesubmittedby', { $a: CoreTimeUtils.userDate(dueDate) }); } } /** * Turn attempt's state into a readable state, including some extra data depending on the state. * * @param quiz Quiz. * @param attempt Attempt. * @return List of state sentences. */ getAttemptReadableState(quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttempt): string[] { if (attempt.finishedOffline) { return [Translate.instant('addon.mod_quiz.finishnotsynced')]; } switch (attempt.state) { case AddonModQuizProvider.ATTEMPT_IN_PROGRESS: return [Translate.instant('addon.mod_quiz.stateinprogress')]; case AddonModQuizProvider.ATTEMPT_OVERDUE: { const sentences: string[] = []; const dueDate = this.getAttemptDueDate(quiz, attempt); sentences.push(Translate.instant('addon.mod_quiz.stateoverdue')); if (dueDate) { sentences.push(Translate.instant( 'addon.mod_quiz.stateoverduedetails', { $a: CoreTimeUtils.userDate(dueDate) }, )); } return sentences; } case AddonModQuizProvider.ATTEMPT_FINISHED: return [ Translate.instant('addon.mod_quiz.statefinished'), Translate.instant( 'addon.mod_quiz.statefinisheddetails', { $a: CoreTimeUtils.userDate(attempt.timefinish! * 1000) }, ), ]; case AddonModQuizProvider.ATTEMPT_ABANDONED: return [Translate.instant('addon.mod_quiz.stateabandoned')]; default: return []; } } /** * Turn attempt's state into a readable state name, without any more data. * * @param state State. * @return Readable state name. */ getAttemptReadableStateName(state: string): string { switch (state) { case AddonModQuizProvider.ATTEMPT_IN_PROGRESS: return Translate.instant('addon.mod_quiz.stateinprogress'); case AddonModQuizProvider.ATTEMPT_OVERDUE: return Translate.instant('addon.mod_quiz.stateoverdue'); case AddonModQuizProvider.ATTEMPT_FINISHED: return Translate.instant('addon.mod_quiz.statefinished'); case AddonModQuizProvider.ATTEMPT_ABANDONED: return Translate.instant('addon.mod_quiz.stateabandoned'); default: return ''; } } /** * Get cache key for get attempt review WS calls. * * @param attemptId Attempt ID. * @param page Page. * @return Cache key. */ protected getAttemptReviewCacheKey(attemptId: number, page: number): string { return this.getAttemptReviewCommonCacheKey(attemptId) + ':' + page; } /** * Get common cache key for get attempt review WS calls. * * @param attemptId Attempt ID. * @return Cache key. */ protected getAttemptReviewCommonCacheKey(attemptId: number): string { return ROOT_CACHE_KEY + 'attemptReview:' + attemptId; } /** * Get an attempt's review. * * @param attemptId Attempt ID. * @param options Other options. * @return Promise resolved with the attempt review. */ async getAttemptReview( attemptId: number, options: AddonModQuizGetAttemptReviewOptions = {}, ): Promise<AddonModQuizGetAttemptReviewResponse> { const page = typeof options.page == 'undefined' ? -1 : options.page; const site = await CoreSites.getSite(options.siteId); const params = { attemptid: attemptId, page: page, }; const preSets = { cacheKey: this.getAttemptReviewCacheKey(attemptId, page), cacheErrors: ['noreview'], component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const result = await site.read<AddonModQuizGetAttemptReviewWSResponse>('mod_quiz_get_attempt_review', params, preSets); result.questions = CoreQuestion.parseQuestions(result.questions); return result; } /** * Get cache key for get attempt summary WS calls. * * @param attemptId Attempt ID. * @return Cache key. */ protected getAttemptSummaryCacheKey(attemptId: number): string { return ROOT_CACHE_KEY + 'attemptSummary:' + attemptId; } /** * Get an attempt's summary. * * @param attemptId Attempt ID. * @param preflightData Preflight required data (like password). * @param options Other options. * @return Promise resolved with the list of questions for the attempt summary. */ async getAttemptSummary( attemptId: number, preflightData: Record<string, string>, options: AddonModQuizGetAttemptSummaryOptions = {}, ): Promise<CoreQuestionQuestionParsed[]> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetAttemptSummaryWSParams = { attemptid: attemptId, preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', true, ), }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getAttemptSummaryCacheKey(attemptId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModQuizGetAttemptSummaryWSResponse>('mod_quiz_get_attempt_summary', params, preSets); const questions = CoreQuestion.parseQuestions(response.questions); if (options.loadLocal) { return AddonModQuizOffline.loadQuestionsLocalStates(attemptId, questions, site.getId()); } return questions; } /** * Get cache key for get combined review options WS calls. * * @param quizId Quiz ID. * @param userId User ID. * @return Cache key. */ protected getCombinedReviewOptionsCacheKey(quizId: number, userId: number): string { return this.getCombinedReviewOptionsCommonCacheKey(quizId) + ':' + userId; } /** * Get common cache key for get combined review options WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getCombinedReviewOptionsCommonCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'combinedReviewOptions:' + quizId; } /** * Get a quiz combined review options. * * @param quizId Quiz ID. * @param options Other options. * @return Promise resolved with the combined review options. */ async getCombinedReviewOptions( quizId: number, options: AddonModQuizUserOptions = {}, ): Promise<AddonModQuizCombinedReviewOptions> { const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModQuizGetCombinedReviewOptionsWSParams = { quizid: quizId, userid: userId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getCombinedReviewOptionsCacheKey(quizId, userId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModQuizGetCombinedReviewOptionsWSResponse>( 'mod_quiz_get_combined_review_options', params, preSets, ); // Convert the arrays to objects with name -> value. return { someoptions: <Record<string, number>> CoreUtils.objectToKeyValueMap(response.someoptions, 'name', 'value'), alloptions: <Record<string, number>> CoreUtils.objectToKeyValueMap(response.alloptions, 'name', 'value'), warnings: response.warnings, }; } /** * Get cache key for get feedback for grade WS calls. * * @param quizId Quiz ID. * @param grade Grade. * @return Cache key. */ protected getFeedbackForGradeCacheKey(quizId: number, grade: number): string { return this.getFeedbackForGradeCommonCacheKey(quizId) + ':' + grade; } /** * Get common cache key for get feedback for grade WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getFeedbackForGradeCommonCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'feedbackForGrade:' + quizId; } /** * Get the feedback for a certain grade. * * @param quizId Quiz ID. * @param grade Grade. * @param options Other options. * @return Promise resolved with the feedback. */ async getFeedbackForGrade( quizId: number, grade: number, options: CoreCourseCommonModWSOptions = {}, ): Promise<AddonModQuizGetQuizFeedbackForGradeWSResponse> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizFeedbackForGradeWSParams = { quizid: quizId, grade: grade, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getFeedbackForGradeCacheKey(quizId, grade), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_quiz_feedback_for_grade', params, preSets); } /** * Determine the correct number of decimal places required to format a grade. * Based on Moodle's quiz_get_grade_format. * * @param quiz Quiz. * @return Number of decimals. */ getGradeDecimals(quiz: AddonModQuizQuizWSData): number { if (typeof quiz.questiondecimalpoints == 'undefined') { quiz.questiondecimalpoints = -1; } if (quiz.questiondecimalpoints == -1) { return quiz.decimalpoints!; } return quiz.questiondecimalpoints; } /** * Gets a quiz grade and feedback from the gradebook. * * @param courseId Course ID. * @param moduleId Quiz module ID. * @param ignoreCache Whether it should ignore cached data (it will always fail in offline or server down). * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined use site's current user. * @return Promise resolved with an object containing the grade and the feedback. */ async getGradeFromGradebook( courseId: number, moduleId: number, ignoreCache?: boolean, siteId?: string, userId?: number, ): Promise<CoreGradesFormattedItem | CoreGradesFormattedRow | undefined> { const items = await CoreGradesHelper.getGradeModuleItems( courseId, moduleId, userId, undefined, siteId, ignoreCache, ); return items.shift(); } /** * Given a list of attempts, returns the last finished attempt. * * @param attempts Attempts. * @return Last finished attempt. */ getLastFinishedAttemptFromList(attempts?: AddonModQuizAttemptWSData[]): AddonModQuizAttemptWSData | undefined { return attempts?.find(attempt => this.isAttemptFinished(attempt.state)); } /** * Given a list of questions, check if the quiz can be submitted. * Will return an array with the messages to prevent the submit. Empty array if quiz can be submitted. * * @param questions Questions. * @return List of prevent submit messages. Empty array if quiz can be submitted. */ getPreventSubmitMessages(questions: CoreQuestionQuestionParsed[]): string[] { const messages: string[] = []; questions.forEach((question) => { if (question.type != 'random' && !CoreQuestionDelegate.isQuestionSupported(question.type)) { // The question isn't supported. messages.push(Translate.instant('core.question.questionmessage', { $a: question.slot, $b: Translate.instant('core.question.errorquestionnotsupported', { $a: question.type }), })); } else { let message = CoreQuestionDelegate.getPreventSubmitMessage(question); if (message) { message = Translate.instant(message); messages.push(Translate.instant('core.question.questionmessage', { $a: question.slot, $b: message })); } } }); return messages; } /** * Get cache key for quiz data WS calls. * * @param courseId Course ID. * @return Cache key. */ protected getQuizDataCacheKey(courseId: number): string { return ROOT_CACHE_KEY + 'quiz:' + courseId; } /** * Get a Quiz with key=value. If more than one is found, only the first will be returned. * * @param courseId Course ID. * @param key Name of the property to check. * @param value Value to search. * @param options Other options. * @return Promise resolved when the Quiz is retrieved. */ protected async getQuizByField( courseId: number, key: string, value: unknown, options: CoreSitesCommonWSOptions = {}, ): Promise<AddonModQuizQuizWSData> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizzesByCoursesWSParams = { courseids: [courseId], }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getQuizDataCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModQuizProvider.COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModQuizGetQuizzesByCoursesWSResponse>( 'mod_quiz_get_quizzes_by_courses', params, preSets, ); // Search the quiz. const quiz = response.quizzes.find(quiz => quiz[key] == value); if (!quiz) { throw new CoreError('Quiz not found.'); } return quiz; } /** * Get a quiz by module ID. * * @param courseId Course ID. * @param cmId Course module ID. * @param options Other options. * @return Promise resolved when the quiz is retrieved. */ getQuiz(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModQuizQuizWSData> { return this.getQuizByField(courseId, 'coursemodule', cmId, options); } /** * Get a quiz by quiz ID. * * @param courseId Course ID. * @param id Quiz ID. * @param options Other options. * @return Promise resolved when the quiz is retrieved. */ getQuizById(courseId: number, id: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModQuizQuizWSData> { return this.getQuizByField(courseId, 'id', id, options); } /** * Get cache key for get quiz access information WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getQuizAccessInformationCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'quizAccessInformation:' + quizId; } /** * Get access information for an attempt. * * @param quizId Quiz ID. * @param options Other options. * @return Promise resolved with the access information. */ async getQuizAccessInformation( quizId: number, options: CoreCourseCommonModWSOptions = {}, ): Promise<AddonModQuizGetQuizAccessInformationWSResponse> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizAccessInformationWSParams = { quizid: quizId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getQuizAccessInformationCacheKey(quizId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_quiz_access_information', params, preSets); } /** * Get a readable Quiz grade method. * * @param method Grading method. * @return Readable grading method. */ getQuizGradeMethod(method?: number | string): string { if (method === undefined) { return ''; } if (typeof method == 'string') { method = parseInt(method, 10); } switch (method) { case AddonModQuizProvider.GRADEHIGHEST: return Translate.instant('addon.mod_quiz.gradehighest'); case AddonModQuizProvider.GRADEAVERAGE: return Translate.instant('addon.mod_quiz.gradeaverage'); case AddonModQuizProvider.ATTEMPTFIRST: return Translate.instant('addon.mod_quiz.attemptfirst'); case AddonModQuizProvider.ATTEMPTLAST: return Translate.instant('addon.mod_quiz.attemptlast'); default: return ''; } } /** * Get cache key for get quiz required qtypes WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getQuizRequiredQtypesCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'quizRequiredQtypes:' + quizId; } /** * Get the potential question types that would be required for a given quiz. * * @param quizId Quiz ID. * @param options Other options. * @return Promise resolved with the access information. */ async getQuizRequiredQtypes(quizId: number, options: CoreCourseCommonModWSOptions = {}): Promise<string[]> { const site = await CoreSites.getSite(options.siteId); const params: AddonModQuizGetQuizRequiredQtypesWSParams = { quizid: quizId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getQuizRequiredQtypesCacheKey(quizId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModQuizGetQuizRequiredQtypesWSResponse>( 'mod_quiz_get_quiz_required_qtypes', params, preSets, ); return response.questiontypes; } /** * Given an attempt's layout, return the list of pages. * * @param layout Attempt's layout. * @return Pages. * @description * An attempt's layout is a string with the question numbers separated by commas. A 0 indicates a change of page. * Example: 1,2,3,0,4,5,6,0 * In the example above, first page has questions 1, 2 and 3. Second page has questions 4, 5 and 6. * * This function returns a list of pages. */ getPagesFromLayout(layout?: string): number[] { if (!layout) { return []; } const split = layout.split(','); const pages: number[] = []; let page = 0; for (let i = 0; i < split.length; i++) { if (split[i] == '0') { pages.push(page); page++; } } return pages; } /** * Given an attempt's layout and a list of questions identified by question slot, * return the list of pages that have at least 1 of the questions. * * @param layout Attempt's layout. * @param questions List of questions. It needs to be an object where the keys are question slot. * @return Pages. * @description * An attempt's layout is a string with the question numbers separated by commas. A 0 indicates a change of page. * Example: 1,2,3,0,4,5,6,0 * In the example above, first page has questions 1, 2 and 3. Second page has questions 4, 5 and 6. * * This function returns a list of pages. */ getPagesFromLayoutAndQuestions(layout: string, questions: AddonModQuizQuestionsWithAnswers): number[] { const split = layout.split(','); const pages: number[] = []; let page = 0; let pageAdded = false; for (let i = 0; i < split.length; i++) { const value = Number(split[i]); if (value == 0) { page++; pageAdded = false; } else if (!pageAdded && questions[value]) { pages.push(page); pageAdded = true; } } return pages; } /** * Given a list of question types, returns the types that aren't supported. * * @param questionTypes Question types to check. * @return Not supported question types. */ getUnsupportedQuestions(questionTypes: string[]): string[] { const notSupported: string[] = []; questionTypes.forEach((type) => { if (type != 'random' && !CoreQuestionDelegate.isQuestionSupported(type)) { notSupported.push(type); } }); return notSupported; } /** * Given a list of access rules names, returns the rules that aren't supported. * * @param rulesNames Rules to check. * @return Not supported rules names. */ getUnsupportedRules(rulesNames: string[]): string[] { const notSupported: string[] = []; rulesNames.forEach((name) => { if (!AddonModQuizAccessRuleDelegate.isAccessRuleSupported(name)) { notSupported.push(name); } }); return notSupported; } /** * Get cache key for get user attempts WS calls. * * @param quizId Quiz ID. * @param userId User ID. * @return Cache key. */ protected getUserAttemptsCacheKey(quizId: number, userId: number): string { return this.getUserAttemptsCommonCacheKey(quizId) + ':' + userId; } /** * Get common cache key for get user attempts WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getUserAttemptsCommonCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'userAttempts:' + quizId; } /** * Get quiz attempts for a certain user. * * @param quizId Quiz ID. * @param options Other options. * @return Promise resolved with the attempts. */ async getUserAttempts( quizId: number, options: AddonModQuizGetUserAttemptsOptions = {}, ): Promise<AddonModQuizAttemptWSData[]> { const status = options.status || 'all'; const includePreviews = typeof options.includePreviews == 'undefined' ? true : options.includePreviews; const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModQuizGetUserAttemptsWSParams = { quizid: quizId, userid: userId, status: status, includepreviews: !!includePreviews, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getUserAttemptsCacheKey(quizId, userId), updateFrequency: CoreSite.FREQUENCY_SOMETIMES, component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModQuizGetUserAttemptsWSResponse>('mod_quiz_get_user_attempts', params, preSets); return response.attempts; } /** * Get cache key for get user best grade WS calls. * * @param quizId Quiz ID. * @param userId User ID. * @return Cache key. */ protected getUserBestGradeCacheKey(quizId: number, userId: number): string { return this.getUserBestGradeCommonCacheKey(quizId) + ':' + userId; } /** * Get common cache key for get user best grade WS calls. * * @param quizId Quiz ID. * @return Cache key. */ protected getUserBestGradeCommonCacheKey(quizId: number): string { return ROOT_CACHE_KEY + 'userBestGrade:' + quizId; } /** * Get best grade in a quiz for a certain user. * * @param quizId Quiz ID. * @param options Other options. * @return Promise resolved with the best grade data. */ async getUserBestGrade(quizId: number, options: AddonModQuizUserOptions = {}): Promise<AddonModQuizGetUserBestGradeWSResponse> { const site = await CoreSites.getSite(options.siteId); const userId = options.userId || site.getUserId(); const params: AddonModQuizGetUserBestGradeWSParams = { quizid: quizId, userid: userId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getUserBestGradeCacheKey(quizId, userId), component: AddonModQuizProvider.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return site.read('mod_quiz_get_user_best_grade', params, preSets); } /** * Invalidates all the data related to a certain quiz. * * @param quizId Quiz ID. * @param courseId Course ID. * @param attemptId Attempt ID to invalidate some WS calls. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined use site's current user. * @return Promise resolved when the data is invalidated. */ async invalidateAllQuizData( quizId: number, courseId?: number, attemptId?: number, siteId?: string, userId?: number, ): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); const promises: Promise<void>[] = []; promises.push(this.invalidateAttemptAccessInformation(quizId, siteId)); promises.push(this.invalidateCombinedReviewOptionsForUser(quizId, siteId, userId)); promises.push(this.invalidateFeedback(quizId, siteId)); promises.push(this.invalidateQuizAccessInformation(quizId, siteId)); promises.push(this.invalidateQuizRequiredQtypes(quizId, siteId)); promises.push(this.invalidateUserAttemptsForUser(quizId, siteId, userId)); promises.push(this.invalidateUserBestGradeForUser(quizId, siteId, userId)); if (attemptId) { promises.push(this.invalidateAttemptData(attemptId, siteId)); promises.push(this.invalidateAttemptReview(attemptId, siteId)); promises.push(this.invalidateAttemptSummary(attemptId, siteId)); } if (courseId) { promises.push(this.invalidateGradeFromGradebook(courseId, siteId, userId)); } await Promise.all(promises); } /** * Invalidates attempt access information for all attempts in a quiz. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptAccessInformation(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAttemptAccessInformationCommonCacheKey(quizId)); } /** * Invalidates attempt access information for an attempt. * * @param quizId Quiz ID. * @param attemptId Attempt ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptAccessInformationForAttempt(quizId: number, attemptId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptAccessInformationCacheKey(quizId, attemptId)); } /** * Invalidates attempt data for all pages. * * @param attemptId Attempt ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptData(attemptId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAttemptDataCommonCacheKey(attemptId)); } /** * Invalidates attempt data for a certain page. * * @param attemptId Attempt ID. * @param page Page. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptDataForPage(attemptId: number, page: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptDataCacheKey(attemptId, page)); } /** * Invalidates attempt review for all pages. * * @param attemptId Attempt ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptReview(attemptId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getAttemptReviewCommonCacheKey(attemptId)); } /** * Invalidates attempt review for a certain page. * * @param attemptId Attempt ID. * @param page Page. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptReviewForPage(attemptId: number, page: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptReviewCacheKey(attemptId, page)); } /** * Invalidates attempt summary. * * @param attemptId Attempt ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAttemptSummary(attemptId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getAttemptSummaryCacheKey(attemptId)); } /** * Invalidates combined review options for all users. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateCombinedReviewOptions(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getCombinedReviewOptionsCommonCacheKey(quizId)); } /** * Invalidates combined review options for a certain user. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined use site's current user. * @return Promise resolved when the data is invalidated. */ async invalidateCombinedReviewOptionsForUser(quizId: number, siteId?: string, userId?: number): Promise<void> { const site = await CoreSites.getSite(siteId); return site.invalidateWsCacheForKey(this.getCombinedReviewOptionsCacheKey(quizId, userId || site.getUserId())); } /** * Invalidate the prefetched content except files. * * @param moduleId The module ID. * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); // Get required data to call the invalidate functions. const quiz = await this.getQuiz(courseId, moduleId, { readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE, siteId, }); const attempts = await this.getUserAttempts(quiz.id, { cmId: moduleId, siteId }); // Now invalidate it. const lastAttemptId = attempts.length ? attempts[attempts.length - 1].id : undefined; await this.invalidateAllQuizData(quiz.id, courseId, lastAttemptId, siteId); } /** * Invalidates feedback for all grades of a quiz. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateFeedback(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getFeedbackForGradeCommonCacheKey(quizId)); } /** * Invalidates feedback for a certain grade. * * @param quizId Quiz ID. * @param grade Grade. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateFeedbackForGrade(quizId: number, grade: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getFeedbackForGradeCacheKey(quizId, grade)); } /** * Invalidates grade from gradebook for a certain user. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined use site's current user. * @return Promise resolved when the data is invalidated. */ async invalidateGradeFromGradebook(courseId: number, siteId?: string, userId?: number): Promise<void> { const site = await CoreSites.getSite(siteId); await CoreGradesHelper.invalidateGradeModuleItems(courseId, userId || site.getUserId(), undefined, siteId); } /** * Invalidates quiz access information for a quiz. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateQuizAccessInformation(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuizAccessInformationCacheKey(quizId)); } /** * Invalidates required qtypes for a quiz. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateQuizRequiredQtypes(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuizRequiredQtypesCacheKey(quizId)); } /** * Invalidates user attempts for all users. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateUserAttempts(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserAttemptsCommonCacheKey(quizId)); } /** * Invalidates user attempts for a certain user. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined use site's current user. * @return Promise resolved when the data is invalidated. */ async invalidateUserAttemptsForUser(quizId: number, siteId?: string, userId?: number): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserAttemptsCacheKey(quizId, userId || site.getUserId())); } /** * Invalidates user best grade for all users. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateUserBestGrade(quizId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getUserBestGradeCommonCacheKey(quizId)); } /** * Invalidates user best grade for a certain user. * * @param quizId Quiz ID. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined use site's current user. * @return Promise resolved when the data is invalidated. */ async invalidateUserBestGradeForUser(quizId: number, siteId?: string, userId?: number): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getUserBestGradeCacheKey(quizId, userId || site.getUserId())); } /** * Invalidates quiz data. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateQuizData(courseId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getQuizDataCacheKey(courseId)); } /** * Check if an attempt is finished based on its state. * * @param state Attempt's state. * @return Whether it's finished. */ isAttemptFinished(state?: string): boolean { return state == AddonModQuizProvider.ATTEMPT_FINISHED || state == AddonModQuizProvider.ATTEMPT_ABANDONED; } /** * Check if an attempt is finished in offline but not synced. * * @param attemptId Attempt ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: true if finished in offline but not synced, false otherwise. */ async isAttemptFinishedOffline(attemptId: number, siteId?: string): Promise<boolean> { try { const attempt = await AddonModQuizOffline.getAttemptById(attemptId, siteId); return !!attempt.finished; } catch { return false; } } /** * Check if an attempt is nearly over. We consider an attempt nearly over or over if: * - Is not in progress * OR * - It finished before autosaveperiod passes. * * @param quiz Quiz. * @param attempt Attempt. * @return Whether it's nearly over or over. */ isAttemptTimeNearlyOver(quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData): boolean { if (attempt.state != AddonModQuizProvider.ATTEMPT_IN_PROGRESS) { // Attempt not in progress, return true. return true; } const dueDate = this.getAttemptDueDate(quiz, attempt); const autoSavePeriod = quiz.autosaveperiod || 0; if (dueDate > 0 && Date.now() + autoSavePeriod >= dueDate) { return true; } return false; } /** * Check if last attempt is offline and unfinished. * * @param attemptId Attempt ID. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined, user current site's user. * @return Promise resolved with boolean: true if last offline attempt is unfinished, false otherwise. */ async isLastAttemptOfflineUnfinished(quiz: AddonModQuizQuizWSData, siteId?: string, userId?: number): Promise<boolean> { try { const attempts = await AddonModQuizOffline.getQuizAttempts(quiz.id, siteId, userId); const last = attempts.pop(); return !!last && !last.finished; } catch { return false; } } /** * Check if a quiz navigation is sequential. * * @param quiz Quiz. * @return Whether navigation is sequential. */ isNavigationSequential(quiz: AddonModQuizQuizWSData): boolean { return quiz.navmethod == 'sequential'; } /** * Check if a question is blocked. * * @param question Question. * @return Whether it's blocked. */ isQuestionBlocked(question: CoreQuestionQuestionParsed): boolean { const element = CoreDomUtils.convertToElement(question.html); return !!element.querySelector('.mod_quiz-blocked_question_warning'); } /** * Check if a quiz is enabled to be used in offline. * * @param quiz Quiz. * @return Whether offline is enabled. */ isQuizOffline(quiz: AddonModQuizQuizWSData): boolean { // Don't allow downloading the quiz if offline is disabled to prevent wasting a lot of data when opening it. return !!quiz.allowofflineattempts && !CoreSites.getCurrentSite()?.isOfflineDisabled(); } /** * Report an attempt as being viewed. It did not store logs offline because order of the log is important. * * @param attemptId Attempt ID. * @param page Page number. * @param preflightData Preflight required data (like password). * @param offline Whether attempt is offline. * @param quiz Quiz instance. If set, a Firebase event will be stored. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ async logViewAttempt( attemptId: number, page: number = 0, preflightData: Record<string, string> = {}, offline?: boolean, quiz?: AddonModQuizQuizWSData, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonModQuizViewAttemptWSParams = { attemptid: attemptId, page: page, preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', ), }; const promises: Promise<unknown>[] = []; promises.push(site.write('mod_quiz_view_attempt', params)); if (offline) { promises.push(AddonModQuizOffline.setAttemptCurrentPage(attemptId, page, site.getId())); } if (quiz) { CorePushNotifications.logViewEvent( quiz.id, quiz.name, 'quiz', 'mod_quiz_view_attempt', { attemptid: attemptId, page }, siteId, ); } await Promise.all(promises); } /** * Report an attempt's review as being viewed. * * @param attemptId Attempt ID. * @param quizId Quiz ID. * @param name Name of the quiz. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ logViewAttemptReview(attemptId: number, quizId: number, name?: string, siteId?: string): Promise<void> { const params: AddonModQuizViewAttemptReviewWSParams = { attemptid: attemptId, }; return CoreCourseLogHelper.logSingle( 'mod_quiz_view_attempt_review', params, AddonModQuizProvider.COMPONENT, quizId, name, 'quiz', params, siteId, ); } /** * Report an attempt's summary as being viewed. * * @param attemptId Attempt ID. * @param preflightData Preflight required data (like password). * @param quizId Quiz ID. * @param name Name of the quiz. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ logViewAttemptSummary( attemptId: number, preflightData: Record<string, string>, quizId: number, name?: string, siteId?: string, ): Promise<void> { const params: AddonModQuizViewAttemptSummaryWSParams = { attemptid: attemptId, preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', ), }; return CoreCourseLogHelper.logSingle( 'mod_quiz_view_attempt_summary', params, AddonModQuizProvider.COMPONENT, quizId, name, 'quiz', { attemptid: attemptId }, siteId, ); } /** * Report a quiz as being viewed. * * @param id Module ID. * @param name Name of the quiz. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ logViewQuiz(id: number, name?: string, siteId?: string): Promise<void> { const params: AddonModQuizViewQuizWSParams = { quizid: id, }; return CoreCourseLogHelper.logSingle( 'mod_quiz_view_quiz', params, AddonModQuizProvider.COMPONENT, id, name, 'quiz', {}, siteId, ); } /** * Process an attempt, saving its data. * * @param quiz Quiz. * @param attempt Attempt. * @param data Data to save. * @param preflightData Preflight required data (like password). * @param finish Whether to finish the quiz. * @param timeUp Whether the quiz time is up, false otherwise. * @param offline Whether the attempt is offline. * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success, rejected otherwise. */ async processAttempt( quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData, data: CoreQuestionsAnswers, preflightData: Record<string, string>, finish?: boolean, timeUp?: boolean, offline?: boolean, siteId?: string, ): Promise<void> { if (offline) { return this.processAttemptOffline(quiz, attempt, data, preflightData, finish, siteId); } await this.processAttemptOnline(attempt.id, data, preflightData, finish, timeUp, siteId); } /** * Process an online attempt, saving its data. * * @param attemptId Attempt ID. * @param data Data to save. * @param preflightData Preflight required data (like password). * @param finish Whether to finish the quiz. * @param timeUp Whether the quiz time is up, false otherwise. * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success, rejected otherwise. */ protected async processAttemptOnline( attemptId: number, data: CoreQuestionsAnswers, preflightData: Record<string, string>, finish?: boolean, timeUp?: boolean, siteId?: string, ): Promise<string> { const site = await CoreSites.getSite(siteId); const params: AddonModQuizProcessAttemptWSParams = { attemptid: attemptId, data: CoreUtils.objectToArrayOfObjects(data, 'name', 'value'), finishattempt: !!finish, timeup: !!timeUp, preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', ), }; const response = await site.write<AddonModQuizProcessAttemptWSResponse>('mod_quiz_process_attempt', params); if (response.warnings?.length) { // Reject with the first warning. throw new CoreWSError(response.warnings[0]); } return response.state; } /** * Process an offline attempt, saving its data. * * @param quiz Quiz. * @param attempt Attempt. * @param data Data to save. * @param preflightData Preflight required data (like password). * @param finish Whether to finish the quiz. * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success, rejected otherwise. */ protected async processAttemptOffline( quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData, data: CoreQuestionsAnswers, preflightData: Record<string, string>, finish?: boolean, siteId?: string, ): Promise<void> { // Get attempt summary to have the list of questions. const questionsArray = await this.getAttemptSummary(attempt.id, preflightData, { cmId: quiz.coursemodule, loadLocal: true, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE, siteId, }); // Convert the question array to an object. const questions = CoreUtils.arrayToObject(questionsArray, 'slot'); return AddonModQuizOffline.processAttempt(quiz, attempt, questions, data, finish, siteId); } /** * Check if it's a graded quiz. Based on Moodle's quiz_has_grades. * * @param quiz Quiz. * @return Whether quiz is graded. */ quizHasGrades(quiz: AddonModQuizQuizWSData): boolean { return quiz.grade! >= 0.000005 && quiz.sumgrades! >= 0.000005; } /** * Convert the raw grade into a grade out of the maximum grade for this quiz. * Based on Moodle's quiz_rescale_grade. * * @param rawGrade The unadjusted grade, for example attempt.sumgrades. * @param quiz Quiz. * @param format True to format the results for display, 'question' to format a question grade * (different number of decimal places), false to not format it. * @return Grade to display. */ rescaleGrade( rawGrade: string | number | undefined | null, quiz: AddonModQuizQuizWSData, format: boolean | string = true, ): string | undefined { let grade: number | undefined; const rawGradeNum = typeof rawGrade == 'string' ? parseFloat(rawGrade) : rawGrade; if (rawGradeNum !== undefined && rawGradeNum !== null && !isNaN(rawGradeNum)) { if (quiz.sumgrades! >= 0.000005) { grade = rawGradeNum * quiz.grade! / quiz.sumgrades!; } else { grade = 0; } } if (grade === null || grade === undefined) { return; } if (format === 'question') { return this.formatGrade(grade, this.getGradeDecimals(quiz)); } else if (format) { return this.formatGrade(grade, quiz.decimalpoints!); } return String(grade); } /** * Save an attempt data. * * @param quiz Quiz. * @param attempt Attempt. * @param data Data to save. * @param preflightData Preflight required data (like password). * @param offline Whether attempt is offline. * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success, rejected otherwise. */ async saveAttempt( quiz: AddonModQuizQuizWSData, attempt: AddonModQuizAttemptWSData, data: CoreQuestionsAnswers, preflightData: Record<string, string>, offline?: boolean, siteId?: string, ): Promise<void> { try { if (offline) { return await this.processAttemptOffline(quiz, attempt, data, preflightData, false, siteId); } await this.saveAttemptOnline(attempt.id, data, preflightData, siteId); } catch (error) { this.logger.error(error); throw error; } } /** * Save an attempt data. * * @param attemptId Attempt ID. * @param data Data to save. * @param preflightData Preflight required data (like password). * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success, rejected otherwise. */ protected async saveAttemptOnline( attemptId: number, data: CoreQuestionsAnswers, preflightData: Record<string, string>, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonModQuizSaveAttemptWSParams = { attemptid: attemptId, data: CoreUtils.objectToArrayOfObjects(data, 'name', 'value'), preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', ), }; const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_quiz_save_attempt', params); if (response.warnings?.length) { // Reject with the first warning. throw new CoreWSError(response.warnings[0]); } else if (!response.status) { // It shouldn't happen that status is false and no warnings were returned. throw new CoreError('Cannot save data.'); } } /** * Check if time left should be shown. * * @param rules List of active rules names. * @param attempt Attempt. * @param endTime The attempt end time (in seconds). * @return Whether time left should be displayed. */ shouldShowTimeLeft(rules: string[], attempt: AddonModQuizAttemptWSData, endTime: number): boolean { const timeNow = CoreTimeUtils.timestamp(); if (attempt.state != AddonModQuizProvider.ATTEMPT_IN_PROGRESS) { return false; } return AddonModQuizAccessRuleDelegate.shouldShowTimeLeft(rules, attempt, endTime, timeNow); } /** * Start an attempt. * * @param quizId Quiz ID. * @param preflightData Preflight required data (like password). * @param forceNew Whether to force a new attempt or not. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the attempt data. */ async startAttempt( quizId: number, preflightData: Record<string, string>, forceNew?: boolean, siteId?: string, ): Promise<AddonModQuizAttemptWSData> { const site = await CoreSites.getSite(siteId); const params: AddonModQuizStartAttemptWSParams = { quizid: quizId, preflightdata: CoreUtils.objectToArrayOfObjects<AddonModQuizPreflightDataWSParam>( preflightData, 'name', 'value', ), forcenew: !!forceNew, }; const response = await site.write<AddonModQuizStartAttemptWSResponse>('mod_quiz_start_attempt', params); if (response.warnings?.length) { // Reject with the first warning. throw new CoreWSError(response.warnings[0]); } return response.attempt; } } export const AddonModQuiz = makeSingleton(AddonModQuizProvider); /** * Common options with user ID. */ export type AddonModQuizUserOptions = CoreCourseCommonModWSOptions & { userId?: number; // User ID. If not defined use site's current user. }; /** * Options to pass to getAllQuestionsData. */ export type AddonModQuizAllQuestionsDataOptions = CoreCourseCommonModWSOptions & { pages?: number[]; // List of pages to get. If not defined, all pages. }; /** * Options to pass to getAttemptReview. */ export type AddonModQuizGetAttemptReviewOptions = CoreCourseCommonModWSOptions & { page?: number; // List of pages to get. If not defined, all pages. }; /** * Options to pass to getAttemptSummary. */ export type AddonModQuizGetAttemptSummaryOptions = CoreCourseCommonModWSOptions & { loadLocal?: boolean; // Whether it should load local state for each question. }; /** * Options to pass to getUserAttempts. */ export type AddonModQuizGetUserAttemptsOptions = CoreCourseCommonModWSOptions & { status?: string; // Status of the attempts to get. By default, 'all'. includePreviews?: boolean; // Whether to include previews. Defaults to true. userId?: number; // User ID. If not defined use site's current user. }; /** * Preflight data in the format accepted by the WebServices. */ type AddonModQuizPreflightDataWSParam = { name: string; // Data name. value: string; // Data value. }; /** * Params of mod_quiz_get_attempt_access_information WS. */ export type AddonModQuizGetAttemptAccessInformationWSParams = { quizid: number; // Quiz instance id. attemptid?: number; // Attempt id, 0 for the user last attempt if exists. }; /** * Data returned by mod_quiz_get_attempt_access_information WS. */ export type AddonModQuizGetAttemptAccessInformationWSResponse = { endtime?: number; // When the attempt must be submitted (determined by rules). isfinished: boolean; // Whether there is no way the user will ever be allowed to attempt. ispreflightcheckrequired?: boolean; // Whether a check is required before the user starts/continues his attempt. preventnewattemptreasons: string[]; // List of reasons. warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_get_attempt_data WS. */ export type AddonModQuizGetAttemptDataWSParams = { attemptid: number; // Attempt id. page: number; // Page number. preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). }; /** * Data returned by mod_quiz_get_attempt_data WS. */ export type AddonModQuizGetAttemptDataWSResponse = { attempt: AddonModQuizAttemptWSData; messages: string[]; // Access messages, will only be returned for users with mod/quiz:preview capability. nextpage: number; // Next page number. questions: CoreQuestionQuestionWSData[]; warnings?: CoreWSExternalWarning[]; }; /** * Attempt data returned by several WebServices. */ export type AddonModQuizAttemptWSData = { id: number; // Attempt id. quiz?: number; // Foreign key reference to the quiz that was attempted. userid?: number; // Foreign key reference to the user whose attempt this is. attempt?: number; // Sequentially numbers this students attempts at this quiz. uniqueid?: number; // Foreign key reference to the question_usage that holds the details of the the question_attempts. layout?: string; // Attempt layout. currentpage?: number; // Attempt current page. preview?: number; // Whether is a preview attempt or not. state?: string; // The current state of the attempts. 'inprogress', 'overdue', 'finished' or 'abandoned'. timestart?: number; // Time when the attempt was started. timefinish?: number; // Time when the attempt was submitted. 0 if the attempt has not been submitted yet. timemodified?: number; // Last modified time. timemodifiedoffline?: number; // Last modified time via webservices. timecheckstate?: number; // Next time quiz cron should check attempt for state changes. NULL means never check. sumgrades?: number | null; // Total marks for this attempt. }; /** * Get attempt data response with parsed questions. */ export type AddonModQuizGetAttemptDataResponse = Omit<AddonModQuizGetAttemptDataWSResponse, 'questions'> & { questions: CoreQuestionQuestionParsed[]; }; /** * Params of mod_quiz_get_attempt_review WS. */ export type AddonModQuizGetAttemptReviewWSParams = { attemptid: number; // Attempt id. page?: number; // Page number, empty for all the questions in all the pages. }; /** * Data returned by mod_quiz_get_attempt_review WS. */ export type AddonModQuizGetAttemptReviewWSResponse = { grade: string; // Grade for the quiz (or empty or "notyetgraded"). attempt: AddonModQuizAttemptWSData; additionaldata: AddonModQuizWSAdditionalData[]; questions: CoreQuestionQuestionWSData[]; warnings?: CoreWSExternalWarning[]; }; /** * Additional data returned by mod_quiz_get_attempt_review WS. */ export type AddonModQuizWSAdditionalData = { id: string; // Id of the data. title: string; // Data title. content: string; // Data content. }; /** * Get attempt review response with parsed questions. */ export type AddonModQuizGetAttemptReviewResponse = Omit<AddonModQuizGetAttemptReviewWSResponse, 'questions'> & { questions: CoreQuestionQuestionParsed[]; }; /** * Params of mod_quiz_get_attempt_summary WS. */ export type AddonModQuizGetAttemptSummaryWSParams = { attemptid: number; // Attempt id. preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). }; /** * Data returned by mod_quiz_get_attempt_summary WS. */ export type AddonModQuizGetAttemptSummaryWSResponse = { questions: CoreQuestionQuestionWSData[]; warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_get_combined_review_options WS. */ export type AddonModQuizGetCombinedReviewOptionsWSParams = { quizid: number; // Quiz instance id. userid?: number; // User id (empty for current user). }; /** * Data returned by mod_quiz_get_combined_review_options WS. */ export type AddonModQuizGetCombinedReviewOptionsWSResponse = { someoptions: AddonModQuizWSReviewOption[]; alloptions: AddonModQuizWSReviewOption[]; warnings?: CoreWSExternalWarning[]; }; /** * Option data returned by mod_quiz_get_combined_review_options. */ export type AddonModQuizWSReviewOption = { name: string; // Option name. value: number; // Option value. }; /** * Data returned by mod_quiz_get_combined_review_options WS, formatted to convert the options to objects. */ export type AddonModQuizCombinedReviewOptions = Omit<AddonModQuizGetCombinedReviewOptionsWSResponse, 'alloptions'|'someoptions'> & { someoptions: Record<string, number>; alloptions: Record<string, number>; }; /** * Params of mod_quiz_get_quiz_feedback_for_grade WS. */ export type AddonModQuizGetQuizFeedbackForGradeWSParams = { quizid: number; // Quiz instance id. grade: number; // The grade to check. }; /** * Data returned by mod_quiz_get_quiz_feedback_for_grade WS. */ export type AddonModQuizGetQuizFeedbackForGradeWSResponse = { feedbacktext: string; // The comment that corresponds to this grade (empty for none). feedbacktextformat?: number; // Feedbacktext format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). feedbackinlinefiles?: CoreWSExternalFile[]; warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_get_quizzes_by_courses WS. */ export type AddonModQuizGetQuizzesByCoursesWSParams = { courseids?: number[]; // Array of course ids. }; /** * Data returned by mod_quiz_get_quizzes_by_courses WS. */ export type AddonModQuizGetQuizzesByCoursesWSResponse = { quizzes: AddonModQuizQuizWSData[]; warnings?: CoreWSExternalWarning[]; }; /** * Quiz data returned by mod_quiz_get_quizzes_by_courses WS. */ export type AddonModQuizQuizWSData = { id: number; // Standard Moodle primary key. course: number; // Foreign key reference to the course this quiz is part of. coursemodule: number; // Course module id. name: string; // Quiz name. intro?: string; // Quiz introduction text. introformat?: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). introfiles?: CoreWSExternalFile[]; timeopen?: number; // The time when this quiz opens. (0 = no restriction.). timeclose?: number; // The time when this quiz closes. (0 = no restriction.). timelimit?: number; // The time limit for quiz attempts, in seconds. overduehandling?: string; // The method used to handle overdue attempts. 'autosubmit', 'graceperiod' or 'autoabandon'. graceperiod?: number; // The amount of time (in seconds) after time limit during which attempts can still be submitted. preferredbehaviour?: string; // The behaviour to ask questions to use. canredoquestions?: number; // Allows students to redo any completed question within a quiz attempt. attempts?: number; // The maximum number of attempts a student is allowed. attemptonlast?: number; // Whether subsequent attempts start from the answer to the previous attempt (1) or start blank (0). grademethod?: number; // One of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE, QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST. decimalpoints?: number; // Number of decimal points to use when displaying grades. questiondecimalpoints?: number; // Number of decimal points to use when displaying question grades. reviewattempt?: number; // Whether users are allowed to review their quiz attempts at various times. reviewcorrectness?: number; // Whether users are allowed to review their quiz attempts at various times. reviewmarks?: number; // Whether users are allowed to review their quiz attempts at various times. reviewspecificfeedback?: number; // Whether users are allowed to review their quiz attempts at various times. reviewgeneralfeedback?: number; // Whether users are allowed to review their quiz attempts at various times. reviewrightanswer?: number; // Whether users are allowed to review their quiz attempts at various times. reviewoverallfeedback?: number; // Whether users are allowed to review their quiz attempts at various times. questionsperpage?: number; // How often to insert a page break when editing the quiz, or when shuffling the question order. navmethod?: string; // Any constraints on how the user is allowed to navigate around the quiz. shuffleanswers?: number; // Whether the parts of the question should be shuffled, in those question types that support it. sumgrades?: number | null; // The total of all the question instance maxmarks. grade?: number; // The total that the quiz overall grade is scaled to be out of. timecreated?: number; // The time when the quiz was added to the course. timemodified?: number; // Last modified time. password?: string; // A password that the student must enter before starting or continuing a quiz attempt. subnet?: string; // Used to restrict the IP addresses from which this quiz can be attempted. browsersecurity?: string; // Restriciton on the browser the student must use. E.g. 'securewindow'. delay1?: number; // Delay that must be left between the first and second attempt, in seconds. delay2?: number; // Delay that must be left between the second and subsequent attempt, in seconds. showuserpicture?: number; // Option to show the user's picture during the attempt and on the review page. showblocks?: number; // Whether blocks should be shown on the attempt.php and review.php pages. completionattemptsexhausted?: number; // Mark quiz complete when the student has exhausted the maximum number of attempts. completionpass?: number; // Whether to require passing grade. allowofflineattempts?: number; // Whether to allow the quiz to be attempted offline in the mobile app. autosaveperiod?: number; // Auto-save delay. hasfeedback?: number; // Whether the quiz has any non-blank feedback text. hasquestions?: number; // Whether the quiz has questions. section?: number; // Course section id. visible?: number; // Module visibility. groupmode?: number; // Group mode. groupingid?: number; // Grouping id. }; /** * Params of mod_quiz_get_quiz_access_information WS. */ export type AddonModQuizGetQuizAccessInformationWSParams = { quizid: number; // Quiz instance id. }; /** * Data returned by mod_quiz_get_quiz_access_information WS. */ export type AddonModQuizGetQuizAccessInformationWSResponse = { canattempt: boolean; // Whether the user can do the quiz or not. canmanage: boolean; // Whether the user can edit the quiz settings or not. canpreview: boolean; // Whether the user can preview the quiz or not. canreviewmyattempts: boolean; // Whether the users can review their previous attempts or not. canviewreports: boolean; // Whether the user can view the quiz reports or not. accessrules: string[]; // List of rules. activerulenames: string[]; // List of active rules. preventaccessreasons: string[]; // List of reasons. warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_get_quiz_required_qtypes WS. */ export type AddonModQuizGetQuizRequiredQtypesWSParams = { quizid: number; // Quiz instance id. }; /** * Data returned by mod_quiz_get_quiz_required_qtypes WS. */ export type AddonModQuizGetQuizRequiredQtypesWSResponse = { questiontypes: string[]; // List of question types used in the quiz. warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_get_user_attempts WS. */ export type AddonModQuizGetUserAttemptsWSParams = { quizid: number; // Quiz instance id. userid?: number; // User id, empty for current user. status?: string; // Quiz status: all, finished or unfinished. includepreviews?: boolean; // Whether to include previews or not. }; /** * Data returned by mod_quiz_get_user_attempts WS. */ export type AddonModQuizGetUserAttemptsWSResponse = { attempts: AddonModQuizAttemptWSData[]; warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_get_user_best_grade WS. */ export type AddonModQuizGetUserBestGradeWSParams = { quizid: number; // Quiz instance id. userid?: number; // User id. }; /** * Data returned by mod_quiz_get_user_best_grade WS. */ export type AddonModQuizGetUserBestGradeWSResponse = { hasgrade: boolean; // Whether the user has a grade on the given quiz. grade?: number; // The grade (only if the user has a grade). gradetopass?: number; // @since 3.11. The grade to pass the quiz (only if set). warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_view_attempt WS. */ export type AddonModQuizViewAttemptWSParams = { attemptid: number; // Attempt id. page: number; // Page number. preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). }; /** * Params of mod_quiz_process_attempt WS. */ export type AddonModQuizProcessAttemptWSParams = { attemptid: number; // Attempt id. data?: { // The data to be saved. name: string; // Data name. value: string; // Data value. }[]; finishattempt?: boolean; // Whether to finish or not the attempt. timeup?: boolean; // Whether the WS was called by a timer when the time is up. preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). }; /** * Data returned by mod_quiz_process_attempt WS. */ export type AddonModQuizProcessAttemptWSResponse = { state: string; // The new attempt state: inprogress, finished, overdue, abandoned. warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_save_attempt WS. */ export type AddonModQuizSaveAttemptWSParams = { attemptid: number; // Attempt id. data: { // The data to be saved. name: string; // Data name. value: string; // Data value. }[]; preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). }; /** * Params of mod_quiz_start_attempt WS. */ export type AddonModQuizStartAttemptWSParams = { quizid: number; // Quiz instance id. preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). forcenew?: boolean; // Whether to force a new attempt or not. }; /** * Data returned by mod_quiz_start_attempt WS. */ export type AddonModQuizStartAttemptWSResponse = { attempt: AddonModQuizAttemptWSData; warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_quiz_view_attempt_review WS. */ export type AddonModQuizViewAttemptReviewWSParams = { attemptid: number; // Attempt id. }; /** * Params of mod_quiz_view_attempt_summary WS. */ export type AddonModQuizViewAttemptSummaryWSParams = { attemptid: number; // Attempt id. preflightdata?: AddonModQuizPreflightDataWSParam[]; // Preflight required data (like passwords). }; /** * Params of mod_quiz_view_quiz WS. */ export type AddonModQuizViewQuizWSParams = { quizid: number; // Quiz instance id. }; /** * Data passed to ATTEMPT_FINISHED_EVENT event. */ export type AddonModQuizAttemptFinishedData = { quizId: number; attemptId: number; synced: boolean; };
the_stack
import { css } from "@emotion/react"; import dynamic from "next/dynamic"; import { useRouter } from "next/router"; import React, { useEffect } from "react"; import { atom, useAtom } from "jotai"; import { Button } from "dyson/src/components/atoms"; import { Conditional } from "dyson/src/components/layouts"; import { BackSVG } from "@svg/builds"; import { LayoutSVG, ReportSVG } from "@svg/dashboard"; import { CalendarSVG, FailedSVG, InitiatedSVG, PassedSVG, RerunSVG, ReviewRequiredSVG, RunningSVG, TestStatusSVG, ThunderSVG } from "@svg/testReport"; import { backendRequest } from "@utils/common/backendRequest"; import { timeSince } from "@utils/common/dateTimeUtils"; import { sendSnackBarEvent } from "@utils/common/notify"; import { getAllConfiguration, getStatusString, showReviewButton, getCountByTestStatus } from "@utils/core/buildReportUtils"; import { usePageTitle } from "../../../hooks/seo"; import { useBuildReport } from "../../../store/serverState/buildReports"; import { RequestMethod } from "../../../types/RequestOptions"; import { updateMeta } from "../../../store/mutators/metaData"; import { PROJECT_META_KEYS, USER_META_KEYS } from "@constants/USER"; import { useMemo } from "react"; import { TestTypeLabel } from "@constants/test"; const ReportSection = dynamic(() => import("./testList")); function TitleSection() { const router = useRouter(); const { query } = router; const { data } = useBuildReport(query.id); return ( <div> <div className={"font-cera text-19 font-700 leading-none flex items-center"} id={"title"}> <BackSVG height={"22rem"} className={"mr-12"} onClick={() => { router.push("/app/builds"); }} />{" "} {data?.name} #{data?.id} </div> </div> ); } function StatusTag({ type }) { if (type === "MANUAL_REVIEW_REQUIRED") { return ( <div className={"flex items-center px-12 justify-center mr-8"} css={[statusTag, review]}> <ReviewRequiredSVG height={"17rem"} isMonochrome={true} /> <span className={"ml-16 text-14 font-600 ml-8 leading-none"}>Review required</span> </div> ); } if (type === "FAILED") { return ( <div className={"flex items-center px-12 justify-center mr-8"} css={[statusTag, failed]}> <FailedSVG height={"17rem"} isMonochrome={true} /> <span className={"ml-16 text-14 font-600 ml-8 leading-none"}>Failed</span> </div> ); } if (type === "PASSED") { return ( <div className={"flex items-center px-12 justify-center mr-8"} css={[statusTag, passed]}> <PassedSVG height={"20rem"} isMonochrome={true} /> <span className={"ml-16 text-14 font-600 ml-8 leading-none"}>Passed</span> </div> ); } if (type === "RUNNING") { return ( <div className={"flex items-center px-12 justify-center mr-8"} css={[statusTag, running]}> <RunningSVG height={"16rem"} isMonochrome={true} /> <span className={"ml-16 text-14 font-600 ml-8 leading-none"}>Running</span> </div> ); } return ( <div className={"flex items-center px-12 justify-center mr-8"} css={[statusTag, waiting]}> <InitiatedSVG height={"16rem"} isMonochrome={true} /> <span className={"ml-16 text-14 font-600 ml-8 leading-none"}>Waiting</span> </div> ); } function NameNStatusSection() { const { query } = useRouter(); const { data } = useBuildReport(query.id); const title = data.name || `#${data?.id}`; usePageTitle(title); return ( <div className={"flex items-center justify-between"}> <div className={"flex items-center"}> <TitleSection /> <Button size={"small"} bgColor={"tertiary"} className={"ml-20"} css={css` width: 96rem; `} onClick={rerunBuild.bind(this, query.id)} title="Rerun this build" > <div className={"flex items-center justify-center text-13 font-400"}> <RerunSVG className={"mr-6"} height={"14rem"} /> Rerun </div> </Button> {/*<ThreeEllipsisSVG className={"ml-22"} width={"25rem"} />*/} </div> <StatusTag type={data.status} isMonochrome={true} /> </div> ); } const section = [ { name: "Overview", icon: <LayoutSVG height={"10rem"} width={"10rem"} />, key: "overview", }, { name: "Test report", icon: ( <ReportSVG height={"12rem"} width={"12rem"} css={css` margin-right: -2rem; `} /> ), key: "reports", }, // { // name: "History", // icon: null, // }, ]; const selectedTabAtom = atom(0); export const rerunBuild = async (buildId) => { await backendRequest(`/builds/${buildId}/actions/rerun`, { method: RequestMethod.POST, }); sendSnackBarEvent({ type: "normal", message: "We've started new build" }); }; function TabBar() { const [selectedTabIndex, setSelectedTabIndex] = useAtom(selectedTabAtom); return ( <div css={Tab} className={"flex mt-48 "}> {section.map(({ name, icon, key }, i) => ( <div onClick={setSelectedTabIndex.bind(this, i)} key={key}> <div css={[TabItem, selectedTabIndex === i && selected]} className={`flex items-center justify-center text-15`}> <Conditional showIf={icon}> <span className={"mr-8"}>{icon}</span> </Conditional> {name} </div> </div> ))} </div> ); } function ConfigurationMethod({ configType, array }) { return ( <div className={"text-13 mb-16"}> <span className={"text-13 font-600 capitalize"}>{configType}</span> <span className={"capitalize ml-32"} css={css` font-size: 12.8rem; `} > {array.join(", ").toLowerCase()} </span> </div> ); } function TestOverviewTab() { const { query } = useRouter(); const { data } = useBuildReport(query.id); const [, setSelectedTabIndex] = useAtom(selectedTabAtom); const showReview = showReviewButton(data?.status); const allConfiguration = getAllConfiguration(data?.tests); const countByTestStatus = useMemo(() => { return getCountByTestStatus(data?.tests); }, [data]); return ( <div className={"flex mt-48 justify-between"}> <div css={leftSection}> <div css={overviewCard} className={"flex flex-col items-center justify-center pt-120"}> <div className={"flex flex-col items-center"}> <div className={"mb-28"}> <TestStatusSVG type={data?.status} height={"24rem"} width={"28rem"} /> </div> <div className={"font-cera text-15 font-500 mb-24"}>{getStatusString(data?.status)}</div> <div className={"flex items-center"}> <Conditional showIf={showReview}> <Button bgColor={"tertiary"} css={css` width: 148rem; `} onClick={setSelectedTabIndex.bind(this, 1)} > <span className={"font-400"}>Review</span> </Button> </Conditional> <Button bgColor={"tertiary"} css={css` width: 148rem; `} className={"ml-16"} onClick={rerunBuild.bind(this, query.id)} title="Rerun this build" > <div className={"flex items-center justify-center text-13 font-400"}> <RerunSVG className={"mr-6"} height={"14rem"} /> Rerun </div> </Button> </div> <div className={"mt-60 text-14 font-600 mb-24"}>Your test were run on</div> {Object.entries(allConfiguration).map(([key, value]) => ( <ConfigurationMethod configType={key} array={value} /> ))} </div> <div css={css` background: #0a0b0e; height: 64rem; `} className={"flex text-12.5 font-600 w-full mt-100 justify-center"} > {Object.entries(countByTestStatus).map(([status, count]) => { return ( <div className={"flex items-center px-28"}> <TestStatusSVG type={status} height={"18rem"} width={"18rem"} />{" "} <span className={"ml-12 leading-none"}> {count} {TestTypeLabel[status]} </span> </div> ); })} </div> </div> </div> <div css={rightSection} className={"ml-36 pt-12"}> {/* <div className={"mb-32"}> <div className={"font-600 text-14 mb-16"}>Reviewers</div> <div css={tag} className={"text-13 px-18 py-7 mb-12"}> Himanshu </div> <div css={tag} className={"text-13 px-18 py-7"}> Himanshu </div> </div> */} <div> <div className={"font-600 text-14 mb-16"}>Environments</div> <div css={tag} className={"text-13 px-18 py-7 mb-12"}> Production </div> </div> </div> </div> ); } const tag = css` background: rgba(16, 18, 21, 0.5); border: 1rem solid #171c24; border-radius: 4px; height: 32px; `; const overviewCard = css` width: 100%; min-height: 500px; background: rgba(16, 18, 21, 0.5); border: 1px solid #171c24; box-sizing: border-box; border-radius: 4px; overflow: hidden; `; const leftSection = css` width: 70%; `; const rightSection = css` width: 30%; max-width: 315px; `; export const TestReportScreen = () => { const [selectedTabIndex, setSelectedTabIndex] = useAtom(selectedTabAtom); const { query } = useRouter(); const { data } = useBuildReport(query.id); const [, updateMetaData] = useAtom(updateMeta); const testsCount = data.tests.length; useEffect(() => { updateMetaData({ type: "user", key: USER_META_KEYS.VIEW_REPORT, value: true, }); updateMetaData({ type: "project", key: PROJECT_META_KEYS.VIEW_REPORT, value: true, }); if (query.view_draft) setSelectedTabIndex(1); }, [query.view_draft]); return ( <div className={"px-16 mt-56"}> <NameNStatusSection /> <div className={"flex items-center leading-none mt-16 text-13"}> <CalendarSVG className={"mr-16"} /> Ran {timeSince(new Date(data.startedAt))} </div> <Conditional showIf={selectedTabIndex !== 1}> <div className={"flex items-center leading-none mt-56 mb-57 text-13"}> <ThunderSVG className={"mr-16"} /> Wohoo! You ran {testsCount} tests </div> </Conditional> <Conditional showIf={selectedTabIndex === 1}> <div className={"flex leading-none mt-56 mb-52 items-center invisible"}> <div className={"text-13"} css={css` width: 100px; line-height: 19rem; `} > Last build </div> <div css={timeLine} className={"ml-40 relative"}> <div className={"absolute flex flex-col items-center"} css={currentSelected}> <div className={"mb-8 text-12"}>12Jun</div> <div> <PassedSVG /> </div> </div> <div className={"absolute flex flex-col items-center"} css={timelineItem}> <div> <PassedSVG /> </div> </div> </div> </div> </Conditional> <TabBar /> <Conditional showIf={selectedTabIndex === 0}> <TestOverviewTab /> </Conditional> <Conditional showIf={selectedTabIndex === 1}> <ReportSection /> </Conditional> </div> ); }; const timeLine = css` height: 2px; width: 100%; background: #1e242c; `; const currentSelected = css` position: absolute; transform: translateY(-72%); `; const timelineItem = css` position: absolute; transform: translateY(-50%); left: 50%; `; const statusTag = css` min-width: 140px; height: 30px; box-sizing: border-box; border-radius: 15.5px; `; const failed = css` background: rgba(152, 38, 127, 0.8); border: 1px solid rgba(255, 64, 213, 0.46); `; const passed = css` background: #416a3e; border: 1px solid #64ae59; `; const review = css` background: #44293c; border: 1px solid #77516c; min-width: 172px; `; const running = css` background: #1e242c; border: 1px solid #545e6b; `; const waiting = css` border: 1px solid #545e6b; `; const Tab = css` border-bottom: 1px solid #1e242c; `; const TabItem = css` top: 1px; position: relative; height: 37px; min-width: 143px; padding: 0 24px; padding-top: 1rem !important; :hover { color: #fff; font-weight: 600; } `; const selected = css` top: 1px; position: relative; border: 1px solid #1e242c; border-radius: 6px 6px 0 0; border-bottom: 1px solid #0a0b0e; color: #fff; font-weight: 600; padding-top: 1px; `;
the_stack
import { AfterViewInit, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subject, Subscription } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { sortBy } from 'lodash-es'; import { Course } from 'app/entities/course.model'; import { CourseManagementService } from 'app/course/manage/course-management.service'; import dayjs from 'dayjs/esm'; import { Exercise, ExerciseType, IncludedInOverallScore } from 'app/entities/exercise.model'; import { CourseScoreCalculationService, ScoreType } from 'app/overview/course-score-calculation.service'; import { InitializationState } from 'app/entities/participation/participation.model'; import { roundValueSpecifiedByCourseSettings } from 'app/shared/util/utils'; import { GradeType } from 'app/entities/grading-scale.model'; import { GradingSystemService } from 'app/grading-system/grading-system.service'; import { GradeDTO } from 'app/entities/grade-step.model'; import { Color, LegendPosition, ScaleType } from '@swimlane/ngx-charts'; import { faClipboard, faFilter, faQuestionCircle } from '@fortawesome/free-solid-svg-icons'; import { BarControlConfiguration, BarControlConfigurationProvider } from 'app/overview/course-overview.component'; import { GraphColors } from 'app/entities/statistics.model'; import { NgxChartsSingleSeriesDataEntry } from 'app/shared/chart/ngx-charts-datatypes'; import { ArtemisNavigationUtilService } from 'app/utils/navigation.utils'; const QUIZ_EXERCISE_COLOR = '#17a2b8'; const PROGRAMMING_EXERCISE_COLOR = '#fd7e14'; const MODELING_EXERCISE_COLOR = '#6610f2'; const TEXT_EXERCISE_COLOR = '#B00B6B'; const FILE_UPLOAD_EXERCISE_COLOR = '#2D9C88'; type ExerciseTypeMap = { [type in ExerciseType]: number; }; interface YourOverallPointsEntry extends NgxChartsSingleSeriesDataEntry { color: string; } enum ChartBarTitle { NO_DUE_DATE = 'No due date', INCLUDED = 'Achieved (included)', NOT_INCLUDED = 'Achieved (not included)', BONUS = 'Achieved bonus', NOT_GRADED = 'Not graded', MISSED = 'Missed points', } @Component({ selector: 'jhi-course-statistics', templateUrl: './course-statistics.component.html', styleUrls: ['../course-overview.scss'], }) export class CourseStatisticsComponent implements OnInit, OnDestroy, AfterViewInit, BarControlConfigurationProvider { courseId: number; private courseExercises: Exercise[]; private paramSubscription?: Subscription; private courseUpdatesSubscription: Subscription; private translateSubscription: Subscription; course?: Course; exerciseCategories: Set<string> = new Set(); exerciseCategoryFilters: Map<string, boolean> = new Map(); numberOfAppliedFilters: number; allCategoriesSelected = true; includeExercisesWithNoCategory = true; private courseExercisesNotIncludedInScore: Exercise[]; private courseExercisesFilteredByCategories: Exercise[]; currentlyHidingNotIncludedInScoreExercises: boolean; filteredExerciseIDs: number[]; // Icons faFilter = faFilter; // TODO: improve the types here and use maps instead of java script objects, also avoid the use of 'any' // overall points overallPoints = 0; overallPointsPerExercise: ExerciseTypeMap; // relative score totalRelativeScore = 0; relativeScoresPerExercise: ExerciseTypeMap; // max points overallMaxPoints = 0; overallMaxPointsPerExercise: ExerciseTypeMap; // reachable points reachablePoints = 0; reachablePointsPerExercise: ExerciseTypeMap; // current relative score currentRelativeScore = 0; currentRelativeScoresPerExercise: ExerciseTypeMap; // presentation score overallPresentationScore = 0; presentationScoresPerExercise: ExerciseTypeMap; doughnutChartColors: string[] = [PROGRAMMING_EXERCISE_COLOR, QUIZ_EXERCISE_COLOR, MODELING_EXERCISE_COLOR, TEXT_EXERCISE_COLOR, FILE_UPLOAD_EXERCISE_COLOR, GraphColors.RED]; public exerciseTitles: object = { quiz: { name: this.translateService.instant('artemisApp.course.quizExercises'), color: QUIZ_EXERCISE_COLOR, }, modeling: { name: this.translateService.instant('artemisApp.course.modelingExercises'), color: MODELING_EXERCISE_COLOR, }, programming: { name: this.translateService.instant('artemisApp.course.programmingExercises'), color: PROGRAMMING_EXERCISE_COLOR, }, text: { name: this.translateService.instant('artemisApp.course.textExercises'), color: TEXT_EXERCISE_COLOR, }, 'file-upload': { name: this.translateService.instant('artemisApp.course.fileUploadExercises'), color: FILE_UPLOAD_EXERCISE_COLOR, }, }; // ngx-charts ngxDoughnutData: YourOverallPointsEntry[] = []; // Labels for the different parts in Your overall points chart programmingPointLabel = 'programmingPointLabel'; quizPointLabel = 'quizPointLabel'; modelingPointLabel = 'modelingPointLabel'; textPointLabel = 'textPointLabel'; fileUploadPointLabel = 'fileUploadPointLabel'; missingPointsLabel = 'missingPointsLabel'; labels = [this.programmingPointLabel, this.quizPointLabel, this.modelingPointLabel, this.textPointLabel, this.fileUploadPointLabel, this.missingPointsLabel]; ngxDoughnutColor = { name: 'Your overall points color', selectable: true, group: ScaleType.Ordinal, domain: [], // colors: orange, turquoise, violet, bordeaux, green, red } as Color; // arrays representing each exercise group ngxModelingExercises: any[] = []; ngxProgrammingExercises: any[] = []; ngxQuizExercises: any[] = []; ngxFileUploadExercises: any[] = []; ngxTextExercises: any[] = []; // flags determining for each exercise group if at least one exercise has presentation score enabled quizPresentationScoreEnabled = false; programmingPresentationScoreEnabled = false; modelingPresentationScoreEnabled = false; textPresentationScoreEnabled = false; fileUploadPresentationScoreEnabled = false; ngxBarColor = { name: 'Score per exercise group', selectable: true, group: ScaleType.Ordinal, domain: [GraphColors.LIGHT_GREY, GraphColors.GREEN, GraphColors.LIGHT_GREY, GraphColors.YELLOW, GraphColors.BLUE, GraphColors.RED], } as Color; readonly roundScoreSpecifiedByCourseSettings = roundValueSpecifiedByCourseSettings; readonly legendPosition = LegendPosition; readonly barChartTitle = ChartBarTitle; readonly chartHeight = 25; readonly barPadding = 4; readonly defaultSize = 50; // additional space for the x-axis and its labels // array containing every non-empty exercise group ngxExerciseGroups: any[] = []; gradingScaleExists = false; isBonus = false; gradeDTO?: GradeDTO; // Icons faQuestionCircle = faQuestionCircle; faClipboard = faClipboard; // The extracted controls template from our template to be rendered in the top bar of "CourseOverviewComponent" @ViewChild('controls', { static: false }) private controls: TemplateRef<any>; // Provides the control configuration to be read and used by "CourseOverviewComponent" public readonly controlConfiguration: BarControlConfiguration = { subject: new Subject<TemplateRef<any>>(), useIndentation: false, }; constructor( private courseService: CourseManagementService, private courseCalculationService: CourseScoreCalculationService, private translateService: TranslateService, private route: ActivatedRoute, private gradingSystemService: GradingSystemService, private navigationUtilService: ArtemisNavigationUtilService, ) {} ngOnInit() { // Note: due to lazy loading and router outlet, we use parent 2x here this.paramSubscription = this.route.parent?.parent?.params.subscribe((params) => { this.courseId = parseInt(params['courseId'], 10); }); this.course = this.courseCalculationService.getCourse(this.courseId); this.onCourseLoad(); this.courseUpdatesSubscription = this.courseService.getCourseUpdates(this.courseId).subscribe((course: Course) => { this.courseCalculationService.updateCourse(course); this.course = this.courseCalculationService.getCourse(this.courseId); this.onCourseLoad(); }); this.translateSubscription = this.translateService.onLangChange.subscribe(() => { this.exerciseTitles = { quiz: { name: this.translateService.instant('artemisApp.course.quizExercises'), color: QUIZ_EXERCISE_COLOR, }, modeling: { name: this.translateService.instant('artemisApp.course.modelingExercises'), color: MODELING_EXERCISE_COLOR, }, programming: { name: this.translateService.instant('artemisApp.course.programmingExercises'), color: PROGRAMMING_EXERCISE_COLOR, }, text: { name: this.translateService.instant('artemisApp.course.textExercises'), color: TEXT_EXERCISE_COLOR, }, 'file-upload': { name: this.translateService.instant('artemisApp.course.fileUploadExercises'), color: FILE_UPLOAD_EXERCISE_COLOR, }, }; this.groupExercisesByType(this.courseExercises); this.ngxExerciseGroups = [...this.ngxExerciseGroups]; }); this.calculateCourseGrade(); } ngAfterViewInit() { // Send our controls template to parent so it will be rendered in the top bar if (this.controls) { this.controlConfiguration.subject!.next(this.controls); } } ngOnDestroy() { this.translateSubscription.unsubscribe(); this.courseUpdatesSubscription.unsubscribe(); this.paramSubscription?.unsubscribe(); } private calculateCourseGrade(): void { this.gradingSystemService.matchPercentageToGradeStep(this.totalRelativeScore, this.courseId).subscribe((gradeDTO) => { if (gradeDTO) { this.gradingScaleExists = true; this.gradeDTO = gradeDTO; this.isBonus = gradeDTO.gradeType === GradeType.BONUS; } }); } private onCourseLoad(): void { if (this.course?.exercises) { this.courseExercises = this.course.exercises; this.calculateAndFilterNotIncludedInScore(); this.calculateMaxPoints(); this.calculateReachablePoints(); this.calculateAbsoluteScores(); this.calculateRelativeScores(); this.calculatePresentationScores(); this.calculateCurrentRelativeScores(); this.groupExercisesByType(this.courseExercises); } } /** * Sorts exercises into their corresponding exercise groups and creates dedicated objects that * can be processed by ngx-charts in order to visualize the students score for each exercise * @param exercises the exercises that should be grouped * @private */ private groupExercisesByType(exercises: Exercise[]): void { const exerciseTypes: string[] = []; this.ngxExerciseGroups = []; // this reset is now necessary because of the filtering option that triggers the grouping again. this.ngxModelingExercises = []; this.ngxProgrammingExercises = []; this.ngxQuizExercises = []; this.ngxFileUploadExercises = []; this.ngxTextExercises = []; this.quizPresentationScoreEnabled = false; this.programmingPresentationScoreEnabled = false; this.modelingPresentationScoreEnabled = false; this.textPresentationScoreEnabled = false; this.fileUploadPresentationScoreEnabled = false; // adding several years to be sure that exercises without due date are sorted at the end. this is necessary for the order inside the statistic charts exercises = sortBy(exercises, [(exercise: Exercise) => (exercise.dueDate || dayjs().add(5, 'year')).valueOf()]); exercises.forEach((exercise) => { if (!exercise.dueDate || exercise.dueDate.isBefore(dayjs()) || exercise.type === ExerciseType.PROGRAMMING) { const index = exerciseTypes.indexOf(exercise.type!); if (index === -1) { exerciseTypes.push(exercise.type!); } const series = CourseStatisticsComponent.generateDefaultSeries(); if (!exercise.studentParticipations || exercise.studentParticipations.length === 0) { series[5].value = 100; series[5].afterDueDate = false; series[5].notParticipated = true; series[5].exerciseTitle = exercise.title; series[5].exerciseId = exercise.id; this.pushToData(exercise, series); } else { exercise.studentParticipations.forEach((participation) => { if (participation.results && participation.results.length > 0) { const participationResult = this.courseCalculationService.getResultForParticipation(participation, exercise.dueDate!); if (participationResult && participationResult.rated) { const roundedParticipationScore = roundValueSpecifiedByCourseSettings(participationResult.score!, this.course); const cappedParticipationScore = Math.min(roundedParticipationScore, 100); const missedScore = 100 - cappedParticipationScore; const replaced = participationResult.resultString!.replace(',', '.'); const split = replaced.split(' '); const missedPoints = Math.max(parseFloat(split[2]) - parseFloat(split[0]), 0); series[5].value = missedScore; series[5].absoluteValue = missedPoints; series[5].afterDueDate = false; series[5].notParticipated = false; series[5].exerciseId = exercise.id; this.identifyBar(exercise, series, roundedParticipationScore, parseFloat(split[0])); this.pushToData(exercise, series); } } else { if ( participation.initializationState === InitializationState.FINISHED && (!exercise.dueDate || participation.initializationDate!.isBefore(exercise.dueDate!)) ) { series[4].value = 100; series[4].exerciseTitle = exercise.title; series[4].exerciseId = exercise.id; this.pushToData(exercise, series); } else { series[5].value = 100; // If the user only presses "start exercise", there is still no participation if (participation.initializationState === InitializationState.INITIALIZED) { series[5].afterDueDate = false; series[5].notParticipated = true; } else { series[5].afterDueDate = true; } series[5].exerciseTitle = exercise.title; series[5].exerciseId = exercise.id; this.pushToData(exercise, series); } } }); } } }); const allGroups = [this.ngxProgrammingExercises, this.ngxQuizExercises, this.ngxModelingExercises, this.ngxTextExercises, this.ngxFileUploadExercises]; const allTypes = [ExerciseType.PROGRAMMING, ExerciseType.QUIZ, ExerciseType.MODELING, ExerciseType.TEXT, ExerciseType.FILE_UPLOAD]; this.pushExerciseGroupsToData(allGroups, allTypes); } toggleNotIncludedInScoreExercises() { if (this.currentlyHidingNotIncludedInScoreExercises) { this.courseExercises = this.courseExercises.concat(this.courseExercisesNotIncludedInScore); this.filteredExerciseIDs = []; } else { this.courseExercises = this.courseExercises.filter((exercise) => !this.courseExercisesNotIncludedInScore.includes(exercise)); this.filteredExerciseIDs = this.courseExercisesNotIncludedInScore.map((exercise) => exercise.id!); } this.currentlyHidingNotIncludedInScoreExercises = !this.currentlyHidingNotIncludedInScoreExercises; this.determineDisplayableCategories(); this.groupExercisesByType(this.courseExercises); } /** * Generates array containing default configuration for every possible part in one stacked bar * @private * @returns dedicated object that is requested by ngx-charts in order to visualize one bar in the horizontal bar chart */ private static generateDefaultSeries(): any[] { return [ { name: ChartBarTitle.NO_DUE_DATE, value: 0, absoluteValue: 0, exerciseId: 0 }, { name: ChartBarTitle.INCLUDED, value: 0, absoluteValue: 0, exerciseId: 0 }, { name: ChartBarTitle.NOT_INCLUDED, value: 0, absoluteValue: 0, exerciseId: 0 }, { name: ChartBarTitle.BONUS, value: 0, absoluteValue: 0, exerciseId: 0 }, { name: ChartBarTitle.NOT_GRADED, value: 0, exerciseTitle: '', exerciseId: 0 }, { name: ChartBarTitle.MISSED, value: 0, absoluteValue: 0, afterDueDate: false, notParticipated: false, exerciseTitle: '', exerciseId: 0 }, ]; } /** * Calculates absolute score for each exercise group in the course and adds it to the doughnut chart * @private */ private calculateAbsoluteScores(): void { const quizzesTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, ScoreType.ABSOLUTE_SCORE); const programmingExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ScoreType.ABSOLUTE_SCORE); const modelingExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ScoreType.ABSOLUTE_SCORE); const textExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ScoreType.ABSOLUTE_SCORE); const fileUploadExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ScoreType.ABSOLUTE_SCORE); this.overallPoints = this.calculateTotalScoreForTheCourse(ScoreType.ABSOLUTE_SCORE); let totalMissedPoints = this.reachablePoints - this.overallPoints; if (totalMissedPoints < 0) { totalMissedPoints = 0; } const scores = [programmingExerciseTotalScore, quizzesTotalScore, modelingExerciseTotalScore, textExerciseTotalScore, fileUploadExerciseTotalScore, totalMissedPoints]; const absoluteScores = {} as ExerciseTypeMap; absoluteScores[ExerciseType.QUIZ] = quizzesTotalScore; absoluteScores[ExerciseType.PROGRAMMING] = programmingExerciseTotalScore; absoluteScores[ExerciseType.MODELING] = modelingExerciseTotalScore; absoluteScores[ExerciseType.TEXT] = textExerciseTotalScore; absoluteScores[ExerciseType.FILE_UPLOAD] = fileUploadExerciseTotalScore; this.overallPointsPerExercise = absoluteScores; scores.forEach((score, index) => { if (score > 0) { this.ngxDoughnutData.push({ name: 'artemisApp.courseOverview.statistics.' + this.labels[index], value: score, color: this.doughnutChartColors[index], }); this.ngxDoughnutColor.domain.push(this.doughnutChartColors[index]); } }); this.ngxDoughnutData = [...this.ngxDoughnutData]; } /** * Calculates the maximum of points for the course * @private */ private calculateMaxPoints(): void { const quizzesTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, ScoreType.MAX_POINTS); const programmingExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ScoreType.MAX_POINTS); const modelingExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ScoreType.MAX_POINTS); const textExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ScoreType.MAX_POINTS); const fileUploadExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ScoreType.MAX_POINTS); const overallMaxPoints = {} as ExerciseTypeMap; overallMaxPoints[ExerciseType.QUIZ] = quizzesTotalMaxPoints; overallMaxPoints[ExerciseType.PROGRAMMING] = programmingExerciseTotalMaxPoints; overallMaxPoints[ExerciseType.MODELING] = modelingExerciseTotalMaxPoints; overallMaxPoints[ExerciseType.TEXT] = textExerciseTotalMaxPoints; overallMaxPoints[ExerciseType.FILE_UPLOAD] = fileUploadExerciseTotalMaxPoints; this.overallMaxPointsPerExercise = overallMaxPoints; this.overallMaxPoints = this.calculateTotalScoreForTheCourse(ScoreType.MAX_POINTS); } /** * Calculates the relative score for each exercise group in the course * @private */ private calculateRelativeScores(): void { const quizzesRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, ScoreType.RELATIVE_SCORE); const programmingExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ScoreType.RELATIVE_SCORE); const modelingExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ScoreType.RELATIVE_SCORE); const textExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ScoreType.RELATIVE_SCORE); const fileUploadExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ScoreType.RELATIVE_SCORE); const relativeScores = {} as ExerciseTypeMap; relativeScores[ExerciseType.QUIZ] = quizzesRelativeScore; relativeScores[ExerciseType.PROGRAMMING] = programmingExerciseRelativeScore; relativeScores[ExerciseType.MODELING] = modelingExerciseRelativeScore; relativeScores[ExerciseType.TEXT] = textExerciseRelativeScore; relativeScores[ExerciseType.FILE_UPLOAD] = fileUploadExerciseRelativeScore; this.relativeScoresPerExercise = relativeScores; this.totalRelativeScore = this.calculateTotalScoreForTheCourse(ScoreType.RELATIVE_SCORE); } /** * Calculates the reachable points for the course * @private */ private calculateReachablePoints(): void { const quizzesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, ScoreType.REACHABLE_POINTS); const programmingExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ScoreType.REACHABLE_POINTS); const modelingExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ScoreType.REACHABLE_POINTS); const textExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ScoreType.REACHABLE_POINTS); const fileUploadExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ScoreType.REACHABLE_POINTS); const reachablePoints = {} as ExerciseTypeMap; reachablePoints[ExerciseType.QUIZ] = quizzesReachablePoints; reachablePoints[ExerciseType.PROGRAMMING] = programmingExercisesReachablePoints; reachablePoints[ExerciseType.MODELING] = modelingExercisesReachablePoints; reachablePoints[ExerciseType.TEXT] = textExercisesReachablePoints; reachablePoints[ExerciseType.FILE_UPLOAD] = fileUploadExercisesReachablePoints; this.reachablePointsPerExercise = reachablePoints; this.reachablePoints = this.calculateTotalScoreForTheCourse(ScoreType.REACHABLE_POINTS); } /** * Calculates the current relative score for the course * @private */ private calculateCurrentRelativeScores(): void { const quizzesCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, ScoreType.CURRENT_RELATIVE_SCORE); const programmingExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ScoreType.CURRENT_RELATIVE_SCORE); const modelingExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ScoreType.CURRENT_RELATIVE_SCORE); const textExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ScoreType.CURRENT_RELATIVE_SCORE); const fileUploadExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ScoreType.CURRENT_RELATIVE_SCORE); const currentRelativeScores = {} as ExerciseTypeMap; currentRelativeScores[ExerciseType.QUIZ] = quizzesCurrentRelativeScore; currentRelativeScores[ExerciseType.PROGRAMMING] = programmingExerciseCurrentRelativeScore; currentRelativeScores[ExerciseType.MODELING] = modelingExerciseCurrentRelativeScore; currentRelativeScores[ExerciseType.TEXT] = textExerciseCurrentRelativeScore; currentRelativeScores[ExerciseType.FILE_UPLOAD] = fileUploadExerciseCurrentRelativeScore; this.currentRelativeScoresPerExercise = currentRelativeScores; this.currentRelativeScore = this.calculateTotalScoreForTheCourse(ScoreType.CURRENT_RELATIVE_SCORE); } /** * Calculates the presentation score for the course * @private */ private calculatePresentationScores(): void { const programmingExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ScoreType.PRESENTATION_SCORE); const modelingExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ScoreType.PRESENTATION_SCORE); const textExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ScoreType.PRESENTATION_SCORE); const fileUploadExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ScoreType.PRESENTATION_SCORE); // TODO: use a proper type here, e.g. a map const presentationScores = {} as ExerciseTypeMap; presentationScores[ExerciseType.QUIZ] = 0; presentationScores[ExerciseType.PROGRAMMING] = programmingExercisePresentationScore; presentationScores[ExerciseType.MODELING] = modelingExercisePresentationScore; presentationScores[ExerciseType.TEXT] = textExercisePresentationScore; presentationScores[ExerciseType.FILE_UPLOAD] = fileUploadExercisePresentationScore; this.presentationScoresPerExercise = presentationScores; this.overallPresentationScore = this.calculateTotalScoreForTheCourse(ScoreType.PRESENTATION_SCORE); } /** * Calculates the total score for every exercise in the course satisfying the filter function * @param filterFunction the filter the exercises have to satisfy * @returns map containing score for every score type * @private */ private calculateScores(filterFunction: (courseExercise: Exercise) => boolean): Map<string, number> { let courseExercises = this.courseExercises; if (filterFunction) { courseExercises = courseExercises.filter(filterFunction); } return this.courseCalculationService.calculateTotalScores(courseExercises, this.course!); } /** * Calculates an arbitrary score type for an arbitrary exercise type * @param exerciseType the exercise type for which the score should be calculated. Must be an element of {Programming, Modeling, Quiz, Text, File upload} * @param scoreType the score type that should be calculated. Element of {Absolute score, Max points,Current relative score,Presentation score,Reachable points,Relative score} * @returns requested score value * @private */ private calculateScoreTypeForExerciseType(exerciseType: ExerciseType, scoreType: ScoreType): number { if (exerciseType != undefined && scoreType != undefined) { const filterFunction = (courseExercise: Exercise) => courseExercise.type === exerciseType; const scores = this.calculateScores(filterFunction); return scores.get(scoreType)!; } else { return NaN; } } /** * Calculates a score type for the whole course * @param scoreType the score type that should be calculated. Element of {Absolute score, Max points,Current relative score,Presentation score,Reachable points,Relative score} * @returns requested score type value * @private */ private calculateTotalScoreForTheCourse(scoreType: ScoreType): number { const scores = this.courseCalculationService.calculateTotalScores(this.courseExercises, this.course!); return scores.get(scoreType)!; } calculateAndFilterNotIncludedInScore() { this.currentlyHidingNotIncludedInScoreExercises = true; this.courseExercisesNotIncludedInScore = this.courseExercises.filter((exercise) => exercise.includedInOverallScore === IncludedInOverallScore.NOT_INCLUDED); this.courseExercises = this.courseExercises.filter((exercise) => !this.courseExercisesNotIncludedInScore.includes(exercise)); this.courseExercisesFilteredByCategories = this.courseExercises; this.filteredExerciseIDs = this.courseExercisesNotIncludedInScore.map((exercise) => exercise.id!); this.determineDisplayableCategories(); } /** * Depending on the type of the exercise, it adds a new object containing * the different scores of the corresponding exercise group of the chart * @param exercise an arbitrary exercise of a course * @param series an array of dedicated objects containing the students' performance in this exercise that is visualized by the chart * @private */ private pushToData(exercise: Exercise, series: any[]): void { switch (exercise.type!) { case ExerciseType.MODELING: this.ngxModelingExercises.push({ name: exercise.title, series, }); this.modelingPresentationScoreEnabled = this.modelingPresentationScoreEnabled || exercise.presentationScoreEnabled!; break; case ExerciseType.PROGRAMMING: series.forEach((part: any) => { part.isProgrammingExercise = true; }); this.ngxProgrammingExercises.push({ name: exercise.title, series, }); this.programmingPresentationScoreEnabled = this.programmingPresentationScoreEnabled || exercise.presentationScoreEnabled!; break; case ExerciseType.QUIZ: this.ngxQuizExercises.push({ name: exercise.title, series, }); this.quizPresentationScoreEnabled = this.quizPresentationScoreEnabled || exercise.presentationScoreEnabled!; break; case ExerciseType.FILE_UPLOAD: this.ngxFileUploadExercises.push({ name: exercise.title, series, }); this.fileUploadPresentationScoreEnabled = this.fileUploadPresentationScoreEnabled || exercise.presentationScoreEnabled!; break; case ExerciseType.TEXT: this.ngxTextExercises.push({ name: exercise.title, series, }); this.textPresentationScoreEnabled = this.textPresentationScoreEnabled || exercise.presentationScoreEnabled!; break; } } /** * Adds some metadata to every non-empty exercise group and pushes it to ngxExerciseGroups * @param exerciseGroups array containing the exercise groups * @param types array containing all possible exercise types (programming, modeling, quiz, text, file upload) * @private */ private pushExerciseGroupsToData(exerciseGroups: any[], types: ExerciseType[]): void { exerciseGroups.forEach((exerciseGroup, index) => { if (exerciseGroup.length > 0) { exerciseGroup[0] = { name: exerciseGroup[0].name, series: exerciseGroup[0].series, type: types[index], absoluteScore: this.overallPointsPerExercise[types[index]], relativeScore: this.relativeScoresPerExercise[types[index]], reachableScore: this.reachablePointsPerExercise[types[index]], currentRelativeScore: this.currentRelativeScoresPerExercise[types[index]], overallMaxPoints: this.overallMaxPointsPerExercise[types[index]], presentationScore: this.presentationScoresPerExercise[types[index]], presentationScoreEnabled: false, xScaleMax: this.setXScaleMax(exerciseGroup), height: this.calculateChartHeight(exerciseGroup.length), }; switch (types[index]) { case ExerciseType.MODELING: exerciseGroup[0].presentationScoreEnabled = this.modelingPresentationScoreEnabled; break; case ExerciseType.PROGRAMMING: exerciseGroup[0].presentationScoreEnabled = this.programmingPresentationScoreEnabled; break; case ExerciseType.QUIZ: exerciseGroup[0].presentationScoreEnabled = this.quizPresentationScoreEnabled; break; case ExerciseType.FILE_UPLOAD: exerciseGroup[0].presentationScoreEnabled = this.fileUploadPresentationScoreEnabled; break; case ExerciseType.TEXT: exerciseGroup[0].presentationScoreEnabled = this.textPresentationScoreEnabled; break; } this.ngxExerciseGroups.push(exerciseGroup); } }); } /** * Depending on if the exercise has a due date and how its score is included, * adds the student score to the corresponding bar. * @param exercise the exercise of interest which has to be displayed by the chart * @param series the series the students score gets pushed to * @param roundedParticipationScore the students relative score * @param split the students absolute score * @private */ private identifyBar(exercise: Exercise, series: any[], roundedParticipationScore: number, split: number): void { // the bar on index 0 is only rendered if the exercise has no due date let index = 0; if (exercise.dueDate) { const scoreTypes = [IncludedInOverallScore.INCLUDED_COMPLETELY, IncludedInOverallScore.NOT_INCLUDED, IncludedInOverallScore.INCLUDED_AS_BONUS]; // we shift the index by 1, because index 0 is accessed if the exercise has no due date and this case is not represented in scoreTypes index = scoreTypes.indexOf(exercise.includedInOverallScore!) + 1; } series[index].value = roundedParticipationScore; series[index].absoluteValue = split; series[index].exerciseId = exercise.id; } /** * Sets the maximum scale on the x-axis if there are exercises with > 100% * @param exerciseGroup the exercise group * @private * @returns maximum value visible on xAxis */ private setXScaleMax(exerciseGroup: any[]): number { let xScaleMax = 100; exerciseGroup.forEach((exercise: any) => { const maxScore = Math.max(exercise.series[0].value, exercise.series[1].value, exercise.series[2].value, exercise.series[3].value); xScaleMax = xScaleMax > maxScore ? xScaleMax : Math.ceil(maxScore); }); return xScaleMax; } /** * Handles the event fired if the user clicks on an arbitrary bar in the vertical bar charts. * Delegates the user to the corresponding exercise detail page in a new tab * @param event the event that is fired by ngx-charts */ onSelect(event: any) { this.navigationUtilService.routeInNewTab(['courses', this.course!.id!, 'exercises', event.exerciseId]); } /** * Handles the selection or deselection of a specific category and configures the filter accordingly * @param category the category that is selected or deselected */ toggleCategory(category: string) { const isIncluded = this.exerciseCategoryFilters.get(category)!; this.exerciseCategoryFilters.set(category, !isIncluded); this.numberOfAppliedFilters += !isIncluded ? 1 : -1; this.applyCategoryFilter(); this.areAllCategoriesSelected(!isIncluded); this.filterExerciseIDsForCategorySelection(!isIncluded!); } /** * Creates an initial filter setting by including all categories * @private */ private setupCategoryFilter(): void { this.exerciseCategories.forEach((category) => this.exerciseCategoryFilters.set(category, true)); this.allCategoriesSelected = true; this.includeExercisesWithNoCategory = true; this.calculateNumberOfAppliedFilters(); } /** * Collects all categories from the currently visible exercises (included or excluded the optional exercises depending on the prior state) * @private */ private determineDisplayableCategories(): void { const exerciseCategories = this.courseExercises .filter((exercise) => exercise.categories) .flatMap((exercise) => exercise.categories!) .map((category) => category.category!); this.exerciseCategories = new Set(exerciseCategories); this.setupCategoryFilter(); } /** * Handles the use case when the user selects or deselects the option "select all categories" */ toggleAllCategories(): void { if (!this.allCategoriesSelected) { this.setupCategoryFilter(); this.includeExercisesWithNoCategory = true; this.calculateNumberOfAppliedFilters(); } else { this.exerciseCategories.forEach((category) => this.exerciseCategoryFilters.set(category, false)); this.numberOfAppliedFilters -= this.exerciseCategories.size + 1; this.allCategoriesSelected = !this.allCategoriesSelected; this.includeExercisesWithNoCategory = false; } this.applyCategoryFilter(); this.filterExerciseIDsForCategorySelection(this.includeExercisesWithNoCategory); } /** * handles the selection and deselection of "exercises with no categories" filter option */ toggleExercisesWithNoCategory(): void { this.numberOfAppliedFilters += this.includeExercisesWithNoCategory ? -1 : 1; this.includeExercisesWithNoCategory = !this.includeExercisesWithNoCategory; this.applyCategoryFilter(); this.areAllCategoriesSelected(this.includeExercisesWithNoCategory); this.filterExerciseIDsForCategorySelection(this.includeExercisesWithNoCategory); } /** * Auxiliary method in order to reduce code duplication * Takes the currently configured exerciseCategoryFilters and applies it to the course exercises * * Important note: As exercises can have no or multiple categories, the filter is designed to be non-exclusive. This means * as long as an exercise has at least one of the selected categories, it is displayed. */ private applyCategoryFilter(): void { this.courseExercisesFilteredByCategories = this.courseExercises.filter((exercise) => { if (!exercise.categories) { return this.includeExercisesWithNoCategory; } return exercise.categories!.flatMap((category) => this.exerciseCategoryFilters.get(category.category!)!).reduce((value1, value2) => value1 || value2); }); this.groupExercisesByType(this.courseExercisesFilteredByCategories); } /** * Auxiliary method that updates the filtered exercise IDs. These are necessary in order to update the performance in exercises chart below * @param included indicates whether the updated filter is now selected or deselected and updates the filtered exercise IDs accordingly * @private */ private filterExerciseIDsForCategorySelection(included: boolean): void { if (!included) { const newlyFilteredIDs = this.courseExercises .filter((exercise) => !this.courseExercisesFilteredByCategories.includes(exercise)) .map((exercise) => exercise.id!) .filter((id) => !this.filteredExerciseIDs.includes(id)); this.filteredExerciseIDs = this.filteredExerciseIDs.concat(newlyFilteredIDs); } else { this.filteredExerciseIDs = this.filteredExerciseIDs.filter((id) => !this.courseExercisesFilteredByCategories.find((exercise) => exercise.id === id)); } } /** * Auxiliary method that checks whether all possible categories are selected and updates the allCategoriesSelected flag accordingly * @param newFilterStatement indicates whether the updated filter option got selected or deselected and updates the flag accordingly * @private */ private areAllCategoriesSelected(newFilterStatement: boolean): void { if (newFilterStatement) { if (!this.includeExercisesWithNoCategory) { this.allCategoriesSelected = false; } else { this.allCategoriesSelected = true; this.exerciseCategoryFilters.forEach((value) => (this.allCategoriesSelected = value && this.allCategoriesSelected)); } } else { this.allCategoriesSelected = false; } } private calculateNumberOfAppliedFilters(): void { this.numberOfAppliedFilters = this.exerciseCategories.size + (this.currentlyHidingNotIncludedInScoreExercises ? 1 : 0) + (this.includeExercisesWithNoCategory ? 1 : 0); } /** * Determines and returns the height of the whole chart depending of the amount of its entries * @param chartEntries the amount of chart entries * @private */ private calculateChartHeight(chartEntries: number): number { /* Each chart bar should have a height of 45px Furthermore we have to take the bar padding between the bars into account Finally, we need to add space for the x-axis and its ticks */ return chartEntries * this.chartHeight + this.barPadding * (chartEntries - 1) + this.defaultSize; } }
the_stack
import { RollupContext } from "./rollupcontext"; import { ConsoleContext, VerbosityLevel } from "./context"; import { LanguageServiceHost } from "./host"; import { TsCache, convertDiagnostic, convertEmitOutput, getAllReferences } from "./tscache"; import { tsModule, setTypescriptModule } from "./tsproxy"; import * as tsTypes from "typescript"; import * as resolve from "resolve"; import * as _ from "lodash"; import { IOptions } from "./ioptions"; import { Partial } from "./partial"; import { parseTsConfig } from "./parse-tsconfig"; import { printDiagnostics } from "./print-diagnostics"; import { TSLIB, TSLIB_VIRTUAL, tslibSource, tslibVersion } from "./tslib"; import { blue, red, yellow, green } from "colors/safe"; import { relative, dirname, normalize as pathNormalize, resolve as pathResolve } from "path"; import { normalize } from "./normalize"; import { satisfies } from "semver"; import findCacheDir from "find-cache-dir"; import { PluginImpl, PluginContext, InputOptions, OutputOptions, TransformResult, SourceMap, Plugin } from "rollup"; import { createFilter } from "./get-options-overrides"; type RPT2Options = Partial<IOptions>; export { RPT2Options } const typescript: PluginImpl<RPT2Options> = (options) => { let watchMode = false; let generateRound = 0; let rollupOptions: InputOptions; let context: ConsoleContext; let filter: any; let parsedConfig: tsTypes.ParsedCommandLine; let tsConfigPath: string | undefined; let servicesHost: LanguageServiceHost; let service: tsTypes.LanguageService; let noErrors = true; const declarations: { [name: string]: { type: tsTypes.OutputFile; map?: tsTypes.OutputFile } } = {}; const allImportedFiles = new Set<string>(); let _cache: TsCache; const cache = (): TsCache => { if (!_cache) _cache = new TsCache(pluginOptions.clean, pluginOptions.objectHashIgnoreUnknownHack, servicesHost, pluginOptions.cacheRoot, parsedConfig.options, rollupOptions, parsedConfig.fileNames, context); return _cache; }; const pluginOptions = { ...options } as IOptions; _.defaults(pluginOptions, { check: true, verbosity: VerbosityLevel.Warning, clean: false, cacheRoot: findCacheDir({ name: "rollup-plugin-typescript2" }), include: ["*.ts+(|x)", "**/*.ts+(|x)"], exclude: ["*.d.ts", "**/*.d.ts"], abortOnError: true, rollupCommonJSResolveHack: false, tsconfig: undefined, useTsconfigDeclarationDir: false, tsconfigOverride: {}, transformers: [], tsconfigDefaults: {}, objectHashIgnoreUnknownHack: false, cwd: process.cwd(), }); if (!pluginOptions.typescript) { pluginOptions.typescript = require("typescript"); } setTypescriptModule(pluginOptions.typescript); const self: Plugin & { _ongenerate: () => void, _onwrite: (this: PluginContext, _output: OutputOptions) => void } = { name: "rpt2", options(config) { rollupOptions = {... config}; context = new ConsoleContext(pluginOptions.verbosity, "rpt2: "); watchMode = process.env.ROLLUP_WATCH === "true"; ({ parsedTsConfig: parsedConfig, fileName: tsConfigPath } = parseTsConfig(context, pluginOptions)); if (generateRound === 0) { parsedConfig.fileNames.forEach((fileName) => { allImportedFiles.add(fileName); }); context.info(`typescript version: ${tsModule.version}`); context.info(`tslib version: ${tslibVersion}`); if (this.meta) context.info(`rollup version: ${this.meta.rollupVersion}`); if (!satisfies(tsModule.version, "$TS_VERSION_RANGE", { includePrerelease : true } as any)) throw new Error(`Installed typescript version '${tsModule.version}' is outside of supported range '$TS_VERSION_RANGE'`); context.info(`rollup-plugin-typescript2 version: $RPT2_VERSION`); context.debug(() => `plugin options:\n${JSON.stringify(pluginOptions, (key, value) => key === "typescript" ? `version ${(value as typeof tsModule).version}` : value, 4)}`); context.debug(() => `rollup config:\n${JSON.stringify(rollupOptions, undefined, 4)}`); context.debug(() => `tsconfig path: ${tsConfigPath}`); if (pluginOptions.objectHashIgnoreUnknownHack) context.warn(() => `${yellow("You are using 'objectHashIgnoreUnknownHack' option")}. If you enabled it because of async functions, try disabling it now.`); if (watchMode) context.info(`running in watch mode`); } filter = createFilter(context, pluginOptions, parsedConfig); servicesHost = new LanguageServiceHost(parsedConfig, pluginOptions.transformers, pluginOptions.cwd); service = tsModule.createLanguageService(servicesHost, tsModule.createDocumentRegistry()); servicesHost.setLanguageService(service); // printing compiler option errors if (pluginOptions.check) printDiagnostics(context, convertDiagnostic("options", service.getCompilerOptionsDiagnostics()), parsedConfig.options.pretty === true); if (pluginOptions.clean) cache().clean(); return config; }, watchChange(id) { const key = normalize(id); delete declarations[key]; }, resolveId(importee, importer) { if (importee === TSLIB) return TSLIB_VIRTUAL; if (!importer) return; importer = normalize(importer); // avoiding trying to resolve ids for things imported from files unrelated to this plugin if (!allImportedFiles.has(importer)) return; // TODO: use module resolution cache const result = tsModule.nodeModuleNameResolver(importee, importer, parsedConfig.options, tsModule.sys); if (result.resolvedModule && result.resolvedModule.resolvedFileName) { if (filter(result.resolvedModule.resolvedFileName)) cache().setDependency(result.resolvedModule.resolvedFileName, importer); if (_.endsWith(result.resolvedModule.resolvedFileName, ".d.ts")) return; const resolved = pluginOptions.rollupCommonJSResolveHack ? resolve.sync(result.resolvedModule.resolvedFileName) : result.resolvedModule.resolvedFileName; context.debug(() => `${blue("resolving")} '${importee}' imported by '${importer}'`); context.debug(() => ` to '${resolved}'`); return pathNormalize(resolved); } return; }, load(id) { if (id === TSLIB_VIRTUAL) return tslibSource; return null; }, transform(code, id) { generateRound = 0; // in watch mode transform call resets generate count (used to avoid printing too many copies of the same error messages) if (!filter(id)) return undefined; allImportedFiles.add(normalize(id)); const contextWrapper = new RollupContext(pluginOptions.verbosity, pluginOptions.abortOnError, this, "rpt2: "); const snapshot = servicesHost.setSnapshot(id, code); // getting compiled file from cache or from ts const result = cache().getCompiled(id, snapshot, () => { const output = service.getEmitOutput(id); if (output.emitSkipped) { noErrors = false; // always checking on fatal errors, even if options.check is set to false const diagnostics = _.concat( cache().getSyntacticDiagnostics(id, snapshot, () => { return service.getSyntacticDiagnostics(id); }), cache().getSemanticDiagnostics(id, snapshot, () => { return service.getSemanticDiagnostics(id); }), ); printDiagnostics(contextWrapper, diagnostics, parsedConfig.options.pretty === true); // since no output was generated, aborting compilation cache().done(); if (_.isFunction(this.error)) this.error(red(`failed to transpile '${id}'`)); } const references = getAllReferences(id, servicesHost.getScriptSnapshot(id), parsedConfig.options); return convertEmitOutput(output, references); }); if (pluginOptions.check) { const diagnostics = _.concat( cache().getSyntacticDiagnostics(id, snapshot, () => { return service.getSyntacticDiagnostics(id); }), cache().getSemanticDiagnostics(id, snapshot, () => { return service.getSemanticDiagnostics(id); }), ); if (diagnostics.length > 0) noErrors = false; printDiagnostics(contextWrapper, diagnostics, parsedConfig.options.pretty === true); } if (result) { if (result.references) result.references.map(normalize).map(allImportedFiles.add, allImportedFiles); if (watchMode && this.addWatchFile && result.references) { if (tsConfigPath) this.addWatchFile(tsConfigPath); result.references.map(this.addWatchFile, this); context.debug(() => `${green(" watching")}: ${result.references!.join("\nrpt2: ")}`); } if (result.dts) { const key = normalize(id); declarations[key] = { type: result.dts, map: result.dtsmap }; context.debug(() => `${blue("generated declarations")} for '${key}'`); } const transformResult: TransformResult = { code: result.code, map: { mappings: "" } }; if (result.map) { if (pluginOptions.sourceMapCallback) pluginOptions.sourceMapCallback(id, result.map); transformResult.map = JSON.parse(result.map); } return transformResult; } return undefined; }, generateBundle(bundleOptions) { self._ongenerate(); self._onwrite.call(this, bundleOptions); }, _ongenerate(): void { context.debug(() => `generating target ${generateRound + 1}`); if (pluginOptions.check && watchMode && generateRound === 0) { cache().walkTree((id) => { if (!filter(id)) return; const snapshot = servicesHost.getScriptSnapshot(id); if (!snapshot) return; const diagnostics = _.concat( cache().getSyntacticDiagnostics(id, snapshot, () => { return service.getSyntacticDiagnostics(id); }), cache().getSemanticDiagnostics(id, snapshot, () => { return service.getSemanticDiagnostics(id); }), ); printDiagnostics(context, diagnostics, parsedConfig.options.pretty === true); }); } if (!watchMode && !noErrors) context.info(yellow("there were errors or warnings.")); cache().done(); generateRound++; }, _onwrite(this: PluginContext, _output: OutputOptions): void { if (!parsedConfig.options.declaration) return; _.each(parsedConfig.fileNames, (name) => { const key = normalize(name); if (_.has(declarations, key)) return; if (!allImportedFiles.has(key)) { context.debug(() => `skipping declarations for unused '${key}'`); return; } context.debug(() => `generating missed declarations for '${key}'`); const output = service.getEmitOutput(key, true); const out = convertEmitOutput(output); if (out.dts) declarations[key] = { type: out.dts, map: out.dtsmap }; }); const emitDeclaration = (key: string, extension: string, entry?: tsTypes.OutputFile) => { if (!entry) return; let fileName = entry.name; if (fileName.includes("?")) // HACK for rollup-plugin-vue, it creates virtual modules in form 'file.vue?rollup-plugin-vue=script.ts' fileName = fileName.split("?", 1) + extension; // If 'useTsconfigDeclarationDir' is given in the // plugin options, directly write to the path provided // by Typescript's LanguageService (which may not be // under Rollup's output directory, and thus can't be // emitted as an asset). if (pluginOptions.useTsconfigDeclarationDir) { context.debug(() => `${blue("emitting declarations")} for '${key}' to '${fileName}'`); tsModule.sys.writeFile(fileName, entry.text, entry.writeByteOrderMark); } else { // don't mutate the entry because generateBundle gets called multiple times let entryText = entry.text const declarationDir = (_output.file ? dirname(_output.file) : _output.dir) as string; const cachePlaceholder = `${pluginOptions.cacheRoot}/placeholder` // modify declaration map sources to correct relative path if (extension === ".d.ts.map") { const parsedText = JSON.parse(entryText) as SourceMap; // invert back to absolute, then make relative to declarationDir parsedText.sources = parsedText.sources.map(source => { const absolutePath = pathResolve(cachePlaceholder, source); return normalize(relative(declarationDir, absolutePath)); }); entryText = JSON.stringify(parsedText); } const relativePath = normalize(relative(cachePlaceholder, fileName)); context.debug(() => `${blue("emitting declarations")} for '${key}' to '${relativePath}'`); this.emitFile({ type: "asset", source: entryText, fileName: relativePath, }); } }; _.each(declarations, ({ type, map }, key) => { emitDeclaration(key, ".d.ts", type); emitDeclaration(key, ".d.ts.map", map); }); }, }; return self; }; export default typescript;
the_stack
const snapshot = require('snap-shot-it') import { SpawnOptions } from 'child_process' import { expect } from './spec_helper' require('mocha-banner').register() const chalk = require('chalk').default const _ = require('lodash') let cp = require('child_process') const path = require('path') const http = require('http') const human = require('human-interval') const morgan = require('morgan') const stream = require('stream') const express = require('express') const Bluebird = require('bluebird') const debug = require('debug')('cypress:system-tests') const httpsProxy = require('@packages/https-proxy') const Fixtures = require('./fixtures') const { allowDestroy } = require(`@packages/server/lib/util/server_destroy`) const cypress = require(`@packages/server/lib/cypress`) const screenshots = require(`@packages/server/lib/screenshots`) const videoCapture = require(`@packages/server/lib/video_capture`) const settings = require(`@packages/server/lib/util/settings`) // mutates mocha test runner - needed for `test.titlePath` // TODO: fix this - this mutates cwd and is strange in general require(`@packages/server/lib/project-base`) type CypressConfig = { [key: string]: any } type BrowserName = 'electron' | 'firefox' | 'chrome' type ExecResult = { code: number stdout: string stderr: string } type ExecFn = (options?: ExecOptions) => Promise<ExecResult> type ItOptions = ExecOptions & { /** * If a function is supplied, it will be executed instead of running the `systemTests.exec` function immediately. */ onRun?: ( execFn: ExecFn ) => Promise<any> | any /** * Same as using `systemTests.it.only`. */ only?: boolean /** * Same as using `systemTests.it.skip`. */ skip?: boolean } type ExecOptions = { /** * Deprecated. Use `--cypress-inspect-brk` from command line instead. * @deprecated */ inspectBrk?: null /** * Deprecated. Use `--no-exit` from command line instead. * @deprecated */ exit?: null /** * Don't exit when tests are finished. You can also pass `--no-exit` via the command line. */ noExit?: boolean /** * The browser to run the system tests on. By default, runs on all. */ browser?: BrowserName | Array<BrowserName> /** * Test timeout in milliseconds. */ timeout?: number /** * The spec argument to pass to Cypress. */ spec?: string /** * The project fixture to scaffold and pass to Cypress. */ project?: string /** * The testing type to use. */ testingType?: 'e2e' | 'component' /** * If set, asserts that Cypress exited with the given exit code. * If all is working as it should, this is the number of failing tests. */ expectedExitCode?: number /** * Force Cypress's server to use the specified port. */ port?: number /** * Set headed mode. By default system tests run headlessly. */ headed?: boolean /** * Set if the run should record. By default system tests do not record. */ record?: boolean /** * Set additional command line args to be passed to the executable. */ args?: string[] /** * If set, automatically snapshot the test's stdout. */ snapshot?: boolean /** * Pass a function to assert on and/or modify the stdout before snapshotting. */ onStdout?: (stdout: string) => string | void /** * User-supplied snapshot title. If unset, one will be autogenerated from the suite name. */ originalTitle?: string /** * If set, screenshot dimensions will be sanitized for snapshotting purposes. * @default false */ sanitizeScreenshotDimensions?: boolean /** * If set, the list of available browsers in stdout will be sanitized for snapshotting purposes. * @default true */ normalizeStdoutAvailableBrowsers?: boolean /** * Runs Cypress in quiet mode. */ quiet?: boolean /** * Run Cypress with parallelization. */ parallel?: boolean /** * Run Cypress with run groups. */ group?: string /** * Run Cypress with a CI build ID. */ ciBuildId?: string /** * Run Cypress with a record key. */ key?: string /** * Run Cypress with a custom Mocha reporter. */ reporter?: string /** * Run Cypress with custom reporter options. */ reporterOptions?: string /** * Run Cypress with CLI config. */ config?: CypressConfig /** * Set Cypress env vars (not OS-level env) */ env?: string /** * Set OS-level env vars. */ processEnv?: { [key: string]: string | number } /** * Set an output path. */ outputPath?: string /** * Set a run tag. */ tag?: string /** * Run Cypress with a custom config filename. */ configFile?: string /** * Set a custom executable to run instead of the default. */ command?: string /** * Additional options to pass to `cp.spawn`. */ spawnOpts?: SpawnOptions /** * Emulate a no-typescript environment. */ noTypeScript?: boolean /** * If set, a dummy `node_modules` project with this name will be set up. */ stubPackage?: string } type Server = { /** * The port to listen on. */ port: number /** * If set, use `@packages/https-proxy`'s CA to set up self-signed HTTPS. */ https?: boolean /** * If set, use `express.static` middleware to serve the e2e project's static assets. */ static?: boolean /** * If set, use the `cors` middleware to provide CORS headers. */ cors?: boolean /** * A function that receives the Express app for setting up routes, etc. */ onServer?: (app: Express.Application) => void } type SetupOptions = { servers?: Server | Array<Server> /** * Set default Cypress config. */ settings?: CypressConfig } const serverPath = path.dirname(require.resolve('@packages/server')) cp = Bluebird.promisifyAll(cp) const env = _.clone(process.env) Bluebird.config({ longStackTraces: true, }) const e2ePath = Fixtures.projectPath('e2e') const pathUpToProjectName = Fixtures.projectPath('') const DEFAULT_BROWSERS = ['electron', 'chrome', 'firefox'] const stackTraceLinesRe = /(\n?[^\S\n\r]*).*?(@|\bat\b).*\.(js|coffee|ts|html|jsx|tsx)(-\d+)?:\d+:\d+[\n\S\s]*?(\n\s*?\n|$)/g const browserNameVersionRe = /(Browser\:\s+)(Custom |)(Electron|Chrome|Canary|Chromium|Firefox)(\s\d+)(\s\(\w+\))?(\s+)/ const availableBrowsersRe = /(Available browsers found on your system are:)([\s\S]+)/g const crossOriginErrorRe = /(Blocked a frame .* from accessing a cross-origin frame.*|Permission denied.*cross-origin object.*)/gm const whiteSpaceBetweenNewlines = /\n\s+\n/ const retryDuration = /Timed out retrying after (\d+)ms/g const escapedRetryDuration = /TORA(\d+)/g export const STDOUT_DURATION_IN_TABLES_RE = /(\s+?)(\d+ms|\d+:\d+:?\d+)/g // extract the 'Difference' section from a snap-shot-it error message const diffRe = /Difference\n-{10}\n([\s\S]*)\n-{19}\nSaved snapshot text/m const expectedAddedVideoSnapshotLines = [ 'Warning: We failed processing this video.', 'This error will not alter the exit code.', '', 'TimeoutError: operation timed out', '[stack trace lines]', '', '', ] const expectedDeletedVideoSnapshotLines = [ '(Video)', '', '- Started processing: Compressing to 32 CRF', ] const sometimesAddedVideoSnapshotLine = '│ Video: false │' const sometimesDeletedVideoSnapshotLine = '│ Video: true │' const isVideoSnapshotError = (err: Error) => { const [added, deleted] = [[], []] const matches = diffRe.exec(err.message) if (!matches || !matches.length) { return false } const lines = matches[1].split('\n') for (const line of lines) { // past this point, the content is variable - mp4 path length if (line.includes('Finished processing:')) break if (line.charAt(0) === '+') added.push(line.slice(1).trim()) if (line.charAt(0) === '-') deleted.push(line.slice(1).trim()) } _.pull(added, sometimesAddedVideoSnapshotLine) _.pull(deleted, sometimesDeletedVideoSnapshotLine) return _.isEqual(added, expectedAddedVideoSnapshotLines) && _.isEqual(deleted, expectedDeletedVideoSnapshotLines) } // this captures an entire stack trace and replaces it with [stack trace lines] // so that the stdout can contain stack traces of different lengths // '@' will be present in firefox stack trace lines // 'at' will be present in chrome stack trace lines const replaceStackTraceLines = (str) => { return str.replace(stackTraceLinesRe, (match, ...parts) => { const isFirefoxStack = parts[1] === '@' let post = parts[4] if (isFirefoxStack) { post = post.replace(whiteSpaceBetweenNewlines, '\n') } return `\n [stack trace lines]${post}` }) } const replaceBrowserName = function (str, key, customBrowserPath, browserName, version, headless, whitespace) { // get the padding for the existing browser string const lengthOfExistingBrowserString = _.sum([browserName.length, version.length, _.get(headless, 'length', 0), whitespace.length]) // this ensures we add whitespace so the border is not shifted return key + customBrowserPath + _.padEnd('FooBrowser 88', lengthOfExistingBrowserString) } const replaceDurationSeconds = function (str, p1, p2, p3, p4) { // get the padding for the existing duration const lengthOfExistingDuration = _.sum([(p2 != null ? p2.length : undefined) || 0, p3.length, p4.length]) return p1 + _.padEnd('X seconds', lengthOfExistingDuration) } // duration='1589' const replaceDurationFromReporter = (str, p1, p2, p3) => { return p1 + _.padEnd('X', p2.length, 'X') + p3 } const replaceNodeVersion = (str, p1, p2, p3) => _.padEnd(`${p1}X (/foo/bar/node)`, (p1.length + p2.length + p3.length)) const replaceCypressVersion = (str, p1, p2) => { // Cypress: 12.10.10 -> Cypress: 1.2.3 (handling padding) return _.padEnd(`${p1}1.2.3`, (p1.length + p2.length)) } // when swapping out the duration, ensure we pad the // full length of the duration so it doesn't shift content const replaceDurationInTables = (str, p1, p2) => { return _.padStart('XX:XX', p1.length + p2.length) } // could be (1 second) or (10 seconds) // need to account for shortest and longest const replaceParenTime = (str, p1) => { return _.padStart('(X second)', p1.length) } const replaceScreenshotDims = (str, p1) => _.padStart('(YxX)', p1.length) const replaceUploadingResults = function (orig, ...rest) { const adjustedLength = Math.max(rest.length, 2) const match = rest.slice(0, adjustedLength - 2) const results = match[1].split('\n').map((res) => res.replace(/\(\d+\/(\d+)\)/g, '(*/$1)')) .sort() .join('\n') const ret = match[0] + results + match[3] return ret } /** * Takes normalized runner STDOUT, finds the "Run Finished" line * and returns everything AFTER that, which usually is just the * test summary table. * @param {string} stdout from the test run, probably normalized */ const leaveRunFinishedTable = (stdout) => { const index = stdout.indexOf(' (Run Finished)') if (index === -1) { throw new Error('Cannot find Run Finished line') } return stdout.slice(index) } const normalizeStdout = function (str, options: any = {}) { const { normalizeStdoutAvailableBrowsers } = options // remove all of the dynamic parts of stdout // to normalize against what we expected str = str // /Users/jane/........../ -> //foo/bar/.projects/ // (Required when paths are printed outside of our own formatting) .split(pathUpToProjectName).join('/foo/bar/.projects') // unless normalization is explicitly turned off then // always normalize the stdout replacing the browser text if (normalizeStdoutAvailableBrowsers !== false) { // usually we are not interested in the browsers detected on this particular system // but some tests might filter / change the list of browsers // in that case the test should pass "normalizeStdoutAvailableBrowsers: false" as options str = str.replace(availableBrowsersRe, '$1\n- browser1\n- browser2\n- browser3') } str = str .replace(browserNameVersionRe, replaceBrowserName) // numbers in parenths .replace(/\s\(\d+([ms]|ms)\)/g, '') // escape "Timed out retrying" messages .replace(retryDuration, 'TORA$1') // 12:35 -> XX:XX .replace(STDOUT_DURATION_IN_TABLES_RE, replaceDurationInTables) // restore "Timed out retrying" messages .replace(escapedRetryDuration, 'Timed out retrying after $1ms') .replace(/(coffee|js)-\d{3}/g, '$1-456') // Cypress: 2.1.0 -> Cypress: 1.2.3 .replace(/(Cypress\:\s+)(\d+\.\d+\.\d+)/g, replaceCypressVersion) // Node Version: 10.2.3 (Users/jane/node) -> Node Version: X (foo/bar/node) .replace(/(Node Version\:\s+v)(\d+\.\d+\.\d+)( \(.*\)\s+)/g, replaceNodeVersion) // 15 seconds -> X second .replace(/(Duration\:\s+)(\d+\sminutes?,\s+)?(\d+\sseconds?)(\s+)/g, replaceDurationSeconds) // duration='1589' -> duration='XXXX' .replace(/(duration\=\')(\d+)(\')/g, replaceDurationFromReporter) // (15 seconds) -> (XX seconds) .replace(/(\((\d+ minutes?,\s+)?\d+ seconds?\))/g, replaceParenTime) .replace(/\r/g, '') // replaces multiple lines of uploading results (since order not guaranteed) .replace(/(Uploading Results.*?\n\n)((.*-.*[\s\S\r]){2,}?)(\n\n)/g, replaceUploadingResults) // fix "Require stacks" for CI .replace(/^(\- )(\/.*\/packages\/server\/)(.*)$/gm, '$1$3') // Different browsers have different cross-origin error messages .replace(crossOriginErrorRe, '[Cross origin error message]') if (options.sanitizeScreenshotDimensions) { // screenshot dimensions str = str.replace(/(\(\d+x\d+\))/g, replaceScreenshotDims) } return replaceStackTraceLines(str) } const ensurePort = function (port) { if (port === 5566) { throw new Error('Specified port cannot be on 5566 because it conflicts with --inspect-brk=5566') } } const startServer = function (obj) { const { onServer, port, https } = obj ensurePort(port) const app = express() const srv = https ? httpsProxy.httpsServer(app) : new http.Server(app) allowDestroy(srv) app.use(morgan('dev')) if (obj.cors) { app.use(require('cors')()) } const s = obj.static if (s) { const opts = _.isObject(s) ? s : {} app.use(express.static(e2ePath, opts)) } return new Bluebird((resolve) => { return srv.listen(port, () => { console.log(`listening on port: ${port}`) if (typeof onServer === 'function') { onServer(app, srv) } return resolve(srv) }) }) } const stopServer = (srv) => srv.destroyAsync() const copy = function () { const ca = process.env.CIRCLE_ARTIFACTS debug('Should copy Circle Artifacts?', Boolean(ca)) if (ca) { const videosFolder = path.join(e2ePath, 'cypress/videos') const screenshotsFolder = path.join(e2ePath, 'cypress/screenshots') debug('Copying Circle Artifacts', ca, videosFolder, screenshotsFolder) // copy each of the screenshots and videos // to artifacts using each basename of the folders return Bluebird.join( screenshots.copy( screenshotsFolder, path.join(ca, path.basename(screenshotsFolder)), ), videoCapture.copy( videosFolder, path.join(ca, path.basename(videosFolder)), ), ) } } const getMochaItFn = function (only, skip, browser, specifiedBrowser) { // if we've been told to skip this test // or if we specified a particular browser and this // doesn't match the one we're currently trying to run... if (skip || (specifiedBrowser && (specifiedBrowser !== browser))) { // then skip this test return it.skip } if (only) { return it.only } return it } function getBrowsers (browserPattern) { if (!browserPattern.length) { return DEFAULT_BROWSERS } let selected = [] const addBrowsers = _.clone(browserPattern) const removeBrowsers = _.remove(addBrowsers, (b) => b.startsWith('!')).map((b) => b.slice(1)) if (removeBrowsers.length) { selected = _.without(DEFAULT_BROWSERS, ...removeBrowsers) } else { selected = _.intersection(DEFAULT_BROWSERS, addBrowsers) } if (!selected.length) { throw new Error(`options.browser: "${browserPattern}" matched no browsers`) } return selected } const normalizeToArray = (value) => { if (value && !_.isArray(value)) { return [value] } return value } const localItFn = function (title: string, opts: ItOptions) { opts.browser = normalizeToArray(opts.browser) const DEFAULT_OPTIONS = { only: false, skip: false, browser: [], snapshot: false, spec: 'no spec name supplied!', onStdout: _.noop, onRun (execFn, browser, ctx) { return execFn() }, } const options = _.defaults({}, opts, DEFAULT_OPTIONS) if (!title) { throw new Error('systemTests.it(...) must be passed a title as the first argument') } // LOGIC FOR AUTOGENERATING DYNAMIC TESTS // - create multiple tests for each default browser // - if browser is specified in options: // ...skip the tests for each default browser if that browser // ...does not match the specified one (used in CI) // run the tests for all the default browsers, or if a browser // has been specified, only run it for that const specifiedBrowser = process.env.BROWSER const browsersToTest = getBrowsers(options.browser) const browserToTest = function (browser) { const mochaItFn = getMochaItFn(options.only, options.skip, browser, specifiedBrowser) const testTitle = `${title} [${browser}]` return mochaItFn(testTitle, function () { if (options.useSeparateBrowserSnapshots) { title = testTitle } const originalTitle = this.test.parent.titlePath().concat(title).join(' / ') const ctx = this const execFn = (overrides = {}) => { return systemTests.exec(ctx, _.extend({ originalTitle }, options, overrides, { browser })) } return options.onRun(execFn, browser, ctx) }) } return _.each(browsersToTest, browserToTest) } localItFn.only = function (title: string, options: ItOptions) { options.only = true return localItFn(title, options) } localItFn.skip = function (title: string, options: ItOptions) { options.skip = true return localItFn(title, options) } const maybeVerifyExitCode = (expectedExitCode, fn) => { // bail if this is explicitly null so // devs can turn off checking the exit code if (expectedExitCode === null) { return } return fn() } const systemTests = { replaceStackTraceLines, normalizeStdout, leaveRunFinishedTable, it: localItFn, snapshot (...args) { args = _.compact(args) // avoid snapshot cwd issue - see /patches/snap-shot* for more information global.CACHED_CWD_FOR_SNAP_SHOT_IT = path.join(__dirname, '..') return snapshot.apply(null, args) }, setup (options: SetupOptions = {}) { beforeEach(async function () { // after installing node modules copying all of the fixtures // can take a long time (5-15 secs) this.timeout(human('2 minutes')) Fixtures.scaffold() if (process.env.NO_EXIT) { Fixtures.scaffoldWatch() } sinon.stub(process, 'exit') if (options.servers) { const optsServers = [].concat(options.servers) const servers = await Bluebird.map(optsServers, startServer) this.servers = servers } else { this.servers = null } const s = options.settings if (s) { await settings.write(e2ePath, s) } }) afterEach(async function () { process.env = _.clone(env) this.timeout(human('2 minutes')) Fixtures.remove() const s = this.servers if (s) { await Bluebird.map(s, stopServer) } }) }, options (ctx, options: ExecOptions) { if (options.inspectBrk != null) { throw new Error(` passing { inspectBrk: true } to system test options is no longer supported Please pass the --cypress-inspect-brk flag to the test command instead e.g. "yarn test async_timeouts_spec.js --cypress-inspect-brk" `) } _.defaults(options, { browser: 'electron', headed: process.env.HEADED || false, project: e2ePath, timeout: 120000, originalTitle: null, expectedExitCode: 0, sanitizeScreenshotDimensions: false, normalizeStdoutAvailableBrowsers: true, noExit: process.env.NO_EXIT, inspectBrk: process.env.CYPRESS_INSPECT_BRK, }) if (options.exit != null) { throw new Error(` passing { exit: false } to system test options is no longer supported Please pass the --no-exit flag to the test command instead e.g. "yarn test async_timeouts_spec.js --no-exit" `) } if (options.noExit && options.timeout < 3000000) { options.timeout = 3000000 } ctx.timeout(options.timeout) const { spec } = options if (spec) { // normalize into array and then prefix const specs = spec.split(',').map((spec) => { if (path.isAbsolute(spec)) { return spec } const specDir = options.testingType === 'component' ? 'component' : 'integration' return path.join(options.project, 'cypress', specDir, spec) }) // normalize the path to the spec options.spec = specs.join(',') } return options }, args (options: ExecOptions) { debug('converting options to args %o', { options }) const args = [ // hides a user warning to go through NPM module `--cwd=${serverPath}`, `--run-project=${options.project}`, `--testingType=${options.testingType || 'e2e'}`, ] if (options.testingType === 'component') { args.push('--component-testing') } if (options.spec) { args.push(`--spec=${options.spec}`) } if (options.port) { ensurePort(options.port) args.push(`--port=${options.port}`) } if (!_.isUndefined(options.headed)) { args.push('--headed', String(options.headed)) } if (options.record) { args.push('--record') } if (options.quiet) { args.push('--quiet') } if (options.parallel) { args.push('--parallel') } if (options.group) { args.push(`--group=${options.group}`) } if (options.ciBuildId) { args.push(`--ci-build-id=${options.ciBuildId}`) } if (options.key) { args.push(`--key=${options.key}`) } if (options.reporter) { args.push(`--reporter=${options.reporter}`) } if (options.reporterOptions) { args.push(`--reporter-options=${options.reporterOptions}`) } if (options.browser) { args.push(`--browser=${options.browser}`) } if (options.config) { args.push('--config', JSON.stringify(options.config)) } if (options.env) { args.push('--env', options.env) } if (options.outputPath) { args.push('--output-path', options.outputPath) } if (options.noExit) { args.push('--no-exit') } if (options.inspectBrk) { args.push('--inspect-brk') } if (options.tag) { args.push(`--tag=${options.tag}`) } if (options.configFile) { args.push(`--config-file=${options.configFile}`) } return args }, start (ctx, options: ExecOptions) { options = this.options(ctx, options) const args = this.args(options) return cypress.start(args) .then(() => { const { expectedExitCode } = options maybeVerifyExitCode(expectedExitCode, () => { expect(process.exit).to.be.calledWith(expectedExitCode) }) }) }, /** * Executes a given project and optionally sanitizes and checks output. * @example ``` systemTests.setup() project = Fixtures.projectPath("component-tests") systemTests.exec(this, { project, config: { video: false } }) .then (result) -> console.log(systemTests.normalizeStdout(result.stdout)) ``` */ exec (ctx, options: ExecOptions) { debug('systemTests.exec options %o', options) options = this.options(ctx, options) debug('processed options %o', options) let args = this.args(options) const specifiedBrowser = process.env.BROWSER if (specifiedBrowser && (![].concat(options.browser).includes(specifiedBrowser))) { ctx.skip() } if (options.stubPackage) { Fixtures.installStubPackage(options.project, options.stubPackage) } args = options.args || ['index.js'].concat(args) let stdout = '' let stderr = '' const exit = function (code) { const { expectedExitCode } = options maybeVerifyExitCode(expectedExitCode, () => { expect(code).to.eq(expectedExitCode, 'expected exit code') }) // snapshot the stdout! if (options.snapshot) { // enable callback to modify stdout const ostd = options.onStdout if (ostd) { const newStdout = ostd(stdout) if (newStdout && _.isString(newStdout)) { stdout = newStdout } } // if we have browser in the stdout make // sure its legit const matches = browserNameVersionRe.exec(stdout) if (matches) { // eslint-disable-next-line no-unused-vars const [, , customBrowserPath, browserName, version, headless] = matches const { browser } = options if (browser && !customBrowserPath) { expect(_.capitalize(browser)).to.eq(browserName) } expect(parseFloat(version)).to.be.a.number // if we are in headed mode or headed is undefined in a browser other // than electron if (options.headed || (_.isUndefined(options.headed) && browser && browser !== 'electron')) { expect(headless).not.to.exist } else { expect(headless).to.include('(headless)') } } const str = normalizeStdout(stdout, options) try { if (options.originalTitle) { systemTests.snapshot(options.originalTitle, str, { allowSharedSnapshot: true }) } else { systemTests.snapshot(str) } } catch (err) { // firefox has issues with recording video. for now, ignore snapshot diffs that only differ in this error. // @see https://github.com/cypress-io/cypress/pull/16731 if (!(options.browser === 'firefox' && isVideoSnapshotError(err))) { throw err } console.log('(system tests warning) Firefox failed to process the video, but this is being ignored due to known issues with video processing in Firefox.') } } return { code, stdout, stderr, } } return new Bluebird((resolve, reject) => { debug('spawning Cypress %o', { args }) const cmd = options.command || 'node' const sp = cp.spawn(cmd, args, { env: _.chain(process.env) .omit('CYPRESS_DEBUG') .extend({ // FYI: color will be disabled // because we are piping the child process COLUMNS: 100, LINES: 24, }) .defaults({ // match CircleCI's filesystem limits, so screenshot names in snapshots match CYPRESS_MAX_SAFE_FILENAME_BYTES: 242, FAKE_CWD_PATH: '/XXX/XXX/XXX', DEBUG_COLORS: '1', // prevent any Compression progress // messages from showing up VIDEO_COMPRESSION_THROTTLE: 120000, // don't fail our own tests running from forked PR's CYPRESS_INTERNAL_SYSTEM_TESTS: '1', // Emulate no typescript environment CYPRESS_INTERNAL_NO_TYPESCRIPT: options.noTypeScript ? '1' : '0', // disable frame skipping to make quick Chromium tests have matching snapshots/working video CYPRESS_EVERY_NTH_FRAME: 1, // force file watching for use with --no-exit ...(options.noExit ? { CYPRESS_INTERNAL_FORCE_FILEWATCH: '1' } : {}), }) .extend(options.processEnv) .value(), ...options.spawnOpts, }) const ColorOutput = function () { const colorOutput = new stream.Transform() colorOutput._transform = (chunk, encoding, cb) => cb(null, chalk.magenta(chunk.toString())) return colorOutput } // pipe these to our current process // so we can see them in the terminal // color it so we can tell which is test output sp.stdout .pipe(ColorOutput()) .pipe(process.stdout) sp.stderr .pipe(ColorOutput()) .pipe(process.stderr) sp.stdout.on('data', (buf) => stdout += buf.toString()) sp.stderr.on('data', (buf) => stderr += buf.toString()) sp.on('error', reject) return sp.on('exit', resolve) }).tap(copy) .then(exit) }, sendHtml (contents) { return function (req, res) { res.set('Content-Type', 'text/html') return res.send(`\ <!DOCTYPE html> <html lang="en"> <body> ${contents} </body> </html>\ `) } }, normalizeWebpackErrors (stdout) { return stdout .replace(/using description file: .* \(relative/g, 'using description file: [..] (relative') .replace(/Module build failed \(from .*\)/g, 'Module build failed (from [..])') }, normalizeRuns (runs) { runs.forEach((run) => { run.tests.forEach((test) => { test.attempts.forEach((attempt) => { const codeFrame = attempt.error && attempt.error.codeFrame if (codeFrame) { codeFrame.absoluteFile = codeFrame.absoluteFile.split(pathUpToProjectName).join('/foo/bar/.projects') } }) }) }) return runs }, } export { systemTests as default, expect, }
the_stack