text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
* @title: Material * @description: * This sample shows how to load materials, how to create them procedurally, and how to apply them to renderables in the scene. * You can select and apply different materials using different rendering effects to the rotation model. */ /*{{ javascript("jslib/aabbtree.js") }}*/ /*{{ javascript("jslib/camera.js") }}*/ /*{{ javascript("jslib/geometry.js") }}*/ /*{{ javascript("jslib/material.js") }}*/ /*{{ javascript("jslib/light.js") }}*/ /*{{ javascript("jslib/scenenode.js") }}*/ /*{{ javascript("jslib/scene.js") }}*/ /*{{ javascript("jslib/vmath.js") }}*/ /*{{ javascript("jslib/effectmanager.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/texturemanager.js") }}*/ /*{{ javascript("jslib/renderingcommon.js") }}*/ /*{{ javascript("jslib/defaultrendering.js") }}*/ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/resourceloader.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/vertexbuffermanager.js") }}*/ /*{{ javascript("jslib/indexbuffermanager.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("scripts/sceneloader.js") }}*/ /*{{ javascript("scripts/motion.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*global TurbulenzEngine: true */ /*global TurbulenzServices: false */ /*global Motion: false */ /*global RequestHandler: false */ /*global TextureManager: false */ /*global ShaderManager: false */ /*global EffectManager: false */ /*global Scene: false */ /*global SceneLoader: false */ /*global Camera: false */ /*global HTMLControls: false */ /*global DefaultRendering: false */ /*global VMath: false */ TurbulenzEngine.onload = function onloadFn() { var errorCallback = function errorCallback(msg) { window.alert(msg); }; var graphicsDeviceParameters = { }; var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters); if (!graphicsDevice.shadingLanguageVersion) { errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date."); graphicsDevice = null; return; } // Clear the background color of the engine window var clearColor = [0.5, 0.5, 0.5, 1.0]; if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor); graphicsDevice.endFrame(); } var mathDeviceParameters = {}; var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters); var requestHandlerParameters = {}; var requestHandler = RequestHandler.create(requestHandlerParameters); var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback); var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback); var effectManager = EffectManager.create(); var scene = Scene.create(mathDevice); var sceneLoader = SceneLoader.create(); var renderer; // Setup world space var worldUp = mathDevice.v3BuildYAxis(); // Setup a camera to view a close-up object var camera = Camera.create(mathDevice); var cameraDistanceFactor = 1.0; camera.nearPlane = 0.05; // Choice of materials to view: // // 'defaultMaterialName' : A material with a texture and technique set on the object by the scene // colouredMaterial : A material with a materialColor and technique that uses material Color to render // newTextureMaterial : A material with a new texture other than the one specified by the scene // The material list var materials = { newTextureMaterial : { effect : "phong", parameters : { diffuse : "textures/brick.png" } }, coloredMaterial : { effect : "constant", meta : { materialcolor : true }, parameters : { materialColor : VMath.v4Build(1.0, 0.1, 0.1, 1.0) } } }; // We will find the default material name after the scene is loaded var defaultMaterialName; // The name of the node we want to rotate to demonstrate the material var nodeName = "LOD3sp"; var objectNode = null; var objectInstance = null; var rotation = Motion.create(mathDevice, "scene"); rotation.setConstantRotation(0.01); // Initialize the previous frame time var previousFrameTime = TurbulenzEngine.time; var renderFrame = function renderFrameFn() { var currentTime = TurbulenzEngine.time; var deltaTime = (currentTime - previousFrameTime); if (deltaTime > 0.1) { deltaTime = 0.1; } var deviceWidth = graphicsDevice.width; var deviceHeight = graphicsDevice.height; var aspectRatio = (deviceWidth / deviceHeight); if (aspectRatio !== camera.aspectRatio) { camera.aspectRatio = aspectRatio; camera.updateProjectionMatrix(); } camera.updateViewProjectionMatrix(); if (objectNode) { // Update the scene with rotation rotation.update(deltaTime); objectNode.setLocalTransform(rotation.matrix); } scene.update(); renderer.update(graphicsDevice, camera, scene, currentTime); if (graphicsDevice.beginFrame()) { if (renderer.updateBuffers(graphicsDevice, deviceWidth, deviceHeight)) { renderer.draw(graphicsDevice, clearColor); } graphicsDevice.endFrame(); } }; // Controls var htmlControls = HTMLControls.create(); htmlControls.addRadioControl({ id : "radio01", groupName : "materialType", radioIndex : 0, value : "default", fn : function () { if (objectInstance) { var materialName = defaultMaterialName; var material = materials[materialName]; if (material && material.loaded) { // Set the material to use on the node objectInstance.setMaterial(scene.getMaterial(materialName)); } } }, isDefault : true }); htmlControls.addRadioControl({ id : "radio02", groupName : "materialType", radioIndex : 1, value : "coloured", fn : function () { if (objectInstance) { var materialName = "coloredMaterial"; var material = materials[materialName]; if (material && material.loaded) { objectInstance.setMaterial(scene.getMaterial(materialName)); } } }, isDefault : false }); htmlControls.addRadioControl({ id : "radio03", groupName : "materialType", radioIndex : 2, value : "newTexture", fn : function () { if (objectInstance) { var materialName = "newTextureMaterial"; var material = materials[materialName]; if (material && material.loaded) { // Set the material to use on the node objectInstance.setMaterial(scene.getMaterial(materialName)); } } }, isDefault : false }); htmlControls.register(); var intervalID; var loadingLoop = function loadingLoopFn() { if (sceneLoader.complete()) { TurbulenzEngine.clearInterval(intervalID); // For the default texture, take the result loaded by the scene objectNode = scene.findNode(nodeName); if (objectNode) { if (objectNode.hasRenderables()) { objectInstance = objectNode.renderables[0]; defaultMaterialName = objectInstance.getMaterial().getName(); if (defaultMaterialName) { // We don't have the material parameters or effect, but we can refer to it by name materials[defaultMaterialName] = {}; materials[defaultMaterialName].loaded = true; scene.getMaterial(defaultMaterialName).reference.add(); } } } var sceneExtents = scene.getExtents(); var sceneMinExtent = mathDevice.v3Build(sceneExtents[0], sceneExtents[1], sceneExtents[2]); var sceneMaxExtent = mathDevice.v3Build(sceneExtents[3], sceneExtents[4], sceneExtents[5]); var center = mathDevice.v3ScalarMul(mathDevice.v3Add(sceneMaxExtent, sceneMinExtent), 0.5); var extent = mathDevice.v3Sub(center, sceneMinExtent); camera.lookAt(center, worldUp, mathDevice.v3Build(center[0] + extent[0] * 2 * cameraDistanceFactor, center[1] + extent[1] * cameraDistanceFactor, center[2] + extent[2] * 2 * cameraDistanceFactor)); camera.updateViewMatrix(); renderer.updateShader(shaderManager); intervalID = TurbulenzEngine.setInterval(renderFrame, 1000 / 60); } }; intervalID = TurbulenzEngine.setInterval(loadingLoop, 1000 / 10); var postLoad = function postLoadFn() { for (var m in materials) { if (materials.hasOwnProperty(m)) { if (scene.loadMaterial(graphicsDevice, textureManager, effectManager, m, materials[m])) { materials[m].loaded = true; scene.getMaterial(m).reference.add(); } else { errorCallback("Failed to load material: " + m); } } } }; var loadAssets = function loadAssetsFn() { // Renderer for the scene (requires shader assets). renderer = DefaultRendering.create(graphicsDevice, mathDevice, shaderManager, effectManager); renderer.setGlobalLightPosition(mathDevice.v3Build(0.5, 100.0, 0.5)); renderer.setAmbientColor(mathDevice.v3Build(0.3, 0.3, 0.4)); // Create object using scene loader sceneLoader.load({ scene : scene, assetPath : "models/duck.dae", graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, effectManager : effectManager, shaderManager : shaderManager, requestHandler: requestHandler, append : false, dynamic : true, postSceneLoadFn : postLoad }); }; var mappingTableReceived = function mappingTableReceivedFn(mappingTable) { textureManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); loadAssets(); }; var gameSessionCreated = function gameSessionCreatedFn(gameSession) { TurbulenzServices.createMappingTable(requestHandler, gameSession, mappingTableReceived); }; var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated); // Create a scene destroy callback to run when the window is closed TurbulenzEngine.onunload = function destroyScene() { TurbulenzEngine.clearInterval(intervalID); if (gameSession) { gameSession.destroy(); gameSession = null; } clearColor = null; rotation = null; if (scene) { scene.destroy(); scene = null; } requestHandler = null; if (renderer) { renderer.destroy(); renderer = null; } materials = null; camera = null; if (textureManager) { textureManager.destroy(); textureManager = null; } if (shaderManager) { shaderManager.destroy(); shaderManager = null; } effectManager = null; TurbulenzEngine.flush(); graphicsDevice = null; mathDevice = null; }; };
the_stack
import { union } from 'lodash'; import { logger, Type } from '../utils'; import { ElementDefinition, ElementDefinitionType, StructureDefinition } from '../fhirtypes'; import { FHIRDefinitions } from '../fhirdefs'; export const IMPLIED_EXTENSION_REGEX = /^http:\/\/hl7\.org\/fhir\/([1345]\.0)\/StructureDefinition\/extension-(([^./]+)\..+)$/; // This map represents the relationship from the version part of the extension URL to the FHIR package const VERSION_TO_PACKAGE_MAP: { [key: string]: string } = { '1.0': 'hl7.fhir.r2.core#1.0.2', '3.0': 'hl7.fhir.r3.core#3.0.2', '4.0': 'hl7.fhir.r4.core#4.0.1', '5.0': 'hl7.fhir.r5.core#current' }; // This map represents how old resource types (R2/R3) map to R4/R5 or how new resource types (R5) map to R4. // This is only used for references, otherwise a complex extension representing the resource should be used // instead. We need this for references because there is no way to point a reference at an extension. // For conversation on this, see: https://chat.fhir.org/#narrow/stream/215610-shorthand/topic/Use.205.2E0.20Extension/near/232846364 // TODO: Redo when implied extension behavior is clarified in R5 and to confirm R5-based mappings are still correct. const RESOURCE_TO_RESOURCE_MAP: { [key: string]: string } = { // Mappings R2 -> R4/R5 BodySite: 'BodyStructure', Conformance: 'CapabilityStatement', DeviceComponent: 'DeviceDefinition', DeviceUseRequest: 'DeviceRequest', DiagnosticOrder: 'ServiceRequest', EligibilityRequest: 'CoverageEligibilityRequest', EligibilityResponse: 'CoverageEligibilityResponse', MedicationOrder: 'MedicationRequest', ProcedureRequest: 'ServiceRequest', ReferralRequest: 'ServiceRequest', // Mappings R3 -> R4/R5 (no new mappings, already covered by R2 -> R4/R5) // Mappings R4 -> R5 DeviceUseStatement: 'DeviceUsage', MedicationStatement: 'MedicationUsage', MedicinalProduct: 'MedicinalProductDefinition', MedicinalProductAuthorization: 'RegulatedAuthorization', MedicinalProductContraindication: 'ClinicalUseIssue', MedicinalProductIndication: 'ClinicalUseIssue', MedicinalProductIngredient: 'Ingredient', MedicinalProductInteraction: 'ClinicalUseIssue', MedicinalProductManufactured: 'ManufacturedItemDefinition', MedicinalProductPackaged: 'PackagedProductDefinition', MedicinalProductPharmaceutical: 'AdministrableProductDefinition', MedicinalProductUndesirableEffect: 'ClinicalUseIssue', SubstanceSpecification: 'SubstanceDefinition', // Mappings R5 -> R4 AdministrableProductDefinition: 'MedicinalProductPharmaceutical', CapabilityStatement2: 'CapabilityStatement', DeviceUsage: 'DeviceUseStatement', Ingredient: 'MedicinalProductIngredient', ManufacturedItemDefinition: 'MedicinalProductManufactured', MedicationUsage: 'MedicationUseStatement', MedicinalProductDefinition: 'MedicinalProduct', PackagedProductDefinition: 'MedicinalProductPackaged', RegulatedAuthorization: 'MedicinalProductAuthorization', SubstanceDefinition: 'SubstanceSpecification' }; // It's sad to ignore any child, but really, we don't care about these particular // children of the original element when building complex extensions. Sorry kids! const IGNORED_CHILDREN = ['id', 'extension', 'modifierExtension']; /** * Determines if the passed in URL is an implied extension URL by checking if it follows the * format: http://hl7.org/fhir/[version]/StructureDefinition/extension-[Path] * @param url {string} - the extension URL to test * @returns {boolean} true if the extension is an implied extension; false otherwise. */ export function isImpliedExtension(url: string): boolean { return IMPLIED_EXTENSION_REGEX.test(url); } /** * Given an extension URL and FHIRDefinitions, materializeImpliedExtension will extract the FHIR * version and element path from the URL and generate a StructureDefinition representing the * requested extension. This is necessary because implied extensions do not exist in physical * packages; they must be "materialized" on-the-fly. For an overview of the general approach, see * the comments at the top of this file. * @param url {string} - the URL of the extension to materialize * @param defs {FHIRDefinitions} - the primary FHIRDefinitons object for the current project * @returns {any} a JSON StructureDefinition representing the implied extension */ export function materializeImpliedExtension(url: string, defs: FHIRDefinitions): any { const match = url.match(IMPLIED_EXTENSION_REGEX); if (match == null) { logger.error( `Unsupported extension URL: ${url}. Extension URLs for converting between versions of ` + 'FHIR must follow the pattern http://hl7.org/fhir/[version]/StructureDefinition/extension-[Path]. ' + 'See: http://hl7.org/fhir/versions.html#extensions.' ); return; } const [, version, id, type] = match; const supplementalPackage = VERSION_TO_PACKAGE_MAP[version]; // guaranteed not to be null thanks to REGEX check above const supplementalDefs = defs.getSupplementalFHIRDefinitions(supplementalPackage); if (supplementalDefs == null) { const extRelease = version === '1.0' ? 'r2' : `r${version[0]}`; const fhirVersion = defs.fishForFHIR('StructureDefinition', Type.Resource)?.fhirVersion; logger.error( `The extension ${url} requires the following dependency to be declared in your sushi-config.yaml ` + `file:\n hl7.fhir.extensions.${extRelease}: ${fhirVersion}` ); return; } const sd = supplementalDefs.fishForFHIR(type, Type.Resource, Type.Type); if (sd == null) { logger.error( `Cannot process extension (${url}) since ${type} is not a valid resource or ` + `data type in ${supplementalPackage}.` ); return; } // NOTE: DSTU2 definitions don't populate element id, so fallback to path in that case const ed = sd.snapshot.element.find((ed: any) => (ed.id ?? ed.path) === id); if (ed == null) { logger.error(`Cannot process extension (${url}) since ${id} is not a valid id in ${type}.`); return; } else if (isUnsupported(ed)) { logger.error( `Cannot process extension (${url}) since its type is Resource. ` + 'See: http://hl7.org/fhir/versions.html#extensions.' ); return; } const ext = StructureDefinition.fromJSON(defs.fishForFHIR('Extension')); applyMetadataToExtension(sd, ed, version, ext); const rootElement = ext.findElement('Extension'); applyMetadataToElement(ed, rootElement); applyContent(sd, ed, version, ext, rootElement, [], defs, supplementalDefs); return ext.toJSON(true); } /** * Determines if the ElementDefinition can be represented using an implied extension. According to * the FHIR documentation, elements with type "Resource" cannot be represented as implied * extensions. * @param fromED {any} - the ElementDefinition JSON to check for unsupported types * @returns {boolean} true if any of the element types are not supported; false otherwise */ function isUnsupported(fromED: any): boolean { return fromED.type?.some((t: any) => t.code === 'Resource'); } /** * Determines if the target element of the implied extension needs to be represented as a complex * extension. There are two basic reasons an element would require a complex extension * representation: (1) if it is a backbone element or element, since their child paths are always * defined inline; (2) if the element's type does not exist in the IG's specified version of FHIR. * Note that if the element is a choice, it must be represented as a simple extension since there * is no way to represent a choice in a complex extension. * @param fromED {any} - the ElementDefinition of the element that the implied extension represents * @param defs {FHIRDefinitions} - the primary FHIRDefinitions object for the current project * @returns {boolean} true if the element should be represented using a complex extension; false * if the element should be represented using a simple extension. */ function isComplex(fromED: any, defs: FHIRDefinitions): boolean { const codes: string[] = union(fromED.type?.map((t: any) => t.code)); if (codes.length !== 1) { // We can't represent a choice as a complex extension return false; } else if (codes[0] === 'BackboneElement' || codes[0] === 'Element') { return true; } // Else if the type does not exist in this version of FHIR, we need to use a complex extension. return defs.fishForFHIR(codes[0], Type.Resource, Type.Type) == null; } /** * Sets the top-level metadata fields on the extension's StructureDefinition, using the relevant * metadata from the source StructureDefinition and ElementDefinition that the extension * represents. * @param fromSD {any} - the JSON StructureDefinition containing the element to represent * @param fromED {any} - the JSON ElementDefinition that defines the element to represent * @param fromVersion {string} - the version portion of the extension URL (e.g., 1.0, 3.0, etc.) * @param toExt {StructurDefinition} - the implied extension's StructureDefinition */ function applyMetadataToExtension( fromSD: any, fromED: any, fromVersion: string, toExt: StructureDefinition ): void { const elementId = fromED.id ?? fromED.path; toExt.id = `extension-${elementId}`; toExt.url = `http://hl7.org/fhir/${fromVersion}/StructureDefinition/${toExt.id}`; toExt.version = fromSD.fhirVersion; toExt.name = `Extension_${elementId.replace(/[^A-Za-z0-9]/g, '_')}`; toExt.title = toExt.description = `Implied extension for ${elementId}`; toExt.date = new Date().toISOString(); toExt.context = [{ expression: 'Element', type: 'element' }]; toExt.baseDefinition = 'http://hl7.org/fhir/StructureDefinition/Extension'; toExt.derivation = 'constraint'; } /** * Sets metadata on an ElementDefinition in the implied extension using relevant metadata from the * source ElementDefinition. * @param fromED {any} - the JSON ElementDefinition to represent * @param toED {ElementDefinition} - an ElementDefinition from the implied extension */ function applyMetadataToElement(fromED: any, toED: ElementDefinition): void { toED.constrainCardinality(fromED.min, fromED.max); if (fromED.short) { toED.short = fromED.short; } if (fromED.definition) { toED.definition = fromED.definition; } if (fromED.comment || fromED.comments) { toED.comment = fromED.comment ?? fromED.comments; } if (fromED.requirements) { toED.requirements = fromED.requirements; } if (fromED.isModifier) { toED.isModifier = fromED.isModifier; } if (fromED.isModifierReason) { toED.isModifierReason = fromED.isModifierReason; } } /** * Given information about a source element to represent, the applyContent function will modify * the passed in element (from the implied extension) so that it can represent the actual content * of the source element (e.g., cardinality, types, bindings). This may result in the * ElementDefinition's value[x] being constrained (for simple extensions) or child elements being * added to represent sub-extensions (for complex extensions). This function can set content * starting at the StructureDefinition's root element or starting at an element representing a * sub-extension in the StructureDefinition. * @param fromSD {any} - the JSON StructureDefinition containing the element to represent * @param fromED {any} - the JSON ElementDefinition that defines the element to represent * @param fromVersion {string} - the version portion of the extension URL (e.g., 1.0, 3.0, etc.) * @param toExt {StructurDefinition} - the implied extension's StructureDefinition * @param toBaseED {ElementDefinition} - the ElementDefinition in the implied extension that should * be modified to represent the content. This could be the root element of the implied extension, * but in cases where a complex extension is needed, it might be the root of a sub-extension. * @param visitedTypes {string[]} - the types that have already been represented in this particular * ElementDefinition's hierarchy. This is needed to avoid infinite recursion since complex * extensions are defined to be fully self-contained (e.g., sub-extensions are defined inline * rather than referenced by their URL). * @param defs {FHIRDefinitions} - the primary FHIRDefinitions object for the current project * @param supplementalDefs {FHIRDefinitions} - the supplemental FHIRDefinitions object for the * version of FHIR corresponding to the source element represented by the implied extension. */ function applyContent( fromSD: any, fromED: any, fromVersion: string, toExt: StructureDefinition, toBaseED: ElementDefinition, visitedTypes: string[], defs: FHIRDefinitions, supplementalDefs: FHIRDefinitions ): void { const url = toBaseED.sliceName ?? toExt.url; toExt.findElement(`${toBaseED.id}.url`).assignValue(url, true); const valueED = toExt.findElement(`${toBaseED.id}.value[x]`); const extensionED = toExt.findElement(`${toBaseED.id}.extension`); if (isComplex(fromED, defs)) { applyToExtensionElement( fromSD, fromED, fromVersion, toExt, extensionED, visitedTypes.slice(0), // pass down a clone so that siblings aren't adding to the same array (we only care recursive descendents) defs, supplementalDefs ); valueED.constrainCardinality(0, '0'); } else { applyToValueXElement(fromED, fromVersion, toExt, valueED, defs); extensionED.constrainCardinality(0, '0'); } } /** * Given information about a source element to represent, the applyToValueXElement function will * modify the passed in value[x] ElementDefinition to represent the applicable content from the * source element (e.g., cardinality, types, bindings). * @param fromED {any} - the JSON ElementDefinition that defines the element to represent * @param fromVersion {string} - the version portion of the extension URL (e.g., 1.0, 3.0, etc.) * @param toExt {StructurDefinition} - the implied extension's StructureDefinition * @param toED {ElementDefinition} - a value[x] ElementDefinition in the implied extension * @param defs {FHIRDefinitions} - the primary FHIRDefinitions object for the current project */ function applyToValueXElement( fromED: any, fromVersion: string, toExt: StructureDefinition, toED: ElementDefinition, defs: FHIRDefinitions ): void { toED.type = getTypes(fromED, fromVersion); if (fromED.binding) { toED.bindToVS( // Handle different representation in DSTU2 and STU3 fromED.binding.valueSet ?? fromED.binding.valueSetUri ?? fromED.binding.valueSetReference.reference, fromED.binding.strength ); if (fromED.binding.description) { toED.binding.description = fromED.binding.description; } // NOTE: Even though there might be extensions on bindings, we are intentionally not carrying // them over because (a) it's not clear that we should, (b) the extension might not exist in // our version of FHIR, (c) the extension might exist but its definition may have changed, and // (d) if we support extensions on binding, shouldn't we support them everywhere? Where do you // draw the line? So... we favor sanity and maintainability over implementing something that // is very likely totally unecessary and inconsequential anyway. } filterAndFixTypes(toExt, toED, defs); } /** * Given information about a source element to represent, the applyToExtensionElement function will * create and modify the relevant sub-extensions on the passed in extension element. * @param fromSD {any} - the JSON StructureDefinition containing the element to represent * @param fromED {any} - the JSON ElementDefinition that defines the element to represent * @param fromVersion {string} - the version portion of the extension URL (e.g., 1.0, 3.0, etc.) * @param toExt {StructurDefinition} - the implied extension's StructureDefinition * @param toED {ElementDefinition} - an extension ElementDefinition in the implied extension * @param visitedTypes {string[]} - the types that have already been represented in this particular * ElementDefinition's hierarchy. This is needed to avoid infinite recursion since complex * extensions are defined to be fully self-contained (e.g., sub-extensions are defined inline * rather than referenced by their URL). * @param defs {FHIRDefinitions} - the primary FHIRDefinitions object for the current project * @param supplementalDefs {FHIRDefinitions} - the supplemental FHIRDefinitions object for the * version of FHIR corresponding to the source element represented by the implied extension. */ function applyToExtensionElement( fromSD: any, fromED: any, fromVersion: string, toExt: StructureDefinition, toED: ElementDefinition, visitedTypes: string[], defs: FHIRDefinitions, supplementalDefs: FHIRDefinitions ): void { let edId: string = fromED.id ?? fromED.path; // First look for children directly in the SD let childElements = fromSD.snapshot.element.filter((e: any) => (e.id ?? e.path).startsWith(`${edId}.`) ); // If no children are found, this may be a type not supported in this version of FHIR, // so use the unknown type's children instead if (childElements.length === 0) { const edTypes = getTypes(fromED, fromVersion); if (edTypes.length === 1) { const typeSD = supplementalDefs.fishForFHIR(edTypes[0].code, Type.Resource, Type.Type); if (typeSD) { if (visitedTypes.indexOf(typeSD.url) !== -1) { // Infinite recursion should be rare, and perhaps never happens under normal circumstances, but it // could happen if an unknown type (which we are handling here) has an element whose type is itself. // In testing, this happened because the test environment did not have all types, and an unknown primitive // type's value element referred back to itself (via the special FHIRPath URL). Anyway, this code // stops those kinds of shenanigans! const parentId = toED.id.replace(/\.extension$/, ''); logger.warn( `Definition of extension (${toExt.url}) is incomplete because ${parentId} causes ` + 'sub-extension recursion.' ); return; } else { visitedTypes.push(typeSD.url); } // Reset edId to the root of the type's SD since all paths will be relative to it edId = typeSD.id ?? typeSD.path; childElements = typeSD.snapshot.element.slice(1); } } } // Now go through the child elements building up the complex extensions structure childElements.forEach((e: any) => { const id: string = e.id ?? e.path; const tail = id.slice(edId.length + 1); if (tail.indexOf('.') === -1 && !IGNORED_CHILDREN.includes(tail)) { const slice = toED.addSlice(tail); applyMetadataToElement(e, slice); slice.type = [new ElementDefinitionType('Extension')]; slice.unfold(defs); applyContent( fromSD, e, fromVersion, toExt, slice, visitedTypes.slice(0), // pass down a clone so that siblings aren't adding to the same array (we only care recursive descendents) defs, supplementalDefs ); } }); // Now apply special logic to handle R5 CodeableReference, which puts bindings and type restrictions // on the CodeableReference instead of underlying concept and reference elemenst if (fromED.type?.[0]?.code === 'CodeableReference') { if (fromED.binding) { const crConcept = toExt.findElement(`${toED.id}:concept.value[x]`); crConcept.bindToVS(fromED.binding.valueSet, fromED.binding.strength); if (fromED.binding.description) { crConcept.binding.description = fromED.binding.description; } } if (fromED.type[0].targetProfile?.length > 0) { const crRef = toExt.findElement(`${toED.id}:reference.value[x]`); crRef.type[0].targetProfile = fromED.type[0].targetProfile.slice(0); filterAndFixTypes(toExt, crRef, defs); } } } /** * Given a JSON ElementDefinition defining the element to represent in an implied extension, the getTypes * function will convert the types from their original format (e.g., DSTU2, STU3) to an R4-compatible set * of types. This is needed because (1) DSTU2 types don't have a 'targetProfile' property, and (2) STU3 * types represent the 'profile' and 'targetProfile' properties as single objects instead of arrays. * @param fromED {any} - the JSON ElementDefinition that defines the element to represent * @param fromVersion {string} - the version portion of the extension URL (e.g., 1.0, 3.0, etc.) * @returns {ElementDefinitionType}[] the R4-compatible set of type objects */ function getTypes(fromED: any, fromVersion: string): ElementDefinitionType[] { if (fromED.type == null || fromED.type.length === 0) { return []; } else if (fromVersion === '4.0' || fromVersion === '5.0') { return fromED.type.map(ElementDefinitionType.fromJSON); } else if (fromVersion === '3.0') { // STU3 only has 0..1 profile and 0..1 targetProfile, so multiple profiles are represented as multiple types w/ duplicated codes. // We need to merge these multiple types w/ the same code into single R4 types where applicable. const r4types: ElementDefinitionType[] = []; for (const r3Type of fromED.type as R3Type[]) { let r4Type = r4types.find(t => t.code === r3Type.code); if (r4Type == null) { r4Type = new ElementDefinitionType(r3Type.code); r4types.push(r4Type); } if (r3Type.profile != null) { r4Type.profile = union(r4Type.profile ?? [], [r3Type.profile]); } if (r3Type.targetProfile != null) { r4Type.targetProfile = union(r4Type.targetProfile ?? [], [r3Type.targetProfile]); } if (r3Type.aggregation != null) { r4Type.aggregation = union(r4Type.aggregation ?? [], r3Type.aggregation); } if (r3Type.versioning != null) { // There's only room for one, so last in wins r4Type.versioning = r3Type.versioning; } } return r4types; } else if (fromVersion === '1.0') { // DSTU2 has 0..* profile but no targetProfile, so if it is a Reference, make it a targetProfile. // It also sometimes represents the same type.code over multiple types, so normalize those. const r4types: ElementDefinitionType[] = []; for (const r2Type of fromED.type as R2Type[]) { let r4Type = r4types.find(t => t.code === r2Type.code); if (r4Type == null) { r4Type = new ElementDefinitionType(r2Type.code); r4types.push(r4Type); } if (r2Type.profile != null) { if (r2Type.code === 'Reference') { r4Type.targetProfile = union(r4Type.targetProfile ?? [], r2Type.profile); } else { r4Type.profile = union(r4Type.profile ?? [], r2Type.profile); } } if (r2Type.aggregation != null) { r4Type.aggregation = union(r4Type.aggregation ?? [], r2Type.aggregation); } } return r4types; } } /** * The filterAndFixTypes function processes the provided ElementDefinition's types, which have * been populated using the source (other version of FHIR) element's types and (1) removes all * types that cannot be represented as an R4/R5 type, and (2) converts renamed types where * possible (e.g., MedicationOrder --> MedicationRequest). * @param toExt {StructurDefinition} - the implied extension's StructureDefinition * @param toED {ElementDefinition} - a value[x] ElementDefinition in the implied extension * @param defs {FHIRDefinitions} - the primary FHIRDefinitions object for the current project */ function filterAndFixTypes( toExt: StructureDefinition, toED: ElementDefinition, defs: FHIRDefinitions ): void { const unsupportedTypes: string[] = []; toED.type = toED.type?.filter(t => { // Maintain types w/ no code; they're valid but there's nothing for us to do. NOTE: these should be rare. if (t.code == null) { return true; } // Unknown codes are handled by a complex extension when there is only one type, but in a choice we // should just filter them out so they're no longer a choice (since they're not valid in this version of FHIR). if (defs.fishForFHIR(t.code, Type.Resource, Type.Type) == null) { unsupportedTypes.push(t.code); return false; } // Remove unknown profile references. // NOTE: Search extension definitions since extensions are { code: 'Extension', profile: '{extensionURL}' }. t.profile = t.profile?.filter(p => { if (defs.fishForFHIR(p, Type.Profile, Type.Extension) == null) { unsupportedTypes.push(p); return false; } return true; }); // If we're left with none (or there were none), it's better to leave the type wide open. if (t.profile?.length === 0) { delete t.profile; } // Replace unknown reference target resources with corresponding known replacement resources // (e.g., MedicationOrder -> MedicationRequest). If no replacement exists, filter it out. t.targetProfile = t.targetProfile ?.map(p => { if (defs.fishForFHIR(p, Type.Resource, Type.Profile)) { return p; } // It wasn't found, so try to find a renamed resource const match = p.match(/^http:\/\/hl7\.org\/fhir\/StructureDefinition\/(.+)$/); if (match) { const renamed = RESOURCE_TO_RESOURCE_MAP[match[1]]; if (renamed) { return `http://hl7.org/fhir/StructureDefinition/${renamed}`; } } unsupportedTypes.push(p); return null; }) .filter(p => p != null); // If we're left with none (or there were none), it's better to leave the reference wide open. if (t.targetProfile?.length === 0) { delete t.targetProfile; } return true; }); if (unsupportedTypes.length > 0) { const typesHave = unsupportedTypes.length === 1 ? 'type has' : 'types have'; logger.warn( `Definition of extension (${toExt.url}) is incomplete since the following ${typesHave} no ` + `equivalent in FHIR ${toExt.fhirVersion}: ${unsupportedTypes.join(', ')}.` ); } } type R3Type = { code: string; profile?: string; targetProfile?: string; aggregation?: string[]; versioning?: string; }; type R2Type = { code: string; profile?: string[]; aggregation?: string[]; };
the_stack
import dbInit from '../helpers/database-init'; import getLogger from '../../fixtures/no-logger'; // eslint-disable-next-line import/no-unresolved import { AccessService, ALL_PROJECTS, } from '../../../lib/services/access-service'; import * as permissions from '../../../lib/types/permissions'; import { RoleName } from '../../../lib/types/model'; let db; let stores; let accessService; let editorUser; let superUser; let editorRole; let adminRole; let readRole; const createUserEditorAccess = async (name, email) => { const { userStore } = stores; const user = await userStore.insert({ name, email }); await accessService.addUserToRole(user.id, editorRole.id); return user; }; const createSuperUser = async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Alice Admin', email: 'admin@getunleash.io', }); await accessService.addUserToRole(user.id, adminRole.id); return user; }; beforeAll(async () => { db = await dbInit('access_service_serial', getLogger); stores = db.stores; // projectStore = stores.projectStore; accessService = new AccessService(stores, { getLogger }); const roles = await accessService.getRootRoles(); editorRole = roles.find((r) => r.name === RoleName.EDITOR); adminRole = roles.find((r) => r.name === RoleName.ADMIN); readRole = roles.find((r) => r.name === RoleName.VIEWER); editorUser = await createUserEditorAccess('Bob Test', 'bob@getunleash.io'); superUser = await createSuperUser(); }); afterAll(async () => { await db.destroy(); }); test('should have access to admin addons', async () => { const { CREATE_ADDON, UPDATE_ADDON, DELETE_ADDON } = permissions; const user = editorUser; expect(await accessService.hasPermission(user, CREATE_ADDON)).toBe(true); expect(await accessService.hasPermission(user, UPDATE_ADDON)).toBe(true); expect(await accessService.hasPermission(user, DELETE_ADDON)).toBe(true); }); test('should have access to admin strategies', async () => { const { CREATE_STRATEGY, UPDATE_STRATEGY, DELETE_STRATEGY } = permissions; const user = editorUser; expect(await accessService.hasPermission(user, CREATE_STRATEGY)).toBe(true); expect(await accessService.hasPermission(user, UPDATE_STRATEGY)).toBe(true); expect(await accessService.hasPermission(user, DELETE_STRATEGY)).toBe(true); }); test('should have access to admin contexts', async () => { const { CREATE_CONTEXT_FIELD, UPDATE_CONTEXT_FIELD, DELETE_CONTEXT_FIELD } = permissions; const user = editorUser; expect(await accessService.hasPermission(user, CREATE_CONTEXT_FIELD)).toBe( true, ); expect(await accessService.hasPermission(user, UPDATE_CONTEXT_FIELD)).toBe( true, ); expect(await accessService.hasPermission(user, DELETE_CONTEXT_FIELD)).toBe( true, ); }); test('should have access to create projects', async () => { const { CREATE_PROJECT } = permissions; const user = editorUser; expect(await accessService.hasPermission(user, CREATE_PROJECT)).toBe(true); }); test('should have access to update applications', async () => { const { UPDATE_APPLICATION } = permissions; const user = editorUser; expect(await accessService.hasPermission(user, UPDATE_APPLICATION)).toBe( true, ); }); test('should not have admin permission', async () => { const { ADMIN } = permissions; const user = editorUser; expect(await accessService.hasPermission(user, ADMIN)).toBe(false); }); test('should have project admin to default project', async () => { const { DELETE_PROJECT, UPDATE_PROJECT, CREATE_FEATURE, UPDATE_FEATURE, DELETE_FEATURE, } = permissions; const user = editorUser; expect( await accessService.hasPermission(user, DELETE_PROJECT, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, UPDATE_PROJECT, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, CREATE_FEATURE, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, UPDATE_FEATURE, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, DELETE_FEATURE, 'default'), ).toBe(true); }); test('should grant member CREATE_FEATURE on all projects', async () => { const { CREATE_FEATURE } = permissions; const user = editorUser; await accessService.addPermissionToRole( editorRole.id, permissions.CREATE_FEATURE, ALL_PROJECTS, ); expect( await accessService.hasPermission(user, CREATE_FEATURE, 'some-project'), ).toBe(true); }); test('cannot add CREATE_FEATURE without defining project', async () => { await expect(async () => { await accessService.addPermissionToRole( editorRole.id, permissions.CREATE_FEATURE, ); }).rejects.toThrow( new Error('ProjectId cannot be empty for permission=CREATE_FEATURE'), ); }); test('cannot remove CREATE_FEATURE without defining project', async () => { await expect(async () => { await accessService.removePermissionFromRole( editorRole.id, permissions.CREATE_FEATURE, ); }).rejects.toThrow( new Error('ProjectId cannot be empty for permission=CREATE_FEATURE'), ); }); test('should remove CREATE_FEATURE on all projects', async () => { const { CREATE_FEATURE } = permissions; const user = editorUser; await accessService.addPermissionToRole( editorRole.id, permissions.CREATE_FEATURE, ALL_PROJECTS, ); await accessService.removePermissionFromRole( editorRole.id, permissions.CREATE_FEATURE, ALL_PROJECTS, ); expect( await accessService.hasPermission(user, CREATE_FEATURE, 'some-project'), ).toBe(false); }); test('admin should be admin', async () => { const { DELETE_PROJECT, UPDATE_PROJECT, CREATE_FEATURE, UPDATE_FEATURE, DELETE_FEATURE, ADMIN, } = permissions; const user = superUser; expect( await accessService.hasPermission(user, DELETE_PROJECT, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, UPDATE_PROJECT, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, CREATE_FEATURE, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, UPDATE_FEATURE, 'default'), ).toBe(true); expect( await accessService.hasPermission(user, DELETE_FEATURE, 'default'), ).toBe(true); expect(await accessService.hasPermission(user, ADMIN)).toBe(true); }); test('should create default roles to project', async () => { const { DELETE_PROJECT, UPDATE_PROJECT, CREATE_FEATURE, UPDATE_FEATURE, DELETE_FEATURE, } = permissions; const project = 'some-project'; const user = editorUser; await accessService.createDefaultProjectRoles(user, project); expect( await accessService.hasPermission(user, UPDATE_PROJECT, project), ).toBe(true); expect( await accessService.hasPermission(user, DELETE_PROJECT, project), ).toBe(true); expect( await accessService.hasPermission(user, CREATE_FEATURE, project), ).toBe(true); expect( await accessService.hasPermission(user, UPDATE_FEATURE, project), ).toBe(true); expect( await accessService.hasPermission(user, DELETE_FEATURE, project), ).toBe(true); }); test('should require name when create default roles to project', async () => { await expect(async () => { await accessService.createDefaultProjectRoles(editorUser); }).rejects.toThrow(new Error('ProjectId cannot be empty')); }); test('should grant user access to project', async () => { const { DELETE_PROJECT, UPDATE_PROJECT, CREATE_FEATURE, UPDATE_FEATURE, DELETE_FEATURE, } = permissions; const project = 'another-project'; const user = editorUser; const sUser = await createUserEditorAccess( 'Some Random', 'random@getunleash.io', ); await accessService.createDefaultProjectRoles(user, project); const roles = await accessService.getRolesForProject(project); const projectRole = roles.find( (r) => r.name === 'Member' && r.project === project, ); await accessService.addUserToRole(sUser.id, projectRole.id); // Should be able to update feature toggles inside the project expect( await accessService.hasPermission(sUser, CREATE_FEATURE, project), ).toBe(true); expect( await accessService.hasPermission(sUser, UPDATE_FEATURE, project), ).toBe(true); expect( await accessService.hasPermission(sUser, DELETE_FEATURE, project), ).toBe(true); // Should not be able to admin the project itself. expect( await accessService.hasPermission(sUser, UPDATE_PROJECT, project), ).toBe(false); expect( await accessService.hasPermission(sUser, DELETE_PROJECT, project), ).toBe(false); }); test('should not get access if not specifying project', async () => { const { CREATE_FEATURE, UPDATE_FEATURE, DELETE_FEATURE } = permissions; const project = 'another-project-2'; const user = editorUser; const sUser = await createUserEditorAccess( 'Some Random', 'random22@getunleash.io', ); await accessService.createDefaultProjectRoles(user, project); const roles = await accessService.getRolesForProject(project); const projectRole = roles.find( (r) => r.name === 'Member' && r.project === project, ); await accessService.addUserToRole(sUser.id, projectRole.id); // Should not be able to update feature toggles outside project expect(await accessService.hasPermission(sUser, CREATE_FEATURE)).toBe( false, ); expect(await accessService.hasPermission(sUser, UPDATE_FEATURE)).toBe( false, ); expect(await accessService.hasPermission(sUser, DELETE_FEATURE)).toBe( false, ); }); test('should remove user from role', async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Some User', email: 'random123@getunleash.io', }); await accessService.addUserToRole(user.id, editorRole.id); // check user has one role const userRoles = await accessService.getRolesForUser(user.id); expect(userRoles.length).toBe(1); expect(userRoles[0].name).toBe(RoleName.EDITOR); await accessService.removeUserFromRole(user.id, editorRole.id); const userRolesAfterRemove = await accessService.getRolesForUser(user.id); expect(userRolesAfterRemove.length).toBe(0); }); test('should return role with users', async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Some User', email: 'random2223@getunleash.io', }); await accessService.addUserToRole(user.id, editorRole.id); const roleWithUsers = await accessService.getRole(editorRole.id); expect(roleWithUsers.role.name).toBe(RoleName.EDITOR); expect(roleWithUsers.users.length > 2).toBe(true); expect(roleWithUsers.users.find((u) => u.id === user.id)).toBeTruthy(); expect( roleWithUsers.users.find((u) => u.email === user.email), ).toBeTruthy(); }); test('should return role with permissions and users', async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Some User', email: 'random2244@getunleash.io', }); await accessService.addUserToRole(user.id, editorRole.id); const roleWithPermission = await accessService.getRole(editorRole.id); expect(roleWithPermission.role.name).toBe(RoleName.EDITOR); expect(roleWithPermission.permissions.length > 2).toBe(true); expect( roleWithPermission.permissions.find( (p) => p.permission === permissions.CREATE_PROJECT, ), ).toBeTruthy(); expect(roleWithPermission.users.length > 2).toBe(true); }); test('should return list of permissions', async () => { const p = await accessService.getPermissions(); const findPerm = (perm) => p.find((_) => _.name === perm); const { DELETE_FEATURE, UPDATE_FEATURE, CREATE_FEATURE, UPDATE_PROJECT, CREATE_PROJECT, } = permissions; expect(p.length > 2).toBe(true); expect(findPerm(CREATE_PROJECT).type).toBe('root'); expect(findPerm(UPDATE_PROJECT).type).toBe('project'); expect(findPerm(CREATE_FEATURE).type).toBe('project'); expect(findPerm(UPDATE_FEATURE).type).toBe('project'); expect(findPerm(DELETE_FEATURE).type).toBe('project'); }); test('should set root role for user', async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Some User', email: 'random2255@getunleash.io', }); await accessService.setUserRootRole(user.id, editorRole.id); const roles = await accessService.getRolesForUser(user.id); expect(roles.length).toBe(1); expect(roles[0].name).toBe(RoleName.EDITOR); }); test('should switch root role for user', async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Some User', email: 'random22Read@getunleash.io', }); await accessService.setUserRootRole(user.id, editorRole.id); await accessService.setUserRootRole(user.id, readRole.id); const roles = await accessService.getRolesForUser(user.id); expect(roles.length).toBe(1); expect(roles[0].name).toBe(RoleName.VIEWER); }); test('should not crash if user does not have permission', async () => { const { userStore } = stores; const user = await userStore.insert({ name: 'Some User', email: 'random55Read@getunleash.io', }); await accessService.setUserRootRole(user.id, readRole.id); const { UPDATE_CONTEXT_FIELD } = permissions; const hasAccess = await accessService.hasPermission( user, UPDATE_CONTEXT_FIELD, ); expect(hasAccess).toBe(false); });
the_stack
import * as React from 'react'; import { IconName, Icon, HotkeysTarget, Hotkeys, Hotkey, IHotkeysProps } from '@blueprintjs/core'; import { Column, Table, AutoSizer, Index, HeaderMouseEventHandlerParams, RowMouseEventHandlerParams, TableHeaderProps, ScrollParams, TableCellProps, } from 'react-virtualized'; import { AppState } from '../state/appState'; import { WithNamespaces, withNamespaces } from 'react-i18next'; import { inject } from 'mobx-react'; import i18next from 'i18next'; import { IReactionDisposer, reaction, toJS, IObservableArray } from 'mobx'; import { File, FileID } from '../services/Fs'; import { formatBytes } from '../utils/formatBytes'; import { shouldCatchEvent, isEditable } from '../utils/dom'; import { AppAlert } from './AppAlert'; import { WithMenuAccelerators, Accelerators, Accelerator } from './WithMenuAccelerators'; import { isMac } from '../utils/platform'; import { ipcRenderer } from 'electron'; import classnames from 'classnames'; import { RowRenderer, RowRendererProps } from './RowRenderer'; import { SettingsState } from '../state/settingsState'; import { ViewState } from '../state/viewState'; import { debounce } from '../utils/debounce'; import { TSORT_METHOD_NAME, TSORT_ORDER, getSortMethod } from '../services/FsSort'; import CONFIG from '../config/appConfig'; import { getSelectionRange } from '../utils/fileUtils'; import { throttle } from '../utils/throttle'; import { FileState } from '../state/fileState'; declare const ENV: { [key: string]: string | boolean | number | Record<string, unknown> }; require('react-virtualized/styles.css'); require('../css/filetable.css'); const CLICK_DELAY = 300; const SCROLL_DEBOUNCE = 50; const ARROW_KEYS_REPEAT_DELAY = 5; const ROW_HEIGHT = 28; const SIZE_COLUMN_WITDH = 70; // this is just some small enough value: column will grow // automatically to make the name visible const NAME_COLUMN_WIDTH = 10; const LABEL_CLASSNAME = 'file-label'; const GRID_CLASSNAME = 'filetable-grid'; const TYPE_ICONS: { [key: string]: IconName } = { img: 'media', any: 'document', snd: 'music', vid: 'mobile-video', exe: 'application', arc: 'compressed', doc: 'align-left', cod: 'code', dir: 'folder-close', }; enum KEYS { Backspace = 8, Enter = 13, Escape = 27, Down = 40, Up = 38, PageDown = 34, PageUp = 33, } interface TableRow { name: string; icon: IconName; size: string; isSelected: boolean; nodeData: File; className: string; title: string; } interface State { nodes: TableRow[]; // number of items selected selected: number; type: string; // position of last selected element position: number; // last path that was used path: string; } interface Props extends WithNamespaces { hide: boolean; } // Here we extend our props in order to keep the injected props private // and still keep strong typing. // // if appState was added to the public props FileListProps, // it would have to be specified when composing FileList, ie: // <FileList ... appState={appState}/> and we don't want that // see: https://github.com/mobxjs/mobx-react/issues/256 interface InjectedProps extends Props { appState: AppState; viewState: ViewState; settingsState: SettingsState; } @inject('appState', 'viewState', 'settingsState') @WithMenuAccelerators @HotkeysTarget export class FileTableClass extends React.Component<Props, State> { private viewState: ViewState; private disposers: Array<IReactionDisposer> = []; private editingElement: HTMLElement = null; private editingFile: File; private clickTimeout: number; gridElement: HTMLElement; tableRef: React.RefObject<Table> = React.createRef(); constructor(props: Props) { super(props); const cache = this.cache; this.state = { nodes: [], // this.buildNodes(this.cache.files, false), selected: 0, type: 'local', position: -1, path: cache.path, }; this.installReactions(); // since the nodes are only generated after the files are updated // we re-render them after language has changed otherwise FileList // gets re-rendered with the wrong language after language has been changed this.bindLanguageChange(); // this.cache.cd(this.cache.path); } get cache(): FileState { const viewState = this.injected.viewState; return viewState.getVisibleCache(); } private bindLanguageChange = (): void => { i18next.on('languageChanged', this.onLanguageChanged); }; private unbindLanguageChange = (): void => { i18next.off('languageChanged', this.onLanguageChanged); }; public onLanguageChanged = (lang: string): void => { this.updateNodes(this.cache.files); }; public componentWillUnmount(): void { for (const disposer of this.disposers) { disposer(); } document.removeEventListener('keydown', this.onDocKeyDown); this.unbindLanguageChange(); } public componentDidMount(): void { document.addEventListener('keydown', this.onDocKeyDown); } public componentDidUpdate(): void { const scrollTop = this.state.position === -1 ? this.cache.scrollTop : null; const viewState = this.injected.viewState; // if (!viewState.viewId) { // console.log('componentDidUpdate', this.state.position, this.cache.scrollTop, scrollTop); // } // edge case: previous saved scrollTop isn't valid anymore // eg. files have been deleted, or selected item has been renamed, // so that using previous scrollTop would hide the selected item // if (/*scrollTop !== null && scrollTop > -1*/1) { this.tableRef.current.scrollToPosition(this.cache.scrollTop); // } } renderMenuAccelerators(): React.ReactElement<Record<string, unknown>> { return ( <Accelerators> <Accelerator combo="CmdOrCtrl+A" onClick={this.onSelectAll}></Accelerator> <Accelerator combo="rename" onClick={this.getElementAndToggleRename}></Accelerator> </Accelerators> ); } renderHotkeys(): React.ReactElement<IHotkeysProps> { const { t } = this.props; return ( <Hotkeys> <Hotkey global={true} combo="mod + o" label={t('SHORTCUT.ACTIVE_VIEW.OPEN_FILE')} onKeyDown={this.onOpenFile} group={t('SHORTCUT.GROUP.ACTIVE_VIEW')} ></Hotkey> <Hotkey global={true} combo="mod + shift + o" label={t('SHORTCUT.ACTIVE_VIEW.OPEN_FILE')} onKeyDown={this.onOpenFile} group={t('SHORTCUT.GROUP.ACTIVE_VIEW')} ></Hotkey> {(!isMac || ENV.CY) && ( <Hotkey global={true} combo="mod + a" label={t('SHORTCUT.ACTIVE_VIEW.SELECT_ALL')} onKeyDown={this.onSelectAll} group={t('SHORTCUT.GROUP.ACTIVE_VIEW')} ></Hotkey> )} <Hotkey global={true} combo="mod + i" label={t('SHORTCUT.ACTIVE_VIEW.SELECT_INVERT')} onKeyDown={this.onInvertSelection} group={t('SHORTCUT.GROUP.ACTIVE_VIEW')} ></Hotkey> </Hotkeys> ) as React.ReactElement<IHotkeysProps>; } private get injected(): InjectedProps { return this.props as InjectedProps; } private installReactions(): void { this.disposers.push( reaction( (): IObservableArray<File> => toJS(this.cache.files), (files: File[]): void => { const cache = this.cache; // when cache is being (re)loaded, cache.files is empty: // we don't want to show "empty folder" placeholder // that case, only when cache is loaded and there are no files if (cache.cmd === 'cwd' || cache.history.length) { this.updateNodes(files); } }, ), reaction( (): boolean => this.cache.error, (): void => this.updateNodes(this.cache.files), ), ); } private getSelectedState(name: string): boolean { const cache = this.cache; return !!cache.selected.find((file) => file.fullname === name); } buildNodeFromFile(file: File, keepSelection: boolean): TableRow { const filetype = file.type; const isSelected = (keepSelection && this.getSelectedState(file.fullname)) || false; const classes = classnames({ isHidden: file.fullname.startsWith('.'), isSymlink: file.isSym, }); // if (file.name.match(/link/)) // debugger; const res: TableRow = { icon: (file.isDir && TYPE_ICONS['dir']) || (filetype && TYPE_ICONS[filetype]) || TYPE_ICONS['any'], name: file.fullname, title: file.isSym ? `${file.fullname} → ${file.target}` : file.fullname, nodeData: file, className: classes, isSelected: isSelected, size: (!file.isDir && formatBytes(file.length)) || '--', }; return res; } private buildNodes = (list: File[], keepSelection = false): TableRow[] => { // console.time('buildingNodes'); const { sortMethod, sortOrder } = this.cache; const SortFn = getSortMethod(sortMethod, sortOrder); const dirs = list.filter((file) => file.isDir); const files = list.filter((file) => !file.isDir); // if we sort by size, we only sort files by size: folders should still be sorted // alphabetically const nodes = dirs .sort(sortMethod !== 'size' ? SortFn : getSortMethod('name', 'asc')) .concat(files.sort(SortFn)) .map((file) => this.buildNodeFromFile(file, keepSelection)); // console.timeEnd('buildingNodes'); return nodes; }; _noRowsRenderer = (): JSX.Element => { const { t } = this.injected; const status = this.cache.status; const error = this.cache.error; // we don't want to show empty + loader at the same time if (status !== 'busy') { const placeholder = (error && t('COMMON.NO_SUCH_FOLDER')) || t('COMMON.EMPTY_FOLDER'); const icon = error ? 'warning-sign' : 'tick-circle'; return ( <div className="empty"> <Icon icon={icon} iconSize={40} /> {placeholder} </div> ); } else { return <div />; } }; private updateNodes(files: File[]): void { // reselect previously selected file in case of reload/change tab const keepSelection = !!this.cache.selected.length; const nodes = this.buildNodes(files, keepSelection); this.updateState(nodes, keepSelection); } private updateState(nodes: TableRow[], keepSelection = false): void { const cache = this.cache; const newPath = (nodes.length && nodes[0].nodeData.dir) || ''; const position = keepSelection && cache.selectedId ? this.getFilePosition(nodes, cache.selectedId) : -1; // cancel inlineedit if there was one this.clearEditElement(); this.setState({ nodes, selected: keepSelection ? this.state.selected : 0, position, path: newPath }, () => { if (keepSelection && cache.editingId && position > -1) { this.getElementAndToggleRename(undefined, false); } else if (this.editingElement) { this.editingElement = null; } }); } getFilePosition(nodes: TableRow[], id: FileID): number { return nodes.findIndex((node) => { const fileId = node.nodeData.id; return fileId && fileId.ino === id.ino && fileId.dev === id.dev; }); } getRow(index: number): TableRow { return this.state.nodes[index]; } nameRenderer = (data: TableCellProps): React.ReactNode => { const { icon, title } = data.rowData; return ( <div className="name"> <Icon icon={icon}></Icon> <span title={title} className="file-label"> {data.cellData} </span> </div> ); }; /* { columnData, dataKey, disableSort, label, sortBy, sortDirection } */ headerRenderer = (data: TableHeaderProps): React.ReactNode => { // TOOD: hardcoded for now, should store the column size/list // and use it here instead const hasResize = data.columnData.index < 1; const { sortMethod, sortOrder } = this.cache; const isSort = data.columnData.sortMethod === sortMethod; const classes = classnames('sort', sortOrder); return ( <React.Fragment key={data.dataKey}> <div className="ReactVirtualized__Table__headerTruncatedText">{data.label}</div> {isSort && <div className={classes}>^</div>} {hasResize && <Icon className="resizeHandle" icon="drag-handle-vertical"></Icon>} </React.Fragment> ); }; rowClassName = (data: Index): string => { const file = this.state.nodes[data.index]; const error = file && file.nodeData.mode === -1; const mainClass = data.index === -1 ? 'headerRow' : 'tableRow'; return classnames(mainClass, file && file.className, { selected: file && file.isSelected, error: error, headerRow: data.index === -1, }); }; clearClickTimeout(): void { if (this.clickTimeout) { clearTimeout(this.clickTimeout); this.clickTimeout = 0; } } setEditElement(element: HTMLElement, file: File): void { const cache = this.cache; this.editingElement = element; this.editingFile = file; cache.setEditingFile(file); } setSort(newMethod: TSORT_METHOD_NAME, newOrder: TSORT_ORDER): void { this.cache.setSort(newMethod, newOrder); } /* { columnData: any, dataKey: string, event: Event } */ onHeaderClick = ({ columnData /*, dataKey */ }: HeaderMouseEventHandlerParams): void => { const { sortMethod, sortOrder } = this.cache; const newMethod = columnData.sortMethod as TSORT_METHOD_NAME; const newOrder = sortMethod !== newMethod ? 'asc' : (((sortOrder === 'asc' && 'desc') || 'asc') as TSORT_ORDER); this.setSort(newMethod, newOrder); this.updateNodes(this.cache.files); }; onRowClick = (data: RowMouseEventHandlerParams): void => { const { rowData, event, index } = data; const { nodes, selected } = this.state; const originallySelected = rowData.isSelected; const file = rowData.nodeData as File; // keep a reference to the target before set setTimeout is called // because React appaers to recycle the event object after event handler // has returned const element = event.target as HTMLElement; // do not select parent dir pseudo file if (this.editingElement === element) { return; } let newSelected = selected; let position = index; if (!event.shiftKey) { newSelected = 0; nodes.forEach((n) => (n.isSelected = false)); rowData.isSelected = true; // online toggle rename when clicking on the label, not the icon if (element.classList.contains(LABEL_CLASSNAME)) { this.clearClickTimeout(); // only toggle inline if last selected element was this one if (index === this.state.position && originallySelected) { this.clickTimeout = window.setTimeout(() => { this.toggleInlineRename(element, originallySelected, file); }, CLICK_DELAY); } } } else { rowData.isSelected = !rowData.isSelected; if (!rowData.isSelected) { // need to update position with last one // will be -1 if no left selected node is position = nodes.findIndex((node) => node.isSelected); } this.setEditElement(null, null); } if (rowData.isSelected) { newSelected++; } else if (originallySelected && newSelected > 0) { newSelected--; } this.setState({ nodes, selected: newSelected, position }, () => { this.updateSelection(); }); }; private onInlineEdit(cancel: boolean): void { const editingElement = this.editingElement; if (cancel) { // restore previous value editingElement.innerText = this.editingFile.fullname; } else { // since the File element is modified by the rename FileState.rename method there is // no need to refresh the file cache: // 1. innerText has been updated and is valid // 2. File.fullname is also updated, so any subsequent render will get the latest version as well this.cache .rename(this.editingFile.dir, this.editingFile, editingElement.innerText) .then(() => { // this will not re-sort the files this.updateSelection(); // we could also reload but not very optimal when working on remote files // const { fileCache } = this.injected; // fileCache.reload(); // Finder automatically repositions the file but won't automatically scroll the list // so the file may be invisible after the reposition: not sure this is perfect either }) .catch((error) => { AppAlert.show(error.message).then(() => { editingElement.innerText = error.oldName; }); }); } this.setEditElement(null, null); editingElement.blur(); editingElement.removeAttribute('contenteditable'); } updateSelection(): void { const { appState } = this.injected; const fileCache = this.cache; const { nodes, position } = this.state; const selection = nodes .filter((node, i) => i !== position && node.isSelected) .map((node) => node.nodeData) as File[]; if (position > -1) { const cursorFile = nodes[position].nodeData as File; selection.push(cursorFile); } appState.updateSelection(fileCache, selection); } selectLeftPart(): void { const filename = this.editingFile.fullname; const selectionRange = getSelectionRange(filename); const selection = window.getSelection(); const range = document.createRange(); const textNode = this.editingElement.childNodes[0]; range.setStart(textNode, selectionRange.start); range.setEnd(textNode, selectionRange.end); selection.empty(); selection.addRange(range); } clearContentEditable(): void { if (this.editingElement) { this.editingElement.blur(); this.editingElement.removeAttribute('contenteditable'); } } toggleInlineRename(element: HTMLElement, originallySelected: boolean, file: File, selectText = true): void { if (!file.readonly) { if (originallySelected) { element.contentEditable = 'true'; element.focus(); this.setEditElement(element, file); selectText && this.selectLeftPart(); element.onblur = (): void => { if (this.editingElement) { this.onInlineEdit(true); } }; } else { // clear rename this.clearContentEditable(); this.setEditElement(null, null); } } } onRowDoubleClick = (data: RowMouseEventHandlerParams): void => { this.clearClickTimeout(); const { rowData, event } = data; const file = rowData.nodeData as File; if ((event.target as HTMLElement) !== this.editingElement) { this.openFileOrDirectory(file, event.shiftKey); } }; async openFileOrDirectory(file: File, useInactiveCache: boolean): Promise<void> { const { appState } = this.injected; try { if (!file.isDir) { await this.cache.openFile(appState, this.cache, file); } else { const cache = useInactiveCache ? appState.getInactiveViewVisibleCache() : this.cache; await cache.openDirectory(file); } } catch (error) { const { t } = this.injected; AppAlert.show(t('ERRORS.GENERIC', { error }), { intent: 'danger', }); } } unSelectAll(): void { const { nodes } = this.state; const selectedNodes = nodes.filter((node) => node.isSelected); if (selectedNodes.length && this.isViewActive()) { selectedNodes.forEach((node) => { node.isSelected = false; }); this.setState({ nodes, selected: 0, position: -1 }, () => { this.updateSelection(); }); } } selectAll(invert = false): void { let { position, selected } = this.state; const { nodes } = this.state; if (nodes.length && this.isViewActive()) { selected = 0; position = -1; let i = 0; for (const node of nodes) { node.isSelected = invert ? !node.isSelected : true; if (node.isSelected) { position = i; selected++; } i++; } this.setState({ nodes, selected, position }, () => { this.updateSelection(); }); } } onOpenFile = (e: KeyboardEvent): void => { const { position, nodes } = this.state; if (this.isViewActive() && position > -1) { const file = nodes[position].nodeData as File; this.openFileOrDirectory(file, e.shiftKey); } }; onSelectAll = (): void => { const isOverlayOpen = document.body.classList.contains('bp3-overlay-open'); if (!isOverlayOpen && !isEditable(document.activeElement)) { this.selectAll(); } else { // need to select all text: send message ipcRenderer.invoke('selectAll'); } }; onInvertSelection = (): void => { this.selectAll(true); }; onInputKeyDown = (e: React.KeyboardEvent<HTMLElement>): void => { if (this.editingElement) { e.nativeEvent.stopImmediatePropagation(); if (e.keyCode === KEYS.Escape || e.keyCode === KEYS.Enter) { if (e.keyCode === KEYS.Enter) { e.preventDefault(); } this.onInlineEdit(e.keyCode === KEYS.Escape); } } }; getNodeContentElement(position: number): HTMLElement { const selector = `[aria-rowindex="${position}"]`; return this.gridElement.querySelector(selector); } clearEditElement(): void { const selector = `[aria-rowindex] [contenteditable]`; const element = this.gridElement.querySelector(selector) as HTMLElement; if (element) { element.onblur = null; element.removeAttribute('contenteditable'); } } isViewActive(): boolean { const { viewState } = this.injected; return viewState.isActive && !this.props.hide; } getElementAndToggleRename = (e?: KeyboardEvent | string, selectText = true): void => { if (this.state.selected > 0) { const { position, nodes } = this.state; const node = nodes[position]; const file = nodes[position].nodeData as File; const element = this.getNodeContentElement(position + 1); const span: HTMLElement = element.querySelector(`.${LABEL_CLASSNAME}`); if (e && typeof e !== 'string') { e.preventDefault(); } this.toggleInlineRename(span, node.isSelected, file, selectText); } }; scrollPage = throttle((up: boolean): void => { const table = this.tableRef.current; const props = this.tableRef.current.props; const headerHeight = props.disableHeader ? 0 : props.headerHeight; const scrollTop = this.cache.scrollTop; // TODO: props.rowHeight may be a function const rowHeight = props.rowHeight as number; const maxHeight = this.state.nodes.length * rowHeight - (props.height - headerHeight); let newScrollTop = 0; if (!up) { newScrollTop = scrollTop + (props.height - headerHeight); if (newScrollTop > maxHeight) { newScrollTop = maxHeight; } } else { newScrollTop = scrollTop - (props.height - headerHeight); if (newScrollTop < 0) { newScrollTop = 0; } } table.scrollToPosition(newScrollTop); }, ARROW_KEYS_REPEAT_DELAY); onDocKeyDown = (e: KeyboardEvent): void => { if (!this.isViewActive() || !shouldCatchEvent(e)) { return; } switch (e.keyCode) { case KEYS.Down: case KEYS.Up: if (!this.editingElement && (e.keyCode === KEYS.Down || e.keyCode === KEYS.Up)) { this.moveSelection(e.keyCode === KEYS.Down ? 1 : -1, e.shiftKey); e.preventDefault(); } break; case KEYS.Enter: this.getElementAndToggleRename(e); break; case KEYS.PageDown: case KEYS.PageUp: this.scrollPage(e.keyCode === KEYS.PageUp); break; case KEYS.Backspace: if (!this.editingElement && !this.cache.isRoot()) { this.cache.openParentDirectory(); } break; } }; moveSelection = throttle((step: number, isShiftDown: boolean) => { let { position, selected } = this.state; const { nodes } = this.state; position += step; if (position > -1 && position <= this.state.nodes.length - 1) { if (isShiftDown) { selected++; } else { // unselect previous one nodes.forEach((n) => (n.isSelected = false)); selected = 1; } nodes[position].isSelected = true; // move in method to reuse this.setState({ nodes, selected, position }, () => { this.updateSelection(); // test this.tableRef.current.scrollToRow(position); }); } }, ARROW_KEYS_REPEAT_DELAY); setGridRef = (element: HTMLElement): void => { this.gridElement = (element && element.querySelector(`.${GRID_CLASSNAME}`)) || null; }; rowRenderer = (props: RowRendererProps): JSX.Element => { const { selected, nodes } = this.state; const { settingsState } = this.injected; const fileCache = this.cache; const node = nodes[props.index]; props.selectedCount = node.isSelected ? selected : 0; props.fileCache = fileCache; props.isDarkModeActive = settingsState.isDarkModeActive; return RowRenderer(props); }; onScroll = debounce(({ scrollTop }: ScrollParams): void => { this.cache.scrollTop = scrollTop; // console.log('onScroll: updating scrollTop', scrollTop, this.cache.path); }, SCROLL_DEBOUNCE); rowGetter = (index: Index): TableRow => this.getRow(index.index); onBlankAreaClick = (e: React.MouseEvent<HTMLElement>): void => { if (e.target === this.gridElement) { this.unSelectAll(); } }; render(): React.ReactElement { const { t } = this.injected; const rowCount = this.state.nodes.length; const GRID_CLASSES = `data-cy-filetable ${GRID_CLASSNAME} ${CONFIG.CUSTOM_SCROLLBAR_CLASSNAME}`; return ( <div ref={this.setGridRef} onClick={this.onBlankAreaClick} onKeyDown={this.onInputKeyDown} className={`fileListSizerWrapper`} > <AutoSizer> {({ width, height }) => ( <Table headerClassName="tableHeader" headerHeight={ROW_HEIGHT} height={height} gridClassName={GRID_CLASSES} onRowClick={this.onRowClick} onRowDoubleClick={this.onRowDoubleClick} onHeaderClick={this.onHeaderClick} noRowsRenderer={this._noRowsRenderer} rowClassName={this.rowClassName} rowHeight={ROW_HEIGHT} rowGetter={this.rowGetter} rowCount={rowCount} // scrollToIndex={position < 0 ? undefined : position} onScroll={this.onScroll} rowRenderer={this.rowRenderer} ref={this.tableRef} width={width} > <Column dataKey="name" label={t('FILETABLE.COL_NAME')} cellRenderer={this.nameRenderer} headerRenderer={this.headerRenderer} width={NAME_COLUMN_WIDTH} flexGrow={1} columnData={{ index: 0, sortMethod: 'name' }} /> <Column className="size bp3-text-small" width={SIZE_COLUMN_WITDH} label={t('FILETABLE.COL_SIZE')} headerRenderer={this.headerRenderer} dataKey="size" flexShrink={1} columnData={{ index: 1, sortMethod: 'size' }} /> </Table> )} </AutoSizer> </div> ); } } const FileTable = withNamespaces()(FileTableClass); export { FileTable };
the_stack
import React from "react"; import ReactDOM from "react-dom"; import { html_beautify } from "vscode-html-languageservice/lib/esm/beautify/beautify-html"; import { mapDataDictionaryToMonacoEditorHTML } from "@microsoft/fast-tooling/dist/esm/data-utilities/monaco"; import { AjvMapper, CustomMessage, DataDictionary, MessageSystem, MessageSystemType, MonacoAdapter, MonacoAdapterAction, MonacoAdapterActionCallbackConfig, } from "@microsoft/fast-tooling"; import { ViewerCustomAction } from "@microsoft/fast-tooling-react"; // This is only used as a typescript reference, the actual monaco import must // be passed from the derived class or it will cause import issues import * as monaco from "monaco-editor/esm/vs/editor/editor.api"; import { StandardLuminance } from "@microsoft/fast-components"; import { classNames, Direction } from "@microsoft/fast-web-utilities"; import FASTMessageSystemWorker from "@microsoft/fast-tooling/dist/message-system.min.js"; import { EditorState } from "./editor.props"; export const previewBackgroundTransparency: string = "PREVIEW::TRANSPARENCY"; export const previewDirection: string = "PREVIEW::DIRECTION"; export const previewTheme: string = "PREVIEW::THEME"; const fastMessageSystemWorker = new FASTMessageSystemWorker(); const fastDesignMessageSystemWorker = new FASTMessageSystemWorker(); abstract class Editor<P, S extends EditorState> extends React.Component<P, S> { public editor: monaco.editor.IStandaloneCodeEditor; public abstract editorContainerRef: React.RefObject<HTMLDivElement>; public abstract viewerContainerRef: React.RefObject<HTMLDivElement>; public viewerContentAreaPadding: number = 20; public maxViewerHeight: number = 0; public maxViewerWidth: number = 0; public fastMessageSystem: MessageSystem; public fastDesignMessageSystem: MessageSystem; // This is the current monaco editor models string value public monacoValue: string[]; public paneStartClassNames: string = "pane pane__start"; public paneEndClassNames: string = "pane pane__end"; public viewerClassNames: string = "preview"; public canvasContentClassNames: string = "canvas-content"; public menuItemRegionClassNames: string = "menu-item-region"; public canvasMenuBarClassNames: string = "canvas-menu-bar"; public mobileMenuBarClassNames: string = "mobile-menu-bar"; public logoClassNames: string = "logo"; public navigationClassNames: string = "navigation"; public canvasClassNames: string = "canvas"; public menuBarClassNames: string = "menu-bar"; private adapter: MonacoAdapter; private monacoEditorModel: monaco.editor.ITextModel; private firstRun: boolean = true; constructor(props: P) { super(props); if ((window as any).Worker) { this.fastMessageSystem = new MessageSystem({ webWorker: fastMessageSystemWorker, }); this.fastDesignMessageSystem = new MessageSystem({ webWorker: fastDesignMessageSystemWorker, }); new AjvMapper({ messageSystem: this.fastDesignMessageSystem, }); new AjvMapper({ messageSystem: this.fastMessageSystem, }); } this.monacoValue = []; this.adapter = new MonacoAdapter({ messageSystem: this.fastMessageSystem, actions: [ new MonacoAdapterAction({ id: "monaco.setValue", action: (config: MonacoAdapterActionCallbackConfig): void => { // trigger an update to the monaco value that // also updates the DataDictionary which fires a // postMessage to the MessageSystem if the update // is coming from Monaco and not a data dictionary update config.updateMonacoModelValue( this.monacoValue, this.state.lastMappedDataDictionaryToMonacoEditorHTMLValue === this.monacoValue[0] ); }, }), ], }); } public setupMonacoEditor = (monacoRef: any): void => { monacoRef.editor.onDidCreateModel((listener: monaco.editor.ITextModel) => { this.monacoEditorModel = monacoRef.editor.getModel( listener.uri ) as monaco.editor.ITextModel; this.monacoEditorModel.onDidChangeContent( (e: monaco.editor.IModelContentChangedEvent) => { /** * Sets the value to be used by monaco */ if (this.state.previewReady) { const modelValue = this.monacoEditorModel.getValue(); this.monacoValue = Array.isArray(modelValue) ? modelValue : [modelValue]; if (!this.firstRun) { this.adapter.action("monaco.setValue").run(); } this.firstRun = false; } } ); }); }; public createMonacoEditor = ( monacoRef: any, alternateContainerRef?: HTMLElement, editorOptions?: any ): void => { if ((alternateContainerRef || this.editorContainerRef.current) && !this.editor) { this.editor = monacoRef.editor.create( alternateContainerRef ? alternateContainerRef : this.editorContainerRef.current, { value: "", language: "html", formatOnPaste: true, lineNumbers: "off", theme: "vs-dark", wordWrap: "on", wordWrapColumn: 80, wordWrapMinified: true, wrappingIndent: "same", minimap: { showSlider: "mouseover", }, ...editorOptions, } ); this.updateEditorContent(this.state.dataDictionary); } }; public updateEditorContent(dataDictionary: DataDictionary<unknown>): void { if (this.editor) { const lastMappedDataDictionaryToMonacoEditorHTMLValue = html_beautify( mapDataDictionaryToMonacoEditorHTML( dataDictionary, this.state.schemaDictionary ) ); this.setState( { lastMappedDataDictionaryToMonacoEditorHTMLValue, }, () => { this.editor.setValue(lastMappedDataDictionaryToMonacoEditorHTMLValue); } ); } } public setViewerToFullSize(alternateContainerRef?: HTMLElement): void { const viewerContainer: HTMLElement | null = alternateContainerRef ? alternateContainerRef : this.viewerContainerRef.current; if (viewerContainer) { /* eslint-disable-next-line react/no-find-dom-node */ const viewerNode: Element | Text | null = ReactDOM.findDOMNode( viewerContainer ); if (viewerNode instanceof Element) { // 24 is height of view label this.maxViewerHeight = viewerNode.clientHeight - this.viewerContentAreaPadding * 2 - 24; this.maxViewerWidth = viewerNode.clientWidth - this.viewerContentAreaPadding * 2; this.setState({ viewerWidth: this.maxViewerWidth, viewerHeight: this.maxViewerHeight, }); } } } public getContainerClassNames(): string { return classNames( "container", ["container__form-visible", this.state.mobileFormVisible], ["container__navigation-visible", this.state.mobileNavigationVisible] ); } public getCanvasOverlayClassNames(): string { return classNames("canvas-overlay", [ "canvas-overlay__active", this.state.mobileFormVisible || this.state.mobileNavigationVisible, ]); } public handleCanvasOverlayTrigger = (): void => { this.setState({ mobileFormVisible: false, mobileNavigationVisible: false, }); }; public handleMobileNavigationTrigger = (): void => { this.setState({ mobileNavigationVisible: true, }); }; public handleMobileFormTrigger = (): void => { this.setState({ mobileFormVisible: true, }); }; public handleUpdateTheme = (): void => { const updatedTheme: StandardLuminance = this.state.theme === StandardLuminance.DarkMode ? StandardLuminance.LightMode : StandardLuminance.DarkMode; this.setState({ theme: updatedTheme, }); this.fastMessageSystem.postMessage({ type: MessageSystemType.custom, action: ViewerCustomAction.response, id: previewTheme, value: updatedTheme, } as CustomMessage<{}, {}>); }; public handleUpdateDirection = (): void => { const updatedDirection: Direction = this.state.direction === Direction.ltr ? Direction.rtl : Direction.ltr; this.setState({ direction: updatedDirection, }); this.fastMessageSystem.postMessage({ type: MessageSystemType.custom, action: ViewerCustomAction.response, id: previewDirection, value: updatedDirection, } as CustomMessage<{}, {}>); }; public handleUpdateTransparency = (): void => { this.setState({ transparentBackground: !this.state.transparentBackground, }); this.fastMessageSystem.postMessage({ type: MessageSystemType.custom, action: ViewerCustomAction.response, id: previewBackgroundTransparency, value: !this.state.transparentBackground, } as CustomMessage<{}, {}>); }; public handleUpdateHeight = (updatedHeight: number): void => { this.setState({ viewerHeight: updatedHeight > this.maxViewerHeight ? this.maxViewerHeight : updatedHeight, }); }; public handleUpdateWidth = (updatedWidth: number): void => { this.setState({ viewerWidth: updatedWidth > this.maxViewerWidth ? this.maxViewerWidth : updatedWidth, }); }; public renderCanvasOverlay(): React.ReactNode { return ( <div className={this.getCanvasOverlayClassNames()} onClick={this.handleCanvasOverlayTrigger} ></div> ); } public renderMobileNavigationTrigger(): React.ReactNode { return ( <button className={"mobile-pane-trigger"} onClick={this.handleMobileNavigationTrigger} > <svg width="16" height="15" viewBox="0 0 16 15" fill="none" xmlns="http://www.w3.org/2000/svg" > <rect width="16" height="1" rx="0.5" fill="white" /> <rect y="7" width="16" height="1" rx="0.5" fill="white" /> <rect y="14" width="16" height="1" rx="0.5" fill="white" /> </svg> </button> ); } public renderMobileFormTrigger(): React.ReactNode { return ( <button className={"mobile-pane-trigger"} onClick={this.handleMobileFormTrigger} > <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M16.5253 1.47498C17.6898 2.63953 17.6898 4.52764 16.5253 5.69219L6.55167 15.6658C6.32095 15.8965 6.034 16.0631 5.71919 16.1489L1.45612 17.3116C0.989558 17.4388 0.56145 17.0107 0.688694 16.5441L1.85135 12.2811C1.93721 11.9663 2.10373 11.6793 2.33446 11.4486L12.3081 1.47498C13.4726 0.310424 15.3607 0.310424 16.5253 1.47498ZM11.5001 4.05073L3.21834 12.3325C3.14143 12.4094 3.08592 12.505 3.05731 12.61L2.18243 15.8178L5.3903 14.943C5.49523 14.9143 5.59088 14.8588 5.66779 14.7819L13.9493 6.4999L11.5001 4.05073ZM13.1919 2.35886L12.3835 3.16656L14.8326 5.61656L15.6414 4.80831C16.3178 4.13191 16.3178 3.03526 15.6414 2.35886C14.965 1.68246 13.8683 1.68246 13.1919 2.35886Z" fill="white" /> </svg> </button> ); } } export { Editor, EditorState };
the_stack
import {AC} from './AC'; import {NotEnoughDataError} from '../error'; describe('AC', () => { describe('getResult', () => { it('works with a signal line of SMA(5)', () => { const ac = new AC(5, 34, 5); // Test data taken from: // https://github.com/jesse-ai/jesse/blob/8e502d070c24bed29db80e1d0938781d8cdb1046/tests/data/test_candles_indicators.py#L4351 const candles = [ [1563408000000, 210.8, 225.73, 229.65, 205.71, 609081.49094], [1563494400000, 225.75, 220.73, 226.23, 212.52, 371622.21865], [1563580800000, 220.84, 228.2, 235.09, 219.78, 325393.97225], [1563667200000, 228.25, 225.38, 229.66, 216.99, 270046.1519], [1563753600000, 225.49, 217.51, 228.34, 212.25, 271310.40446], [1563840000000, 217.59, 212.48, 219.55, 208.36, 317876.48242], [1563926400000, 212.55, 216.31, 218.28, 202.0, 331162.6484], [1564012800000, 216.31, 219.14, 225.12, 215.23, 280370.29627], [1564099200000, 219.14, 218.81, 220.0, 212.71, 197781.98653], [1564185600000, 218.81, 207.3, 223.3, 203.0, 301209.41113], [1564272000000, 207.3, 211.62, 213.52, 198.24, 218801.16693], [1564358400000, 211.58, 210.89, 215.83, 206.59, 226941.28], [1564444800000, 210.84, 209.58, 214.36, 204.4, 222683.79393], [1564531200000, 209.57, 218.42, 218.79, 209.2, 207213.55658], [1564617600000, 218.42, 216.84, 219.39, 210.54, 186806.18844], [1564704000000, 216.8, 217.61, 222.18, 214.31, 206867.03039], [1564790400000, 217.69, 222.14, 224.51, 216.62, 181591.95296], [1564876800000, 222.14, 221.79, 223.34, 216.9, 135622.0258], [1564963200000, 221.79, 233.54, 236.25, 221.79, 307956.27211], [1565049600000, 233.53, 226.28, 239.15, 223.03, 341279.08159], [1565136000000, 226.31, 226.1, 231.25, 220.95, 279104.7037], [1565222400000, 226.11, 221.39, 228.5, 215.51, 236886.35423], [1565308800000, 221.38, 210.53, 221.79, 207.3, 232062.12757], [1565395200000, 210.52, 206.48, 215.0, 202.6, 252614.02389], [1565481600000, 206.48, 216.42, 216.94, 206.14, 188474.09048], [1565568000000, 216.41, 211.41, 216.81, 209.75, 122760.94619], [1565654400000, 211.58, 209.3, 214.3, 204.0, 166922.48201], [1565740800000, 209.31, 187.1, 209.9, 183.49, 325228.98931], [1565827200000, 187.08, 188.03, 189.95, 181.23, 237953.09426], [1565913600000, 187.98, 184.88, 188.39, 178.04, 282177.01584], [1566000000000, 184.83, 185.59, 187.0, 181.83, 138799.61508], [1566086400000, 185.67, 194.33, 197.91, 183.35, 175363.5062], [1566172800000, 194.32, 202.28, 203.59, 192.7, 239541.5978], [1566259200000, 202.24, 196.6, 202.75, 194.45, 189297.75494], [1566345600000, 196.55, 187.45, 197.2, 179.53, 284973.64194], [1566432000000, 187.45, 190.35, 195.14, 182.8, 245575.98772], [1566518400000, 190.36, 194.02, 196.19, 188.16, 192548.51552], [1566604800000, 194.02, 190.6, 194.09, 185.63, 167806.34294], [1566691200000, 190.6, 186.54, 192.4, 182.8, 169862.91522], [1566777600000, 186.54, 188.67, 193.7, 186.0, 254397.79472], [1566864000000, 188.61, 187.24, 189.49, 184.75, 157898.563], [1566950400000, 187.3, 173.03, 188.25, 166.48, 334480.61761], [1567036800000, 173.03, 169.01, 173.5, 163.61, 295241.216], [1567123200000, 169.03, 168.5, 170.77, 165.55, 238616.68868], [1567209600000, 168.48, 171.57, 174.98, 165.63, 194999.19583], [1567296000000, 171.52, 170.74, 173.42, 167.61, 191140.52368], [1567382400000, 170.73, 178.05, 181.0, 170.02, 294627.31247], [1567468800000, 178.0, 178.75, 183.0, 174.09, 327857.85447], [1567555200000, 178.79, 174.72, 180.14, 173.0, 286226.25171], [1567641600000, 174.7, 173.75, 176.19, 168.1, 232753.83596], [1567728000000, 173.74, 169.08, 177.87, 165.0, 315822.37984], [1567814400000, 169.11, 177.62, 180.8, 168.3, 253831.23169], [1567900800000, 177.58, 181.19, 184.18, 176.13, 290083.47501], [1567987200000, 181.18, 180.54, 185.38, 176.01, 273729.94868], [1568073600000, 180.52, 179.81, 184.36, 177.0, 238387.50999], [1568160000000, 179.87, 178.28, 182.8, 173.0, 278555.46708], [1568246400000, 178.3, 180.72, 182.38, 176.62, 203543.13663], [1568332800000, 180.71, 180.95, 181.38, 177.54, 264422.54059], [1568419200000, 180.96, 188.13, 188.79, 179.75, 279371.83423], [1568505600000, 188.14, 189.03, 190.45, 185.76, 288928.60827], [1568592000000, 189.05, 197.22, 199.44, 188.3, 551006.81686], [1568678400000, 197.23, 207.84, 215.13, 195.74, 715863.2262], [1568764800000, 207.85, 210.21, 217.27, 207.66, 539028.51013], [1568851200000, 210.27, 220.24, 223.94, 202.3, 844358.82155], [1568937600000, 220.26, 218.03, 221.54, 212.05, 437804.12669], [1569024000000, 218.01, 215.05, 221.5, 213.2, 417891.5242], [1569110400000, 215.04, 211.2, 215.61, 206.1, 445388.94787], [1569196800000, 211.2, 201.29, 211.68, 198.65, 392437.07084], [1569283200000, 201.25, 165.81, 202.98, 150.03, 1478218.82714], [1569369600000, 165.72, 169.96, 174.85, 161.88, 879001.46213], [1569456000000, 169.96, 165.92, 171.01, 152.11, 779942.17148], [1569542400000, 165.92, 173.79, 176.72, 161.03, 634932.96707], [1569628800000, 173.83, 173.49, 175.49, 168.0, 521775.46593], [1569715200000, 173.5, 169.24, 174.5, 164.12, 410855.12176], [1569801600000, 169.26, 180.85, 181.24, 165.01, 580295.3997], [1569888000000, 180.89, 175.66, 185.53, 173.19, 609819.60828], [1569974400000, 175.65, 180.24, 181.29, 173.65, 348268.1162], [1570060800000, 180.24, 174.69, 180.72, 169.55, 354756.78478], [1570147200000, 174.71, 175.55, 178.98, 170.74, 333897.63876], [1570233600000, 175.55, 176.25, 176.71, 172.02, 278488.61771], [1570320000000, 176.23, 170.1, 177.04, 167.68, 314932.39629], [1570406400000, 170.08, 179.85, 182.32, 168.68, 496523.48038], [1570492800000, 179.88, 180.6, 184.87, 177.0, 400832.37828], [1570579200000, 180.61, 192.62, 195.53, 178.96, 562506.82189], [1570665600000, 192.61, 191.14, 194.2, 186.88, 436588.58452], [1570752000000, 191.18, 180.72, 196.65, 179.41, 621693.63125], [1570838400000, 180.65, 179.68, 184.64, 177.59, 290415.22038], [1570924800000, 179.65, 180.99, 184.95, 178.52, 247589.23231], [1571011200000, 180.98, 186.72, 187.54, 180.43, 279732.84612], [1571097600000, 186.7, 180.49, 188.37, 175.96, 405466.38109], [1571184000000, 180.52, 174.47, 181.44, 171.81, 347764.93459], [1571270400000, 174.52, 177.16, 178.96, 172.61, 298795.8198], [1571356800000, 177.17, 172.74, 177.44, 168.66, 319602.48508], [1571443200000, 172.78, 171.79, 174.98, 169.44, 296918.73026], [1571529600000, 171.84, 175.22, 176.88, 169.21, 299141.07152], [1571616000000, 175.18, 173.98, 177.9, 171.59, 270608.51385], [1571702400000, 174.0, 171.2, 175.04, 170.3, 255429.41624], [1571788800000, 171.19, 162.35, 171.49, 153.45, 746955.09806], [1571875200000, 162.35, 160.38, 163.72, 158.72, 387310.83766], [1571961600000, 160.39, 181.5, 187.78, 160.25, 904832.86059], [1572048000000, 181.53, 179.49, 197.74, 173.8, 1211737.43684], [1572134400000, 179.42, 183.75, 188.7, 176.22, 724423.40525], [1572220800000, 183.84, 181.72, 189.48, 180.35, 582179.44545], [1572307200000, 181.67, 190.46, 192.74, 181.26, 529964.5054], [1572393600000, 190.45, 183.13, 191.71, 179.28, 537770.43056], [1572480000000, 183.14, 182.18, 185.27, 177.66, 410969.86104], [1572566400000, 182.19, 182.85, 184.5, 177.02, 331519.76963], [1572652800000, 182.86, 182.91, 186.0, 181.53, 179864.39739], [1572739200000, 182.9, 181.54, 184.7, 178.95, 232621.52147], [1572825600000, 181.53, 185.71, 188.64, 180.36, 321175.29134], [1572912000000, 185.71, 188.68, 192.51, 182.22, 389668.6472], [1572998400000, 188.65, 191.16, 195.09, 187.72, 343219.9224], [1573084800000, 191.16, 186.68, 192.27, 184.59, 309882.08206], [1573171200000, 186.67, 183.74, 188.26, 181.41, 365029.75027], [1573257600000, 183.71, 184.89, 185.79, 182.63, 192073.38044], [1573344000000, 184.86, 188.96, 191.58, 183.3, 274940.53448], [1573430400000, 188.96, 184.98, 190.19, 184.06, 255579.93429], [1573516800000, 184.98, 187.09, 187.65, 182.41, 256782.63119], [1573603200000, 187.09, 188.11, 189.66, 185.3, 197273.84001], [1573689600000, 188.07, 184.92, 188.72, 183.34, 245505.29971], [1573776000000, 184.93, 180.0, 186.7, 177.67, 407466.78964], [1573862400000, 179.99, 182.37, 183.46, 179.3, 172801.52576], [1573948800000, 182.37, 183.82, 186.09, 180.0, 198892.4372], [1574035200000, 183.82, 178.2, 184.06, 175.01, 293551.23632], [1574121600000, 178.2, 175.94, 178.52, 172.65, 275886.6411], [1574208000000, 175.93, 174.72, 177.41, 173.5, 216315.93309], [1574294400000, 174.75, 161.01, 175.85, 157.26, 473895.92992], [1574380800000, 161.02, 149.56, 162.79, 138.0, 977977.23794], [1574467200000, 149.55, 151.84, 154.33, 146.11, 369721.0996], [1574553600000, 151.84, 139.96, 152.86, 138.62, 352319.21558], [1574640000000, 139.99, 145.69, 151.5, 131.45, 749675.41303], [1574726400000, 145.81, 147.47, 149.97, 143.37, 354023.04298], [1574812800000, 147.47, 152.62, 155.54, 140.84, 564796.4284], [1574899200000, 152.61, 150.72, 154.63, 149.09, 317714.56326], [1574985600000, 150.69, 154.57, 157.6, 150.23, 328712.25558], [1575072000000, 154.54, 151.37, 155.25, 149.7, 226863.41299], [1575158400000, 151.43, 150.73, 152.49, 145.79, 344178.14088], [1575244800000, 150.72, 148.65, 151.42, 146.71, 233839.0973], [1575331200000, 148.66, 147.17, 149.93, 145.77, 196329.22503], [1575417600000, 147.19, 145.38, 151.98, 143.15, 434430.62379], [1575504000000, 145.45, 148.1, 149.02, 143.64, 299073.53972], [1575590400000, 148.11, 148.45, 149.77, 145.74, 220674.68581], [1575676800000, 148.46, 147.14, 149.49, 146.85, 140471.68588], [1575763200000, 147.16, 150.44, 151.62, 146.11, 205301.6026], [1575849600000, 150.44, 147.38, 151.19, 146.56, 243775.99249], [1575936000000, 147.4, 145.56, 148.57, 143.81, 203215.84937], [1576022400000, 145.53, 143.39, 146.34, 142.12, 157843.10484], [1576108800000, 143.41, 144.87, 145.85, 139.24, 261615.30437], [1576195200000, 144.87, 144.8, 146.0, 142.8, 160695.18556], [1576281600000, 144.8, 141.79, 145.07, 141.18, 126232.59201], [1576368000000, 141.79, 142.46, 144.12, 139.92, 151189.65877], [1576454400000, 142.46, 132.73, 142.72, 127.93, 471018.85942], [1576540800000, 132.72, 121.88, 132.98, 119.11, 563257.36001], [1576627200000, 121.88, 132.78, 134.87, 116.26, 884960.91334], [1576713600000, 132.8, 128.1, 134.0, 125.69, 420674.8172], [1576800000000, 128.1, 128.19, 129.39, 125.84, 213897.4673], [1576886400000, 128.19, 126.99, 128.4, 126.5, 135196.11641], [1576972800000, 127.0, 132.09, 133.07, 126.82, 253140.72413], [1577059200000, 132.12, 127.8, 135.1, 126.0, 421600.75655], [1577145600000, 127.8, 127.75, 129.69, 126.61, 200637.10098], [1577232000000, 127.7, 125.09, 127.84, 123.07, 225004.4909], [1577318400000, 125.09, 125.58, 132.26, 124.32, 274986.52097], [1577404800000, 125.58, 126.29, 127.1, 121.91, 240012.37451], [1577491200000, 126.28, 128.11, 129.68, 125.84, 196893.52277], [1577577600000, 128.11, 134.36, 138.07, 127.52, 316347.26666], [1577664000000, 134.36, 131.59, 136.24, 130.3, 320347.21956], [1577750400000, 131.61, 129.16, 133.68, 128.17, 264933.98418], [1577836800000, 129.16, 130.77, 133.05, 128.68, 144770.52197], [1577923200000, 130.72, 127.19, 130.78, 126.38, 213757.05806], [1578009600000, 127.19, 134.35, 135.14, 125.88, 413055.18895], [1578096000000, 134.37, 134.2, 135.85, 132.5, 184276.17102], [1578182400000, 134.2, 135.37, 138.19, 134.19, 254120.45343], [1578268800000, 135.37, 144.15, 144.41, 134.86, 408020.27375], [1578355200000, 144.14, 142.8, 145.31, 138.76, 447762.17281], [1578441600000, 142.8, 140.72, 147.77, 137.03, 570465.57764], [1578528000000, 140.76, 137.74, 141.5, 135.3, 366076.06569], [1578614400000, 137.73, 144.84, 145.17, 135.32, 409403.59507], [1578700800000, 144.83, 142.38, 148.05, 142.09, 368350.57939], [1578787200000, 142.4, 146.54, 146.6, 141.76, 229541.86137], [1578873600000, 146.56, 143.58, 147.0, 142.27, 207996.61865], [1578960000000, 143.58, 165.64, 171.7, 143.51, 1108476.31186], [1579046400000, 165.6, 166.4, 171.98, 159.2, 721687.80381], [1579132800000, 166.4, 164.21, 167.4, 157.8, 456170.86719], [1579219200000, 164.24, 169.85, 174.81, 162.14, 767180.67853], [1579305600000, 169.92, 174.14, 179.5, 164.92, 688783.17982], [1579392000000, 174.1, 166.79, 178.05, 161.66, 624681.28604], [1579478400000, 166.79, 166.87, 169.33, 161.24, 358092.8841], [1579564800000, 166.86, 169.49, 170.32, 164.8, 308007.6353], [1579651200000, 169.48, 168.07, 171.47, 166.03, 272240.90286], [1579737600000, 168.07, 162.81, 168.2, 159.21, 373414.34985], [1579824000000, 162.85, 162.54, 164.45, 155.55, 430013.19902], [1579910400000, 162.51, 160.35, 162.79, 157.61, 219921.65197], [1579996800000, 160.36, 167.86, 168.08, 159.41, 251582.55758], [1580083200000, 167.91, 170.08, 172.56, 165.22, 365894.81917], [1580169600000, 170.04, 175.64, 176.2, 170.03, 473433.89609], [1580256000000, 175.58, 173.72, 178.45, 173.33, 317382.90161], [1580342400000, 173.68, 184.69, 187.0, 170.93, 477721.6609], [1580428800000, 184.71, 179.99, 185.82, 175.22, 385596.53365], [1580515200000, 179.94, 183.6, 184.28, 179.23, 259370.12902], [1580601600000, 183.63, 188.44, 193.43, 179.1, 552621.13619], [1580688000000, 188.48, 189.69, 195.19, 186.62, 417175.95781], [1580774400000, 189.74, 188.91, 191.6, 184.69, 366389.69686], [1580860800000, 188.91, 203.78, 207.61, 188.19, 550942.11417], [1580947200000, 203.78, 213.19, 216.33, 201.02, 608240.2233], [1581033600000, 213.16, 223.33, 225.0, 213.14, 629361.15466], [1581120000000, 223.36, 223.05, 227.75, 213.22, 548551.87465], [1581206400000, 223.01, 228.49, 230.65, 222.86, 350336.24399], [1581292800000, 228.53, 222.89, 229.4, 216.37, 510415.49949], [1581379200000, 222.89, 236.69, 239.15, 218.17, 595576.90276], [1581465600000, 236.69, 265.74, 275.34, 236.69, 1038073.74782], [1581552000000, 265.74, 268.32, 277.69, 256.08, 1089679.1537], [1581638400000, 268.34, 285.15, 287.15, 260.28, 734944.32266], [1581724800000, 285.11, 264.88, 288.41, 261.86, 860813.14274], [1581811200000, 264.91, 258.85, 274.0, 237.41, 1110118.46395], [1581897600000, 258.89, 267.85, 268.77, 242.0, 1110371.39094], [1581984000000, 267.9, 282.61, 285.88, 258.0, 1115523.43992], [1582070400000, 282.64, 258.45, 285.0, 251.56, 705973.72988], [1582156800000, 258.44, 256.96, 264.33, 245.34, 972969.71691], [1582243200000, 256.97, 265.27, 268.24, 253.61, 525827.8734], [1582329600000, 265.32, 261.57, 266.81, 256.0, 313062.52133], [1582416000000, 261.55, 274.48, 275.68, 261.02, 444740.82883], [1582502400000, 274.5, 265.52, 277.2, 257.09, 696591.72983], [1582588800000, 265.47, 246.67, 266.22, 244.44, 774791.01027], [1582675200000, 246.67, 223.93, 250.32, 215.66, 1395879.41507], [1582761600000, 223.98, 227.79, 238.3, 210.0, 1273793.11658], [1582848000000, 227.73, 226.76, 234.67, 214.01, 1054994.92397], [1582934400000, 226.76, 217.21, 233.0, 217.0, 546866.6851], [1583020800000, 217.29, 217.81, 227.89, 212.36, 715016.01941], [1583107200000, 217.81, 231.97, 234.4, 216.07, 810051.4833], [1583193600000, 232.1, 223.91, 232.46, 219.57, 741498.54825], [1583280000000, 223.84, 224.26, 228.85, 220.23, 443780.33772], [1583366400000, 224.26, 228.38, 234.09, 224.23, 601479.87587], [1583452800000, 228.38, 244.88, 245.16, 227.33, 628147.3257], [1583539200000, 244.93, 237.23, 251.93, 236.0, 633748.89662], [1583625600000, 237.23, 199.43, 237.23, 195.5, 1278973.53741], [1583712000000, 199.43, 202.81, 208.62, 190.0, 1661331.83553], [1583798400000, 202.79, 200.7, 206.2, 195.54, 1020260.107], [1583884800000, 200.74, 194.61, 203.18, 181.73, 1079824.90167], [1583971200000, 194.61, 107.82, 195.55, 101.2, 3814533.14046], ]; for (const candle of candles) { const [, , , high, low] = candle; ac.update(low, high); } // Result verified with: // https://github.com/jesse-ai/jesse/blob/53297462d48ebf43f9df46ab5005076d25073e5e/tests/test_indicators.py#L14 expect(ac.isStable).toBeTrue(); expect(ac.getResult().toFixed(2)).toBe('-21.97'); expect(ac.momentum.getResult().toFixed(2)).toBe('-9.22'); expect(ac.lowest!.toFixed(2)).toBe('-21.97'); expect(ac.highest!.toFixed(2)).toBe('11.65'); }); it('throws an error when there is not enough input data', () => { const ac = new AC(5, 34, 5); try { ac.getResult(); fail('Expected error'); } catch (error) { expect(error).toBeInstanceOf(NotEnoughDataError); } }); }); });
the_stack
import type { SinonSpy, SinonStub } from 'sinon'; import * as C from '@apollo/client/core'; import * as S from '@apollo-elements/test'; import { ApolloError } from '@apollo/client/core'; import { aTimeout, expect, fixture, fixtureSync, nextFrame, oneEvent, } from '@open-wc/testing'; import { html } from 'lit/static-html.js'; import { match, spy, stub } from 'sinon'; import { setupClient, teardownClient } from '@apollo-elements/test'; import './apollo-mutation'; import { ApolloMutationElement, } from './apollo-mutation'; import { MutationCompletedEvent, WillNavigateEvent, WillMutateEvent, MutationErrorEvent, } from './events'; describe('[components] <apollo-mutation>', function describeApolloMutation() { beforeEach(setupClient); afterEach(teardownClient); describe('simply instantiating', function() { let element: ApolloMutationElement; beforeEach(async function() { element = await fixture(html`<apollo-mutation></apollo-mutation>`); }); it('has a shadow root', function() { expect(element.shadowRoot).to.be.ok; }); it('uses default template', function() { expect(element).shadowDom.to.equal('<slot></slot>'); }); it('has called: false', function() { expect(element.called).to.be.false; }); describe('setting fetch-policy attr', function() { it('cache-and-network', async function() { element.setAttribute('fetch-policy', 'no-cache'); await element.updateComplete; expect(element.fetchPolicy) .to.equal('no-cache') .and .to.equal(element.controller.options.fetchPolicy); }); it('forwards an illegal value', async function() { element.setAttribute('fetch-policy', 'network-only'); await element.updateComplete; expect(element.fetchPolicy) .to.equal('network-only') .and .to.equal(element.controller.options.fetchPolicy); }); }); describe('setting error-policy attr', function() { it('all', async function() { element.setAttribute('error-policy', 'all'); await element.updateComplete; expect(element.errorPolicy === 'all').to.be.true; expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy); }); it('none', async function() { element.setAttribute('error-policy', 'none'); await element.updateComplete; expect(element.errorPolicy === 'none').to.be.true; expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy); }); it('ignore', async function() { element.setAttribute('error-policy', 'ignore'); await element.updateComplete; expect(element.errorPolicy === 'ignore').to.be.true; expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy); }); it('forwards an illegal value', async function() { element.setAttribute('error-policy', 'shmoo'); await element.updateComplete; // @ts-expect-error: test for bad value expect(element.errorPolicy === 'shmoo').to.be.true; expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy); }); }); describe('setting context', function() { it('as empty object', async function() { element.context = {}; await element.updateComplete; expect(element.controller.options.context) .to.be.ok .to.equal(element.context).and .and.to.be.empty; }); it('as non-empty object', async function() { element.context = { a: 'b' }; await element.updateComplete; expect(element.controller.options.context) .to.equal(element.context).and .to.deep.equal({ a: 'b' }); }); it('as illegal non-object', async function() { // @ts-expect-error: test bad value element.context = 1; await element.updateComplete; expect(element.controller.options.context).to.equal(1); }); }); describe('setting client', function() { it('as global client', async function() { element.client = window.__APOLLO_CLIENT__!; await element.updateComplete; expect(element.controller.client).to.equal(window.__APOLLO_CLIENT__); }); it('as new client', async function() { const client = new C.ApolloClient({ cache: new C.InMemoryCache() }); element.client = client; await element.updateComplete; expect(element.controller.client).to.equal(client); }); it('as illegal value', async function() { // @ts-expect-error: test bad value element.client = 1; await element.updateComplete; expect(element.controller.client).to.equal(1); }); }); describe('setting ignoreResults', function() { it('as true', async function() { element.ignoreResults = true; await element.updateComplete; expect(element.controller.options.ignoreResults).to.equal(true); }); it('as false', async function() { element.ignoreResults = false; await element.updateComplete; expect(element.controller.options.ignoreResults).to.equal(false); }); it('as illegal value', async function() { // @ts-expect-error: test bad value element.ignoreResults = 1; await element.updateComplete; expect(element.controller.options.ignoreResults).to.equal(1); }); }); describe('setting awaitRefetchQueries', function() { it('as true', async function() { element.awaitRefetchQueries = true; await element.updateComplete; expect(element.controller.options.awaitRefetchQueries).to.equal(true); }); it('as false', async function() { element.awaitRefetchQueries = false; await element.updateComplete; expect(element.controller.options.awaitRefetchQueries).to.equal(false); }); it('as illegal value', async function() { // @ts-expect-error: test bad value element.awaitRefetchQueries = 1; await element.updateComplete; expect(element.controller.options.awaitRefetchQueries).to.equal(1); }); }); describe('setting loading', function() { it('as true', async function() { element.loading = true; await element.updateComplete; expect(element.controller.loading).to.equal(true); }); it('as false', async function() { element.loading = false; await element.updateComplete; expect(element.controller.loading).to.equal(false); }); it('as illegal value', async function() { // @ts-expect-error: test bad value element.loading = 1; await element.updateComplete; expect(element.controller.loading).to.equal(1); }); }); describe('setting mutation', function() { it('as DocumentNode', async function() { const mutation = C.gql`mutation { nullable }`; element.mutation = mutation; await element.updateComplete; expect(element.controller.mutation) .to.equal(mutation) .and.to.equal(element.controller.document); }); it('as TypedDocumentNode', async function() { const mutation = C.gql`mutation { nullable }` as C.TypedDocumentNode<{ a: 'b'}, {a: 'b'}>; element.mutation = mutation; await element.updateComplete; expect(element.controller.mutation).to.equal(mutation); const l = element as unknown as ApolloMutationElement<typeof mutation>; l.data = { a: 'b' }; // @ts-expect-error: can't assign bad data type l.data = { b: 'c' }; // @ts-expect-error: can't assign bad variables type l.variables = { b: 'c' }; }); it('as illegal value', async function() { expect(() => { // @ts-expect-error: can't assign bad variables type element.mutation = 1; }).to.throw(/Mutation must be a parsed GraphQL document./); await element.updateComplete; expect(element.mutation) .to.be.null.and .to.equal(element.document).and .to.equal(element.controller.mutation).and .to.equal(element.controller.document); }); }); describe('setting error', function() { it('as ApolloError', async function() { let error: C.ApolloError | undefined = undefined; try { error = new C.ApolloError({ }); element.error = error; } catch { null; } await element.updateComplete; expect(element.controller.error).to.equal(error); }); it('as Error', async function() { let error: Error; try { throw new Error(); } catch (e) { error = e as Error; element.error = error as Error; } await element.updateComplete; expect(element.controller.error).to.equal(error); }); it('as null', async function() { const error = null; element.error = error; await element.updateComplete; expect(element.controller.error).to.equal(error); }); it('as illegal value', async function() { const error = 0; // @ts-expect-error: test bad value element.error = error; await element.updateComplete; expect(element.controller.error).to.equal(error); }); }); describe('setting optimisticResponse', function() { let l: ApolloMutationElement<typeof S.UpdateUserMutation>; beforeEach(() => l = element as unknown as typeof l); it('as Object', async function() { const optimisticResponse = { updateUser: { username: 'bob', haircolor: 'red', nickname: 'red bob', }, }; l.optimisticResponse = optimisticResponse; await l.updateComplete; expect(l.controller.options.optimisticResponse).to.equal(optimisticResponse); }); it('as function', async function() { const optimisticResponse = (vars: typeof l['variables']) => ({ updateUser: { username: vars?.username, haircolor: vars?.haircolor, nickname: `${vars?.haircolor} ${vars?.username}`, }, }); l.optimisticResponse = optimisticResponse; await l.updateComplete; expect(l.controller.options.optimisticResponse).to.equal(optimisticResponse); }); it('as undefined', async function() { const optimisticResponse = undefined; l.optimisticResponse = optimisticResponse; await l.updateComplete; expect(l.controller.options.optimisticResponse).to.equal(optimisticResponse); }); it('as illegal value', async function() { const optimisticResponse = 0; // @ts-expect-error: test bad value l.optimisticResponse = optimisticResponse; await l.updateComplete; expect(l.controller.options.optimisticResponse).to.equal(optimisticResponse); }); }); }); describe('with no variables in DOM', function() { let element: ApolloMutationElement; beforeEach(async function() { element = await fixture(html`<apollo-mutation></apollo-mutation>`); }); it('does not set variables', function() { expect(element.variables).to.be.null; }); describe('calling mutate({ mutation, variables })', function() { beforeEach(() => spy(element.controller, 'mutate')); afterEach(() => (element.controller.mutate as SinonSpy).restore?.()); beforeEach(() => element.mutate({ mutation: S.NullableParamMutation, variables: { nullable: 'nul' }, })); it('calls controller mutate', function() { expect(element.controller.mutate).to.have.been.calledWithMatch({ mutation: S.NullableParamMutation, variables: { nullable: 'nul' }, }); }); it('sets called', function() { expect(element.called).to.be.true; }); }); }); describe('with refetch-queries attr', function() { type D = { i: number } type V = { data: number, context: Record<string, unknown>, errors: string[] } let element: ApolloMutationElement<D, V>; beforeEach(async function() { element = await fixture(html` <apollo-mutation refetch-queries="A, B,C , D ,E"></apollo-mutation> `); }); beforeEach(nextFrame); it('sets refetchQueries', function() { expect(element.refetchQueries) .to.deep.equal(['A', 'B', 'C', 'D', 'E']) .and.to.deep.equal(element.controller.options.refetchQueries); element.refetchQueries = ['a', 'b']; element.refetchQueries = result => ['a', { query: C.gql`{}` as C.TypedDocumentNode<D, V>, variables: { data: result.data?.i, context: result.context, errors: result.errors!.map(x => x.message), }, }]; }); describe('then removing attribute', function() { beforeEach(() => element.removeAttribute('refetch-queries')); beforeEach(nextFrame); it('unsets the property', function() { expect(element.refetchQueries).to.be.null; }); }); describe('calling mutate({ mutation })', function() { beforeEach(() => spy(element.controller.client!, 'mutate')); afterEach(() => (element.controller.client!.mutate as SinonSpy).restore?.()); beforeEach(() => element.mutate({ mutation: S.NullableParamMutation })); it('calls client mutate', function() { expect(element.controller.client!.mutate).to.have.been.calledWith(match({ mutation: S.NullableParamMutation, refetchQueries: ['A', 'B', 'C', 'D', 'E'], })); }); }); }); describe('with variables as data attributes', function() { let element: ApolloMutationElement; beforeEach(async function() { element = await fixture<ApolloMutationElement>(html` <apollo-mutation data-var-a="variable-a" data-var-b="variable-b" ></apollo-mutation> `); }); beforeEach(nextFrame); it('reads variables from dataset', function() { expect(element.variables).to.deep.equal({ varA: 'variable-a', varB: 'variable-b', }); }); describe('setting inputKey', function() { const inputKey = 'inputTypeName'; beforeEach(function() { element.inputKey = inputKey; }); beforeEach(nextFrame); it('wraps variables in object with input key', function() { expect(element.variables).to.deep.equal({ [inputKey]: { varA: 'variable-a', varB: 'variable-b', }, }); }); it('sets input-key attribute', function() { expect(element.getAttribute('input-key')).to.equal(inputKey); }); describe('then removing input-key attribute', function() { beforeEach(function() { element.removeAttribute('input-key'); }); beforeEach(nextFrame); it('unsets inputKey', function() { expect(element.inputKey).to.be.null; }); }); describe('then setting input-key attribute with the same value', function() { beforeEach(function() { element.setAttribute('input-key', inputKey); }); beforeEach(nextFrame); it('has no effect', function() { expect(element.inputKey).to.equal(inputKey); }); }); }); }); describe('with children for variables', function() { let element: ApolloMutationElement; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation input-key="inputTypeName"> <input data-variable="varA" value="variable-a"/> <input data-variable="varB" value="variable-b"/> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ inputTypeName: { varA: 'variable-a', varB: 'variable-b', }, }); }); }); describe('with single input variable', function() { let element: ApolloMutationElement; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation> <input data-variable="varA" value="variable-a"/> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ varA: 'variable-a', }); }); }); describe('with multiple input variables', function() { let element: ApolloMutationElement; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation> <input data-variable="varA" value="variable-a"/> <input data-variable="varB" value="variable-b"/> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ varA: 'variable-a', varB: 'variable-b', }); }); }); describe('with single labeled variable', function() { let element: ApolloMutationElement; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation> <label> variable-a <input data-variable="varA" value="variable-a"/> </label> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ varA: 'variable-a', }); }); }); describe('with mixed attribute, input, and labeled variables', function() { let element: ApolloMutationElement; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation data-var-b="variable-b"> <label> variable-a <input data-variable="varA" value="variable-a"/> </label> <input data-variable="varC" value="variable-c" aria-label="variable C"/> <input class="sneaky-non-variable-no-dataset"/> </apollo-mutation> `); }); it('reads variables from attributes and children', function() { expect(element.variables).to.deep.equal({ varA: 'variable-a', varB: 'variable-b', varC: 'variable-c', }); }); }); describe('with variables as data attributes and children variables', function() { let element: ApolloMutationElement; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation data-var-a="variable-a" data-var-b="variable-b"> <input data-variable="varC" value="variable-c"/> <input data-variable="varD" value="variable-d"/> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ varA: 'variable-a', varB: 'variable-b', varC: 'variable-c', varD: 'variable-d', }); }); }); describe('with `variables-for` and `trigger-for` sibling nodes', function() { let container: HTMLElement; let element: ApolloMutationElement; beforeEach(async function() { container = await fixture(` <div> <button trigger-for="my-mutation">Launch</button> <label>Name <input variable-for="my-mutation" data-variable="name" value="Neil"/></label> <apollo-mutation id="my-mutation" data-id="1"> <label>Email <input type="email" data-variable="email" value="neil@nasa.gov"/></label> </apollo-mutation> </div> `); element = container.querySelector('apollo-mutation') as ApolloMutationElement; spy(element, 'mutate'); await element.updateComplete; }); it('reads variables from the root node', function() { expect(element.variables).to.deep.equal({ id: '1', name: 'Neil', email: 'neil@nasa.gov', }); }); describe('clicking the sibling trigger', function() { beforeEach(function() { container.querySelector('button')!.click(); }); it('calls mutate on the element', function() { expect(element.mutate).to.have.been.calledOnce; }); }); }); describe('with an input key', function() { describe('with variables as data attributes', function() { let element: ApolloMutationElement; const inputKey = 'inputTypeName'; beforeEach(async function() { element = fixtureSync<ApolloMutationElement>(html` <apollo-mutation input-key="${inputKey}" data-var-a="variable-a" data-var-b="variable-b" ></apollo-mutation> `); }); it('reads variables from dataset', function() { expect(element.variables).to.deep.equal({ [inputKey]: { varA: 'variable-a', varB: 'variable-b', }, }); }); describe('then nullifying inputKey', function() { beforeEach(function() { element.inputKey = null; }); beforeEach(nextFrame); it('removes the input-key attribute', function() { expect(element.hasAttribute('input-key')).to.be.false; }); }); describe('then setting inputKey with the same value', function() { beforeEach(function() { element.inputKey = inputKey; }); it('has no effect', function() { expect(element.getAttribute('input-key')).to.equal(inputKey); }); }); }); describe('with children for variables', function() { let element: ApolloMutationElement; beforeEach(async function() { element = await fixture<ApolloMutationElement>(html` <apollo-mutation input-key="inputTypeName"> <input data-variable="varA" value="variable-a"/> <input data-variable="varB" value="variable-b"/> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ inputTypeName: { varA: 'variable-a', varB: 'variable-b', }, }); }); }); describe('with variables as data attributes and children for variables', function() { let element: ApolloMutationElement; beforeEach(async function() { element = await fixture<ApolloMutationElement>(html` <apollo-mutation input-key="inputTypeName" data-var-a="variable-a" data-var-b="variable-b"> <input data-variable="varC" value="variable-c"/> <input data-variable="varD" value="variable-d"/> </apollo-mutation> `); }); it('reads variables from children', function() { expect(element.variables).to.deep.equal({ inputTypeName: { varA: 'variable-a', varB: 'variable-b', varC: 'variable-c', varD: 'variable-d', }, }); }); }); }); describe('with a button trigger', function() { let element: ApolloMutationElement<typeof S.NoParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NoParamMutation}"> <button trigger>mutate</button> </apollo-mutation> `); }); function clickButton() { element.querySelector('button')!.click(); } it('has no href', function() { // @ts-expect-error: coverage... expect(element.href).to.be.undefined; }); describe('clicking the button', function() { it('mutates', async function() { expect(element.data).to.not.be.ok; clickButton(); await aTimeout(10); expect(element.data).to.be.ok; }); it('fires will-mutate event', async function() { setTimeout(clickButton); const event = await oneEvent(element, WillMutateEvent.type); expect(event.detail.element).to.equal(element); }); it('fires mutation-completed event', async function() { setTimeout(clickButton); const event = await oneEvent(element, MutationCompletedEvent.type); expect(event.detail.element).to.equal(element); }); describe('when will-mutate event is canceled', function() { it('does not mutate', async function() { const { type } = WillMutateEvent; element.addEventListener(type, function(event) { event.preventDefault(); expect(event.detail.element).to.equal(element); }, { once: true }); clickButton(); await aTimeout(10); expect(element.data).to.not.be.ok; }); }); }); describe('when button is removed', function() { beforeEach(function() { element.querySelector('button')!.remove(); }); it('destroys trigger', function() { // @ts-expect-error: doing it for the coverage expect(element.buttons.length).to.equal(0); }); }); }); describe('with a link trigger', function() { let element: ApolloMutationElement<typeof S.NoParamMutation>; let replaceStateStub: SinonStub; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NoParamMutation}"> <a href="#foo" trigger>do it.</a> </apollo-mutation> `); replaceStateStub = stub(history, 'replaceState'); }); afterEach(function() { replaceStateStub.restore(); element.remove(); // just clearing the text fixture element = undefined as unknown as typeof element; }); describe('clicking the link', function() { it('mutates', async function() { expect(element.data).to.not.be.ok; element.querySelector<HTMLButtonElement>('[trigger]')!.click(); await aTimeout(10); expect(element.data).to.be.ok; }); it('fires will-mutate event', async function() { setTimeout(() => { element.querySelector<HTMLButtonElement>('[trigger]')!.click(); }); const event = await oneEvent(element, WillMutateEvent.type); expect(event.detail.element).to.equal(element); }); it('fires mutation-completed event', async function() { setTimeout(() => { element.querySelector<HTMLButtonElement>('[trigger]')!.click(); }); const event = await oneEvent(element, MutationCompletedEvent.type); expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); }); it('fires will-navigate event', async function() { setTimeout(() => { element.querySelector<HTMLButtonElement>('[trigger]')!.click(); }); const event = await oneEvent(element, WillNavigateEvent.type); expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); }); it('navigates', async function() { setTimeout(() => { element.querySelector<HTMLButtonElement>('[trigger]')!.click(); }); await oneEvent(element, WillNavigateEvent.type); expect(replaceStateStub).to.have.been.called; }); describe('when will-navigate event is canceled', function() { it('does not navigate', async function() { const { type } = WillNavigateEvent; element.addEventListener(type, function(event) { event.preventDefault(); expect(event.detail.element).to.equal(element); }, { once: true }); element.querySelector<HTMLButtonElement>('[trigger]')!.click(); await aTimeout(10); expect(replaceStateStub).to.not.have.been.called; }); }); describe('when will-mutate event is canceled', function() { it('does not mutate', async function() { const { type } = WillMutateEvent; element.addEventListener(type, function(event) { event.preventDefault(); expect(event.detail.element).to.equal(element); }, { once: true }); element.querySelector<HTMLButtonElement>('[trigger]')!.click(); await aTimeout(10); expect(element.data).to.not.be.ok; }); }); }); describe('clicking twice', function() { it('mutates', async function() { const link = element.querySelector('a'); let count = 0; element.addEventListener(WillMutateEvent.type, function() { count++; }); link!.click(); link!.click(); link!.click(); expect(count).to.equal(1); }); }); }); describe('with a link trigger that wraps a button', function() { let element: ApolloMutationElement<typeof S.NullableParamMutation>; let replaceStateStub: SinonStub; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NullableParamMutation}"> <a href="#foo" trigger> <button>do it</button> </a> </apollo-mutation> `); replaceStateStub = stub(history, 'replaceState'); }); afterEach(function() { replaceStateStub.restore(); }); describe('when element has `resolveURL` property', function() { beforeEach(function() { element.resolveURL = (data: S.NullableParamMutationData): string => `/nullable/${data?.nullableParam?.nullable}/`; element.setAttribute('data-nullable', 'special'); }); beforeEach(nextFrame); describe('clicking the button', function() { beforeEach(() => spy(element.controller.client!, 'mutate')); afterEach(() => (element.controller.client!.mutate as SinonSpy).restore?.()); beforeEach(async function() { const button = element.querySelector('button'); button!.click(); await aTimeout(100); }); it('navigates to the resolved URL', function() { expect(element.controller.client!.mutate).to.have.been.calledWithMatch({ variables: { nullable: 'special', }, }); expect(replaceStateStub) .to.have.been.calledWith(element.data, 'will-navigate', '/nullable/special/'); }); }); }); describe('clicking the link', function() { it('mutates', async function() { const button = element.querySelector('button'); expect(element.data).to.not.be.ok; button!.click(); await aTimeout(10); expect(element.data).to.be.ok; }); it('fires will-mutate event', async function() { const button = element.querySelector('button'); setTimeout(() => button!.click()); const event = await oneEvent(element, WillMutateEvent.type); expect(event.detail.element).to.equal(element); }); it('fires mutation-completed event', async function() { const button = element.querySelector('button'); setTimeout(async function() { button!.click(); expect(button!.disabled, 'button disabled').to.be.true; }); const event = await oneEvent(element, MutationCompletedEvent.type); expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); expect(button!.disabled).to.be.false; }); it('fires will-navigate event', async function() { const button = element.querySelector('button'); setTimeout(() => button!.click()); const event = await oneEvent(element, WillNavigateEvent.type); expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); }); it('navigates', async function() { setTimeout(() => { element.querySelector('button')!.click(); }); await oneEvent(element, WillNavigateEvent.type); expect(replaceStateStub).to.have.been.called; }); describe('when will-navigate event is canceled', function() { it('does not navigate', async function() { const button = element.querySelector('button'); const { type } = WillNavigateEvent; element.addEventListener(type, function(event) { event.preventDefault(); expect(event.detail.element).to.equal(element); }, { once: true }); button!.click(); await aTimeout(100); expect(replaceStateStub).to.not.have.been.called; }); }); describe('when will-mutate event is canceled', function() { it('does not mutate', async function() { const { type } = WillMutateEvent; element.addEventListener(type, function(event) { event.preventDefault(); expect(event.detail.element).to.equal(element); }, { once: true }); element.querySelector('button')!.click(); await aTimeout(10); expect(element.data).to.not.be.ok; }); }); }); }); describe('with variable inputs and a button trigger', function() { let element: ApolloMutationElement<typeof S.NullableParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NullableParamMutation}"> <input data-variable="nullable" value="input"> <input data-vrible="nullable" value="fail"> <button trigger>Do It</button> </apollo-mutation> `); }); describe('clicking the button', function() { let input: HTMLInputElement; let button: HTMLButtonElement; let event: MutationCompletedEvent; beforeEach(async function() { input = element.querySelector('input')!; button = element.querySelector('button')!; setTimeout(async function() { button.click(); expect(input.disabled, 'input disabled').to.be.true; }); event = await oneEvent(element, MutationCompletedEvent.type); }); it('toggles input disabled property', async function() { expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); expect(input.disabled).to.be.false; }); it('uses input variables', function() { expect(element.data!.nullableParam!.nullable).to.equal('input'); }); }); describe('setting variables property', function() { let input: HTMLInputElement; let button: HTMLButtonElement; let event: MutationCompletedEvent; beforeEach(function() { element.variables = { nullable: 'manual' }; }); beforeEach(async function() { input = element.querySelector('input')!; button = element.querySelector('button')!; setTimeout(async function() { button.click(); expect(input.disabled).to.be.true; }); event = await oneEvent(element, MutationCompletedEvent.type); }); describe('clicking the button', function() { it('toggles input disabled property', async function() { expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); expect(input.disabled).to.be.false; }); it('uses set variables instead of input variables', function() { expect(element.data!.nullableParam!.nullable).to.equal('manual'); }); }); }); }); describe('with variable script and a button trigger', function() { let element: ApolloMutationElement<typeof S.NullableParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NullableParamMutation}"> <button trigger>Do It</button> <script type="application/json"> { "nullable": "DOM" } </script> </apollo-mutation> `); }); describe('clicking the button', function() { let button: HTMLButtonElement; beforeEach(async function() { button = element.querySelector('button')!; setTimeout(async function() { button.click(); }); await oneEvent(element, MutationCompletedEvent.type); }); it('uses DOM variables', function() { expect(element.data!.nullableParam!.nullable).to.equal('DOM'); }); }); describe('setting variables property', function() { let button: HTMLButtonElement; let event: MutationCompletedEvent; beforeEach(function() { element.variables = { nullable: 'manual' }; }); beforeEach(async function() { button = element.querySelector('button')!; setTimeout(async function() { button.click(); }); event = await oneEvent(element, MutationCompletedEvent.type); }); describe('clicking the button', function() { it('toggles input disabled property', async function() { expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); }); it('uses set variables instead of input variables', function() { expect(element.data!.nullableParam!.nullable).to.equal('manual'); }); }); }); }); describe('with multiple variable inputs that trigger on change', function() { let element: ApolloMutationElement<typeof S.InputParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation input-key="input" .mutation="${S.InputParamMutation}"> <input data-variable="a" trigger="change"/> <input data-variable="b" trigger="change"/> <button trigger>Save</button> </apollo-mutation> `); }); describe('typing in the first input', function() { let input: HTMLInputElement; let event: MutationCompletedEvent; let disabledAfterTyping: boolean; beforeEach(async function() { input = element.querySelector('input[data-variable="a"]')!; setTimeout(async function() { input.value = 'hello'; input.dispatchEvent(new Event('change')); disabledAfterTyping = input.disabled; }); event = await oneEvent(element, MutationCompletedEvent.type); }); it('toggles input disabled property', async function() { expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); expect(input.disabled).to.be.false.and.to.not.equal(disabledAfterTyping); }); it('uses input variables', function() { expect(element.data!.inputParam!.a).to.equal('hello'); expect(element.data!.inputParam!.b).to.equal('b'); }); }); describe('typing in the second input', function() { let input: HTMLInputElement; let event: MutationCompletedEvent; let disabledAfterTyping: boolean; beforeEach(nextFrame); beforeEach(async function() { input = element.querySelector('input[data-variable="b"]')!; setTimeout(function() { input.value = 'hello'; input.dispatchEvent(new Event('change')); disabledAfterTyping = input.disabled; }); event = await oneEvent(element, MutationCompletedEvent.type); }); it('toggles input disabled property', async function() { expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); expect(input.disabled).to.be.false.and.to.not.equal(disabledAfterTyping); }); it('uses input variables', function() { expect(element.data!.inputParam!.a).to.equal('a'); expect(element.data!.inputParam!.b).to.equal('hello'); }); }); describe('clicking the button', function() { let input: HTMLInputElement; let button: HTMLButtonElement; let event: MutationCompletedEvent; beforeEach(async function() { input = element.querySelector('input')!; button = element.querySelector('button')!; setTimeout(async function() { button.click(); expect(input.disabled).to.be.true; }); event = await oneEvent(element, MutationCompletedEvent.type); }); it('toggles input disabled property', async function() { expect(event.detail.element).to.equal(element); expect(event.detail.data).to.equal(element.data); expect(input.disabled).to.be.false; }); it('uses input variables', function() { expect(element.data!.inputParam!.a).to.equal('a'); expect(element.data!.inputParam!.b).to.equal('b'); }); }); }); describe('with multiple variable inputs that trigger on keyup', function() { let element: ApolloMutationElement<typeof S.InputParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation input-key="input" .mutation="${S.InputParamMutation}"> <input data-variable="a" trigger="keyup"/> <input data-variable="b" trigger="keyup"/> </apollo-mutation> `); }); describe('setting debounce to 500', function() { beforeEach(() => spy(element.controller, 'mutate')); afterEach(() => (element.controller.mutate as SinonSpy).restore?.()); beforeEach(function() { element.debounce = 500; }); beforeEach(nextFrame); it('reflects to attr', function() { expect(element.getAttribute('debounce')).to.equal('500'); }); describe('then typing in first input', function() { beforeEach(async function() { const input = element.querySelector('input')!; input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); }); beforeEach(() => aTimeout(1000)); it('only mutates once', function() { expect(element.controller.mutate).to.have.been.calledOnce; }); }); describe('then removing attribute', function() { beforeEach(function() { element.removeAttribute('debounce'); }); beforeEach(nextFrame); it('unsets property', function() { expect(element.debounce).to.be.null; }); describe('then typing in first input', function() { beforeEach(async function() { const input = element.querySelector('input')!; input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); await nextFrame(); input.dispatchEvent(new Event('keyup')); }); beforeEach(() => aTimeout(1000)); it('mutates many times', function() { expect((element.controller.mutate as SinonSpy).callCount).to.be.greaterThan(1); }); }); }); }); }); describe('when mutation errors', function() { let element: ApolloMutationElement<typeof S.NullableParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NullableParamMutation}" data-nullable="error"> <button trigger>Do It</button> </apollo-mutation> `); }); describe('clicking the button', function() { it('fires mutation-error event', async function() { setTimeout(() => element.querySelector('button')!.click()); const event = await oneEvent(element, MutationErrorEvent.type); expect(event.detail.element).to.equal(element); expect(event.detail.error).to.be.an.instanceOf(ApolloError); }); }); }); describe('with a template and a mutation', function() { let element: ApolloMutationElement<typeof S.NoParamMutation>; beforeEach(async function() { element = await fixture<typeof element>(html` <apollo-mutation .mutation="${S.NoParamMutation}"> <button trigger>mutate</button> <template> <span class="{{ data.noParam.noParam || 'no-data' }}"></span> </template> </apollo-mutation> `); }); describe('before mutating', function() { it('renders null data to shadow root', function() { expect(element).shadowDom.to.equal('<span class="no-data"></span>'); }); }); describe('after mutating', function() { beforeEach(async function() { setTimeout(function() { element.querySelector('button')!.click(); }); await oneEvent(element, 'mutation-completed'); }); beforeEach(() => element.updateComplete); it('renders data to shadow root', function() { expect(element).shadowDom.to.equal('<span class="noParam"></span>'); }); }); }); describe('with no-shadow attribute set, a template, and a mutation', function() { let element: ApolloMutationElement<typeof S.NoParamMutation>; beforeEach(async function() { element = fixtureSync<typeof element>(html` <apollo-mutation no-shadow .mutation="${S.NoParamMutation}"> <button id="trigger" trigger>mutate</button> <template> <span class="{{ data.noParam.noParam || 'no-data' }}"></span> </template> </apollo-mutation> `); }); describe('before mutating', function() { it('renders null data to light children', function() { expect(element.shadowRoot).to.be.null; expect(element).lightDom.to.equal(` <button id="trigger" trigger>mutate</button> <template></template> <div class="output"> <span class="no-data"></span> </div> `); }); }); describe('after mutating', function() { beforeEach(async function() { setTimeout(function() { element.querySelector('button')!.click(); }); await oneEvent(element, 'mutation-completed'); }); beforeEach(() => element.updateComplete); it('renders data to shadow root', function() { expect(element).lightDom.to.equal(` <button id="trigger" trigger>mutate</button> <template></template> <div class="output"> <span class="noParam"></span> </div> `); }); }); describe('when cheekily moving the trigger', function() { let movedTrigger: HTMLButtonElement; let newTrigger: HTMLButtonElement; beforeEach(() => spy(element.controller, 'mutate')); afterEach(() => (element.controller.mutate as SinonSpy).restore?.()); beforeEach(function() { const node = document.createElement('div'); movedTrigger = element.querySelector('[trigger]')!; node.classList.add('haha'); document.body.append(node); node.append(movedTrigger); }); beforeEach(nextFrame); afterEach(function() { document.querySelector('haha')?.remove?.(); }); describe('then clicking the moved trigger', function() { beforeEach(nextFrame); beforeEach(function() { movedTrigger.click(); }); it('does not mutate', function() { expect(element.controller.mutate).to.not.have.been.called; }); }); describe('then adding a new trigger', function() { beforeEach(function() { newTrigger = document.createElement('button'); newTrigger.id = 'new-trigger'; newTrigger.setAttribute('trigger', ''); element.appendChild(newTrigger); }); beforeEach(nextFrame); describe('when clicking the new trigger', function() { beforeEach(function() { newTrigger.click(); }); beforeEach(nextFrame); it('mutates', function() { expect(element.controller.mutate).to.have.been.called; }); }); }); }); }); });
the_stack
// This is internal methods of graphql-js (introduced in 14.0.0) // required for correct config conversion to internal field definition of types // copy pasted from https://github.com/graphql/graphql-js/blame/master/src/type/definition.js import type { Thunk } from './definitions'; import { inspect, invariant } from './misc'; import { isFunction, isObject } from './is'; import { SchemaComposer } from '../SchemaComposer'; import { ThunkComposer } from '../ThunkComposer'; import type { GraphQLFieldConfigMap, GraphQLInputFieldConfigMap, GraphQLFieldMap, GraphQLEnumType, GraphQLEnumValueConfigMap, GraphQLEnumValue, GraphQLObjectType, GraphQLInterfaceType, GraphQLInputObjectType, GraphQLInputFieldMap, ObjectTypeDefinitionNode, InterfaceTypeDefinitionNode, EnumTypeDefinitionNode, FieldDefinitionNode, InputObjectTypeDefinitionNode, } from '../graphql'; import type { InputTypeComposerFieldConfigMap } from '../InputTypeComposer'; import type { EnumTypeComposerValueConfigMap } from '../EnumTypeComposer'; import { ObjectTypeComposer, ObjectTypeComposerFieldConfigMap, ObjectTypeComposerFieldConfigMapDefinition, ObjectTypeComposerDefinition, ObjectTypeComposerThunked, ObjectTypeComposerArgumentConfigMap, } from '../ObjectTypeComposer'; import { InterfaceTypeComposerDefinition, InterfaceTypeComposerThunked, InterfaceTypeComposer, } from '../InterfaceTypeComposer'; import { getComposeTypeName } from './typeHelpers'; function isPlainObj(obj: any): obj is Record<any, any> { return obj && typeof obj === 'object' && !Array.isArray(obj); } export function defineFieldMap( config: GraphQLObjectType | GraphQLInterfaceType, fieldMap: GraphQLFieldConfigMap<any, any>, parentAstNode?: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | null ): GraphQLFieldMap<any, any> { invariant( isPlainObj(fieldMap), `${config.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); // Perf: prepare AST node maps to avoid costly lookups const fieldAstNodeMap = Object.create(null); const argAstNodeMap = Object.create(null); for (const fieldNode of parentAstNode?.fields ?? []) { if (!fieldAstNodeMap[fieldNode.name.value]) { fieldAstNodeMap[fieldNode.name.value] = fieldNode; argAstNodeMap[fieldNode.name.value] = Object.create(null); } for (const argAstNode of fieldNode?.arguments ?? []) { if (!argAstNodeMap[fieldNode.name.value][argAstNode.name.value]) { argAstNodeMap[fieldNode.name.value][argAstNode.name.value] = argAstNode; } } } const resultFieldMap = Object.create(null); for (const fieldName of Object.keys(fieldMap)) { const fieldConfig = fieldMap[fieldName]; const fieldNodeAst = fieldAstNodeMap[fieldName] as FieldDefinitionNode; invariant( isPlainObj(fieldConfig), `${config.name}.${fieldName} field config must be an object` ); const field = { ...fieldConfig, isDeprecated: Boolean(fieldConfig.deprecationReason), name: fieldName, astNode: fieldNodeAst, }; invariant( field.resolve == null || typeof field.resolve === 'function', `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${inspect(field.resolve)}.` ); const argsConfig = fieldConfig.args; if (!argsConfig) { field.args = [] as any; } else { invariant( isPlainObj(argsConfig), `${config.name}.${fieldName} args must be an object with argument names as keys.` ); const fieldArgNodeMap = argAstNodeMap[fieldName] ?? {}; field.args = Object.keys(argsConfig).map((argName) => { const arg = argsConfig[argName]; return { name: argName, description: arg.description === undefined ? null : arg.description, type: arg.type, isDeprecated: Boolean(fieldConfig.deprecationReason), deprecationReason: arg?.deprecationReason, defaultValue: arg.defaultValue, astNode: fieldArgNodeMap[argName], }; }) as any; } resultFieldMap[fieldName] = field; } return resultFieldMap; } export function convertObjectFieldMapToConfig( fieldMap: Thunk<GraphQLFieldMap<any, any> | ObjectTypeComposerFieldConfigMapDefinition<any, any>>, sc: SchemaComposer<any> ): ObjectTypeComposerFieldConfigMap<any, any> { const fields = {} as ObjectTypeComposerFieldConfigMap<any, any>; const isThunk = isFunction(fieldMap); const _fields: any = isThunk ? (fieldMap as any)(sc) : fieldMap; if (!isObject(_fields)) return {}; Object.keys(_fields).forEach((n) => { const { name, isDeprecated, ...fc } = _fields[n]; const args = {} as ObjectTypeComposerArgumentConfigMap; if (Array.isArray(fc.args)) { // `fc.args` is an Array in `GraphQLFieldMap` fc.args.forEach((arg: any) => { const { name: argName, ...ac } = arg; args[argName] = { ...ac, type: isThunk ? new ThunkComposer( () => sc.typeMapper.convertInputTypeDefinition(ac.type || arg) as any ) : sc.typeMapper.convertInputTypeDefinition(ac.type || arg), directives: sc.typeMapper.parseDirectives(ac?.astNode?.directives), }; }); fc.args = args; } else if (isObject(fc.args)) { // `fc.args` is Object in `ObjectTypeComposerFieldConfigMapDefinition` Object.keys(fc.args).forEach((argName) => { const sourceArgs = fc.args; args[argName] = { ...(isObject(sourceArgs[argName]) ? sourceArgs[argName] : null), type: isThunk ? new ThunkComposer( () => sc.typeMapper.convertInputTypeDefinition( sourceArgs[argName].type || sourceArgs[argName] ) as any ) : sc.typeMapper.convertInputTypeDefinition( sourceArgs[argName].type || sourceArgs[argName] ), }; }); fc.args = args; } fields[n] = { ...fc, type: isThunk ? new ThunkComposer( () => sc.typeMapper.convertOutputTypeDefinition(fc.type || _fields[n]) as any ) : sc.typeMapper.convertOutputTypeDefinition(fc.type || _fields[n]), directives: sc.typeMapper.parseDirectives(fc?.astNode?.directives), }; }); return fields; } export function defineEnumValues( type: GraphQLEnumType, valueMap: GraphQLEnumValueConfigMap /* <T> */, parentAstNode?: EnumTypeDefinitionNode ): Array<GraphQLEnumValue /* <T> */> { invariant( isPlainObj(valueMap), `${type.name} values must be an object with value names as keys.` ); const astNodeMap = Object.create(null); for (const valueNode of parentAstNode?.values ?? []) { astNodeMap[valueNode.name.value] = valueNode; } return Object.keys(valueMap).map((valueName) => { const value = valueMap[valueName]; invariant( isPlainObj(value), `${type.name}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${inspect(value)}.` ); invariant( !value.hasOwnProperty('isDeprecated'), `${type.name}.${valueName} should provide "deprecationReason" instead of "isDeprecated".` ); return { name: valueName, description: value.description, isDeprecated: Boolean(value.deprecationReason), deprecationReason: value.deprecationReason, astNode: astNodeMap[valueName], value: value.hasOwnProperty('value') ? value.value : valueName, extensions: {}, } as GraphQLEnumValue; }); } export function convertEnumValuesToConfig( values: ReadonlyArray<GraphQLEnumValue>, schemaComposer: SchemaComposer<any> ): EnumTypeComposerValueConfigMap { const fields = {} as EnumTypeComposerValueConfigMap; values.forEach(({ name, isDeprecated, ...fc }: any) => { fields[name] = fc as any; if (fc?.astNode?.directives) { const directives = schemaComposer.typeMapper.parseDirectives(fc.astNode.directives); if (directives) { fields[name].directives = directives; } } }); return fields; } export function defineInputFieldMap( config: GraphQLInputObjectType, fieldMap: GraphQLInputFieldConfigMap, parentAstNode?: InputObjectTypeDefinitionNode | null ): GraphQLInputFieldMap { invariant( isPlainObj(fieldMap), `${config.name} fields must be an object with field names as keys or a ` + 'function which returns such an object.' ); const astNodeMap = Object.create(null); for (const fieldNode of parentAstNode?.fields ?? []) { astNodeMap[fieldNode.name.value] = fieldNode; } const resultFieldMap = Object.create(null); for (const fieldName of Object.keys(fieldMap)) { const field = { ...fieldMap[fieldName], name: fieldName, astNode: astNodeMap[fieldName], }; invariant( !field.hasOwnProperty('resolve'), `${config.name}.${fieldName} field has a resolve property, but ` + 'Input Types cannot define resolvers.' ); resultFieldMap[fieldName] = field; } return resultFieldMap; } export function convertInputFieldMapToConfig( fieldMap: Thunk<GraphQLInputFieldMap>, sc: SchemaComposer<any> ): InputTypeComposerFieldConfigMap { const fields = {} as InputTypeComposerFieldConfigMap; const isThunk = isFunction(fieldMap); const _fields: any = isThunk ? (fieldMap as any)(sc) : fieldMap; Object.keys(_fields).forEach((n) => { const { name, isDeprecated, ...fc } = _fields[n]; fields[n] = { ...fc, type: isThunk ? new ThunkComposer( () => sc.typeMapper.convertInputTypeDefinition(fc.type || _fields[n]) as any ) : sc.typeMapper.convertInputTypeDefinition(fc.type || _fields[n]), directives: sc.typeMapper.parseDirectives(fc?.astNode?.directives), }; }); return fields; } export function convertObjectTypeArrayAsThunk( types: Thunk< ReadonlyArray< | GraphQLObjectType | ObjectTypeComposerDefinition<any, any> | ObjectTypeComposerThunked<any, any> > >, sc: SchemaComposer<any> ): Array<ObjectTypeComposerThunked<any, any>> { const isThunk = isFunction(types); const t: any = isThunk ? (types as any)(sc) : types; if (!Array.isArray(t)) return []; return t.map((type) => { if (type instanceof ObjectTypeComposer || type instanceof ThunkComposer) { return type; } const tc = sc.typeMapper.convertOutputTypeDefinition(type); if (!tc && isThunk) { return new ThunkComposer( () => sc.typeMapper.convertOutputTypeDefinition(type) as any, getComposeTypeName(type, sc) ); } if (!(tc instanceof ObjectTypeComposer) && !(tc instanceof ThunkComposer)) { throw new Error(`Should be provided ObjectType but received ${inspect(type)}`); } return tc; }); } export function convertInterfaceArrayAsThunk( types: Thunk< ReadonlyArray< | InterfaceTypeComposerDefinition<any, any> | Readonly<GraphQLInterfaceType> | Readonly<InterfaceTypeComposerThunked<any, any>> > >, sc: SchemaComposer<any> ): Array<InterfaceTypeComposerThunked<any, any>> { const isThunk = isFunction(types); const t: any = isThunk ? (types as any)(sc) : types; if (!Array.isArray(t)) return []; return t.map((type) => { if (type instanceof InterfaceTypeComposer || type instanceof ThunkComposer) { return type; } return isThunk ? new ThunkComposer( () => sc.typeMapper.convertInterfaceTypeDefinition(type) as any, getComposeTypeName(type, sc) ) : sc.typeMapper.convertInterfaceTypeDefinition(type); }); }
the_stack
import { AfterContentChecked, ChangeDetectorRef, Component, Input, OnInit, ViewEncapsulation } from '@angular/core'; import { ListPropertyConfig } from '../list-property.component'; import { COMMA, ENTER } from '@angular/cdk/keycodes'; import { MatChipInputEvent } from '@angular/material/chips'; import { FormControl, Validators } from '@angular/forms'; import { MatOptionSelectionChange } from '@angular/material/core'; import { MatDialog } from '@angular/material/dialog'; import { RestApiConnectorService } from 'src/app/services/connectors/rest-api/rest-api-connector.service'; import { SelectionModel } from '@angular/cdk/collections'; import { Tactic } from 'src/app/classes/stix/tactic'; import { StixObject } from 'src/app/classes/stix/stix-object'; import { AddDialogComponent } from 'src/app/components/add-dialog/add-dialog.component'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-list-edit', templateUrl: './list-edit.component.html', styleUrls: ['./list-edit.component.scss'], encapsulation: ViewEncapsulation.None }) export class ListEditComponent implements OnInit, AfterContentChecked { @Input() public config: ListPropertyConfig; // allowed values (editType: 'select') public allAllowedValues: any; public selectControl: FormControl; public disabledTooltip: string = "a valid domain must be selected first"; public dataLoaded: boolean = false; // prevent async issues private sub: Subscription = new Subscription(); public fieldToStix = { "platforms": "x_mitre_platforms", "tactic_type": "x_mitre_tactic_type", "impact_type": "x_mitre_impact_type", "effective_permissions": "x_mitre_effective_permissions", "permissions_required": "x_mitre_permissions_required", "collection_layers": "x_mitre_collection_layers", "data_sources": "x_mitre_data_sources" } public domains = [ "enterprise-attack", "mobile-attack", "ics-attack" ] // selection model (editType: 'stixList') public select: SelectionModel<string>; public type: string; public allObjects: StixObject[] = []; // any value (editType: 'any') public inputControl: FormControl; readonly separatorKeysCodes: number[] = [ENTER, COMMA]; constructor(public dialog: MatDialog, private restAPIConnectorService: RestApiConnectorService, private ref: ChangeDetectorRef) { } ngOnInit(): void { this.selectControl = new FormControl({value: this.config.object[this.config.field], disabled: this.config.disabled ? this.config.disabled : false}); this.inputControl = new FormControl(null, this.config.required ? [Validators.required] : undefined); if (this.config.field == 'platforms' || this.config.field == 'tactic_type' || this.config.field == 'permissions_required' || this.config.field == 'effective_permissions' || this.config.field == 'impact_type' || this.config.field == 'domains' || this.config.field == 'collection_layers' || this.config.field == 'data_sources') { if (!this.dataLoaded) { let data$ = this.restAPIConnectorService.getAllAllowedValues(); this.sub = data$.subscribe({ next: (data) => { let stixObject = this.config.object as StixObject; this.allAllowedValues = data.find(obj => { return obj.objectType == stixObject.attackType; }); this.dataLoaded = true; }, complete: () => { this.sub.unsubscribe(); } }); } } else if (this.config.field == 'defense_bypassed') { } //any else if (this.config.field == 'system_requirements') { } //any else if (this.config.field == 'contributors') { } //any else if (this.config.field == 'tactics') { this.type = 'tactic'; let subscription = this.restAPIConnectorService.getAllTactics().subscribe({ next: (tactics) => { this.allObjects = tactics.data; // retrieve currently selected tactics let object = this.config.object as any; let selectedTactics = this.shortnameToTactic(object.domains); let selectedTacticIDs = selectedTactics.map(tactic => tactic.stixID); // set up domain & tactic tracking this.domainState = []; this.tacticState = []; object.domains.forEach(domain => this.domainState.push(domain)); selectedTactics.forEach(tactic => this.tacticState.push(tactic)); // set selection model with initial values this.select = new SelectionModel<string>(true, selectedTacticIDs); this.dataLoaded = true; }, complete: () => { subscription.unsubscribe(); } }) } } ngAfterContentChecked() { this.ref.detectChanges(); } /** Retrieves a list of selected tactics */ private shortnameToTactic(domains: string[]): Tactic[] { let allObjects = this.allObjects as Tactic[]; let tactics = this.config.object[this.config.field].map(shortname => { let tactic = allObjects.find(tactic => { return tactic.shortname == shortname && this.tacticInDomain(tactic, domains) }); return tactic; }) return tactics; } /** Retrieves a list of selected tactic shortnames */ private stixIDToShortname(tacticID: string): string[] { let allObjects = this.allObjects as Tactic[]; let tactic = allObjects.find(object => object.stixID == tacticID) return [tactic.shortname, tactic.domains[0]]; } /** Update current stix-list selection on domain change */ private domainState: string[]; private tacticState: Tactic[]; public selectedValues(): string[] { if (!this.dataLoaded) return null; let isEqual = function(arr1:string[], arr2:string[]) { return (arr1.length == arr2.length) && arr1.every(function(element, index) { return element === arr2[index]; }); } if (this.config.field == 'tactics') { let object = this.config.object as Tactic; if (!isEqual(this.domainState, object.domains)) { // get selected tactics let selectedTactics = this.tacticState; if (object.domains.length < this.domainState.length) { // a domain was removed // filter selected tactics with updated domain selection selectedTactics = selectedTactics.filter(tactic => this.tacticInDomain(tactic)); let selectedTacticIDs = selectedTactics.map(tactic => tactic.stixID); let tacticShortnames = selectedTacticIDs.map(id => this.stixIDToShortname(id)); // udpate object & selection model this.config.object[this.config.field] = tacticShortnames; this.select.clear(); selectedTacticIDs.forEach(tactic=>this.select.select(tactic)); } // reset domain & tactic selection state with a copy of current state this.domainState = []; this.tacticState = []; object.domains.forEach(domain => this.domainState.push(domain)); selectedTactics.forEach(tactic => this.tacticState.push(tactic)); } } return this.config.object[this.config.field]; } /** Get allowed values for this field */ public getAllowedValues(): string[] { if (this.config.field == 'domains') return this.domains; if (!this.dataLoaded) { this.selectControl.disable(); return null; }; // filter values let values: string[] = []; let property = this.allAllowedValues.properties.find(p => {return p.propertyName == this.fieldToStix[this.config.field]}); if (!property) { // property not found this.selectControl.disable(); return null; } if ("domains" in this.config.object) { let object = this.config.object as any; property.domains.forEach(domain => { if (object.domains.includes(domain.domainName)) { values = values.concat(domain.allowedValues); } }) } else { // domains not specified on object property.domains.forEach(domain => { values = values.concat(domain.allowedValues); }); } // check for existing data if (this.selectControl.value) { for (let value of this.selectControl.value) { if (!values.includes(value)) values.push(value); } } if (!values.length) { // disable field and reset selection this.selectControl.disable(); this.selectControl.reset(); this.config.object[this.config.field] = []; } else { this.selectControl.enable(); // re-enable field } return values; } /** Add value to object property list */ public add(event: MatChipInputEvent): void { if (event.value && event.value.trim()) { this.config.object[this.config.field].push(event.value.trim()); this.inputControl.setValue(this.config.object[this.config.field]); } if (event.input) { event.input.value = ''; // reset input value } } /** Remove value from object property list */ public remove(value: string): void { let i = this.config.object[this.config.field].indexOf(value); if (i >= 0) { this.config.object[this.config.field].splice(i, 1); } this.inputControl.setValue(this.config.object[this.config.field]) } /** Remove selection from via chip cancel button */ public removeSelection(value: string): void { let values = this.selectControl.value as string[]; let i = values.indexOf(value); if (i >= 0) { values.splice(i, 1); } this.selectControl.setValue([]); // reset selection this.selectControl.setValue(values); this.remove(value); // remove value from object property } /** Add or remove selection from object property list via select-list */ public change(event: MatOptionSelectionChange): void { if (event.isUserInput) { if (event.source.selected) this.config.object[this.config.field].push(event.source.value); else this.remove(event.source.value); } } /** Check if the given tactic is in the same domain as this object */ private tacticInDomain(tactic: Tactic, domains?: string[]) { let object = this.config.object as Tactic; let checkDomains = domains ? domains : object.domains; for (let domain of tactic.domains) { if (checkDomains.includes(domain)) return true; } } /** Open stix list selection window */ public openStixList() { // filter tactic objects by domain let tactics = this.allObjects as Tactic[]; let selectableObjects = tactics.filter(tactic => this.tacticInDomain(tactic)); let dialogRef = this.dialog.open(AddDialogComponent, { maxWidth: "70em", maxHeight: "70em", data: { selectableObjects: selectableObjects, select: this.select, type: this.type, buttonLabel: "OK" } }); let selectCopy = new SelectionModel(true, this.select.selected); let subscription = dialogRef.afterClosed().subscribe({ next: (result) => { if (result) { let tacticShortnames = this.select.selected.map(id => this.stixIDToShortname(id)); this.config.object[this.config.field] = tacticShortnames; // reset tactic selection state this.tacticState = []; let allObjects = this.allObjects as Tactic[]; let tactics = this.select.selected.map(tacticID => allObjects.find(tactic => tactic.stixID == tacticID)); tactics.forEach(tactic => this.tacticState.push(tactic)); } else { // user cancel this.select = selectCopy; // reset selection } }, complete: () => { subscription.unsubscribe(); } }); } }
the_stack
import * as React from "react" import * as moment from "moment" import { OrderProps, amountOfAsset, amountOfAssetPlusFees } from "./market" import { monsterImageSrc } from "../monsters/monsters" import { State, GlobalConfig, NOTIFICATION_SUCCESS, pushNotification, NOTIFICATION_ERROR, doLoadMyMonsters, } from "../../store" import { connect } from "react-redux" import { getEosAccount } from "../../utils/scatter" import { trxClaimPetMarket, trxRemoveOrderMarket, MONSTERS_ACCOUNT, trxTokenTransfer, } from "../../utils/eos" import { Link } from "react-router-dom" import NewOrderModal from "./NewOrderModal" interface Props { order: OrderProps eosAccount: string globalConfig: GlobalConfig requestUpdate?: any dispatchPushNotification: any dispatchDoLoadMyMonsters: any scatter: any selected?: boolean hideLink?: boolean hideActions?: boolean hideProfile?: boolean customActions?: MonsterAction[] } export interface MonsterAction { label: string action: any } interface ReactState { showNewOrderModal: boolean } class OrderCard extends React.Component<Props, ReactState> { public state = { showNewOrderModal: false, } public render() { const { order, selected, dispatchDoLoadMyMonsters, requestUpdate, hideProfile, } = this.props const monster = order.monster const { showNewOrderModal } = this.state const selectedClass = selected ? "monster-selected" : "" const refetchMonstersAndOrders = () => { setTimeout(() => dispatchDoLoadMyMonsters(), 500) } const newOrderClosure = (doRefetch: boolean) => { this.setState({ showNewOrderModal: false }) if (doRefetch) { refetchMonstersAndOrders() if (requestUpdate) { requestUpdate() } } } return ( <div className="column is-one-third"> <div className={`card monster-card ${selectedClass}`}> <div className="card-content"> <div className="columns is-mobile"> {!hideProfile && ( <div className="column">{this.renderMonster()}</div> )} <div className={`column ${hideProfile ? "" : "is-three-fifths"}`}> {this.renderHeader()} {this.renderOrderData()} </div> </div> </div> {this.renderFooter()} </div> {showNewOrderModal && ( <NewOrderModal closeModal={newOrderClosure} initialMonster={monster} initialName={order.newOwner} initialAmount={amountOfAsset(order.value)} /> )} </div> ) } private renderMonster() { const { order } = this.props const monster = order.monster const figureClass = `image monster-image ${ monster.deathAt ? "grayscale" : "" }` const monsterImage = monsterImageSrc(monster.type) return ( <div className="card-image"> <figure className={figureClass}> <img alt={monster.name} src={monsterImage} /> </figure> </div> ) } private renderHeader() { const { order, hideLink, hideProfile } = this.props const monster = order.monster // const createdAt = moment(monster.createdAt) // const createdAtText = createdAt.format("MMMM, D YYYY @ h:mm a") // const createdAtIso = createdAt.toLocaleString() // const deathAt = moment(monster.deathAt) // const deathAtText = deathAt.format("MMMM, D YYYY @ h:mm a") // const deathAtIso = deathAt.toLocaleString() const aliveDuration = (monster.deathAt ? monster.deathAt : Date.now()) - monster.createdAt const aliveDurationText = moment.duration(aliveDuration).humanize() const headerContent = !hideProfile && ( <div className={`monster-card-title ${monster.deathAt ? "dead" : ""}`}> <div> <div className="monster-name">{monster.name}</div> <div className="monster-status"> {monster.deathAt ? ( <p>Stayed alive for {aliveDurationText}</p> ) : ( <p>Has been alive for {aliveDurationText}</p> )} </div> </div> <div className="monster-id">#{monster.id}</div> <br /> </div> ) return ( <div className="monster-card-header"> <span>Order #{order.id}</span> <br /> {!hideLink ? ( <Link to={`/monster/${monster.id}`} className="monster-header-link"> {headerContent} </Link> ) : ( headerContent )} </div> ) } private renderFooter() { const { order, customActions, eosAccount, globalConfig } = this.props let actions: MonsterAction[] = [] const isReal = order.monster.name.length > 0 // not deleted if (order.user === eosAccount) { if (isReal) { actions.push({ action: this.requestUpdateOrder, label: "Update Order" }) } actions.push({ action: this.requestDeleteOrder, label: "Delete Order" }) } if ( eosAccount && (!order.newOwner || order.newOwner === eosAccount) && order.user !== eosAccount && isReal ) { const amount = amountOfAssetPlusFees(order.value, globalConfig.market_fee) actions.push({ action: this.requestClaimMonster, label: amount > 0 ? `Buy for ${amount.toLocaleString()} EOS` : `Claim for FREE`, }) } if (customActions) { actions = actions.concat(customActions) } return ( <footer className="card-footer"> {actions.map((action, index) => ( <a key={index} className="card-footer-item" onClick={action.action}> {action.label} </a> ))} </footer> ) } private renderOrderData = () => { const { order, globalConfig } = this.props const { monster } = order const transferEnds = moment(order.transferEndsAt) const transferEndsText = transferEnds.format("MMMM, D YYYY @ h:mm a") const transferEndsIso = transferEnds.toLocaleString() const amount = amountOfAsset(order.value) const fees = ((amount * globalConfig.market_fee) / 10000).toLocaleString( undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }, ) const priceTxt = amount >= 1000000 ? amount.toLocaleString() : amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2, }) return ( <div className="card-content"> <span className="is-6">current owner {monster.owner}</span> <div className="is-6">order by {order.user}</div> {order.newOwner && ( <div className="is-6">ordered to {order.newOwner}</div> )} {order.transferEndsAt > 0 && ( <div className="is-6"> <time dateTime={transferEndsIso}> re-transferable from {transferEndsText} </time> </div> )} {amount > 0 && ( <div className="is-6 price"> <hr /> Price: {priceTxt} EOS <br /> Fees: {fees} EOS </div> )} </div> ) } private requestUpdateOrder = () => { this.setState({ showNewOrderModal: true }) } private requestDeleteOrder = () => { const { scatter, order, requestUpdate, dispatchPushNotification, } = this.props const monster = order.monster trxRemoveOrderMarket(scatter, monster.id) .then((res: any) => { console.info( `Order for monster #${monster.id} was deleted successfully`, res, ) dispatchPushNotification( `Order for ${monster.name} was deleted successfully`, NOTIFICATION_SUCCESS, ) if (requestUpdate) { requestUpdate() } }) .catch((err: any) => { dispatchPushNotification( `Fail to order for ${monster.name} ${err.eosError}`, NOTIFICATION_ERROR, ) }) } private requestClaimMonster = () => { const { scatter, order, requestUpdate, dispatchPushNotification, globalConfig, } = this.props const monster = order.monster const amount = amountOfAssetPlusFees(order.value, globalConfig.market_fee) if (amount > 0) { const orderAmount = `${amount.toFixed(4)} EOS` trxTokenTransfer(scatter, MONSTERS_ACCOUNT, orderAmount, "mtt" + order.id) .then((res: any) => { console.info(`Pet ${monster.id} was claimed successfully`, res) dispatchPushNotification( `Pet ${monster.name} was claimed successfully`, NOTIFICATION_SUCCESS, ) if (requestUpdate) { requestUpdate() } }) .catch((err: any) => { dispatchPushNotification( `Fail to claim ${monster.name} ${err.eosError}`, NOTIFICATION_ERROR, ) }) } else { trxClaimPetMarket(scatter, monster.id, order.user) .then((res: any) => { console.info(`Pet ${monster.id} was claimed successfully`, res) dispatchPushNotification( `Pet ${monster.name} was claimed successfully`, NOTIFICATION_SUCCESS, ) if (requestUpdate) { requestUpdate() } }) .catch((err: any) => { dispatchPushNotification( `Fail to claim ${monster.name} ${err.eosError}`, NOTIFICATION_ERROR, ) }) } } } const mapStateToProps = (state: State) => { const eosAccount = getEosAccount(state.identity) return { eosAccount, globalConfig: state.globalConfig, scatter: state.scatter, } } const mapDispatchToProps = { dispatchPushNotification: pushNotification, dispatchDoLoadMyMonsters: doLoadMyMonsters, } export default connect( mapStateToProps, mapDispatchToProps, )(OrderCard)
the_stack
import Ethash, { Solution, Miner as EthashMiner } from '@ethereumjs/ethash' import { BlockHeader } from '@ethereumjs/block' import { BN } from 'ethereumjs-util' import { ConsensusType, Hardfork } from '@ethereumjs/common' import { Event } from '../types' import { Config } from '../config' import { FullSynchronizer } from '../sync' const level = require('level-mem') export interface MinerOptions { /* Config */ config: Config /* FullSynchronizer */ synchronizer: FullSynchronizer } /** * @module miner */ /** * Implements Ethereum block creation and mining. * @memberof module:miner */ export class Miner { private DEFAULT_PERIOD = 10 private _nextAssemblyTimeoutId: NodeJS.Timeout | undefined /* global NodeJS */ private _boundChainUpdatedHandler: (() => void) | undefined private config: Config private synchronizer: FullSynchronizer private assembling: boolean private period: number private ethash: Ethash | undefined private ethashMiner: EthashMiner | undefined private nextSolution: Solution | undefined public running: boolean /** * Create miner * @param options constructor parameters */ constructor(options: MinerOptions) { this.config = options.config this.synchronizer = options.synchronizer this.running = false this.assembling = false this.period = (this.config.chainCommon.consensusConfig().period ?? this.DEFAULT_PERIOD) * 1000 // defined in ms for setTimeout use if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfWork) { const cacheDB = level() this.ethash = new Ethash(cacheDB) } } /** * Convenience alias to return the latest block in the blockchain */ private latestBlockHeader(): BlockHeader { return (this.synchronizer as any).chain.headers.latest } /** * Sets the timeout for the next block assembly */ private async queueNextAssembly(timeout?: number) { if (this._nextAssemblyTimeoutId) { clearTimeout(this._nextAssemblyTimeoutId) } if (!this.running) { return } if (this.config.chainCommon.gteHardfork(Hardfork.Merge)) { this.config.logger.info('Miner: reached merge hardfork - stopping') this.stop() return } timeout = timeout ?? this.period if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfAuthority) { // EIP-225 spec: If the signer is out-of-turn, // delay signing by rand(SIGNER_COUNT * 500ms) const [signerAddress] = this.config.accounts[0] const { blockchain } = (this.synchronizer as any).chain const inTurn = await blockchain.cliqueSignerInTurn(signerAddress) if (!inTurn) { const signerCount = blockchain.cliqueActiveSigners().length timeout += Math.random() * signerCount * 500 } } this._nextAssemblyTimeoutId = setTimeout(this.assembleBlock.bind(this), timeout) if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfWork) { // If PoW, find next solution while waiting for next block assembly to start void this.findNextSolution() } } /** * Finds the next PoW solution. */ private async findNextSolution() { if (!this.ethash) { return } this.config.logger.info('Miner: Finding next PoW solution 🔨') const header = this.latestBlockHeader() this.ethashMiner = this.ethash.getMiner(header) const solution = await this.ethashMiner.iterate(-1) if (!header.hash().equals(this.latestBlockHeader().hash())) { // New block was inserted while iterating so we will discard solution return } this.nextSolution = solution this.config.logger.info('Miner: Found PoW solution 🔨') return solution } /** * Sets the next block assembly to latestBlock.timestamp + period */ private async chainUpdated() { this.ethashMiner?.stop() const latestBlockHeader = this.latestBlockHeader() const target = latestBlockHeader.timestamp.muln(1000).addn(this.period).sub(new BN(Date.now())) const timeout = BN.max(new BN(0), target).toNumber() this.config.logger.debug( `Miner: Chain updated with block ${ latestBlockHeader.number }. Queuing next block assembly in ${Math.round(timeout / 1000)}s` ) await this.queueNextAssembly(timeout) } /** * Start miner */ start(): boolean { if (!this.config.mine || this.running) { return false } this.running = true this._boundChainUpdatedHandler = this.chainUpdated.bind(this) this.config.events.on(Event.CHAIN_UPDATED, this._boundChainUpdatedHandler) this.config.logger.info(`Miner started. Assembling next block in ${this.period / 1000}s`) void this.queueNextAssembly() // void operator satisfies eslint rule for no-floating-promises return true } /** * Assembles a block from txs in the TxPool and adds it to the chain. * If a new block is received while assembling it will abort. */ async assembleBlock() { if (this.assembling) { return } this.assembling = true // Abort if a new block is received while assembling this block // eslint-disable-next-line prefer-const let _boundSetInterruptHandler: () => void let interrupt = false const setInterrupt = () => { interrupt = true this.assembling = false this.config.events.removeListener(Event.CHAIN_UPDATED, _boundSetInterruptHandler) } _boundSetInterruptHandler = setInterrupt.bind(this) this.config.events.once(Event.CHAIN_UPDATED, _boundSetInterruptHandler) const parentBlock = (this.synchronizer as any).chain.blocks.latest const number = parentBlock.header.number.addn(1) let { gasLimit } = parentBlock.header if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfAuthority) { // Abort if we have too recently signed const cliqueSigner = this.config.accounts[0][1] const header = BlockHeader.fromHeaderData( { number }, { common: this.config.chainCommon, cliqueSigner } ) if ((this.synchronizer as any).chain.blockchain.cliqueCheckRecentlySigned(header)) { this.config.logger.info(`Miner: We have too recently signed, waiting for next block`) this.assembling = false return } } if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfWork) { while (!this.nextSolution) { this.config.logger.info(`Miner: Waiting to find next PoW solution 🔨`) await new Promise((r) => setTimeout(r, 1000)) } } // Use a copy of the vm to not modify the existing state. // The state will be updated when the newly assembled block // is inserted into the canonical chain. const vmCopy = this.synchronizer.execution.vm.copy() // Set the state root to ensure the resulting state // is based on the parent block's state await vmCopy.stateManager.setStateRoot(parentBlock.header.stateRoot) let difficulty let cliqueSigner let inTurn if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfAuthority) { const [signerAddress, signerPrivKey] = this.config.accounts[0] cliqueSigner = signerPrivKey // Determine if signer is INTURN (2) or NOTURN (1) inTurn = await vmCopy.blockchain.cliqueSignerInTurn(signerAddress) difficulty = inTurn ? 2 : 1 } let baseFeePerGas const londonHardforkBlock = this.config.chainCommon.hardforkBlockBN(Hardfork.London) const isInitialEIP1559Block = londonHardforkBlock && number.eq(londonHardforkBlock) if (isInitialEIP1559Block) { // Get baseFeePerGas from `paramByEIP` since 1559 not currently active on common baseFeePerGas = new BN( this.config.chainCommon.paramByEIP('gasConfig', 'initialBaseFee', 1559) ) // Set initial EIP1559 block gas limit to 2x parent gas limit per logic in `block.validateGasLimit` gasLimit = gasLimit.muln(2) } else if (this.config.chainCommon.isActivatedEIP(1559)) { baseFeePerGas = parentBlock.header.calcNextBaseFee() } let calcDifficultyFromHeader let coinbase if (this.config.chainCommon.consensusType() === ConsensusType.ProofOfWork) { calcDifficultyFromHeader = parentBlock.header coinbase = this.config.minerCoinbase ?? this.config.accounts[0][0] } const blockBuilder = await vmCopy.buildBlock({ parentBlock, headerData: { number, difficulty, gasLimit, baseFeePerGas, coinbase, }, blockOpts: { cliqueSigner, hardforkByBlockNumber: true, calcDifficultyFromHeader, }, }) const txs = await this.synchronizer.txPool.txsByPriceAndNonce( vmCopy.stateManager, baseFeePerGas ) this.config.logger.info( `Miner: Assembling block from ${txs.length} eligible txs ${ baseFeePerGas ? `(baseFee: ${baseFeePerGas})` : '' }` ) let index = 0 let blockFull = false while (index < txs.length && !blockFull && !interrupt) { try { await blockBuilder.addTransaction(txs[index]) } catch (error: any) { if (error.message === 'tx has a higher gas limit than the remaining gas in the block') { if (blockBuilder.gasUsed.gt(gasLimit.subn(21000))) { // If block has less than 21000 gas remaining, consider it full blockFull = true this.config.logger.info( `Miner: Assembled block full (gasLeft: ${gasLimit.sub(blockBuilder.gasUsed)})` ) } } else { // If there is an error adding a tx, it will be skipped const hash = '0x' + txs[index].hash().toString('hex') this.config.logger.debug( `Skipping tx ${hash}, error encountered when trying to add tx:\n${error}` ) } } index++ } if (interrupt) return // Build block, sealing it const block = await blockBuilder.build(this.nextSolution) this.config.logger.info( `Miner: Sealed block with ${block.transactions.length} txs ${ this.config.chainCommon.consensusType() === ConsensusType.ProofOfWork ? `(difficulty: ${block.header.difficulty})` : `(${inTurn ? 'in turn' : 'not in turn'})` }` ) this.assembling = false if (interrupt) return // Put block in blockchain await this.synchronizer.handleNewBlock(block) // Remove included txs from TxPool this.synchronizer.txPool.removeNewBlockTxs([block]) this.config.events.removeListener(Event.CHAIN_UPDATED, _boundSetInterruptHandler) } /** * Stop miner execution */ stop(): boolean { if (!this.running) { return false } this.config.events.removeListener(Event.CHAIN_UPDATED, this._boundChainUpdatedHandler!) if (this._nextAssemblyTimeoutId) { clearTimeout(this._nextAssemblyTimeoutId) } this.running = false this.config.logger.info('Miner stopped.') return true } }
the_stack
import { OperationParameter, OperationURLParameter, OperationQueryParameter } from "@azure/core-client"; import { Lab as LabMapper, LabFragment as LabFragmentMapper, LabVirtualMachineCreationParameter as LabVirtualMachineCreationParameterMapper, ExportResourceUsageParameters as ExportResourceUsageParametersMapper, GenerateUploadUriParameter as GenerateUploadUriParameterMapper, ImportLabVirtualMachineRequest as ImportLabVirtualMachineRequestMapper, Schedule as ScheduleMapper, ScheduleFragment as ScheduleFragmentMapper, RetargetScheduleProperties as RetargetSchedulePropertiesMapper, ArtifactSource as ArtifactSourceMapper, ArtifactSourceFragment as ArtifactSourceFragmentMapper, GenerateArmTemplateRequest as GenerateArmTemplateRequestMapper, LabCost as LabCostMapper, CustomImage as CustomImageMapper, CustomImageFragment as CustomImageFragmentMapper, Formula as FormulaMapper, FormulaFragment as FormulaFragmentMapper, NotificationChannel as NotificationChannelMapper, NotificationChannelFragment as NotificationChannelFragmentMapper, NotifyParameters as NotifyParametersMapper, EvaluatePoliciesRequest as EvaluatePoliciesRequestMapper, Policy as PolicyMapper, PolicyFragment as PolicyFragmentMapper, ServiceRunner as ServiceRunnerMapper, User as UserMapper, UserFragment as UserFragmentMapper, Disk as DiskMapper, DiskFragment as DiskFragmentMapper, AttachDiskProperties as AttachDiskPropertiesMapper, DetachDiskProperties as DetachDiskPropertiesMapper, DtlEnvironment as DtlEnvironmentMapper, DtlEnvironmentFragment as DtlEnvironmentFragmentMapper, Secret as SecretMapper, SecretFragment as SecretFragmentMapper, ServiceFabric as ServiceFabricMapper, ServiceFabricFragment as ServiceFabricFragmentMapper, LabVirtualMachine as LabVirtualMachineMapper, LabVirtualMachineFragment as LabVirtualMachineFragmentMapper, DataDiskProperties as DataDiskPropertiesMapper, ApplyArtifactsRequest as ApplyArtifactsRequestMapper, DetachDataDiskProperties as DetachDataDiskPropertiesMapper, ResizeLabVirtualMachineProperties as ResizeLabVirtualMachinePropertiesMapper, VirtualNetwork as VirtualNetworkMapper, VirtualNetworkFragment as VirtualNetworkFragmentMapper } from "../models/mappers"; export const accept: OperationParameter = { parameterPath: "accept", mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; export const $host: OperationURLParameter = { parameterPath: "$host", mapper: { serializedName: "$host", required: true, type: { name: "String" } }, skipEncoding: true }; export const apiVersion: OperationQueryParameter = { parameterPath: "apiVersion", mapper: { defaultValue: "2018-09-15", isConstant: true, serializedName: "api-version", type: { name: "String" } } }; export const nextLink: OperationURLParameter = { parameterPath: "nextLink", mapper: { serializedName: "nextLink", required: true, type: { name: "String" } }, skipEncoding: true }; export const subscriptionId: OperationURLParameter = { parameterPath: "subscriptionId", mapper: { serializedName: "subscriptionId", required: true, type: { name: "String" } } }; export const expand: OperationQueryParameter = { parameterPath: ["options", "expand"], mapper: { serializedName: "$expand", type: { name: "String" } } }; export const filter: OperationQueryParameter = { parameterPath: ["options", "filter"], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const top: OperationQueryParameter = { parameterPath: ["options", "top"], mapper: { serializedName: "$top", type: { name: "Number" } } }; export const orderby: OperationQueryParameter = { parameterPath: ["options", "orderby"], mapper: { serializedName: "$orderby", type: { name: "String" } } }; export const resourceGroupName: OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { serializedName: "resourceGroupName", required: true, type: { name: "String" } } }; export const name: OperationURLParameter = { parameterPath: "name", mapper: { serializedName: "name", required: true, type: { name: "String" } } }; export const contentType: OperationParameter = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; export const lab: OperationParameter = { parameterPath: "lab", mapper: LabMapper }; export const lab1: OperationParameter = { parameterPath: "lab", mapper: LabFragmentMapper }; export const labVirtualMachineCreationParameter: OperationParameter = { parameterPath: "labVirtualMachineCreationParameter", mapper: LabVirtualMachineCreationParameterMapper }; export const exportResourceUsageParameters: OperationParameter = { parameterPath: "exportResourceUsageParameters", mapper: ExportResourceUsageParametersMapper }; export const generateUploadUriParameter: OperationParameter = { parameterPath: "generateUploadUriParameter", mapper: GenerateUploadUriParameterMapper }; export const importLabVirtualMachineRequest: OperationParameter = { parameterPath: "importLabVirtualMachineRequest", mapper: ImportLabVirtualMachineRequestMapper }; export const locationName: OperationURLParameter = { parameterPath: "locationName", mapper: { serializedName: "locationName", required: true, type: { name: "String" } } }; export const schedule: OperationParameter = { parameterPath: "schedule", mapper: ScheduleMapper }; export const schedule1: OperationParameter = { parameterPath: "schedule", mapper: ScheduleFragmentMapper }; export const retargetScheduleProperties: OperationParameter = { parameterPath: "retargetScheduleProperties", mapper: RetargetSchedulePropertiesMapper }; export const labName: OperationURLParameter = { parameterPath: "labName", mapper: { serializedName: "labName", required: true, type: { name: "String" } } }; export const artifactSource: OperationParameter = { parameterPath: "artifactSource", mapper: ArtifactSourceMapper }; export const artifactSource1: OperationParameter = { parameterPath: "artifactSource", mapper: ArtifactSourceFragmentMapper }; export const artifactSourceName: OperationURLParameter = { parameterPath: "artifactSourceName", mapper: { serializedName: "artifactSourceName", required: true, type: { name: "String" } } }; export const generateArmTemplateRequest: OperationParameter = { parameterPath: "generateArmTemplateRequest", mapper: GenerateArmTemplateRequestMapper }; export const labCost: OperationParameter = { parameterPath: "labCost", mapper: LabCostMapper }; export const customImage: OperationParameter = { parameterPath: "customImage", mapper: CustomImageMapper }; export const customImage1: OperationParameter = { parameterPath: "customImage", mapper: CustomImageFragmentMapper }; export const formula: OperationParameter = { parameterPath: "formula", mapper: FormulaMapper }; export const formula1: OperationParameter = { parameterPath: "formula", mapper: FormulaFragmentMapper }; export const notificationChannel: OperationParameter = { parameterPath: "notificationChannel", mapper: NotificationChannelMapper }; export const notificationChannel1: OperationParameter = { parameterPath: "notificationChannel", mapper: NotificationChannelFragmentMapper }; export const notifyParameters: OperationParameter = { parameterPath: "notifyParameters", mapper: NotifyParametersMapper }; export const evaluatePoliciesRequest: OperationParameter = { parameterPath: "evaluatePoliciesRequest", mapper: EvaluatePoliciesRequestMapper }; export const policySetName: OperationURLParameter = { parameterPath: "policySetName", mapper: { serializedName: "policySetName", required: true, type: { name: "String" } } }; export const policy: OperationParameter = { parameterPath: "policy", mapper: PolicyMapper }; export const policy1: OperationParameter = { parameterPath: "policy", mapper: PolicyFragmentMapper }; export const serviceRunner: OperationParameter = { parameterPath: "serviceRunner", mapper: ServiceRunnerMapper }; export const user: OperationParameter = { parameterPath: "user", mapper: UserMapper }; export const user1: OperationParameter = { parameterPath: "user", mapper: UserFragmentMapper }; export const userName: OperationURLParameter = { parameterPath: "userName", mapper: { serializedName: "userName", required: true, type: { name: "String" } } }; export const disk: OperationParameter = { parameterPath: "disk", mapper: DiskMapper }; export const disk1: OperationParameter = { parameterPath: "disk", mapper: DiskFragmentMapper }; export const attachDiskProperties: OperationParameter = { parameterPath: "attachDiskProperties", mapper: AttachDiskPropertiesMapper }; export const detachDiskProperties: OperationParameter = { parameterPath: "detachDiskProperties", mapper: DetachDiskPropertiesMapper }; export const dtlEnvironment: OperationParameter = { parameterPath: "dtlEnvironment", mapper: DtlEnvironmentMapper }; export const dtlEnvironment1: OperationParameter = { parameterPath: "dtlEnvironment", mapper: DtlEnvironmentFragmentMapper }; export const secret: OperationParameter = { parameterPath: "secret", mapper: SecretMapper }; export const secret1: OperationParameter = { parameterPath: "secret", mapper: SecretFragmentMapper }; export const serviceFabric: OperationParameter = { parameterPath: "serviceFabric", mapper: ServiceFabricMapper }; export const serviceFabric1: OperationParameter = { parameterPath: "serviceFabric", mapper: ServiceFabricFragmentMapper }; export const serviceFabricName: OperationURLParameter = { parameterPath: "serviceFabricName", mapper: { serializedName: "serviceFabricName", required: true, type: { name: "String" } } }; export const labVirtualMachine: OperationParameter = { parameterPath: "labVirtualMachine", mapper: LabVirtualMachineMapper }; export const labVirtualMachine1: OperationParameter = { parameterPath: "labVirtualMachine", mapper: LabVirtualMachineFragmentMapper }; export const dataDiskProperties: OperationParameter = { parameterPath: "dataDiskProperties", mapper: DataDiskPropertiesMapper }; export const applyArtifactsRequest: OperationParameter = { parameterPath: "applyArtifactsRequest", mapper: ApplyArtifactsRequestMapper }; export const detachDataDiskProperties: OperationParameter = { parameterPath: "detachDataDiskProperties", mapper: DetachDataDiskPropertiesMapper }; export const resizeLabVirtualMachineProperties: OperationParameter = { parameterPath: "resizeLabVirtualMachineProperties", mapper: ResizeLabVirtualMachinePropertiesMapper }; export const virtualMachineName: OperationURLParameter = { parameterPath: "virtualMachineName", mapper: { serializedName: "virtualMachineName", required: true, type: { name: "String" } } }; export const virtualNetwork: OperationParameter = { parameterPath: "virtualNetwork", mapper: VirtualNetworkMapper }; export const virtualNetwork1: OperationParameter = { parameterPath: "virtualNetwork", mapper: VirtualNetworkFragmentMapper };
the_stack
import { triggerEvent, options, arrayForEach } from '@tko/utils' import { applyBindings, contextFor, dataFor } from '@tko/bind' import { observable, observableArray } from '@tko/observable' import { DataBindProvider } from '@tko/provider.databind' import { MultiProvider } from '@tko/provider.multi' import { VirtualProvider } from '@tko/provider.virtual' import {bindings as withBindings} from '../dist' import {bindings as coreBindings} from '@tko/binding.core' import {bindings as templateBindings} from '@tko/binding.template' import '@tko/utils/helpers/jasmine-13-helper' describe('Binding: With', function () { beforeEach(jasmine.prepareTestNode) beforeEach(function () { var provider = new MultiProvider({ providers: [new DataBindProvider(), new VirtualProvider()] }) options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) provider.bindingHandlers.set(withBindings) provider.bindingHandlers.set(templateBindings) }) it('Should remove descendant nodes from the document (and not bind them) if the value is falsy', function () { testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: someItem.nonExistentChildProp'></span></div>" expect(testNode.childNodes[0].childNodes.length).toEqual(1) applyBindings({ someItem: null }, testNode) expect(testNode.childNodes[0].childNodes.length).toEqual(0) }) it('Should leave descendant nodes in the document (and bind them in the context of the supplied value) if the value is truthy', function () { testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: existentChildProp'></span></div>" expect(testNode.childNodes.length).toEqual(1) applyBindings({ someItem: { existentChildProp: 'Child prop value' } }, testNode) expect(testNode.childNodes[0].childNodes.length).toEqual(1) expect(testNode.childNodes[0].childNodes[0]).toContainText('Child prop value') }) it('Should leave descendant nodes unchanged if the value is truthy', function () { var someItem = observable({ childProp: 'child prop value' }) testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: childProp'></span></div>" var originalNode = testNode.childNodes[0].childNodes[0] // Value is initially true, so nodes are retained applyBindings({ someItem: someItem }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('child prop value') expect(testNode.childNodes[0].childNodes[0]).toEqual(originalNode) }) it('Should toggle the presence and bindedness of descendant nodes according to the truthiness of the value, performing binding in the context of the value', function () { var someItem = observable(undefined) testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: occasionallyExistentChildProp'></span></div>" applyBindings({ someItem: someItem }, testNode) // First it's not there expect(testNode.childNodes[0].childNodes.length).toEqual(0) // Then it's there someItem({ occasionallyExistentChildProp: 'Child prop value' }) expect(testNode.childNodes[0].childNodes.length).toEqual(1) expect(testNode.childNodes[0].childNodes[0]).toContainText('Child prop value') // Then it's gone again someItem(null) expect(testNode.childNodes[0].childNodes.length).toEqual(0) }) it('Should reconstruct and bind descendants when the data item notifies about mutation', function () { var someItem = observable({ childProp: 'Hello' }) testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: childProp'></span></div>" applyBindings({ someItem: someItem }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('Hello') // Force "update" binding handler to fire, then check the DOM changed someItem().childProp = 'Goodbye' someItem.valueHasMutated() expect(testNode.childNodes[0].childNodes[0]).toContainText('Goodbye') }) it('Should not bind the same elements more than once even if the supplied value notifies a change', function () { var countedClicks = 0 var someItem = observable({ childProp: observable('Hello'), handleClick: function () { countedClicks++ } }) testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: childProp, click: handleClick'></span></div>" applyBindings({ someItem: someItem }, testNode) // Initial state is one subscriber, one click handler expect(testNode.childNodes[0].childNodes[0]).toContainText('Hello') expect(someItem().childProp.getSubscriptionsCount()).toEqual(1) triggerEvent(testNode.childNodes[0].childNodes[0], 'click') expect(countedClicks).toEqual(1) // Force "update" binding handler to fire, then check we still have one subscriber... someItem.valueHasMutated() expect(someItem().childProp.getSubscriptionsCount()).toEqual(1) // ... and one click handler countedClicks = 0 triggerEvent(testNode.childNodes[0].childNodes[0], 'click') expect(countedClicks).toEqual(1) }) it('Should be able to access parent binding context via $parent', function () { testNode.innerHTML = "<div data-bind='with: someItem'><span data-bind='text: $parent.parentProp'></span></div>" applyBindings({ someItem: { }, parentProp: 'Parent prop value' }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('Parent prop value') }) it('Should be able to access all parent binding contexts via $parents, and root context via $root', function () { testNode.innerHTML = "<div data-bind='with: topItem'>" + "<div data-bind='with: middleItem'>" + "<div data-bind='with: bottomItem'>" + "<span data-bind='text: name'></span>" + "<span data-bind='text: $parent.name'></span>" + "<span data-bind='text: $parents[1].name'></span>" + "<span data-bind='text: $parents[2].name'></span>" + "<span data-bind='text: $root.name'></span>" + '</div>' + '</div>' + '</div>' applyBindings({ name: 'outer', topItem: { name: 'top', middleItem: { name: 'middle', bottomItem: { name: 'bottom' } } } }, testNode) var finalContainer = testNode.childNodes[0].childNodes[0].childNodes[0] expect(finalContainer.childNodes[0]).toContainText('bottom') expect(finalContainer.childNodes[1]).toContainText('middle') expect(finalContainer.childNodes[2]).toContainText('top') expect(finalContainer.childNodes[3]).toContainText('outer') expect(finalContainer.childNodes[4]).toContainText('outer') // Also check that, when we later retrieve the binding contexts, we get consistent results expect(contextFor(testNode).$data.name).toEqual('outer') expect(contextFor(testNode.childNodes[0]).$data.name).toEqual('outer') expect(contextFor(testNode.childNodes[0].childNodes[0]).$data.name).toEqual('top') expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0]).$data.name).toEqual('middle') expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0].childNodes[0]).$data.name).toEqual('bottom') var firstSpan = testNode.childNodes[0].childNodes[0].childNodes[0].childNodes[0] expect(firstSpan.tagName).toEqual('SPAN') expect(contextFor(firstSpan).$data.name).toEqual('bottom') expect(contextFor(firstSpan).$root.name).toEqual('outer') expect(contextFor(firstSpan).$parents[1].name).toEqual('top') }) it('Should be able to access all parent bindings when using "as"', async function () { testNode.innerHTML = `<div data-bind='with: topItem'> <div data-bind="with: middleItem, as: 'middle'"> <div data-bind='with: middle.bottomItem'> <span data-bind='text: name'></span> <span data-bind='text: $parent.name'></span> <span data-bind='text: middle.name'></span> <span data-bind='text: $parents[1].name'></span> <span data-bind='text: $root.name'></span> </div> </div> </div>` applyBindings({ name: 'outer', topItem: { name: 'top', middleItem: { name: 'middle', bottomItem: { name: 'bottom' } } } }, testNode) const finalContainer = testNode.childNodes[0].children[0].children[0] // This differs from ko 3.x in that `with` does not create a child context // when using `as`. const [name, parentName, middleName, parent1Name, rootName] = finalContainer.children expect(name).toContainText('bottom') expect(parentName).toContainText('top') expect(middleName).toContainText('middle') expect(parent1Name).toContainText('outer') expect(rootName).toContainText('outer') expect(contextFor(name).parents.length).toEqual(2) }) it('Should not create a child context', function () { testNode.innerHTML = "<div data-bind='with: someItem, as: \"item\"'><span data-bind='text: item.childProp'></span></div>" var someItem = { childProp: 'Hello' } applyBindings({ someItem: someItem }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('Hello') expect(dataFor(testNode.childNodes[0].childNodes[0])).toEqual(dataFor(testNode)) }) it('Should provide access to observable value', function () { testNode.innerHTML = "<div data-bind='with: someItem, as: \"item\"'><input data-bind='value: item'/></div>" var someItem = observable('Hello') applyBindings({ someItem: someItem }, testNode) expect(testNode.childNodes[0].childNodes[0].value).toEqual('Hello') expect(dataFor(testNode.childNodes[0].childNodes[0])).toEqual(dataFor(testNode)) // Should update observable when input is changed testNode.childNodes[0].childNodes[0].value = 'Goodbye' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(someItem()).toEqual('Goodbye') // Should update the input when the observable changes someItem('Hello again') expect(testNode.childNodes[0].childNodes[0].value).toEqual('Hello again') }) it('Should not re-render the nodes when an observable value changes', function () { testNode.innerHTML = "<div data-bind='with: someItem, as: \"item\"'><span data-bind='text: item'></span></div>" var someItem = observable('first') applyBindings({ someItem }, testNode) expect(testNode.childNodes[0]).toContainText('first') var saveNode = testNode.childNodes[0].childNodes[0] someItem('second') expect(testNode.childNodes[0]).toContainText('second') expect(testNode.childNodes[0].childNodes[0]).toEqual(saveNode) }) it('Should remove nodes with an observable value become falsy', function () { var someItem = observable(undefined) testNode.innerHTML = "<div data-bind='with: someItem, as: \"item\"'><span data-bind='text: item().occasionallyExistentChildProp'></span></div>" applyBindings({ someItem: someItem }, testNode) // First it's not there expect(testNode.childNodes[0].childNodes.length).toEqual(0) // Then it's there someItem({ occasionallyExistentChildProp: 'Child prop value' }) expect(testNode.childNodes[0].childNodes.length).toEqual(1) expect(testNode.childNodes[0].childNodes[0]).toContainText('Child prop value') // Then it's gone again someItem(null) expect(testNode.childNodes[0].childNodes.length).toEqual(0) }) it('Should be able to define an "with" region using a containerless template', function () { var someitem = observable(undefined) testNode.innerHTML = 'hello <!-- ko with: someitem --><span data-bind="text: occasionallyexistentchildprop"></span><!-- /ko --> goodbye' applyBindings({ someitem: someitem }, testNode) // First it's not there expect(testNode).toContainHtml('hello <!-- ko with: someitem --><!-- /ko --> goodbye') // Then it's there someitem({ occasionallyexistentchildprop: 'child prop value' }) expect(testNode).toContainHtml('hello <!-- ko with: someitem --><span data-bind="text: occasionallyexistentchildprop">child prop value</span><!-- /ko --> goodbye') // Then it's gone again someitem(null) expect(testNode).toContainHtml('hello <!-- ko with: someitem --><!-- /ko --> goodbye') }) it('Should be able to nest "with" regions defined by containerless templates', function () { testNode.innerHTML = 'hello <!-- ko with: topitem -->' + 'Got top: <span data-bind="text: topprop"></span>' + '<!-- ko with: childitem -->' + 'Got child: <span data-bind="text: childprop"></span>' + '<!-- /ko -->' + '<!-- /ko -->' var viewModel = { topitem: observable(null) } applyBindings(viewModel, testNode) // First neither are there expect(testNode).toContainHtml('hello <!-- ko with: topitem --><!-- /ko -->') // Make top appear viewModel.topitem({ topprop: 'property of top', childitem: observable() }) expect(testNode).toContainHtml('hello <!-- ko with: topitem -->got top: <span data-bind="text: topprop">property of top</span><!-- ko with: childitem --><!-- /ko --><!-- /ko -->') // Make child appear viewModel.topitem().childitem({ childprop: 'property of child' }) expect(testNode).toContainHtml('hello <!-- ko with: topitem -->got top: <span data-bind="text: topprop">property of top</span><!-- ko with: childitem -->got child: <span data-bind="text: childprop">property of child</span><!-- /ko --><!-- /ko -->') // Make top disappear viewModel.topitem(null) expect(testNode).toContainHtml('hello <!-- ko with: topitem --><!-- /ko -->') }) it('Should provide access to an observable viewModel through $rawData', function () { testNode.innerHTML = `<div data-bind='with: item'><input data-bind='value: $rawData'/><div data-bind='text: $data'></div></div>` var item = observable('one') applyBindings({ item: item }, testNode) expect(item.getSubscriptionsCount('change')).toEqual(3) // subscriptions are the with and value bindings, and the binding contex expect(testNode.childNodes[0]).toHaveValues(['one']) expect(testNode.childNodes[0]).toContainText('one') // Should update observable when input is changed testNode.childNodes[0].childNodes[0].value = 'two' triggerEvent(testNode.childNodes[0].childNodes[0], 'change') expect(item()).toEqual('two') expect(testNode.childNodes[0]).toContainText('two') // Should update the input when the observable changes item('three') expect(testNode.childNodes[0]).toHaveValues(['three']) expect(testNode.childNodes[0]).toContainText('three') // Subscription count is stable expect(item.getSubscriptionsCount('change')).toEqual(3) }) it('Should update if given a function', function () { // See knockout/knockout#2285 testNode.innerHTML = '<div data-bind="with: getTotal">Total: <div data-bind="text: $data"></div>' function ViewModel () { var self = this self.items = observableArray([{ x: observable(4) }]) self.getTotal = function () { var total = 0 arrayForEach(self.items(), item => { total += item.x() }) return total } } var model = new ViewModel() applyBindings(model, testNode) expect(testNode).toContainText('Total: 4') model.items.push({ x: observable(15) }) expect(testNode).toContainText('Total: 19') model.items()[0].x(10) expect(testNode).toContainText('Total: 25') }) it('should refresh on dependency update binding', function () { // Note: // - knockout/knockout#2285 // - http://jsfiddle.net/g15jphta/6/ testNode.innerHTML = `<!-- ko template: {foreach: items} --> <div data-bind="text: x"></div> <div data-bind="with: $root.getTotal.bind($data)"> Total: <div data-bind="text: $data"></div> </div> <!-- /ko -->` function ViewModel () { var self = this self.items = observableArray([{ x: observable(4) }]) self.getTotal = function () { return self.items() .reduce(function (sum, value) { return sum + value.x() }, 0) } } var model = new ViewModel() applyBindings(model, testNode) model.items.push({ x: observable(15) }) }) it('Should call a childrenComplete callback function', function () { testNode.innerHTML = "<div data-bind='with: someItem, childrenComplete: callback'><span data-bind='text: childprop'></span></div>" var someItem = observable({ childprop: 'child' }), callbacks = 0 applyBindings({ someItem: someItem, callback: function () { callbacks++ } }, testNode) expect(callbacks).toEqual(1) expect(testNode.childNodes[0]).toContainText('child') someItem(null) expect(callbacks).toEqual(1) expect(testNode.childNodes[0].childNodes.length).toEqual(0) someItem({ childprop: 'new child' }) expect(callbacks).toEqual(2) expect(testNode.childNodes[0]).toContainText('new child') }) })
the_stack
import { act, fireEvent, render, screen } from "@testing-library/react"; import "@testing-library/jest-dom"; import userEvent from "@testing-library/user-event"; import React, { useState } from "react"; import { z } from "zod"; import { useZorm } from "../src"; import { assertNotAny } from "./test-helpers"; import { useValue, Value } from "../src/use-value"; test("can read value with useValue()", () => { const Schema = z.object({ thing: z.string().min(1), }); function Test() { const zo = useZorm("form", Schema); const value = useValue({ name: zo.fields.thing(), form: zo.ref, }); assertNotAny(value); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="input" name={zo.fields.thing()} /> <div data-testid="value">{value}</div> </form> ); } render(<Test />); userEvent.type(screen.getByTestId("input"), "value1"); expect(screen.queryByTestId("value")).toHaveTextContent("value1"); userEvent.type(screen.getByTestId("input"), "value2"); expect(screen.queryByTestId("value")).toHaveTextContent("value1value2"); }); test("can read value with <Value/>", () => { const renderSpy = jest.fn(); const valueRenderSpy = jest.fn(); const Schema = z.object({ thing: z.string().min(1), }); function Test() { renderSpy(); const zo = useZorm("form", Schema); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="input" name={zo.fields.thing()} /> <Value form={zo.ref} name={zo.fields.thing()}> {(value) => { valueRenderSpy(); return <div data-testid="value">{value}</div>; }} </Value> </form> ); } render(<Test />); userEvent.type(screen.getByTestId("input"), "value1"); expect(screen.queryByTestId("value")).toHaveTextContent("value1"); userEvent.type(screen.getByTestId("input"), "value2"); expect(screen.queryByTestId("value")).toHaveTextContent("value1value2"); expect(renderSpy).toHaveBeenCalledTimes(1); expect(valueRenderSpy.mock.calls.length).toBeGreaterThan(5); }); test("can transform the value with <Value/>", () => { const renderSpy = jest.fn(); const Schema = z.object({ thing: z.string().min(1), }); function Test() { renderSpy(); const zo = useZorm("form", Schema); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="input" name={zo.fields.thing()} /> <Value form={zo.ref} name={zo.fields.thing()} initialValue={0} transform={(value) => Number(value)} > {(value) => { const _: number = value; assertNotAny(value); return <div data-testid="value">{typeof value}</div>; }} </Value> </form> ); } render(<Test />); userEvent.type(screen.getByTestId("input"), "value1"); expect(screen.queryByTestId("value")).toHaveTextContent("number"); }); test("renders default value", () => { const Schema = z.object({ thing: z.string().min(1), }); function Test() { const zo = useZorm("form", Schema); const value: string = useValue({ name: zo.fields.thing(), form: zo.ref, }); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="input" name={zo.fields.thing()} defaultValue="defaultvalue" /> <div data-testid="value">{value}</div> </form> ); } render(<Test />); expect(screen.queryByTestId("value")).toHaveTextContent("defaultvalue"); }); test("can transform value", () => { const Schema = z.object({ thing: z.string().min(1), }); function Test() { const zo = useZorm("form", Schema); const value = useValue({ name: zo.fields.thing(), form: zo.ref, transform(value) { return value.toUpperCase(); }, }); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="input" name={zo.fields.thing()} defaultValue="value" /> <div data-testid="value">{value}</div> </form> ); } render(<Test />); expect(screen.queryByTestId("value")).toHaveTextContent("VALUE"); }); test("can transform to custom type", () => { const Schema = z.object({ thing: z.string().min(1), }); function Test() { const zo = useZorm("form", Schema); const value = useValue({ name: zo.fields.thing(), form: zo.ref, initialValue: 0, transform(value) { return value.length; }, }); const _num: number = value; assertNotAny(value); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="input" name={zo.fields.thing()} defaultValue="value" /> <div data-testid="value">{typeof value}</div> </form> ); } render(<Test />); expect(screen.queryByTestId("value")).toHaveTextContent("number"); }); test("can read lazily rendered value", () => { const Schema = z.object({ thing: z.string().min(1), }); function Test() { const zo = useZorm("form", Schema); const [showInput, setShowInput] = useState(false); const value = useValue({ name: zo.fields.thing(), form: zo.ref, initialValue: "initialvalue", }); return ( <form ref={zo.ref} data-testid="form"> {showInput && ( <input data-testid="input" name={zo.fields.thing()} /> )} <button type="button" onClick={() => { setShowInput(true); }} > show </button> <div data-testid="value">{value}</div> </form> ); } render(<Test />); expect(screen.queryByTestId("value")).toHaveTextContent("initialvalue"); fireEvent.click(screen.getByText("show")); userEvent.type(screen.getByTestId("input"), "typed value"); expect(screen.queryByTestId("value")).toHaveTextContent("typed value"); }); test("can read lazily rendered default value", () => { const Schema = z.object({ thing: z.string().min(1), }); function Test() { const zo = useZorm("form", Schema); const [showInput, setShowInput] = useState(false); const value = useValue({ name: zo.fields.thing(), form: zo.ref, initialValue: "initialvalue", }); return ( <form ref={zo.ref} data-testid="form"> {showInput && ( <input data-testid="input" name={zo.fields.thing()} defaultValue="defaultvalue" /> )} <button type="button" onClick={() => { setShowInput(true); }} > show </button> <div data-testid="value">{value}</div> </form> ); } render(<Test />); expect(screen.queryByTestId("value")).toHaveTextContent("initialvalue"); fireEvent.click(screen.getByText("show")); // XXX requires change simulation to be picked up const event = new Event("input", { bubbles: true, cancelable: true, }); act(() => { screen.getByTestId("input").dispatchEvent(event); }); // fireEvent.input(screen.getByTestId("input")); expect(screen.queryByTestId("value")).toHaveTextContent("defaultvalue"); }); test("can read checkbox", () => { const Schema = z.object({ checkbox: z.string().optional(), }); function Test() { const zo = useZorm("form", Schema); const value = useValue({ name: zo.fields.checkbox(), form: zo.ref, initialValue: false, transform: (value) => { return Boolean(value); }, }); const _bool: boolean = value; assertNotAny(value); return ( <form ref={zo.ref} data-testid="form"> <input data-testid="checkbox" name={zo.fields.checkbox()} /> <div data-testid="value"> {typeof value}: {String(value)} </div> </form> ); } render(<Test />); expect(screen.queryByTestId("value")).toHaveTextContent("boolean: false"); // This does not emit bubbling input event like in browser // userEvent.click(screen.getByTestId("checkbox")); // So simulate it manually: const checkbox = screen.getByTestId("checkbox"); if (checkbox instanceof HTMLInputElement) { checkbox.value = "on"; } act(() => { const event = new Event("input", { bubbles: true, cancelable: true, }); checkbox.dispatchEvent(event); }); expect(screen.queryByTestId("value")).toHaveTextContent("boolean: true"); });
the_stack
import { Stats, StatsCompilation, StatsModule } from 'webpack'; const anyPathSeparator = /\/|\\/; /** * Replaces the loader path in an identifier. * '(<loader expression>!)?/path/to/module.js' */ export const replaceLoaderInIdentifier = (identifier?: string) => { if (!identifier) { return ''; } const index = identifier.lastIndexOf('!'); return index === -1 ? identifier : identifier.slice(index + 1); }; /** * Normalizes an identifier so that it carries over time: removing the * "+ X modules" from the end of concatenated module identifiers. */ export const normalizeName = (identifier?: string) => identifier ? identifier.replace(/ \+ [0-9]+ modules$/, '') : ''; /** * Higher-order function that caches input to the wrapped function by argument. * It's expected that the first argument to the function is a reference type, * and that the function is not variadic. * * This works pretty simply and gracefully. JavaScript gives us the number of * arguments a given function takes. We use a WeakMap on the first argument, * and then store recursive maps for each subsequent argument. */ // tslint:disable-next-line const cacheByArg = <T extends Function>(fn: T): T => { const cacheMap = new WeakMap<any, any>(); const argCount = fn.length; return function(this: any) { let mapping: Map<any, any> | WeakMap<any, any> = cacheMap; for (let i = 0; i < argCount - 1; i++) { const next = arguments[i]; if (mapping.has(next)) { mapping = mapping.get(next); } else { const newMap = new Map(); mapping.set(next, newMap); mapping = newMap; } } const lastArg = arguments[argCount - 1]; if (!mapping.has(lastArg)) { const value = fn.apply(this, arguments); mapping.set(lastArg, value); return value; } return mapping.get(lastArg); } as any; }; /** * Returns the size of all chunks from the stats. */ export const getTotalChunkSize = cacheByArg((stats: StatsCompilation) => stats.chunks!.reduce((sum, chunk) => sum + chunk.size, 0), ); /** * Returns the size of the entry chunk(s). */ export const getEntryChunkSize = cacheByArg((stats: StatsCompilation) => stats.chunks!.filter(c => c.entry).reduce((sum, chunk) => sum + chunk.size, 0), ); /** * Bitfield of module types. */ export const enum ImportType { Unknown = 0, EsModule = 1 << 1, CommonJs = 1 << 2, } /** * Type containing metadata about an external node module. */ export interface INodeModule { /** * Friendly name of the dependency node. */ name: string; /** * Total size of the node module in the stats. */ totalSize: number; /** * Modules imported from this dependency. */ modules: StatsModule[]; /** * Type of the node module. */ importType: ImportType; } /** * Tries to get the node module in the given identifier, returning null if * it's not a node module import. */ export const getNodeModuleFromIdentifier = (identifier: string): string | null => { const parts = replaceLoaderInIdentifier(identifier).split(anyPathSeparator); for (let i = parts.length - 1; i >= 0; i--) { if (parts[i] !== 'node_modules') { continue; } let packageName = parts[i + 1]; if (packageName[0] === '@') { packageName += '/' + parts[i + 2]; } return packageName; } return null; }; const concatParents = new WeakMap<StatsModule, StatsModule>(); /** * Returns the concatenation parent in which the given module resides. Will * returnt he module itself if it's already top-level. */ export const getConcatenationParent = (m: StatsModule): StatsModule => concatParents.get(m) || m; /** * Get webpack modules, either globally ro in a single chunk. */ export const getWebpackModules = cacheByArg((stats: StatsCompilation, filterToChunk?: number) => { const modules: StatsModule[] = []; if (!stats.modules) { return modules; } for (const parent of stats.modules) { if (filterToChunk !== undefined && !parent.chunks?.includes(filterToChunk)) { continue; } // If it has nested modules, it's a concatened chunk. Remove the // concatenation and only emit children. if (!parent.modules) { modules.push(parent); continue; } for (const child of parent.modules) { modules.push(child); concatParents.set(child, parent); } } return modules; }); /** * Returns a mapping of normalized identifiers in the chunk to module data. */ export const getWebpackModulesMap = cacheByArg( (stats: StatsCompilation, filterToChunk?: number) => { const mapping: { [name: string]: StatsModule } = {}; for (const m of getWebpackModules(stats, filterToChunk)) { mapping[normalizeName(m.name)] = m; } return mapping; }, ); /** * Gets the type of import of the given module. */ export const getImportType = (importedModule: StatsModule) => { let flags = 0; for (const reason of getReasons(importedModule)) { if (reason.type) { flags |= reason.type.includes('cjs') ? ImportType.CommonJs : reason.type.includes('harmony') ? ImportType.EsModule : ImportType.Unknown; } } return flags; }; /** * Returns the number of dependencies. */ export const getNodeModules = cacheByArg((stats: StatsCompilation, inChunk?: number) => { const modules: { [key: string]: INodeModule } = {}; for (const importedModule of getWebpackModules(stats, inChunk)) { const packageName = getNodeModuleFromIdentifier(importedModule.identifier!); if (!packageName) { continue; } const moduleType = getImportType(importedModule); const previous = modules[packageName]; if (!previous) { modules[packageName] = { name: packageName, totalSize: importedModule.size || 0, modules: [importedModule], importType: moduleType, }; } else { previous.totalSize += importedModule.size || 0; previous.importType |= moduleType; previous.modules.push(importedModule); } } return modules; }); /** * Types of importable modules. */ export const enum ModuleType { Javascript, Style, External, NodeModule, } /** * Identifies a module type, given an ID. */ export const identifyModuleType = (id: string): ModuleType => { if (id.includes('style-loader') || id.includes('css-loader')) { return ModuleType.Style; } if (id.startsWith('external ')) { return ModuleType.External; } if (id.includes('node_modules')) { return ModuleType.NodeModule; } return ModuleType.Javascript; }; /** * Grouped output comparing an old and new node module. */ export interface IWebpackModuleComparisonOutput { name: string; type: ModuleType; fromSize: number; toSize: number; nodeModule?: string; old?: StatsModule; new?: StatsModule; } /** * Returns a grouped comparison of the old and new modules from the stats. */ export const compareAllModules = ( oldStats: StatsCompilation, newStats: StatsCompilation, inChunk?: number, ) => { const oldModules = getWebpackModules(oldStats, inChunk); const newModules = getWebpackModules(newStats, inChunk); const output: { [name: string]: IWebpackModuleComparisonOutput } = {}; for (const m of oldModules) { if (!m.identifier) { continue; } const normalized = normalizeName(m.name); output[normalized] = { name: normalized, type: identifyModuleType(m.identifier), nodeModule: getNodeModuleFromIdentifier(m.identifier) || undefined, toSize: 0, fromSize: m.size || 0, old: m, }; } for (const m of newModules) { if (!m.identifier) { continue; } const normalized = normalizeName(m.name); if (output[normalized]) { output[normalized].new = m; output[normalized].toSize = m.size || 0; } else { output[normalized] = { name: normalized, type: identifyModuleType(m.identifier), nodeModule: getNodeModuleFromIdentifier(m.identifier) || undefined, fromSize: 0, toSize: m.size || 0, new: m, }; } } return output; }; /** * Grouped output comparing an old and new node module. */ export interface INodeModuleComparisonOutput { name: string; old?: INodeModule; new?: INodeModule; } /** * Returns a grouped comparison of the old and new modules from the stats. */ export const compareNodeModules = ( oldStats: StatsCompilation, newStats: StatsCompilation, inChunk?: number, ) => { const oldModules = getNodeModules(oldStats, inChunk); const newModules = getNodeModules(newStats, inChunk); const output: { [name: string]: INodeModuleComparisonOutput } = {}; for (const name of Object.keys(oldModules)) { output[name] = { name, old: oldModules[name] }; } for (const name of Object.keys(newModules)) { if (output[name]) { output[name].new = newModules[name]; } else { output[name] = { name, new: oldModules[name] }; } } return Object.values(output); }; /** * Gets the number of node modules. */ export const getNodeModuleSize = cacheByArg((stats: StatsCompilation, inChunk?: number) => { let total = 0; const modules = getNodeModules(stats, inChunk); for (const key of Object.keys(modules)) { total += modules[key].totalSize; } return total; }); /** * Gets the number of node modules. */ export const getNodeModuleCount = (stats: StatsCompilation, inChunk?: number) => Object.keys(getNodeModules(stats, inChunk)).length; /** * Gets the number of node modules. */ export const getTreeShakablePercent = cacheByArg((stats: StatsCompilation, inChunk?: number) => { const modules = Object.values(getNodeModules(stats, inChunk)); if (modules.length === 0) { return 1; } let harmony = 0; for (const { importType: moduleType } of modules) { if (moduleType & ImportType.EsModule && !(moduleType & ImportType.CommonJs)) { harmony++; } } return harmony / modules.length; }); /** * Gets the number of node modules. */ export const getTotalModuleCount = (stats: StatsCompilation, inChunk?: number) => getWebpackModules(stats, inChunk)!.length; /** * Gets the number of node modules. */ export const getAverageChunkSize = (stats: StatsCompilation) => { let sum = 0; for (const chunk of stats.chunks!) { sum += chunk.size; } return sum / stats.chunks!.length; }; export interface IModuleTreeNode { /** * Module ID. */ id: number; /** * Friendly module name. */ name: string; /** * Module size */ size: number; /** * List of children this module imports. */ children: IModuleTreeNode[]; } /** * Gets the reasons that the module was imported. Fix for broken webpack typings here. */ export const getReasons = (m: StatsModule): Stats.Reason[] => m.reasons as any; /** * Gets all direct imports of the given node module. */ export const getDirectImportsOfNodeModule = (stats: StatsCompilation, name: string) => stats.modules!.filter(m => m.name && getNodeModuleFromIdentifier(m.name) === name); /** * Gets all direct imports of the given node module. */ export const getImportsOfName = (stats: StatsCompilation, name: string): StatsModule[] => { const modules = getWebpackModulesMap(stats); const root = modules[name]; if (!root) { return []; } return getReasons(root) .map(reason => modules[reason.moduleName]) .filter(Boolean); };
the_stack
import { AfterContentInit, ChangeDetectionStrategy, Component, ContentChildren, ElementRef, Inject, Input, NgZone, OnDestroy, OnInit, QueryList, Renderer2, ViewChild } from '@angular/core'; import { BehaviorSubject, iif, merge, NEVER, Observable, Subject, Subscription } from 'rxjs'; import { exhaustMap, filter, map, startWith, switchMap, take, takeUntil } from 'rxjs/operators'; import { ktdMouseOrTouchDown, ktdMouseOrTouchEnd, ktdPointerClient } from '../utils/pointer.utils'; import { GRID_ITEM_GET_RENDER_DATA_TOKEN, KtdGridItemRenderDataTokenType } from '../grid.definitions'; import { KTD_GRID_DRAG_HANDLE, KtdGridDragHandle } from '../directives/drag-handle'; import { KTD_GRID_RESIZE_HANDLE, KtdGridResizeHandle } from '../directives/resize-handle'; import { KtdGridService } from '../grid.service'; import { ktdOutsideZone } from '../utils/operators'; import { BooleanInput, coerceBooleanProperty } from '../coercion/boolean-property'; import { coerceNumberProperty, NumberInput } from '../coercion/number-property'; @Component({ selector: 'ktd-grid-item', templateUrl: './grid-item.component.html', styleUrls: ['./grid-item.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class KtdGridItemComponent implements OnInit, OnDestroy, AfterContentInit { /** Elements that can be used to drag the grid item. */ @ContentChildren(KTD_GRID_DRAG_HANDLE, {descendants: true}) _dragHandles: QueryList<KtdGridDragHandle>; @ContentChildren(KTD_GRID_RESIZE_HANDLE, {descendants: true}) _resizeHandles: QueryList<KtdGridResizeHandle>; @ViewChild('resizeElem', {static: true, read: ElementRef}) resizeElem: ElementRef; /** CSS transition style. Note that for more performance is preferable only make transition on transform property. */ @Input() transition: string = 'transform 500ms ease, width 500ms ease, height 500ms ease'; dragStart$: Observable<MouseEvent | TouchEvent>; resizeStart$: Observable<MouseEvent | TouchEvent>; /** Id of the grid item. This property is strictly compulsory. */ @Input() get id(): string { return this._id; } set id(val: string) { this._id = val; } private _id: string; /** Minimum amount of pixels that the user should move before it starts the drag sequence. */ @Input() get dragStartThreshold(): number { return this._dragStartThreshold; } set dragStartThreshold(val: number) { this._dragStartThreshold = coerceNumberProperty(val); } private _dragStartThreshold: number = 0; /** Whether the item is draggable or not. Defaults to true. */ @Input() get draggable(): boolean { return this._draggable; } set draggable(val: boolean) { this._draggable = coerceBooleanProperty(val); this._draggable$.next(this._draggable); } private _draggable: boolean = true; private _draggable$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(this._draggable); /** Whether the item is resizable or not. Defaults to true. */ @Input() get resizable(): boolean { return this._resizable; } set resizable(val: boolean) { this._resizable = coerceBooleanProperty(val); this._resizable$.next(this._resizable); } private _resizable: boolean = true; private _resizable$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(this._resizable); private dragStartSubject: Subject<MouseEvent | TouchEvent> = new Subject<MouseEvent | TouchEvent>(); private resizeStartSubject: Subject<MouseEvent | TouchEvent> = new Subject<MouseEvent | TouchEvent>(); private subscriptions: Subscription[] = []; constructor(public elementRef: ElementRef, private gridService: KtdGridService, private renderer: Renderer2, private ngZone: NgZone, @Inject(GRID_ITEM_GET_RENDER_DATA_TOKEN) private getItemRenderData: KtdGridItemRenderDataTokenType) { this.dragStart$ = this.dragStartSubject.asObservable(); this.resizeStart$ = this.resizeStartSubject.asObservable(); } ngOnInit() { const gridItemRenderData = this.getItemRenderData(this.id)!; this.setStyles(gridItemRenderData); } ngAfterContentInit() { this.subscriptions.push( this._dragStart$().subscribe(this.dragStartSubject), this._resizeStart$().subscribe(this.resizeStartSubject), ); } ngOnDestroy() { this.subscriptions.forEach(sub => sub.unsubscribe()); } setStyles({top, left, width, height}: { top: string, left: string, width?: string, height?: string }) { // transform is 6x times faster than top/left this.renderer.setStyle(this.elementRef.nativeElement, 'transform', `translateX(${left}) translateY(${top})`); this.renderer.setStyle(this.elementRef.nativeElement, 'display', `block`); this.renderer.setStyle(this.elementRef.nativeElement, 'transition', this.transition); if (width != null) { this.renderer.setStyle(this.elementRef.nativeElement, 'width', width); } if (height != null) {this.renderer.setStyle(this.elementRef.nativeElement, 'height', height); } } private _dragStart$(): Observable<MouseEvent | TouchEvent> { return this._draggable$.pipe( switchMap((draggable) => { if (!draggable) { return NEVER; } else { return this._dragHandles.changes.pipe( startWith(this._dragHandles), switchMap((dragHandles: QueryList<KtdGridDragHandle>) => { return iif( () => dragHandles.length > 0, merge(...dragHandles.toArray().map(dragHandle => ktdMouseOrTouchDown(dragHandle.element.nativeElement, 1))), ktdMouseOrTouchDown(this.elementRef.nativeElement, 1) ).pipe( exhaustMap((startEvent) => { // If the event started from an element with the native HTML drag&drop, it'll interfere // with our own dragging (e.g. `img` tags do it by default). Prevent the default action // to stop it from happening. Note that preventing on `dragstart` also seems to work, but // it's flaky and it fails if the user drags it away quickly. Also note that we only want // to do this for `mousedown` since doing the same for `touchstart` will stop any `click` // events from firing on touch devices. if (startEvent.target && (startEvent.target as HTMLElement).draggable && startEvent.type === 'mousedown') { startEvent.preventDefault(); } const startPointer = ktdPointerClient(startEvent); return this.gridService.mouseOrTouchMove$(document).pipe( takeUntil(ktdMouseOrTouchEnd(document, 1)), ktdOutsideZone(this.ngZone), filter((moveEvent) => { moveEvent.preventDefault(); const movePointer = ktdPointerClient(moveEvent); const distanceX = Math.abs(startPointer.clientX - movePointer.clientX); const distanceY = Math.abs(startPointer.clientY - movePointer.clientY); // When this conditions returns true mean that we are over threshold. return distanceX + distanceY >= this.dragStartThreshold; }), take(1), // Return the original start event map(() => startEvent) ); }) ); }) ); } }) ); } private _resizeStart$(): Observable<MouseEvent | TouchEvent> { return this._resizable$.pipe( switchMap((resizable) => { if (!resizable) { // Side effect to hide the resizeElem if resize is disabled. this.renderer.setStyle(this.resizeElem.nativeElement, 'display', 'none'); return NEVER; } else { return this._resizeHandles.changes.pipe( startWith(this._resizeHandles), switchMap((resizeHandles: QueryList<KtdGridResizeHandle>) => { if (resizeHandles.length > 0) { // Side effect to hide the resizeElem if there are resize handles. this.renderer.setStyle(this.resizeElem.nativeElement, 'display', 'none'); return merge(...resizeHandles.toArray().map(resizeHandle => ktdMouseOrTouchDown(resizeHandle.element.nativeElement, 1))); } else { this.renderer.setStyle(this.resizeElem.nativeElement, 'display', 'block'); return ktdMouseOrTouchDown(this.resizeElem.nativeElement, 1); } }) ); } }) ); } // tslint:disable-next-line static ngAcceptInputType_draggable: BooleanInput; // tslint:disable-next-line static ngAcceptInputType_resizable: BooleanInput; // tslint:disable-next-line static ngAcceptInputType_dragStartThreshold: NumberInput; }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const acceptLanguage: msRest.OperationParameter = { parameterPath: "acceptLanguage", mapper: { serializedName: "accept-language", defaultValue: 'en-US', type: { name: "String" } } }; export const activityName: msRest.OperationURLParameter = { parameterPath: "activityName", mapper: { required: true, serializedName: "activityName", type: { name: "String" } } }; export const apiVersion0: msRest.OperationQueryParameter = { parameterPath: "apiVersion", mapper: { required: true, isConstant: true, serializedName: "api-version", defaultValue: '2015-10-31', type: { name: "String" } } }; export const apiVersion1: msRest.OperationQueryParameter = { parameterPath: "apiVersion", mapper: { required: true, isConstant: true, serializedName: "api-version", defaultValue: '2017-05-15-preview', type: { name: "String" } } }; export const apiVersion2: msRest.OperationQueryParameter = { parameterPath: "apiVersion", mapper: { required: true, isConstant: true, serializedName: "api-version", defaultValue: '2018-01-15', type: { name: "String" } } }; export const apiVersion3: msRest.OperationQueryParameter = { parameterPath: "apiVersion", mapper: { required: true, isConstant: true, serializedName: "api-version", defaultValue: '2018-06-30', type: { name: "String" } } }; export const automationAccountName: msRest.OperationURLParameter = { parameterPath: "automationAccountName", mapper: { required: true, serializedName: "automationAccountName", type: { name: "String" } } }; export const certificateName: msRest.OperationURLParameter = { parameterPath: "certificateName", mapper: { required: true, serializedName: "certificateName", type: { name: "String" } } }; export const clientRequestId: msRest.OperationParameter = { parameterPath: [ "options", "clientRequestId" ], mapper: { serializedName: "clientRequestId", type: { name: "String" } } }; export const compilationJobName: msRest.OperationURLParameter = { parameterPath: "compilationJobName", mapper: { required: true, serializedName: "compilationJobName", type: { name: "String" } } }; export const configurationName: msRest.OperationURLParameter = { parameterPath: "configurationName", mapper: { required: true, serializedName: "configurationName", type: { name: "String" } } }; export const connectionName: msRest.OperationURLParameter = { parameterPath: "connectionName", mapper: { required: true, serializedName: "connectionName", type: { name: "String" } } }; export const connectionTypeName: msRest.OperationURLParameter = { parameterPath: "connectionTypeName", mapper: { required: true, serializedName: "connectionTypeName", type: { name: "String" } } }; export const countType: msRest.OperationURLParameter = { parameterPath: "countType", mapper: { required: true, serializedName: "countType", type: { name: "String" } } }; export const credentialName: msRest.OperationURLParameter = { parameterPath: "credentialName", mapper: { required: true, serializedName: "credentialName", type: { name: "String" } } }; export const filter: msRest.OperationQueryParameter = { parameterPath: [ "options", "filter" ], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const hybridRunbookWorkerGroupName: msRest.OperationURLParameter = { parameterPath: "hybridRunbookWorkerGroupName", mapper: { required: true, serializedName: "hybridRunbookWorkerGroupName", type: { name: "String" } } }; export const inlinecount: msRest.OperationQueryParameter = { parameterPath: [ "options", "inlinecount" ], mapper: { serializedName: "$inlinecount", type: { name: "String" } } }; export const jobId: msRest.OperationURLParameter = { parameterPath: "jobId", mapper: { required: true, serializedName: "jobId", type: { name: "Uuid" } } }; export const jobName: msRest.OperationURLParameter = { parameterPath: "jobName", mapper: { required: true, serializedName: "jobName", type: { name: "String" } } }; export const jobScheduleId: msRest.OperationURLParameter = { parameterPath: "jobScheduleId", mapper: { required: true, serializedName: "jobScheduleId", type: { name: "Uuid" } } }; export const jobStreamId: msRest.OperationURLParameter = { parameterPath: "jobStreamId", mapper: { required: true, serializedName: "jobStreamId", type: { name: "String" } } }; export const moduleName: msRest.OperationURLParameter = { parameterPath: "moduleName", mapper: { required: true, serializedName: "moduleName", type: { name: "String" } } }; export const nextPageLink: msRest.OperationURLParameter = { parameterPath: "nextPageLink", mapper: { required: true, serializedName: "nextLink", type: { name: "String" } }, skipEncoding: true }; export const nodeConfigurationName: msRest.OperationURLParameter = { parameterPath: "nodeConfigurationName", mapper: { required: true, serializedName: "nodeConfigurationName", type: { name: "String" } } }; export const nodeId: msRest.OperationURLParameter = { parameterPath: "nodeId", mapper: { required: true, serializedName: "nodeId", type: { name: "String" } } }; export const packageName: msRest.OperationURLParameter = { parameterPath: "packageName", mapper: { required: true, serializedName: "packageName", type: { name: "String" } } }; export const reportId: msRest.OperationURLParameter = { parameterPath: "reportId", mapper: { required: true, serializedName: "reportId", type: { name: "String" } } }; export const resourceGroupName: msRest.OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { required: true, serializedName: "resourceGroupName", constraints: { MaxLength: 90, MinLength: 1, Pattern: /^[-\w\._]+$/ }, type: { name: "String" } } }; export const runbookName: msRest.OperationURLParameter = { parameterPath: "runbookName", mapper: { required: true, serializedName: "runbookName", type: { name: "String" } } }; export const scheduleName: msRest.OperationURLParameter = { parameterPath: "scheduleName", mapper: { required: true, serializedName: "scheduleName", type: { name: "String" } } }; export const skip0: msRest.OperationQueryParameter = { parameterPath: [ "options", "skip" ], mapper: { serializedName: "$skip", type: { name: "Number" } } }; export const skip1: msRest.OperationQueryParameter = { parameterPath: [ "options", "skip" ], mapper: { serializedName: "$skip", type: { name: "String" } } }; export const softwareUpdateConfigurationMachineRunId: msRest.OperationURLParameter = { parameterPath: "softwareUpdateConfigurationMachineRunId", mapper: { required: true, serializedName: "softwareUpdateConfigurationMachineRunId", type: { name: "Uuid" } } }; export const softwareUpdateConfigurationName: msRest.OperationURLParameter = { parameterPath: "softwareUpdateConfigurationName", mapper: { required: true, serializedName: "softwareUpdateConfigurationName", type: { name: "String" } } }; export const softwareUpdateConfigurationRunId: msRest.OperationURLParameter = { parameterPath: "softwareUpdateConfigurationRunId", mapper: { required: true, serializedName: "softwareUpdateConfigurationRunId", type: { name: "Uuid" } } }; export const sourceControlName: msRest.OperationURLParameter = { parameterPath: "sourceControlName", mapper: { required: true, serializedName: "sourceControlName", type: { name: "String" } } }; export const sourceControlSyncJobId: msRest.OperationURLParameter = { parameterPath: "sourceControlSyncJobId", mapper: { required: true, serializedName: "sourceControlSyncJobId", type: { name: "Uuid" } } }; export const streamId: msRest.OperationURLParameter = { parameterPath: "streamId", mapper: { required: true, serializedName: "streamId", type: { name: "String" } } }; export const subscriptionId: msRest.OperationURLParameter = { parameterPath: "subscriptionId", mapper: { required: true, serializedName: "subscriptionId", type: { name: "String" } } }; export const top0: msRest.OperationQueryParameter = { parameterPath: [ "options", "top" ], mapper: { serializedName: "$top", type: { name: "Number" } } }; export const top1: msRest.OperationQueryParameter = { parameterPath: [ "options", "top" ], mapper: { serializedName: "$top", type: { name: "String" } } }; export const typeName: msRest.OperationURLParameter = { parameterPath: "typeName", mapper: { required: true, serializedName: "typeName", type: { name: "String" } } }; export const variableName: msRest.OperationURLParameter = { parameterPath: "variableName", mapper: { required: true, serializedName: "variableName", type: { name: "String" } } }; export const watcherName: msRest.OperationURLParameter = { parameterPath: "watcherName", mapper: { required: true, serializedName: "watcherName", type: { name: "String" } } }; export const webhookName: msRest.OperationURLParameter = { parameterPath: "webhookName", mapper: { required: true, serializedName: "webhookName", type: { name: "String" } } };
the_stack
export type ClarinetEvent = | 'onvalue' | 'onstring' | 'onkey' | 'onopenobject' | 'oncloseobject' | 'onopenarray' | 'onclosearray' | 'onerror' | 'onend' | 'onready'; // Removes the MAX_BUFFER_LENGTH, originally set to 64 * 1024 const MAX_BUFFER_LENGTH = Number.MAX_SAFE_INTEGER; // const DEBUG = false; enum STATE { BEGIN = 0, VALUE, // general stuff OPEN_OBJECT, // { CLOSE_OBJECT, // } OPEN_ARRAY, // [ CLOSE_ARRAY, // ] TEXT_ESCAPE, // \ stuff STRING, // "" BACKSLASH, END, // No more stack OPEN_KEY, // , "a" CLOSE_KEY, // : TRUE, // r TRUE2, // u TRUE3, // e FALSE, // a FALSE2, // l FALSE3, // s FALSE4, // e NULL, // u NULL2, // l NULL3, // l NUMBER_DECIMAL_POINT, // . NUMBER_DIGIT // [0-9] } const Char = { tab: 0x09, // \t lineFeed: 0x0a, // \n carriageReturn: 0x0d, // \r space: 0x20, // " " doubleQuote: 0x22, // " plus: 0x2b, // + comma: 0x2c, // , minus: 0x2d, // - period: 0x2e, // . _0: 0x30, // 0 _9: 0x39, // 9 colon: 0x3a, // : E: 0x45, // E openBracket: 0x5b, // [ backslash: 0x5c, // \ closeBracket: 0x5d, // ] a: 0x61, // a b: 0x62, // b e: 0x65, // e f: 0x66, // f l: 0x6c, // l n: 0x6e, // n r: 0x72, // r s: 0x73, // s t: 0x74, // t u: 0x75, // u openBrace: 0x7b, // { closeBrace: 0x7d // } }; const stringTokenPattern = /[\\"\n]/g; type ParserEvent = (parser: ClarinetParser, event: string, data?: any) => void; export type ClarinetParserOptions = { onready?: ParserEvent; onopenobject?: ParserEvent; onkey?: ParserEvent; oncloseobject?: ParserEvent; onopenarray?: ParserEvent; onclosearray?: ParserEvent; onvalue?: ParserEvent; onerror?: ParserEvent; onend?: ParserEvent; onchunkparsed?: ParserEvent; }; const DEFAULT_OPTIONS: Required<ClarinetParserOptions> = { onready: () => {}, onopenobject: () => {}, onkey: () => {}, oncloseobject: () => {}, onopenarray: () => {}, onclosearray: () => {}, onvalue: () => {}, onerror: () => {}, onend: () => {}, onchunkparsed: () => {} }; export default class ClarinetParser { protected options: Required<ClarinetParserOptions> = DEFAULT_OPTIONS; bufferCheckPosition = MAX_BUFFER_LENGTH; q = ''; c = ''; p = ''; closed = false; closedRoot = false; sawRoot = false; // tag = null; error: Error | null = null; state = STATE.BEGIN; stack: STATE[] = []; // mostly just for error reporting position: number = 0; column: number = 0; line: number = 1; slashed: boolean = false; unicodeI: number = 0; unicodeS: string | null = null; depth: number = 0; textNode; numberNode; constructor(options: ClarinetParserOptions = {}) { this.options = {...DEFAULT_OPTIONS, ...options}; this.textNode = undefined; this.numberNode = ''; this.emit('onready'); } end() { if (this.state !== STATE.VALUE || this.depth !== 0) this._error('Unexpected end'); this._closeValue(); this.c = ''; this.closed = true; this.emit('onend'); return this; } resume() { this.error = null; return this; } close() { return this.write(null); } // protected emit(event: string, data?: any): void { // if (DEBUG) console.log('-- emit', event, data); this.options[event]?.(data, this); } emitNode(event: string, data?: any): void { this._closeValue(); this.emit(event, data); } /* eslint-disable no-continue */ // eslint-disable-next-line complexity, max-statements write(chunk) { if (this.error) { throw this.error; } if (this.closed) { return this._error('Cannot write after close. Assign an onready handler.'); } if (chunk === null) { return this.end(); } let i = 0; let c = chunk.charCodeAt(0); let p = this.p; // if (DEBUG) console.log(`write -> [${ chunk }]`); while (c) { p = c; this.c = c = chunk.charCodeAt(i++); // if chunk doesnt have next, like streaming char by char // this way we need to check if previous is really previous // if not we need to reset to what the this says is the previous // from buffer if (p !== c) { this.p = p; } else { p = this.p; } if (!c) break; // if (DEBUG) console.log(i, c, STATE[this.state]); this.position++; if (c === Char.lineFeed) { this.line++; this.column = 0; } else this.column++; switch (this.state) { case STATE.BEGIN: if (c === Char.openBrace) this.state = STATE.OPEN_OBJECT; else if (c === Char.openBracket) this.state = STATE.OPEN_ARRAY; else if (!isWhitespace(c)) { this._error('Non-whitespace before {[.'); } continue; case STATE.OPEN_KEY: case STATE.OPEN_OBJECT: if (isWhitespace(c)) continue; if (this.state === STATE.OPEN_KEY) this.stack.push(STATE.CLOSE_KEY); else if (c === Char.closeBrace) { this.emit('onopenobject'); this.depth++; this.emit('oncloseobject'); this.depth--; this.state = this.stack.pop() || STATE.VALUE; continue; } else this.stack.push(STATE.CLOSE_OBJECT); if (c === Char.doubleQuote) this.state = STATE.STRING; else this._error('Malformed object key should start with "'); continue; case STATE.CLOSE_KEY: case STATE.CLOSE_OBJECT: if (isWhitespace(c)) continue; // let event = this.state === STATE.CLOSE_KEY ? 'key' : 'object'; if (c === Char.colon) { if (this.state === STATE.CLOSE_OBJECT) { this.stack.push(STATE.CLOSE_OBJECT); this._closeValue('onopenobject'); this.depth++; } else this._closeValue('onkey'); this.state = STATE.VALUE; } else if (c === Char.closeBrace) { this.emitNode('oncloseobject'); this.depth--; this.state = this.stack.pop() || STATE.VALUE; } else if (c === Char.comma) { if (this.state === STATE.CLOSE_OBJECT) this.stack.push(STATE.CLOSE_OBJECT); this._closeValue(); this.state = STATE.OPEN_KEY; } else this._error('Bad object'); continue; case STATE.OPEN_ARRAY: // after an array there always a value case STATE.VALUE: if (isWhitespace(c)) continue; if (this.state === STATE.OPEN_ARRAY) { this.emit('onopenarray'); this.depth++; this.state = STATE.VALUE; if (c === Char.closeBracket) { this.emit('onclosearray'); this.depth--; this.state = this.stack.pop() || STATE.VALUE; continue; } else { this.stack.push(STATE.CLOSE_ARRAY); } } if (c === Char.doubleQuote) this.state = STATE.STRING; else if (c === Char.openBrace) this.state = STATE.OPEN_OBJECT; else if (c === Char.openBracket) this.state = STATE.OPEN_ARRAY; else if (c === Char.t) this.state = STATE.TRUE; else if (c === Char.f) this.state = STATE.FALSE; else if (c === Char.n) this.state = STATE.NULL; else if (c === Char.minus) { // keep and continue this.numberNode += '-'; } else if (Char._0 <= c && c <= Char._9) { this.numberNode += String.fromCharCode(c); this.state = STATE.NUMBER_DIGIT; } else this._error('Bad value'); continue; case STATE.CLOSE_ARRAY: if (c === Char.comma) { this.stack.push(STATE.CLOSE_ARRAY); this._closeValue('onvalue'); this.state = STATE.VALUE; } else if (c === Char.closeBracket) { this.emitNode('onclosearray'); this.depth--; this.state = this.stack.pop() || STATE.VALUE; } else if (isWhitespace(c)) continue; else this._error('Bad array'); continue; case STATE.STRING: if (this.textNode === undefined) { this.textNode = ''; } // thanks thejh, this is an about 50% performance improvement. let starti = i - 1; let slashed = this.slashed; let unicodeI = this.unicodeI; // eslint-disable-next-line no-constant-condition, no-labels STRING_BIGLOOP: while (true) { // if (DEBUG) console.log(i, c, STATE[this.state], slashed); // zero means "no unicode active". 1-4 mean "parse some more". end after 4. while (unicodeI > 0) { this.unicodeS += String.fromCharCode(c); c = chunk.charCodeAt(i++); this.position++; if (unicodeI === 4) { // TODO this might be slow? well, probably not used too often anyway this.textNode += String.fromCharCode(parseInt(this.unicodeS as string, 16)); unicodeI = 0; starti = i - 1; } else { unicodeI++; } // we can just break here: no stuff we skipped that still has to be sliced out or so // eslint-disable-next-line no-labels if (!c) break STRING_BIGLOOP; } if (c === Char.doubleQuote && !slashed) { this.state = this.stack.pop() || STATE.VALUE; this.textNode += chunk.substring(starti, i - 1); this.position += i - 1 - starti; break; } if (c === Char.backslash && !slashed) { slashed = true; this.textNode += chunk.substring(starti, i - 1); this.position += i - 1 - starti; c = chunk.charCodeAt(i++); this.position++; if (!c) break; } if (slashed) { slashed = false; if (c === Char.n) { this.textNode += '\n'; } else if (c === Char.r) { this.textNode += '\r'; } else if (c === Char.t) { this.textNode += '\t'; } else if (c === Char.f) { this.textNode += '\f'; } else if (c === Char.b) { this.textNode += '\b'; } else if (c === Char.u) { // \uxxxx. meh! unicodeI = 1; this.unicodeS = ''; } else { this.textNode += String.fromCharCode(c); } c = chunk.charCodeAt(i++); this.position++; starti = i - 1; if (!c) break; else continue; } stringTokenPattern.lastIndex = i; const reResult = stringTokenPattern.exec(chunk); if (reResult === null) { i = chunk.length + 1; this.textNode += chunk.substring(starti, i - 1); this.position += i - 1 - starti; break; } i = reResult.index + 1; c = chunk.charCodeAt(reResult.index); if (!c) { this.textNode += chunk.substring(starti, i - 1); this.position += i - 1 - starti; break; } } this.slashed = slashed; this.unicodeI = unicodeI; continue; case STATE.TRUE: if (c === Char.r) this.state = STATE.TRUE2; else this._error(`Invalid true started with t${c}`); continue; case STATE.TRUE2: if (c === Char.u) this.state = STATE.TRUE3; else this._error(`Invalid true started with tr${c}`); continue; case STATE.TRUE3: if (c === Char.e) { this.emit('onvalue', true); this.state = this.stack.pop() || STATE.VALUE; } else this._error(`Invalid true started with tru${c}`); continue; case STATE.FALSE: if (c === Char.a) this.state = STATE.FALSE2; else this._error(`Invalid false started with f${c}`); continue; case STATE.FALSE2: if (c === Char.l) this.state = STATE.FALSE3; else this._error(`Invalid false started with fa${c}`); continue; case STATE.FALSE3: if (c === Char.s) this.state = STATE.FALSE4; else this._error(`Invalid false started with fal${c}`); continue; case STATE.FALSE4: if (c === Char.e) { this.emit('onvalue', false); this.state = this.stack.pop() || STATE.VALUE; } else this._error(`Invalid false started with fals${c}`); continue; case STATE.NULL: if (c === Char.u) this.state = STATE.NULL2; else this._error(`Invalid null started with n${c}`); continue; case STATE.NULL2: if (c === Char.l) this.state = STATE.NULL3; else this._error(`Invalid null started with nu${c}`); continue; case STATE.NULL3: if (c === Char.l) { this.emit('onvalue', null); this.state = this.stack.pop() || STATE.VALUE; } else this._error(`Invalid null started with nul${c}`); continue; case STATE.NUMBER_DECIMAL_POINT: if (c === Char.period) { this.numberNode += '.'; this.state = STATE.NUMBER_DIGIT; } else this._error('Leading zero not followed by .'); continue; case STATE.NUMBER_DIGIT: if (Char._0 <= c && c <= Char._9) this.numberNode += String.fromCharCode(c); else if (c === Char.period) { if (this.numberNode.indexOf('.') !== -1) this._error('Invalid number has two dots'); this.numberNode += '.'; } else if (c === Char.e || c === Char.E) { if (this.numberNode.indexOf('e') !== -1 || this.numberNode.indexOf('E') !== -1) this._error('Invalid number has two exponential'); this.numberNode += 'e'; } else if (c === Char.plus || c === Char.minus) { // @ts-expect-error if (!(p === Char.e || p === Char.E)) this._error('Invalid symbol in number'); this.numberNode += String.fromCharCode(c); } else { this._closeNumber(); i--; // go back one this.state = this.stack.pop() || STATE.VALUE; } continue; default: this._error(`Unknown state: ${this.state}`); } } if (this.position >= this.bufferCheckPosition) { checkBufferLength(this); } this.emit('onchunkparsed'); return this; } _closeValue(event: string = 'onvalue'): void { if (this.textNode !== undefined) { this.emit(event, this.textNode); } this.textNode = undefined; } _closeNumber(): void { if (this.numberNode) this.emit('onvalue', parseFloat(this.numberNode)); this.numberNode = ''; } _error(message: string = ''): void { this._closeValue(); message += `\nLine: ${this.line}\nColumn: ${this.column}\nChar: ${this.c}`; const error = new Error(message); this.error = error; this.emit('onerror', error); } } function isWhitespace(c): boolean { return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab; } function checkBufferLength(parser) { const maxAllowed = Math.max(MAX_BUFFER_LENGTH, 10); let maxActual = 0; for (const buffer of ['textNode', 'numberNode']) { const len = parser[buffer] === undefined ? 0 : parser[buffer].length; if (len > maxAllowed) { switch (buffer) { case 'text': // TODO - should this be closeValue? // closeText(parser); break; default: parser._error(`Max buffer length exceeded: ${buffer}`); } } maxActual = Math.max(maxActual, len); } parser.bufferCheckPosition = MAX_BUFFER_LENGTH - maxActual + parser.position; }
the_stack
// Text Field inputs // // Spec: http://www.google.com/design/spec/components/text-fields.html // // Single-line text fields: // // Without floating label: // // | 16 |--- // 48 | |Input Text (16sp) // | 16 |--- // // With floating label: // // | 16 |--- // | |Label Text (12sp) // 72 | 8 |--- // | |Input Text (16sp) // | 16 |--- import react = require('react'); import react_dom = require('react-dom'); import style = require('ts-style'); import { div, input } from '../base/dom_factory'; import colors = require('./colors'); import fonts = require('./fonts'); // Color of floating label and underline when focused var FOCUS_COLOR = colors.MATERIAL_COLOR_PRIMARY; // Color of label when unfocused var LABEL_COLOR = colors.MATERIAL_GREY_P500; var TRANSITION_DURATION = '0.2s'; var TEXT_MARGIN = '0.5em 0 0.25em'; var theme = style.create( { textField: { normalTextFieldStyle: { background: 'transparent', fontSize: 16, border: 'none', outline: 'none', left: 0, width: '100%', padding: 0, margin: TEXT_MARGIN, }, underlineContainer: { position: 'relative', left: 0, right: 0, height: 0, overflow: 'visible', }, underline: { backgroundColor: LABEL_COLOR, height: 1, }, // style used for the underline when the input // has focus focusedUnderline: { backgroundColor: FOCUS_COLOR, height: 2, position: 'absolute', top: 0, left: 0, right: 0, opacity: 0, transition: 'left ' + TRANSITION_DURATION + ' ease-out, right ' + TRANSITION_DURATION + ' ease-out', }, errorUnderline: { backgroundColor: colors.MATERIAL_RED_P500, }, errorLabel: { color: colors.MATERIAL_RED_P500, fontSize: fonts.caption.size, marginTop: 8, }, fullWidthTextFieldStyle: { width: '100%', }, placeholder: { color: LABEL_COLOR, fontSize: 16, left: 1, position: 'absolute', opacity: 1, transition: 'top .18s linear, font-size .18s linear, opacity .10s linear', pointerEvents: 'none', margin: TEXT_MARGIN, }, floatingLabel: { top: 27, error: { color: colors.MATERIAL_RED_P500, }, }, container: { position: 'relative', paddingBottom: 8, }, placeholderTop: { fontSize: 12, top: 4, }, scrollBlocksStyle: { backgroundColor: LABEL_COLOR, bottom: 6, height: 3, opacity: 0, position: 'absolute', transition: 'opacity .28s linear', width: 3, ':before': { backgroundColor: LABEL_COLOR, bottom: 0, content: "''", position: 'absolute', height: 3, width: 3, right: 6, }, ':after': { backgroundColor: LABEL_COLOR, bottom: 0, content: "''", position: 'absolute', height: 3, width: 3, right: -6, }, }, focusStyle: { backgroundColor: FOCUS_COLOR, ':before': { backgroundColor: FOCUS_COLOR, }, ':after': { backgroundColor: FOCUS_COLOR, }, }, }, }, __filename ); /** Specify custom styling for the component. */ export interface TextFieldStyle { fontFamily?: string; } export interface TextFieldProps extends react.Props<void> { /** Specifies the type of <input> field */ type?: string; /** Initial value of the <input> field, still allowing * the user to edit it. */ defaultValue?: string; /** Fixed value for the <input> field. */ value?: string; /** Specifies whether the placeholder text * should be shown above the field when it has * a value. */ floatingLabel?: boolean; /** A validation error string displayed beneath * the input area. */ error?: string; /** Label that is displayed in the field when empty. * If floatingLabel is enabeld, this value will also float above * the field's content when non-empty. */ placeHolder?: string; showUnderline?: boolean; readOnly?: boolean; /** Specifies whether the field should be focused when mounted * or when this prop changes from false to true. */ focus?: boolean; onChange?: react.FormEventHandler<Element>; onBlur?: react.FocusEventHandler<Element>; onFocus?: react.FocusEventHandler<Element>; style?: TextFieldStyle; } interface TextFieldState { // indicates whether the input field has focus focus?: boolean; // a flag set when the user initiates focusing the // text field and then cleared a moment later focusing?: boolean; // the X-coordinate of the mouse event that // caused the field to gain focus focusX?: number; } export class TextField extends react.Component<TextFieldProps, TextFieldState> { private textField: HTMLInputElement; static defaultProps = { showUnderline: true, }; constructor(props?: TextFieldProps) { super(props); this.state = { focus: false, focusing: true, }; this.onMouseDown = this.onMouseDown.bind(this); this.onTouchStart = this.onTouchStart.bind(this); this.onChange = this.onChange.bind(this); this.onBlur = this.onBlur.bind(this); this.onFocus = this.onFocus.bind(this); } componentDidMount() { if (this.props.focus) { this.setFocus(); } } componentWillReceiveProps(nextProps: TextFieldProps) { if (!this.props.focus && nextProps.focus) { this.setFocus(); } } private setFocus() { var textField = <HTMLInputElement>react_dom.findDOMNode( this.refs['textField'] ); textField.select(); } render() { var props = this.props; var styles = theme.textField; var placeHolderStyling: any[] = [styles.placeholder]; if (props.floatingLabel) { placeHolderStyling.push(styles.floatingLabel); } if (this.state.focus || this.effectiveValue().length > 0) { if (props.floatingLabel) { placeHolderStyling.push(styles.placeholderTop); if (this.state.focus) { placeHolderStyling.push({ color: FOCUS_COLOR }); if (this.props.error) { placeHolderStyling.push(styles.floatingLabel.error); } } } else { placeHolderStyling.push({ opacity: '0' }); } } var containerStyling: any[] = [styles.container]; if (props.floatingLabel) { containerStyling.push({ height: '66px' }); } var textFieldStyling: any[] = [styles.normalTextFieldStyle]; if (props.style && props.style.fontFamily) { textFieldStyling.push({ fontFamily: props.style.fontFamily }); } if (props.floatingLabel) { textFieldStyling.push({ paddingTop: 25 }); } var focusedUnderlineStyling: any[] = [styles.focusedUnderline]; if (this.state.focus || this.props.error) { focusedUnderlineStyling.push({ opacity: 1 }); } var errorLabel: react.ReactElement<any>; if (props.error) { focusedUnderlineStyling.push(styles.errorUnderline); errorLabel = div(style.mixin(styles.errorLabel), props.error); } var underline: react.ReactElement<any>; if (props.showUnderline) { underline = div( style.mixin(styles.underlineContainer, { ref: 'underlineContainer', }), div(style.mixin(styles.underline, { ref: 'underline' })), div( style.mixin(focusedUnderlineStyling, { ref: 'focusedUnderline', }) ) ); } return div( style.mixin(containerStyling), div(style.mixin(placeHolderStyling), props.placeHolder), input( style.mixin(textFieldStyling, { onChange: this.onChange, onKeyUp: this.onChange, onClick: this.onChange, onWheel: this.onChange, onFocus: this.onFocus, onBlur: this.onBlur, onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart, type: this.props.type || 'text', ref: (el: HTMLInputElement) => (this.textField = el), defaultValue: this.props.defaultValue, value: this.props.value, readOnly: this.props.readOnly, }) ), underline, errorLabel ); } onMouseDown(e: react.MouseEvent<Element>) { if (this.state.focus) { return; } this.setState({ focusX: e.clientX }); } onTouchStart(e: react.TouchEvent<Element>) { if (this.state.focus) { return; } var touch = e.touches.item(0); this.setState({ focusX: touch.clientX }); } onChange(e: react.FormEvent<Element>) { if (this.props.onChange) { this.props.onChange(e); } } onBlur(e: react.FocusEvent<Element>) { this.setState({ focus: false, focusX: null, }); if (this.props.onBlur) { this.props.onBlur(e); } } onFocus(e: react.FocusEvent<Element>) { this.setState({ focus: true, }); // if the user focused via touch or mouse, // animate the focused underline, spilling from the horizontal // position of the mouse or touch if (this.state.focusX && this.props.showUnderline) { var underlineEl = react_dom.findDOMNode(this.refs['underlineContainer']) as Element; var underlineRect = underlineEl.getBoundingClientRect(); var focusedUnderline = <HTMLElement>react_dom.findDOMNode( this.refs['focusedUnderline'] ); this.setState({ focusing: true }); focusedUnderline.style.transition = 'none'; focusedUnderline.style.left = (this.state.focusX - underlineRect.left).toString() + 'px'; focusedUnderline.style.right = (underlineRect.right - this.state.focusX).toString() + 'px'; setTimeout(() => { focusedUnderline.style.transition = ''; focusedUnderline.style.left = '0px'; focusedUnderline.style.right = '0px'; this.setState({ focusing: false }); }, 1); } if (this.props.onFocus) { this.props.onFocus(e); } } // returns the value being displayed in the text field. // This is equal to props.value if set or the current // value of the actual DOM node if mounted effectiveValue() { if (this.props.value !== undefined) { return this.props.value; } else if (this.props.defaultValue) { return this.props.defaultValue; } else if (this.textField) { return this.textField.value; } else { return ''; } } } export var TextFieldF = react.createFactory(TextField);
the_stack
import * as Analytics from "expo-firebase-analytics"; import * as Haptics from "expo-haptics"; import { Platform } from "react-native"; import * as THREE from "three"; import { DirectionalLight, HemisphereLight } from "three"; import Settings from "../constants/Settings"; import { dispatch } from "../rematch/store"; import GameObject from "./GameObject"; import PlatformObject from "./entities/Platform"; import PlayerBall from "./entities/PlayerBall"; import randomRange from "./utils/randomRange"; import GameScene from "./GameScene"; import GameStates from "./GameStates"; import MenuObject from "./MenuObject"; function distance( p1: { x: number; z: number }, p2: { x: number; z: number } ): number { const a = p1.x - p2.x; const b = p1.z - p2.z; return Math.sqrt(a * a + b * b); } class PlayerGroupObject extends GameObject { private mainBall = 1; /** * Current angle in degrees */ rotationAngle = 0; velocity = Settings.rotationSpeed; balls: PlayerBall[] = []; async loadAsync() { this.balls = [new PlayerBall(), new PlayerBall()]; await this.add(...this.balls); this.reset(); return super.loadAsync(); } landed = (accuracy: number, radius: number): void => { this.getActiveItem().landed(accuracy, radius); this.toggleActiveItem(); this.resetScale(); this.rotationAngle -= 180; }; toggleActiveItem = (): void => { this.mainBall = 1 - this.mainBall; }; getActiveItem = (): PlayerBall => { return this.balls[this.mainBall]; }; getStaticItem = (): PlayerBall => { return this.balls[1 - this.mainBall]; }; getActiveItemsDistanceFromObject = (target: THREE.Object3D) => { return distance(this.getActiveItem().position, target.position); }; getStaticItemsDistanceFromObject = (target: THREE.Object3D) => { return distance(this.getStaticItem().position, target.position); }; reset = () => { this.velocity = Settings.rotationSpeed; this.rotationAngle = 0; this.mainBall = 1; for (const ball of this.balls) { ball.position.x = 0; ball.position.z = 0; ball.alpha = 1; } this.getStaticItem().z = Settings.ballDistance; this.resetScale(); }; resetScale = () => { for (const ball of this.balls) { ball.scale.set(1, 1, 1); } }; playGameOverAnimation = (onComplete: () => void): void => { this.getActiveItem().hide({ onComplete }); this.getStaticItem().hide({ duration: 0.4 }); }; getActiveItemScale = (): number => { return this.getActiveItem().scale.x; }; shrinkActiveItemScale = (amount: number): void => { const scale = Math.max( Settings.minBallScale, this.getActiveItem().scale.x - amount ); this.getActiveItem().scale.set(scale, 1, scale); }; /** * Given a distance and angle in degrees, sets the active item's position relative to the static item's position. */ moveActiveItem = (distance: number): void => { const [x, z] = this.getPositionWithDistanceAndAngle( distance, this.rotationAngle ); this.getActiveItem().position.x = x; this.getActiveItem().position.z = z; }; getRotationSpeedForScore = (score: number): number => { return Math.min(this.velocity + score * 0.05, Settings.maxRotationSpeed); }; incrementRotationWithScoreAndDirection = ( score: number, direction: number ): void => { const speed = this.getRotationSpeedForScore(score); this.rotationAngle = this.getRotationAngleForDirection(speed, direction); }; getRotationAngleForDirection(delta: number, direction: number): number { return (this.rotationAngle + delta * direction) % 360; } getPositionWithDistanceAndAngle( distance: number, angle: number ): [number, number] { // @ts-ignore const radians = THREE.Math.degToRad(angle); return [ this.getStaticItem().x - distance * Math.sin(radians), this.getStaticItem().z + distance * Math.cos(radians), ]; } } function getAbsolutePosition(gameObject: THREE.Object3D): THREE.Vector3 { const position = new THREE.Vector3(); gameObject.getWorldPosition(position); return position; } function playHaptics(impact: number) { if (Platform.OS !== "ios") { return; } if (impact < 0.3) { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); } else if (impact < 0.6) { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); } else { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy); } } class PillarGroupObject extends GameObject { pillars: PlatformObject[] = []; getCurrentPillar(): PlatformObject { return this.pillars[0]; } getNextPillar(): PlatformObject { return this.pillars[1]; } async getPillarAtIndexAsync( index: number, score: number ): Promise<PlatformObject> { // Ensure enough pillars exist while (this.pillars.length < index + 1) { await this.addPillarAsync(score); } return this.pillars[index]; } getLastPillar(): PlatformObject { return this.pillars[this.pillars.length - 1]; } getCurrentLevelForScore(score: number) { return Math.floor(score / 10); } getVisiblePillarCount = (score: number = 0): number => { const level = this.getCurrentLevelForScore(score); if (level < 4) { return Math.max(4, Settings.visiblePillars - level); } return Math.max(3, Settings.visiblePillars - (score % 5)); }; playGameOverAnimation = (): void => { for (const target of this.pillars) { target.animateOut(); } }; async loadAsync() { await this.reset(); return super.loadAsync(); } reset = async (): Promise<void> => { for (const pillar of this.pillars) { pillar.destroy(); } this.pillars = []; await this.ensureTargetsAreCreatedAsync(); this.getCurrentPillar().becomeCurrent(); this.getNextPillar().becomeTarget(); }; addPillarAsync = async (score: number) => { const lastPillar = this.getLastPillar(); const target = await this.add(new PlatformObject()); this.pillars.push(target); const distance = Settings.ballDistance; // * 0.5; if (!lastPillar) { // is the first pillar target.z = Settings.ballDistance; } else { // find a random location relative to the last pillar const startX = lastPillar.x; const startZ = lastPillar.z; const radians = this.generateRandomAngleForPillar(); target.position.x = startX + distance * Math.sin(radians); target.position.z = startZ + distance * Math.cos(radians); target.lastAngle = Math.atan2(startZ - target.z, startX - target.x); // This seems to cause lag // target.alpha = this.alphaForTarget(this.pillars.length, score); target.animateIn(); } }; generateRandomAngleForPillar() { const range = 90; const randomAngle = randomRange( Settings.angleRange[0] + range, Settings.angleRange[1] + range ); // @ts-ignore const radians = THREE.Math.degToRad(randomAngle); return radians; } alphaForTarget = (i: number, score: number) => { const inverse = i - 1; const alpha = inverse / this.getVisiblePillarCount(score); return 1 - alpha; }; syncTargetsAlpha = (score: number) => { for (let i = 0; i < this.pillars.length; i++) { this.pillars[i].alpha = this.alphaForTarget(i, score); } }; ensureTargetsAreCreatedAsync = async (score: number) => { while (this.pillars.length < this.getVisiblePillarCount(score)) { await this.addPillarAsync(score); } }; getLandedPillarIndex = (playerObject: PlayerGroupObject) => { // End before 0 to skip the current pillar that the player is standing on. // Go in reverse order to ensure the player gets optimal skipping for (let index = this.pillars.length - 1; index > 0; index--) { const targetPlatform = this.pillars[index]; const distanceFromTarget = playerObject.getActiveItemsDistanceFromObject( targetPlatform ); if (distanceFromTarget < targetPlatform.radius) return [index, distanceFromTarget]; } return null; }; } class Game extends GameObject { state = GameStates.Menu; score = 0; taps = 0; direction = 1; camera?: THREE.PerspectiveCamera; private _width: number; private _height: number; private originalCameraPosition: THREE.Vector3 = new THREE.Vector3(); titleGroup?: MenuObject; gameGroup?: GameObject; pillarGroup?: PillarGroupObject; playerObject?: PlayerGroupObject; scene?: GameScene; constructor(width: number, height: number, public renderer: THREE.Renderer) { super({}); this._game = this; this._width = width; this._height = height; if (Settings.isAutoStartEnabled) { this.setGameState(GameStates.Playing); } } createCameraAsync = ( width: number, height: number ): THREE.PerspectiveCamera => { const camera = new THREE.PerspectiveCamera(70, width / height, 1, 10000); camera.position.set(20, 260, 100); camera.lookAt(new THREE.Vector3()); this.originalCameraPosition = camera.position.clone(); return camera; }; /** * Ensure the direction the play spins is the shortest route between pillars. */ generateDirection = (targetPosition: THREE.Vector3) => { if (!this.playerObject) return; // Get the distance between the player and the next pillar const ballDistance = distance( this.playerObject.getStaticItem().position, targetPosition ); // Measure the distance between the player if it moved const pos1 = this.playerObject.getPositionWithDistanceAndAngle( ballDistance, this.playerObject.getRotationAngleForDirection(1, 1) ); // Measure the distance between the player if it didn't move const pos2 = this.playerObject.getPositionWithDistanceAndAngle( ballDistance, this.playerObject.rotationAngle ); // Calculate the distances const delta1 = distance({ x: pos1[0], z: pos1[1] }, targetPosition); const delta2 = distance({ x: pos2[0], z: pos2[1] }, targetPosition); // If moving the player +1 is shorter then keep it if (delta1 > delta2) { this.direction = 1; } else { this.direction = -1; } }; async reset() { super.reset(); if (this.gameGroup) { this.gameGroup.position.z = 0; this.gameGroup.position.x = 0; } this.playerObject?.reset(); await this.pillarGroup?.reset(); } async loadAsync() { this.scene = new GameScene(); // @ts-ignore: idk this.scene.add(this); this.camera = await this.createCameraAsync(this._width, this._height); const light = new DirectionalLight(0xffffff, 0.9); light.position.set(0, 350, 350); this.scene.add(new HemisphereLight(0xaaaaaa, 0x000000, 0.9), light); if (this.state === GameStates.Menu) { await this.loadMenu(); dispatch.game.menu(); } else { dispatch.game.play(); await this.loadGame(); } await super.loadAsync(this.scene); } loadMenu = async () => { this.titleGroup = await this.add(new MenuObject()); }; loadGame = async () => { this.gameGroup = await this.add(new GameObject()); this.pillarGroup = await this.gameGroup.add(new PillarGroupObject()); this.playerObject = await this.gameGroup.add(new PlayerGroupObject()); this.alpha = 1; }; startGame = () => { if (this.state === GameStates.Playing) { return; } this.titleGroup?.animateHidden(async () => { await this.loadGame(); this.setGameState(GameStates.Playing); }); }; setGameState = (state: GameStates) => { this.state = state; }; onTouchesBegan = async () => { if (this.state === GameStates.Menu) { this.startGame(); } else { this.changeBall(); // if (Math.round(randomRange(0, 3)) === 0) { // this.takeScreenshot(); // } } }; changeBall = async () => { // postpone to prevent lag during interactions setTimeout(() => { this.taps += 1; // Every three taps, change the background color if (this.taps % 3 === 0) { this.scene?.animateBackgroundColor(this.taps); } }, 0); if (!this.loaded || !this.pillarGroup) { return; } const landedPillarInfo = this.pillarGroup.getLandedPillarIndex( this.playerObject! ); if (landedPillarInfo == null) { // Missed the pillars this.gameOver(); return; } const [pillarIndex, distanceFromTarget] = landedPillarInfo; const targetPlatform = this.pillarGroup.pillars[pillarIndex]; const landedPillarRadius = targetPlatform.radius; const accuracy = 1 - distanceFromTarget / landedPillarRadius; // maybe hide menu if (this.score <= 1) { dispatch.game.play(); } // Score for every pillar traversed for (let i = pillarIndex; i > 0; i--) { dispatch.score.increment(); this.score += 1; } playHaptics(accuracy); // if (this.particles) { // this.particles.impulse(); // } const nextPillar = await this.pillarGroup.getPillarAtIndexAsync( pillarIndex + 1, this.score ); this.generateDirection(nextPillar.position); targetPlatform.updateDirection(this.direction); // Animate out all of the skipped pillars while ( this.pillarGroup.pillars.length && this.pillarGroup.pillars[0].pillarId !== targetPlatform.pillarId ) { const previousPillar = this.pillarGroup.pillars.shift()!; previousPillar.animateOut(); } targetPlatform.becomeCurrent(); if (Settings.gemsEnabled && this.score > 3) { const gemCount = Math.floor(accuracy * 6); targetPlatform.showGems(gemCount); } nextPillar.becomeTarget(); this.playerObject?.landed(accuracy, landedPillarRadius); await this.pillarGroup.ensureTargetsAreCreatedAsync(this.score); // this.pillarGroup.syncTargetsAlpha(this.score); }; screenShotTaken: boolean = false; takeScreenshot = async () => { if (this.screenShotTaken || !Settings.isScreenshotEnabled) { return; } this.screenShotTaken = true; // @ts-ignore await dispatch.screenshot.updateAsync({ // @ts-ignore ref: global.gameRef, width: this._width, height: this._height, }); }; gameOver = (animate = true) => { this.takeScreenshot(); this.screenShotTaken = false; dispatch.score.reset(); Analytics.logEvent("game_over", { score: this.score, }); this.score = 0; dispatch.game.menu(); if (!this.playerObject) throw new Error("Player must be defined before invoking game over"); // Freeze the player during the animation this.playerObject.velocity = 0; if (animate) { this.playerObject.playGameOverAnimation(() => this.reset()); this.pillarGroup?.playGameOverAnimation(); } else { this.reset(); } }; update(delta: number, time: number) { if (!this.camera) return; if (this.state === GameStates.Menu) { this.titleGroup?.updateWithCamera(this.camera); } else { this.camera.position.z = this.originalCameraPosition.z; this.camera.position.x = this.originalCameraPosition.x; if ( !this.loaded || !this.playerObject || !this.pillarGroup || !this.gameGroup ) { return; } super.update(delta, time); if (!this.playerObject.getActiveItem()) return; const isFirst = this.score === 0; const minScale = this.playerObject.getActiveItemScale() <= Settings.minBallScale; if (!isFirst) { if (minScale) { this.playerObject.resetScale(); this.gameOver(false); } else { // Currently the item shrinks at a fixed rate this.playerObject.shrinkActiveItemScale(0.3 * delta); } } // guard against race condition when pillars are recycled if (this.pillarGroup.getNextPillar()) { // move rotation angle this.playerObject.incrementRotationWithScoreAndDirection( this.score, this.direction ); const ballDistance = this.playerObject.getStaticItemsDistanceFromObject( this.pillarGroup.getNextPillar() ); this.playerObject.moveActiveItem(ballDistance); } // Ease the game to the static item position to make the scene move. const distanceX = this.playerObject.getStaticItem().position.x; const distanceZ = this.playerObject.getStaticItem().position.z; const easing = 0.03; this.gameGroup.position.z -= (distanceZ - 0 + this.gameGroup.position.z) * easing; this.gameGroup.position.x -= (distanceX - 0 + this.gameGroup.position.x) * easing; const currentPillar = this.pillarGroup.getCurrentPillar(); // Collect gems if ( Settings.gemsEnabled && currentPillar && currentPillar.gems && currentPillar.gems.length ) { const collideGems = currentPillar.gems.filter( (gem) => gem.canBeCollected && gem.driftAngle !== undefined ); if (collideGems.length) { let _ballPosition = getAbsolutePosition( this.playerObject.getActiveItem() ); for (const gem of collideGems) { let position = getAbsolutePosition(gem); const angleDist = distance(_ballPosition, position); if (angleDist < 15) { gem.pickup(); dispatch.currency.change(gem.getValue()); } } } } } } } export default Game;
the_stack
(function () { GM.xmlHttpRequest = GM_xmlhttpRequest; GM.getValue = GM_getValue; GM.setValue = GM_setValue; GM.deleteValue = GM_deleteValue; GM.listValues = GM_listValues; GM.getResourceText = GM_getResourceText; GM.getResourceURL = GM_getResourceText; // @ts-ignore 忽略unsafeWindow错误 const root: Window = unsafeWindow; const modules: Record<string, any> = {}; /* 模块占位 */ /** * 初始化脚本设置数据 */ const CONFIG: { [name: string]: any } = {}; const config: { [name: string]: any } = new Proxy(CONFIG, { set: (_target, p: string, value) => { CONFIG[p] = value; GM.setValue<{ [name: string]: any }>("config", CONFIG); return true; }, get: (_target, p: string) => CONFIG[p] }) Object.entries(GM.getValue<{ [name: string]: any }>("config", {})).forEach(k => Reflect.set(config, k[0], k[1])); class API { static API: Object; static SETTING: any[] = []; static MENU: Record<string, any> = {}; GM = GM; module: (string | symbol)[] = []; Name: string = GM.info.script.name; Virsion: string = GM.info.script.version; Handler: string = [GM.info.scriptHandler, GM.info.version].join(" "); config = config; /** * 获取模块内容 * @param name 模块名字 * @returns json直接返回格式化对象,其他返回字符串 */ getModule = (name: string) => Reflect.get(modules, name); /** * 载入模块 * @param name 模块名字 * @param args 传递给对方的全局变量:格式{变量名:变量值} * @param force 是否强制载入,一般模块只会载入一次,需要二次载入请将本值设为真 */ importModule = (name?: string | symbol, args: { [key: string]: any } = {}, force?: boolean) => { if (!name) return Object.keys(modules); if (this.module.includes(name) && !force) return this.module; if (Reflect.has(modules, name)) { !this.module.includes(name) && this.module.push(name); new Function("API", "GM", "debug", "toast", "xhr", "config", "importModule", ...Object.keys(args), Reflect.get(modules, name)) (API.API, GM, Reflect.get(this, "debug"), Reflect.get(this, "toast"), Reflect.get(this, "xhr"), config, this.importModule, ...Object.keys(args).reduce((s: object[], d) => { s.push(args[d]); return s; }, [])) } } static modifyConfig(obj: any) { Reflect.has(obj, "value") && !Reflect.has(config, Reflect.get(obj, "key")) && Reflect.set(config, Reflect.get(obj, "key"), Reflect.get(obj, "value")); Reflect.get(obj, "type") == "sort" && Reflect.has(obj, "list") && Reflect.get(obj, "list").forEach((d: any) => this.modifyConfig(d)); } registerSetting(obj: any) { API.SETTING.push(obj); API.modifyConfig(obj); } registerMenu(obj: any) { Reflect.set(API.MENU, Reflect.get(obj, "key"), obj); } changeSettingMode(mode: Record<string, boolean>) { const keys = Object.keys(mode); API.SETTING.forEach(d => { Reflect.has(d, "key") && keys.includes(Reflect.get(d, "key")) && Reflect.set(d, "hidden", Reflect.get(mode, Reflect.get(d, "key"))); }) } rewriteHTML(html: string) { this.getModule("bug.json").forEach((d: string) => { root[d] && Reflect.set(root, d, undefined) }) document.open(); document.write(html); document.close(); config.rewriteMethod == "异步" && this.importModule("vector.js"); // 重写后页面正常引导 } initUi() { root.self === root.top && (<any>this).runWhile(() => document.body, () => { this.importModule("ui.js", { MENU: API.MENU, SETTING: API.SETTING }); }); new Promise(r => delete this.initUi); } constructor() { API.API = new Proxy(this, { get: (t, p) => { return Reflect.get(t, p) || Reflect.get(root, p) || ( Reflect.has(modules["apply.json"], p) ? ( t.importModule(modules["apply.json"][p], {}), Reflect.get(t, p) ) : undefined); }, set: (t, p, value) => { Reflect.set(t, p, value); return true; } }) new Function("API", Reflect.get(modules, "debug.js"))(API.API); new Function("API", "debug", "config", Reflect.get(modules, "toast.js"))(API.API, Reflect.get(this, "debug"), config); new Function("API", "GM", Reflect.get(modules, "xhr.js"))(API.API, GM); this.importModule("rewrite.js"); } } new API(); })(); declare namespace GM { interface cookieDetails { /** * 域 */ domain: string, /** * 截止日期时间戳(10位) */ expirationDate: number; /** * 客户端专用,不会发送给服务端 */ hostOnly: boolean; /** * 服务端专用,客户端js无法获取/修改 */ httpOnly: boolean; /** * 名称 */ name: string; /** * 子页面路径 */ path: string; /** * 同源策略 */ sameSite: string; /** * 是否允许通过非安全链接发送给服务器 */ secure: boolean; /** * 会话型cookie,临时有效,随页面一起销毁 */ session: boolean; /** * 值 */ value: string } let xmlHttpRequest: typeof GM_xmlhttpRequest; let getValue: typeof GM_getValue; let setValue: typeof GM_setValue; let deleteValue: typeof GM_deleteValue; let listValues: typeof GM_listValues; let getResourceText: typeof GM_getResourceText; let getResourceURL: typeof GM_getResourceURL; const info: { downloadMode: string; isFirstPartyIsolation: boolean; isIncognito: boolean; scriptHandler: string; scriptMetaStr: string; scriptSource: string; scriptUpdateURL: string; scriptWillUpdate: string; version: string; script: { antifeatures: {}; author: string; blockers: []; copyright: string; description: string; description_i18n: {}; evilness: number; excludes: []; grant: []; header: string; homepage: string; icon: string; icon64: string; includes: []; lastModified: number; matches: []; name: string; name_i18n: []; namespace: string; options: { check_for_updates: boolean; comment: string; compat_foreach: boolean; compat_metadata: boolean; compat_prototypes: boolean; compat_wrappedjsobject: boolean; compatopts_for_requires: boolean; noframes: boolean; override: { merge_connects: boolean; merge_excludes: boolean; merge_includes: boolean; merge_matches: boolean; orig_connects: []; orig_excludes: []; orig_includes: []; orig_matches: []; orig_noframes: boolean; orig_run_at: string; use_blockers: []; use_connects: []; use_excludes: []; use_includes: []; use_matches: []; } run_at: string; } position: number; requires: []; resources: [{ [name: string]: string }]; "run-at": string; supportURL: string; sync: { imported: string }; unwrap: boolean; updateURL: string; uuid: string; version: string; webRequest: string; } } const cookie: { /** * **警告:此实验性特性仅在Tampermonkey Beta中可用,否则将抛出语法错误!** */ <T extends keyof typeof cookie>(method: T, ...args: Parameters<(typeof cookie)[T]>): ReturnType<(typeof cookie)[T]>; /** * 以数组形式返回所有cookie * **警告:此实验性特性仅在Tampermonkey Beta中可用,否则将抛出语法错误!** * @param details 筛选条件,无条件请使用空对象{}会返回所有cookie * @returns 符合条件的cookie对象数组 */ list(details: Partial<Record<"domain" | "name" | "path", string>>): Promise<cookieDetails[]>; /** * 修改/添加cookie * **警告:此实验性特性仅在Tampermonkey Beta中可用,否则将抛出语法错误!** * @param args cookie详细信息 */ set(details: Partial<cookieDetails>): Promise<void>; /** * 删除cookie * **警告:此实验性特性仅在Tampermonkey Beta中可用,否则将抛出语法错误!** * @param args 删除条件 */ delete(details: Record<"name", string>): Promise<void>; } } declare function GM_xmlhttpRequest(details: GMxhrDetails): { abort: () => void }; declare function GM_getResourceText(name: string): string; declare function GM_getResourceURL(name: string): string; declare function GM_getValue<T>(name: string, defaultValue?: T): T; declare function GM_setValue<T>(name: string, value: T): void; declare function GM_deleteValue(name: string): void; declare function GM_listValues(): string[]; /** * 模块间的顶层变量,类似于`window` */ declare namespace API { /** * 脚本名字 */ let Name: string; /** * 脚本版本 */ let Virsion: string; /** * 脚本管理器名字 */ let Handler: string; /** * 载入模块 * @param name 模块名字 * @param args 传递给对方的全局变量:格式{变量名:变量值} * @param force 是否强制载入,一般模块只会载入一次,需要二次载入请将本值设为真 */ function importModule(name?: string | symbol, args?: { [key: string]: any; }, force?: boolean): string[]; /** * 获取模块内容 * @param name 模块名字 * @returns json直接返回格式化对象,其他返回字符串 */ function getModule(name: string): any; /** * 重写网页框架 * @param html 网页模板 */ function rewriteHTML(html: string): void; }
the_stack
import { UserError } from "@adpt/utils"; import { cloneDeep, isError } from "lodash"; import * as randomstring from "randomstring"; import { DeployStatus } from "../deploy"; import { DeploymentNotActive, DeploymentOpIDNotActive, DeployStepIDNotFound, InternalError } from "../error"; import { ElementID } from "../jsx"; import { DeploymentInfo } from "../ops/listDeployments"; import { DeploymentStored, DeployOpID, DeployStepID, DeployStepInfo, ElementStatus, ElementStatusMap, } from "./deployment_data"; import { HistoryEntry, HistoryName, HistoryStatus, HistoryStore } from "./history"; import { AdaptServer, isServerPathExists, ServerLock, withLock } from "./server"; export interface Deployment { readonly deployID: string; getDataDir(withStatus: HistoryStatus): Promise<string>; releaseDataDir(): Promise<void>; commitEntry(toStore: HistoryEntry): Promise<void>; historyEntry(historyName: HistoryName): Promise<HistoryEntry>; lastEntry(withStatus?: HistoryStatus): Promise<HistoryEntry | undefined>; currentOpID(): Promise<DeployOpID>; newOpID(): Promise<DeployOpID>; currentStepID(opID: DeployOpID): Promise<DeployStepID>; newStepID(opID: DeployOpID): Promise<DeployStepID>; status(stepID: DeployStepID): Promise<DeployStepInfo>; status(stepID: DeployStepID, info: Partial<DeployStepInfo>): Promise<void>; elementStatus(stepID: DeployStepID, elementID: ElementID): Promise<ElementStatus>; elementStatus(stepID: DeployStepID, statusMap: ElementStatusMap): Promise<void>; } const deploymentPath = "/deployments"; const maxTries = 100; const invalidChars = RegExp("[:/]", "g"); export function encodePathComponent(comp: string) { return comp.replace(invalidChars, "_"); } function dpath(deployID: string) { deployID = encodePathComponent(deployID); return `${deploymentPath}/${deployID}`; } function makeName(base: string) { const rand = randomstring.generate({ length: 4, charset: "alphabetic", readable: true, capitalization: "lowercase", }); return `${base}-${rand}`; } function isPathNotFound(err: any) { // FIXME(mark): AdaptServer should have its own error. This is actually // specific to the current local server implementation. Encapsulating here // to make it easier to fix later. return isError(err) && err.name === "DataError"; } export interface DeploymentOptions { deployID?: string; } export async function createDeployment(server: AdaptServer, projectName: string, stackName: string, options: DeploymentOptions = {}): Promise<Deployment> { const baseName = `${projectName}::${stackName}`; let deployID = ""; for (let i = 0; i < maxTries; i++) { deployID = options.deployID || makeName(baseName); const deployData: DeploymentStored = { deployID, currentOpID: null, deployOpInfo: {}, stateDirs: [], }; try { await server.set(dpath(deployID), deployData, { mustCreate: true }); break; } catch (err) { if (isServerPathExists(err) && options.deployID) { throw new UserError(`DeployID '${deployID}' already exists`); } if (!isPathNotFound(err)) throw err; // continue } } const deployment = new DeploymentImpl(deployID, server); await deployment.init(); return deployment; } export async function loadDeployment(server: AdaptServer, deployID: string): Promise<Deployment> { try { // Validate that the deployment exists await server.get(dpath(deployID)); } catch (err) { if (!isPathNotFound(err)) throw err; throw new UserError(`Deployment '${deployID}' does not exist`); } const deployment = new DeploymentImpl(deployID, server); await deployment.init(); return deployment; } export async function destroyDeployment(server: AdaptServer, deployID: string): Promise<void> { let history: HistoryStore | undefined; const errs: string[] = []; try { history = await server.historyStore(dpath(deployID), false); } catch (err) { if (!isPathNotFound(err)) throw err; // Not an error if the store is not found. If there's no entry // for this deployID, server.delete will give the right error to the // caller. } try { await server.delete(dpath(deployID)); } catch (err) { errs.push(err.message || err.toString()); } try { if (history) await history.destroy(); } catch (err) { errs.push(err.message || err.toString()); } if (errs.length > 0) { const msg = `Error deleting deployment '${deployID}': ` + errs.join(" and "); throw new Error(msg); } } export async function listDeploymentIDs(server: AdaptServer): Promise<string[]> { try { const deps = await listDeployments(server); return deps.map((dep) => dep.deployID); } catch (err) { throw new Error(`Error listing deployments: ${err}`); } } export async function listDeployments(server: AdaptServer): Promise<DeploymentInfo[]> { try { const deps = await server.get(deploymentPath); return Object.keys(deps).map((key) => ({ deployID: deps[key].deployID })); } catch (err) { // deploymentPath may not have been set yet. if (isPathNotFound(err)) return []; throw new Error(`Error listing deployments: ${err}`); } } class DeploymentImpl implements Deployment { private historyStore_?: HistoryStore; private basePath_: string; constructor(public deployID: string, private server: AdaptServer) { this.basePath_ = dpath(this.deployID); } init = async () => { this.historyStore_ = await this.server.historyStore(this.basePath_, true); } getDataDir = (withStatus: HistoryStatus) => this.historyStore.getDataDir(withStatus); releaseDataDir = () => this.historyStore.releaseDataDir(); commitEntry = (toStore: HistoryEntry) => this.historyStore.commitEntry(toStore); historyEntry = (name: string) => this.historyStore.historyEntry(name); lastEntry = (withStatus: HistoryStatus) => this.historyStore.last(withStatus); async status(stepID: DeployStepID): Promise<DeployStepInfo>; async status(stepID: DeployStepID, info: Partial<DeployStepInfo>): Promise<void>; async status(stepID: DeployStepID, info?: Partial<DeployStepInfo>): Promise<DeployStepInfo | void> { const path = this.stepInfoPath(stepID); if (info !== undefined) { // Set return withLock(this.server, async (lock) => { await this.assertCurrent(stepID, lock); const cur = await this.server.get(path, { lock }); await this.server.set(path, { ...cur, ...info }, { lock }); return; }); } // Get try { const i: DeployStepInfo = await this.server.get(path); return cloneDeep(i); } catch (err) { if (!isPathNotFound(err)) throw err; throw new DeployStepIDNotFound(stepID.deployOpID, stepID.deployStepNum); } } async elementStatus(stepID: DeployStepID, elementID: ElementID): Promise<ElementStatus>; async elementStatus(stepID: DeployStepID, statusMap: ElementStatusMap): Promise<void>; async elementStatus(stepID: DeployStepID, idOrMap: ElementID | ElementStatusMap): Promise<ElementStatus | void> { const path = this.stepInfoPath(stepID) + `/elementStatus`; return withLock(this.server, async (lock) => { // Get if (typeof idOrMap === "string") { await this.currentOpID(lock); // Throws if currentOpID===null try { return await this.server.get(`${path}/${idOrMap}`, { lock }); } catch (err) { if (!isPathNotFound(err)) throw err; throw new Error(`ElementID '${idOrMap}' not found`); } } // Set await this.assertCurrent(stepID, lock); let old: ElementStatusMap = {}; try { old = await this.server.get(path, { lock }); } catch (err) { if (!isPathNotFound(err)) throw err; // Fall through } await this.server.set(path, { ...old, ...idOrMap }, { lock }); }); } async newOpID(): Promise<DeployOpID> { return withLock(this.server, async (lock) => { const opPath = this.basePath_ + "/currentOpID"; const cur: DeploymentStored["currentOpID"] = await this.server.get(opPath, { lock }); const next = cur == null ? 0 : cur + 1; const stepPath = this.stepNumPath(next); await this.server.set(stepPath, null, { lock }); await this.server.set(opPath, next, { lock }); return next; }); } async currentOpID(lock?: ServerLock): Promise<DeployOpID> { const path = this.basePath_ + "/currentOpID"; const cur: DeploymentStored["currentOpID"] = await this.server.get(path, { lock }); if (cur == null) throw new DeploymentNotActive(this.deployID); return cur; } async newStepID(deployOpID: DeployOpID): Promise<DeployStepID> { return withLock(this.server, async (lock) => { await this.assertCurrentOpID(deployOpID, lock); const cur = await this.currentStepNum(deployOpID, lock); const deployStepNum = cur == null ? 0 : cur + 1; const info: DeployStepInfo = { deployStatus: DeployStatus.Initial, goalStatus: DeployStatus.Initial, elementStatus: {}, }; const step: DeployStepID = { deployOpID, deployStepNum, }; await this.server.set(this.stepInfoPath(step), info, { lock }); await this.server.set(this.stepNumPath(deployOpID), deployStepNum, { lock }); return step; }); } async currentStepID(deployOpID: DeployOpID): Promise<DeployStepID> { return withLock(this.server, async (lock) => { await this.assertCurrentOpID(deployOpID, lock); const deployStepNum = await this.currentStepNum(deployOpID, lock); if (deployStepNum == null) { throw new DeploymentOpIDNotActive(this.deployID, deployOpID); } return { deployOpID, deployStepNum, }; }); } private stepInfoPath(stepID: DeployStepID) { return `${this.basePath_}/deployOpInfo/` + `${stepID.deployOpID}/${stepID.deployStepNum}`; } private stepNumPath(opID: DeployOpID) { return this.basePath_ + `/deployOpInfo/${opID}/currentStepNum`; } private get historyStore() { if (this.historyStore_ == null) throw new InternalError(`null historyStore`); return this.historyStore_; } private async currentStepNum(opID: DeployOpID, lock: ServerLock): Promise<number | null> { const path = this.stepNumPath(opID); return this.server.get(path, { lock }); } private async assertCurrentOpID(opID: DeployOpID, lock: ServerLock) { const current = await this.currentOpID(lock); if (opID !== current) { throw new Error(`Requested DeployOpID (${opID}) is not current (${current})`); } } private async assertCurrent(stepID: DeployStepID, lock: ServerLock) { await this.assertCurrentOpID(stepID.deployOpID, lock); const current = await this.currentStepNum(stepID.deployOpID, lock); if (current == null) { throw new DeploymentOpIDNotActive(this.deployID, stepID.deployOpID); } if (stepID.deployStepNum !== current) { throw new Error(`Requested DeployStepID ` + `(${stepID.deployOpID}.${stepID.deployStepNum}) is not ` + `current (${stepID.deployOpID}.${current})`); } } }
the_stack
import * as core from '@actions/core'; import * as github from '@actions/github'; import {wasLineAddedInPR, GHFile} from './git'; const pkg = require('../package.json'); const USER_AGENT = `${pkg.name}/${pkg.version} (${pkg.bugs.url})`; type ChecksCreateParamsOutputAnnotations = any; type Severity = 'suggestion' | 'warning' | 'error'; interface Alert { readonly Check: string; readonly Line: number; readonly Message: string; readonly Span: [number, number]; readonly Severity: Severity; } interface ValeJSON { readonly [propName: string]: ReadonlyArray<Alert>; } interface Stats { suggestions: number; warnings: number; errors: number; } interface CheckOptions { token: string; owner: string; repo: string; name: string; head_sha: string; started_at: string; // ISO8601 context: { vale: string; }; } const onlyAnnotateModifiedLines = core.getInput('onlyAnnotateModifiedLines') != 'false'; /** * CheckRunner handles all communication with GitHub's Check API. * * See https://developer.github.com/v3/checks. */ export class CheckRunner { private annotations: Array<ChecksCreateParamsOutputAnnotations>; private stats: Stats; private modified: Record<string, GHFile>; constructor(modified: Record<string, GHFile>) { this.annotations = []; this.stats = { suggestions: 0, warnings: 0, errors: 0 }; this.modified = modified; } /** * Convert Vale's JSON `output` into an array of annotations. */ public makeAnnotations(output: string): void { const alerts = JSON.parse(output) as ValeJSON; for (const filename of Object.getOwnPropertyNames(alerts)) { for (const alert of alerts[filename]) { if ( onlyAnnotateModifiedLines && !wasLineAddedInPR(this.modified[filename], alert.Line) ) { continue; } switch (alert.Severity) { case 'suggestion': this.stats.suggestions += 1; break; case 'warning': this.stats.warnings += 1; break; case 'error': this.stats.errors += 1; break; default: break; } this.annotations.push(CheckRunner.makeAnnotation(filename, alert)); } } } /** * Show the results of running Vale. * * NOTE: Support for annotation is still a WIP: * * - https://github.com/actions/toolkit/issues/186 * - https://github.com/actions-rs/clippy-check/issues/2 */ public async executeCheck(options: CheckOptions): Promise<void> { core.info(`Vale: ${this.getSummary()}`); const client = github.getOctokit(options.token, { userAgent: USER_AGENT }); let checkRunId: number; try { checkRunId = await this.createCheck(client, options); } catch (error) { // NOTE: `GITHUB_HEAD_REF` is set only for forked repos. if (process.env.GITHUB_HEAD_REF) { core.warning( `Unable to create annotations; printing Vale alerts instead.` ); this.dumpToStdout(); if (this.getConclusion() == 'failure') { throw new Error('Exiting due to Vale errors'); } return; } else { throw error; } } try { if (this.isSuccessCheck()) { // We don't have any alerts to report ... await this.successCheck(client, checkRunId, options); } else { // Vale found some alerts to report ... await this.runUpdateCheck(client, checkRunId, options); } } catch (error) { await this.cancelCheck(client, checkRunId, options); throw error; } } /** * Create our initial check run. * * See https://developer.github.com/v3/checks/runs/#create-a-check-run. */ private async createCheck( client: any, options: CheckOptions ): Promise<number> { const response = await client.checks.create({ owner: options.owner, repo: options.repo, name: options.name, head_sha: options.head_sha, status: 'in_progress' }); if (response.status != 201) { core.warning(`[createCheck] Unexpected status code ${response.status}`); } return response.data.id; } /** * End our check run. * * NOTE: The Checks API only allows 50 annotations per request, so we send * multiple "buckets" if we have more than 50. */ private async runUpdateCheck( client: any, checkRunId: number, options: CheckOptions ): Promise<void> { let annotations = this.getBucket(); while (annotations.length > 0) { let req: any = { owner: options.owner, repo: options.repo, name: options.name, check_run_id: checkRunId, output: { title: options.name, summary: this.getSummary(), text: this.getText(options.context), annotations: annotations } }; if (this.annotations.length > 0) { // There will be more annotations later ... req.status = 'in_progress'; } else { req.status = 'completed'; req.conclusion = this.getConclusion(); req.completed_at = new Date().toISOString(); } const response = await client.checks.update(req); if (response.status != 200) { core.warning(`[updateCheck] Unexpected status code ${response.status}`); } annotations = this.getBucket(); } return; } /** * Indicate that no alerts were found. */ private async successCheck( client: any, checkRunId: number, options: CheckOptions ): Promise<void> { let req: any = { owner: options.owner, repo: options.repo, name: options.name, check_run_id: checkRunId, status: 'completed', conclusion: this.getConclusion(), completed_at: new Date().toISOString(), output: { title: options.name, summary: this.getSummary(), text: this.getText(options.context) } }; const response = await client.checks.update(req); if (response.status != 200) { core.warning(`[successCheck] Unexpected status code ${response.status}`); } return; } /** * Something went wrong; cancel the check run and report the exception. */ private async cancelCheck( client: any, checkRunId: number, options: CheckOptions ): Promise<void> { let req: any = { owner: options.owner, repo: options.repo, name: options.name, check_run_id: checkRunId, status: 'completed', conclusion: 'cancelled', completed_at: new Date().toISOString(), output: { title: options.name, summary: 'Unhandled error', text: 'Check was cancelled due to unhandled error. Check the Action logs for details.' } }; const response = await client.checks.update(req); if (response.status != 200) { core.warning(`[cancelCheck] Unexpected status code ${response.status}`); } return; } /** * Print Vale's output to stdout. * * NOTE: This should only happen if we can't create annotations (see * `executeCheck` above). * * TODO: Nicer formatting? */ private dumpToStdout() { console.dir(this.annotations, {depth: null, colors: true}); } /** * Create buckets of at most 50 annotations for the API. * * See https://developer.github.com/v3/checks/runs/#output-object. */ private getBucket(): Array<ChecksCreateParamsOutputAnnotations> { let annotations: Array<ChecksCreateParamsOutputAnnotations> = []; while (annotations.length < 50) { const annotation = this.annotations.pop(); if (annotation) { annotations.push(annotation); } else { break; } } core.debug(`Prepared next annotations bucket, ${annotations.length} size`); return annotations; } /** * Report a summary of the alerts found by Vale. */ private getSummary(): string { const sn = this.stats.suggestions; const wn = this.stats.warnings; const en = this.stats.errors; return `Found ${sn} suggestion(s), ${wn} warning(s), and ${en} error(s).`; } /** * Create a Markdown-formatted summary of the alerts found by Vale. */ private getText(context: CheckOptions['context']): string { return `Vale ${context.vale}`; } /** * If Vale found an error-level alerts, we mark the check result as "failure". */ private getConclusion(): string { if (this.stats.errors > 0) { return 'failure'; } else { return 'success'; } } /** * No alerts found. */ private isSuccessCheck(): boolean { return ( this.stats.suggestions == 0 && this.stats.warnings == 0 && this.stats.errors == 0 ); } /** * Convert Vale-formatted JSON object into an array of annotations: * * { * "README.md": [ * { * "Check": "DocsStyles.BadWords", * "Description": "", * "Line": 6, * "Link": "", * "Message": "'slave' should be changed", * "Severity": "error", * "Span": [ * 22, * 26 * ], * "Hide": false, * "Match": "slave" * } * ] * } * * See https://developer.github.com/v3/checks/runs/#annotations-object. */ static makeAnnotation( name: string, alert: Alert ): ChecksCreateParamsOutputAnnotations { let annotation_level: ChecksCreateParamsOutputAnnotations['annotation_level']; switch (alert.Severity) { case 'suggestion': annotation_level = 'notice'; break; case 'warning': annotation_level = 'warning'; break; default: annotation_level = 'failure'; break; } let annotation: ChecksCreateParamsOutputAnnotations = { path: name, start_line: alert.Line, end_line: alert.Line, start_column: alert.Span[0], end_column: alert.Span[1], annotation_level: annotation_level, title: `[${alert.Severity}] ${alert.Check}`, message: alert.Message }; return annotation; } }
the_stack
import * as grpc from '@grpc/grpc-js'; import { filterNullAndUndefined, normalizeTlsConfig, TLSConfig } from '@temporalio/internal-non-workflow-common'; import { AsyncLocalStorage } from 'async_hooks'; import type { RPCImpl } from 'protobufjs'; import { isServerErrorResponse, ServiceError } from './errors'; import { defaultGrpcRetryOptions, makeGrpcRetryInterceptor } from './grpc-retry'; import pkg from './pkg'; import { CallContext, Metadata, WorkflowService } from './types'; /** * GRPC + Temporal server connection options */ export interface ConnectionOptions { /** * Server hostname and optional port. * Port defaults to 7233 if address contains only host. * * @default localhost:7233 */ address?: string; /** * TLS configuration. * Pass a falsy value to use a non-encrypted connection or `true` or `{}` to * connect with TLS without any customization. * * Either {@link credentials} or this may be specified for configuring TLS */ tls?: TLSConfig | boolean | null; /** * Channel credentials, create using the factory methods defined {@link https://grpc.github.io/grpc/node/grpc.credentials.html | here} * * Either {@link tls} or this may be specified for configuring TLS */ credentials?: grpc.ChannelCredentials; /** * GRPC Channel arguments * * @see option descriptions {@link https://grpc.github.io/grpc/core/group__grpc__arg__keys.html | here} */ channelArgs?: grpc.ChannelOptions; /** * Grpc interceptors which will be applied to every RPC call performed by this connection. By * default, an interceptor will be included which automatically retries retryable errors. If you * do not wish to perform automatic retries, set this to an empty list (or a list with your own * interceptors). */ interceptors?: grpc.Interceptor[]; /** * Optional mapping of gRPC metadata (HTTP headers) to send with each request to the server. * * In order to dynamically set metadata, use {@link Connection.withMetadata} */ metadata?: Metadata; /** * Milliseconds to wait until establishing a connection with the server. * * Used either when connecting eagerly with {@link Connection.connect} or * calling {@link Connection.ensureConnected}. * * @format {@link https://www.npmjs.com/package/ms | ms} formatted string * @default 10 seconds */ connectTimeout?: number | string; } export type ConnectionOptionsWithDefaults = Required<Omit<ConnectionOptions, 'tls' | 'connectTimeout'>> & { connectTimeoutMs: number; }; export const LOCAL_TARGET = '127.0.0.1:7233'; export function defaultConnectionOpts(): ConnectionOptionsWithDefaults { return { address: LOCAL_TARGET, credentials: grpc.credentials.createInsecure(), channelArgs: {}, interceptors: [makeGrpcRetryInterceptor(defaultGrpcRetryOptions())], metadata: {}, connectTimeoutMs: 10_000, }; } /** * - Convert {@link ConnectionOptions.tls} to {@link grpc.ChannelCredentials} * - Add the grpc.ssl_target_name_override GRPC {@link ConnectionOptions.channelArgs | channel arg} * - Add default port to address if port not specified */ function normalizeGRPCConfig(options?: ConnectionOptions): ConnectionOptions { const { tls: tlsFromConfig, credentials, ...rest } = options || {}; if (rest.address) { // eslint-disable-next-line prefer-const let [host, port] = rest.address.split(':', 2); port = port || '7233'; rest.address = `${host}:${port}`; } const tls = normalizeTlsConfig(tlsFromConfig); if (tls) { if (credentials) { throw new TypeError('Both `tls` and `credentials` ConnectionOptions were provided'); } return { ...rest, credentials: grpc.credentials.createSsl( tls.serverRootCACertificate, tls.clientCertPair?.key, tls.clientCertPair?.crt ), channelArgs: { ...rest.channelArgs, ...(tls.serverNameOverride ? { 'grpc.ssl_target_name_override': tls.serverNameOverride, 'grpc.default_authority': tls.serverNameOverride, } : undefined), }, }; } else { return rest; } } export interface RPCImplOptions { serviceName: string; client: grpc.Client; callContextStorage: AsyncLocalStorage<CallContext>; interceptors?: grpc.Interceptor[]; } export interface ConnectionCtorOptions { readonly options: ConnectionOptionsWithDefaults; readonly client: grpc.Client; /** * Raw gRPC access to the Temporal service. * * **NOTE**: The namespace provided in {@link options} is **not** automatically set on requests made to the service. */ readonly workflowService: WorkflowService; readonly callContextStorage: AsyncLocalStorage<CallContext>; } /** * Client connection to the Temporal Service * * NOTE: Connections are expensive to construct and should be reused. * Make sure to `close()` any unused connections to avoid leaking resources. */ export class Connection { public static readonly Client = grpc.makeGenericClientConstructor({}, 'WorkflowService', {}); public readonly options: ConnectionOptionsWithDefaults; protected readonly client: grpc.Client; /** * Used to ensure `ensureConnected` is called once. */ protected connectPromise?: Promise<void>; /** * Raw gRPC access to the Temporal service. */ public readonly workflowService: WorkflowService; readonly callContextStorage: AsyncLocalStorage<CallContext>; protected static createCtorOptions(options?: ConnectionOptions): ConnectionCtorOptions { const optionsWithDefaults = { ...defaultConnectionOpts(), ...filterNullAndUndefined(normalizeGRPCConfig(options)), }; // Allow overriding this optionsWithDefaults.metadata['client-name'] ??= 'temporal-typescript'; optionsWithDefaults.metadata['client-version'] ??= pkg.version; const client = new this.Client( optionsWithDefaults.address, optionsWithDefaults.credentials, optionsWithDefaults.channelArgs ); const callContextStorage = new AsyncLocalStorage<CallContext>(); callContextStorage.enterWith({ metadata: optionsWithDefaults.metadata }); const rpcImpl = this.generateRPCImplementation({ serviceName: 'temporal.api.workflowservice.v1.WorkflowService', client, callContextStorage, interceptors: optionsWithDefaults?.interceptors, }); const workflowService = WorkflowService.create(rpcImpl, false, false); return { client, callContextStorage, workflowService, options: optionsWithDefaults, }; } /** * Ensure connection can be established. * * This method's result is memoized to ensure it runs only once. * * Calls WorkflowService.getSystemInfo internally. */ async ensureConnected(): Promise<void> { if (this.connectPromise == null) { const deadline = Date.now() + this.options.connectTimeoutMs; this.connectPromise = (async () => { await this.untilReady(deadline); try { await this.withDeadline(deadline, () => this.workflowService.getSystemInfo({})); } catch (err) { if (isServerErrorResponse(err)) { // Ignore old servers if (err.code !== grpc.status.UNIMPLEMENTED) { throw new ServiceError('Failed to connect to Temporal server', { cause: err }); } } else { throw err; } } })(); } return this.connectPromise; } /** * Create a lazy Connection instance. * * This method does not verify connectivity with the server, it is recommended to use * {@link connect} instead. */ static lazy(options?: ConnectionOptions): Connection { return new this(this.createCtorOptions(options)); } /** * Establish a connection with the server and return a Connection instance. * * This is the preferred method of creating connections as it verifies connectivity. */ static async connect(options?: ConnectionOptions): Promise<Connection> { const conn = this.lazy(options); await conn.ensureConnected(); return conn; } protected constructor({ options, client, workflowService, callContextStorage }: ConnectionCtorOptions) { this.options = options; this.client = client; this.workflowService = workflowService; this.callContextStorage = callContextStorage; } protected static generateRPCImplementation({ serviceName, client, callContextStorage, interceptors, }: RPCImplOptions): RPCImpl { return (method: { name: string }, requestData: any, callback: grpc.requestCallback<any>) => { const metadataContainer = new grpc.Metadata(); const { metadata, deadline } = callContextStorage.getStore() ?? {}; if (metadata != null) { for (const [k, v] of Object.entries(metadata)) { metadataContainer.set(k, v); } } return client.makeUnaryRequest( `/${serviceName}/${method.name}`, (arg: any) => arg, (arg: any) => arg, requestData, metadataContainer, { interceptors, deadline }, callback ); }; } /** * Set the deadline for any service requests executed in `fn`'s scope. */ async withDeadline<R>(deadline: number | Date, fn: () => Promise<R>): Promise<R> { const cc = this.callContextStorage.getStore(); return await this.callContextStorage.run({ deadline, metadata: cc?.metadata }, fn); } /** * Set metadata for any service requests executed in `fn`'s scope. * * The provided metadata is merged on top of any existing metadata in current scope * including metadata provided in {@link ConnectionOptions.metadata} * * @returns returned value of `fn` * * @example * * ```ts * await conn.withMetadata({ apiKey: 'secret' }, () => * conn.withMetadata({ otherKey: 'set' }, () => client.start(options))) * ); * ``` */ async withMetadata<R>(metadata: Metadata, fn: () => Promise<R>): Promise<R> { const cc = this.callContextStorage.getStore(); metadata = { ...cc?.metadata, ...metadata }; return await this.callContextStorage.run({ metadata, deadline: cc?.deadline }, fn); } /** * Wait for successful connection to the server. * * @see https://grpc.github.io/grpc/node/grpc.Client.html#waitForReady__anchor */ protected async untilReady(deadline: number): Promise<void> { return new Promise<void>((resolve, reject) => { this.client.waitForReady(deadline, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } // This method is async for uniformity with NativeConnection which could be used in the future to power clients /** * Close the underlying gRPC client. * * Make sure to call this method to ensure proper resource cleanup. */ public async close(): Promise<void> { this.client.close(); } }
the_stack
import * as React from "react"; import * as data from "./data"; import * as simulator from "./simulator"; import { DebuggerTable, DebuggerTableRow } from "./debuggerTable"; const MAX_VARIABLE_LENGTH = 20; interface ScopeVariables { title: string; variables: Variable[]; key?: string; } interface Variable { name: string; value: any; id?: number; prevValue?: any; children?: Variable[]; } interface PreviewState { id: number; top: number; left: number; } interface DebuggerVariablesProps { apis: pxt.Map<pxtc.SymbolInfo>; sequence: number; breakpoint?: pxsim.DebuggerBreakpointMessage; filters?: string[] activeFrame?: number; } interface DebuggerVariablesState { globalFrame: ScopeVariables; stackFrames: ScopeVariables[]; nextID: number; renderedSequence?: number; frozen?: boolean; preview: PreviewState | null; } export class DebuggerVariables extends data.Component<DebuggerVariablesProps, DebuggerVariablesState> { constructor(props: DebuggerVariablesProps) { super(props); this.state = { globalFrame: { title: lf("Globals"), variables: [] }, stackFrames: [], nextID: 0, preview: null }; } clear() { this.setState({ globalFrame: { title: this.state.globalFrame.title, variables: [] }, stackFrames: [], preview: null }); } update(frozen = false) { this.setState({ frozen, preview: frozen ? null : this.state.preview }); } componentDidUpdate(prevProps: DebuggerVariablesProps) { if (this.props.breakpoint) { if (this.props.sequence != this.state.renderedSequence) { this.updateVariables(this.props.breakpoint, this.props.filters); } } else if (!this.state.frozen) { this.update(true); } } renderCore() { const { globalFrame, stackFrames, frozen, preview } = this.state; const { activeFrame, breakpoint } = this.props; const variableTableHeader = lf("Variables"); let variables = globalFrame.variables; // Add in the local variables. // TODO: Handle callstack if (stackFrames && stackFrames.length && activeFrame !== undefined) { variables = stackFrames[activeFrame].variables.concat(variables); } let placeholderText: string; if (frozen) { placeholderText = lf("Code is running..."); } else if (!variables.length && !breakpoint?.exceptionMessage) { placeholderText = lf("No variables to show"); } const tableRows = placeholderText ? [] : this.renderVars(variables); if (breakpoint?.exceptionMessage && !frozen) { tableRows.unshift(<DebuggerTableRow leftText={lf("Exception:")} leftClass="exception" key="exception-message" rightText={truncateLength(breakpoint.exceptionMessage)} rightTitle={breakpoint.exceptionMessage} />); } const previewVar = this.getVariableById(preview?.id); const previewLabel = previewVar && lf("Current value for '{0}'", previewVar.name); return <div> <DebuggerTable header={variableTableHeader} placeholderText={placeholderText}> {tableRows} </DebuggerTable> { preview && <div id="debugger-preview" role="tooltip" className="debugger-preview" ref={this.handlePreviewRef} tabIndex={0} aria-label={previewLabel} style={{ top: `${preview.top}px`, left: `${preview.left}px` }}> {renderValue(previewVar.value)} </div> } </div> } renderVars(vars: Variable[], depth = 0, result: JSX.Element[] = []) { const previewed = this.state.preview?.id; vars.forEach(varInfo => { const valueString = renderValue(varInfo.value); const typeString = variableType(varInfo); result.push(<DebuggerTableRow key={varInfo.id} describedBy={varInfo.id === previewed ? "debugger-preview" : undefined} refID={varInfo.id} icon={(varInfo.value && varInfo.value.hasFields) ? (varInfo.children ? "down triangle" : "right triangle") : undefined} leftText={varInfo.name + ":"} leftTitle={varInfo.name} leftClass={varInfo.prevValue !== undefined ? "changed" : undefined} rightText={truncateLength(valueString)} rightTitle={shouldShowValueOnHover(typeString) ? valueString : undefined} rightClass={typeString} onClick={this.handleComponentClick} onValueClick={this.handleValueClick} depth={depth} />) if (varInfo.children) { this.renderVars(varInfo.children, depth + 1, result); } }); return result; } updateVariables( breakpoint: pxsim.DebuggerBreakpointMessage, filters?: string[] ) { const { globals, environmentGlobals, stackframes } = breakpoint; if (!globals && !environmentGlobals) { // freeze the ui this.update(true) return; } let nextId = 0; const updatedGlobals = updateScope(this.state.globalFrame, globals); if (filters) { updatedGlobals.variables = updatedGlobals.variables.filter(v => filters.indexOf(v.name) !== -1) } // inject unfiltered environment variables if (environmentGlobals) updatedGlobals.variables = updatedGlobals.variables.concat(variablesToVariableList(environmentGlobals)); assignVarIds(updatedGlobals.variables); let updatedFrames: ScopeVariables[]; if (stackframes) { const oldFrames = this.state.stackFrames; updatedFrames = stackframes.map((sf, index) => { const key = sf.breakpointId + "_" + index; for (const frame of oldFrames) { if (frame.key === key) return updateScope(frame, sf.locals, getArgArray(sf.arguments)); } return updateScope({ key, title: sf.funcInfo.functionName, variables: [] }, sf.locals, getArgArray(sf.arguments)) }); updatedFrames.forEach(sf => assignVarIds(sf.variables)); } this.setState({ globalFrame: updatedGlobals, stackFrames: updatedFrames || [], nextID: nextId, renderedSequence: this.props.sequence, frozen: false }); function getArgArray(info: pxsim.FunctionArgumentsInfo): Variable[] { if (info) { if (info.thisParam != null) { return [{ name: "this", value: info.thisParam }, ...info.params] } else { return info.params; } } return [] } function assignVarIds(vars: Variable[]) { vars.forEach(v => { v.id = nextId++ if (v.children) assignVarIds(v.children) }); } } protected getVariableById(id: number) { if (id === null) return null; for (const v of this.getFullVariableList()) { if (v.id === id) { return v; } } return null; } protected handleComponentClick = (e: React.SyntheticEvent<HTMLDivElement>, component: DebuggerTableRow) => { if (this.state.frozen) return; const variable = this.getVariableById(component.props.refID as number); if (variable) { this.toggle(variable); if (this.state.preview !== null) { this.setState({ preview: null }); } } } protected handleValueClick = (e: React.SyntheticEvent<HTMLDivElement>, component: DebuggerTableRow) => { if (this.state.frozen) return; const id = component.props.refID; const bb = (e.target as HTMLDivElement).getBoundingClientRect(); this.setState({ preview: { id: id as number, top: bb.top, left: bb.left } }); } protected handlePreviewRef = (ref: HTMLDivElement) => { if (ref) { const previewed = this.state.preview; ref.focus(); ref.addEventListener("blur", () => { if (this.state.preview?.id === previewed.id) { this.setState({ preview: null }); } }); const select = window.getSelection(); select.removeAllRanges(); const range = document.createRange(); range.selectNodeContents(ref); select.addRange(range); } } protected getFullVariableList() { let result: Variable[] = []; collectVariables(this.state.globalFrame.variables); if (this.state.stackFrames) this.state.stackFrames.forEach(sf => collectVariables(sf.variables)); return result; function collectVariables(vars: Variable[]) { vars.forEach(v => { result.push(v); if (v.children) { collectVariables(v.children) } }); } } private toggle(v: Variable) { // We have to take care of the logic for nested looped variables. Currently they break this implementation. if (v.children) { delete v.children; this.setState({ globalFrame: this.state.globalFrame }) } else { if (!v.value || !v.value.id) return; // We filter the getters we want to call for this variable. let allApis = this.props.apis; let matcher = new RegExp("^((.+\.)?" + v.value.type + ")\."); let potentialKeys = Object.keys(allApis).filter(key => matcher.test(key)); let fieldsToGet: string[] = []; potentialKeys.forEach(key => { let symbolInfo = allApis[key]; if (!key.endsWith("@set") && symbolInfo && symbolInfo.attributes.callInDebugger) { fieldsToGet.push(key); } }); simulator.driver.variablesAsync(v.value.id, fieldsToGet) .then((msg: pxsim.VariablesMessage) => { if (msg && msg.variables) { let nextID = this.state.nextID; v.children = Object.keys(msg.variables).map(key => ({ name: key, value: msg.variables[key], id: nextID++ })) this.setState({ globalFrame: this.state.globalFrame, nextID }) } }) } } } function variablesToVariableList(newVars: pxsim.Variables) { const current = Object.keys(newVars).map(varName => ({ name: fixVarName(varName), value: newVars[varName] })); return current; } function updateScope(lastScope: ScopeVariables, newVars: pxsim.Variables, params?: Variable[]): ScopeVariables { let current = variablesToVariableList(newVars); if (params) { current = params.concat(current); } return { ...lastScope, variables: getUpdatedVariables(lastScope.variables, current) }; } function fixVarName(name: string) { return name.replace(/___\d+$/, ""); } function getUpdatedVariables(previous: Variable[], current: Variable[]): Variable[] { return current.map(v => { const prev = getVariable(previous, v); if (prev && prev.value && !prev.value.id && prev.value !== v.value) { return { ...v, prevValue: prev.value } } return v }); }; function getVariable(variables: Variable[], value: Variable) { for (let i = 0; i < variables.length; i++) { if (variables[i].name === value.name) { return variables[i]; } } return undefined; } function renderValue(v: any): string { let sv = ''; let type = typeof v; switch (type) { case "undefined": sv = "undefined"; break; case "number": sv = v + ""; break; case "boolean": sv = v + ""; break; case "string": sv = JSON.stringify(v); break; case "object": if (v == null) sv = "null"; else if (v.text) sv = v.text; else if (v.id && v.preview) return v.preview; else if (v.id !== undefined) sv = "(object)" else sv = "(unknown)" break; } return sv; } function truncateLength(varstr: string) { let remaining = MAX_VARIABLE_LENGTH - 3; // acount for ... let hasQuotes = false; if (varstr.indexOf('"') == 0) { remaining -= 2; hasQuotes = true; varstr = varstr.substring(1, varstr.length - 1); } if (varstr.length > remaining) varstr = varstr.substring(0, remaining) + '...'; if (hasQuotes) { varstr = '"' + varstr + '"' } return varstr; } function variableType(variable: Variable): string { let val = variable.value; if (val == null) return "undefined"; let type = typeof val switch (type) { case "string": case "number": case "boolean": return type; case "object": if (val.type) return val.type; if (val.preview) return val.preview; if (val.text) return val.text; return "object"; default: return "unknown"; } } function shouldShowValueOnHover(type: string): boolean { switch (type) { case "string": case "number": case "boolean": case "array": return true; default: return false; } }
the_stack
import { ReactiveElement, PropertyValues, ReactiveControllerHost, } from '@lit/reactive-element'; import {ResizeController, ResizeControllerConfig} from '../resize_controller'; import {generateElementName, nextFrame} from './test-helpers'; import {assert} from '@esm-bundle/chai'; // Note, since tests are not built with production support, detect DEV_MODE // by checking if warning API is available. const DEV_MODE = !!ReactiveElement.enableWarning; if (DEV_MODE) { ReactiveElement.disableWarning?.('change-in-update'); } (window.ResizeObserver ? suite : suite.skip)('ResizeController', () => { let container: HTMLElement; interface TestElement extends ReactiveElement { observer: ResizeController; observerValue: unknown; resetObserverValue: () => void; changeDuringUpdate?: () => void; } const defineTestElement = ( getControllerConfig: ( host: ReactiveControllerHost ) => ResizeControllerConfig ) => { class A extends ReactiveElement { observer: ResizeController; observerValue: unknown; changeDuringUpdate?: () => void; constructor() { super(); const config = getControllerConfig(this); this.observer = new ResizeController(this, config); } override update(props: PropertyValues) { super.update(props); if (this.changeDuringUpdate) { this.changeDuringUpdate(); } } override updated() { this.observerValue = this.observer.value; } resetObserverValue() { this.observer.value = this.observerValue = undefined; } } customElements.define(generateElementName(), A); return A; }; const renderTestElement = async (Ctor: typeof HTMLElement) => { const el = new Ctor() as TestElement; container.appendChild(el); await el.updateComplete; return el; }; let size = 1; const resizeElement = (el: HTMLElement, x?: number) => { el.style.display = 'block'; el.style.position = 'absolute'; const d = x !== undefined ? x : size++; el.style.height = el.style.width = `${d}px`; }; const resizeComplete = async () => { await nextFrame(); await nextFrame(); }; const getTestElement = async ( getControllerConfig: ( host: ReactiveControllerHost ) => ResizeControllerConfig = () => ({}) ) => { const ctor = defineTestElement(getControllerConfig); const el = await renderTestElement(ctor); return el; }; setup(() => { container = document.createElement('div'); document.body.appendChild(container); }); teardown(() => { if (container && container.parentNode) { container.parentNode.removeChild(container); } }); test('can observe changes', async () => { const el = await getTestElement(); // Reports initial change by default assert.isTrue(el.observerValue); // Reports attribute change el.resetObserverValue(); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); // Reports another attribute change el.resetObserverValue(); el.requestUpdate(); await resizeComplete(); assert.isUndefined(el.observerValue); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); }); test('skips initial changes when `skipInitial` is `true`', async () => { const el = await getTestElement(() => ({ skipInitial: true, })); // Does not reports initial change when `skipInitial` is set assert.isUndefined(el.observerValue); // Reports subsequent attribute change when `skipInitial` is set el.resetObserverValue(); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); // Reports another attribute change el.resetObserverValue(); el.requestUpdate(); await resizeComplete(); assert.isUndefined(el.observerValue); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); }); test('observation managed via connection', async () => { const el = await getTestElement(() => ({ skipInitial: true, })); assert.isUndefined(el.observerValue); // Does not report change after element removed. el.remove(); resizeElement(el); // Reports change after element re-connected since this changes its size! container.appendChild(el); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change on mutation when element is connected el.resetObserverValue(); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); }); test('can observe external element', async () => { const d = document.createElement('div'); container.appendChild(d); const el = await getTestElement(() => ({ target: d, skipInitial: true, })); assert.equal(el.observerValue, undefined); resizeElement(d); await resizeComplete(); assert.isTrue(el.observerValue); // Change again el.resetObserverValue(); resizeElement(d); await resizeComplete(); assert.isTrue(el.observerValue); }); test('can manage value via `callback`', async () => { const el = await getTestElement(() => ({ callback: (entries: ResizeObserverEntry[]) => entries[0]?.contentRect.width ?? true, })); resizeElement(el, 100); await resizeComplete(); // assert.equal(el.observerValue as number, 100); resizeElement(el, 150); await resizeComplete(); // assert.equal(el.observerValue as number, 150); }); test('can observe changes during update', async () => { const el = await getTestElement(() => ({ callback: (entries: ResizeObserverEntry[]) => entries[0]?.contentRect.width ?? true, })); // Change size during update. let s = 100; el.changeDuringUpdate = () => resizeElement(el, s); el.resetObserverValue(); el.requestUpdate(); await resizeComplete(); assert.equal(el.observerValue as number, 100); // Change size again during update. s = 150; el.resetObserverValue(); el.requestUpdate(); await resizeComplete(); assert.equal(el.observerValue as number, 150); // Update without changing size. el.resetObserverValue(); el.requestUpdate(); await resizeComplete(); assert.isUndefined(el.observerValue); }); test('can call `observe` to observe element', async () => { const el = await getTestElement(); el.resetObserverValue(); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.renderRoot.appendChild(d1); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to observed target. el.resetObserverValue(); resizeElement(d1); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to configured target. el.resetObserverValue(); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); // Can observe another target el.resetObserverValue(); const d2 = document.createElement('div'); el.observer.observe(d2); el.renderRoot.appendChild(d2); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to new observed target. el.resetObserverValue(); resizeElement(d2); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to configured target. el.resetObserverValue(); resizeElement(el); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to first observed target. el.resetObserverValue(); resizeElement(d1); await resizeComplete(); assert.isTrue(el.observerValue); }); test('can specifying target as `null` and call `observe` to observe element', async () => { const el = await getTestElement(() => ({target: null})); el.resetObserverValue(); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.renderRoot.appendChild(d1); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to observed target. el.resetObserverValue(); resizeElement(d1); await resizeComplete(); assert.isTrue(el.observerValue); // Can observe another target el.resetObserverValue(); const d2 = document.createElement('div'); el.observer.observe(d2); el.renderRoot.appendChild(d2); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to new observed target. el.resetObserverValue(); resizeElement(d2); await resizeComplete(); assert.isTrue(el.observerValue); // Reports change to first observed target. el.resetObserverValue(); resizeElement(d1); await resizeComplete(); assert.isTrue(el.observerValue); }); test('observed target respects `skipInitial`', async () => { const el = await getTestElement(() => ({ target: null, skipInitial: true, })); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.renderRoot.appendChild(d1); await resizeComplete(); // Note, appending changes size! assert.isTrue(el.observerValue); // Reports change to observed target. resizeElement(d1); await resizeComplete(); assert.isTrue(el.observerValue); }); test('observed target not re-observed on connection', async () => { const el = await getTestElement(() => ({target: null})); const d1 = document.createElement('div'); // Reports initial changes when observe called. el.observer.observe(d1); el.renderRoot.appendChild(d1); await resizeComplete(); assert.isTrue(el.observerValue); el.resetObserverValue(); await resizeComplete(); el.remove(); // Does not reports change when disconnected. resizeElement(d1); await resizeComplete(); assert.isUndefined(el.observerValue); // Does not report change when re-connected container.appendChild(el); resizeElement(d1); await resizeComplete(); assert.isUndefined(el.observerValue); // Can re-observe after connection. el.observer.observe(d1); resizeElement(d1); await resizeComplete(); assert.isTrue(el.observerValue); }); });
the_stack
export interface HeaderFromValue { /** * Name of the header */ name: string; /** * Value of the header */ value: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/syntax-defs.html#headerfromenv */ export interface HeaderFromEnv { /** * Name of the header */ name: string; /** * Name of the environment variable which holds the value of the header */ value_from_env: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#objectfield */ export interface ObjectField { /** * Description of the Input object type */ description?: string; /** * Name of the Input object type */ name: string; /** * GraphQL type of the Input object type */ type: string; } /** * Type used in exported 'metadata.json' and replace metadata endpoint * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/manage-metadata.html#replace-metadata */ export interface HasuraMetadataV2 { actions?: Action[]; allowlist?: AllowList[]; cron_triggers?: CronTrigger[]; custom_types?: CustomTypes; functions?: CustomFunction[]; query_collections?: QueryCollectionEntry[]; remote_schemas?: RemoteSchema[]; tables: TableEntry[]; version: number; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/actions.html#args-syntax */ export interface Action { /** * Comment */ comment?: string; /** * Definition of the action */ definition: ActionDefinition; /** * Name of the action */ name: string; /** * Permissions of the action */ permissions?: Permissions; } /** * Definition of the action * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/actions.html#actiondefinition */ export interface ActionDefinition { arguments?: InputArgument[]; forward_client_headers?: boolean; /** * A String value which supports templating environment variables enclosed in {{ and }}. * Template example: https://{{ACTION_API_DOMAIN}}/create-user */ handler: string; headers?: Header[]; kind?: string; output_type?: string; type?: ActionDefinitionType; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/actions.html#inputargument */ export interface InputArgument { name: string; type: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/syntax-defs.html#headerfromvalue * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/syntax-defs.html#headerfromenv */ export interface Header { /** * Name of the header */ name: string; /** * Value of the header */ value?: string; /** * Name of the environment variable which holds the value of the header */ value_from_env?: string; } export enum ActionDefinitionType { Mutation = "mutation", Query = "query", } /** * Permissions of the action */ export interface Permissions { role: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/query-collections.html#add-collection-to-allowlist-syntax */ export interface AllowList { /** * Name of a query collection to be added to the allow-list */ collection: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/scheduled-triggers.html#create-cron-trigger */ export interface CronTrigger { /** * Custom comment. */ comment?: string; /** * List of headers to be sent with the webhook */ headers: Header[]; /** * Flag to indicate whether a trigger should be included in the metadata. When a cron * trigger is included in the metadata, the user will be able to export it when the metadata * of the graphql-engine is exported. */ include_in_metadata: boolean; /** * Name of the cron trigger */ name: string; /** * Any JSON payload which will be sent when the webhook is invoked. */ payload?: { [key: string]: any }; /** * Retry configuration if scheduled invocation delivery fails */ retry_conf?: RetryConfST; /** * Cron expression at which the trigger should be invoked. */ schedule: string; /** * URL of the webhook */ webhook: string; } /** * Retry configuration if scheduled invocation delivery fails * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/scheduled-triggers.html#retryconfst */ export interface RetryConfST { /** * Number of times to retry delivery. * Default: 0 */ num_retries?: number; /** * Number of seconds to wait between each retry. * Default: 10 */ retry_interval_seconds?: number; /** * Number of seconds to wait for response before timing out. * Default: 60 */ timeout_seconds?: number; /** * Number of seconds between scheduled time and actual delivery time that is acceptable. If * the time difference is more than this, then the event is dropped. * Default: 21600 (6 hours) */ tolerance_seconds?: number; } export interface CustomTypes { enums?: EnumType[]; input_objects?: InputObjectType[]; objects?: ObjectType[]; scalars?: ScalarType[]; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#enumtype */ export interface EnumType { /** * Description of the Enum type */ description?: string; /** * Name of the Enum type */ name: string; /** * Values of the Enum type */ values: EnumValue[]; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#enumvalue */ export interface EnumValue { /** * Description of the Enum value */ description?: string; /** * If set to true, the enum value is marked as deprecated */ is_deprecated?: boolean; /** * Value of the Enum type */ value: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#inputobjecttype */ export interface InputObjectType { /** * Description of the Input object type */ description?: string; /** * Fields of the Input object type */ fields: InputObjectField[]; /** * Name of the Input object type */ name: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#inputobjectfield */ export interface InputObjectField { /** * Description of the Input object type */ description?: string; /** * Name of the Input object type */ name: string; /** * GraphQL type of the Input object type */ type: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#objecttype */ export interface ObjectType { /** * Description of the Input object type */ description?: string; /** * Fields of the Input object type */ fields: InputObjectField[]; /** * Name of the Input object type */ name: string; /** * Relationships of the Object type to tables */ relationships?: CustomTypeObjectRelationship[]; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#objectrelationship */ export interface CustomTypeObjectRelationship { /** * Mapping of fields of object type to columns of remote table */ field_mapping: { [key: string]: string }; /** * Name of the relationship, shouldn’t conflict with existing field names */ name: string; /** * The table to which relationship is defined */ remote_table: QualifiedTable | string; /** * Type of the relationship */ type: CustomTypeObjectRelationshipType; } export interface QualifiedTable { name: string; schema: string; } /** * Type of the relationship */ export enum CustomTypeObjectRelationshipType { Array = "array", Object = "object", } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-types.html#scalartype */ export interface ScalarType { /** * Description of the Scalar type */ description?: string; /** * Name of the Scalar type */ name: string; } /** * A custom SQL function to add to the GraphQL schema with configuration. * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-functions.html#args-syntax */ export interface CustomFunction { /** * Configuration for the SQL function */ configuration?: FunctionConfiguration; /** * Name of the SQL function */ function: QualifiedFunction | string; } /** * Configuration for the SQL function * * Configuration for a CustomFunction * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/custom-functions.html#function-configuration */ export interface FunctionConfiguration { /** * Function argument which accepts session info JSON * Currently, only functions which satisfy the following constraints can be exposed over the * GraphQL API (terminology from Postgres docs): * - Function behaviour: ONLY `STABLE` or `IMMUTABLE` * - Return type: MUST be `SETOF <table-name>` * - Argument modes: ONLY `IN` */ session_argument?: string; } export interface QualifiedFunction { name: string; schema: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/query-collections.html#args-syntax */ export interface QueryCollectionEntry { /** * Comment */ comment?: string; /** * List of queries */ definition: Definition; /** * Name of the query collection */ name: string; } /** * List of queries */ export interface Definition { queries: QueryCollection[]; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/syntax-defs.html#collectionquery */ export interface QueryCollection { name: string; query: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/remote-schemas.html#add-remote-schema */ export interface RemoteSchema { /** * Comment */ comment?: string; /** * Name of the remote schema */ definition: RemoteSchemaDef; /** * Name of the remote schema */ name: string; } /** * Name of the remote schema * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/syntax-defs.html#remoteschemadef */ export interface RemoteSchemaDef { forward_client_headers?: boolean; headers?: Header[]; timeout_seconds?: number; url?: string; url_from_env?: string; } /** * Representation of a table in metadata, 'tables.yaml' and 'metadata.json' */ export interface TableEntry { array_relationships?: ArrayRelationship[]; computed_fields?: ComputedField[]; /** * Configuration for the table/view * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/table-view.html#table-config */ configuration?: TableConfig; delete_permissions?: DeletePermissionEntry[]; event_triggers?: EventTrigger[]; insert_permissions?: InsertPermissionEntry[]; is_enum?: boolean; object_relationships?: ObjectRelationship[]; remote_relationships?: RemoteRelationship[]; select_permissions?: SelectPermissionEntry[]; table: QualifiedTable; update_permissions?: UpdatePermissionEntry[]; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#create-array-relationship-syntax */ export interface ArrayRelationship { /** * Comment */ comment?: string; /** * Name of the new relationship */ name: string; /** * Use one of the available ways to define an array relationship */ using: ArrRelUsing; } /** * Use one of the available ways to define an array relationship * * Use one of the available ways to define an object relationship * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#arrrelusing */ export interface ArrRelUsing { /** * The column with foreign key constraint */ foreign_key_constraint_on?: ArrRelUsingFKeyOn; /** * Manual mapping of table and columns */ manual_configuration?: ArrRelUsingManualMapping; } /** * The column with foreign key constraint * * The column with foreign key constraint * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#arrrelusingfkeyon */ export interface ArrRelUsingFKeyOn { column: string; table: QualifiedTable | string; } /** * Manual mapping of table and columns * * Manual mapping of table and columns * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#arrrelusingmanualmapping */ export interface ArrRelUsingManualMapping { /** * Mapping of columns from current table to remote table */ column_mapping: { [key: string]: string }; /** * The table to which the relationship has to be established */ remote_table: QualifiedTable | string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/computed-field.html#args-syntax */ export interface ComputedField { /** * Comment */ comment?: string; /** * The computed field definition */ definition: ComputedFieldDefinition; /** * Name of the new computed field */ name: string; } /** * The computed field definition * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/computed-field.html#computedfielddefinition */ export interface ComputedFieldDefinition { /** * The SQL function */ function: QualifiedFunction | string; /** * Name of the argument which accepts the Hasura session object as a JSON/JSONB value. If * omitted, the Hasura session object is not passed to the function */ session_argument?: string; /** * Name of the argument which accepts a table row type. If omitted, the first argument is * considered a table argument */ table_argument?: string; } /** * Configuration for the table/view * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/table-view.html#table-config */ export interface TableConfig { /** * Customise the table name / query root name */ custom_name: string; /** * Customise the column names */ custom_column_names?: { [key: string]: string }; /** * Customise the root fields */ custom_root_fields?: CustomRootFields; } /** * Customise the root fields * * Customise the root fields * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/table-view.html#custom-root-fields */ export interface CustomRootFields { /** * Customise the `delete_<table-name>` root field */ delete?: string; /** * Customise the `delete_<table-name>_by_pk` root field */ delete_by_pk?: string; /** * Customise the `insert_<table-name>` root field */ insert?: string; /** * Customise the `insert_<table-name>_one` root field */ insert_one?: string; /** * Customise the `<table-name>` root field */ select?: string; /** * Customise the `<table-name>_aggregate` root field */ select_aggregate?: string; /** * Customise the `<table-name>_by_pk` root field */ select_by_pk?: string; /** * Customise the `update_<table-name>` root field */ update?: string; /** * Customise the `update_<table-name>_by_pk` root field */ update_by_pk?: string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#create-delete-permission-syntax */ export interface DeletePermissionEntry { /** * Comment */ comment?: string; /** * The permission definition */ permission: DeletePermission; /** * Role */ role: string; } /** * The permission definition * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#deletepermission */ export interface DeletePermission { /** * Only the rows where this precondition holds true are updatable */ filter?: { [key: string]: number | { [key: string]: any } | string }; } /** * NOTE: The metadata type doesn't QUITE match the 'create' arguments here * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#create-event-trigger */ export interface EventTrigger { /** * The SQL function */ definition: EventTriggerDefinition; /** * The SQL function */ headers?: Header[]; /** * Name of the event trigger */ name: string; /** * The SQL function */ retry_conf: RetryConf; /** * The SQL function */ webhook?: string; webhook_from_env?: string; } /** * The SQL function */ export interface EventTriggerDefinition { /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#operationspec */ delete?: OperationSpec; enable_manual: boolean; /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#operationspec */ insert?: OperationSpec; /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#operationspec */ update?: OperationSpec; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#operationspec */ export interface OperationSpec { /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#eventtriggercolumns */ columns: string[] | Columns; /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#eventtriggercolumns */ payload?: string[] | Columns; } export enum Columns { Empty = "*", } /** * The SQL function * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/event-triggers.html#retryconf */ export interface RetryConf { /** * Number of seconds to wait between each retry. * Default: 10 */ interval_sec?: number; /** * Number of times to retry delivery. * Default: 0 */ num_retries?: number; /** * Number of seconds to wait for response before timing out. * Default: 60 */ timeout_sec?: number; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#args-syntax */ export interface InsertPermissionEntry { /** * Comment */ comment?: string; /** * The permission definition */ permission: InsertPermission; /** * Role */ role: string; } /** * The permission definition * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#insertpermission */ export interface InsertPermission { /** * When set to true the mutation is accessible only if x-hasura-use-backend-only-permissions * session variable exists * and is set to true and request is made with x-hasura-admin-secret set if any auth is * configured */ backend_only?: boolean; /** * This expression has to hold true for every new row that is inserted */ check?: { [key: string]: number | { [key: string]: any } | string }; /** * Can insert into only these columns (or all when '*' is specified) */ columns: string[] | Columns; /** * Preset values for columns that can be sourced from session variables or static values */ set?: { [key: string]: string }; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#args-syntax */ export interface ObjectRelationship { /** * Comment */ comment?: string; /** * Name of the new relationship */ name: string; /** * Use one of the available ways to define an object relationship */ using: ObjRelUsing; } /** * Use one of the available ways to define an object relationship * * Use one of the available ways to define an object relationship * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#objrelusing */ export interface ObjRelUsing { /** * The column with foreign key constraint */ foreign_key_constraint_on?: string; /** * Manual mapping of table and columns */ manual_configuration?: ObjRelUsingManualMapping; } /** * Manual mapping of table and columns * * Manual mapping of table and columns * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/relationship.html#objrelusingmanualmapping */ export interface ObjRelUsingManualMapping { /** * Mapping of columns from current table to remote table */ column_mapping: { [key: string]: string }; /** * The table to which the relationship has to be established */ remote_table: QualifiedTable | string; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/remote-relationships.html#args-syntax */ export interface RemoteRelationship { /** * Definition object */ definition: RemoteRelationshipDef; /** * Name of the remote relationship */ name: string; } /** * Definition object */ export interface RemoteRelationshipDef { /** * Column(s) in the table that is used for joining with remote schema field. * All join keys in remote_field must appear here. */ hasura_fields: string[]; /** * The schema tree ending at the field in remote schema which needs to be joined with. */ remote_field: { [key: string]: RemoteField }; /** * Name of the remote schema to join with */ remote_schema: string; } export interface RemoteField { arguments: { [key: string]: string }; /** * A recursive tree structure that points to the field in the remote schema that needs to be * joined with. * It is recursive because the remote field maybe nested deeply in the remote schema. * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/remote-relationships.html#remotefield */ field?: { [key: string]: RemoteField }; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#create-select-permission-syntax */ export interface SelectPermissionEntry { /** * Comment */ comment?: string; /** * The permission definition */ permission: SelectPermission; /** * Role */ role: string; } /** * The permission definition * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#selectpermission */ export interface SelectPermission { /** * Toggle allowing aggregate queries */ allow_aggregations?: boolean; /** * Only these columns are selectable (or all when '*' is specified) */ columns: string[] | Columns; /** * Only these computed fields are selectable */ computed_fields?: string[]; /** * Only the rows where this precondition holds true are selectable */ filter?: { [key: string]: number | { [key: string]: any } | string }; /** * The maximum number of rows that can be returned */ limit?: number; } /** * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#create-update-permission-syntax */ export interface UpdatePermissionEntry { /** * Comment */ comment?: string; /** * The permission definition */ permission: UpdatePermission; /** * Role */ role: string; } /** * The permission definition * * * https://hasura.io/docs/latest/graphql/core/api-reference/schema-metadata-api/permission.html#updatepermission */ export interface UpdatePermission { /** * Postcondition which must be satisfied by rows which have been updated */ check?: { [key: string]: number | { [key: string]: any } | string }; /** * Only these columns are selectable (or all when '*' is specified) */ columns: string[] | Columns; /** * Only the rows where this precondition holds true are updatable */ filter?: { [key: string]: number | { [key: string]: any } | string }; /** * Preset values for columns that can be sourced from session variables or static values */ set?: { [key: string]: string }; } // Converts JSON strings to/from your types // and asserts the results of JSON.parse at runtime export class Convert { public static toPGColumn(json: string): string { return cast(JSON.parse(json), ""); } public static pGColumnToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toComputedFieldName(json: string): string { return cast(JSON.parse(json), ""); } public static computedFieldNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toRoleName(json: string): string { return cast(JSON.parse(json), ""); } public static roleNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toTriggerName(json: string): string { return cast(JSON.parse(json), ""); } public static triggerNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toRemoteRelationshipName(json: string): string { return cast(JSON.parse(json), ""); } public static remoteRelationshipNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toRemoteSchemaName(json: string): string { return cast(JSON.parse(json), ""); } public static remoteSchemaNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toCollectionName(json: string): string { return cast(JSON.parse(json), ""); } public static collectionNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toGraphQLName(json: string): string { return cast(JSON.parse(json), ""); } public static graphQLNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toGraphQLType(json: string): string { return cast(JSON.parse(json), ""); } public static graphQLTypeToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toRelationshipName(json: string): string { return cast(JSON.parse(json), ""); } public static relationshipNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toActionName(json: string): string { return cast(JSON.parse(json), ""); } public static actionNameToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toWebhookURL(json: string): string { return cast(JSON.parse(json), ""); } public static webhookURLToJson(value: string): string { return JSON.stringify(uncast(value, ""), null, 2); } public static toTableName(json: string): QualifiedTable | string { return cast(JSON.parse(json), u(r("QualifiedTable"), "")); } public static tableNameToJson(value: QualifiedTable | string): string { return JSON.stringify(uncast(value, u(r("QualifiedTable"), "")), null, 2); } public static toQualifiedTable(json: string): QualifiedTable { return cast(JSON.parse(json), r("QualifiedTable")); } public static qualifiedTableToJson(value: QualifiedTable): string { return JSON.stringify(uncast(value, r("QualifiedTable")), null, 2); } public static toTableConfig(json: string): TableConfig { return cast(JSON.parse(json), r("TableConfig")); } public static tableConfigToJson(value: TableConfig): string { return JSON.stringify(uncast(value, r("TableConfig")), null, 2); } public static toTableEntry(json: string): TableEntry { return cast(JSON.parse(json), r("TableEntry")); } public static tableEntryToJson(value: TableEntry): string { return JSON.stringify(uncast(value, r("TableEntry")), null, 2); } public static toCustomRootFields(json: string): CustomRootFields { return cast(JSON.parse(json), r("CustomRootFields")); } public static customRootFieldsToJson(value: CustomRootFields): string { return JSON.stringify(uncast(value, r("CustomRootFields")), null, 2); } public static toCustomColumnNames(json: string): { [key: string]: string } { return cast(JSON.parse(json), m("")); } public static customColumnNamesToJson(value: { [key: string]: string }): string { return JSON.stringify(uncast(value, m("")), null, 2); } public static toFunctionName(json: string): QualifiedFunction | string { return cast(JSON.parse(json), u(r("QualifiedFunction"), "")); } public static functionNameToJson(value: QualifiedFunction | string): string { return JSON.stringify(uncast(value, u(r("QualifiedFunction"), "")), null, 2); } public static toQualifiedFunction(json: string): QualifiedFunction { return cast(JSON.parse(json), r("QualifiedFunction")); } public static qualifiedFunctionToJson(value: QualifiedFunction): string { return JSON.stringify(uncast(value, r("QualifiedFunction")), null, 2); } public static toCustomFunction(json: string): CustomFunction { return cast(JSON.parse(json), r("CustomFunction")); } public static customFunctionToJson(value: CustomFunction): string { return JSON.stringify(uncast(value, r("CustomFunction")), null, 2); } public static toFunctionConfiguration(json: string): FunctionConfiguration { return cast(JSON.parse(json), r("FunctionConfiguration")); } public static functionConfigurationToJson(value: FunctionConfiguration): string { return JSON.stringify(uncast(value, r("FunctionConfiguration")), null, 2); } public static toObjectRelationship(json: string): ObjectRelationship { return cast(JSON.parse(json), r("ObjectRelationship")); } public static objectRelationshipToJson(value: ObjectRelationship): string { return JSON.stringify(uncast(value, r("ObjectRelationship")), null, 2); } public static toObjRelUsing(json: string): ObjRelUsing { return cast(JSON.parse(json), r("ObjRelUsing")); } public static objRelUsingToJson(value: ObjRelUsing): string { return JSON.stringify(uncast(value, r("ObjRelUsing")), null, 2); } public static toObjRelUsingManualMapping(json: string): ObjRelUsingManualMapping { return cast(JSON.parse(json), r("ObjRelUsingManualMapping")); } public static objRelUsingManualMappingToJson(value: ObjRelUsingManualMapping): string { return JSON.stringify(uncast(value, r("ObjRelUsingManualMapping")), null, 2); } public static toArrayRelationship(json: string): ArrayRelationship { return cast(JSON.parse(json), r("ArrayRelationship")); } public static arrayRelationshipToJson(value: ArrayRelationship): string { return JSON.stringify(uncast(value, r("ArrayRelationship")), null, 2); } public static toArrRelUsing(json: string): ArrRelUsing { return cast(JSON.parse(json), r("ArrRelUsing")); } public static arrRelUsingToJson(value: ArrRelUsing): string { return JSON.stringify(uncast(value, r("ArrRelUsing")), null, 2); } public static toArrRelUsingFKeyOn(json: string): ArrRelUsingFKeyOn { return cast(JSON.parse(json), r("ArrRelUsingFKeyOn")); } public static arrRelUsingFKeyOnToJson(value: ArrRelUsingFKeyOn): string { return JSON.stringify(uncast(value, r("ArrRelUsingFKeyOn")), null, 2); } public static toArrRelUsingManualMapping(json: string): ArrRelUsingManualMapping { return cast(JSON.parse(json), r("ArrRelUsingManualMapping")); } public static arrRelUsingManualMappingToJson(value: ArrRelUsingManualMapping): string { return JSON.stringify(uncast(value, r("ArrRelUsingManualMapping")), null, 2); } public static toColumnPresetsExpression(json: string): { [key: string]: string } { return cast(JSON.parse(json), m("")); } public static columnPresetsExpressionToJson(value: { [key: string]: string }): string { return JSON.stringify(uncast(value, m("")), null, 2); } public static toInsertPermissionEntry(json: string): InsertPermissionEntry { return cast(JSON.parse(json), r("InsertPermissionEntry")); } public static insertPermissionEntryToJson(value: InsertPermissionEntry): string { return JSON.stringify(uncast(value, r("InsertPermissionEntry")), null, 2); } public static toInsertPermission(json: string): InsertPermission { return cast(JSON.parse(json), r("InsertPermission")); } public static insertPermissionToJson(value: InsertPermission): string { return JSON.stringify(uncast(value, r("InsertPermission")), null, 2); } public static toSelectPermissionEntry(json: string): SelectPermissionEntry { return cast(JSON.parse(json), r("SelectPermissionEntry")); } public static selectPermissionEntryToJson(value: SelectPermissionEntry): string { return JSON.stringify(uncast(value, r("SelectPermissionEntry")), null, 2); } public static toSelectPermission(json: string): SelectPermission { return cast(JSON.parse(json), r("SelectPermission")); } public static selectPermissionToJson(value: SelectPermission): string { return JSON.stringify(uncast(value, r("SelectPermission")), null, 2); } public static toUpdatePermissionEntry(json: string): UpdatePermissionEntry { return cast(JSON.parse(json), r("UpdatePermissionEntry")); } public static updatePermissionEntryToJson(value: UpdatePermissionEntry): string { return JSON.stringify(uncast(value, r("UpdatePermissionEntry")), null, 2); } public static toUpdatePermission(json: string): UpdatePermission { return cast(JSON.parse(json), r("UpdatePermission")); } public static updatePermissionToJson(value: UpdatePermission): string { return JSON.stringify(uncast(value, r("UpdatePermission")), null, 2); } public static toDeletePermissionEntry(json: string): DeletePermissionEntry { return cast(JSON.parse(json), r("DeletePermissionEntry")); } public static deletePermissionEntryToJson(value: DeletePermissionEntry): string { return JSON.stringify(uncast(value, r("DeletePermissionEntry")), null, 2); } public static toDeletePermission(json: string): DeletePermission { return cast(JSON.parse(json), r("DeletePermission")); } public static deletePermissionToJson(value: DeletePermission): string { return JSON.stringify(uncast(value, r("DeletePermission")), null, 2); } public static toComputedField(json: string): ComputedField { return cast(JSON.parse(json), r("ComputedField")); } public static computedFieldToJson(value: ComputedField): string { return JSON.stringify(uncast(value, r("ComputedField")), null, 2); } public static toComputedFieldDefinition(json: string): ComputedFieldDefinition { return cast(JSON.parse(json), r("ComputedFieldDefinition")); } public static computedFieldDefinitionToJson(value: ComputedFieldDefinition): string { return JSON.stringify(uncast(value, r("ComputedFieldDefinition")), null, 2); } public static toEventTrigger(json: string): EventTrigger { return cast(JSON.parse(json), r("EventTrigger")); } public static eventTriggerToJson(value: EventTrigger): string { return JSON.stringify(uncast(value, r("EventTrigger")), null, 2); } public static toEventTriggerDefinition(json: string): EventTriggerDefinition { return cast(JSON.parse(json), r("EventTriggerDefinition")); } public static eventTriggerDefinitionToJson(value: EventTriggerDefinition): string { return JSON.stringify(uncast(value, r("EventTriggerDefinition")), null, 2); } public static toEventTriggerColumns(json: string): string[] | Columns { return cast(JSON.parse(json), u(a(""), r("Columns"))); } public static eventTriggerColumnsToJson(value: string[] | Columns): string { return JSON.stringify(uncast(value, u(a(""), r("Columns"))), null, 2); } public static toOperationSpec(json: string): OperationSpec { return cast(JSON.parse(json), r("OperationSpec")); } public static operationSpecToJson(value: OperationSpec): string { return JSON.stringify(uncast(value, r("OperationSpec")), null, 2); } public static toHeaderFromValue(json: string): HeaderFromValue { return cast(JSON.parse(json), r("HeaderFromValue")); } public static headerFromValueToJson(value: HeaderFromValue): string { return JSON.stringify(uncast(value, r("HeaderFromValue")), null, 2); } public static toHeaderFromEnv(json: string): HeaderFromEnv { return cast(JSON.parse(json), r("HeaderFromEnv")); } public static headerFromEnvToJson(value: HeaderFromEnv): string { return JSON.stringify(uncast(value, r("HeaderFromEnv")), null, 2); } public static toRetryConf(json: string): RetryConf { return cast(JSON.parse(json), r("RetryConf")); } public static retryConfToJson(value: RetryConf): string { return JSON.stringify(uncast(value, r("RetryConf")), null, 2); } public static toCronTrigger(json: string): CronTrigger { return cast(JSON.parse(json), r("CronTrigger")); } public static cronTriggerToJson(value: CronTrigger): string { return JSON.stringify(uncast(value, r("CronTrigger")), null, 2); } public static toRetryConfST(json: string): RetryConfST { return cast(JSON.parse(json), r("RetryConfST")); } public static retryConfSTToJson(value: RetryConfST): string { return JSON.stringify(uncast(value, r("RetryConfST")), null, 2); } public static toRemoteSchema(json: string): RemoteSchema { return cast(JSON.parse(json), r("RemoteSchema")); } public static remoteSchemaToJson(value: RemoteSchema): string { return JSON.stringify(uncast(value, r("RemoteSchema")), null, 2); } public static toRemoteSchemaDef(json: string): RemoteSchemaDef { return cast(JSON.parse(json), r("RemoteSchemaDef")); } public static remoteSchemaDefToJson(value: RemoteSchemaDef): string { return JSON.stringify(uncast(value, r("RemoteSchemaDef")), null, 2); } public static toRemoteRelationship(json: string): RemoteRelationship { return cast(JSON.parse(json), r("RemoteRelationship")); } public static remoteRelationshipToJson(value: RemoteRelationship): string { return JSON.stringify(uncast(value, r("RemoteRelationship")), null, 2); } public static toRemoteRelationshipDef(json: string): RemoteRelationshipDef { return cast(JSON.parse(json), r("RemoteRelationshipDef")); } public static remoteRelationshipDefToJson(value: RemoteRelationshipDef): string { return JSON.stringify(uncast(value, r("RemoteRelationshipDef")), null, 2); } public static toRemoteField(json: string): { [key: string]: RemoteField } { return cast(JSON.parse(json), m(r("RemoteField"))); } public static remoteFieldToJson(value: { [key: string]: RemoteField }): string { return JSON.stringify(uncast(value, m(r("RemoteField"))), null, 2); } public static toInputArguments(json: string): { [key: string]: string } { return cast(JSON.parse(json), m("")); } public static inputArgumentsToJson(value: { [key: string]: string }): string { return JSON.stringify(uncast(value, m("")), null, 2); } public static toQueryCollectionEntry(json: string): QueryCollectionEntry { return cast(JSON.parse(json), r("QueryCollectionEntry")); } public static queryCollectionEntryToJson(value: QueryCollectionEntry): string { return JSON.stringify(uncast(value, r("QueryCollectionEntry")), null, 2); } public static toQueryCollection(json: string): QueryCollection { return cast(JSON.parse(json), r("QueryCollection")); } public static queryCollectionToJson(value: QueryCollection): string { return JSON.stringify(uncast(value, r("QueryCollection")), null, 2); } public static toAllowList(json: string): AllowList { return cast(JSON.parse(json), r("AllowList")); } public static allowListToJson(value: AllowList): string { return JSON.stringify(uncast(value, r("AllowList")), null, 2); } public static toCustomTypes(json: string): CustomTypes { return cast(JSON.parse(json), r("CustomTypes")); } public static customTypesToJson(value: CustomTypes): string { return JSON.stringify(uncast(value, r("CustomTypes")), null, 2); } public static toInputObjectType(json: string): InputObjectType { return cast(JSON.parse(json), r("InputObjectType")); } public static inputObjectTypeToJson(value: InputObjectType): string { return JSON.stringify(uncast(value, r("InputObjectType")), null, 2); } public static toInputObjectField(json: string): InputObjectField { return cast(JSON.parse(json), r("InputObjectField")); } public static inputObjectFieldToJson(value: InputObjectField): string { return JSON.stringify(uncast(value, r("InputObjectField")), null, 2); } public static toObjectType(json: string): ObjectType { return cast(JSON.parse(json), r("ObjectType")); } public static objectTypeToJson(value: ObjectType): string { return JSON.stringify(uncast(value, r("ObjectType")), null, 2); } public static toObjectField(json: string): ObjectField { return cast(JSON.parse(json), r("ObjectField")); } public static objectFieldToJson(value: ObjectField): string { return JSON.stringify(uncast(value, r("ObjectField")), null, 2); } public static toCustomTypeObjectRelationship(json: string): CustomTypeObjectRelationship { return cast(JSON.parse(json), r("CustomTypeObjectRelationship")); } public static customTypeObjectRelationshipToJson(value: CustomTypeObjectRelationship): string { return JSON.stringify(uncast(value, r("CustomTypeObjectRelationship")), null, 2); } public static toScalarType(json: string): ScalarType { return cast(JSON.parse(json), r("ScalarType")); } public static scalarTypeToJson(value: ScalarType): string { return JSON.stringify(uncast(value, r("ScalarType")), null, 2); } public static toEnumType(json: string): EnumType { return cast(JSON.parse(json), r("EnumType")); } public static enumTypeToJson(value: EnumType): string { return JSON.stringify(uncast(value, r("EnumType")), null, 2); } public static toEnumValue(json: string): EnumValue { return cast(JSON.parse(json), r("EnumValue")); } public static enumValueToJson(value: EnumValue): string { return JSON.stringify(uncast(value, r("EnumValue")), null, 2); } public static toAction(json: string): Action { return cast(JSON.parse(json), r("Action")); } public static actionToJson(value: Action): string { return JSON.stringify(uncast(value, r("Action")), null, 2); } public static toActionDefinition(json: string): ActionDefinition { return cast(JSON.parse(json), r("ActionDefinition")); } public static actionDefinitionToJson(value: ActionDefinition): string { return JSON.stringify(uncast(value, r("ActionDefinition")), null, 2); } public static toInputArgument(json: string): InputArgument { return cast(JSON.parse(json), r("InputArgument")); } public static inputArgumentToJson(value: InputArgument): string { return JSON.stringify(uncast(value, r("InputArgument")), null, 2); } public static toHasuraMetadataV2(json: string): HasuraMetadataV2 { return cast(JSON.parse(json), r("HasuraMetadataV2")); } public static hasuraMetadataV2ToJson(value: HasuraMetadataV2): string { return JSON.stringify(uncast(value, r("HasuraMetadataV2")), null, 2); } } function invalidValue(typ: any, val: any): never { throw Error(`Invalid value ${JSON.stringify(val)} for type ${JSON.stringify(typ)}`); } function jsonToJSProps(typ: any): any { if (typ.jsonToJS === undefined) { const map: any = {}; typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ }); typ.jsonToJS = map; } return typ.jsonToJS; } function jsToJSONProps(typ: any): any { if (typ.jsToJSON === undefined) { const map: any = {}; typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ }); typ.jsToJSON = map; } return typ.jsToJSON; } function transform(val: any, typ: any, getProps: any): any { function transformPrimitive(typ: string, val: any): any { if (typeof typ === typeof val) return val; return invalidValue(typ, val); } function transformUnion(typs: any[], val: any): any { // val must validate against one typ in typs const l = typs.length; for (let i = 0; i < l; i++) { const typ = typs[i]; try { return transform(val, typ, getProps); } catch (_) {} } return invalidValue(typs, val); } function transformEnum(cases: string[], val: any): any { if (cases.indexOf(val) !== -1) return val; return invalidValue(cases, val); } function transformArray(typ: any, val: any): any { // val must be an array with no invalid elements if (!Array.isArray(val)) return invalidValue("array", val); return val.map(el => transform(el, typ, getProps)); } function transformDate(val: any): any { if (val === null) { return null; } const d = new Date(val); if (isNaN(d.valueOf())) { return invalidValue("Date", val); } return d; } function transformObject(props: { [k: string]: any }, additional: any, val: any): any { if (val === null || typeof val !== "object" || Array.isArray(val)) { return invalidValue("object", val); } const result: any = {}; Object.getOwnPropertyNames(props).forEach(key => { const prop = props[key]; const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined; result[prop.key] = transform(v, prop.typ, getProps); }); Object.getOwnPropertyNames(val).forEach(key => { if (!Object.prototype.hasOwnProperty.call(props, key)) { result[key] = transform(val[key], additional, getProps); } }); return result; } if (typ === "any") return val; if (typ === null) { if (val === null) return val; return invalidValue(typ, val); } if (typ === false) return invalidValue(typ, val); while (typeof typ === "object" && typ.ref !== undefined) { typ = typeMap[typ.ref]; } if (Array.isArray(typ)) return transformEnum(typ, val); if (typeof typ === "object") { return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val) : typ.hasOwnProperty("arrayItems") ? transformArray(typ.arrayItems, val) : typ.hasOwnProperty("props") ? transformObject(getProps(typ), typ.additional, val) : invalidValue(typ, val); } // Numbers can be parsed by Date but shouldn't be. if (typ === Date && typeof val !== "number") return transformDate(val); return transformPrimitive(typ, val); } function cast<T>(val: any, typ: any): T { return transform(val, typ, jsonToJSProps); } function uncast<T>(val: T, typ: any): any { return transform(val, typ, jsToJSONProps); } function a(typ: any) { return { arrayItems: typ }; } function u(...typs: any[]) { return { unionMembers: typs }; } function o(props: any[], additional: any) { return { props, additional }; } function m(additional: any) { return { props: [], additional }; } function r(name: string) { return { ref: name }; } const typeMap: any = { "HeaderFromValue": o([ { json: "name", js: "name", typ: "" }, { json: "value", js: "value", typ: "" }, ], "any"), "HeaderFromEnv": o([ { json: "name", js: "name", typ: "" }, { json: "value_from_env", js: "value_from_env", typ: "" }, ], "any"), "ObjectField": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "name", js: "name", typ: "" }, { json: "type", js: "type", typ: "" }, ], "any"), "HasuraMetadataV2": o([ { json: "actions", js: "actions", typ: u(undefined, a(r("Action"))) }, { json: "allowlist", js: "allowlist", typ: u(undefined, a(r("AllowList"))) }, { json: "cron_triggers", js: "cron_triggers", typ: u(undefined, a(r("CronTrigger"))) }, { json: "custom_types", js: "custom_types", typ: u(undefined, r("CustomTypes")) }, { json: "functions", js: "functions", typ: u(undefined, a(r("CustomFunction"))) }, { json: "query_collections", js: "query_collections", typ: u(undefined, a(r("QueryCollectionEntry"))) }, { json: "remote_schemas", js: "remote_schemas", typ: u(undefined, a(r("RemoteSchema"))) }, { json: "tables", js: "tables", typ: a(r("TableEntry")) }, { json: "version", js: "version", typ: 3.14 }, ], "any"), "Action": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "definition", js: "definition", typ: r("ActionDefinition") }, { json: "name", js: "name", typ: "" }, { json: "permissions", js: "permissions", typ: u(undefined, r("Permissions")) }, ], "any"), "ActionDefinition": o([ { json: "arguments", js: "arguments", typ: u(undefined, a(r("InputArgument"))) }, { json: "forward_client_headers", js: "forward_client_headers", typ: u(undefined, true) }, { json: "handler", js: "handler", typ: "" }, { json: "headers", js: "headers", typ: u(undefined, a(r("Header"))) }, { json: "kind", js: "kind", typ: u(undefined, "") }, { json: "output_type", js: "output_type", typ: u(undefined, "") }, { json: "type", js: "type", typ: u(undefined, r("ActionDefinitionType")) }, ], "any"), "InputArgument": o([ { json: "name", js: "name", typ: "" }, { json: "type", js: "type", typ: "" }, ], "any"), "Header": o([ { json: "name", js: "name", typ: "" }, { json: "value", js: "value", typ: u(undefined, "") }, { json: "value_from_env", js: "value_from_env", typ: u(undefined, "") }, ], "any"), "Permissions": o([ { json: "role", js: "role", typ: "" }, ], "any"), "AllowList": o([ { json: "collection", js: "collection", typ: "" }, ], "any"), "CronTrigger": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "headers", js: "headers", typ: a(r("Header")) }, { json: "include_in_metadata", js: "include_in_metadata", typ: true }, { json: "name", js: "name", typ: "" }, { json: "payload", js: "payload", typ: u(undefined, m("any")) }, { json: "retry_conf", js: "retry_conf", typ: u(undefined, r("RetryConfST")) }, { json: "schedule", js: "schedule", typ: "" }, { json: "webhook", js: "webhook", typ: "" }, ], "any"), "RetryConfST": o([ { json: "num_retries", js: "num_retries", typ: u(undefined, 0) }, { json: "retry_interval_seconds", js: "retry_interval_seconds", typ: u(undefined, 0) }, { json: "timeout_seconds", js: "timeout_seconds", typ: u(undefined, 0) }, { json: "tolerance_seconds", js: "tolerance_seconds", typ: u(undefined, 0) }, ], "any"), "CustomTypes": o([ { json: "enums", js: "enums", typ: u(undefined, a(r("EnumType"))) }, { json: "input_objects", js: "input_objects", typ: u(undefined, a(r("InputObjectType"))) }, { json: "objects", js: "objects", typ: u(undefined, a(r("ObjectType"))) }, { json: "scalars", js: "scalars", typ: u(undefined, a(r("ScalarType"))) }, ], "any"), "EnumType": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "name", js: "name", typ: "" }, { json: "values", js: "values", typ: a(r("EnumValue")) }, ], "any"), "EnumValue": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "is_deprecated", js: "is_deprecated", typ: u(undefined, true) }, { json: "value", js: "value", typ: "" }, ], "any"), "InputObjectType": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "fields", js: "fields", typ: a(r("InputObjectField")) }, { json: "name", js: "name", typ: "" }, ], "any"), "InputObjectField": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "name", js: "name", typ: "" }, { json: "type", js: "type", typ: "" }, ], "any"), "ObjectType": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "fields", js: "fields", typ: a(r("InputObjectField")) }, { json: "name", js: "name", typ: "" }, { json: "relationships", js: "relationships", typ: u(undefined, a(r("CustomTypeObjectRelationship"))) }, ], "any"), "CustomTypeObjectRelationship": o([ { json: "field_mapping", js: "field_mapping", typ: m("") }, { json: "name", js: "name", typ: "" }, { json: "remote_table", js: "remote_table", typ: u(r("QualifiedTable"), "") }, { json: "type", js: "type", typ: r("CustomTypeObjectRelationshipType") }, ], "any"), "QualifiedTable": o([ { json: "name", js: "name", typ: "" }, { json: "schema", js: "schema", typ: "" }, ], "any"), "ScalarType": o([ { json: "description", js: "description", typ: u(undefined, "") }, { json: "name", js: "name", typ: "" }, ], "any"), "CustomFunction": o([ { json: "configuration", js: "configuration", typ: u(undefined, r("FunctionConfiguration")) }, { json: "function", js: "function", typ: u(r("QualifiedFunction"), "") }, ], "any"), "FunctionConfiguration": o([ { json: "session_argument", js: "session_argument", typ: u(undefined, "") }, ], "any"), "QualifiedFunction": o([ { json: "name", js: "name", typ: "" }, { json: "schema", js: "schema", typ: "" }, ], "any"), "QueryCollectionEntry": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "definition", js: "definition", typ: r("Definition") }, { json: "name", js: "name", typ: "" }, ], "any"), "Definition": o([ { json: "queries", js: "queries", typ: a(r("QueryCollection")) }, ], "any"), "QueryCollection": o([ { json: "name", js: "name", typ: "" }, { json: "query", js: "query", typ: "" }, ], "any"), "RemoteSchema": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "definition", js: "definition", typ: r("RemoteSchemaDef") }, { json: "name", js: "name", typ: "" }, ], "any"), "RemoteSchemaDef": o([ { json: "forward_client_headers", js: "forward_client_headers", typ: u(undefined, true) }, { json: "headers", js: "headers", typ: u(undefined, a(r("Header"))) }, { json: "timeout_seconds", js: "timeout_seconds", typ: u(undefined, 3.14) }, { json: "url", js: "url", typ: u(undefined, "") }, { json: "url_from_env", js: "url_from_env", typ: u(undefined, "") }, ], "any"), "TableEntry": o([ { json: "array_relationships", js: "array_relationships", typ: u(undefined, a(r("ArrayRelationship"))) }, { json: "computed_fields", js: "computed_fields", typ: u(undefined, a(r("ComputedField"))) }, { json: "configuration", js: "configuration", typ: u(undefined, r("TableConfig")) }, { json: "delete_permissions", js: "delete_permissions", typ: u(undefined, a(r("DeletePermissionEntry"))) }, { json: "event_triggers", js: "event_triggers", typ: u(undefined, a(r("EventTrigger"))) }, { json: "insert_permissions", js: "insert_permissions", typ: u(undefined, a(r("InsertPermissionEntry"))) }, { json: "is_enum", js: "is_enum", typ: u(undefined, true) }, { json: "object_relationships", js: "object_relationships", typ: u(undefined, a(r("ObjectRelationship"))) }, { json: "remote_relationships", js: "remote_relationships", typ: u(undefined, a(r("RemoteRelationship"))) }, { json: "select_permissions", js: "select_permissions", typ: u(undefined, a(r("SelectPermissionEntry"))) }, { json: "table", js: "table", typ: r("QualifiedTable") }, { json: "update_permissions", js: "update_permissions", typ: u(undefined, a(r("UpdatePermissionEntry"))) }, ], "any"), "ArrayRelationship": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "name", js: "name", typ: "" }, { json: "using", js: "using", typ: r("ArrRelUsing") }, ], "any"), "ArrRelUsing": o([ { json: "foreign_key_constraint_on", js: "foreign_key_constraint_on", typ: u(undefined, r("ArrRelUsingFKeyOn")) }, { json: "manual_configuration", js: "manual_configuration", typ: u(undefined, r("ArrRelUsingManualMapping")) }, ], "any"), "ArrRelUsingFKeyOn": o([ { json: "column", js: "column", typ: "" }, { json: "table", js: "table", typ: u(r("QualifiedTable"), "") }, ], "any"), "ArrRelUsingManualMapping": o([ { json: "column_mapping", js: "column_mapping", typ: m("") }, { json: "remote_table", js: "remote_table", typ: u(r("QualifiedTable"), "") }, ], "any"), "ComputedField": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "definition", js: "definition", typ: r("ComputedFieldDefinition") }, { json: "name", js: "name", typ: "" }, ], "any"), "ComputedFieldDefinition": o([ { json: "function", js: "function", typ: u(r("QualifiedFunction"), "") }, { json: "session_argument", js: "session_argument", typ: u(undefined, "") }, { json: "table_argument", js: "table_argument", typ: u(undefined, "") }, ], "any"), "TableConfig": o([ { json: "custom_column_names", js: "custom_column_names", typ: u(undefined, m("")) }, { json: "custom_root_fields", js: "custom_root_fields", typ: u(undefined, r("CustomRootFields")) }, ], "any"), "CustomRootFields": o([ { json: "delete", js: "delete", typ: u(undefined, "") }, { json: "delete_by_pk", js: "delete_by_pk", typ: u(undefined, "") }, { json: "insert", js: "insert", typ: u(undefined, "") }, { json: "insert_one", js: "insert_one", typ: u(undefined, "") }, { json: "select", js: "select", typ: u(undefined, "") }, { json: "select_aggregate", js: "select_aggregate", typ: u(undefined, "") }, { json: "select_by_pk", js: "select_by_pk", typ: u(undefined, "") }, { json: "update", js: "update", typ: u(undefined, "") }, { json: "update_by_pk", js: "update_by_pk", typ: u(undefined, "") }, ], "any"), "DeletePermissionEntry": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "permission", js: "permission", typ: r("DeletePermission") }, { json: "role", js: "role", typ: "" }, ], "any"), "DeletePermission": o([ { json: "filter", js: "filter", typ: u(undefined, m(u(3.14, m("any"), ""))) }, ], "any"), "EventTrigger": o([ { json: "definition", js: "definition", typ: r("EventTriggerDefinition") }, { json: "headers", js: "headers", typ: u(undefined, a(r("Header"))) }, { json: "name", js: "name", typ: "" }, { json: "retry_conf", js: "retry_conf", typ: r("RetryConf") }, { json: "webhook", js: "webhook", typ: u(undefined, "") }, { json: "webhook_from_env", js: "webhook_from_env", typ: u(undefined, "") }, ], "any"), "EventTriggerDefinition": o([ { json: "delete", js: "delete", typ: u(undefined, r("OperationSpec")) }, { json: "enable_manual", js: "enable_manual", typ: true }, { json: "insert", js: "insert", typ: u(undefined, r("OperationSpec")) }, { json: "update", js: "update", typ: u(undefined, r("OperationSpec")) }, ], "any"), "OperationSpec": o([ { json: "columns", js: "columns", typ: u(a(""), r("Columns")) }, { json: "payload", js: "payload", typ: u(undefined, u(a(""), r("Columns"))) }, ], "any"), "RetryConf": o([ { json: "interval_sec", js: "interval_sec", typ: u(undefined, 0) }, { json: "num_retries", js: "num_retries", typ: u(undefined, 0) }, { json: "timeout_sec", js: "timeout_sec", typ: u(undefined, 0) }, ], "any"), "InsertPermissionEntry": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "permission", js: "permission", typ: r("InsertPermission") }, { json: "role", js: "role", typ: "" }, ], "any"), "InsertPermission": o([ { json: "backend_only", js: "backend_only", typ: u(undefined, true) }, { json: "check", js: "check", typ: u(undefined, m(u(3.14, m("any"), ""))) }, { json: "columns", js: "columns", typ: u(a(""), r("Columns")) }, { json: "set", js: "set", typ: u(undefined, m("")) }, ], "any"), "ObjectRelationship": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "name", js: "name", typ: "" }, { json: "using", js: "using", typ: r("ObjRelUsing") }, ], "any"), "ObjRelUsing": o([ { json: "foreign_key_constraint_on", js: "foreign_key_constraint_on", typ: u(undefined, "") }, { json: "manual_configuration", js: "manual_configuration", typ: u(undefined, r("ObjRelUsingManualMapping")) }, ], "any"), "ObjRelUsingManualMapping": o([ { json: "column_mapping", js: "column_mapping", typ: m("") }, { json: "remote_table", js: "remote_table", typ: u(r("QualifiedTable"), "") }, ], "any"), "RemoteRelationship": o([ { json: "definition", js: "definition", typ: r("RemoteRelationshipDef") }, { json: "name", js: "name", typ: "" }, ], "any"), "RemoteRelationshipDef": o([ { json: "hasura_fields", js: "hasura_fields", typ: a("") }, { json: "remote_field", js: "remote_field", typ: m(r("RemoteField")) }, { json: "remote_schema", js: "remote_schema", typ: "" }, ], "any"), "RemoteField": o([ { json: "arguments", js: "arguments", typ: m("") }, { json: "field", js: "field", typ: u(undefined, m(r("RemoteField"))) }, ], "any"), "SelectPermissionEntry": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "permission", js: "permission", typ: r("SelectPermission") }, { json: "role", js: "role", typ: "" }, ], "any"), "SelectPermission": o([ { json: "allow_aggregations", js: "allow_aggregations", typ: u(undefined, true) }, { json: "columns", js: "columns", typ: u(a(""), r("Columns")) }, { json: "computed_fields", js: "computed_fields", typ: u(undefined, a("")) }, { json: "filter", js: "filter", typ: u(undefined, m(u(3.14, m("any"), ""))) }, { json: "limit", js: "limit", typ: u(undefined, 0) }, ], "any"), "UpdatePermissionEntry": o([ { json: "comment", js: "comment", typ: u(undefined, "") }, { json: "permission", js: "permission", typ: r("UpdatePermission") }, { json: "role", js: "role", typ: "" }, ], "any"), "UpdatePermission": o([ { json: "check", js: "check", typ: u(undefined, m(u(3.14, m("any"), ""))) }, { json: "columns", js: "columns", typ: u(a(""), r("Columns")) }, { json: "filter", js: "filter", typ: u(undefined, m(u(3.14, m("any"), ""))) }, { json: "set", js: "set", typ: u(undefined, m("")) }, ], "any"), "ActionDefinitionType": [ "mutation", "query", ], "CustomTypeObjectRelationshipType": [ "array", "object", ], "Columns": [ "*", ], };
the_stack
import type { AddedKeywordDefinition, AnySchema, AnySchemaObject, KeywordErrorCxt, KeywordCxtParams, } from "../../types" import type {SchemaCxt, SchemaObjCxt} from ".." import type {InstanceOptions} from "../../core" import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema" import {coerceAndCheckDataType, getSchemaTypes} from "./dataType" import {shouldUseGroup, shouldUseRule} from "./applicability" import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType" import {assignDefaults} from "./defaults" import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword" import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema" import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen" import N from "../names" import {resolveUrl} from "../resolve" import { schemaRefOrVal, schemaHasRulesButRef, checkUnknownRules, checkStrictMode, unescapeJsonPointer, mergeEvaluated, } from "../util" import type {JSONType, Rule, RuleGroup} from "../rules" import { ErrorPaths, reportError, reportExtraError, resetErrorsCount, keyword$DataError, } from "../errors" // schema compilation - generates validation function, subschemaCode (below) is used for subschemas export function validateFunctionCode(it: SchemaCxt): void { if (isSchemaObj(it)) { checkKeywords(it) if (schemaCxtHasRules(it)) { topSchemaObjCode(it) return } } validateFunction(it, () => topBoolOrEmptySchema(it)) } function validateFunction( {gen, validateName, schema, schemaEnv, opts}: SchemaCxt, body: Block ): void { if (opts.code.es5) { gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => { gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`) destructureValCxtES5(gen, opts) gen.code(body) }) } else { gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body) ) } } function destructureValCxt(opts: InstanceOptions): Code { return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${ N.data }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}` } function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void { gen.if( N.valCxt, () => { gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`) gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`) gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`) gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`) if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`) }, () => { gen.var(N.instancePath, _`""`) gen.var(N.parentData, _`undefined`) gen.var(N.parentDataProperty, _`undefined`) gen.var(N.rootData, N.data) if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`) } ) } function topSchemaObjCode(it: SchemaObjCxt): void { const {schema, opts, gen} = it validateFunction(it, () => { if (opts.$comment && schema.$comment) commentKeyword(it) checkNoDefault(it) gen.let(N.vErrors, null) gen.let(N.errors, 0) if (opts.unevaluated) resetEvaluated(it) typeAndKeywords(it) returnResults(it) }) return } function resetEvaluated(it: SchemaObjCxt): void { // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated const {gen, validateName} = it it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`) gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`)) gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`)) } function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code { const schId = typeof schema == "object" && schema[opts.schemaId] return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil } // schema compilation - this function is used recursively to generate code for sub-schemas function subschemaCode(it: SchemaCxt, valid: Name): void { if (isSchemaObj(it)) { checkKeywords(it) if (schemaCxtHasRules(it)) { subSchemaObjCode(it, valid) return } } boolOrEmptySchema(it, valid) } function schemaCxtHasRules({schema, self}: SchemaCxt): boolean { if (typeof schema == "boolean") return !schema for (const key in schema) if (self.RULES.all[key]) return true return false } function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt { return typeof it.schema != "boolean" } function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void { const {schema, gen, opts} = it if (opts.$comment && schema.$comment) commentKeyword(it) updateContext(it) checkAsyncSchema(it) const errsCount = gen.const("_errs", N.errors) typeAndKeywords(it, errsCount) // TODO var gen.var(valid, _`${errsCount} === ${N.errors}`) } function checkKeywords(it: SchemaObjCxt): void { checkUnknownRules(it) checkRefsAndKeywords(it) } function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void { if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount) const types = getSchemaTypes(it.schema) const checkedTypes = coerceAndCheckDataType(it, types) schemaKeywords(it, types, !checkedTypes, errsCount) } function checkRefsAndKeywords(it: SchemaObjCxt): void { const {schema, errSchemaPath, opts, self} = it if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) { self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`) } } function checkNoDefault(it: SchemaObjCxt): void { const {schema, opts} = it if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { checkStrictMode(it, "default is ignored in the schema root") } } function updateContext(it: SchemaObjCxt): void { const schId = it.schema[it.opts.schemaId] if (schId) it.baseId = resolveUrl(it.baseId, schId) } function checkAsyncSchema(it: SchemaObjCxt): void { if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema") } function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void { const msg = schema.$comment if (opts.$comment === true) { gen.code(_`${N.self}.logger.log(${msg})`) } else if (typeof opts.$comment == "function") { const schemaPath = str`${errSchemaPath}/$comment` const rootName = gen.scopeValue("root", {ref: schemaEnv.root}) gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`) } } function returnResults(it: SchemaCxt): void { const {gen, schemaEnv, validateName, ValidationError, opts} = it if (schemaEnv.$async) { // TODO assign unevaluated gen.if( _`${N.errors} === 0`, () => gen.return(N.data), () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) ) } else { gen.assign(_`${validateName}.errors`, N.vErrors) if (opts.unevaluated) assignEvaluated(it) gen.return(_`${N.errors} === 0`) } } function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) } function schemaKeywords( it: SchemaObjCxt, types: JSONType[], typeErrors: boolean, errsCount?: Name ): void { const {gen, schema, data, allErrors, opts, self} = it const {RULES} = self if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast return } if (!opts.jtd) checkStrictTypes(it, types) gen.block(() => { for (const group of RULES.rules) groupKeywords(group) groupKeywords(RULES.post) }) function groupKeywords(group: RuleGroup): void { if (!shouldUseGroup(schema, group)) return if (group.type) { gen.if(checkDataType(group.type, data, opts.strictNumbers)) iterateKeywords(it, group) if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else() reportTypeError(it) } gen.endIf() } else { iterateKeywords(it, group) } // TODO make it "ok" call? if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`) } } function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { const { gen, schema, opts: {useDefaults}, } = it if (useDefaults) assignDefaults(it, group.type) gen.block(() => { for (const rule of group.rules) { if (shouldUseRule(schema, rule)) { keywordCode(it, rule.keyword, rule.definition, group.type) } } }) } function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { if (it.schemaEnv.meta || !it.opts.strictTypes) return checkContextTypes(it, types) if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) checkKeywordTypes(it, it.dataTypes) } function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { if (!types.length) return if (!it.dataTypes.length) { it.dataTypes = types return } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`) } }) it.dataTypes = it.dataTypes.filter((t) => includesType(types, t)) } function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword") } } function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { const rules = it.self.RULES.all for (const keyword in rules) { const rule = rules[keyword] if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { const {type} = rule.definition if (type.length && !type.some((t) => hasApplicableType(ts, t))) { strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`) } } } } function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean { return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")) } function includesType(ts: JSONType[], t: JSONType): boolean { return ts.includes(t) || (t === "integer" && ts.includes("number")) } function strictTypesError(it: SchemaObjCxt, msg: string): void { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath msg += ` at "${schemaPath}" (strictTypes)` checkStrictMode(it, msg, it.opts.strictTypes) } export class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } } function keywordCode( it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType ): void { const cxt = new KeywordCxt(it, def, keyword) if ("code" in def) { def.code(cxt, ruleType) } else if (cxt.$data && def.validate) { funcKeywordCode(cxt, def) } else if ("macro" in def) { macroKeywordCode(cxt, def) } else if (def.compile || def.validate) { funcKeywordCode(cxt, def) } } const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/ const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/ export function getData( $data: string, {dataLevel, dataNames, dataPathArr}: SchemaCxt ): Code | number { let jsonPointer let data: Code if ($data === "") return N.rootData if ($data[0] === "/") { if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`) jsonPointer = $data data = N.rootData } else { const matches = RELATIVE_JSON_POINTER.exec($data) if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`) const up: number = +matches[1] jsonPointer = matches[2] if (jsonPointer === "#") { if (up >= dataLevel) throw new Error(errorMsg("property/index", up)) return dataPathArr[dataLevel - up] } if (up > dataLevel) throw new Error(errorMsg("data", up)) data = dataNames[dataLevel - up] if (!jsonPointer) return data } let expr = data const segments = jsonPointer.split("/") for (const segment of segments) { if (segment) { data = _`${data}${getProperty(unescapeJsonPointer(segment))}` expr = _`${expr} && ${data}` } } return expr function errorMsg(pointerType: string, up: number): string { return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}` } }
the_stack
import { __ } from '@/components/_utils/_all'; declare global { interface Window { dragEvents?: any[any]; intervalEvents?: any[any]; windowResizeEvents?: any[any]; } } interface sliderAnimeConfig { /** Setup a sliderAnime for the slider to animate automatically. */ auto?: string | boolean | undefined; /** Autoplay interval. */ timing?: number | undefined; /** Gives the slider a seamless infinite loop. */ loop?: boolean | undefined; /** Total number ID or class of counter. */ countTotalID?: string | undefined; /** Current number ID or class of counter. */ countCurID?: string | undefined; /** Navigation ID for paging control of each slide. */ paginationID?: string | undefined; /** Previous/Next arrow navigation ID. */ arrowsID?: string | boolean | undefined; /** Allow drag and drop on the slider (touch devices will always work). */ draggable?: boolean | undefined; /** Drag & Drop Change icon/cursor while dragging. */ draggableCursor?: string | boolean | undefined; } export function sliderAnime( curElement: any, config: sliderAnimeConfig ) { if ( typeof curElement === typeof undefined ) return; // Set a default configuration config = __.setDefaultOptions({ "auto" : false, "timing" : 10000, "loop" : false, "countTotalID" : "p.count em.count", "countCurID" : "p.count em.current", "paginationID" : ".poemkit-slideshow__pagination", "arrowsID" : ".poemkit-slideshow__arrows", "draggable" : false, "draggableCursor" : "move" }, config); // let dataAuto = config.auto, dataTiming = config.timing, dataLoop = config.loop, dataControlsPagination = config.paginationID, dataControlsArrows = config.arrowsID, dataDraggable = config.draggable, dataDraggableCursor = config.draggableCursor, dataCountTotal = config.countTotalID, dataCountCur = config.countCurID; // const $sliderWrapper = curElement; let animDelay: any = 0; //Used to delete the global listening event when the component is about to be unmounted window.dragEvents = []; window.intervalEvents = []; window.windowResizeEvents = []; //Slider Initialize //------------------------------------------ let windowWidth = window.innerWidth; sliderInit( false ); function windowUpdate() { // Check window width has actually changed and it's not just iOS triggering a resize event on scroll if ( window.innerWidth != windowWidth ) { // Update the window width for next time windowWidth = window.innerWidth; // Do stuff here sliderInit( true ); } } // Add function to the window that should be resized const debounceFunc = __.debounce(windowUpdate, 50); window.removeEventListener('resize', debounceFunc); window.addEventListener('resize', debounceFunc); window.windowResizeEvents.push(debounceFunc); /* * Returns the dimensions of a video asynchrounsly. * * @param {String} url - Video URL. * @return {Json} - An object containing the properties height and width. */ function getVideoDimensions(url) { return new Promise(function (resolve) { // create the video element let video = document.createElement('video'); // place a listener on it video.addEventListener("loadedmetadata", function () { // retrieve dimensions let height = this.videoHeight; let width = this.videoWidth; // send back result resolve({ height: height, width: width }); }, false); // start download meta-datas video.src = url; }); } /* * Initialize sliderAnime * * @param {Boolean} resize - Determine whether the window size changes. * @return {Void} */ function sliderInit(resize) { const $items = $sliderWrapper.find('.poemkit-slideshow__item'), $first = $items.first(); let nativeItemW, nativeItemH, activated = $sliderWrapper.data('activated'); if (activated === null || activated === 0) { //Autoplay times let playTimes; //A function called "timer" once every second (like a digital watch). //An interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval(). $sliderWrapper.get(0).animatedSlides = null; setTimeout(function () { //The speed of movement between elements. // Avoid the error that getTransitionDuration takes 0 animDelay = __.cssProperty.getTransitionDuration($first[0]); }, 100); //Initialize the first item container //------------------------------------- $items.addClass('next'); setTimeout(function () { $first.addClass('is-active'); }, animDelay); if ($first.find('video').len() > 0) { //Returns the dimensions (intrinsic height and width ) of the video const video = $first.find( 'video' ).get(0); const _sources = video.getElementsByTagName('source'); const _src = _sources.length > 0 ? _sources[0].src : video.src; $first.find('video').css({ 'width': $sliderWrapper.width() + 'px' }); getVideoDimensions(_src).then(function (res: any): void { $sliderWrapper.css('height', res.height * ($sliderWrapper.width() / res.width) + 'px'); nativeItemW = res.width; nativeItemH = res.height; //Initialize all the items to the stage addItemsToStage($sliderWrapper, nativeItemW, nativeItemH, dataControlsPagination, dataControlsArrows, dataLoop, dataDraggable, dataDraggableCursor, dataCountTotal, dataCountCur); }); } else { const imgURL = $first.find('img').attr('src'); if ( imgURL !== null ) { const img = new Image(); img.onload = function () { $sliderWrapper.css('height', $sliderWrapper.width() * (img.height / img.width) + 'px'); nativeItemW = img.width; nativeItemH = img.height; //Initialize all the items to the stage addItemsToStage($sliderWrapper, nativeItemW, nativeItemH, dataControlsPagination, dataControlsArrows, dataLoop, dataDraggable, dataDraggableCursor, dataCountTotal, dataCountCur); }; img.src = imgURL; } } //Autoplay Slider //------------------------------------- if (!resize) { if (dataAuto && !isNaN(dataTiming as number) && isFinite(dataTiming as number)) { sliderAutoPlay(playTimes, dataTiming, dataLoop, $sliderWrapper, dataCountTotal, dataCountCur, dataControlsPagination, dataControlsArrows); const autoplayEnter = function() { clearInterval($sliderWrapper.get(0).animatedSlides); }; const autoplayLeave = function() { sliderAutoPlay(playTimes, dataTiming, dataLoop, $sliderWrapper, dataCountTotal, dataCountCur, dataControlsPagination, dataControlsArrows); }; // Do not use the `off()` method, otherwise it will cause the second mouseenter to be invalid $sliderWrapper.on( 'mouseenter', autoplayEnter ); $sliderWrapper.on( 'mouseleave', autoplayLeave ); if ( __.isTouchCapable() ) { $sliderWrapper.on( 'pointerenter', autoplayEnter ); $sliderWrapper.on( 'pointerleave', autoplayLeave ); } } } //Prevents front-end javascripts that are activated with AJAX to repeat loading. $sliderWrapper.data('activated', 1); }//endif activated } /* * Trigger slider autoplay * * @param {Function} playTimes - Number of times. * @param {Number} timing - Autoplay interval. * @param {Boolean} loop - Gives the slider a seamless infinite loop. * @param {Object} slider - Selector of the slider . * @param {String} countTotalID - Total number ID or class of counter. * @param {String} countCurID - Current number ID or class of counter. * @param {String} paginationID - Navigation ID for paging control of each slide. * @param {String} arrowsID - Previous/Next arrow navigation ID. * @return {Void} - The constructor. */ function sliderAutoPlay( playTimes, timing, loop, slider, countTotalID, countCurID, paginationID, arrowsID ) { const items = slider.find( '.poemkit-slideshow__item' ), total = items.len(); slider.get(0).animatedSlides = setInterval( function() { playTimes = parseFloat( items.filter( '.is-active' ).index() ); playTimes++; if ( !loop ) { if ( playTimes < total && playTimes >= 0 ) sliderUpdates( playTimes, $sliderWrapper, 'next', countTotalID, countCurID, paginationID, arrowsID, loop ); } else { if ( playTimes == total ) playTimes = 0; if ( playTimes < 0 ) playTimes = total-1; sliderUpdates( playTimes, $sliderWrapper, 'next', countTotalID, countCurID, paginationID, arrowsID, loop ); } }, timing ); window.intervalEvents.push(slider.get(0).animatedSlides); } /* * Initialize all the items to the stage * * @param {Object} slider - Current selector of each slider. * @param {Number} nativeItemW - Returns the intrinsic width of the image/video. * @param {Number} nativeItemH - Returns the intrinsic height of the image/video. * @param {String} paginationID - Navigation ID for paging control of each slide. * @param {String} arrowsID - Previous/Next arrow navigation ID. * @param {Boolean} loop - Gives the slider a seamless infinite loop. * @param {Boolean} draggable - Allow drag and drop on the slider (touch devices will always work). * @param {String} draggableCursor - Drag & Drop Change icon/cursor while dragging. * @param {String} countTotalID - Total number ID or class of counter. * @param {String} countCurID - Current number ID or class of counter. * @return {Void} */ function addItemsToStage( slider, nativeItemW, nativeItemH, paginationID, arrowsID, loop, draggable, draggableCursor, countTotalID, countCurID ) { const $this = slider, $items = $this.find( '.poemkit-slideshow__item' ), $first = $items.first(), itemsTotal = $items.len(); //If arrows does not exist on the page, it will be added by default, //and the drag and drop function will be activated. if ( __( arrowsID ).len() == 0 ) { __( 'body' ).prepend( '<div style="display:none;" class="poemkit-slideshow__arrows '+arrowsID.replace('#','').replace('.','')+'"><a href="#" class="poemkit-slideshow__arrows--prev"></a><a href="#" class="poemkit-slideshow__arrows--next"></a></div>' ); } //Prevent bubbling if ( itemsTotal == 1 ) { __( paginationID ).hide(); __( arrowsID ).hide(); } //Add identifiers for the first and last items $items.last().addClass( 'last' ); $items.first().addClass( 'first' ); //Pagination dots //------------------------------------- let _dot = '', _dotActive = ''; _dot += '<ul>'; for ( let i = 0; i < itemsTotal; i++ ) { _dotActive = ( i == 0 ) ? 'class="is-active"' : ''; _dot += '<li><a '+_dotActive+' data-index="'+i+'" href="#"></a></li>'; } _dot += '</ul>'; if ( __( paginationID ).html() == '' ) __( paginationID ).html( _dot ); __( paginationID ).find( 'li a' ).off( 'click' ).on( 'click', function( this: any, e: any ) { e.preventDefault(); const curBtnIndex = parseFloat( __( this ).data( 'index' ) ); //Prevent buttons' events from firing multiple times const $btn = __( this ); if ( $btn.attr( 'aria-disabled' ) == 'true' ) return false; __( paginationID ).find( 'li a' ).attr( 'aria-disabled', 'true' ); setTimeout( function() { __( paginationID ).find( 'li a' ).attr( 'aria-disabled', 'false' ); }, animDelay ); if ( !__( this ).hasClass( 'is-active' ) ) { //Determine the direction let curDir = 'prev'; if ( curBtnIndex > parseFloat( $items.filter( '.is-active' ).index() ) ) { curDir = 'next'; } sliderUpdates( curBtnIndex, $this, curDir, countTotalID, countCurID, paginationID, arrowsID, loop ); //Pause the auto play event clearInterval( $this.get(0).animatedSlides ); } }); //Next/Prev buttons //------------------------------------- const _prev = __( arrowsID ).find( '.poemkit-slideshow__arrows--prev' ), _next = __( arrowsID ).find( '.poemkit-slideshow__arrows--next' ); __( arrowsID ).find( 'a' ).removeClass( 'is-disabled' ); if ( !loop ) { _prev.addClass( 'is-disabled' ); } _prev.off( 'click' ).on( 'click', function( this: any, e: any ) { e.preventDefault(); //Pause the auto play event clearInterval( $this.get(0).animatedSlides ); //Move animation prevMove(); }); _next.off( 'click' ).on( 'click', function( this: any, e: any ) { e.preventDefault(); //Pause the auto play event clearInterval( $this.get(0).animatedSlides ); //Move animation nextMove(); }); function prevMove() { //Prevent buttons' events from firing multiple times if ( _prev.attr( 'aria-disabled' ) == 'true' ) return false; _prev.attr( 'aria-disabled', 'true' ); setTimeout( function() { _prev.attr( 'aria-disabled', 'false' ); }, animDelay ); // if ( _prev.hasClass( 'is-disabled' ) ) return false; // sliderUpdates( parseFloat( $items.filter( '.is-active' ).index() ) - 1, $this, 'prev', countTotalID, countCurID, paginationID, arrowsID, loop ); } function nextMove() { //Prevent buttons' events from firing multiple times if ( _next.attr( 'aria-disabled' ) == 'true' ) return false; _next.attr( 'aria-disabled', 'true' ); setTimeout( function() { _next.attr( 'aria-disabled', 'false' ); }, animDelay ); // if ( _next.hasClass( 'is-disabled' ) ) return false; // sliderUpdates( parseFloat( $items.filter( '.is-active' ).index() ) + 1, $this, 'next', countTotalID, countCurID, paginationID, arrowsID, loop ); } //Added touch method to mobile device and desktop //------------------------------------- const $dragTrigger = $this.find( '.poemkit-slideshow__inner' ); let mouseX, mouseY; let isMoving = false; //Avoid images causing mouseup to fail $dragTrigger.find( 'img' ).css({ 'pointer-events': 'none', 'user-select': 'none' }); //Make the cursor a move icon when a user hovers over an item if ( draggable && draggableCursor != '' && draggableCursor != false ) $dragTrigger.css( 'cursor', draggableCursor ); //draggable for touch devices if ( __.isTouchCapable() ) draggable = true; if ( draggable ) { $dragTrigger.get(0).removeEventListener( 'mousedown', dragStart ); document.removeEventListener( 'mouseup', dragEnd ); $dragTrigger.get(0).removeEventListener( 'touchstart', dragStart ); document.removeEventListener( 'touchend', dragEnd ); // $dragTrigger.get(0).addEventListener( 'mousedown', dragStart ); $dragTrigger.get(0).addEventListener( 'touchstart', dragStart ); } function dragStart(e) { //Do not use "e.preventDefault()" to avoid prevention page scroll on drag in IOS and Android const touches = e.touches; if ( touches && touches.length ) { mouseX = touches[0].clientX; mouseY = touches[0].clientY; } else { mouseX = e.clientX; mouseY = e.clientY; } document.addEventListener('mouseup', dragEnd); document.addEventListener('mousemove', dragProcess); document.addEventListener('touchend', dragEnd); document.addEventListener('touchmove', dragProcess); window.dragEvents.push(dragEnd, dragProcess); } function dragProcess(e) { const touches = e.touches; let offsetX, offsetY; if ( touches && touches.length ) { offsetX = mouseX - touches[0].clientX, offsetY = mouseY - touches[0].clientY; } else { offsetX = mouseX - e.clientX, offsetY = mouseY - e.clientY; } //--- left if ( offsetX >= 50) { if ( !isMoving ) { isMoving = true; nextMove(); } } //--- right if ( offsetX <= -50) { if ( !isMoving ) { isMoving = true; prevMove(); } } //--- up if ( offsetY >= 50) { } //--- down if ( offsetY <= -50) { } } function dragEnd(e) { document.removeEventListener( 'mousemove', dragProcess); document.removeEventListener( 'touchmove', dragProcess); //restore move action status setTimeout( function() { isMoving = false; }, animDelay); } } /* * Transition Between Slides * * @param {Number} elementIndex - Index of current slider. * @param {Object} slider - Selector of the slider . * @param {String} dir - Switching direction indicator. * @param {String} countTotalID - Total number ID or class of counter. * @param {String} countCurID - Current number ID or class of counter. * @param {String} paginationID - Navigation ID for paging control of each slide. * @param {String} arrowsID - Previous/Next arrow navigation ID. * @param {Boolean} loop - Gives the slider a seamless infinite loop. * @return {Void} */ function sliderUpdates( elementIndex, slider, dir, countTotalID, countCurID, paginationID, arrowsID, loop ) { const $items = slider.find( '.poemkit-slideshow__item' ), total = $items.len(); //Prevent bubbling if ( total == 1 ) { __( paginationID ).hide(); __( arrowsID ).hide(); return false; } //Transition Interception //------------------------------------- if ( loop ) { if ( elementIndex == total ) elementIndex = 0; if ( elementIndex < 0 ) elementIndex = total-1; } else { __( arrowsID ).find( 'a' ).removeClass( 'is-disabled' ); if ( elementIndex == total - 1 ) __( arrowsID ).find( '.poemkit-slideshow__arrows--next' ).addClass( 'is-disabled' ); if ( elementIndex == 0 ) __( arrowsID ).find( '.poemkit-slideshow__arrows--prev' ).addClass( 'is-disabled' ); } if ( __.isTouchCapable() ) { if ( elementIndex == total ) elementIndex = total-1; if ( elementIndex < 0 ) elementIndex = 0; //Prevent bubbling if ( !loop ) { //first item if ( elementIndex == 0 ) { __( arrowsID ).find( '.poemkit-slideshow__arrows--prev' ).addClass( 'is-disabled' ); } //last item if ( elementIndex == total - 1 ) { __( arrowsID ).find( '.poemkit-slideshow__arrows--next' ).addClass( 'is-disabled' ); } } } // call the current item //------------------------------------- const $current = $items.eq( elementIndex ); //Determine the direction and add class to switching direction indicator. let dirIndicatorClassName = ''; if ( dir == 'prev' ) dirIndicatorClassName = 'prev'; if ( dir == 'next' ) dirIndicatorClassName = 'next'; //Add transition class to Controls Pagination __( paginationID ).find( 'li a' ).removeClass( 'leave' ); __( paginationID ).find( 'li a.is-active' ).removeClass( 'is-active' ).addClass( 'leave'); __( paginationID ).find( 'li a[data-index="'+elementIndex+'"]' ).addClass( 'is-active').removeClass( 'leave' ); //Add transition class to each item $items.removeClass( 'leave prev next' ); $items.addClass( dirIndicatorClassName ); slider.find( '.poemkit-slideshow__item.is-active' ).removeClass( 'is-active' ).addClass( 'leave ' + dirIndicatorClassName ); $items.eq( elementIndex ).addClass( 'is-active ' + dirIndicatorClassName ).removeClass( 'leave' ); //Display counter //------------------------------------- if ( countTotalID !== false ) __( countTotalID ).text( total ); if ( countCurID !== false ) __( countCurID ).text( parseFloat( elementIndex ) + 1 ); //Reset the default height of item //------------------------------------- itemDefaultInit( slider, $current ); } /* * Initialize the default height of item * * @param {Object} slider - Selector of the slider . * @param {Object} currentLlement - Current selector of each slider. * @return {Void} */ function itemDefaultInit( slider, currentLlement ) { if ( currentLlement.find( 'video' ).len() > 0 ) { //Returns the dimensions (intrinsic height and width ) of the video const video = currentLlement.find( 'video' ).get(0); const _sources = video.getElementsByTagName('source'); const _src = _sources.length > 0 ? _sources[0].src : video.src; currentLlement.find( 'video' ).css({ 'width': currentLlement.closest( '.poemkit-slideshow__outline' ).width() + 'px' }); getVideoDimensions(_src).then(function (res: any): void { slider.css( 'height', res.height*(currentLlement.closest( '.poemkit-slideshow__outline' ).width()/res.width) + 'px' ); }); } else { const imgURL = currentLlement.find( 'img' ).attr( 'src' ); if ( imgURL !== null ) { const img = new Image(); img.onload = function() { slider.css( 'height', currentLlement.closest( '.poemkit-slideshow__outline' ).width()*(img.height/img.width) + 'px' ); }; img.src = imgURL; } } } } export default sliderAnime;
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreApp } from '@services/app'; import { CoreFile } from '@services/file'; import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreTextUtils } from '@services/utils/text'; import { CoreUrlUtils } from '@services/utils/url'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; const ROOT_CACHE_KEY = 'mmaModLti:'; const LAUNCHER_FILE_NAME = 'lti_launcher.html'; /** * Service that provides some features for LTI. */ @Injectable({ providedIn: 'root' }) export class AddonModLtiProvider { static readonly COMPONENT = 'mmaModLti'; /** * Delete launcher. * * @return Promise resolved when the launcher file is deleted. */ deleteLauncher(): Promise<void> { return CoreFile.removeFile(LAUNCHER_FILE_NAME); } /** * Generates a launcher file. * * @param url Launch URL. * @param params Launch params. * @return Promise resolved with the file URL. */ async generateLauncher(url: string, params: AddonModLtiParam[]): Promise<string> { if (!CoreFile.isAvailable()) { return url; } // Generate a form with the params. let text = `<form action="${url}" name="ltiLaunchForm" method="post" encType="application/x-www-form-urlencoded">\n`; params.forEach((p) => { if (p.name == 'ext_submit') { text += ' <input type="submit"'; } else { text += ' <input type="hidden" name="' + CoreTextUtils.escapeHTML(p.name) + '"'; } text += ' value="' + CoreTextUtils.escapeHTML(p.value) + '"/>\n'; }); text += '</form>\n'; // Add an in-line script to automatically submit the form. text += '<script type="text/javascript"> \n' + ' window.onload = function() { \n' + ' document.ltiLaunchForm.submit(); \n' + ' }; \n' + '</script> \n'; const entry = await CoreFile.writeFile(LAUNCHER_FILE_NAME, text); return entry.toURL(); } /** * Get a LTI. * * @param courseId Course ID. * @param cmId Course module ID. * @param options Other options. * @return Promise resolved when the LTI is retrieved. */ async getLti(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModLtiLti> { const params: AddonModLtiGetLtisByCoursesWSParams = { courseids: [courseId], }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getLtiCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModLtiProvider.COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const site = await CoreSites.getSite(options.siteId); const response = await site.read<AddonModLtiGetLtisByCoursesWSResponse>('mod_lti_get_ltis_by_courses', params, preSets); const currentLti = response.ltis.find((lti) => lti.coursemodule == cmId); if (currentLti) { return currentLti; } throw new CoreError('Activity not found.'); } /** * Get cache key for LTI data WS calls. * * @param courseId Course ID. * @return Cache key. */ protected getLtiCacheKey(courseId: number): string { return ROOT_CACHE_KEY + 'lti:' + courseId; } /** * Get a LTI launch data. * * @param id LTI id. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the launch data is retrieved. */ async getLtiLaunchData(id: number, siteId?: string): Promise<AddonModLtiGetToolLaunchDataWSResponse> { const params: AddonModLtiGetToolLaunchDataWSParams = { toolid: id, }; // Try to avoid using cache since the "nonce" parameter is set to a timestamp. const preSets: CoreSiteWSPreSets = { getFromCache: false, saveToCache: true, emergencyCache: true, cacheKey: this.getLtiLaunchDataCacheKey(id), }; const site = await CoreSites.getSite(siteId); return site.read<AddonModLtiGetToolLaunchDataWSResponse>('mod_lti_get_tool_launch_data', params, preSets); } /** * Get cache key for LTI launch data WS calls. * * @param id LTI id. * @return Cache key. */ protected getLtiLaunchDataCacheKey(id: number): string { return `${ROOT_CACHE_KEY}launch:${id}`; } /** * Invalidates LTI data. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateLti(courseId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getLtiCacheKey(courseId)); } /** * Invalidates options. * * @param id LTI id. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateLtiLaunchData(id: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getLtiLaunchDataCacheKey(id)); } /** * Check if open LTI in browser via site with auto-login is disabled. * This setting was added in 3.11. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether it's disabled. */ async isLaunchViaSiteDisabled(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return this.isLaunchViaSiteDisabledInSite(site); } /** * Check if open LTI in browser via site with auto-login is disabled. * This setting was added in 3.11. * * @param site Site. If not defined, current site. * @return Whether it's disabled. */ isLaunchViaSiteDisabledInSite(site?: CoreSite): boolean { site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('CoreCourseModuleDelegate_AddonModLti:launchViaSite'); } /** * Check if open in InAppBrowser is disabled. * This setting was removed in Moodle 3.11 because the default behaviour of the app changed. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether it's disabled. */ async isOpenInAppBrowserDisabled(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return this.isOpenInAppBrowserDisabledInSite(site); } /** * Check if open in InAppBrowser is disabled. * This setting was removed in Moodle 3.11 because the default behaviour of the app changed. * * @param site Site. If not defined, current site. * @return Whether it's disabled. */ isOpenInAppBrowserDisabledInSite(site?: CoreSite): boolean { site = site || CoreSites.getCurrentSite(); return !!site?.isFeatureDisabled('CoreCourseModuleDelegate_AddonModLti:openInAppBrowser'); } /** * Launch LTI. * * @param url Launch URL. * @param params Launch params. * @return Promise resolved when the WS call is successful. */ async launch(url: string, params: AddonModLtiParam[]): Promise<void> { if (!CoreUrlUtils.isHttpURL(url)) { throw Translate.instant('addon.mod_lti.errorinvalidlaunchurl'); } // Generate launcher and open it. const launcherUrl = await this.generateLauncher(url, params); if (CoreApp.isMobile()) { CoreUtils.openInApp(launcherUrl); } else { // In desktop open in browser, we found some cases where inapp caused JS issues. CoreUtils.openInBrowser(launcherUrl); } } /** * Report the LTI as being viewed. * * @param id LTI id. * @param name Name of the lti. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ logView(id: number, name?: string, siteId?: string): Promise<void> { const params: AddonModLtiViewLtiWSParams = { ltiid: id, }; return CoreCourseLogHelper.logSingle( 'mod_lti_view_lti', params, AddonModLtiProvider.COMPONENT, id, name, 'lti', {}, siteId, ); } /** * Check whether the LTI should be launched in browser via the site with auto-login. * * @param siteId Site ID. * @return Promise resolved with boolean. */ async shouldLaunchInBrowser(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); if (site.isVersionGreaterEqualThan('3.11')) { // In 3.11+, launch in browser by default unless it's disabled. return !this.isLaunchViaSiteDisabledInSite(site); } else { // In old sites the default behaviour is to launch in InAppBrowser. return this.isOpenInAppBrowserDisabledInSite(site); } } } export const AddonModLti = makeSingleton(AddonModLtiProvider); /** * Params of mod_lti_get_ltis_by_courses WS. */ export type AddonModLtiGetLtisByCoursesWSParams = { courseids?: number[]; // Array of course ids. }; /** * Data returned by mod_lti_get_ltis_by_courses WS. */ export type AddonModLtiGetLtisByCoursesWSResponse = { ltis: AddonModLtiLti[]; warnings?: CoreWSExternalWarning[]; }; /** * LTI returned by mod_lti_get_ltis_by_courses. */ export type AddonModLtiLti = { id: number; // External tool id. coursemodule: number; // Course module id. course: number; // Course id. name: string; // LTI name. intro?: string; // The LTI intro. introformat?: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). introfiles?: CoreWSExternalFile[]; // @since 3.2. timecreated?: number; // Time of creation. timemodified?: number; // Time of last modification. typeid?: number; // Type id. toolurl?: string; // Tool url. securetoolurl?: string; // Secure tool url. instructorchoicesendname?: string; // Instructor choice send name. instructorchoicesendemailaddr?: number; // Instructor choice send mail address. instructorchoiceallowroster?: number; // Instructor choice allow roster. instructorchoiceallowsetting?: number; // Instructor choice allow setting. instructorcustomparameters?: string; // Instructor custom parameters. instructorchoiceacceptgrades?: number; // Instructor choice accept grades. grade?: number; // Enable grades. launchcontainer?: number; // Launch container mode. resourcekey?: string; // Resource key. password?: string; // Shared secret. debuglaunch?: number; // Debug launch. showtitlelaunch?: number; // Show title launch. showdescriptionlaunch?: number; // Show description launch. servicesalt?: string; // Service salt. icon?: string; // Alternative icon URL. secureicon?: string; // Secure icon URL. section?: number; // Course section id. visible?: number; // Visible. groupmode?: number; // Group mode. groupingid?: number; // Group id. }; /** * Params of mod_lti_get_tool_launch_data WS. */ export type AddonModLtiGetToolLaunchDataWSParams = { toolid: number; // External tool instance id. }; /** * Data returned by mod_lti_get_tool_launch_data WS. */ export type AddonModLtiGetToolLaunchDataWSResponse = { endpoint: string; // Endpoint URL. parameters: AddonModLtiParam[]; warnings?: CoreWSExternalWarning[]; }; /** * Param to send to the LTI. */ export type AddonModLtiParam = { name: string; // Parameter name. value: string; // Parameter value. }; /** * Params of mod_lti_view_lti WS. */ export type AddonModLtiViewLtiWSParams = { ltiid: number; // Lti instance id. };
the_stack
import * as React from 'react'; import { DateUtils, RangeModifier, DayModifiers } from 'react-day-picker'; import fnsIsSameDay from 'date-fns/isSameDay'; import MonthPicker from '@synerise/ds-date-picker/dist/Elements/MonthPicker/MonthPicker'; import MomentLocaleUtils from 'react-day-picker/moment'; import TimePicker from '@synerise/ds-date-picker/dist/Elements/TimePicker/TimePicker'; import { DayBackground, DayForeground, DayText, DayTooltip, } from '@synerise/ds-date-picker/dist/Elements/DayPicker/DayPicker.styles'; import YearPicker from '@synerise/ds-date-picker/dist/Elements/YearPicker/YearPicker'; import DayPicker from '@synerise/ds-date-picker/dist/Elements/DayPicker/DayPicker'; import Icon from '@synerise/ds-icon'; import { CalendarM, ClockM } from '@synerise/ds-icon/dist/icons'; import { fnsDifferenceInYears } from '@synerise/ds-date-picker/dist/fns'; import fnsFormat from '@synerise/ds-date-picker/dist/format'; import { legacyParse } from '@date-fns/upgrade/v2'; import { Range } from '../RelativeRangePicker/RelativeRangePicker.styles'; import { fnsStartOfDay, fnsEndOfDay, fnsIsSameMonth, fnsIsAfter, fnsAddMinutes, fnsAddDays } from '../fns'; import * as S from './RangePicker.styles'; import { ABSOLUTE, COLUMNS, MODES } from '../constants'; import ADD from '../dateUtils/add'; import { DateFilter } from '../date.types'; import { Props, State, Side as SideType } from './RangePicker.types'; import getDateFromString from '../dateUtils/getDateFromString'; import { getSidesState, getDisabledTimeOptions, getModifiers } from './utils'; // eslint-disable-next-line @typescript-eslint/no-empty-function const NOOP = (): void => {}; const TOOLTIP_FORMAT = 'MMM d, yyyy, HH:mm'; export default class RangePicker extends React.PureComponent<Props, State> { constructor(props: Props) { super(props); // eslint-disable-next-line react/state-in-constructor this.state = { enteredTo: null, ...getSidesState(props.value), }; } getSnapshotBeforeUpdate(prevProps: Readonly<Props>): null { const { value, forceAdjacentMonths } = this.props; const { left } = this.state; if ( (!!value?.to && value?.to !== prevProps?.value?.to && !fnsIsSameMonth(legacyParse(value.to), legacyParse(left.month))) || (!!value?.from && value?.from !== prevProps?.value?.from && !fnsIsSameMonth(legacyParse(value.from), legacyParse(left.month))) || forceAdjacentMonths !== prevProps.forceAdjacentMonths ) { this.setState(getSidesState(value, forceAdjacentMonths)); } return null; } componentDidUpdate = NOOP; handleDayMouseEnter = (day: Date): void => { this.setState({ enteredTo: day }); }; handleDayMouseLeave = (): void => { this.setState({ enteredTo: null }); }; handleDayClick = (day: Date, modifiers: DayModifiers, e: React.MouseEvent<HTMLDivElement>): void => { e.preventDefault(); const { value, onChange } = this.props; if (modifiers.disabled) return; let { from, to } = DateUtils.addDayToRange(day, value as RangeModifier); from = from ? fnsStartOfDay(from) : from; to = to ? fnsEndOfDay(to) : to; if (to) { const now = new Date(); if (fnsIsSameDay(legacyParse(to), legacyParse(now))) { to = now; } } onChange && onChange({ type: ABSOLUTE, from, to }); }; handleFromTimeChange = (from: string | Date | undefined): void => { const { onChange, value } = this.props; onChange({ type: ABSOLUTE, from, to: value.to }); }; handleToTimeChange = (to: string | Date | undefined): void => { const { onChange, value } = this.props; onChange({ type: ABSOLUTE, from: value.from, to }); }; handleAddDay = (numberOfDays: number, side: string): void => { if (side === COLUMNS.LEFT) { const { onChange, value } = this.props; onChange({ ...value, type: ABSOLUTE, from: fnsAddDays(legacyParse(value.from), numberOfDays) }); } if (side === COLUMNS.RIGHT) { const { onChange, value } = this.props; onChange({ ...value, type: ABSOLUTE, to: fnsAddDays(legacyParse(value.to), numberOfDays) }); } }; handleSideMonthChange = (side: 'left' | 'right', month: Date, mode: string): void => { const opposite = side === COLUMNS.LEFT ? COLUMNS.RIGHT : COLUMNS.LEFT; const { state } = this; const { forceAdjacentMonths } = this.props; if (fnsIsSameMonth(month, state[opposite])) { const dir = fnsIsAfter(month, legacyParse(state[side].month)) ? 1 : -1; const adjacentMonth = ADD.MONTHS(month, dir); this.setState(prevState => ({ ...prevState, [side]: { ...state[side], adjacentMonth, mode } })); return; } if (forceAdjacentMonths) { const dir = side === COLUMNS.RIGHT ? -1 : 1; this.setState(prevState => ({ ...prevState, [opposite]: { ...state[opposite], month: ADD.MONTHS(month, dir) }, [side]: { ...state[side], month, mode }, })); return; } this.setState(prevState => ({ ...prevState, [side]: { ...state[side], month, mode } })); }; handleSideModeChange = (side: string, mode: string): void => { this.setState(prevState => ({ ...prevState, [side]: { ...prevState[side], mode } })); }; renderDay = (day: Date): React.ReactNode => { const text = day.getDate(); const { value, intl } = this.props; return ( <> <DayBackground className="DayPicker-Day-BG" /> <DayText className="DayPicker-Day-Text" data-attr={text}> {value.to && value.from && ( <DayTooltip> {fnsFormat(legacyParse(value.from), TOOLTIP_FORMAT, intl.locale)} -{' '} {fnsFormat(legacyParse(value.to), TOOLTIP_FORMAT, intl.locale)} </DayTooltip> )} {text} </DayText> <DayForeground className="DayPicker-Day-FG" /> </> ); }; renderYearPicker = (side: SideType): React.ReactNode => { const { [side]: currentSide } = this.state; const { month } = currentSide; return ( <YearPicker key={`year_picker_${side}`} value={month instanceof Date ? month : new Date(month)} onChange={(m: Date): void => this.handleSideMonthChange(side, m, 'date')} /> ); }; renderMonthPicker = (side: SideType): React.ReactNode => { const opposite: SideType = side === COLUMNS.LEFT ? (COLUMNS.RIGHT as SideType) : (COLUMNS.LEFT as SideType); const { [side]: currentSide, [opposite]: oppositeSide } = this.state; const oppositeMonth = legacyParse(oppositeSide.month); return ( <MonthPicker key={`month_picker_${opposite}`} max={side === COLUMNS.LEFT ? ADD.MONTHS(oppositeMonth, -1) : undefined} min={side === COLUMNS.RIGHT ? ADD.MONTHS(oppositeMonth, 1) : undefined} value={currentSide.month instanceof Date ? currentSide.month : new Date(currentSide.month)} onChange={(month: Date): void => this.handleSideMonthChange(side, month, 'date')} /> ); }; renderDatePicker = (side: SideType): React.ReactNode => { const { value, disabledDate, forceAdjacentMonths } = this.props; const { enteredTo, left, right, [side]: sideState } = this.state; const { from, to, type } = value; const modifiers = getModifiers(from, to, enteredTo); const selectedDays = [from, { from, to } as DateFilter]; const parsedLeft = legacyParse(left.month); const parsedRight = legacyParse(right.month); const adjacentMonths = forceAdjacentMonths || fnsIsSameMonth(ADD.MONTHS(parsedLeft, 1), parsedRight); const adjacentYears = forceAdjacentMonths || fnsDifferenceInYears(ADD.MONTHS(parsedLeft, 1), parsedRight) === 0; return ( <DayPicker key={`day_picker_${side}`} className={type.toLowerCase()} canChangeMonth={false} disabledDays={disabledDate} localeUtils={MomentLocaleUtils} month={getDateFromString(sideState.month)} title={sideState.monthTitle} hideLongNext={side === COLUMNS.LEFT && adjacentYears} hideShortNext={side === COLUMNS.LEFT && adjacentMonths} hideLongPrev={side === COLUMNS.RIGHT && adjacentYears} hideShortPrev={side === COLUMNS.RIGHT && adjacentMonths} renderDay={this.renderDay} onDayMouseEnter={this.handleDayMouseEnter} onDayMouseLeave={this.handleDayMouseLeave} onMonthNameClick={(): void => this.handleSideModeChange(side, 'month')} onYearNameClick={(): void => this.handleSideModeChange(side, 'year')} onMonthChange={(month: Date): void => this.handleSideMonthChange(side, month, 'date')} fixedWeeks showOutsideDay modifiers={modifiers} // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore onDayClick={this.handleDayClick} // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore selectedDays={selectedDays} /> ); }; renderTimePicker = (side: SideType): React.ReactNode => { const { value } = this.props; const { from, to } = value; if (!from || !to) { return null; } const sidesAreAdjacent = fnsIsSameDay(legacyParse(from), legacyParse(to)); switch (side) { case COLUMNS.LEFT: { return ( <TimePicker key={`time-picker-${side}`} value={getDateFromString(from)} onChange={this.handleFromTimeChange} disabledHours={getDisabledTimeOptions(from, 'HOURS', null, to)} disabledMinutes={getDisabledTimeOptions(from, 'MINUTES', null, to)} disabledSeconds={getDisabledTimeOptions(from, 'SECONDS', null, to)} onShortNext={ sidesAreAdjacent ? undefined : (): void => { this.handleAddDay(1, COLUMNS.LEFT); } } onShortPrev={(): void => { this.handleAddDay(-1, COLUMNS.LEFT); }} /> ); } case COLUMNS.RIGHT: { return ( <TimePicker key={`time-picker-${side}`} value={getDateFromString(to)} onChange={this.handleToTimeChange} disabledHours={getDisabledTimeOptions(to, 'HOURS', from, null)} disabledMinutes={getDisabledTimeOptions(to, 'MINUTES', from, null)} disabledSeconds={getDisabledTimeOptions(to, 'SECONDS', from, null)} onShortNext={(): void => { this.handleAddDay(1, COLUMNS.RIGHT); }} onShortPrev={ sidesAreAdjacent ? undefined : (): void => { this.handleAddDay(-1, COLUMNS.RIGHT); } } /> ); } default: return null; } }; renderSide = (side: SideType): React.ReactNode | null => { const { mode } = this.props; const { [side]: sideState } = this.state; if (mode === MODES.TIME) return this.renderTimePicker(side); switch (sideState.mode) { case 'date': return this.renderDatePicker(side); case 'month': return this.renderMonthPicker(side); case 'year': return this.renderYearPicker(side); default: return null; } }; render(): JSX.Element { const { mode, onChange, value, canSwitchMode, dateOnly, onSwitchMode, texts } = this.props; return ( <> <S.Sides> <S.Side mode={mode}>{this.renderSide(COLUMNS.LEFT as SideType)}</S.Side> <S.Side mode={mode}>{this.renderSide(COLUMNS.RIGHT as SideType)}</S.Side> </S.Sides> <S.PickerFooter> <Range onClick={(): void => { onChange({ ...value, type: 'ABSOLUTE', to: fnsAddMinutes(new Date(), 1), from: new Date() }); }} > {texts.now} </Range> <S.FooterSeparator /> {!dateOnly && ( <S.DateTimeModeSwitch type="ghost" mode="label-icon" disabled={!canSwitchMode} onClick={onSwitchMode} className="ds-date-time-switch" > {mode === MODES.TIME ? texts.selectDate : texts.selectTime} <Icon component={mode === MODES.TIME ? <CalendarM /> : <ClockM />} /> </S.DateTimeModeSwitch> )} </S.PickerFooter> </> ); } }
the_stack
import React, { PureComponent } from 'react'; import { registerComponent, Components } from '../../lib/vulcan-lib'; import { withUpdateCurrentUser, WithUpdateCurrentUserProps } from '../hooks/useUpdateCurrentUser'; import { withSingle } from '../../lib/crud/withSingle'; import withUser, { useCurrentUser } from '../common/withUser'; import withErrorBoundary from '../common/withErrorBoundary' import Paper from '@material-ui/core/Paper'; import IconButton from '@material-ui/core/IconButton'; import { Link } from '../../lib/reactRouterWrapper'; import Users from '../../lib/collections/users/collection'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import Badge from '@material-ui/core/Badge'; import StarIcon from '@material-ui/icons/Star'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import MenuItem from '@material-ui/core/MenuItem'; import { karmaNotificationTimingChoices } from './KarmaChangeNotifierSettings' import { postGetPageUrl } from '../../lib/collections/posts/helpers'; import { commentGetPageUrlFromIds } from '../../lib/collections/comments/helpers'; import { withTracking, AnalyticsContext } from '../../lib/analyticsEvents'; import { taggingNameIsSet, taggingNamePluralSetting } from '../../lib/instanceSettings'; const styles = (theme: ThemeType): JssStyles => ({ root: { display: 'flex', alignItems: 'center', }, karmaNotifierButton: { }, karmaNotifierPaper: { }, karmaNotifierPopper: { zIndex: theme.zIndexes.karmaChangeNotifier, }, starIcon: { color: theme.palette.header.text, }, title: { display: 'block', paddingTop: theme.spacing.unit * 2, paddingLeft: theme.spacing.unit * 2, paddingRight: theme.spacing.unit * 2, paddingBottom: theme.spacing.unit }, votedItems: { }, votedItemRow: { height: 20 }, votedItemScoreChange: { display: "inline-block", minWidth: 20, textAlign: "right", }, votedItemDescription: { display: "inline-block", marginLeft: 5, whiteSpace: "nowrap", overflow: "hidden", maxWidth: 250, textOverflow: "ellipsis" }, singleLinePreview: { whiteSpace: "nowrap", overflow: "hidden", maxWidth: 300, }, pointBadge: { fontSize: '0.9rem' }, gainedPoints: { color: theme.palette.primary.main, }, zeroPoints: { }, lostPoints: { }, settings: { display: 'block', textAlign: 'right', paddingTop: theme.spacing.unit, paddingRight: theme.spacing.unit * 2, paddingLeft: theme.spacing.unit * 2, paddingBottom: theme.spacing.unit * 2, color: theme.palette.grey[600], '&:hover': { color: theme.palette.grey[500] } }, }); // Given a number, return a span of it as a string, with a plus sign if it's // positive, and green, red, or black coloring for positive, negative, and // zero, respectively. const ColoredNumber = ({n, classes}: { n: number, classes: ClassesType }) => { if (n>0) { return <span className={classes.gainedPoints}>{`+${n}`}</span> } else if (n==0) { return <span className={classes.zeroPoints}>{n}</span> } else { return <span className={classes.lostPoints}>{n}</span> } } const KarmaChangesDisplay = ({karmaChanges, classes, handleClose }: { karmaChanges: any, classes: ClassesType, handleClose: (ev: MouseEvent)=>any, }) => { const { posts, comments, tagRevisions, updateFrequency } = karmaChanges const currentUser = useCurrentUser(); const noKarmaChanges = !( (posts && (posts.length > 0)) || (comments && (comments.length > 0)) || (tagRevisions && (tagRevisions.length > 0)) ) // MenuItem takes a component and passes unrecognized props to that component, // but its material-ui-provided type signature does not include this feature. // Case to any to work around it, to be able to pass a "to" parameter. const MenuItemUntyped = MenuItem as any; return ( <Components.Typography variant="body2"> {noKarmaChanges ? <span className={classes.title}>{ karmaNotificationTimingChoices[updateFrequency].emptyText }</span> : <div> <span className={classes.title}>{ karmaNotificationTimingChoices[updateFrequency].infoText }</span> <div className={classes.votedItems}> {karmaChanges.posts && karmaChanges.posts.map(postChange => ( <MenuItemUntyped className={classes.votedItemRow} component={Link} to={postGetPageUrl(postChange)} key={postChange._id} > <span className={classes.votedItemScoreChange}> <ColoredNumber n={postChange.scoreChange} classes={classes}/> </span> <div className={classes.votedItemDescription}> {postChange.title} </div> </MenuItemUntyped> ))} {karmaChanges.comments && karmaChanges.comments.map(commentChange => ( <MenuItemUntyped className={classes.votedItemRow} component={Link} to={commentGetPageUrlFromIds({postId:commentChange.postId, postSlug:commentChange.postSlug, tagSlug:commentChange.tagSlug, commentId: commentChange._id})} key={commentChange._id} > <span className={classes.votedItemScoreChange}> <ColoredNumber n={commentChange.scoreChange} classes={classes}/> </span> <div className={classes.votedItemDescription}> {commentChange.description} </div> </MenuItemUntyped> ))} {karmaChanges.tagRevisions.map(tagChange => ( <MenuItemUntyped className={classes.votedItemRow} component={Link} key={tagChange._id} to={`/${taggingNameIsSet.get() ? taggingNamePluralSetting.get() : 'tag'}/${tagChange.tagSlug}/history?user=${currentUser!.slug}`} > <span className={classes.votedItemScoreChange}> <ColoredNumber n={tagChange.scoreChange} classes={classes}/> </span> <div className={classes.votedItemDescription}> {tagChange.tagName} </div> </MenuItemUntyped> ))} </div> </div> } <Link to={`/account`} onClick={handleClose}> <span className={classes.settings}>Change Settings </span> </Link> </Components.Typography> ); } interface ExternalProps { documentId: string, } interface KarmaChangeNotifierProps extends ExternalProps, WithUserProps, WithUpdateCurrentUserProps, WithStylesProps, WithTrackingProps { document: UserKarmaChanges } interface KarmaChangeNotifierState { cleared: boolean, open: boolean, anchorEl: HTMLElement|null, karmaChanges: any, karmaChangeLastOpened: Date, } class KarmaChangeNotifier extends PureComponent<KarmaChangeNotifierProps,KarmaChangeNotifierState> { state: KarmaChangeNotifierState = { cleared: false, open: false, anchorEl: null, karmaChanges: this.props.document?.karmaChanges, karmaChangeLastOpened: this.props.currentUser?.karmaChangeLastOpened || new Date(), }; handleOpen = (event) => { this.setState({ open: true, anchorEl: event.currentTarget, karmaChangeLastOpened: new Date() }); } handleToggle = (e) => { const { open } = this.state const { captureEvent } = this.props if (open) { this.handleClose(null) // When closing from toggle, force a close by not providing an event } else { this.handleOpen(e) } captureEvent("karmaNotifierToggle", {open: !open, karmaChangeLastOpened: this.state.karmaChangeLastOpened, karmaChanges: this.state.karmaChanges}) } handleClose = (e) => { const { document, updateCurrentUser, currentUser } = this.props; const { anchorEl } = this.state if (e && anchorEl?.contains(e.target)) { return; } this.setState({ open: false, anchorEl: null, }); if (!currentUser) return; if (document?.karmaChanges) { void updateCurrentUser({ karmaChangeLastOpened: document.karmaChanges.endDate, karmaChangeBatchStart: document.karmaChanges.startDate }); if (document.karmaChanges.updateFrequency === "realtime") { this.setState({cleared: true}); } } } render() { const {document, classes, currentUser} = this.props; if (!currentUser || !document) return null const {open, anchorEl, karmaChanges: stateKarmaChanges, karmaChangeLastOpened} = this.state; const karmaChanges = stateKarmaChanges || document.karmaChanges; // Covers special case when state was initialized when user wasn't logged in if (!karmaChanges) return null; const { karmaChangeNotifierSettings: settings } = currentUser if (settings && settings.updateFrequency === "disabled") return null; const { posts, comments, tagRevisions, endDate, totalChange } = karmaChanges //Check if user opened the karmaChangeNotifications for the current interval const newKarmaChangesSinceLastVisit = new Date(karmaChangeLastOpened || 0) < new Date(endDate || 0) const starIsHollow = ((comments.length===0 && posts.length===0 && tagRevisions.length===0) || this.state.cleared || !newKarmaChangesSinceLastVisit) const { LWPopper } = Components; return <AnalyticsContext pageSection="karmaChangeNotifer"> <div className={classes.root}> <IconButton onClick={this.handleToggle} className={classes.karmaNotifierButton}> {starIsHollow ? <StarBorderIcon className={classes.starIcon}/> : <Badge badgeContent={<span className={classes.pointBadge}><ColoredNumber n={totalChange} classes={classes}/></span>}> <StarIcon className={classes.starIcon}/> </Badge> } </IconButton> <LWPopper open={open} anchorEl={anchorEl} placement="bottom-end" className={classes.karmaNotifierPopper} > <ClickAwayListener onClickAway={this.handleClose}> <Paper className={classes.karmaNotifierPaper}> <KarmaChangesDisplay karmaChanges={karmaChanges} classes={classes} handleClose={this.handleClose} /> </Paper> </ClickAwayListener> </LWPopper> </div> </AnalyticsContext> } } const KarmaChangeNotifierComponent = registerComponent<ExternalProps>('KarmaChangeNotifier', KarmaChangeNotifier, { styles, hocs: [ withUser, withErrorBoundary, withSingle({ collection: Users, fragmentName: 'UserKarmaChanges' }), withUpdateCurrentUser, withTracking ] }); declare global { interface ComponentTypes { KarmaChangeNotifier: typeof KarmaChangeNotifierComponent } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { LiveEvent, LiveEventsListOptionalParams, LiveEventsGetOptionalParams, LiveEventsGetResponse, LiveEventsCreateOptionalParams, LiveEventsCreateResponse, LiveEventsUpdateOptionalParams, LiveEventsUpdateResponse, LiveEventsDeleteOptionalParams, LiveEventsAllocateOptionalParams, LiveEventsStartOptionalParams, LiveEventActionInput, LiveEventsStopOptionalParams, LiveEventsResetOptionalParams } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a LiveEvents. */ export interface LiveEvents { /** * Lists all the live events in the account. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param options The options parameters. */ list( resourceGroupName: string, accountName: string, options?: LiveEventsListOptionalParams ): PagedAsyncIterableIterator<LiveEvent>; /** * Gets properties of a live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ get( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsGetOptionalParams ): Promise<LiveEventsGetResponse>; /** * Creates a new live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param parameters Live event properties needed for creation. * @param options The options parameters. */ beginCreate( resourceGroupName: string, accountName: string, liveEventName: string, parameters: LiveEvent, options?: LiveEventsCreateOptionalParams ): Promise< PollerLike< PollOperationState<LiveEventsCreateResponse>, LiveEventsCreateResponse > >; /** * Creates a new live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param parameters Live event properties needed for creation. * @param options The options parameters. */ beginCreateAndWait( resourceGroupName: string, accountName: string, liveEventName: string, parameters: LiveEvent, options?: LiveEventsCreateOptionalParams ): Promise<LiveEventsCreateResponse>; /** * Updates settings on an existing live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param parameters Live event properties needed for patch. * @param options The options parameters. */ beginUpdate( resourceGroupName: string, accountName: string, liveEventName: string, parameters: LiveEvent, options?: LiveEventsUpdateOptionalParams ): Promise< PollerLike< PollOperationState<LiveEventsUpdateResponse>, LiveEventsUpdateResponse > >; /** * Updates settings on an existing live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param parameters Live event properties needed for patch. * @param options The options parameters. */ beginUpdateAndWait( resourceGroupName: string, accountName: string, liveEventName: string, parameters: LiveEvent, options?: LiveEventsUpdateOptionalParams ): Promise<LiveEventsUpdateResponse>; /** * Deletes a live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginDelete( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes a live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsDeleteOptionalParams ): Promise<void>; /** * A live event is in StandBy state after allocation completes, and is ready to start. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginAllocate( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsAllocateOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * A live event is in StandBy state after allocation completes, and is ready to start. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginAllocateAndWait( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsAllocateOptionalParams ): Promise<void>; /** * A live event in Stopped or StandBy state will be in Running state after the start operation * completes. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginStart( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsStartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * A live event in Stopped or StandBy state will be in Running state after the start operation * completes. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginStartAndWait( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsStartOptionalParams ): Promise<void>; /** * Stops a running live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param parameters LiveEvent stop parameters * @param options The options parameters. */ beginStop( resourceGroupName: string, accountName: string, liveEventName: string, parameters: LiveEventActionInput, options?: LiveEventsStopOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Stops a running live event. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param parameters LiveEvent stop parameters * @param options The options parameters. */ beginStopAndWait( resourceGroupName: string, accountName: string, liveEventName: string, parameters: LiveEventActionInput, options?: LiveEventsStopOptionalParams ): Promise<void>; /** * Resets an existing live event. All live outputs for the live event are deleted and the live event is * stopped and will be started again. All assets used by the live outputs and streaming locators * created on these assets are unaffected. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginReset( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsResetOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Resets an existing live event. All live outputs for the live event are deleted and the live event is * stopped and will be started again. All assets used by the live outputs and streaming locators * created on these assets are unaffected. * @param resourceGroupName The name of the resource group within the Azure subscription. * @param accountName The Media Services account name. * @param liveEventName The name of the live event, maximum length is 32. * @param options The options parameters. */ beginResetAndWait( resourceGroupName: string, accountName: string, liveEventName: string, options?: LiveEventsResetOptionalParams ): Promise<void>; }
the_stack
import express from 'express'; import * as fs from 'fs'; import JSZip from 'jszip'; import * as ThingTalk from 'thingtalk'; import * as stream from 'stream'; import deq from 'deep-equal'; import * as util from 'util'; import * as model from '../model/device'; import * as schemaModel from '../model/schema'; import * as exampleModel from '../model/example'; import * as entityModel from '../model/entity'; import * as user from './user'; import * as I18n from './i18n'; import * as graphics from '../almond/graphics'; import colorScheme from './color_scheme'; import * as Validation from './validation'; import * as code_storage from './code_storage'; import * as SchemaUtils from './manifest_to_schema'; import * as DatasetUtils from './dataset'; import * as FactoryUtils from './device_factories'; import TrainingServer from './training_server'; import { NotFoundError, ForbiddenError, BadRequestError } from './errors'; import * as db from './db'; import * as EngineManager from '../almond/enginemanagerclient'; type RequestLike = Validation.RequestLike; function areMetaIdentical(one : schemaModel.SchemaMetadata, two : schemaModel.SchemaMetadata) { for (const what of ['queries', 'actions'] as const) { const oneKeys = Object.keys(one[what]).sort(); const twoKeys = Object.keys(two[what]).sort(); if (oneKeys.length !== twoKeys.length) return false; for (let i = 0; i < oneKeys.length; i++) { if (oneKeys[i] !== twoKeys[i]) return false; // ignore confirmation remote in comparison one[what][oneKeys[i]].confirmation_remote = two[what][twoKeys[i]].confirmation_remote; if (!deq(one[what][oneKeys[i]], two[what][twoKeys[i]], { strict: true })) return false; } } return true; } async function ensurePrimarySchema(dbClient : db.Client, name : string, classDef : ThingTalk.Ast.ClassDef, req : RequestLike, approve : boolean) : Promise<[number, boolean]> { const metas = SchemaUtils.classDefToSchema(classDef); return schemaModel.getByKind(dbClient, classDef.kind).then(async (existing) => { if (existing.owner !== req.user!.developer_org && (req.user!.roles & user.Role.THINGPEDIA_ADMIN) === 0) throw new ForbiddenError(); const existingMeta = (await schemaModel.getMetasByKindAtVersion(dbClient, classDef.kind, existing.developer_version, 'en'))[0]; if (areMetaIdentical(existingMeta, metas)) { console.log('Skipped updating of schema: identical to previous version'); if (existing.approved_version === null && approve) await schemaModel.approveByKind(dbClient, classDef.kind); return [existing.id, false]; } const obj : { kind_canonical : string, developer_version : number, approved_version ?: number } = { kind_canonical: classDef.metadata.canonical, developer_version: existing.developer_version + 1 }; if (approve) obj.approved_version = obj.developer_version; await schemaModel.update(dbClient, existing.id, existing.kind, obj, metas); return [existing.id, true]; }, async (e) => { const obj = { kind: classDef.kind, kind_canonical: classDef.metadata.canonical, kind_type: 'primary', owner: req.user!.developer_org!, approved_version: approve ? 0 : null, developer_version: 0 } as const; const schema = await schemaModel.create(dbClient, obj, metas); return [schema.id, true]; }); } async function ensureDataset(dbClient : db.Client, schemaId : number, classDef : ThingTalk.Ast.ClassDef|null, dataset : ThingTalk.Ast.Dataset) { /* This functions does three things: - it fetches the list of existing examples in the database - it matches the names against the examples in the dataset file and updates the database - it creates fresh examples for secondary utterances */ const tokenizer = I18n.get(dataset.language || 'en').genie.getTokenizer(); const existingMap = new Map; const toDelete = new Set<number>(); const old = await exampleModel.getBaseBySchema(dbClient, schemaId, dataset.language || 'en', !!classDef /* includeSynthetic */); for (const row of old) { if (row.name) existingMap.set(row.name, row); toDelete.add(row.id); } const toCreate = []; const toUpdate = []; // make up examples for the queries and actions in the class definition // these examples have the synthetic flag so they don't show up in most // APIs, but they do show up in commandpedia and in the cheatsheet if (classDef) { for (const qname in classDef.queries) { const query = classDef.queries[qname]; for (const phrase of query.metadata.canonical) { toCreate.push({ utterance: phrase, preprocessed: tokenizer.tokenize(phrase).rawTokens.join(' '), target_code: 'query = @' + classDef.kind + '.' + qname + '();', name: null, flags: 'template,synthetic', }); } } for (const aname in classDef.actions) { const action = classDef.actions[aname]; for (const phrase of action.metadata.canonical) { toCreate.push({ utterance: phrase, preprocessed: tokenizer.tokenize(phrase).rawTokens.join(' '), target_code: 'action = @' + classDef.kind + '.' + aname + '();', name: null, flags: 'template,synthetic', }); } } } for (const example of dataset.examples) { const code = DatasetUtils.exampleToCode(example); const name = example.annotations.name.toJS() as string; let mustCreate = true; if (name && existingMap.has(name)) { const existing = existingMap.get(name); if (existing.target_code === code && existing.language === (dataset.language || 'en')) { toDelete.delete(existing.id); if (existing.utterance !== example.utterances[0]) { toUpdate.push({ id: existing.id, utterance: example.utterances[0], preprocessed: example.preprocessed[0] }); } mustCreate = false; } } if (mustCreate) { toCreate.push({ utterance: example.utterances[0], preprocessed: example.preprocessed[0], target_code: code, name, flags: 'template', }); } for (let i = 1; i < example.utterances.length; i++) { toCreate.push({ utterance: example.utterances[i], preprocessed: example.preprocessed[i], target_code: code, name: null, flags: 'template', }); } } if (toDelete.size === 0 && toCreate.length === 0 && toUpdate.length === 0) return false; // delete first so we don't race with insertions and get duplicate keys await exampleModel.deleteMany(dbClient, Array.from(toDelete)); await Promise.all([ Promise.all(toUpdate.map((ex) => { return exampleModel.update(dbClient, ex.id, ex); })), exampleModel.createMany(dbClient, toCreate.map((ex) => { return ({ schema_id: schemaId, utterance: ex.utterance, preprocessed: ex.preprocessed, target_code: ex.target_code, target_json: '', // FIXME type: 'thingpedia', language: dataset.language || 'en', is_base: true, flags: ex.flags, name: ex.name }); }), false) ]); return true; } interface SimpleDevice { primary_kind : string; developer_version : number; } function uploadZipFile(req : RequestLike, obj : SimpleDevice, fromStream : stream.Readable) { const zipFile = new JSZip(); return Promise.resolve().then(() => { // unfortunately JSZip only loads from memory, so we need to load the entire file // at once // this is somewhat a problem, because the file can be up to 30-50MB in size // we just hope the GC will get rid of the buffer quickly const buffers : Buffer[] = []; let length = 0; return new Promise<Buffer>((callback, errback) => { fromStream.on('data', (buffer) => { buffers.push(buffer); length += buffer.length; }); fromStream.on('end', () => { callback(Buffer.concat(buffers, length)); }); fromStream.on('error', errback); }); }).then((buffer) => { return zipFile.loadAsync(buffer, { checkCRC32: false }); }).then(() => { const packageJson = zipFile.file('package.json'); if (!packageJson) throw new BadRequestError(req._("package.json missing from device zip file")); return packageJson.async('string'); }).then((text) => { let parsed; try { parsed = JSON.parse(text); } catch(e) { throw new BadRequestError("Invalid package.json: SyntaxError at line " + e.lineNumber + ": " + e.message); } if (!parsed.name || (!parsed.main && !zipFile.file('index.js'))) throw new BadRequestError(req._("Invalid package.json (missing name or main)")); parsed['thingpedia-version'] = obj.developer_version; zipFile.file('package.json', JSON.stringify(parsed)); return code_storage.storeZipFile(zipFile.generateNodeStream({ compression: 'DEFLATE', type: 'nodebuffer', platform: 'UNIX'}), obj.primary_kind, obj.developer_version); }).catch((e) => { console.error('Failed to upload zip file to S3: ' + e); e.status = 400; throw e; }); } function uploadJavaScript(req : RequestLike, obj : SimpleDevice, stream : stream.Readable) { const zipFile = new JSZip(); return Promise.resolve().then(() => { zipFile.file('package.json', JSON.stringify({ name: obj.primary_kind, author: req.user!.username + '@thingpedia.stanford.edu', main: 'index.js', 'thingpedia-version': obj.developer_version })); zipFile.file('index.js', stream); return code_storage.storeZipFile(zipFile.generateNodeStream({ compression: 'DEFLATE', type: 'nodebuffer', platform: 'UNIX'}), obj.primary_kind, obj.developer_version); }).catch((e) => { console.error('Failed to upload zip file to S3: ' + e); console.error(e.stack); throw e; }); } function isDownloadable(classDef : ThingTalk.Ast.ClassDef) { const loader = classDef.loader; return !classDef.is_abstract && Validation.JAVASCRIPT_MODULE_TYPES.has(loader!.module) && loader!.module !== 'org.thingpedia.builtin' && loader!.module !== 'org.thingpedia.embedded'; } function getCategory(classDef : ThingTalk.Ast.ClassDef) { if (classDef.annotations.system && classDef.annotations.system.toJS()) return 'system'; if (classDef.is_abstract) return 'system'; if (classDef.loader!.module === 'org.thingpedia.builtin') { switch (classDef.kind) { case 'org.thingpedia.builtin.thingengine.gnome': case 'org.thingpedia.builtin.thingengine.phone': case 'org.thingpedia.builtin.thingengine.home': return 'physical'; } } switch (classDef.config!.module) { case 'org.thingpedia.config.builtin': case 'org.thingpedia.config.none': return 'data'; case 'org.thingpedia.config.discovery.bluetooth': case 'org.thingpedia.config.discovery.upnp': return 'physical'; default: return 'online'; } } async function uploadIcon(primary_kind : string, iconPath : string, deleteAfterwards = true) { try { const image = graphics.createImageFromPath(iconPath); image.resizeFit(512, 512); const stdout = await image.stream('png'); // we need to consume the stream twice: once // to upload to S3 / store on reliable file system // and the other time to compute the color scheme // // in theory, nodejs supports this // in practice, it depends heavily on what each library // is doing, and I don't want to dig too deep in their // source code (plus it could break at any moment) // // instead, we create a separate PassThrough for each // destination const pt1 = new stream.PassThrough(); stdout.pipe(pt1); const pt2 = new stream.PassThrough(); stdout.pipe(pt2); // we must run the two consumers in parallel, or one of // the streams will be forced to buffer everything in memory // and we'll be sad const [,result] = await Promise.all([ code_storage.storeIcon(pt1, primary_kind), colorScheme(pt2) ]); return result; } finally { if (deleteAfterwards) await util.promisify(fs.unlink)(iconPath); } } interface ImportDeviceMetadata { thingpedia_name : string; thingpedia_description : string; subcategory : string; license ?: string; license_gplcompatible ?: boolean; website ?: string; repository ?: string; issue_tracker ?: string; class : string; dataset : string; } interface ImportDeviceOptions { owner ?: number; zipFilePath ?: string|null; iconPath ?: string|null; approve ?: boolean; } function entityStatementToEntityTypeRow(classDef : ThingTalk.Ast.ClassDef, stmt : ThingTalk.Ast.EntityDef) { let subtype_of = null; if (stmt.extends && stmt.extends.length) { if (stmt.extends.length === 1) { const parent = stmt.extends[0]; subtype_of = parent.includes(':') ? parent : classDef.kind + ':' + parent; } else { subtype_of = JSON.stringify(stmt.extends.map((parent) => parent.includes(':') ? parent : classDef.kind + ':' + parent)); } } return { name: stmt.nl_annotations.description as string, language: 'en', id: classDef.kind + ':' + stmt.name, is_well_known: false, has_ner_support: stmt.impl_annotations.has_ner ? stmt.impl_annotations.has_ner.toJS() as boolean : true, subtype_of }; } async function importDevice(dbClient : db.Client, req : RequestLike, primary_kind : string, json : ImportDeviceMetadata, { owner = 0, zipFilePath = null, iconPath = null, approve = true } : ImportDeviceOptions) { const device = { primary_kind: primary_kind, owner: owner, name: json.thingpedia_name, description: json.thingpedia_description, license: json.license || 'GPL-3.0', license_gplcompatible: json.license_gplcompatible ?? true, website: json.website || '', repository: json.repository || '', issue_tracker: json.issue_tracker || (json.repository ? json.repository + '/issues' : ''), category: 'system' as 'system'|'online'|'data'|'physical', subcategory: json.subcategory, approved_version: (approve ? 0 : null), developer_version: 0, source_code: json.class, colors_dominant: '', colors_palette_default: '', colors_palette_light: '', }; const [classDef, dataset] = await Validation.validateDevice(dbClient, req, device, json.class, json.dataset); await Validation.tokenizeDataset(dataset); device.category = getCategory(classDef); const [schemaId,] = await ensurePrimarySchema(dbClient, device.name, classDef, req, approve); await ensureDataset(dbClient, schemaId, classDef, dataset); if (classDef.entities.length > 0) { await entityModel.updateMany(dbClient, classDef.entities.map((stmt) => entityStatementToEntityTypeRow(classDef, stmt))); } const factory = FactoryUtils.makeDeviceFactory(classDef, device); classDef.annotations.version = new ThingTalk.Ast.Value.Number(device.developer_version); classDef.annotations.package_version = new ThingTalk.Ast.Value.Number(device.developer_version); const versionedInfo = { code: classDef.prettyprint(), factory: JSON.stringify(factory), downloadable: isDownloadable(classDef), module_type: classDef.is_abstract ? 'org.thingpedia.abstract' : classDef.loader!.module }; if (iconPath) Object.assign(device, await uploadIcon(primary_kind, iconPath, false)); await model.create(dbClient, device, classDef.extends || [], classDef.annotations.child_types ? classDef.annotations.child_types.toJS() as string[] : [], FactoryUtils.getDiscoveryServices(classDef), versionedInfo); if (versionedInfo.downloadable && zipFilePath !== null) { if (zipFilePath.endsWith('.js')) await uploadJavaScript(req, device, fs.createReadStream(zipFilePath)); else await uploadZipFile(req, device, fs.createReadStream(zipFilePath)); } return device; } function tryUpdateDevice(primaryKind : string, userId : number) { // do the update asynchronously - if the update fails, the user will // have another chance from the status page EngineManager.get().getEngine(userId).then((engine) => { return engine.upgradeDevice(primaryKind); }).catch((e) => { console.error(`Failed to auto-update device ${primaryKind} for user ${userId}: ${e.message}`); }); return Promise.resolve(); } function isJavaScript(file : Express.Multer.File) { return file.mimetype === 'application/javascript' || file.mimetype === 'text/javascript' || (file.originalname && file.originalname.endsWith('.js')); } async function uploadDevice(req : express.Request) { const approve = (req.user!.roles & (user.Role.TRUSTED_DEVELOPER | user.Role.THINGPEDIA_ADMIN)) !== 0 && !!req.body.approve; const files = req.files as Record<string, Express.Multer.File[]>|undefined; try { const retrain = await db.withTransaction(async (dbClient) => { let create = false; let old = null; try { old = await model.getByPrimaryKind(dbClient, req.body.primary_kind); if (old.owner !== req.user!.developer_org && (req.user!.roles & user.Role.THINGPEDIA_ADMIN) === 0) throw new ForbiddenError(); } catch(e) { if (!(e instanceof NotFoundError)) throw e; create = true; if (!files || !files.icon || !files.icon.length) throw new BadRequestError(req._("An icon must be specified for new devices")); } const [classDef, dataset] = await Validation.validateDevice(dbClient, req, req.body, req.body.code, req.body.dataset); await Validation.tokenizeDataset(dataset); const [schemaId, schemaChanged] = await ensurePrimarySchema(dbClient, req.body.name, classDef, req, approve); const datasetChanged = await ensureDataset(dbClient, schemaId, classDef, dataset); if (classDef.entities.length > 0) { await entityModel.updateMany(dbClient, classDef.entities.map((stmt) => entityStatementToEntityTypeRow(classDef, stmt))); } const extraKinds = classDef.extends || []; const extraChildKinds = classDef.annotations.child_types ? classDef.annotations.child_types.toJS() as string[] : []; const downloadable = isDownloadable(classDef); const developer_version = create ? 0 : old!.developer_version + 1; classDef.annotations.version = new ThingTalk.Ast.Value.Number(developer_version); classDef.annotations.package_version = new ThingTalk.Ast.Value.Number(developer_version); const generalInfo = { primary_kind: req.body.primary_kind, name: req.body.name, description: req.body.description, license: req.body.license, license_gplcompatible: !!req.body.license_gplcompatible, website: req.body.website || '', repository: req.body.repository || '', issue_tracker: req.body.issue_tracker || '', category: getCategory(classDef) as 'system'|'physical'|'data'|'online', subcategory: req.body.subcategory, source_code: req.body.code, developer_version: developer_version, approved_version: approve ? developer_version : (old !== null ? old.approved_version : null), owner: 0, colors_dominant: '', colors_palette_default: '', colors_palette_light: '', }; if (files && files.icon && files.icon.length) Object.assign(generalInfo, await uploadIcon(req.body.primary_kind, files.icon[0].path)); const discoveryServices = FactoryUtils.getDiscoveryServices(classDef); const factory = FactoryUtils.makeDeviceFactory(classDef, generalInfo); const versionedInfo = { code: classDef.prettyprint(), factory: JSON.stringify(factory), module_type: classDef.is_abstract ? 'org.thingpedia.abstract' : classDef.loader!.module, downloadable: downloadable }; if (create) { generalInfo.owner = req.user!.developer_org!; await model.create(dbClient, generalInfo, extraKinds, extraChildKinds, discoveryServices, versionedInfo); } else { generalInfo.owner = old!.owner; await model.update(dbClient, old!.id, generalInfo, extraKinds, extraChildKinds, discoveryServices, versionedInfo); } if (downloadable) { const zipFile = files && files.zipfile && files.zipfile.length ? files.zipfile[0] : null; let stream; if (zipFile !== null) stream = fs.createReadStream(zipFile.path); else if (old !== null) stream = code_storage.downloadZipFile(req.body.primary_kind, old.developer_version); else throw new BadRequestError(req._("Invalid zip file")); if (zipFile && isJavaScript(zipFile)) await uploadJavaScript(req, generalInfo, stream); else await uploadZipFile(req, generalInfo, stream); } return schemaChanged || datasetChanged; }, 'repeatable read'); // the following two ops access the database from other processes, so they must be outside // the transaction, or we will deadlock if (retrain) { // trigger the training server if configured await TrainingServer.get().queue('en', [req.body.primary_kind], 'update-dataset'); } // trigger updating the device on the user await tryUpdateDevice(req.body.primary_kind, req.user!.id); } finally { const toDelete = []; if (files) { if (files.zipfile && files.zipfile.length) toDelete.push(util.promisify(fs.unlink)(files.zipfile[0].path)); } await Promise.all(toDelete); } } export { ensurePrimarySchema, ensureDataset, isDownloadable, getCategory, uploadZipFile, uploadJavaScript, uploadIcon, importDevice, uploadDevice, };
the_stack
* @module Quantity */ import { QuantityConstants } from "../Constants"; import { QuantityError, QuantityStatus } from "../Exception"; import { UnitProps, UnitsProvider } from "../Interfaces"; import { DecimalPrecision, FormatTraits, formatTraitsToArray, FormatType, formatTypeToString, FractionalPrecision, getTraitString, parseFormatTrait, parseFormatType, parsePrecision, parseScientificType, parseShowSignOption, ScientificType, scientificTypeToString, ShowSignOption, showSignOptionToString } from "./FormatEnums"; import { CloneOptions, CustomFormatProps, FormatProps, isCustomFormatProps } from "./Interfaces"; // cSpell:ignore ZERONORMALIZED, nosign, onlynegative, signalways, negativeparentheses // cSpell:ignore trailzeroes, keepsinglezero, zeroempty, keepdecimalpoint, applyrounding, fractiondash, showunitlabel, prependunitlabel, exponentonlynegative /** A base Format class with shared properties and functionality between quantity and ecschema-metadata Format classes * @beta */ export class BaseFormat { private _name = ""; protected _roundFactor: number = 0.0; protected _type: FormatType = FormatType.Decimal; // required; options are decimal, fractional, scientific, station protected _precision: number = DecimalPrecision.Six; // required protected _showSignOption: ShowSignOption = ShowSignOption.OnlyNegative; // options: noSign, onlyNegative, signAlways, negativeParentheses protected _decimalSeparator: string = QuantityConstants.LocaleSpecificDecimalSeparator; protected _thousandSeparator: string = QuantityConstants.LocaleSpecificThousandSeparator; protected _uomSeparator = " "; // optional; default is " "; defined separator between magnitude and the unit protected _stationSeparator = "+"; // optional; default is "+" protected _formatTraits: FormatTraits = FormatTraits.Uninitialized; protected _spacer: string = " "; // optional; default is " " protected _includeZero: boolean = true; // optional; default is true protected _minWidth?: number; // optional; positive int protected _scientificType?: ScientificType; // required if type is scientific; options: normalized, zeroNormalized protected _stationOffsetSize?: number; // required when type is station; positive integer > 0 constructor(name: string) { this._name = name; } public get name(): string { return this._name; } public get roundFactor(): number { return this._roundFactor; } public set roundFactor(roundFactor: number) { this._roundFactor = roundFactor; } public get type(): FormatType { return this._type; } public set type(formatType: FormatType) { this._type = formatType; } public get precision(): DecimalPrecision | FractionalPrecision { return this._precision; } public set precision(precision: DecimalPrecision | FractionalPrecision) { this._precision = precision; } public get minWidth(): number | undefined { return this._minWidth; } public set minWidth(minWidth: number | undefined) { this._minWidth = minWidth; } public get scientificType(): ScientificType | undefined { return this._scientificType; } public set scientificType(scientificType: ScientificType | undefined) { this._scientificType = scientificType; } public get showSignOption(): ShowSignOption { return this._showSignOption; } public set showSignOption(showSignOption: ShowSignOption) { this._showSignOption = showSignOption; } public get decimalSeparator(): string { return this._decimalSeparator; } public set decimalSeparator(decimalSeparator: string) { this._decimalSeparator = decimalSeparator; } public get thousandSeparator(): string { return this._thousandSeparator; } public set thousandSeparator(thousandSeparator: string) { this._thousandSeparator = thousandSeparator; } public get uomSeparator(): string { return this._uomSeparator; } public set uomSeparator(uomSeparator: string) { this._uomSeparator = uomSeparator; } public get stationSeparator(): string { return this._stationSeparator; } public set stationSeparator(stationSeparator: string) { this._stationSeparator = stationSeparator; } public get stationOffsetSize(): number | undefined { return this._stationOffsetSize; } public set stationOffsetSize(stationOffsetSize: number | undefined) {stationOffsetSize = this._stationOffsetSize = stationOffsetSize; } public get formatTraits(): FormatTraits { return this._formatTraits; } public set formatTraits(formatTraits: FormatTraits) { this._formatTraits = formatTraits; } public get spacer(): string | undefined { return this._spacer; } public set spacer(spacer: string | undefined) { this._spacer = spacer ?? this._spacer; } public get includeZero(): boolean | undefined { return this._includeZero; } public set includeZero(includeZero: boolean | undefined) { this._includeZero = includeZero ?? this._includeZero; } /** This method parses input string that is typically extracted for persisted JSON data and validates that the string is a valid FormatType. Throws exception if not valid. */ public parseFormatTraits(formatTraitsFromJson: string | string[]) { const formatTraits = (Array.isArray(formatTraitsFromJson)) ? formatTraitsFromJson : formatTraitsFromJson.split(/,|;|\|/); formatTraits.forEach((formatTraitsString: string) => { // for each element in the string array const formatTrait = parseFormatTrait(formatTraitsString, this.name); this._formatTraits = this.formatTraits | formatTrait; }); } /** This method returns true if the formatTrait is set in this Format object. */ public hasFormatTraitSet(formatTrait: FormatTraits): boolean { return (this._formatTraits & formatTrait) === formatTrait; } public loadFormatProperties(formatProps: FormatProps) { this._type = parseFormatType(formatProps.type, this.name); if (formatProps.precision !== undefined) { if (!Number.isInteger(formatProps.precision)) // mut be an integer throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'precision' attribute. It should be an integer.`); this._precision = parsePrecision(formatProps.precision, this._type, this.name); } if (this.type === FormatType.Scientific) { if (undefined === formatProps.scientificType) // if format type is scientific and scientific type is undefined, throw throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} is 'Scientific' type therefore the attribute 'scientificType' is required.`); this._scientificType = parseScientificType(formatProps.scientificType, this.name); } if (undefined !== formatProps.roundFactor) { // optional; default is 0.0 if (typeof (formatProps.roundFactor) !== "number") throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'roundFactor' attribute. It should be of type 'number'.`); if (formatProps.roundFactor !== this.roundFactor) // if roundFactor isn't default value of 0.0, reassign roundFactor variable this._roundFactor = formatProps.roundFactor; } if (undefined !== formatProps.minWidth) { // optional if (!Number.isInteger(formatProps.minWidth) || formatProps.minWidth < 0) // must be a positive int throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'minWidth' attribute. It should be a positive integer.`); this._minWidth = formatProps.minWidth; } if (FormatType.Station === this.type) { if (undefined === formatProps.stationOffsetSize) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} is 'Station' type therefore the attribute 'stationOffsetSize' is required.`); if (!Number.isInteger(formatProps.stationOffsetSize) || formatProps.stationOffsetSize < 0) // must be a positive int > 0 throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'stationOffsetSize' attribute. It should be a positive integer.`); this._stationOffsetSize = formatProps.stationOffsetSize; } if (undefined !== formatProps.showSignOption) { // optional; default is "onlyNegative" this._showSignOption = parseShowSignOption(formatProps.showSignOption, this.name); } if (undefined !== formatProps.formatTraits && formatProps.formatTraits.length !== 0) { // FormatTraits is optional if (!Array.isArray(formatProps.formatTraits) && typeof (formatProps.formatTraits) !== "string") // must be either an array of strings or a string throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'formatTraits' attribute. It should be of type 'string' or 'string[]'.`); this.parseFormatTraits(formatProps.formatTraits); // check that all of the options for formatTraits are valid. If now, throw } if (undefined !== formatProps.decimalSeparator) { // optional if (typeof (formatProps.decimalSeparator) !== "string") // not a string or not a one character string throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'decimalSeparator' attribute. It should be of type 'string'.`); if (formatProps.decimalSeparator.length > 1) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'decimalSeparator' attribute. It should be an empty or one character string.`); this._decimalSeparator = formatProps.decimalSeparator; } if (undefined !== formatProps.thousandSeparator) { // optional if (typeof (formatProps.thousandSeparator) !== "string") throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'thousandSeparator' attribute. It should be of type 'string'.`); if (formatProps.thousandSeparator.length > 1) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'thousandSeparator' attribute. It should be an empty or one character string.`); this._thousandSeparator = formatProps.thousandSeparator; } if (undefined !== formatProps.uomSeparator) { // optional; default is " " if (typeof (formatProps.uomSeparator) !== "string") throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'uomSeparator' attribute. It should be of type 'string'.`); if (formatProps.uomSeparator.length < 0 || formatProps.uomSeparator.length > 1) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'uomSeparator' attribute. It should be an empty or one character string.`); this._uomSeparator = formatProps.uomSeparator; } if (undefined !== formatProps.stationSeparator) { // optional; default is "+" if (typeof (formatProps.stationSeparator) !== "string") throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'stationSeparator' attribute. It should be of type 'string'.`); if (formatProps.stationSeparator.length > 1) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has an invalid 'stationSeparator' attribute. It should be an empty or one character string.`); this._stationSeparator = formatProps.stationSeparator; } } } /** A class used to define the specifications for formatting quantity values. This class is typically loaded by reading [[FormatProps]]. * @beta */ export class Format extends BaseFormat { protected _units?: Array<[UnitProps, string | undefined]>; protected _customProps?: any; // used by custom formatters and parsers /** Constructor * @param name The name of a format specification. TODO: make optional or remove */ constructor(name: string) { super(name); } public get units(): Array<[UnitProps, string | undefined]> | undefined { return this._units; } public get hasUnits(): boolean { return this._units !== undefined && this._units.length > 0; } public get customProps(): any { return this._customProps; } public static isFormatTraitSetInProps(formatProps: FormatProps, trait: FormatTraits) { if (!formatProps.formatTraits) return false; const formatTraits = Array.isArray(formatProps.formatTraits) ? formatProps.formatTraits : formatProps.formatTraits.split(/,|;|\|/); const traitStr = getTraitString(trait); return formatTraits.find((traitEntry) => traitStr === traitEntry) ? true : false; } private async createUnit(unitsProvider: UnitsProvider, name: string, label?: string): Promise<void> { if (name === undefined || typeof (name) !== "string" || (label !== undefined && typeof (label) !== "string")) // throws if name is undefined or name isn't a string or if label is defined and isn't a string throw new QuantityError(QuantityStatus.InvalidJson, `This Composite has a unit with an invalid 'name' or 'label' attribute.`); for (const unit of this.units!) { const unitObj = unit[0].name; if (unitObj.toLowerCase() === name.toLowerCase()) // duplicate names are not allowed throw new QuantityError(QuantityStatus.InvalidJson, `The unit ${unitObj} has a duplicate name.`); } const newUnit: UnitProps = await unitsProvider.findUnitByName(name); if (!newUnit || !newUnit.isValid) throw new QuantityError(QuantityStatus.InvalidJson, `Invalid unit name '${name}'.`); this.units!.push([newUnit, label]); } /** * Clone Format */ public clone(options?: CloneOptions): Format { const newFormat = new Format(this.name); newFormat._roundFactor = this._roundFactor; newFormat._type = this._type; newFormat._precision = this._precision; newFormat._minWidth = this._minWidth; newFormat._scientificType = this._scientificType; newFormat._showSignOption = this._showSignOption; newFormat._decimalSeparator = this._decimalSeparator; newFormat._thousandSeparator = this._thousandSeparator; newFormat._uomSeparator = this._uomSeparator; newFormat._stationSeparator = this._stationSeparator; newFormat._stationOffsetSize = this._stationOffsetSize; newFormat._formatTraits = this._formatTraits; newFormat._spacer = this._spacer; newFormat._includeZero = this._includeZero; newFormat._customProps = this._customProps; this._units && (newFormat._units = [...this._units]); if (newFormat._units) { if (options?.showOnlyPrimaryUnit) { if (newFormat._units.length > 1) newFormat._units.length = 1; } } if (undefined !== options?.traits) newFormat._formatTraits = options?.traits; if (undefined !== options?.type) newFormat._type = options.type; if (undefined !== options?.precision) { // ensure specified precision is valid const precision = parsePrecision(options?.precision, newFormat._type, newFormat.name); newFormat._precision = precision; } if (undefined !== options?.primaryUnit) { if (options.primaryUnit.unit) { const newUnits = new Array<[UnitProps, string | undefined]>(); newUnits.push([options.primaryUnit.unit, options.primaryUnit.label]); newFormat._units = newUnits; } else if (options.primaryUnit.label && newFormat._units?.length) { // update label only newFormat._units[0][1] = options.primaryUnit.label; } } return newFormat; } /** * Populates this Format with the values from the provided. */ public async fromJSON(unitsProvider: UnitsProvider, jsonObj: FormatProps): Promise<void> { this.loadFormatProperties(jsonObj); if (isCustomFormatProps(jsonObj)) this._customProps = jsonObj.custom; if (undefined !== jsonObj.composite) { // optional this._units = new Array<[UnitProps, string | undefined]>(); if (jsonObj.composite.includeZero !== undefined) { if (typeof (jsonObj.composite.includeZero) !== "boolean") // includeZero must be a boolean IF it is defined throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has a Composite with an invalid 'includeZero' attribute. It should be of type 'boolean'.`); this._includeZero = jsonObj.composite.includeZero; } if (jsonObj.composite.spacer !== undefined) { // spacer must be a string IF it is defined if (typeof (jsonObj.composite.spacer) !== "string") throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has a Composite with an invalid 'spacer' attribute. It must be of type 'string'.`); if (jsonObj.composite.spacer.length > 1) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has a Composite with an invalid 'spacer' attribute. It should be an empty or one character string.`); this._spacer = jsonObj.composite.spacer; } if (jsonObj.composite.units !== undefined) { // if composite is defined, it must be an array with 1-4 units if (!Array.isArray(jsonObj.composite.units)) { // must be an array throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has a Composite with an invalid 'units' attribute. It must be of type 'array'`); } if (jsonObj.composite.units.length > 0 && jsonObj.composite.units.length <= 4) { // Composite requires 1-4 units try { const createUnitPromises: Array<Promise<void>> = []; for (const unit of jsonObj.composite.units) { createUnitPromises.push(this.createUnit(unitsProvider, unit.name, unit.label)); } await Promise.all(createUnitPromises); } catch (e) { throw e; } } } if (undefined === this.units || this.units.length === 0) throw new QuantityError(QuantityStatus.InvalidJson, `The Format ${this.name} has a Composite with no valid 'units'`); } } /** Create a Format from FormatProps */ public static async createFromJSON(name: string, unitsProvider: UnitsProvider, formatProps: FormatProps) { const actualFormat = new Format(name); await actualFormat.fromJSON(unitsProvider, formatProps); return actualFormat; } /** * Returns a JSON object that contain the specification for this Format. */ public toJSON(): FormatProps { let composite; if (this.units) { const units = this.units.map((value) => { if (undefined !== value[1]) return { name: value[0].name, label: value[1] }; else return { name: value[0].name }; }); composite = { spacer: this.spacer, includeZero: this.includeZero, units, }; } if (this.customProps) return { type: formatTypeToString(this.type), precision: this.precision, roundFactor: this.roundFactor, minWidth: this.minWidth, showSignOption: showSignOptionToString(this.showSignOption), formatTraits: formatTraitsToArray(this.formatTraits), decimalSeparator: this.decimalSeparator, thousandSeparator: this.thousandSeparator, uomSeparator: this.uomSeparator, scientificType: this.scientificType ? scientificTypeToString(this.scientificType) : undefined, stationOffsetSize: this.stationOffsetSize, stationSeparator: this.stationSeparator, composite, custom: this.customProps, } as CustomFormatProps; return { type: formatTypeToString(this.type), precision: this.precision, roundFactor: this.roundFactor, minWidth: this.minWidth, showSignOption: showSignOptionToString(this.showSignOption), formatTraits: formatTraitsToArray(this.formatTraits), decimalSeparator: this.decimalSeparator, thousandSeparator: this.thousandSeparator, uomSeparator: this.uomSeparator, scientificType: this.scientificType ? scientificTypeToString(this.scientificType) : undefined, stationOffsetSize: this.stationOffsetSize, stationSeparator: this.stationSeparator, composite, }; } }
the_stack
import { isToday, isYesterday } from 'date-fns'; import { app, Menu, MenuItemConstructorOptions, shell, Tray } from 'electron'; // tslint:disable-line no-implicit-dependencies import settings from 'electron-settings'; import { EventEmitter } from 'events'; import { POLL_DURATIONS } from './config'; import Connection from './connection'; import ICONS from './icons'; import IncidentFeed from './incidentFeed'; import { getCheckboxMenu, getDeploysMenu, getIncidentsMenu, getSitesMenu } from './menus'; import Netlify, { INetlifyDeploy, INetlifySite, INetlifyUser } from './netlify'; import notify from './notify'; import scheduler from './scheduler'; import { getFormattedDeploys, getNotificationOptions, getSuspendedDeployCount } from './util'; interface IJsonObject { [x: string]: JsonValue; } interface IJsonArray extends Array<JsonValue> {} // tslint:disable-line no-empty-interface type JsonValue = string | number | boolean | null | IJsonArray | IJsonObject; export interface IAppSettings { updateAutomatically: boolean; launchAtStart: boolean; pollInterval: number; showNotifications: boolean; currentSiteId: string | null; } interface IAppState { currentSite?: INetlifySite; menuIsOpen: boolean; previousDeploy: INetlifyDeploy | null; updateAvailable: boolean; } export interface IAppDeploys { pending: INetlifyDeploy[]; ready: INetlifyDeploy[]; } interface IAppNetlifyData { deploys: IAppDeploys; sites: INetlifySite[]; user?: INetlifyUser; } const DEFAULT_SETTINGS: IAppSettings = { currentSiteId: null, launchAtStart: false, pollInterval: 10000, showNotifications: false, updateAutomatically: true }; export default class UI extends EventEmitter { private apiClient: Netlify; private incidentFeed: IncidentFeed; private connection: Connection; private state: IAppState; private tray: Tray; private settings: IAppSettings; private netlifyData: IAppNetlifyData; public constructor({ apiClient, connection, incidentFeed }: { apiClient: Netlify; connection: Connection; incidentFeed: IncidentFeed; }) { super(); this.incidentFeed = incidentFeed; this.tray = new Tray(ICONS.loading); this.apiClient = apiClient; this.connection = connection; this.settings = { ...DEFAULT_SETTINGS, ...(settings.getAll() as {}) }; this.netlifyData = { deploys: { pending: [], ready: [] }, sites: [] }; this.state = { menuIsOpen: false, previousDeploy: null, updateAvailable: false }; this.setup().then(() => this.setupScheduler()); } public setState(state: Partial<IAppState>) { this.state = { ...this.state, ...state }; this.render(); } private async setup(): Promise<void> { await this.fetchData(async () => { if (!this.settings.currentSiteId) { this.settings.currentSiteId = await this.getFallbackSiteId(); } const [currentUser, sites, deploys] = await Promise.all([ this.apiClient.getCurrentUser(), this.apiClient.getSites(), this.apiClient.getSiteDeploys(this.settings.currentSiteId) ]); this.netlifyData = { deploys: getFormattedDeploys(deploys), sites, user: { email: currentUser.email } }; this.state.currentSite = this.getSite(this.settings.currentSiteId); }); } private async setupScheduler(): Promise<void> { scheduler.repeat([ { fn: async () => { await this.updateDeploys(); }, interval: this.settings.pollInterval }, { fn: async ({ isFirstRun }) => { await this.updateFeed(); if (isFirstRun) { this.notifyForIncidentsPastTwoDays(); } else { this.notifyForNewAndUpdatedIncidents(); } }, // going with a minute for now interval: 60000 } ]); this.connection.on('status-changed', connection => { if (connection.isOnline) { scheduler.resume(); } else { scheduler.stop(); console.error('Currently offline, unable to get updates...'); // tslint:disable-line no-console this.tray.setImage(ICONS.offline); } }); } private getSite(siteId: string): INetlifySite { return ( this.netlifyData.sites.find(({ id }) => id === siteId) || this.netlifyData.sites[0] ); } private async getFallbackSiteId(): Promise<string> { const sites = await this.apiClient.getSites(); return sites[0].id; } private async fetchData(fn: () => void): Promise<void> { if (this.connection.isOnline) { this.tray.setImage(ICONS.loading); // catch possible network hickups try { await fn(); this.evaluateDeployState(); if (this.state.previousDeploy) { this.tray.setImage(ICONS[this.state.previousDeploy.state]); } } catch (e) { console.error(e); // tslint:disable-line no-console this.tray.setImage(ICONS.offline); } } this.render(); } private updateFeed(): Promise<void> { return this.fetchData(async () => { await this.incidentFeed.update(); }); } private updateDeploys(): Promise<void> { return this.fetchData(async () => { if (this.settings.currentSiteId) { const deploys = await this.apiClient.getSiteDeploys( this.settings.currentSiteId ); this.netlifyData.deploys = getFormattedDeploys(deploys); } }); } private notifyForIncidentsPastTwoDays(): void { const recentIncidents = this.incidentFeed.getFeed().filter(item => { const publicationDate = new Date(item.pubDate); return isToday(publicationDate) || isYesterday(publicationDate); }); if (recentIncidents.length) { this.notifyIncident(recentIncidents[0], 'Recently reported incident'); } } private notifyForNewAndUpdatedIncidents(): void { const newIncidents = this.incidentFeed.newIncidents(); const updatedIncidents = this.incidentFeed.updatedIncidents(); if (newIncidents.length) { this.notifyIncident(newIncidents[0], 'New incident reported'); } if (updatedIncidents.length) { this.notifyIncident(updatedIncidents[0], 'Incident report updated'); } } private notifyIncident( incident: { title: string; link: string }, title: string ): void { notify({ body: incident.title, onClick: () => { shell.openExternal(incident.link); }, title }); } private evaluateDeployState(): void { const { deploys } = this.netlifyData; const { previousDeploy, currentSite } = this.state; let currentDeploy: INetlifyDeploy | null = null; if (deploys.pending.length) { currentDeploy = deploys.pending[deploys.pending.length - 1]; } else if (deploys.ready.length) { currentDeploy = deploys.ready[0]; } // cover edge case for new users // who don't have any deploys yet if (currentDeploy === null) { return; } if (previousDeploy) { const notificationOptions = getNotificationOptions( previousDeploy, currentDeploy ); if (notificationOptions) { notify({ ...notificationOptions, onClick: () => { if (currentSite && currentDeploy) { shell.openExternal( `https://app.netlify.com/sites/${currentSite.name}/deploys/${ currentDeploy.id }` ); } } }); } } this.state.previousDeploy = currentDeploy; } private saveSetting(key: string, value: JsonValue): void { settings.set(key, value); this.settings[key] = value; this.render(); } private async render(): Promise<void> { if (!this.state.currentSite) { console.error('No current site found'); // tslint:disable-line no-console return; } this.tray.setTitle( getSuspendedDeployCount(this.netlifyData.deploys.pending.length) ); this.renderMenu(this.state.currentSite); } private async renderMenu(currentSite: INetlifySite): Promise<void> { if (!this.connection.isOnline) { return this.tray.setContextMenu( Menu.buildFromTemplate([ { enabled: false, label: "Looks like you're offline..." } ]) ); } const { sites, deploys, user } = this.netlifyData; const { pollInterval } = this.settings; const menu = Menu.buildFromTemplate([ { enabled: false, label: `Netlify Menubar ${app.getVersion()}` }, { type: 'separator' }, { label: 'Reported Incidents', submenu: getIncidentsMenu(this.incidentFeed) }, { type: 'separator' }, { enabled: false, label: user && user.email }, { type: 'separator' }, { label: 'Choose site:', submenu: getSitesMenu({ currentSite, onItemClick: siteId => { this.saveSetting('currentSiteId', siteId); this.state.previousDeploy = null; this.state.currentSite = this.getSite(siteId); this.updateDeploys(); }, sites }) }, { type: 'separator' }, { enabled: false, label: `${currentSite.url.replace(/https?:\/\//, '')}` }, { click: () => shell.openExternal(currentSite.url), label: 'Go to Site' }, { click: () => shell.openExternal(currentSite.admin_url), label: 'Go to Admin' }, { enabled: false, label: '—' }, { label: 'Deploys', submenu: getDeploysMenu({ currentSite, deploys, onItemClick: deployId => shell.openExternal( `https://app.netlify.com/sites/${ currentSite.name }/deploys/${deployId}` ) }) }, { click: async () => { this.fetchData(async () => { await this.apiClient.createSiteBuild(currentSite.id); this.updateDeploys(); }); }, label: 'Trigger new deploy' }, { type: 'separator' }, { label: 'Settings', submenu: [ ...getCheckboxMenu({ items: [ { key: 'updateAutomatically', label: 'Receive automatic updates' }, { key: 'launchAtStart', label: 'Launch at Start' }, { key: 'showNotifications', label: 'Show notifications' } ], onItemClick: (key, value) => this.saveSetting(key, !value), settings: this.settings }), { label: 'Poll interval', submenu: POLL_DURATIONS.map( ({ label, value }): MenuItemConstructorOptions => ({ checked: pollInterval === value, click: () => this.saveSetting('pollInterval', value), label, type: 'radio' }) ) } ] }, { type: 'separator' }, { click: () => shell.openExternal( `https://github.com/stefanjudis/netlify-menubar/releases/tag/v${app.getVersion()}` ), label: 'Changelog' }, { click: () => shell.openExternal( 'https://github.com/stefanjudis/netlify-menubar/issues/new' ), label: 'Give feedback' }, { type: 'separator' }, { click: () => { settings.deleteAll(); app.exit(); }, label: 'Logout' }, { type: 'separator' }, ...(this.state.updateAvailable ? [ { click: () => this.emit('ready-to-update'), label: 'Restart and update...' } ] : []), { label: 'Quit Netlify Menubar', role: 'quit' } ]); menu.on('menu-will-show', () => (this.state.menuIsOpen = true)); menu.on('menu-will-close', () => { this.state.menuIsOpen = false; // queue it behind other event handlers because otherwise // the menu-rerender will cancel ongoing click handlers setImmediate(() => this.render()); }); // avoid the menu to close in case the user has it open if (!this.state.menuIsOpen) { // tslint:disable-next-line console.log('UI: rerending menu'); this.tray.setContextMenu(menu); } } }
the_stack
import { ContainerAdapterClient } from '../../container_adapter_client' import { MasterNodeRegTestContainer, RegTestContainer } from '@defichain/testcontainers' import { wallet } from '../../../src' import BigNumber from 'bignumber.js' import waitForExpect from 'wait-for-expect' import { ListUnspentOptions, Mode, SendManyOptions, SendToAddressOptions, UTXO, WalletFlag } from '../../../src/category/wallet' describe('getBalance', () => { describe('regtest', () => { const container = new RegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() }) afterAll(async () => { await container.stop() }) it('should getBalance = 0', async () => { const balance: BigNumber = await client.wallet.getBalance() expect(balance.toString()).toStrictEqual('0') }) }) describe('masternode', () => { const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() await container.waitForWalletBalanceGTE(100) }) afterAll(async () => { await container.stop() }) it('should getBalance >= 100', async () => { const balance: BigNumber = await client.wallet.getBalance() expect(balance.isGreaterThan(new BigNumber('100'))).toStrictEqual(true) }) }) }) describe('setWalletFlag', () => { describe('regtest', () => { const container = new RegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() }) afterAll(async () => { await container.stop() }) it('should setWalletFlag', async () => { return await waitForExpect(async () => { const walletInfoBefore = await client.wallet.getWalletInfo() expect(walletInfoBefore.avoid_reuse).toStrictEqual(false) const result = await client.wallet.setWalletFlag(WalletFlag.AVOID_REUSE) expect(result.flag_name).toStrictEqual('avoid_reuse') expect(result.flag_state).toStrictEqual(true) expect(result.warnings).toStrictEqual('You need to rescan the blockchain in order to correctly mark used destinations in the past. Until this is done, some destinations may be considered unused, even if the opposite is the case.') const walletInfoAfter = await client.wallet.getWalletInfo() expect(walletInfoAfter.avoid_reuse).toStrictEqual(true) }) }) }) describe('masternode', () => { const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await container.stop() }) it('should setWalletFlag', async () => { return await waitForExpect(async () => { const walletInfoBefore = await client.wallet.getWalletInfo() expect(walletInfoBefore.avoid_reuse).toStrictEqual(false) const result = await client.wallet.setWalletFlag(WalletFlag.AVOID_REUSE) expect(result.flag_name).toStrictEqual('avoid_reuse') expect(result.flag_state).toStrictEqual(true) expect(result.warnings).toStrictEqual('You need to rescan the blockchain in order to correctly mark used destinations in the past. Until this is done, some destinations may be considered unused, even if the opposite is the case.') const walletInfoAfter = await client.wallet.getWalletInfo() expect(walletInfoAfter.avoid_reuse).toStrictEqual(true) }) }) }) }) describe('createWallet', () => { describe('regtest', () => { const container = new RegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() }) afterAll(async () => { await container.stop() }) it('should createWallet', async () => { return await waitForExpect(async () => { const wallet = await client.wallet.createWallet('alice') expect(wallet.name).toStrictEqual('alice') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) it('should createWallet with disablePrivateKeys true', async () => { return await waitForExpect(async () => { const wallet = await client.wallet.createWallet('bob', true) expect(wallet.name).toStrictEqual('bob') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) it('should createWallet with blank true', async () => { return await waitForExpect(async () => { const options = { blank: true } const wallet = await client.wallet.createWallet('charlie', false, options) expect(wallet.name).toStrictEqual('charlie') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) it('should createWallet with passphrase', async () => { return await waitForExpect(async () => { const options = { passphrase: 'shhh...' } const wallet = await client.wallet.createWallet('david', false, options) expect(wallet.name).toStrictEqual('david') expect(wallet.warning).toStrictEqual('') }) }) it('should createWallet with avoidReuse true', async () => { return await waitForExpect(async () => { const options = { avoidReuse: true } const wallet = await client.wallet.createWallet('eve', false, options) expect(wallet.name).toStrictEqual('eve') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) }) describe('masternode', () => { const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await container.stop() }) it('should createWallet', async () => { return await waitForExpect(async () => { const wallet = await client.wallet.createWallet('alice') expect(wallet.name).toStrictEqual('alice') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) it('should createWallet with disablePrivateKeys true', async () => { return await waitForExpect(async () => { const wallet = await client.wallet.createWallet('bob', true) expect(wallet.name).toStrictEqual('bob') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) it('should createWallet with blank true', async () => { return await waitForExpect(async () => { const options = { blank: true } const wallet = await client.wallet.createWallet('charlie', false, options) expect(wallet.name).toStrictEqual('charlie') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) it('should createWallet with passphrase', async () => { return await waitForExpect(async () => { const options = { passphrase: 'shhh...' } const wallet = await client.wallet.createWallet('david', false, options) expect(wallet.name).toStrictEqual('david') expect(wallet.warning).toStrictEqual('') }) }) it('should createWallet with avoidReuse true', async () => { return await waitForExpect(async () => { const options = { avoidReuse: true } const wallet = await client.wallet.createWallet('eve', false, options) expect(wallet.name).toStrictEqual('eve') expect(wallet.warning).toStrictEqual('Empty string given as passphrase, wallet will not be encrypted.') }) }) }) }) describe('sendMany', () => { // NOTE(surangap): defid side(c++) does not have much tests for sendmany RPC atm. const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() await container.waitForWalletBalanceGTE(101) }) afterAll(async () => { await container.stop() }) /** * Returns matching utxos for given transaction id and address. */ async function getMatchingUTXO (txId: string, address: string): Promise<UTXO[]> { const options: ListUnspentOptions = { addresses: [address] } const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) return utxos.filter((utxo) => { return (utxo.address === address) && (utxo.txid === txId) }) } it('should send one address using sendMany', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001 } const transactionId = await client.wallet.sendMany(amounts) expect(typeof transactionId).toStrictEqual('string') // generate one block await container.generate(1) // check the corresponding UTXO const utxos = await getMatchingUTXO(transactionId, 'mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') // In this case the we should only have one matching utxo expect(utxos.length).toStrictEqual(1) utxos.forEach(utxo => { expect(utxo.address).toStrictEqual('mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') expect(utxo.amount).toStrictEqual(new BigNumber(0.00001)) }) }) it('should send multiple address using sendMany', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001, mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy: 0.00002 } const transactionId = await client.wallet.sendMany(amounts) expect(typeof transactionId).toStrictEqual('string') // generate one block await container.generate(1) // check the corresponding UTXOs const utxos = await getMatchingUTXO(transactionId, 'mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') // In this case the we should only have one matching utxo expect(utxos.length).toStrictEqual(1) utxos.forEach(utxo => { expect(utxo.address).toStrictEqual('mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') expect(utxo.amount).toStrictEqual(new BigNumber(0.00001)) }) const utxos2 = await getMatchingUTXO(transactionId, 'mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy') // In this case the we should only have one matching utxo expect(utxos2.length).toStrictEqual(1) utxos2.forEach(utxo => { expect(utxo.address).toStrictEqual('mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy') expect(utxo.amount).toStrictEqual(new BigNumber(0.00002)) }) }) it('should sendMany with comment', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001, mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy: 0.00002 } const options: SendManyOptions = { comment: 'test comment' } const transactionId = await client.wallet.sendMany(amounts, [], options) expect(typeof transactionId).toStrictEqual('string') }) it('should sendMany with replaceable', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001, mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy: 0.00002 } const options: SendManyOptions = { replaceable: true } const transactionId = await client.wallet.sendMany(amounts, [], options) expect(typeof transactionId).toStrictEqual('string') }) it('should sendMany with confTarget', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001, mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy: 0.00002 } const options: SendManyOptions = { confTarget: 60 } const transactionId = await client.wallet.sendMany(amounts, [], options) expect(typeof transactionId).toStrictEqual('string') }) it('should sendMany with estimateMode', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001, mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy: 0.00002 } const options: SendManyOptions = { estimateMode: Mode.ECONOMICAL } const transactionId = await client.wallet.sendMany(amounts, [], options) expect(typeof transactionId).toStrictEqual('string') }) it('should sendMany with fee substracted from mentioned recipients', async () => { const amounts: Record<string, number> = { mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU: 0.00001, mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy: 10.5 } const subtractFeeFrom: string [] = ['mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy'] const transactionId = await client.wallet.sendMany(amounts, subtractFeeFrom) expect(typeof transactionId).toStrictEqual('string') // generate one block await container.generate(1) // check the corresponding UTXOs const utxos = await getMatchingUTXO(transactionId, 'mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') // In this case the we should only have one matching utxo expect(utxos.length).toStrictEqual(1) utxos.forEach(utxo => { expect(utxo.address).toStrictEqual('mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') // amount should be equal to 0.00001 expect(utxo.amount).toStrictEqual(new BigNumber(0.00001)) }) const utxos2 = await getMatchingUTXO(transactionId, 'mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy') // In this case the we should only have one matching utxo expect(utxos2.length).toStrictEqual(1) utxos2.forEach(utxo => { expect(utxo.address).toStrictEqual('mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy') // amount should be less than 10.5 expect(utxo.amount.isLessThan(10.5)).toStrictEqual(true) }) }) }) describe('regtest (non-mn)', () => { // TODO(jellyfish): refactor test to be stand alone without using same container const container = new RegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() }) afterAll(async () => { await container.stop() }) describe('getNewAddress', () => { it('should getNewAddress', async () => { return await waitForExpect(async () => { const address = await client.wallet.getNewAddress() expect(typeof address).toStrictEqual('string') }) }) it('should getNewAddress with label', async () => { return await waitForExpect(async () => { const aliceAddress = await client.wallet.getNewAddress('alice') expect(typeof aliceAddress).toStrictEqual('string') }) }) it('should getNewAddress with address type specified', async () => { return await waitForExpect(async () => { const legacyAddress = await client.wallet.getNewAddress('', wallet.AddressType.LEGACY) const legacyAddressValidateResult = await client.wallet.validateAddress(legacyAddress) const p2shSegwitAddress = await client.wallet.getNewAddress('', wallet.AddressType.P2SH_SEGWIT) const p2shSegwitAddressValidateResult = await client.wallet.validateAddress(p2shSegwitAddress) const bech32Address = await client.wallet.getNewAddress('bob', wallet.AddressType.BECH32) const bech32AddressValidateResult = await client.wallet.validateAddress(bech32Address) expect(typeof legacyAddress).toStrictEqual('string') expect(legacyAddressValidateResult.isvalid).toStrictEqual(true) expect(legacyAddressValidateResult.address).toStrictEqual(legacyAddress) expect(typeof legacyAddressValidateResult.scriptPubKey).toStrictEqual('string') expect(legacyAddressValidateResult.isscript).toStrictEqual(false) expect(legacyAddressValidateResult.iswitness).toStrictEqual(false) expect(typeof p2shSegwitAddress).toStrictEqual('string') expect(p2shSegwitAddressValidateResult.isvalid).toStrictEqual(true) expect(p2shSegwitAddressValidateResult.address).toStrictEqual(p2shSegwitAddress) expect(typeof p2shSegwitAddressValidateResult.scriptPubKey).toStrictEqual('string') expect(p2shSegwitAddressValidateResult.isscript).toStrictEqual(true) expect(p2shSegwitAddressValidateResult.iswitness).toStrictEqual(false) expect(typeof bech32Address).toStrictEqual('string') expect(bech32AddressValidateResult.isvalid).toStrictEqual(true) expect(bech32AddressValidateResult.address).toStrictEqual(bech32Address) expect(typeof bech32AddressValidateResult.scriptPubKey).toStrictEqual('string') expect(bech32AddressValidateResult.isscript).toStrictEqual(false) expect(bech32AddressValidateResult.iswitness).toStrictEqual(true) }) }) }) describe('getAddressInfo', () => { it('should getAddressInfo', async () => { return await waitForExpect(async () => { const aliceAddress = await client.wallet.getNewAddress('alice') const addressInfo: wallet.AddressInfo = await client.wallet.getAddressInfo(aliceAddress) expect(addressInfo.address).toStrictEqual(aliceAddress) expect(typeof addressInfo.scriptPubKey).toStrictEqual('string') expect(addressInfo.ismine).toStrictEqual(true) expect(addressInfo.solvable).toStrictEqual(true) expect(typeof addressInfo.desc).toStrictEqual('string') expect(addressInfo.iswatchonly).toStrictEqual(false) expect(addressInfo.isscript).toStrictEqual(false) expect(addressInfo.iswitness).toStrictEqual(true) expect(typeof addressInfo.pubkey).toStrictEqual('string') expect(addressInfo.label).toStrictEqual('alice') expect(addressInfo.ischange).toStrictEqual(false) expect(typeof addressInfo.timestamp).toStrictEqual('number') expect(typeof addressInfo.hdkeypath).toStrictEqual('string') expect(typeof addressInfo.hdseedid).toStrictEqual('string') expect(addressInfo.labels.length).toBeGreaterThanOrEqual(1) expect(addressInfo.labels[0].name).toStrictEqual('alice') expect(addressInfo.labels[0].purpose).toStrictEqual('receive') }) }) }) describe('validateAddress', () => { it('should validateAddress', async () => { return await waitForExpect(async () => { const aliceAddress = await client.wallet.getNewAddress('alice') const result: wallet.ValidateAddressResult = await client.wallet.validateAddress(aliceAddress) expect(result.isvalid).toStrictEqual(true) expect(result.address).toStrictEqual(aliceAddress) expect(typeof result.scriptPubKey).toStrictEqual('string') expect(result.isscript).toStrictEqual(false) expect(result.iswitness).toStrictEqual(true) }) }) }) describe('listAddressGroupings', () => { it('should listAddressGroupings', async () => { return await waitForExpect(async () => { const data = await client.wallet.listAddressGroupings() expect(data.length === 0).toStrictEqual(true) }) }) }) describe('getWalletInfo', () => { it('should getWalletInfo', async () => { return await waitForExpect(async () => { const walletInfo = await client.wallet.getWalletInfo() expect(walletInfo.walletname).toStrictEqual('') expect(walletInfo.walletversion).toStrictEqual(169900) expect(walletInfo.balance instanceof BigNumber).toStrictEqual(true) expect(walletInfo.balance.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(walletInfo.unconfirmed_balance instanceof BigNumber).toStrictEqual(true) expect(walletInfo.unconfirmed_balance.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(walletInfo.immature_balance instanceof BigNumber).toStrictEqual(true) expect(walletInfo.immature_balance.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(walletInfo.txcount).toBeGreaterThanOrEqual(0) expect(typeof walletInfo.keypoololdest).toStrictEqual('number') expect(typeof walletInfo.keypoolsize).toStrictEqual('number') expect(typeof walletInfo.keypoolsize_hd_internal).toStrictEqual('number') expect(walletInfo.paytxfee instanceof BigNumber).toStrictEqual(true) expect(walletInfo.paytxfee.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(typeof walletInfo.hdseedid).toStrictEqual('string') expect(walletInfo.private_keys_enabled).toStrictEqual(true) expect(walletInfo.avoid_reuse).toStrictEqual(false) expect(walletInfo.scanning).toStrictEqual(false) }) }) }) }) describe('masternode', () => { // TODO(jellyfish): refactor test to be stand alone without using same container const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() }) afterAll(async () => { await container.stop() }) describe('listUnspent', () => { it('should listUnspent', async () => { await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent() expect(utxos.length).toBeGreaterThan(0) for (let i = 0; i < utxos.length; i += 1) { const utxo = utxos[i] expect(typeof utxo.txid).toStrictEqual('string') expect(typeof utxo.vout).toStrictEqual('number') expect(typeof utxo.address).toStrictEqual('string') expect(typeof utxo.label).toStrictEqual('string') expect(typeof utxo.scriptPubKey).toStrictEqual('string') expect(utxo.amount instanceof BigNumber).toStrictEqual(true) expect(typeof utxo.tokenId).toStrictEqual('string') expect(typeof utxo.confirmations).toStrictEqual('number') expect(typeof utxo.spendable).toStrictEqual('boolean') expect(typeof utxo.solvable).toStrictEqual('boolean') expect(typeof utxo.desc).toStrictEqual('string') expect(typeof utxo.safe).toStrictEqual('boolean') } }) }) it('test listUnspent minimumConfirmation filter', async () => { await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(99) utxos.forEach(utxo => { expect(utxo.confirmations).toBeGreaterThanOrEqual(99) }) }) }) it('test listUnspent maximumConfirmation filter', async () => { await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 300) utxos.forEach(utxo => { expect(utxo.confirmations).toBeLessThanOrEqual(300) }) }) }) it('test listUnspent addresses filter', async () => { const options: ListUnspentOptions = { addresses: ['mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU'] } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) utxos.forEach(utxo => { expect(utxo.address).toStrictEqual('mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') }) }) }) it('test listUnspent includeUnsafe filter', async () => { const options: ListUnspentOptions = { includeUnsafe: false } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) utxos.forEach(utxo => { expect(utxo.safe).toStrictEqual(true) }) }) }) it('test listUnspent queryOptions minimumAmount filter', async () => { const options: ListUnspentOptions = { queryOptions: { minimumAmount: 5 } } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) utxos.forEach(utxo => { expect(utxo.amount.isGreaterThanOrEqualTo(new BigNumber('5'))).toStrictEqual(true) }) }) }) it('test listUnspent queryOptions maximumAmount filter', async () => { const options: ListUnspentOptions = { queryOptions: { maximumAmount: 100 } } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) utxos.forEach(utxo => { expect(utxo.amount.isLessThanOrEqualTo(new BigNumber('100'))).toStrictEqual(true) }) }) }) it('test listUnspent queryOptions maximumCount filter', async () => { const options: ListUnspentOptions = { queryOptions: { maximumCount: 100 } } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) expect(utxos.length).toBeLessThanOrEqual(100) }) }) it('test listUnspent queryOptions minimumSumAmount filter', async () => { const options: ListUnspentOptions = { queryOptions: { minimumSumAmount: 100 } } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) const sum: BigNumber = utxos.map(utxo => utxo.amount).reduce((acc, val) => acc.plus(val)) expect(sum.isGreaterThanOrEqualTo(new BigNumber('100'))).toStrictEqual(true) }) }) it('test listUnspent queryOptions tokenId filter', async () => { const options: ListUnspentOptions = { queryOptions: { tokenId: '0' } } await waitForExpect(async () => { const utxos: UTXO[] = await client.wallet.listUnspent(1, 9999999, options) utxos.forEach(utxo => { expect(utxo.tokenId).toStrictEqual('0') }) }) }) }) describe('getNewAddress', () => { it('should getNewAddress', async () => { return await waitForExpect(async () => { const address = await client.wallet.getNewAddress() expect(typeof address).toStrictEqual('string') }) }) it('should getNewAddress with label', async () => { return await waitForExpect(async () => { const aliceAddress = await client.wallet.getNewAddress('alice') expect(typeof aliceAddress).toStrictEqual('string') }) }) it('should getNewAddress with address type specified', async () => { return await waitForExpect(async () => { const legacyAddress = await client.wallet.getNewAddress('', wallet.AddressType.LEGACY) const legacyAddressValidateResult = await client.wallet.validateAddress(legacyAddress) const p2shSegwitAddress = await client.wallet.getNewAddress('', wallet.AddressType.P2SH_SEGWIT) const p2shSegwitAddressValidateResult = await client.wallet.validateAddress(p2shSegwitAddress) const bech32Address = await client.wallet.getNewAddress('bob', wallet.AddressType.BECH32) const bech32AddressValidateResult = await client.wallet.validateAddress(bech32Address) expect(typeof legacyAddress).toStrictEqual('string') expect(legacyAddressValidateResult.isvalid).toStrictEqual(true) expect(legacyAddressValidateResult.address).toStrictEqual(legacyAddress) expect(typeof legacyAddressValidateResult.scriptPubKey).toStrictEqual('string') expect(legacyAddressValidateResult.isscript).toStrictEqual(false) expect(legacyAddressValidateResult.iswitness).toStrictEqual(false) expect(typeof p2shSegwitAddress).toStrictEqual('string') expect(p2shSegwitAddressValidateResult.isvalid).toStrictEqual(true) expect(p2shSegwitAddressValidateResult.address).toStrictEqual(p2shSegwitAddress) expect(typeof p2shSegwitAddressValidateResult.scriptPubKey).toStrictEqual('string') expect(p2shSegwitAddressValidateResult.isscript).toStrictEqual(true) expect(p2shSegwitAddressValidateResult.iswitness).toStrictEqual(false) expect(typeof bech32Address).toStrictEqual('string') expect(bech32AddressValidateResult.isvalid).toStrictEqual(true) expect(bech32AddressValidateResult.address).toStrictEqual(bech32Address) expect(typeof bech32AddressValidateResult.scriptPubKey).toStrictEqual('string') expect(bech32AddressValidateResult.isscript).toStrictEqual(false) expect(bech32AddressValidateResult.iswitness).toStrictEqual(true) }) }) }) describe('getAddressInfo', () => { it('should getAddressInfo', async () => { return await waitForExpect(async () => { const aliceAddress = await client.wallet.getNewAddress('alice') const addressInfo: wallet.AddressInfo = await client.wallet.getAddressInfo(aliceAddress) expect(addressInfo.address).toStrictEqual(aliceAddress) expect(typeof addressInfo.scriptPubKey).toStrictEqual('string') expect(addressInfo.ismine).toStrictEqual(true) expect(addressInfo.solvable).toStrictEqual(true) expect(typeof addressInfo.desc).toStrictEqual('string') expect(addressInfo.iswatchonly).toStrictEqual(false) expect(addressInfo.isscript).toStrictEqual(false) expect(addressInfo.iswitness).toStrictEqual(true) expect(typeof addressInfo.pubkey).toStrictEqual('string') expect(addressInfo.label).toStrictEqual('alice') expect(addressInfo.ischange).toStrictEqual(false) expect(typeof addressInfo.timestamp).toStrictEqual('number') expect(typeof addressInfo.hdkeypath).toStrictEqual('string') expect(typeof addressInfo.hdseedid).toStrictEqual('string') expect(addressInfo.labels.length).toBeGreaterThanOrEqual(1) expect(addressInfo.labels[0].name).toStrictEqual('alice') expect(addressInfo.labels[0].purpose).toStrictEqual('receive') }) }) }) describe('validateAddress', () => { it('should validateAddress', async () => { return await waitForExpect(async () => { const aliceAddress = await client.wallet.getNewAddress('alice') const result: wallet.ValidateAddressResult = await client.wallet.validateAddress(aliceAddress) expect(result.isvalid).toStrictEqual(true) expect(result.address).toStrictEqual(aliceAddress) expect(typeof result.scriptPubKey).toStrictEqual('string') expect(result.isscript).toStrictEqual(false) expect(result.iswitness).toStrictEqual(true) }) }) }) describe('listAddressGroupings', () => { it('should listAddressGroupings', async () => { return await waitForExpect(async () => { const data = await client.wallet.listAddressGroupings() expect(data[0][0][0]).toStrictEqual('mswsMVsyGMj1FzDMbbxw2QW3KvQAv2FKiy') expect(data[0][0][1] instanceof BigNumber).toStrictEqual(true) expect(data[0][0][1].isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(data[0][0][2]).toStrictEqual('operator') expect(data[1][0][0]).toStrictEqual('mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU') expect(data[1][0][1] instanceof BigNumber).toStrictEqual(true) expect(data[1][0][1].isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(data[1][0][2]).toStrictEqual('owner') }) }) }) describe('getWalletInfo', () => { it('should getWalletInfo', async () => { return await waitForExpect(async () => { const walletInfo = await client.wallet.getWalletInfo() expect(walletInfo.walletname).toStrictEqual('') expect(walletInfo.walletversion).toStrictEqual(169900) expect(walletInfo.balance instanceof BigNumber).toStrictEqual(true) expect(walletInfo.balance.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(walletInfo.unconfirmed_balance instanceof BigNumber).toStrictEqual(true) expect(walletInfo.unconfirmed_balance.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(walletInfo.immature_balance instanceof BigNumber).toStrictEqual(true) expect(walletInfo.immature_balance.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(walletInfo.txcount).toBeGreaterThanOrEqual(100) expect(typeof walletInfo.keypoololdest).toStrictEqual('number') expect(typeof walletInfo.keypoolsize).toStrictEqual('number') expect(typeof walletInfo.keypoolsize_hd_internal).toStrictEqual('number') expect(walletInfo.paytxfee instanceof BigNumber).toStrictEqual(true) expect(walletInfo.paytxfee.isGreaterThanOrEqualTo(new BigNumber('0'))).toStrictEqual(true) expect(typeof walletInfo.hdseedid).toStrictEqual('string') expect(walletInfo.private_keys_enabled).toStrictEqual(true) expect(walletInfo.avoid_reuse).toStrictEqual(false) expect(walletInfo.scanning).toStrictEqual(false) }) }) }) describe('sendToAddress', () => { const address = 'mwsZw8nF7pKxWH8eoKL9tPxTpaFkz7QeLU' it('should sendToAddress', async () => { return await waitForExpect(async () => { const transactionId = await client.wallet.sendToAddress(address, 0.00001) expect(typeof transactionId).toStrictEqual('string') }) }) it('should sendToAddress with comment and commentTo', async () => { return await waitForExpect(async () => { const options: SendToAddressOptions = { comment: 'pizza', commentTo: 'domino' } const transactionId = await client.wallet.sendToAddress(address, 0.00001, options) expect(typeof transactionId).toStrictEqual('string') }) }) it('should sendToAddress with replaceable', async () => { return await waitForExpect(async () => { const options: SendToAddressOptions = { replaceable: true } const transactionId = await client.wallet.sendToAddress(address, 0.00001, options) expect(typeof transactionId).toStrictEqual('string') }) }) it('should sendToAddress with confTarget', async () => { return await waitForExpect(async () => { const options: SendToAddressOptions = { confTarget: 60 } const transactionId = await client.wallet.sendToAddress(address, 0.00001, options) expect(typeof transactionId).toStrictEqual('string') }) }) it('should sendToAddress with estimateMode', async () => { return await waitForExpect(async () => { const options: SendToAddressOptions = { estimateMode: Mode.ECONOMICAL } const transactionId = await client.wallet.sendToAddress(address, 0.00001, options) expect(typeof transactionId).toStrictEqual('string') }) }) it('should sendToAddress with avoidReuse', async () => { return await waitForExpect(async () => { const options: SendToAddressOptions = { avoidReuse: false } const transactionId = await client.wallet.sendToAddress(address, 0.00001, options) expect(typeof transactionId).toStrictEqual('string') }) }) }) })
the_stack
import _ from "lodash" import moment from "moment-timezone" import { GraphQLFieldConfig, GraphQLList, GraphQLObjectType } from "graphql" import { ResolverContext } from "types/graphql" import gql from "lib/gql" import Sale from "../sale" import { SaleArtworkType } from "../sale_artwork" import { BodyAndHeaders } from "lib/loaders" /** * Reader take note! To work on this section of the codebase one needs things: * - CAUSALITY_TOKEN, set in .env. This can be grabbed via hokusai * - `x-user-id` header set in your graphiql client */ interface LotStandingResponse { isHighestBidder: boolean lot: { // Same as SaleArtwork._id internalID: string saleId: string } } interface SaleResponse { _id: string isClosed: boolean endAt: string } interface SaleArtworkResponse { _id: string sale_id: string // we attach this manually artwork: { sale_ids: string[] } } interface SaleSortingInfo { isLiveAuction: boolean isClosed: boolean isActive: boolean endAt: any liveBiddingStarted: () => boolean } interface SaleArtworkWithPosition extends SaleArtworkResponse { isHighestBidder: boolean isWatching: boolean lotState?: LotStandingResponse["lot"] } interface MyBid { sale: SaleResponse saleArtworks: SaleArtworkWithPosition[] } /** * A Sale and associated sale artworks, including bidder position and watching status for user */ export const MyBidType = new GraphQLObjectType<any, ResolverContext>({ name: "MyBid", fields: () => ({ sale: { type: Sale.type, }, saleArtworks: { type: new GraphQLList(SaleArtworkType), }, }), }) export const MyBids: GraphQLFieldConfig<void, ResolverContext> = { type: new GraphQLObjectType({ name: "MyBids", fields: () => ({ active: { type: new GraphQLList(MyBidType), resolve: ({ active }) => active, }, closed: { type: new GraphQLList(MyBidType), resolve: ({ closed }) => closed, }, }), }), resolve: async ( _root, _args, { causalityLoader, meLoader, saleArtworksLoader, saleArtworksAllLoader, salesLoaderWithHeaders, saleLoader, } ): Promise<{ active: Array<MyBid> closed: Array<MyBid> } | null> => { if ( !( causalityLoader && meLoader && saleArtworksLoader && saleArtworksAllLoader && salesLoaderWithHeaders && saleLoader ) ) { return null } /** * Causality's connection is subject to a max cap of 25, so we'll only ever * be able to return a few items. Increased to an arbitrarily * high number to account for registered sales and watched lots. */ const FETCH_COUNT = 99 // Grab userID to pass to causality const me: { id: string } = await meLoader() // Fetch all auction lot standings from a given user const causalityPromise = causalityLoader({ query: gql` query LotStandingsConnection($userId: ID!, $first: Int) { lotStandingConnection(userId: $userId, first: $first) { edges { node { isHighestBidder lot { bidCount internalID reserveStatus saleId soldStatus floorSellingPriceCents sellingPriceCents onlineAskingPriceCents } } } } } `, variables: { first: FETCH_COUNT, userId: me.id, }, }) as Promise<{ lotStandingConnection: { edges: Array<{ node: LotStandingResponse }> } }> // Queue up promise for all registered sales const registeredSalesPromise = salesLoaderWithHeaders({ registered: true, is_auction: true, size: FETCH_COUNT, }) as Promise<BodyAndHeaders<SaleResponse[]>> // Queue up promise for watched lots const watchedSaleArtworksPromise = saleArtworksAllLoader({ include_watched_artworks: true, total_count: true, first: FETCH_COUNT, }) as Promise<BodyAndHeaders<SaleArtworkResponse[]>> // Fetch everything in parallel const [ causalityResponse, registeredSalesResponse, watchedSaleArtworksResponse, ] = await Promise.all([ causalityPromise, registeredSalesPromise, watchedSaleArtworksPromise, ]) // Map over response to gather all sale IDs const causalityLotStandings = ( causalityResponse?.lotStandingConnection?.edges ?? [] ).map(({ node }) => node) const causalityLotStandingsBySaleId = _.groupBy( causalityLotStandings, (lotStanding) => lotStanding.lot.saleId ) const causalitySaleIds = Object.keys(causalityLotStandingsBySaleId) const registeredSaleIds = registeredSalesResponse.body.map( (sale) => sale._id ) const watchedSaleSlugs = watchedSaleArtworksResponse.body.map( (saleArtwork) => saleArtwork.artwork.sale_ids[0] ) // Combine ids from categories and dedupe const combinedSaleIds = _.uniq([ ...causalitySaleIds, ...registeredSaleIds, ...watchedSaleSlugs, ]) // Fetch all sales to format into a list. Because we are fetching by // both id + slug (watchedSaleIds) we must do another uniq. // We finally remove invalid & duplicate sales from the results const combinedSales: SaleResponse[] = await Promise.all( combinedSaleIds.map((id) => saleLoader(id)) ).then((sales) => { return _.uniqBy(sales, (sale) => sale.id).filter(Boolean) }) // Fetch all sale artworks for lot standings type SaleArtworksBySaleId = { [saleId: string]: SaleArtworkResponse[] | undefined } const bidUponSaleArtworksBySaleId: SaleArtworksBySaleId = await Promise.all( combinedSales.map((sale: any) => { const causalityLotStandingsInSale = causalityLotStandingsBySaleId[sale._id] || [] const lotIds = causalityLotStandingsInSale.map( (causalityLot) => causalityLot.lot.internalID ) return saleArtworksLoader(sale._id, { ids: lotIds, offset: 0, size: lotIds.length, }) }) ).then( (saleArtworksResponses: Array<BodyAndHeaders<SaleArtworkResponse[]>>) => { return saleArtworksResponses.reduce((acc, saleArtworks, index) => { const matchingSaleId = combinedSales[index]._id return { ...acc, [matchingSaleId]: saleArtworks.body, } }, {} as SaleArtworksBySaleId) } ) // Transform data into proper shape for MyBid type plus SaleInfo (used for sorting) const fullyLoadedSales: Array<MyBid & SaleSortingInfo> = combinedSales.map( (sale: any) => { const bidUponSaleArtworksWithoutWatchStatus = bidUponSaleArtworksBySaleId[sale._id] || ([] as SaleArtworkResponse[]) // mark lots wit a bid `isWatching: false` const bidUponSaleArtworks = bidUponSaleArtworksWithoutWatchStatus.map( (sa) => { return { ...sa, isWatching: false } } ) const bidUponSaleArtworkIds = bidUponSaleArtworks.map( (lotStanding) => lotStanding._id ) // mark lots that are watched but not bid on with the `isWatching` prop const watchedOnlySaleArtworks = watchedSaleArtworksResponse.body .filter((saleArtwork) => { const saleSlug = sale.id return ( saleArtwork.sale_id === saleSlug && !bidUponSaleArtworkIds.includes(saleArtwork._id) ) }) .map((saleArtwork) => { return { ...saleArtwork, isWatching: true } }) const allSaleArtworks: Omit< SaleArtworkWithPosition, "isHighestBidder" | "lotState" >[] = watchedOnlySaleArtworks.concat(bidUponSaleArtworks) // Find lot standings for sale const causalityLotStandingsInSale = causalityLotStandingsBySaleId[sale._id] || [] // Attach lot state to each sale artwork const saleArtworksWithPosition: SaleArtworkWithPosition[] = allSaleArtworks.map( (saleArtwork) => { const causalityLotStanding = causalityLotStandingsInSale.find( (lotStanding) => lotStanding.lot.internalID === saleArtwork._id ) // Attach to SaleArtwork.lotState field const result = { ...saleArtwork, lotState: causalityLotStanding?.lot, isHighestBidder: Boolean(causalityLotStanding?.isHighestBidder), } return result } ) return { sale, saleArtworks: saleArtworksWithPosition, ...withSaleInfo(sale), } } ) const sorted = sortSales(fullyLoadedSales) return sorted }, } /** * Lastly, divide sales by opened / closed, sort by position * and remove watched-only lots from the closed sale response */ function sortSales( saleBidsInfoAggregate: (MyBid & SaleSortingInfo)[] ): { active: MyBid[]; closed: MyBid[] } { // Sort sale by relevant end time (liveStartAt or endAt, depending on type) const allSortedByEnd: (MyBid & SaleSortingInfo)[] = _.sortBy( saleBidsInfoAggregate, (saleInfo) => { return moment(saleInfo.endAt).unix() } ) // sort each sale's lots by position allSortedByEnd.forEach((myBid) => { const artworksSortedByPosition: SaleArtworkWithPosition[] = _.sortBy( myBid.saleArtworks, "position" ) myBid.saleArtworks = artworksSortedByPosition }) const [closed, active] = _.partition(allSortedByEnd, (sale) => sale.isClosed) // prune watched lots from closed lots closed.forEach((myBid) => { const biddedOnlySaleArtworks = myBid.saleArtworks.filter((saleArtwork) => Boolean(saleArtwork.lotState) ) myBid.saleArtworks = biddedOnlySaleArtworks }) return { active, closed, } } function withSaleInfo(sale): SaleSortingInfo { const isLiveAuction = Boolean(sale.live_start_at) const isClosed = sale.auction_state === "closed" const isActive = Boolean(sale.auction_state?.match(/(open|preview)/)?.length) const endAt = isLiveAuction ? sale.live_start_at : sale.end_at const liveBiddingStarted = () => { if (isLiveAuction || isClosed) { return false } const tz = moment.tz.guess(true) const now = moment().tz(tz) const liveStartMoment = moment(sale.live_start_at).tz(tz) const started = now.isAfter(liveStartMoment) return started } return { isLiveAuction, isClosed, isActive, endAt, liveBiddingStarted, } }
the_stack
import { serveFormatToWebFormat } from '@/common/js/Utils'; import DiffContents from '@/components/diffContents/DiffContents.vue'; import EmptyView from '@/components/emptyView/EmptyView.vue'; import popContainer from '@/components/popContainer'; import utils from '@/pages/DataGraph/Common/utils.js'; import { bkDiff } from 'bk-magic-vue'; import 'bk-magic-vue/lib/ui/diff.min.css'; import { Component, Emit, Prop, PropSync, Ref, Vue, Watch } from 'vue-property-decorator'; import { DataModelDiff } from '../../Controller/DataModelDiff'; // 获取字段加工 sql const getCode = (data: object, target: string): string => { if (data.isEmpty) { return ''; } const { fields = [] } = data; const field = fields.find(field => field.fieldName === target); return field?.fieldCleanContent?.cleanContent || ''; }; // 获取值约束内容 const getFieldConstraintContent = (data: object, target: string) => { if (data.isEmpty) { return ''; } const { fields = [] } = data; const field = fields.find(field => field.fieldName === target); return field?.fieldConstraintContent || ''; }; // 将 diff key value 格式化为驼峰 const diffObjectsformatter = (objects: any[] = []): any[] => { for (const item of objects) { if (item.diffKeys) { item.diffKeys = item.diffKeys.map((value: string) => serveFormatToWebFormat(value)); } if (item.diffObjects) { item.diffObjects = diffObjectsformatter(item.diffObjects); } } return objects; }; // window type 对应展示字段信息 const extraConfigMap = { scroll: [ { label: window.$t('统计频率'), prop: 'schedulingContent.countFreq' }, { label: window.$t('等待时间'), prop: 'schedulingContent.waitingTime' }, { label: window.$t('依赖计算延迟数据'), prop: 'schedulingContent.windowLateness.allowedLateness' }, ], slide: [ { label: window.$t('统计频率'), prop: 'schedulingContent.countFreq' }, { label: window.$t('窗口长度'), prop: 'schedulingContent.windowTime' }, { label: window.$t('等待时间'), prop: 'schedulingContent.waitingTime' }, { label: window.$t('依赖计算延迟数据'), prop: 'schedulingContent.windowLateness.allowedLateness' }, ], accumulate: [ { label: window.$t('统计频率'), prop: 'schedulingContent.countFreq' }, { label: window.$t('窗口长度'), prop: 'schedulingContent.windowTime' }, { label: window.$t('等待时间'), prop: 'schedulingContent.waitingTime' }, { label: window.$t('依赖计算延迟数据'), prop: 'schedulingContent.windowLateness.allowedLateness' }, ], accumulate_by_hour: [ { label: window.$t('统计频率'), prop: 'schedulingContent.countFreq' }, { label: window.$t('统计延迟'), prop: 'schedulingContent.delay' }, { label: window.$t('窗口起点'), prop: 'schedulingContent.dataStart' }, { label: window.$t('窗口终点'), prop: 'schedulingContent.dataEnd' }, { label: window.$t('依赖策略'), prop: 'schedulingContent.unifiedConfig.dependencyRule' }, { label: window.$t('调度失败重试'), prop: 'schedulingContent.advanced.recoveryEnable' }, ], fixed: [ { label: window.$t('统计频率'), prop: 'schedulingContent.countFreq' }, { label: window.$t('统计延迟'), prop: 'schedulingContent.fixedDelay' }, { label: window.$t('窗口长度'), prop: 'schedulingContent.unifiedConfig.windowSize' }, { label: window.$t('依赖策略'), prop: 'schedulingContent.unifiedConfig.dependencyRule' }, { label: window.$t('调度失败重试'), prop: 'schedulingContent.advanced.recoveryEnable' }, ], }; @Component({ components: { DiffContents, bkDiff, EmptyView, popContainer }, }) export default class BizDiffContents extends Vue { @PropSync('isLoading', { default: false }) public localIsLoading!: boolean; @PropSync('onlyShowDiff', { default: false }) public localOnlyShowDiff!: boolean; @Prop({ default: true }) public showResult!: boolean; @Prop({ required: true }) public newContents!: object; @Prop({ required: true }) public origContents!: object; @Prop({ required: true }) public diff!: object; @Prop({ default: () => [] }) public fieldContraintConfigList!: any[]; @Ref() public readonly diffConditions!: popContainer; @Ref() public readonly diffRelation!: popContainer; get diffObjects() { return diffObjectsformatter(this.diff.diffObjects || []); } get diffResult() { const { update: updateNum, delete: deleteNum, create: createNum, hasDiff } = this.diff.diffResult || {}; return Object.assign({}, new DataModelDiff(), { updateNum, deleteNum, createNum, hasDiff }); } get tableDiffResult() { return this.diff.diffResult?.field || {}; } get versionInfo() { const { createdAt, createdBy } = this.origContents; return createdAt && createdBy ? `${createdBy} (${createdAt})` : ''; } get conditionMap() { const map: any = {}; for (const condition of this.fieldContraintConfigList) { map[condition.constraintId] = condition; if (condition.children) { for (const child of condition.children) { child.parentId = condition.constraintId; map[child.constraintId] = child; } } } return map; } get newContentObjects() { return this.newContents.objects || []; } get originContentObjects() { return this.origContents.objects || []; } get diffList() { return this.resolveContentObject(); } get renderDiffList() { if (this.localOnlyShowDiff) { return this.diffList.filter( (diff: any) => diff.newContent.diffType !== 'default' || diff.originContent.diffType !== 'default' ); } return this.diffList; } /** * 获取内容对象数据 */ getContentsObjectMap() { const newContentsObjectIds = this.newContentObjects.map((item: any) => item.objectId); const origContentsObjectIds = this.originContentObjects.map((item: any) => item.objectId); const uniqueObjectId = Array.from(new Set([...newContentsObjectIds, ...origContentsObjectIds])); const diffObjectsMap = this.diffObjects .reduce((map, item) => Object.assign(map, { [item.objectId]: item }), {}); const newContentsObjectMap = this.newContentObjects .reduce((map: any, item: any) => Object.assign(map, { [item.objectId]: item }), {}); const origContentsObjectMap = this.originContentObjects .reduce((map: any, item: any) => Object.assign(map, { [item.objectId]: item }), {}); return { newContentsObjectIds, origContentsObjectIds, uniqueObjectId, diffObjectsMap, newContentsObjectMap, origContentsObjectMap }; } /** * 对数据进行格式化处理 */ resolveContentObject() { const list = []; const { uniqueObjectId, diffObjectsMap, newContentsObjectMap, origContentsObjectMap } = this.getContentsObjectMap(); for (const id of uniqueObjectId) { const newContent = newContentsObjectMap[id]; const originContent = origContentsObjectMap[id]; if (!newContent && !originContent) { continue; } const { diffInfo, type, objectType, config, newCollapseTitle, originCollapseTitle } = this.resolveDiffInfos(diffObjectsMap, id, newContent, originContent); const oTitle = originCollapseTitle; const nTitle = newCollapseTitle; const defaultItem = { configs: config?.configs || [], type }; let item = this.resolveObjectItem(newContent, originContent, oTitle, diffInfo, nTitle); this.resolveTableField(type, defaultItem, config, item); this.resolveDiffTableFields(diffInfo, type, item); this.resolveIndicatorField(objectType, item, extraConfigMap, defaultItem); list.push(Object.assign(defaultItem, item)); } return list; } /** * 处理 diff 信息 * @param diffObjectsMap * @param id * @param newContent * @param originContent */ resolveDiffInfos(diffObjectsMap: any, id: any, newContent: any, originContent: any,) { const diffInfo = diffObjectsMap[id] || { diffType: 'default' }; const type = (newContent?.objectType || originContent?.objectType || '') .indexOf('table') >= 0 ? 'table' : 'list'; const objectType = newContent?.objectType || originContent?.objectType; const config = objectType ? this.config[objectType] : null; const newCollapseTitle = newContent ? `【${config.title}】${newContent[config.nameKey]} (${newContent[config.aliasKey]})` : '--'; const originCollapseTitle = originContent ? `【${config.title}】${originContent[config.nameKey]} (${originContent[config.aliasKey]})` : '--'; return { diffInfo, type, objectType, config, newCollapseTitle, originCollapseTitle }; } /** * 处理新旧内容 diff 信息 * @param newContent * @param originContent * @param originCollapseTitle * @param diffInfo * @param newCollapseTitle */ resolveObjectItem(newCxt: any, originCxt: any, originCollapseTitle: any, diffInfo: any, newCollapseTitle: any) { let item = {}; if (newCxt && originCxt) { item = { originCxt: Object.assign({ collapseTitle: originCollapseTitle }, originCxt, diffInfo), newCxt: Object.assign({ collapseTitle: newCollapseTitle }, newCxt, diffInfo), }; } else if (newCxt && !originCxt) { item = { originCxt: { isEmpty: true, diffType: 'default', collapseTitle: originCollapseTitle }, newCxt: Object.assign({ collapseTitle: newCollapseTitle }, newCxt, diffInfo), }; } else if (!newCxt && originCxt) { item = { originCxt: Object.assign({ collapseTitle: originCollapseTitle }, originCxt, diffInfo), newCxt: { isEmpty: true, diffType: 'default', collapseTitle: newCollapseTitle }, }; } return item; } /** * 处理 table field 信息 * @param type * @param defaultItem * @param config * @param item */ resolveTableField(type: string, defaultItem: any, config: any, item: any) { if (type === 'table') { Object.assign(defaultItem, { tableParams: config?.tableParams || {} }); if (item.newContent.fields?.length) { item.newContent.fields = this.tableDataFormatter(item.newContent.fields); } if (item.originContent.fields?.length) { item.originContent.fields = this.tableDataFormatter(item.originContent.fields); } } } /** * 处理指标变动字段 * @param objectType * @param item * @param extraConfigMap * @param defaultItem */ resolveIndicatorField(objectType: string, item: any, extraConfigMap: any, defaultItem: any) { if (objectType === 'indicator') { const newExtraConfigs = item.newContent.isEmpty ? [] : extraConfigMap[item.newContent.schedulingContent?.windowType] || []; const originExtraConfigs = item.originContent.isEmpty ? [] : extraConfigMap[item.originContent.schedulingContent?.windowType] || []; Object.assign(defaultItem, { newExtraConfigs, originExtraConfigs }); } } resolveDiffTableFields(diffInfo: any, type: string, item: any,) { // 处理数据 table fields diff 状态 if (diffInfo.diffType !== 'default' && type === 'table') { const fieldDiffObjects = diffInfo.diffObjects || []; const newFields = item.newContent.fields || []; const originFields = item.originContent.fields || []; for (const item of fieldDiffObjects) { const newField = newFields.find((field: any) => field.objectId === item.objectId || `model_relation-${field.modelId}-${field.fieldName}` === item.objectId); const originField = originFields.find((field: any) => field.objectId === item.objectId || `model_relation-${field.modelId}-${field.fieldName}` === item.objectId); this.resolveDiffFieldItem(item, newField, originField); } } } resolveDiffFieldItem(item: any, newField: any, originField: any) { if (item.objectId.indexOf('model_relation') === 0) { if (newField) { !newField.diffType && (newField.diffType = 'update'); newField.diffKeys = [].concat(item.diffKeys || [], newField.diffKeys || []); } if (originField) { !originField.diffType && (originField.diffType = 'update'); originField.diffKeys = [].concat(item.diffKeys || [], originField.diffKeys || []); } } else { newField && Object.assign(newField, item); originField && Object.assign(originField, item); } } public diffConditionsContent = { origin: '', target: '', cls: '', }; public diffRelationContent = { origin: {}, target: {}, modelCls: '', fieldCls: '', }; public activeHoverFieldName: string = ''; public diffCodeDialog: object = { isShow: false, title: '', subTitle: '', originCode: '', targetCode: '', }; public fieldCategoryMap: object = { measure: this.$t('度量'), dimension: this.$t('维度'), }; public dataStartList: any[] = utils.getTimeList(); public dataEndList: any[] = utils.getTimeList('59'); public dependencyRule = { no_failed: this.$t('无失败'), all_finished: this.$t('全部成功'), at_least_one_finished: this.$t('一次成功'), }; public config: object = { model: { title: this.$t('数据模型基本信息'), nameKey: 'modelName', aliasKey: 'modelAlias', configs: [ { label: this.$t('中文名'), prop: 'modelAlias', resizable: false }, { label: this.$t('标签'), prop: 'tags', resizable: false }, { label: this.$t('描述'), prop: 'description', resizable: false }, ], }, master_table: { title: this.$t('主表'), nameKey: 'modelName', aliasKey: 'modelAlias', tableParams: { bind: { rowClassName: this.rowClassName, cellClassName: this.cellClassName, }, on: { 'row-mouse-enter': this.handleRowMouseEnter, 'row-mouse-leave': this.handleRowMouseLeave, }, }, configs: [ { label: this.$t('字段名'), prop: 'fieldName', resizable: false }, { label: this.$t('字段中文名'), prop: 'fieldAlias', resizable: false }, { label: this.$t('数据类型'), prop: 'fieldType', resizable: false }, { label: this.$t('字段角色'), prop: 'fieldCategory', resizable: false }, { label: this.$t('字段描述'), prop: 'description', resizable: false }, { label: this.$t('值约束'), prop: 'fieldConstraintContent', resizable: false }, { label: this.$t('字段加工逻辑'), prop: 'fieldCleanContent', resizable: false }, { label: this.$t('主键'), prop: 'isPrimaryKey', width: 70, resizable: false }, ], }, calculation_atom: { title: this.$t('指标统计口径'), nameKey: 'calculationAtomName', aliasKey: 'calculationAtomAlias', configs: [ { label: this.$t('口径名称'), prop: 'calculationDisplayName' }, { label: this.$t('聚合逻辑'), prop: 'calculationFormulaStrippedComment' }, { label: this.$t('字段类型'), prop: 'fieldType' }, { label: this.$t('描述'), prop: 'description' }, ], }, indicator: { title: this.$t('指标'), nameKey: 'indicatorName', aliasKey: 'indicatorAlias', configs: [ { label: this.$t('指标英文'), prop: 'indicatorName' }, { label: this.$t('指标中文'), prop: 'indicatorAlias' }, { label: this.$t('描述'), prop: 'description' }, { label: this.$t('指标统计口径'), prop: 'calculationDisplayName' }, { label: this.$t('聚合字段'), prop: 'aggregationFieldsStr' }, { label: this.$t('过滤条件'), prop: 'filterFormula' }, { label: this.$t('计算类型'), prop: 'schedulingType' }, { label: this.$t('窗口类型'), prop: 'schedulingContent.windowType' }, ], }, }; public dataMap: object = { schedulingType: { stream: this.$t('实时计算'), batch: this.$t('离线计算'), }, windowType: { scroll: this.$t('滚动窗口'), accumulate: this.$t('累加窗口'), slide: this.$t('滑动窗口'), accumulate_by_hour: this.$t('按小时累加窗口'), fixed: this.$t('固定窗口'), }, booleanMap: { true: this.$t('是'), false: this.$t('否'), }, unitMap: { s: this.$t('秒'), min: this.$t('分钟'), h: this.$t('小时'), d: this.$t('天'), w: this.$t('周'), m: this.$t('月'), }, timeformatter(value: string | number, unit: string | undefined) { const empty = [undefined, null, '']; if (empty.includes(value)) { return '--'; } if (!unit) { return value; } if (unit === 'min') { return value + this.unitMap.min; } const key = unit.charAt(0).toLocaleLowerCase(); return value + this.unitMap[key]; }, }; /** * 格式化值约束渲染的条件 * @param data */ public formatRenderConditions(data: object) { const renderConditions = []; const { op: groupCondition, groups } = data; if (groups) { for (const group of groups) { const itemOp = group.op; const groupItem = { op: groupCondition, items: [], }; for (const item of group.items) { const condition = this.conditionMap[item.constraintId]; const name = condition.constraintName; if (name) { const content = condition.editable ? item.constraintContent : ''; groupItem.items.push({ op: itemOp, content: name + ' ' + content, }); } } renderConditions.push(groupItem); } } return renderConditions; } /** * 展示值约束 diff * @param e * @param item * @param data */ public handleShowContentDiff(e: Event, item: object, data: object) { const { newContent, originContent } = item; const newConditions = getFieldConstraintContent(newContent, data.fieldName); const originConditions = getFieldConstraintContent(originContent, data.fieldName); this.diffConditionsContent.origin = originConditions ? this.formatRenderConditions(originConditions) : ''; this.diffConditionsContent.target = newConditions ? this.formatRenderConditions(newConditions) : ''; this.diffConditionsContent.cls = this.getItemStatus(data, ['fieldConstraintContent']) ? 'is-update' : ''; this.diffConditions.handlePopShow(e, { theme: 'light diff-conditions', placement: 'bottom-end', maxWidth: 568, offset: 100, interactive: false, }); } /** * 隐藏值约束 diff */ public handleHideContentDiff() { this.diffConditionsContent.cls = ''; this.diffConditions.handlePopHidden(); } /** * 展示关联关系 diff * @param e * @param item * @param data */ public handleShowRelationDiff(e: Event, item: object, data: object) { const { newContent = {}, originContent = {} } = item; const originModelRelation = originContent.modelRelation || []; const targetModelRelation = newContent.modelRelation || []; this.diffRelationContent.origin = originModelRelation.find(relation => relation.fieldName === data.fieldName) || {}; this.diffRelationContent.target = targetModelRelation.find(relation => relation.fieldName === data.fieldName) || {}; this.diffRelationContent.modelCls = this.getItemStatus(data, ['isJoinField', 'relatedModelId']) ? 'is-update' : ''; this.diffRelationContent.fieldCls = this.getItemStatus(data, ['isJoinField', 'relatedFieldName']) ? 'is-update' : ''; this.diffRelation.handlePopShow(e, { theme: 'light diff-conditions', placement: 'bottom-end', maxWidth: 568, offset: 100, interactive: false, }); } /** * 隐藏关联关系 diff */ public handleHideRelationDiff() { this.diffRelationContent.modelCls = ''; this.diffRelationContent.fieldCls = ''; this.diffRelation.handlePopHidden(); } /** * 格式化 table 数据 * @param data */ public tableDataFormatter(data: []) { for (let i = 0; i < data.length; i++) { const cur = data[i]; const next = data[i + 1]; if (cur?.isExtendedField && next?.isExtendedField) { cur.isExtendedFieldCls = true; } } return data; } /** * 设置主表 table row 样式 * @param item */ public rowClassName(item: any) { const { row } = item; const cls = { create: 'create-row ', delete: 'delete-row ', update: 'update-row ', }; const isOnlyIndexUpdate = row.diffKeys && row.diffKeys.length === 1 && row.diffKeys[0] === 'fieldIndex'; const basicCls = row.diffType && cls[row.diffType] ? (isOnlyIndexUpdate ? '' : cls[row.diffType]) : ''; if (row.fieldName === this.activeHoverFieldName) { return basicCls + 'is-hover-row'; } return basicCls + (row.isExtendedField ? 'is-extended-row' : ''); } /** * 设置主表 table cell 样式 */ public cellClassName({ row, column, rowIndex, columnIndex }) { return columnIndex === 0 && row?.isExtendedFieldCls ? 'cell-border-bottom-none' : ''; } /** * table row mouseenter * @param index * @param event * @param row */ public handleRowMouseEnter(index, event, row) { this.activeHoverFieldName = row.fieldName; } /** * table row mouseleave */ public handleRowMouseLeave() { this.activeHoverFieldName = ''; } /** * 获取每项的状态 * @param data * @param keys */ public getItemStatus(data: object = {}, keys: string[]) { return (data.diffKeys || []).some(key => keys.includes(key)); } /** * 获取聚合字段信息 * @param data */ public getAggregationFieldsStr(data: object) { // 聚合字段(aggregationFieldsStr),首先用aggregationFieldsAlias,不存在用aggregationFields const arr = data.aggregationFieldsAlias || data.aggregationFields || []; return arr.join(', ') || '--'; } /** * 字段加工逻辑diff * @param data * @param itemData */ public handleShowFieldCleanContent(data: object, itemData: object = {}) { const { originContent, newContent } = itemData; this.diffCodeDialog.originCode = getCode(originContent, data.fieldName); this.diffCodeDialog.targetCode = getCode(newContent, data.fieldName); this.diffCodeDialog.title = this.$t('字段加工逻辑对比'); this.diffCodeDialog.subTitle = `${data.fieldName} (${data.fieldAlias})`; this.diffCodeDialog.isShow = true; } /** * 指标过滤条件diff * @param data * @param itemData */ public handleShowFilterFormula(data: object, itemData: object = {}) { const { originContent, newContent } = itemData; this.diffCodeDialog.originCode = originContent?.filterFormula; this.diffCodeDialog.targetCode = newContent?.filterFormula; this.diffCodeDialog.title = this.$t('指标'); this.diffCodeDialog.subTitle = `${data.indicatorName} (${data.indicatorAlias})`; this.diffCodeDialog.isShow = true; } }
the_stack
import { EventEmitter } from 'events'; import { bind, cloneDeep, defaults, each, isEqual, keys, uniqueId } from 'lodash'; import { CompositeDisposable, IDisposable } from 'ts-disposables'; import { CommandContext } from '../contexts/CommandContext'; import { RequestContext } from '../contexts/RequestContext'; import { ResponseContext } from '../contexts/ResponseContext'; import { IAsyncClientOptions, IAsyncDriver, IDriverOptions, IOmnisharpClientStatus } from '../enums'; import { DriverState } from '../enums'; import { QueueProcessor } from '../helpers/QueueProcessor'; import { request } from '../helpers/decorators'; import { getPreconditions } from '../helpers/preconditions'; import * as OmniSharp from '../omnisharp-server'; import { ensureClientOptions } from '../options'; import * as AsyncEvents from './AsyncEvents'; ///// // NOT TESTED // NOT READY! :) ///// export class AsyncClient implements IAsyncDriver, IDisposable { private _lowestIndexValue = 0; private _emitter = new EventEmitter(); private _queue: QueueProcessor<PromiseLike<ResponseContext<any, any>>>; private _driver: IAsyncDriver; private _uniqueId = uniqueId('client'); private _disposable = new CompositeDisposable(); private _currentRequests = new Set<RequestContext<any>>(); private _currentState: DriverState = DriverState.Disconnected; private _options: IAsyncClientOptions & IDriverOptions; private _fixups: ((action: string, request: any, options?: OmniSharp.RequestOptions) => void)[] = []; public constructor(_options: Partial<IAsyncClientOptions> & { projectPath: string }) { _options.driver = _options.driver || ((options: IDriverOptions) => { // tslint:disable-next-line:no-require-imports const item = require('../drivers/StdioDriver'); const driverFactory = item[keys(item)[0]]; return new driverFactory(this._options); }); this._options = <IAsyncClientOptions & IDriverOptions>defaults(_options, <IDriverOptions>{ onState: state => { this._currentState = state; this._emitter.emit(AsyncEvents.state, state); }, onEvent: event => { this._emitter.emit(AsyncEvents.event, event); }, onCommand: packet => { const response = new ResponseContext(new RequestContext(this._uniqueId, packet.Command, {}, {}, 'command'), packet.Body); this._respondToRequest(packet.Command, response); }, }); ensureClientOptions(this._options); this._resetDriver(); const getStatusValues = () => <IOmnisharpClientStatus>({ state: this._driver.currentState, outgoingRequests: this.outstandingRequests, hasOutgoingRequests: this.outstandingRequests > 0, }); let lastStatus: IOmnisharpClientStatus = <any>{}; const emitStatus = () => { const newStatus = getStatusValues(); if (!isEqual(getStatusValues(), lastStatus)) { lastStatus = newStatus; this._emitter.emit(AsyncEvents.status, lastStatus); } }; this._emitter.on(AsyncEvents.request, emitStatus); this._emitter.on(AsyncEvents.response, emitStatus); this._queue = new QueueProcessor<PromiseLike<ResponseContext<any, any>>>(this._options.concurrency, bind(this._handleResult, this)); if (this._options.debug) { this._emitter.on(AsyncEvents.response, (context: ResponseContext<any, any>) => { this._emitter.emit(AsyncEvents.event, { Event: 'log', Body: { Message: `/${context.command} ${context.responseTime}ms (round trip)`, LogLevel: 'INFORMATION', }, Seq: -1, Type: 'log', }); }); } } public log(message: string, logLevel?: string) { // log our complete response time this._emitter.emit(AsyncEvents.event, { Event: 'log', Body: { Message: message, LogLevel: logLevel ? logLevel.toUpperCase() : 'INFORMATION', }, Seq: -1, Type: 'log', }); } public connect() { // Currently connecting if (this.currentState >= DriverState.Downloading && this.currentState <= DriverState.Connected) { return; } // Bootstrap plugins here this._currentRequests.clear(); this._driver.connect(); } public disconnect() { this._driver.disconnect(); } public request<TRequest, TResponse>(action: string, req: TRequest, options?: OmniSharp.RequestOptions): Promise<TResponse> { const conditions = getPreconditions(action); if (conditions) { each(conditions, x => x(req)); } if (!options) { options = <OmniSharp.RequestOptions>{}; } // Handle disconnected requests if (this.currentState !== DriverState.Connected && this.currentState !== DriverState.Error) { return new Promise<TResponse>((resolve, reject) => { const disposable = this.onState(state => { if (state === DriverState.Connected) { disposable.dispose(); this.request<TRequest, TResponse>(action, req, options) .then(resolve, reject); } }); }); } const context = new RequestContext(this._uniqueId, action, req, options); return new Promise<TResponse>((resolve, reject) => { this._queue.enqueue(context).then(response => resolve(response.response), reject); }); } public registerFixup(func: (action: string, request: any, options?: OmniSharp.RequestOptions) => void) { this._fixups.push(func); } public get uniqueId() { return this._uniqueId; } public get id() { return this._driver.id; } public get serverPath() { return this._driver.serverPath; } public get projectPath() { return this._driver.projectPath; } public get outstandingRequests() { return this._currentRequests.size; } public get currentState() { return this._currentState; } public getCurrentRequests() { const response: { command: string; sequence: string; silent: boolean; request: any; duration: number; }[] = []; this._currentRequests.forEach(req => { response.push({ command: req.command, sequence: cloneDeep(req.sequence), request: req.request, silent: req.silent, duration: Date.now() - req.time.getTime(), }); }); return response; } public onEvent(callback: (event: OmniSharp.Stdio.Protocol.EventPacket) => void) { return this._listen(AsyncEvents.event, callback); } public onState(callback: (state: DriverState) => void) { return this._listen(AsyncEvents.state, callback); } public onStatus(callback: (status: IOmnisharpClientStatus) => void) { return this._listen(AsyncEvents.status, callback); } public onRequest(callback: (request: RequestContext<any>) => void) { return this._listen(AsyncEvents.request, callback); } public onResponse(callback: (response: ResponseContext<any, any>) => void) { return this._listen(AsyncEvents.response, callback); } public onError(callback: (event: OmniSharp.Stdio.Protocol.EventPacket) => void) { return this._listen(AsyncEvents.error, callback); } public dispose() { if (this._disposable.isDisposed) { return; } this.disconnect(); this._disposable.dispose(); } private _listen(event: string, callback: any): IDisposable { this._emitter.addListener(AsyncEvents.event, callback); return { dispose: () => this._emitter.removeListener(AsyncEvents.event, callback) }; } private _handleResult(context: RequestContext<any>, complete?: () => void): Promise<ResponseContext<any, any>> { // TODO: Find a way to not repeat the same commands, if there are outstanding (timed out) requests. // In some cases for example find usages has taken over 30 seconds, so we shouldn"t hit the server // with multiple of these requests (as we slam the cpU) const result = this._driver.request<any, any>(context.command, context.request); const cmp = () => { this._currentRequests.delete(context); if (complete) { complete(); } }; return new Promise((resolve, reject) => { result .then(data => { this._respondToRequest(context.command, new ResponseContext(context, data)); cmp(); resolve(data); }, error => { this._emitter.emit(AsyncEvents.error, new CommandContext(context.command, error)); this._respondToRequest(context.command, new ResponseContext(context, null, true)); this._currentRequests.delete(context); cmp(); reject(error); }); }); } private _resetDriver() { if (this._driver) { this._disposable.remove(this._driver); this._driver.dispose(); } const { driver } = this._options; this._driver = driver(this._options); this._disposable.add(this._driver); return this._driver; } private _respondToRequest(key: string, response: ResponseContext<any, any>) { key = key.toLowerCase(); this._emitter.emit(key, response); this._emitter.emit(AsyncEvents.response, response); } /* tslint:disable:no-unused-variable */ private _fixup<TRequest>(action: string, req: TRequest, options?: OmniSharp.RequestOptions) { each(this._fixups, f => f(action, req, options)); } /* tslint:enable:no-unused-variable */ } // <#GENERATED /> request(AsyncClient.prototype, 'getteststartinfo'); request(AsyncClient.prototype, 'runtest'); request(AsyncClient.prototype, 'autocomplete'); request(AsyncClient.prototype, 'changebuffer'); request(AsyncClient.prototype, 'codecheck'); request(AsyncClient.prototype, 'codeformat'); request(AsyncClient.prototype, 'diagnostics'); request(AsyncClient.prototype, 'close'); request(AsyncClient.prototype, 'open'); request(AsyncClient.prototype, 'filesChanged'); request(AsyncClient.prototype, 'findimplementations'); request(AsyncClient.prototype, 'findsymbols'); request(AsyncClient.prototype, 'findusages'); request(AsyncClient.prototype, 'fixusings'); request(AsyncClient.prototype, 'formatAfterKeystroke'); request(AsyncClient.prototype, 'formatRange'); request(AsyncClient.prototype, 'getcodeactions'); request(AsyncClient.prototype, 'gotodefinition'); request(AsyncClient.prototype, 'gotofile'); request(AsyncClient.prototype, 'gotoregion'); request(AsyncClient.prototype, 'highlight'); request(AsyncClient.prototype, 'currentfilemembersasflat'); request(AsyncClient.prototype, 'currentfilemembersastree'); request(AsyncClient.prototype, 'metadata'); request(AsyncClient.prototype, 'navigatedown'); request(AsyncClient.prototype, 'navigateup'); request(AsyncClient.prototype, 'packagesearch'); request(AsyncClient.prototype, 'packagesource'); request(AsyncClient.prototype, 'packageversion'); request(AsyncClient.prototype, 'rename'); request(AsyncClient.prototype, 'runcodeaction'); request(AsyncClient.prototype, 'signatureHelp'); request(AsyncClient.prototype, 'gettestcontext'); request(AsyncClient.prototype, 'typelookup'); request(AsyncClient.prototype, 'updatebuffer'); request(AsyncClient.prototype, 'project'); request(AsyncClient.prototype, 'projects'); request(AsyncClient.prototype, 'checkalivestatus'); request(AsyncClient.prototype, 'checkreadystatus'); // tslint:disable-next-line:max-file-line-count request(AsyncClient.prototype, 'stopserver');
the_stack
import { BufferGeometry, Float32BufferAttribute, Points, Color, Vector2, ShaderMaterial, MathUtils, BufferAttribute } from 'three'; import { Tween, Easing } from '@tweenjs/tween.js'; import { ParticleShader } from './shaders/particle-shader'; import { ShaderUtils } from './shaders/shader-utils'; import { LoopableTransitionConfig } from '../transition'; interface ParticleMoveOffset { // the distance of the offset. distance: number; // the angle of the offset in degrees. angle: number; } interface ParticleSwayOffset { // the x distance to sway. x: number; // the y distance to sway. y: number; } type ParticleGroupConfigs = {[name: string]: ParticleGroupConfig}; interface ParticleGroupConfig { // the name of the particle group. name: string; // the number of particles to generate. amount: number; // the minimum size of the particles in world units. Defaults to 0. minSize?: number; // the maximum size of the particles in world units. Defaults to 0. maxSize?: number; // the minimum fade gradient of the particles in relative units (0 to 1). Defaults to 0. minGradient?: number; // the maximum fade gradient of the particles in relative units (0 to 1). Defaults to 1. maxGradient?: number; // the minimum opacity of the particles. Defaults to 0. minOpacity?: number; // the maximum opacity of the particles. Defaults to 1. maxOpacity?: number; // optional color of the particles. Defaults to 0xffffff. color?: number; // the amount of smoothing for animated values (i.e size, gradient, opacity), specified as a value between 0 and 1. Defaults to 0.5. smoothing?: number; } interface ParticleTween { offsetX: number; offsetY: number; } type ParticleGroups = {[name: string]: Required<ParticleGroup>}; interface ParticleGroup extends ParticleGroupConfig { index: number; swayOffset: Vector2; positionTransition: Tween<ParticleTween>; swayTransition: Tween<ParticleTween>; } class Particles { private _width: number; private _height: number; private _maxDepth: number; // groups also store the transitions related to the attributes and offsets private _groups: ParticleGroups = {}; private _particles: Points; private _positions: number[] = []; /** * Constructs a Particles object. * @param {number} width * @param {number} height * @param {number} maxDepth - the maximum depth of the particles in world units. */ constructor(width: number, height: number, maxDepth: number) { this._width = width; this._height = height; this._maxDepth = maxDepth; const geometry = new BufferGeometry(); geometry.setAttribute('position', new Float32BufferAttribute(0, 3)); geometry.setAttribute('size', new Float32BufferAttribute(0, 1)); geometry.setAttribute('gradient', new Float32BufferAttribute(0, 1)); geometry.setAttribute('opacity', new Float32BufferAttribute(0, 1)); geometry.setAttribute('color', new Float32BufferAttribute(0, 3)); this._particles = new Points( geometry, ShaderUtils.createShaderMaterial(ParticleShader), ); } /** * Returns the configurations for the currently set particle groups. * @returns ParticleGroupDefinitionMap */ getConfigs(): ParticleGroupConfigs { const configs: ParticleGroupConfigs = {}; for (const group of Object.values(this._groups)) { const { name, amount, minSize, maxSize, minGradient, maxGradient, minOpacity, maxOpacity, color } = group; configs[name] = { name, amount, minSize, maxSize, minGradient, maxGradient, minOpacity, maxOpacity, color }; } return configs; } /** * Returns whether a group of particles is currently moving. * @param {string} name - the name of the particle group. * @returns boolean */ isMoving(name: string): boolean { return this._groups[name]?.positionTransition.isPlaying() ?? false; } /** * Returns whether a group of particles is currently swaying. * @param {string} name - the name of the particle group. * @returns boolean */ isSwaying(name: string): boolean { return this._groups[name]?.swayTransition.isPlaying() ?? false; } /** * Generates particles based on a given set of configurations. * @param {ParticleGroupConfig | ParticleGroupConfig[]} config - a single or array of particle group configurations. */ generate(configs: ParticleGroupConfig | ParticleGroupConfig[]): void { // cleanup previous configs and objects this.removeAll(); configs = Array.isArray(configs) ? configs : [configs]; let index = 0; for (const config of configs) { const { name, amount = 0, minSize = 0, maxSize = 0, minGradient = 0, maxGradient = 1, minOpacity = 0, maxOpacity = 1, color = 0xffffff, smoothing = 0.5, } = config; // Generate points with attributes for (let i = 0; i < amount || 0; ++i) { const x = (-this._width / 2) + Math.random() * this._width; const y = (-this._height / 2) + Math.random() * this._height; const z = (this._maxDepth / 4) * Math.random(); this._positions.push(x, y, z); } // Store group config this._groups[name] = { name, index, amount, minSize, maxSize, minGradient, maxGradient, minOpacity, maxOpacity, color, smoothing, swayOffset: new Vector2(0, 0), positionTransition: new Tween({ offsetX: 0, offsetY: 0 }), swayTransition: new Tween({ offsetX: 0, offsetY: 0 }), }; index += amount; } const geometry = new BufferGeometry(); geometry.setAttribute('position', new Float32BufferAttribute(index * 3, 3)); geometry.setAttribute('color', new Float32BufferAttribute(index * 3, 3)); geometry.setAttribute('size', new Float32BufferAttribute(index, 1)); geometry.setAttribute('gradient', new Float32BufferAttribute(index, 1)); geometry.setAttribute('opacity', new Float32BufferAttribute(index, 1)); const material = ShaderUtils.createShaderMaterial(ParticleShader); material.transparent = true; this._particles.geometry = geometry; this._particles.material = material; } /** * Removes all particle groups. */ removeAll(): void { for (const group in this._groups) { // stop any ongoing transitions this._groups[group].positionTransition.stop(); this._groups[group].swayTransition.stop(); } // reset particles to empty this._positions = []; this._groups = {}; this._particles.geometry.dispose(); (this._particles.material as ShaderMaterial).dispose(); } /** * Calculates a new position based off an existing position and optional offset. Will wrap around boundaries. * @param {Vector2} position - the current position. * @param {Vector2} offset - the offset from the current position. * @returns Vector2 */ private _getNewPosition(position: Vector2, offset: Vector2): Vector2 { let { x: offsetX, y: offsetY } = offset; offsetX %= this._width; offsetY %= this._height; let x = position.x + offsetX; let y = position.y + offsetY; const halfWidth = this._width / 2; const halfHeight = this._height / 2; // wrap around left/right if (Math.abs(position.x + offsetX) > halfWidth) { x = offsetX > 0 ? -halfWidth + (((position.x + offsetX) - halfWidth) % this._width) : halfWidth - ((Math.abs(position.x + offsetX) - halfWidth) % this._width); } // wrap around top/bottom if (Math.abs(position.y + offsetY) > halfHeight) { y = offsetY > 0 ? -halfHeight + (((position.y + offsetY) - halfHeight) % this._height) : halfHeight - ((Math.abs(position.y + offsetY) - halfHeight) % this._height); } return new Vector2(x, y); } /** * Updates the internal positions for particles. This does NOT update the attributes of the BufferGeometry. * @param {number} index - the index to start at. * @param {number} amount - the number of particles. * @param {number[]} positions - an array containing the position values to use. * @param {Vector2} offset - an optional offset to apply to all new position values. */ private _updatePositions(index: number, amount: number, positions: number[], offset: Vector2) { // Each vertex position is a set of 3 values, so index and amount are adjusted accordingly when iterating. for (let i = index; i < index + amount; ++i) { const { x, y } = this._getNewPosition(new Vector2(positions[i * 3], positions[i * 3 + 1]), offset); this._positions[i * 3] = x; this._positions[i * 3 + 1] = y; } } /** * Moves a group of particles. Cancels any in-progress moves. * @param {string} name - the name of the group to move. * @param {ParticleMoveOffset | boolean} offset - the distance and angle in radians to move. * If a boolean is passed in instead then the move will either continue or stop based on the value. * @param {LoopableTransitionConfig} transition - an optional transition configuration. */ move(name: string, offset: ParticleMoveOffset | boolean, transition: LoopableTransitionConfig): void { const group = this._groups[name]; const { index, amount } = group; if (typeof offset === 'boolean') { if (!offset) { group.positionTransition.stop(); } return; } // Stop ongoing position transition for group. group.positionTransition.stop(); const { loop = false, duration = 0, easing = Easing.Linear.None, onStart = () => ({}), onUpdate = () => ({}), onComplete = () => ({}), onStop = () => ({}), } = transition; const { distance, angle } = offset; const offsetX = distance * Math.cos(MathUtils.degToRad(angle)); const offsetY = distance * Math.sin(MathUtils.degToRad(angle)); if (duration > 0) { // Each vertex position is a set of 3 values, so adjust index and amount accordingly. const startPositions = this._positions.slice(); group.positionTransition = new Tween({ offsetX: 0, offsetY: 0 }) .to({ offsetX, offsetY }, duration * 1000) .easing(easing) .onStart(onStart) .onUpdate(({ offsetX, offsetY }) => { this._updatePositions(index, amount, startPositions, new Vector2(offsetX, offsetY)); onUpdate(); }) .onComplete(() => { if (loop) { // Repeat move with same config. this.move(name, offset, transition); } onComplete(); }) .onStop(onStop) .start(); } else { this._updatePositions(index, amount, this._positions, new Vector2(offsetX, offsetY)); } } /** * Sways a group of particles around their current positions. Cancels any in-progress sways. * @param {string} name - the name of the group to sway. * @param {ParticleSwayOffset | boolean} offset - the distances in world units allowed on each axis for swaying. * If a boolean is passed in instead then the sway will either continue or stop based on the value. * @param {LoopableTransitionConfig} transition - optional configuration for a transition. */ sway(name: string, offset: ParticleSwayOffset | boolean, transition: LoopableTransitionConfig = {}): void { const group = this._groups[name]; const { swayOffset } = group; if (typeof offset === 'boolean') { if (!offset) { group.swayTransition.stop(); } return; } // Stop ongoing sway transition for group. group.swayTransition.stop(); const { loop = false, duration = 0, easing = Easing.Linear.None, onStart = () => ({}), onUpdate = () => ({}), onComplete = () => ({}), onStop = () => ({}), } = transition; const { x, y } = offset; group.swayTransition = new Tween({ offsetX: swayOffset.x, offsetY: swayOffset.y, }) .to({ offsetX: -x + Math.random() * x * 2, offsetY: -y + Math.random() * y * 2, }, duration * 1000) .easing(easing) .onStart(onStart) .onUpdate(({ offsetX, offsetY }) => { swayOffset.set(offsetX, offsetY); onUpdate(); }) .onComplete(() => { if (loop) { this.sway(name, offset, transition); } onComplete(); }) .onStop(onStop) .start(); } /** * Generates a new random averaged value based off a given value and its range. * @param {number} prevValue - the previous value. * @param {number} minValue - the minimum value for the given value. * @param {number} maxValue - the maximum value for the given value. * @param {number} smoothing - optional amount of smoothing to use as a value between 0 and 1. Defaults to 0.5. * @returns number */ private _generateNewRandomAveragedValue(prevValue: number, minValue: number, maxValue: number, smoothing = 0.5): number { // cap smoothing at 0.95 smoothing = Math.min(smoothing, 0.95); const offset = (maxValue - minValue) / 2; const nextValue = Math.max(Math.min(prevValue + (-offset + Math.random() * offset * 2), maxValue), minValue); const smoothedValue = (prevValue * smoothing) + (nextValue * (1 - smoothing)); return Math.max(Math.min(smoothedValue, maxValue), minValue); } /** * Updates the positions of the particles. Should be called on every render frame. */ update(): void { const { attributes } = this._particles.geometry; const { position: positions, size: sizes, gradient: gradients, opacity: opacities, color: colors, } = attributes; for (const group of Object.values(this._groups)) { const { index, amount, minSize, maxSize, minGradient, maxGradient, minOpacity, maxOpacity, color, smoothing, swayOffset, } = group; for (let i = index; i < index + amount; ++i) { // Apply offset to current position (excluding z). const position = this._getNewPosition(new Vector2(this._positions[i * 3], this._positions[i * 3 + 1]), swayOffset); const rgb = new Color(color); positions.setXYZ(i, position.x, position.y, this._positions[i * 3 + 2]); colors.setXYZ(i, rgb.r, rgb.g, rgb.b); sizes.setX(i, this._generateNewRandomAveragedValue(sizes.getX(i), minSize, maxSize, smoothing)); gradients.setX(i, this._generateNewRandomAveragedValue(gradients.getX(i), minGradient, maxGradient, smoothing)); opacities.setX(i, this._generateNewRandomAveragedValue(opacities.getX(i), minOpacity, maxOpacity, smoothing)); } } (attributes.position as BufferAttribute).needsUpdate = true; (attributes.size as BufferAttribute).needsUpdate = true; (attributes.gradient as BufferAttribute).needsUpdate = true; (attributes.opacity as BufferAttribute).needsUpdate = true; (attributes.color as BufferAttribute).needsUpdate = true; } /** * Returns a three.js object containing the particles. * To use the particles, add this object into a three.js scene. * @returns Points */ get object(): Points { return this._particles; } /** * Disposes this object. Call when this object is no longer needed, otherwise leaks may occur. */ dispose(): void { this._particles.geometry.dispose(); (this._particles.material as ShaderMaterial).dispose(); } } export { ParticleMoveOffset, ParticleSwayOffset, ParticleGroupConfigs, ParticleGroupConfig, Particles, }; export default Particles;
the_stack
import { Semigroup } from "fp-ts/lib/Semigroup" import { Monoid } from "fp-ts/lib/Monoid"; import { Applicative2 } from "fp-ts/lib/Applicative"; import { Either, left, right } from "fp-ts/lib/Either"; import * as either from "fp-ts/lib/Either"; import { constant, flow, FunctionN, identity, Lazy } from "fp-ts/lib/function"; import { Monad2 } from "fp-ts/lib/Monad"; import { none, some, Option } from "fp-ts/lib/Option"; import * as option from "fp-ts/lib/Option"; import { pipe } from "fp-ts/lib/pipeable"; import { Deferred, makeDeferred } from "./deferred"; import { makeDriver, Driver } from "./driver"; import { Cause, Exit } from "./exit"; import * as ex from "./exit"; import { makeRef, Ref } from "./ref"; import { Runtime } from "./runtime"; import { fst, snd, tuple2 } from "./support/util"; export enum WaveTag { Pure, Raised, Completed, Suspended, Async, Chain, Collapse, InterruptibleRegion, AccessInterruptible, AccessRuntime } /** * A description of an effect to perform */ export type Wave<E, A> = Pure<E, A> | Raised<E, A> | Completed<E, A> | Suspended<E, A> | Async<E, A> | Chain<E, any, A> | // eslint-disable-line @typescript-eslint/no-explicit-any Collapse<any, E, any, A> | // eslint-disable-line @typescript-eslint/no-explicit-any InterruptibleRegion<E, A> | AccessInterruptible<E, A> | AccessRuntime<E, A>; export type ReturnCovaryE<T, E2> = T extends Wave<infer E, infer A> ? (E extends E2 ? Wave<E2, A> : Wave<E | E2, A>) : never /** * Perform a widening of Wave<E1, A> such that the result includes E2. * * This encapsulates normal subtype widening, but will also widen to E1 | E2 as a fallback * Assumes that this function (which does nothing when compiled to js) will be inlined in hot code */ export function covaryE<E1, A, E2>(wave: Wave<E1, A>): ReturnCovaryE<typeof wave, E2> { return wave as unknown as ReturnCovaryE<typeof wave, E2>; } /** * Type inference helper form of covaryToE */ export function covaryToE<E2>(): <E1, A>(wave: Wave<E1, A>) => ReturnCovaryE<Wave<E1, A>, E2> { return (w) => covaryE(w); } export interface Pure<E, A> { readonly _tag: WaveTag.Pure; readonly value: A; } /** * An IO has succeeded * @param a the value */ export function pure<A>(a: A): Wave<never, A> { return { _tag: WaveTag.Pure, value: a }; } export interface Raised<E, A> { readonly _tag: WaveTag.Raised; readonly error: Cause<E>; } /** * An IO that is failed * * Prefer raiseError or raiseAbort * @param e */ export function raised<E>(e: Cause<E>): Wave<E, never> { return { _tag: WaveTag.Raised, error: e }; } /** * An IO that is failed with a checked error * @param e */ export function raiseError<E>(e: E): Wave<E, never> { return raised(ex.raise(e)); } /** * An IO that is failed with an unchecked error * @param u */ export function raiseAbort(u: unknown): Wave<never, never> { return raised(ex.abort(u)); } /** * An IO that is already interrupted */ export const raiseInterrupt: Wave<never, never> = raised(ex.interrupt); export interface Completed<E, A> { readonly _tag: WaveTag.Completed; readonly exit: Exit<E, A>; } /** * An IO that is completed with the given exit * @param exit */ export function completed<E, A>(exit: Exit<E, A>): Wave<E, A> { return { _tag: WaveTag.Completed, exit }; } export interface Suspended<E, A> { readonly _tag: WaveTag.Suspended; readonly thunk: Lazy<Wave<E, A>>; } /** * Wrap a block of impure code that returns an IO into an IO * * When evaluated this IO will run the given thunk to produce the next IO to execute. * @param thunk */ export function suspended<E, A>(thunk: Lazy<Wave<E, A>>): Wave<E, A> { return { _tag: WaveTag.Suspended, thunk }; } /** * Wrap a block of impure code in an IO * * When evaluated the this will produce a value or throw * @param thunk */ export function sync<A>(thunk: Lazy<A>): Wave<never, A> { return suspended(() => pure(thunk())); } export interface Async<E, A> { readonly _tag: WaveTag.Async; readonly op: FunctionN<[FunctionN<[Either<E, A>], void>], Lazy<void>>; } /** * Wrap an impure callback in an IO * * The provided function must accept a callback to report results to and return a cancellation action. * If your action is uncancellable for some reason, you should return an empty thunk and wrap the created IO * in uninterruptible * @param op */ export function async<E, A>(op: FunctionN<[FunctionN<[Either<E, A>], void>], Lazy<void>>): Wave<E, A> { return { _tag: WaveTag.Async, op }; } /** * Wrap an impure callback in IO * * This is a variant of async where the effect cannot fail with a checked exception. * @param op */ export function asyncTotal<A>(op: FunctionN<[FunctionN<[A], void>], Lazy<void>>): Wave<never, A> { return async((callback) => op((a) => callback(right(a)))); } export interface InterruptibleRegion<E, A> { readonly _tag: WaveTag.InterruptibleRegion; readonly inner: Wave<E, A>; readonly flag: boolean; } /** * Demarcate a region of interruptible state * @param inner * @param flag */ export function interruptibleRegion<E, A>(inner: Wave<E, A>, flag: boolean): Wave<E, A> { return { _tag: WaveTag.InterruptibleRegion, inner, flag }; } export interface Chain<E, Z, A> { readonly _tag: WaveTag.Chain; readonly inner: Wave<E, Z>; readonly bind: FunctionN<[Z], Wave<E, A>>; } /** * Produce an new IO that will use the value produced by inner to produce the next IO to evaluate * @param inner * @param bind */ export function chain<E, A, B>(inner: Wave<E, A>, bind: FunctionN<[A], Wave<E, B>>): Wave<E, B> { return { _tag: WaveTag.Chain, inner: inner, bind: bind }; } /** * Lift an Either into an IO * @param e */ export function encaseEither<E, A>(e: Either<E, A>): Wave<E, A> { return pipe(e, either.fold<E, A, Wave<E, A>>(raiseError, pure)); } /** * Lift an Option into an IO * @param o * @param onError */ export function encaseOption<E, A>(o: Option<A>, onError: Lazy<E>): Wave<E, A> { return pipe(o, option.map<A, Wave<E, A>>(pure), option.getOrElse<Wave<E, A>>(() => raiseError(onError()))); } /** * Flatten a nested IO * * @param inner */ export function flatten<E, A>(inner: Wave<E, Wave<E, A>>): Wave<E, A> { return chain(inner, identity); } /** * Curried function first form of chain * @param bind */ export function chainWith<E, Z, A>(bind: FunctionN<[Z], Wave<E, A>>): (io: Wave<E, Z>) => Wave<E, A> { return (io) => chain(io, bind); } export interface Collapse<E1, E2, A1, A2> { readonly _tag: WaveTag.Collapse; readonly inner: Wave<E1, A1>; readonly failure: FunctionN<[Cause<E1>], Wave<E2, A2>>; readonly success: FunctionN<[A1], Wave<E2, A2>>; } /** * Fold the result of an IO into a new IO. * * This can be thought of as a more powerful form of chain * where the computation continues with a new IO depending on the result of inner. * @param inner The IO to fold the exit of * @param failure * @param success */ export function foldExit<E1, E2, A1, A2>(inner: Wave<E1, A1>, failure: FunctionN<[Cause<E1>], Wave<E2, A2>>, success: FunctionN<[A1], Wave<E2, A2>>): Wave<E2, A2> { return { _tag: WaveTag.Collapse, inner, failure, success }; } /** * Curried form of foldExit * @param failure * @param success */ export function foldExitWith<E1, E2, A1, A2>(failure: FunctionN<[Cause<E1>], Wave<E2, A2>>, success: FunctionN<[A1], Wave<E2, A2>>): FunctionN<[Wave<E1, A1>], Wave<E2, A2>> { return (io) => foldExit(io, failure, success); } export interface AccessInterruptible<E, A> { readonly _tag: WaveTag.AccessInterruptible; readonly f: FunctionN<[boolean], A>; } /** * Get the interruptible state of the current fiber */ export const accessInterruptible: Wave<never, boolean> = { _tag: WaveTag.AccessInterruptible, f: identity }; export interface AccessRuntime<E, A> { readonly _tag: WaveTag.AccessRuntime; readonly f: FunctionN<[Runtime], A>; } /** * Get the runtime of the current fiber */ export const accessRuntime: Wave<never, Runtime> = { _tag: WaveTag.AccessRuntime, f: identity }; /** * Access the runtime then provide it to the provided function * @param f */ export function withRuntime<E, A>(f: FunctionN<[Runtime], Wave<E, A>>): Wave<E, A> { return chain(accessRuntime as Wave<E, Runtime>, f); } /** * Map the value produced by an IO * @param io * @param f */ export function map<E, A, B>(base: Wave<E, A>, f: FunctionN<[A], B>): Wave<E, B> { return chain<E, A, B>(base, flow(f, pure)); } /** * Lift a function on values to a function on IOs * @param f */ export function lift<A, B>(f: FunctionN<[A], B>): <E>(io: Wave<E, A>) => Wave<E, B> { return <E>(io: Wave<E, A>) => map(io, f); } export const mapWith = lift; /** * Map the value produced by an IO to the constant b * @param io * @param b */ export function as<E, A, B>(io: Wave<E, A>, b: B): Wave<E, B> { return map(io, constant(b)); } /** * Curried form of as * @param b */ export function to<B>(b: B): <E, A>(io: Wave<E, A>) => Wave<E, B> { return (io) => as(io, b); } /** * Sequence a Wave and then produce an effect based on the produced value for observation. * * Produces the result of the iniital Wave * @param inner * @param bind */ export function chainTap<E, A>(inner: Wave<E, A>, bind: FunctionN<[A], Wave<E, unknown>>): Wave<E, A> { return chain(inner, (a) => as(bind(a), a) ); } export function chainTapWith<E, A>(bind: FunctionN<[A], Wave<E, unknown>>): (inner: Wave<E, A>) => Wave<E, A> { return (inner) => chainTap(inner, bind); } /** * Map the value produced by an IO to void * @param io */ export function asUnit<E, A>(io: Wave<E, A>): Wave<E, void> { return as(io, undefined); } /** * An IO that succeeds immediately with void */ export const unit: Wave<never, void> = pure(undefined); /** * Produce an new IO that will use the error produced by inner to produce a recovery program * @param io * @param f */ export function chainError<E1, E2, A>(io: Wave<E1, A>, f: FunctionN<[E1], Wave<E2, A>>): Wave<E2, A> { return foldExit(io, (cause) => cause._tag === ex.ExitTag.Raise ? f(cause.error) : completed(cause), pure ); } /** * Curriend form of chainError * @param f */ export function chainErrorWith<E1, E2, A>(f: FunctionN<[E1], Wave<E2, A>>): (rio: Wave<E1, A>) => Wave<E2, A> { return (io) => chainError(io, f); } /** * Map the error produced by an IO * @param io * @param f */ export function mapError<E1, E2, A>(io: Wave<E1, A>, f: FunctionN<[E1], E2>): Wave<E2, A> { return chainError(io, flow(f, raiseError)); } /** * Curried form of mapError * @param f */ export function mapErrorWith<E1, E2>(f: FunctionN<[E1], E2>): <A>(io: Wave<E1, A>) => Wave<E2, A> { return <A>(io: Wave<E1, A>) => mapError(io, f); } /** * Map over either the error or value produced by an IO * @param io * @param leftMap * @param rightMap */ export function bimap<E1, E2, A, B>(io: Wave<E1, A>, leftMap: FunctionN<[E1], E2>, rightMap: FunctionN<[A], B>): Wave<E2, B> { return foldExit(io, (cause) => cause._tag === ex.ExitTag.Raise ? raiseError(leftMap(cause.error)) : completed(cause), flow(rightMap, pure) ); } /** * Curried form of bimap * @param leftMap * @param rightMap */ export function bimapWith<E1, E2, A, B>(leftMap: FunctionN<[E1], E2>, rightMap: FunctionN<[A], B>): FunctionN<[Wave<E1, A>], Wave<E2, B>> { return (io) => bimap(io, leftMap, rightMap); } /** * Zip the result of two IOs together using the provided function * @param first * @param second * @param f */ export function zipWith<E, A, B, C>(first: Wave<E, A>, second: Wave<E, B>, f: FunctionN<[A, B], C>): Wave<E, C> { return chain(first, (a) => map(second, (b) => f(a, b)) ); } /** * Zip the result of two IOs together into a tuple type * @param first * @param second */ export function zip<E, A, B>(first: Wave<E, A>, second: Wave<E, B>): Wave<E, readonly [A, B]> { return zipWith(first, second, tuple2); } /** * Evaluate two IOs in sequence and produce the value produced by the first * @param first * @param second */ export function applyFirst<E, A, B>(first: Wave<E, A>, second: Wave<E, B>): Wave<E, A> { return zipWith(first, second, fst); } /** * Evaluate two IOs in sequence and produce the value produced by the second * @param first * @param second */ export function applySecond<E, A, B>(first: Wave<E, A>, second: Wave<E, B>): Wave<E, B> { return zipWith(first, second, snd); } /** * Evaluate two IOs in sequence and produce the value of the second. * This is suitable for cases where second is recursively defined * @param first * @param second */ export function applySecondL<E, A, B>(first: Wave<E, A>, second: Lazy<Wave<E, B>>): Wave<E, B> { return chain(first, () => second()); } /** * Applicative ap * @param ioa * @param iof */ export function ap<E, A, B>(ioa: Wave<E, A>, iof: Wave<E, FunctionN<[A], B>>): Wave<E, B> { // Find the apply/thrush operator I'm sure exists in fp-ts somewhere return zipWith(ioa, iof, (a, f) => f(a)); } /** * Flipped argument form of ap * @param iof * @param ioa */ export function ap_<E, A, B>(iof: Wave<E, FunctionN<[A], B>>, ioa: Wave<E, A>): Wave<E, B> { return zipWith(iof, ioa, (f, a) => f(a)); } /** * Flip the error and success channels in an IO * @param io */ export function flip<E, A>(io: Wave<E, A>): Wave<A, E> { return foldExit( io, (error) => error._tag === ex.ExitTag.Raise ? pure(error.error) : completed(error), raiseError ); } /** * Execute the provided IO forever (or until it errors) * @param io */ export function forever<E, A>(io: Wave<E, A>): Wave<E, A> { return chain(io, () => forever(io)); } /** * Create an IO that traps all exit states of io. * * Note that interruption will not be caught unless in an uninterruptible region * @param io */ export function result<E, A>(io: Wave<E, A>): Wave<never, Exit<E, A>> { return foldExit(io, (c) => pure(c) as Wave<never, Exit<E, A>>, (d) => pure(ex.done(d))); } /** * Create an interruptible region around the evalution of io * @param io */ export function interruptible<E, A>(io: Wave<E, A>): Wave<E, A> { return interruptibleRegion(io, true); } /** * Create an uninterruptible region around the evaluation of io * @param io */ export function uninterruptible<E, A>(io: Wave<E, A>): Wave<E, A> { return interruptibleRegion(io, false); } /** * Create an IO that produces void after ms milliseconds * @param ms */ export function after(ms: number): Wave<never, void> { return chain(accessRuntime, (runtime) => asyncTotal((callback) => runtime.dispatchLater(() => callback(undefined), ms) ) ); } /** * The type of a function that can restore outer interruptible state */ export type InterruptMaskCutout<E, A> = FunctionN<[Wave<E, A>], Wave<E, A>>; function makeInterruptMaskCutout<E, A>(state: boolean): InterruptMaskCutout<E, A> { return (inner: Wave<E, A>) => interruptibleRegion(inner, state); } /** * Create an uninterruptible masked region * * When the returned IO is evaluated an uninterruptible region will be created and , f will receive an InterruptMaskCutout that can be used to restore the * interruptible status of the region above the one currently executing (which is uninterruptible) * @param f */ export function uninterruptibleMask<E, A>(f: FunctionN<[InterruptMaskCutout<E, A>], Wave<E, A>>): Wave<E, A> { return chain(accessInterruptible as Wave<E, boolean>, (flag) => { const cutout = makeInterruptMaskCutout<E, A>(flag); return uninterruptible(f(cutout)); }); } /** * Create an interruptible masked region * * Similar to uninterruptibleMask * @param f */ export function interruptibleMask<E, A>(f: FunctionN<[InterruptMaskCutout<E, A>], Wave<E, A>>): Wave<E, A> { return chain(accessInterruptible as Wave<E, boolean>, (flag) => interruptible(f(makeInterruptMaskCutout(flag))) ); } function combineFinalizerExit<E, A>(fiberExit: Exit<E, A>, releaseExit: Exit<E, unknown>): Exit<E, A> { if (fiberExit._tag === ex.ExitTag.Done && releaseExit._tag === ex.ExitTag.Done) { return fiberExit; } else if (fiberExit._tag === ex.ExitTag.Done) { return releaseExit as Cause<E>; } else if (releaseExit._tag === ex.ExitTag.Done) { return fiberExit; } else { // TODO: Figure out how to sanely report both of these, we swallow them currently // This would affect chainError (i.e. assume multiples are actually an abort condition that happens to be typed) return fiberExit; } } /** * Resource acquisition and release construct. * * Once acquire completes successfully, release is guaranteed to execute following the evaluation of the IO produced by use. * Release receives the exit state of use along with the resource. * @param acquire * @param release * @param use */ export function bracketExit<E, A, B>(acquire: Wave<E, A>, release: FunctionN<[A, Exit<E, B>], Wave<E, unknown>>, use: FunctionN<[A], Wave<E, B>>): Wave<E, B> { return uninterruptibleMask((cutout) => chain(acquire, (a) => chain(result(cutout(use(a))), (exit) => chain(result(release(a, exit)), (finalize) => completed(combineFinalizerExit(exit, finalize))) ) ) ) } /** * Weaker form of bracketExit where release does not receive the exit status of use * @param acquire * @param release * @param use */ export function bracket<E, A, B>(acquire: Wave<E, A>, release: FunctionN<[A], Wave<E, unknown>>, use: FunctionN<[A], Wave<E, B>>): Wave<E, B> { return bracketExit(acquire, (e) => release(e), use); } /** * Guarantee that once ioa begins executing the finalizer will execute. * @param ioa * @param finalizer */ export function onComplete<E, A>(ioa: Wave<E, A>, finalizer: Wave<E, unknown>): Wave<E, A> { return uninterruptibleMask((cutout) => chain(result(cutout(ioa)), (exit) => chain(result(finalizer), (finalize) => completed(combineFinalizerExit(exit, finalize)) ) )); } /** * Guarantee that once ioa begins executing if it is interrupted finalizer will execute * @param ioa * @param finalizer */ export function onInterrupted<E, A>(ioa: Wave<E, A>, finalizer: Wave<E, unknown>): Wave<E, A> { return uninterruptibleMask((cutout) => chain(result(cutout(ioa)), (exit) => exit._tag === ex.ExitTag.Interrupt ? chain(result(finalizer), (finalize) => completed(combineFinalizerExit(exit, finalize))) : completed(exit) ) ); } /** * Introduce a gap in executing to allow other fibers to execute (if any are pending) */ export const shifted: Wave<never, void> = uninterruptible(chain(accessRuntime, (runtime: Runtime) => // why does this not trigger noImplicitAny asyncTotal<void>((callback) => { runtime.dispatch(() => callback(undefined)); // tslint:disable-next-line return () => { }; }) )); /** * Introduce a synchronous gap before io that will allow other fibers to execute (if any are pending) * @param io */ export function shiftBefore<E, A>(io: Wave<E, A>): Wave<E, A> { return applySecond(shifted as Wave<E, void>, io); } /** * Introduce a synchronous gap after an io that will allow other fibers to execute (if any are pending) * @param io */ export function shiftAfter<E, A>(io: Wave<E, A>): Wave<E, A> { return applyFirst(io, shifted as Wave<E, void>); } /** * Introduce an asynchronous gap that will suspend the runloop and return control to the javascript vm */ export const shiftedAsync: Wave<never, void> = pipe( accessRuntime, chainWith((runtime: Runtime) => asyncTotal<void>((callback) => { return runtime.dispatchLater(() => callback(undefined), 0); }) ), uninterruptible ); /** * Introduce an asynchronous gap before IO * @param io */ export function shiftAsyncBefore<E, A>(io: Wave<E, A>): Wave<E, A> { return applySecond(shiftedAsync as Wave<E, void>, io); } /** * Introduce asynchronous gap after an IO * @param io */ export function shiftAsyncAfter<E, A>(io: Wave<E, A>): Wave<E, A> { return applyFirst(io, shiftedAsync as Wave<E, void>); } /** * An IO that never produces a value or an error. * * This IO will however prevent a javascript runtime such as node from exiting by scheduling an interval for 60s */ export const never: Wave<never, never> = asyncTotal(() => { // tslint:disable-next-line:no-empty const handle = setInterval(() => { }, 60000); return () => { clearInterval(handle); }; }); /** * Delay evaluation of inner by some amount of time * @param inner * @param ms */ export function delay<E, A>(inner: Wave<E, A>, ms: number): Wave<E, A> { return applySecond(after(ms) as Wave<E, void>, inner); } /** * Curried form of delay */ export function liftDelay(ms: number): <E, A>(io: Wave<E, A>) => Wave<E, A> { return (io) => delay(io, ms); } export interface Fiber<E, A> { /** * The name of the fiber */ readonly name: Option<string>; /** * Send an interrupt signal to this fiber. * * The this will complete execution once the target fiber has halted. * Does nothing if the target fiber is already complete */ readonly interrupt: Wave<never, void>; /** * Await the result of this fiber */ readonly wait: Wave<never, Exit<E, A>>; /** * Join with this fiber. * This is equivalent to fiber.wait.chain(io.completeWith) */ readonly join: Wave<E, A>; /** * Poll for a fiber result */ readonly result: Wave<E, Option<A>>; /** * Determine if the fiber is complete */ readonly isComplete: Wave<never, boolean>; } function createFiber<E, A>(driver: Driver<E, A>, n?: string): Fiber<E, A> { const name = option.fromNullable(n); const sendInterrupt = sync(() => { driver.interrupt(); }); const wait = asyncTotal(driver.onExit); const interrupt = applySecond(sendInterrupt, asUnit(wait)); const join = chain(wait, (exit) => completed(exit)); const result = chain(sync(() => driver.exit()), (opt) => pipe(opt, option.fold(() => pure(none), (exit: Exit<E, A>) => map(completed(exit), some)))); const isComplete = sync(() => option.isSome(driver.exit())); return { name, wait, interrupt, join, result, isComplete }; } /** * Implementation of wave/waver fork. Creates an IO that will fork a fiber in the background * @param init * @param name */ export function makeFiber<E, A>(init: Wave<E, A>, name?: string): Wave<never, Fiber<E, A>> { return chain( accessRuntime as Wave<never, Runtime>, (runtime) => sync(() => { const driver = makeDriver<E, A>(runtime); const fiber = createFiber(driver, name); driver.start(init); return fiber; })); } /** * Fork the program described by IO in a separate fiber. * * This fiber will begin executing once the current fiber releases control of the runloop. * If you need to begin the fiber immediately you should use applyFirst(forkIO, shifted) * @param io * @param name */ export function fork<E, A>(io: Wave<E, A>, name?: string): Wave<never, Fiber<E, A>> { return makeFiber(io, name); } function completeLatched<E1, E2, A, B, C>(latch: Ref<boolean>, channel: Deferred<E2, C>, combine: FunctionN<[Exit<E1, A>, Fiber<E1, B>], Wave<E2, C>>, other: Fiber<E1, B>): FunctionN<[Exit<E1, A>], Wave<never, void>> { return (exit) => { const act: Wave<never, Wave<never, void>> = latch.modify((flag) => !flag ? [channel.from(combine(exit, other)), true] as const : [unit as Wave<never, void>, flag] as const ) return flatten(act); } } /** * Race two fibers together and combine their results. * * This is the primitive from which all other racing and timeout operators are built and you should favor those unless you have very specific needs. * @param first * @param second * @param onFirstWon * @param onSecondWon */ export function raceFold<E1, E2, A, B, C>(first: Wave<E1, A>, second: Wave<E1, B>, onFirstWon: FunctionN<[Exit<E1, A>, Fiber<E1, B>], Wave<E2, C>>, onSecondWon: FunctionN<[Exit<E1, B>, Fiber<E1, A>], Wave<E2, C>>): Wave<E2, C> { return uninterruptibleMask<E2, C>((cutout) => chain<E2, Ref<boolean>, C>(makeRef<boolean>(false), (latch) => chain<E2, Deferred<E2, C>, C>(makeDeferred<E2, C>(), (channel) => chain(fork(first), (fiber1) => chain(fork(second), (fiber2) => chain(fork(chain(fiber1.wait as Wave<never, Exit<E1, A>>, completeLatched(latch, channel, onFirstWon, fiber2))), () => chain(fork(chain(fiber2.wait as Wave<never, Exit<E1, B>>, completeLatched(latch, channel, onSecondWon, fiber1))), () => onInterrupted(cutout(channel.wait), applySecond(fiber1.interrupt, fiber2.interrupt) as Wave<never, void>) ) ) ) ) ) ) ); } /** * Execute an IO and produce the next IO to run based on whether it completed successfully in the alotted time or not * @param source * @param ms * @param onTimeout * @param onCompleted */ export function timeoutFold<E1, E2, A, B>(source: Wave<E1, A>, ms: number, onTimeout: FunctionN<[Fiber<E1, A>], Wave<E2, B>>, onCompleted: FunctionN<[Exit<E1, A>], Wave<E2, B>>): Wave<E2, B> { return raceFold<E1, E2, A, void, B>( source, after(ms), (exit, delayFiber) => applySecond(delayFiber.interrupt as Wave<never, void>, onCompleted(exit)), (_, fiber) => onTimeout(fiber) ); } function interruptLoser<E, A>(exit: Exit<E, A>, loser: Fiber<E, A>): Wave<E, A> { return applySecond(loser.interrupt, completed(exit)); } /** * Return the reuslt of the first IO to complete or error successfully * @param io1 * @param io2 */ export function raceFirst<E, A>(io1: Wave<E, A>, io2: Wave<E, A>): Wave<E, A> { return raceFold<E, E, A, A, A>(io1, io2, interruptLoser, interruptLoser); } function fallbackToLoser<E, A>(exit: Exit<E, A>, loser: Fiber<E, A>): Wave<E, A> { return exit._tag === ex.ExitTag.Done ? applySecond(loser.interrupt, completed(exit)) : loser.join; } /** * Return the result of the first IO to complete successfully. * * If an error occurs, fall back to the other IO. * If both error, then fail with the second errors * @param io1 * @param io2 */ export function race<E, A>(io1: Wave<E, A>, io2: Wave<E, A>): Wave<E, A> { return raceFold<E, E, A, A, A>(io1, io2, fallbackToLoser, fallbackToLoser); } /** * Zip the result of 2 ios executed in parallel together with the provided function. * @param ioa * @param iob * @param f */ export function parZipWith<E, A, B, C>(ioa: Wave<E, A>, iob: Wave<E, B>, f: FunctionN<[A, B], C>): Wave<E, C> { return raceFold<E, E, A, B, C>(ioa, iob, (aExit, bFiber) => zipWith(completed(aExit), bFiber.join, f), (bExit, aFiber) => zipWith(aFiber.join, completed(bExit), f) ); } /** * Tuple the result of 2 ios executed in parallel * @param ioa * @param iob */ export function parZip<E, A, B>(ioa: Wave<E, A>, iob: Wave<E, B>): Wave<E, readonly [A, B]> { return parZipWith(ioa, iob, tuple2); } /** * Execute two ios in parallel and take the result of the first. * @param ioa * @param iob */ export function parApplyFirst<E, A, B>(ioa: Wave<E, A>, iob: Wave<E, B>): Wave<E, A> { return parZipWith(ioa, iob, fst); } /** * Exeute two IOs in parallel and take the result of the second * @param ioa * @param iob */ export function parApplySecond<E, A, B>(ioa: Wave<E, A>, iob: Wave<E, B>): Wave<E, B> { return parZipWith(ioa, iob, snd); } /** * Parallel form of ap * @param ioa * @param iof */ export function parAp<E, A, B>(ioa: Wave<E, A>, iof: Wave<E, FunctionN<[A], B>>): Wave<E, B> { return parZipWith(ioa, iof, (a, f) => f(a)); } /** * Parallel form of ap_ * @param iof * @param ioa */ export function parAp_<E, A, B>(iof: Wave<E, FunctionN<[A], B>>, ioa: Wave<E, A>): Wave<E, B> { return parZipWith(iof, ioa, (f, a) => f(a)); } /** * Convert an error into an unchecked error. * @param io */ export function orAbort<E, A>(io: Wave<E, A>): Wave<never, A> { return chainError(io, (e) => raiseAbort(e) as Wave<never, never>); } /** * Run source for a maximum amount of ms. * * If it completes succesfully produce a some, if not interrupt it and produce none * @param source * @param ms */ export function timeoutOption<E, A>(source: Wave<E, A>, ms: number): Wave<E, Option<A>> { return timeoutFold<E, E, A, Option<A>>( source, ms, (actionFiber) => applySecond(actionFiber.interrupt, pure(none)), (exit) => map(completed(exit), some) ); } /** * Create an IO from a Promise factory. * @param thunk */ export function fromPromise<A>(thunk: Lazy<Promise<A>>): Wave<unknown, A> { return uninterruptible(async<unknown, A>((callback) => { thunk().then((v) => callback(right(v))).catch((e) => callback(left(e))); // tslint:disable-next-line return () => { }; })); } /** * Run the given IO with the provided environment. * @param io * @param r * @param callback */ export function run<E, A>(io: Wave<E, A>, callback?: FunctionN<[Exit<E, A>], void>): Lazy<void> { const driver = makeDriver<E, A>(); if (callback) { driver.onExit(callback); } driver.start(io); return driver.interrupt; } /** * Run an IO and return a Promise of its result * * Allows providing an environment parameter directly * @param io * @param r */ export function runToPromise<E, A>(io: Wave<E, A>): Promise<A> { return new Promise((resolve, reject) => run(io, (exit) => { if (exit._tag === ex.ExitTag.Done) { resolve(exit.value); } else if (exit._tag === ex.ExitTag.Abort) { reject(exit.abortedWith); } else if (exit._tag === ex.ExitTag.Raise) { reject(exit.error); } else if (exit._tag === ex.ExitTag.Interrupt) { reject(); } }) ); } /** * Run an IO returning a promise of an Exit. * * The Promise will not reject. * Allows providing an environment parameter directly * @param io * @param r */ export function runToPromiseExit<E, A>(io: Wave<E, A>): Promise<Exit<E, A>> { return new Promise((result) => run(io, result)) } export const URI = "Wave"; export type URI = typeof URI; declare module "fp-ts/lib/HKT" { interface URItoKind2<E, A> { Wave: Wave<E, A>; } } export const instances: Monad2<URI> = { URI, map, of: <E, A>(a: A): Wave<E, A> => pure(a), ap: ap_, chain, } as const; export const wave = instances; export const parInstances: Applicative2<URI> = { URI, map, of: <E, A>(a: A): Wave<E, A> => pure(a), ap: parAp_ } as const; export const parWave = parInstances export function getSemigroup<E, A>(s: Semigroup<A>): Semigroup<Wave<E, A>> { return { concat(x: Wave<E, A>, y: Wave<E, A>): Wave<E, A> { return zipWith(x, y, s.concat) } }; } export function getMonoid<E, A>(m: Monoid<A>): Monoid<Wave<E, A>> { return { ...getSemigroup(m), empty: pure(m.empty) } } export function getRaceMonoid<E, A>(): Monoid<Wave<E, A>> { return { concat: race, empty: never } }
the_stack
import * as fs from 'fs-extra'; import * as path from 'path'; import * as semver from 'semver'; import { commands, ProgressLocation, window } from 'vscode'; import { Constants, RequiredApps } from '../Constants'; import { getWorkspaceRoot } from '../helpers'; import { Output } from '../Output'; import { Telemetry } from '../TelemetryClient'; import { executeCommand, tryExecuteCommand } from './command'; import { TruffleConfiguration } from './truffleConfig'; export namespace required { export interface IRequiredVersion { app: string; isValid: boolean; version: string; requiredVersion: string | { min: string, max: string }; } export enum Scope { locally = 1, global = 0, } const currentState: { [key: string]: IRequiredVersion } = {}; const requiredApps = [RequiredApps.node, RequiredApps.npm, RequiredApps.git]; const auxiliaryApps = [RequiredApps.python, RequiredApps.truffle, RequiredApps.ganache]; export function isValid(version: string, minVersion: string, maxVersion?: string): boolean { return !!semver.valid(version) && semver.gte(version, minVersion) && (maxVersion ? semver.lt(version, maxVersion) : true); } /** * Function check all apps: Node.js, npm, git, truffle, ganache-cli, python * Show Requirements Page with checking showOnStartup flag */ export async function checkAllApps(): Promise<boolean> { const valid = await checkAppsSilent(...requiredApps, ...auxiliaryApps); if (!valid) { const message = Constants.informationMessage.invalidRequiredVersion; const details = Constants.informationMessage.seeDetailsRequirementsPage; window .showErrorMessage(`${message}. ${details}`, Constants.informationMessage.detailsButton) .then((answer) => { if (answer) { commands.executeCommand('azureBlockchainService.showRequirementsPage'); } }); commands.executeCommand('azureBlockchainService.showRequirementsPage', true); } return valid; } /** * Function check only required apps: Node.js, npm, git * Show Requirements Page */ export async function checkRequiredApps(): Promise<boolean> { return checkApps(...requiredApps); } export async function checkApps(...apps: RequiredApps[]): Promise<boolean> { const valid = await checkAppsSilent(...apps); if (!valid) { Telemetry.sendEvent(Constants.telemetryEvents.failedToCheckRequiredApps); const message = Constants.errorMessageStrings.RequiredAppsAreNotInstalled; const details = Constants.informationMessage.seeDetailsRequirementsPage; window.showErrorMessage(`${message}. ${details}`); commands.executeCommand('azureBlockchainService.showRequirementsPage'); } return valid; } export async function checkAppsSilent(...apps: RequiredApps[]): Promise<boolean> { const versions = await getExactlyVersions(...apps); const invalid = versions .filter((version) => apps.includes(version.app as RequiredApps)) .some((version) => !version.isValid); return !invalid; } export async function checkHdWalletProviderVersion(): Promise<boolean> { const installedVersion = await getHdWalletProviderVersion(); if (!installedVersion) { return false; } else { const requiredVersion = Constants.requiredVersions[RequiredApps.hdwalletProvider]; if (typeof requiredVersion === 'string') { return isValid(installedVersion, requiredVersion); } else { return isValid( installedVersion, (requiredVersion as { max: string, min: string }).min, (requiredVersion as { max: string, min: string }).max, ); } } } export async function getHdWalletProviderVersion(): Promise<string> { try { const data = fs.readFileSync(path.join(getWorkspaceRoot()!, 'package-lock.json'), null) || fs.readFileSync(path.join(getWorkspaceRoot()!, 'package.json'), null); const packagesData = JSON.parse(data.toString()); return packagesData.dependencies[RequiredApps.hdwalletProvider] ? packagesData.dependencies[RequiredApps.hdwalletProvider].version || packagesData.dependencies[RequiredApps.hdwalletProvider] : ''; } catch (error) { Telemetry.sendException(error); return ''; } } export async function getAllVersions(): Promise<IRequiredVersion[]> { return getExactlyVersions(...requiredApps, ...auxiliaryApps); } export async function getExactlyVersions(...apps: RequiredApps[]): Promise<IRequiredVersion[]> { Output.outputLine('', `Get version for required apps: ${apps.join(',')}`); if (apps.includes(RequiredApps.node)) { currentState.node = currentState.node || await createRequiredVersion(RequiredApps.node, getNodeVersion); } if (apps.includes(RequiredApps.npm)) { currentState.npm = currentState.npm || await createRequiredVersion(RequiredApps.npm, getNpmVersion); } if (apps.includes(RequiredApps.git)) { currentState.git = currentState.git || await createRequiredVersion(RequiredApps.git, getGitVersion); } if (apps.includes(RequiredApps.truffle)) { currentState.truffle = currentState.truffle || await createRequiredVersion(RequiredApps.truffle, getTruffleVersion); } if (apps.includes(RequiredApps.ganache)) { currentState.ganache = currentState.ganache || await createRequiredVersion(RequiredApps.ganache, getGanacheVersion); } return Object.values(currentState); } export async function getNodeVersion(): Promise<string> { return getVersion(RequiredApps.node, '--version', /v(\d+.\d+.\d+)/); } export async function getNpmVersion(): Promise<string> { return getVersion(RequiredApps.npm, '--version', /(\d+.\d+.\d+)/); } export async function getGitVersion(): Promise<string> { return getVersion(RequiredApps.git, '--version', / (\d+.\d+.\d+)/); } export async function getPythonVersion(): Promise<string> { return getVersion(RequiredApps.python, '--version', / (\d+.\d+.\d+)/); } export async function getTruffleVersion(): Promise<string> { const requiredVersion = Constants.requiredVersions[RequiredApps.truffle]; const minRequiredVersion = typeof requiredVersion === 'string' ? requiredVersion : requiredVersion.min; const majorVersion = minRequiredVersion.split('.')[0]; const localVersion = (await tryExecuteCommand(getWorkspaceRoot(true), `npm list --depth 0 truffle@${majorVersion}`)) .cmdOutput .match(/truffle@(\d+.\d+.\d+)/); return (localVersion && localVersion[1]) || getVersion(RequiredApps.truffle, 'version', /(?<=Truffle v)(\d+.\d+.\d+)/); } export async function getGanacheVersion(): Promise<string> { const requiredVersion = Constants.requiredVersions[RequiredApps.ganache]; const minRequiredVersion = typeof requiredVersion === 'string' ? requiredVersion : requiredVersion.min; const majorVersion = minRequiredVersion.split('.')[0]; const localVersion = (await tryExecuteCommand( getWorkspaceRoot(true), `npm list --depth 0 ganache-cli@${majorVersion}`, )) .cmdOutput .match(/ganache-cli@(\d+.\d+.\d+)/); return (localVersion && localVersion[1]) || getVersion(RequiredApps.ganache, '--version', /v(\d+.\d+.\d+)/); } export async function installNpm(): Promise<void> { try { await installUsingNpm(RequiredApps.npm, Constants.requiredVersions[RequiredApps.npm]); } catch (error) { Telemetry.sendException(error); Output.outputLine(Constants.outputChannel.requirements, error.message); } currentState.npm = await createRequiredVersion(RequiredApps.npm, getNpmVersion); } export async function installTruffle(scope?: Scope): Promise<void> { try { await installUsingNpm(RequiredApps.truffle, Constants.requiredVersions[RequiredApps.truffle], scope); } catch (error) { Telemetry.sendException(error); Output.outputLine(Constants.outputChannel.requirements, error.message); } currentState.truffle = await createRequiredVersion( RequiredApps.truffle, getTruffleVersion, ); } export async function installGanache(scope?: Scope): Promise<void> { try { await installUsingNpm(RequiredApps.ganache, Constants.requiredVersions[RequiredApps.ganache], scope); } catch (error) { Telemetry.sendException(error); Output.outputLine(Constants.outputChannel.requirements, error.message); } currentState.ganache = await createRequiredVersion( RequiredApps.ganache, getGanacheVersion, ); } export async function installTruffleHdWalletProvider(): Promise<void> { try { await installUsingNpm( RequiredApps.hdwalletProvider, Constants.requiredVersions[RequiredApps.hdwalletProvider], Scope.locally, ); const truffleConfigPath = await TruffleConfiguration.getTruffleConfigUri(); const config = new TruffleConfiguration.TruffleConfig(truffleConfigPath); await config.importPackage(Constants.truffleConfigRequireNames.hdwalletProvider, RequiredApps.hdwalletProvider); } catch (error) { Telemetry.sendException(error); } } export async function isHdWalletProviderRequired(): Promise<boolean> { try { const truffleConfigPath = TruffleConfiguration.getTruffleConfigUri(); const config = new TruffleConfiguration.TruffleConfig(truffleConfigPath); return config.isHdWalletProviderDeclared(); } catch (error) { Telemetry.sendException(error); Output.outputLine(Constants.outputChannel.requirements, error.message); } return false; } export async function isDefaultProject(): Promise<boolean> { try { // File might not exist in some truffle-box const data = await fs.readFile(path.join(getWorkspaceRoot()!, 'package.json'), 'utf-8'); const packagesData = JSON.parse(data); return packagesData.name === 'blockchain-ethereum-template'; } catch (error) { Telemetry.sendException(error); Output.outputLine(Constants.outputChannel.requirements, error.message); } return false; } async function createRequiredVersion( appName: string, versionFunc: () => Promise<string>, ): Promise<IRequiredVersion> { const version = await versionFunc(); const requiredVersion = Constants.requiredVersions[appName]; const minRequiredVersion = typeof requiredVersion === 'string' ? requiredVersion : requiredVersion.min; const maxRequiredVersion = typeof requiredVersion === 'string' ? '' : requiredVersion.max; const isValidApp = isValid(version, minRequiredVersion, maxRequiredVersion); return { app: appName, isValid: isValidApp, requiredVersion, version, }; } async function installUsingNpm( packageName: string, packageVersion: string | { min: string, max: string }, scope?: Scope, ): Promise<void> { const versionString = typeof packageVersion === 'string' ? `^${packageVersion}` : `>=${packageVersion.min} <${packageVersion.max}`; const workspaceRoot = getWorkspaceRoot(true); if (workspaceRoot === undefined && scope === Scope.locally) { const error = new Error(Constants.errorMessageStrings.WorkspaceShouldBeOpened); Telemetry.sendException(error); throw error; } await window.withProgress({ location: ProgressLocation.Window, title: `Installing ${packageName}`, }, async () => { await executeCommand(workspaceRoot, 'npm', 'i', scope ? '' : '-g', ` ${packageName}@"${versionString}"`); }); } async function getVersion(program: string, command: string, matcher: RegExp): Promise<string> { try { const result = await tryExecuteCommand(undefined, program, command); if (result.code === 0) { const output = result.cmdOutput || result.cmdOutputIncludingStderr; const installedVersion = output.match(matcher); const version = semver.clean(installedVersion ? installedVersion[1] : ''); return version || ''; } } catch (error) { Telemetry.sendException(error); } return ''; } }
the_stack
import {useIsFocused} from '@react-navigation/native'; import React, { useCallback, useLayoutEffect, useState, useMemo, useRef, } from 'react'; import {StyleSheet, LayoutRectangle, Text, View} from 'react-native'; import { Canvas, CanvasRenderingContext2D, Image, ImageUtil, media, MobileModel, Module, Tensor, torch, torchvision, } from 'react-native-pytorch-core'; import {Animator} from '../utils/Animator'; import { PTLColors as colors, PTLFontSizes as fontsizes, } from '../components/UISettings'; import ModelPreloader from '../components/ModelPreloader'; import {MultiClassClassificationModels} from '../Models'; // Must be specified as hex to be parsed correctly. const COLOR_CANVAS_BACKGROUND = colors.light; const COLOR_TRAIL_STROKE = colors.accent2; let mnistModel: Module | null = null; async function getModel() { if (mnistModel != null) { return mnistModel; } const filePath = await MobileModel.download( MultiClassClassificationModels[0].model, ); mnistModel = await torch.jit._loadForMobile(filePath); return mnistModel; } const HEX_RGB_RE = /^#?([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i; function hexRgbToBytes(hexRgb: string): number[] { const match = HEX_RGB_RE.exec(hexRgb); if (!match) { throw `Invalid color hex string: ${hexRgb}`; } return match.slice(1).map(s => parseInt(s, 16)); } /* Tensor input is expected to have shape CHW and range [0, 1]. This is a vectorized version of looping over every pixel: d0 = colorCartesianDistance(pixelColor, backgroundColor) d1 = colorCartesianDistance(pixelColor, foregroundColor) value = d0 / (d0 + d1) Where, for 3-channel data: colorCartesianDistance = function([r0, g0, b0], [r1, g1, b1]) => ( Math.sqrt((r0 - r1) * (r0 - r1) + (g0 - g1) * (g0 - g1) + (b0 - b1) * (b0 - b1)) ); */ function maximizeContrast( tensor: Tensor, backgroundTensor: Tensor, foregroundTensor: Tensor, ): Tensor { const d0Diff = tensor.sub(backgroundTensor); const d0 = d0Diff.mul(d0Diff).sum(0, {keepdim: true}).sqrt(); const d1Diff = tensor.sub(foregroundTensor); const d1 = d1Diff.mul(d1Diff).sum(0, {keepdim: true}).sqrt(); return d0.div(d0.add(d1)); } /** * The React hook provides MNIST model inference on an input image. */ function useMNISTModel() { const processImage = useCallback(async (image: Image) => { // Runs model inference on input image const blob = media.toBlob(image); const imageTensor = torch.fromBlob(blob, [ image.getHeight(), image.getWidth(), 3, ]); const grayscale = torchvision.transforms.grayscale(); const resize = torchvision.transforms.resize(28); const normalize = torchvision.transforms.normalize([0.1307], [0.3081]); const bgColorGrayscale = grayscale( torch .tensor([[hexRgbToBytes(COLOR_CANVAS_BACKGROUND)]]) .permute([2, 0, 1]) .div(255), ); const fgColorGrayscale = grayscale( torch .tensor([[hexRgbToBytes(COLOR_TRAIL_STROKE)]]) .permute([2, 0, 1]) .div(255), ); let tensor = imageTensor.permute([2, 0, 1]).div(255); tensor = resize(tensor); tensor = grayscale(tensor); tensor = maximizeContrast(tensor, bgColorGrayscale, fgColorGrayscale); tensor = normalize(tensor); tensor = tensor.unsqueeze(0); const model = await getModel(); const output = await model.forward<Tensor, Tensor[]>(tensor); const softmax = output[0].squeeze(0).softmax(-1); const sortedScore: number[][] = []; softmax .data() .forEach((score: number, index: number) => sortedScore.push([score, index]), ); return sortedScore.sort((a, b) => b[0] - a[0]); }, []); return { processImage, }; } /** * The React hook provides MNIST inference using the image data extracted from * a canvas. * * @param layout The layout for the canvas */ function useMNISTCanvasInference(layout: LayoutRectangle | null) { const [result, setResult] = useState<number[][]>(); const isRunningInferenceRef = useRef(false); const {processImage} = useMNISTModel(); const classify = useCallback( async (ctx: CanvasRenderingContext2D, forceRun: boolean = false) => { // Return immediately if layout is not available or if an inference is // already in-flight. Ignore in-flight inference if `forceRun` is set to // true. if (layout === null || (isRunningInferenceRef.current && !forceRun)) { return; } // Set inference running if not force run if (!forceRun) { isRunningInferenceRef.current = true; } // Get canvas size const size = [layout.width, layout.height]; // Get image data center crop const imageData = await ctx.getImageData( 0, size[1] / 2 - size[0] / 2, size[0], size[0], ); // Convert image data to image. const image: Image = await ImageUtil.fromImageData(imageData); // Release image data to free memory imageData.release(); // Run MNIST inference on the image const result = await processImage(image); // Release image to free memory image.release(); // Set result state to force re-render of component that uses this hook setResult(result); // If not force run, add a little timeout to give device time to process // other things if (!forceRun) { setTimeout(() => { isRunningInferenceRef.current = false; }, 100); } }, [isRunningInferenceRef, layout, processImage, setResult], ); return { result, classify, }; } // This is an example of creating a simple animation using Animator utility class export default function MNISTExample() { const isFocused = useIsFocused(); // `layout` contains canvas properties like width and height const [layout, setLayout] = useState<LayoutRectangle | null>(null); // `ctx` is drawing context to draw shapes const [ctx, setCtx] = useState<CanvasRenderingContext2D>(); const [drawing, setDrawing] = useState<number[][]>([]); const {classify, result} = useMNISTCanvasInference(layout); // useRef is the React way of storing mutable variable const drawingRef = useRef(false); const showingRef = useRef(false); const trailRef = useRef<number[][]>([]); // handlers for touch events const handleMove = useCallback( async event => { const position = [ event.nativeEvent.locationX, event.nativeEvent.locationY, ]; const trail = trailRef.current; if (trail.length > 0) { const lastPosition: number[] = trail[trail.length - 1]; const dx = position[0] - lastPosition[0]; const dy = position[1] - lastPosition[1]; // add a point to trail if distance from last point > 5 if (dx * dx + dy * dy > 25) { trail.push(position); } } else { trail.push(position); } }, [trailRef], ); const handleStart = useCallback(() => { drawingRef.current = true; showingRef.current = false; }, [drawingRef]); const handleEnd = useCallback(() => { if (ctx != null) { drawingRef.current = false; // Wait for the canvas drawing to center on screen first before classifying setTimeout(async () => { await classify(ctx, true); showingRef.current = true; }, 100); } }, [ctx, classify]); // Instantiate an Animator. `useMemo` is used for React optimization. const animator = useMemo(() => new Animator(), []); const numToLabel = (num: number, choice: number = 0) => { const labels = [ ['zero', '零', '🄌', 'cero'], ['one', '一', '➊', 'uno'], ['two', '二', '➋', 'dos'], ['three', '三', '➌', 'tres'], ['four', '四', '➍', 'cuatro'], ['five', '五', '➎', 'cinco'], ['six', '六', '➏', 'seis'], ['seven', '七', '➐', 'siete'], ['eight', '八', '➑', 'ocho'], ['nine', '九', '➒', 'nueve'], ]; const index = Math.max(0, Math.min(9, num || 0)); return labels[index][choice]; }; const theme = colors.accent2; useLayoutEffect(() => { if (ctx != null) { animator.start(() => { const trail = trailRef.current; if (trail != null) { // Here we use `layout` to get the canvas size const size = [layout?.width || 0, layout?.height || 0]; // clear previous canvas drawing and then redraw // fill background by drawing a rect ctx.fillStyle = theme; ctx.fillRect(0, 0, size[0], size[1]); ctx.fillStyle = COLOR_CANVAS_BACKGROUND; ctx.fillRect(0, size[1] / 2 - size[0] / 2, size[0], size[0]); // Draw text when there's no drawing if (result && trail.length === 0) { } // Draw border ctx.strokeStyle = theme; const borderWidth = Math.max(0, 15 - trail.length); ctx.lineWidth = borderWidth; ctx.strokeRect( borderWidth / 2, size[1] / 2 - size[0] / 2, size[0] - borderWidth, size[0], ); // Draw the trails ctx.lineWidth = 32; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.miterLimit = 1; ctx.strokeStyle = COLOR_TRAIL_STROKE; if (drawing.length > 0) { // ctx.strokeStyle = colors.accent2; ctx.beginPath(); ctx.moveTo(drawing[0][0], drawing[0][1]); for (let i = 1; i < drawing.length; i++) { ctx.lineTo(drawing[i][0], drawing[i][1]); } } if (trail.length > 0) { // ctx.strokeStyle = colors.dark; ctx.beginPath(); ctx.moveTo(trail[0][0], trail[0][1]); for (let i = 1; i < trail.length; i++) { ctx.lineTo(trail[i][0], trail[i][1]); } } ctx.stroke(); // When the drawing is done if (!drawingRef.current && trail.length > 0) { // Before classifying, move the drawing to the center for better accuracy if (!showingRef.current) { const centroid = trail.reduce( (prev, curr) => [prev[0] + curr[0], prev[1] + curr[1]], [0, 0], ); centroid[0] /= trail.length; centroid[1] /= trail.length; const offset = [ centroid[0] - size[0] / 2, centroid[1] - size[1] / 2, ]; if ( Math.max(Math.abs(offset[0]), Math.abs(offset[1])) > size[0] / 8 ) { for (let i = 0; i < trail.length; i++) { trail[i][0] -= offset[0]; trail[i][1] -= offset[1]; } } setDrawing(trail.slice()); // After classifying, remove the trail with a little animation } else { // Shrink trail in a logarithmic size each animation frame trail.splice(0, Math.max(Math.round(Math.log(trail.length)), 1)); } } // Need to include this at the end, for now. ctx.invalidate(); } }); } // Stop animator when exiting (unmount) return () => animator.stop(); }, [ animator, ctx, drawingRef, showingRef, layout, trailRef, result, drawing, ]); // update only when layout or context changes if (!isFocused) { return null; } return ( <ModelPreloader modelInfos={MultiClassClassificationModels}> <Canvas style={StyleSheet.absoluteFill} onContext2D={setCtx} onLayout={event => { const {layout} = event.nativeEvent; setLayout(layout); }} onTouchMove={handleMove} onTouchStart={handleStart} onTouchEnd={handleEnd} /> <View style={styles.instruction}> <Text style={styles.title}>Write a number</Text> </View> <View style={[styles.resultView]} pointerEvents="none"> <Text style={[styles.label]}> {result ? `${numToLabel(result[0][1], 2)} it looks like ${numToLabel( result[0][1], 0, )}` : ''} </Text> <Text style={[styles.label, styles.secondary]}> {result ? `${numToLabel(result[1][1], 2)} it can be ${numToLabel( result[1][1], 0, )} too` : ''} </Text> </View> </ModelPreloader> ); } const styles = StyleSheet.create({ resultView: { position: 'absolute', bottom: 0, flexDirection: 'column', padding: 15, }, resultHidden: { opacity: 0, }, result: { fontSize: 100, color: '#4f25c6', }, instruction: { alignSelf: 'flex-start', flexDirection: 'column', padding: 15, }, title: { fontSize: fontsizes.h1, fontWeight: 'bold', color: colors.dark, }, label: { fontSize: fontsizes.h3, color: colors.white, }, secondary: { color: '#ffffff99', }, });
the_stack
import { IView, IViewSize } from 'vs/base/browser/ui/grid/grid'; import { IconLabel } from 'vs/base/browser/ui/iconLabel/iconLabel'; import { Toggle } from 'vs/base/browser/ui/toggle/toggle'; import { CompareResult } from 'vs/base/common/arrays'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { noBreakWhitespace } from 'vs/base/common/strings'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { Range } from 'vs/editor/common/core/range'; import { IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model'; import { localize } from 'vs/nls'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { DEFAULT_EDITOR_MAX_DIMENSIONS, DEFAULT_EDITOR_MIN_DIMENSIONS } from 'vs/workbench/browser/parts/editor/editor'; import { autorun, derivedObservable, IObservable, ITransaction, ObservableValue, transaction } from 'vs/workbench/contrib/audioCues/browser/observable'; import { MergeEditorModel } from 'vs/workbench/contrib/mergeEditor/browser/model/mergeEditorModel'; import { InputState } from 'vs/workbench/contrib/mergeEditor/browser/model/modifiedBaseRange'; import { LineRange } from 'vs/workbench/contrib/mergeEditor/browser/model/lineRange'; import { applyObservableDecorations, join, h, setStyle } from 'vs/workbench/contrib/mergeEditor/browser/utils'; import { EditorGutter, IGutterItemInfo, IGutterItemView } from './editorGutter'; export interface ICodeEditorViewOptions { readonly: boolean; } abstract class CodeEditorView extends Disposable { private readonly _model = new ObservableValue<undefined | MergeEditorModel>(undefined, 'model'); readonly model: IObservable<undefined | MergeEditorModel> = this._model; protected readonly htmlElements = h('div.code-view', [ h('div.title', { $: 'title' }), h('div.container', [ h('div.gutter', { $: 'gutterDiv' }), h('div', { $: 'editor' }), ]), ]); private readonly _onDidViewChange = new Emitter<IViewSize | undefined>(); public readonly view: IView = { element: this.htmlElements.root, minimumWidth: DEFAULT_EDITOR_MIN_DIMENSIONS.width, maximumWidth: DEFAULT_EDITOR_MAX_DIMENSIONS.width, minimumHeight: DEFAULT_EDITOR_MIN_DIMENSIONS.height, maximumHeight: DEFAULT_EDITOR_MAX_DIMENSIONS.height, onDidChange: this._onDidViewChange.event, layout: (width: number, height: number, top: number, left: number) => { setStyle(this.htmlElements.root, { width, height, top, left }); this.editor.layout({ width: width - this.htmlElements.gutterDiv.clientWidth, height: height - this.htmlElements.title.clientHeight, }); } // preferredWidth?: number | undefined; // preferredHeight?: number | undefined; // priority?: LayoutPriority | undefined; // snap?: boolean | undefined; }; private readonly _title = new IconLabel(this.htmlElements.title, { supportIcons: true }); private readonly _detail = new IconLabel(this.htmlElements.title, { supportIcons: true }); public readonly editor = this.instantiationService.createInstance( CodeEditorWidget, this.htmlElements.editor, { minimap: { enabled: false }, readOnly: this._options.readonly, glyphMargin: false, lineNumbersMinChars: 2, }, { contributions: [] } ); constructor( private readonly _options: ICodeEditorViewOptions, @IInstantiationService private readonly instantiationService: IInstantiationService ) { super(); } public setModel( model: MergeEditorModel, textModel: ITextModel, title: string, description: string | undefined, detail: string | undefined ): void { this.editor.setModel(textModel); this._title.setLabel(title, description); this._detail.setLabel('', detail); this._model.set(model, undefined); } } export class InputCodeEditorView extends CodeEditorView { private readonly decorations = derivedObservable('decorations', reader => { const model = this.model.read(reader); if (!model) { return []; } const result = new Array<IModelDeltaDecoration>(); for (const m of model.modifiedBaseRanges.read(reader)) { const range = m.getInputRange(this.inputNumber); if (!range.isEmpty) { result.push({ range: new Range(range.startLineNumber, 1, range.endLineNumberExclusive - 1, 1), options: { isWholeLine: true, className: `merge-editor-modified-base-range-input${this.inputNumber}`, description: 'Base Range Projection' } }); const inputDiffs = m.getInputDiffs(this.inputNumber); for (const diff of inputDiffs) { if (diff.rangeMappings) { for (const d of diff.rangeMappings) { result.push({ range: d.outputRange, options: { className: `merge-editor-diff-input${this.inputNumber}`, description: 'Base Range Projection' } }); } } } } } return result; }); constructor( public readonly inputNumber: 1 | 2, options: ICodeEditorViewOptions, @IInstantiationService instantiationService: IInstantiationService ) { super(options, instantiationService); this._register(applyObservableDecorations(this.editor, this.decorations)); this._register( new EditorGutter(this.editor, this.htmlElements.gutterDiv, { getIntersectingGutterItems: (range, reader) => { const model = this.model.read(reader); if (!model) { return []; } return model.modifiedBaseRanges.read(reader) .filter((r) => r.getInputDiffs(this.inputNumber).length > 0) .map<ModifiedBaseRangeGutterItemInfo>((baseRange, idx) => ({ id: idx.toString(), additionalHeightInPx: 0, offsetInPx: 0, range: baseRange.getInputRange(this.inputNumber), enabled: model.isUpToDate, toggleState: derivedObservable('toggle', (reader) => model .getState(baseRange) .read(reader) .getInput(this.inputNumber) ), setState: (value, tx) => model.setState( baseRange, model .getState(baseRange) .get() .withInputValue(this.inputNumber, value), tx ), })); }, createView: (item, target) => new MergeConflictGutterItemView(item, target), }) ); } } interface ModifiedBaseRangeGutterItemInfo extends IGutterItemInfo { enabled: IObservable<boolean>; toggleState: IObservable<InputState>; setState(value: boolean, tx: ITransaction): void; } class MergeConflictGutterItemView extends Disposable implements IGutterItemView<ModifiedBaseRangeGutterItemInfo> { private readonly item = new ObservableValue<ModifiedBaseRangeGutterItemInfo | undefined>(undefined, 'item'); constructor(item: ModifiedBaseRangeGutterItemInfo, private readonly target: HTMLElement) { super(); this.item.set(item, undefined); target.classList.add('merge-accept-gutter-marker'); const checkBox = new Toggle({ isChecked: false, title: localize('acceptMerge', "Accept Merge"), icon: Codicon.check }); checkBox.domNode.classList.add('accept-conflict-group'); this._register( autorun((reader) => { const item = this.item.read(reader)!; const value = item.toggleState.read(reader); const iconMap: Record<InputState, { icon: Codicon | undefined; checked: boolean }> = { [InputState.excluded]: { icon: undefined, checked: false }, [InputState.conflicting]: { icon: Codicon.circleFilled, checked: false }, [InputState.first]: { icon: Codicon.check, checked: true }, [InputState.second]: { icon: Codicon.checkAll, checked: true }, }; checkBox.setIcon(iconMap[value].icon); checkBox.checked = iconMap[value].checked; if (!item.enabled.read(reader)) { checkBox.disable(); } else { checkBox.enable(); } }, 'Update Toggle State') ); this._register(checkBox.onChange(() => { transaction(tx => { this.item.get()!.setState(checkBox.checked, tx); }); })); target.appendChild(h('div.background', [noBreakWhitespace]).root); target.appendChild( h('div.checkbox', [h('div.checkbox-background', [checkBox.domNode])]).root ); } layout(top: number, height: number, viewTop: number, viewHeight: number): void { this.target.classList.remove('multi-line'); this.target.classList.remove('single-line'); this.target.classList.add(height > 30 ? 'multi-line' : 'single-line'); } update(baseRange: ModifiedBaseRangeGutterItemInfo): void { this.item.set(baseRange, undefined); } } export class ResultCodeEditorView extends CodeEditorView { private readonly decorations = derivedObservable('decorations', reader => { const model = this.model.read(reader); if (!model) { return []; } const result = new Array<IModelDeltaDecoration>(); const baseRangeWithStoreAndTouchingDiffs = join( model.modifiedBaseRanges.read(reader), model.resultDiffs.read(reader), (baseRange, diff) => baseRange.baseRange.touches(diff.inputRange) ? CompareResult.neitherLessOrGreaterThan : LineRange.compareByStart( baseRange.baseRange, diff.inputRange ) ); for (const m of baseRangeWithStoreAndTouchingDiffs) { for (const r of m.rights) { const range = r.outputRange; const state = m.left ? model.getState(m.left).read(reader) : undefined; if (!range.isEmpty) { result.push({ range: new Range(range.startLineNumber, 1, range.endLineNumberExclusive - 1, 1), options: { isWholeLine: true, // TODO className: (() => { if (state) { if (state.input1 && !state.input2) { return 'merge-editor-modified-base-range-input1'; } if (state.input2 && !state.input1) { return 'merge-editor-modified-base-range-input2'; } if (state.input1 && state.input2) { return 'merge-editor-modified-base-range-combination'; } } return 'merge-editor-modified-base-range'; })(), description: 'Result Diff' } }); } } } return result; }); constructor( options: ICodeEditorViewOptions, @IInstantiationService instantiationService: IInstantiationService ) { super(options, instantiationService); this._register(applyObservableDecorations(this.editor, this.decorations)); } }
the_stack
import { AbstractCrdt, Doc, ApplyResult } from "./AbstractCrdt"; import { deserialize, selfOrRegister, selfOrRegisterValue } from "./utils"; import { SerializedList, SerializedCrdtWithId, Op, CreateListOp, OpType, } from "./live"; import { makePosition, compare } from "./position"; type LiveListItem = [crdt: AbstractCrdt, position: string]; /** * The LiveList class represents an ordered collection of items that is synchorinized across clients. */ export class LiveList<T> extends AbstractCrdt { // TODO: Naive array at first, find a better data structure. Maybe an Order statistics tree? #items: Array<LiveListItem> = []; constructor(items: T[] = []) { super(); let position = undefined; for (let i = 0; i < items.length; i++) { const newPosition = makePosition(position); const item = selfOrRegister(items[i]); this.#items.push([item, newPosition]); position = newPosition; } } /** * INTERNAL */ static _deserialize( [id, item]: [id: string, item: SerializedList], parentToChildren: Map<string, SerializedCrdtWithId[]>, doc: Doc ) { const list = new LiveList([]); list._attach(id, doc); const children = parentToChildren.get(id); if (children == null) { return list; } for (const entry of children) { const child = deserialize(entry, parentToChildren, doc); child._setParentLink(list, entry[1].parentKey!); list.#items.push([child, entry[1].parentKey!]); list.#items.sort((itemA, itemB) => compare(itemA[1], itemB[1])); } return list; } /** * INTERNAL */ _serialize(parentId?: string, parentKey?: string): Op[] { if (this._id == null) { throw new Error("Cannot serialize item is not attached"); } if (parentId == null || parentKey == null) { throw new Error( "Cannot serialize list if parentId or parentKey is undefined" ); } const ops = []; const op: CreateListOp = { id: this._id, type: OpType.CreateList, parentId, parentKey, }; ops.push(op); for (const [value, key] of this.#items) { ops.push(...value._serialize(this._id, key)); } return ops; } /** * INTERNAL */ _attach(id: string, doc: Doc) { super._attach(id, doc); for (const [item, position] of this.#items) { item._attach(doc.generateId(), doc); } } /** * INTERNAL */ _detach() { super._detach(); for (const [value] of this.#items) { value._detach(); } } /** * INTERNAL */ _attachChild(id: string, key: string, child: AbstractCrdt): ApplyResult { if (this._doc == null) { throw new Error("Can't attach child if doc is not present"); } child._attach(id, this._doc); child._setParentLink(this, key); const index = this.#items.findIndex((entry) => entry[1] === key); // Assign a temporary position until we get the fix from the backend if (index !== -1) { this.#items[index][1] = makePosition(key, this.#items[index + 1]?.[1]); } this.#items.push([child, key]); this.#items.sort((itemA, itemB) => compare(itemA[1], itemB[1])); return { reverse: [{ type: OpType.DeleteCrdt, id }], modified: this }; } /** * INTERNAL */ _detachChild(child: AbstractCrdt) { const indexToDelete = this.#items.findIndex((item) => item[0] === child); this.#items.splice(indexToDelete, 1); if (child) { child._detach(); } } /** * INTERNAL */ _setChildKey(key: string, child: AbstractCrdt) { child._setParentLink(this, key); const index = this.#items.findIndex((entry) => entry[1] === key); // Assign a temporary position until we get the fix from the backend if (index !== -1) { this.#items[index][1] = makePosition(key, this.#items[index + 1]?.[1]); } const item = this.#items.find((item) => item[0] === child); if (item) { item[1] = key; } this.#items.sort((itemA, itemB) => compare(itemA[1], itemB[1])); } /** * INTERNAL */ _apply(op: Op) { return super._apply(op); } /** * Returns the number of elements. */ get length() { return this.#items.length; } /** * Adds one element to the end of the LiveList. * @param element The element to add to the end of the LiveList. */ push(element: T) { return this.insert(element, this.length); } /** * Inserts one element at a specified index. * @param element The element to insert. * @param index The index at which you want to insert the element. */ insert(element: T, index: number) { if (index < 0 || index > this.#items.length) { throw new Error( `Cannot delete list item at index "${index}". index should be between 0 and ${ this.#items.length }` ); } let before = this.#items[index - 1] ? this.#items[index - 1][1] : undefined; let after = this.#items[index] ? this.#items[index][1] : undefined; const position = makePosition(before, after); const value = selfOrRegister(element); value._setParentLink(this, position); this.#items.push([value, position]); this.#items.sort((itemA, itemB) => compare(itemA[1], itemB[1])); if (this._doc && this._id) { const id = this._doc.generateId(); value._attach(id, this._doc); this._doc.dispatch( value._serialize(this._id, position), [{ type: OpType.DeleteCrdt, id }], [this] ); } } /** * Move one element from one index to another. * @param index The index of the element to move * @param targetIndex The index where the element should be after moving. */ move(index: number, targetIndex: number) { if (targetIndex < 0) { throw new Error("targetIndex cannot be less than 0"); } if (targetIndex >= this.#items.length) { throw new Error( "targetIndex cannot be greater or equal than the list length" ); } if (index < 0) { throw new Error("index cannot be less than 0"); } if (index >= this.#items.length) { throw new Error("index cannot be greater or equal than the list length"); } let beforePosition = null; let afterPosition = null; if (index < targetIndex) { afterPosition = targetIndex === this.#items.length - 1 ? undefined : this.#items[targetIndex + 1][1]; beforePosition = this.#items[targetIndex][1]; } else { afterPosition = this.#items[targetIndex][1]; beforePosition = targetIndex === 0 ? undefined : this.#items[targetIndex - 1][1]; } const position = makePosition(beforePosition, afterPosition); const item = this.#items[index]; const previousPosition = item[1]; item[1] = position; item[0]._setParentLink(this, position); this.#items.sort((itemA, itemB) => compare(itemA[1], itemB[1])); if (this._doc && this._id) { this._doc.dispatch( [ { type: OpType.SetParentKey, id: item[0]._id!, parentKey: position, }, ], [ { type: OpType.SetParentKey, id: item[0]._id!, parentKey: previousPosition, }, ], [this] ); } } /** * Deletes an element at the specified index * @param index The index of the element to delete */ delete(index: number) { if (index < 0 || index >= this.#items.length) { throw new Error( `Cannot delete list item at index "${index}". index should be between 0 and ${ this.#items.length - 1 }` ); } const item = this.#items[index]; item[0]._detach(); this.#items.splice(index, 1); if (this._doc) { const childRecordId = item[0]._id; if (childRecordId) { this._doc.dispatch( [ { id: childRecordId, type: OpType.DeleteCrdt, }, ], item[0]._serialize(this._id!, item[1]), [this] ); } } } /** * Returns an Array of all the elements in the LiveList. */ toArray(): T[] { return this.#items.map((entry) => selfOrRegisterValue(entry[0])); } /** * Tests whether all elements pass the test implemented by the provided function. * @param predicate Function to test for each element, taking two arguments (the element and its index). * @returns true if the predicate function returns a truthy value for every element. Otherwise, false. */ every(predicate: (value: T, index: number) => unknown): boolean { return this.toArray().every(predicate); } /** * Creates an array with all elements that pass the test implemented by the provided function. * @param predicate Function to test each element of the LiveList. Return a value that coerces to true to keep the element, or to false otherwise. * @returns An array with the elements that pass the test. */ filter(predicate: (value: T, index: number) => unknown): T[] { return this.toArray().filter(predicate); } /** * Returns the first element that satisfies the provided testing function. * @param predicate Function to execute on each value. * @returns The value of the first element in the LiveList that satisfies the provided testing function. Otherwise, undefined is returned. */ find(predicate: (value: T, index: number) => unknown): T | undefined { return this.toArray().find(predicate); } /** * Returns the index of the first element in the LiveList that satisfies the provided testing function. * @param predicate Function to execute on each value until the function returns true, indicating that the satisfying element was found. * @returns The index of the first element in the LiveList that passes the test. Otherwise, -1. */ findIndex(predicate: (value: T, index: number) => unknown): number { return this.toArray().findIndex(predicate); } /** * Executes a provided function once for each element. * @param callbackfn Function to execute on each element. */ forEach(callbackfn: (value: T, index: number) => void): void { return this.toArray().forEach(callbackfn); } /** * Get the element at the specified index. * @param index The index on the element to get. * @returns The element at the specified index or undefined. */ get(index: number): T | undefined { if (index < 0 || index >= this.#items.length) { return undefined; } return selfOrRegisterValue(this.#items[index][0]); } /** * Returns the first index at which a given element can be found in the LiveList, or -1 if it is not present. * @param searchElement Element to locate. * @param fromIndex The index to start the search at. * @returns The first index of the element in the LiveList; -1 if not found. */ indexOf(searchElement: T, fromIndex?: number): number { return this.toArray().indexOf(searchElement, fromIndex); } /** * Returns the last index at which a given element can be found in the LiveList, or -1 if it is not present. The LiveLsit is searched backwards, starting at fromIndex. * @param searchElement Element to locate. * @param fromIndex The index at which to start searching backwards. * @returns */ lastIndexOf(searchElement: T, fromIndex?: number): number { return this.toArray().lastIndexOf(searchElement, fromIndex); } /** * Creates an array populated with the results of calling a provided function on every element. * @param callback Function that is called for every element. * @returns An array with each element being the result of the callback function. */ map<U>(callback: (value: T, index: number) => U): U[] { return this.#items.map((entry, i) => callback(selfOrRegisterValue(entry[0]), i) ); } /** * Tests whether at least one element in the LiveList passes the test implemented by the provided function. * @param predicate Function to test for each element. * @returns true if the callback function returns a truthy value for at least one element. Otherwise, false. */ some(predicate: (value: T, index: number) => unknown): boolean { return this.toArray().some(predicate); } [Symbol.iterator](): IterableIterator<T> { return new LiveListIterator(this.#items); } } class LiveListIterator<T> implements IterableIterator<T> { #innerIterator: IterableIterator<LiveListItem>; constructor(items: Array<LiveListItem>) { this.#innerIterator = items[Symbol.iterator](); } [Symbol.iterator](): IterableIterator<T> { return this; } next(): IteratorResult<T> { const result = this.#innerIterator.next(); if (result.done) { return { done: true, value: undefined, }; } return { value: selfOrRegisterValue(result.value[0]), }; } }
the_stack
import { getColorMode } from '../../colorMode' import { WalletInfo } from '../../events' import { replaceInTemplate } from '../../utils/replace-in-template' import { generateGUID } from '../../utils/generate-uuid' import { toastTemplates } from './toast-templates' export interface ToastAction { text: string actionText?: string actionCallback?(): Promise<void> } export interface ToastConfig { body: string timer?: number forceNew?: boolean state: 'prepare' | 'loading' | 'acknowledge' | 'finished' actions?: ToastAction[] walletInfo?: WalletInfo openWalletAction?(): Promise<void> } let document: Document if (typeof window !== 'undefined' && typeof window.document !== 'undefined') { document = window.document } const EXPAND_AFTER: number = 5 * 1000 let timeout: number | undefined let expandTimeout: number | undefined let globalToastConfig: ToastConfig | undefined const createActionItem = async (toastAction: ToastAction): Promise<HTMLElement> => { const { text, actionText, actionCallback } = toastAction const id = await generateGUID() const wrapper = document.createElement('div') wrapper.classList.add('beacon-toast__action__item') if (actionCallback) { wrapper.innerHTML = text.length > 0 ? `<p>${text}</p>` : `` wrapper.innerHTML += `<p><a id="${id}">${actionText}</a></p>` } else if (actionText) { wrapper.innerHTML = text.length > 0 ? `<p class="beacon-toast__action__item__subtitle">${text}</p>` : `` wrapper.innerHTML += `<p>${actionText}</p>` } else { wrapper.innerHTML = `<p>${text}</p>` } if (actionCallback) { wrapper.addEventListener('click', actionCallback) } return wrapper } const removeAllChildNodes = (parent: HTMLElement): void => { while (parent.firstChild) { parent.removeChild(parent.firstChild) } } const formatToastText = (html: string): string => { const walletIcon = globalToastConfig?.walletInfo?.icon const walletName = globalToastConfig?.walletInfo?.name let wallet = '' if (walletIcon) { wallet += `<span class="beacon-toast__wallet__container"><img class="beacon-toast__content__img" src="${walletIcon}">` } if (walletName) { wallet += `<strong>${walletName}</strong></span>` } else { wallet += `Wallet` } return replaceInTemplate(html, 'wallet', wallet) } const getToastHTML = ( config: ToastConfig ): { style: string html: string } => { const text = config.body let html = replaceInTemplate(toastTemplates.default.html, 'text', text) html = formatToastText(html) return { style: toastTemplates.default.css, html } } /** * Close a toast */ const closeToast = (): Promise<void> => new Promise((resolve) => { globalToastConfig = undefined const wrapper = document.getElementById('beacon-toast-wrapper') if (!wrapper) { return resolve() } const elm = wrapper.shadowRoot?.getElementById('beacon-toast') if (elm) { const animationDuration = 300 if (timeout) { clearTimeout(timeout) timeout = undefined } elm.className = elm.className.replace('fadeIn', 'fadeOut') window.setTimeout(() => { const parent = wrapper.parentNode if (parent) { parent.removeChild(wrapper) } resolve() }, animationDuration) } else { resolve() } }) const registerClick = ( shadowRoot: ShadowRoot, id: string, callback: (el: HTMLElement) => Promise<void> ): HTMLElement | null => { const button = shadowRoot.getElementById(id) if (button) { button.addEventListener('click', async () => { await callback(button) }) } return button } const showElement = (shadowRoot: ShadowRoot, id: string): void => { const el = shadowRoot.getElementById(id) if (el) { el.classList.remove('hide') el.classList.add('show') } } const hideElement = (shadowRoot: ShadowRoot, id: string): void => { const el = shadowRoot.getElementById(id) if (el) { el.classList.add('hide') el.classList.remove('show') } } // const showLoader = (): void => { // showElement('beacon-toast-loader') // } const hideLoader = (shadowRoot: ShadowRoot): void => { hideElement(shadowRoot, 'beacon-toast-loader') showElement(shadowRoot, 'beacon-toast-loader-placeholder') } const showExpand = (shadowRoot: ShadowRoot): void => { showElement(shadowRoot, 'beacon-toast-button-expand') hideElement(shadowRoot, 'beacon-toast-button-close') } const showClose = (shadowRoot: ShadowRoot): void => { showElement(shadowRoot, 'beacon-toast-button-close') hideElement(shadowRoot, 'beacon-toast-button-expand') } const collapseList = (shadowRoot: ShadowRoot): void => { const expandButton = shadowRoot.getElementById('beacon-toast-button-expand') const list = shadowRoot.getElementById('beacon-toast-list') if (expandButton && list) { expandButton.classList.remove('beacon-toast__upside_down') list.classList.add('hide') list.classList.remove('show') } } const expandList = (shadowRoot: ShadowRoot): void => { const expandButton = shadowRoot.getElementById('beacon-toast-button-expand') const list = shadowRoot.getElementById('beacon-toast-list') if (expandButton && list) { expandButton.classList.add('beacon-toast__upside_down') list.classList.remove('hide') list.classList.add('show') } } const expandOrCollapseList = (shadowRoot: ShadowRoot): void => { const expandButton = shadowRoot.getElementById('beacon-toast-button-expand') const list = shadowRoot.getElementById('beacon-toast-list') if (expandButton && list) { if (expandButton.classList.contains('beacon-toast__upside_down')) { collapseList(shadowRoot) } else { expandList(shadowRoot) } } } const addActionsToToast = async ( shadowRoot: ShadowRoot, toastConfig: ToastConfig, list: HTMLElement ): Promise<void> => { const actions = toastConfig.actions if (actions && actions.length > 0) { const actionPromises = actions.map(async (action) => { // eslint-disable-next-line @typescript-eslint/unbound-method return createActionItem(action) }) const actionItems = await Promise.all(actionPromises) actionItems.forEach((item) => list.appendChild(item)) const poweredByBeacon = document.createElement('small') poweredByBeacon.classList.add('beacon-toast__powered') poweredByBeacon.innerHTML = toastTemplates.default.poweredByBeacon list.appendChild(poweredByBeacon) showExpand(shadowRoot) } else { showClose(shadowRoot) collapseList(shadowRoot) } } const createNewToast = async (toastConfig: ToastConfig): Promise<void> => { globalToastConfig = toastConfig const timer = toastConfig.timer const shadowRootEl = document.createElement('div') shadowRootEl.setAttribute('id', 'beacon-toast-wrapper') const shadowRoot = shadowRootEl.attachShadow({ mode: 'open' }) const wrapper = document.createElement('div') const { style, html } = getToastHTML(toastConfig) wrapper.innerHTML = html const styleEl = document.createElement('style') styleEl.textContent = style shadowRoot.appendChild(wrapper) shadowRoot.appendChild(styleEl) if (timer) { timeout = window.setTimeout(async () => { await closeToast() }, timer) } document.body.prepend(shadowRootEl) const colorMode = getColorMode() const elm = shadowRoot.getElementById(`beacon-toast`) if (elm) { elm.classList.add(`theme__${colorMode}`) } const list = shadowRoot.getElementById('beacon-toast-list') if (list) { await addActionsToToast(shadowRoot, toastConfig, list) } const openWalletButtonEl = shadowRoot.getElementById('beacon-open-wallet') if (openWalletButtonEl) { if (toastConfig.openWalletAction) { openWalletButtonEl.addEventListener('click', () => { if (toastConfig.openWalletAction) { toastConfig.openWalletAction() } }) } else { openWalletButtonEl.classList.add('hide') } } if (globalToastConfig.state === 'loading') { expandTimeout = window.setTimeout(async () => { const expandButton = shadowRoot.getElementById('beacon-toast-button-expand') if (expandButton && !expandButton.classList.contains('beacon-toast__upside_down')) { expandOrCollapseList(shadowRoot) } }, EXPAND_AFTER) } registerClick(shadowRoot, 'beacon-toast-button-done', async () => { await closeToast() }) const closeButton = registerClick(shadowRoot, 'beacon-toast-button-close', async () => { await closeToast() }) if (closeButton && globalToastConfig.state === 'loading') { closeButton.classList.add('hide') } registerClick(shadowRoot, 'beacon-toast-button-expand', async () => { expandOrCollapseList(shadowRoot) }) } const updateToast = async (toastConfig: ToastConfig): Promise<void> => { globalToastConfig = { ...globalToastConfig, ...toastConfig } const timer = toastConfig.timer const wrapper = document.getElementById('beacon-toast-wrapper') if (!wrapper) { return } const shadowRoot = wrapper.shadowRoot if (!shadowRoot) { return } const list = shadowRoot.getElementById('beacon-toast-list') if (list) { removeAllChildNodes(list) await addActionsToToast(shadowRoot, toastConfig, list) } if (globalToastConfig.state === 'loading') { expandTimeout = window.setTimeout(async () => { const expandButton = shadowRoot.getElementById('beacon-toast-button-expand') if (expandButton && !expandButton.classList.contains('beacon-toast__upside_down')) { expandOrCollapseList(shadowRoot) } }, EXPAND_AFTER) } const toastTextEl = shadowRoot.getElementById('beacon-text-content') if (toastTextEl) { toastTextEl.innerHTML = formatToastText(toastConfig.body) } const openWalletButtonEl = shadowRoot.getElementById('beacon-open-wallet') if (openWalletButtonEl) { if (toastConfig.openWalletAction) { openWalletButtonEl.classList.remove('hide') openWalletButtonEl.addEventListener('click', () => { if (toastConfig.openWalletAction) { toastConfig.openWalletAction() } }) } else { openWalletButtonEl.classList.add('hide') } } if (timer) { timeout = window.setTimeout(async () => { await closeToast() }, timer) } const doneButton = shadowRoot.getElementById('beacon-toast-button-done') if (doneButton) { doneButton.addEventListener('click', async () => { await closeToast() }) } } /** * Create a new toast * * @param toastConfig Configuration of the toast */ const openToast = async (toastConfig: ToastConfig): Promise<void> => { if (expandTimeout) { clearTimeout(expandTimeout) } const wrapper = document.getElementById('beacon-toast-wrapper') if (wrapper) { if (toastConfig.forceNew) { await closeToast() await createNewToast(toastConfig) } else { await updateToast(toastConfig) } } else { await createNewToast(toastConfig) } if (globalToastConfig && globalToastConfig.state === 'finished') { const shadowRoot = document.getElementById('beacon-toast-wrapper')?.shadowRoot if (shadowRoot) { hideLoader(shadowRoot) showClose(shadowRoot) expandList(shadowRoot) } } return } export { closeToast, openToast }
the_stack
import * as vd from "virtual-dom"; import { combineLatest as observableCombineLatest, concat as observableConcat, merge as observableMerge, empty as observableEmpty, of as observableOf, Observable, Scheduler, Subject, } from "rxjs"; import { auditTime, catchError, debounceTime, distinctUntilChanged, filter, map, publish, publishReplay, refCount, retry, share, skip, startWith, switchMap, take, takeUntil, withLatestFrom, } from "rxjs/operators"; import { Image } from "../../graph/Image"; import { Container } from "../../viewer/Container"; import { Navigator } from "../../viewer/Navigator"; import { GraphMode } from "../../graph/GraphMode"; import { NavigationEdgeStatus } from "../../graph/interfaces/NavigationEdgeStatus"; import { Sequence } from "../../graph/Sequence"; import { ViewportSize } from "../../render/interfaces/ViewportSize"; import { VirtualNodeHash } from "../../render/interfaces/VirtualNodeHash"; import { State } from "../../state/State"; import { SequenceConfiguration } from "../interfaces/SequenceConfiguration"; import { SequenceDOMRenderer } from "./SequenceDOMRenderer"; import { NavigationDirection } from "../../graph/edge/NavigationDirection"; import { Component } from "../Component"; import { ComponentEventType } from "../events/ComponentEventType"; import { ComponentPlayEvent } from "../events/ComponentPlayEvent"; import { ComponentHoverEvent } from "../events/ComponentHoverEvent"; import { ComponentName } from "../ComponentName"; /** * @class SequenceComponent * @classdesc Component showing navigation arrows for sequence directions * as well as playing button. Exposes an API to start and stop play. */ export class SequenceComponent extends Component<SequenceConfiguration> { /** @inheritdoc */ public static componentName: ComponentName = "sequence"; private _sequenceDOMRenderer: SequenceDOMRenderer; private _scheduler: Scheduler; private _hoveredIdSubject$: Subject<string>; private _hoveredId$: Observable<string>; private _containerWidth$: Subject<number>; constructor( name: string, container: Container, navigator: Navigator, renderer?: SequenceDOMRenderer, scheduler?: Scheduler) { super(name, container, navigator); this._sequenceDOMRenderer = !!renderer ? renderer : new SequenceDOMRenderer(container); this._scheduler = scheduler; this._containerWidth$ = new Subject<number>(); this._hoveredIdSubject$ = new Subject<string>(); this._hoveredId$ = this._hoveredIdSubject$.pipe(share()); this._navigator.playService.playing$.pipe( skip(1), withLatestFrom(this._configuration$)) .subscribe( ([playing, configuration]: [boolean, SequenceConfiguration]): void => { const type: ComponentEventType = "playing"; const event: ComponentPlayEvent = { playing, target: this, type, }; this.fire(type, event); if (playing === configuration.playing) { return; } if (playing) { this.play(); } else { this.stop(); } }); this._navigator.playService.direction$.pipe( skip(1), withLatestFrom(this._configuration$)) .subscribe( ([direction, configuration]: [NavigationDirection, SequenceConfiguration]): void => { if (direction !== configuration.direction) { this.configure({ direction }); } }); } public fire( type: "hover", event: ComponentHoverEvent) : void; public fire( type: "playing", event: ComponentPlayEvent) : void; public fire<T>( type: ComponentEventType, event: T) : void { super.fire(type, event); } public off( type: "hover", handler: (event: ComponentHoverEvent) => void) : void; public off( type: "playing", handler: (event: ComponentPlayEvent) => void) : void; public off<T>( type: ComponentEventType, handler: (event: T) => void) : void { super.off(type, handler); } /** * Fired when the hovered element of a component changes. * * @event hover * @example * ```js * // Initialize the viewer * var viewer = new Viewer({ // viewer options }); * var component = viewer.getComponent('<component-name>'); * // Set an event listener * component.on('hover', function() { * console.log("A hover event has occurred."); * }); * ``` */ public on( type: "hover", handler: (event: ComponentHoverEvent) => void) : void; /** * Event fired when playing starts or stops. * * @event playing * @example * ```js * // Initialize the viewer * var viewer = new Viewer({ // viewer options }); * var component = viewer.getComponent('<component-name>'); * // Set an event listener * component.on('playing', function() { * console.log("A playing event has occurred."); * }); * ``` */ public on( type: "playing", handler: (event: ComponentPlayEvent) => void) : void; public on<T>( type: ComponentEventType, handler: (event: T) => void) : void { super.on(type, handler); } /** * Start playing. * * @fires playing */ public play(): void { this.configure({ playing: true }); } /** * Stop playing. * * @fires playing */ public stop(): void { this.configure({ playing: false }); } protected _activate(): void { this._sequenceDOMRenderer.activate(); const edgeStatus$ = this._navigator.stateService.currentImage$.pipe( switchMap( (image: Image): Observable<NavigationEdgeStatus> => { return image.sequenceEdges$; }), publishReplay(1), refCount()); const sequence$ = this._navigator.stateService.currentImage$.pipe( distinctUntilChanged( undefined, (image: Image): string => { return image.sequenceId; }), switchMap( (image: Image): Observable<Sequence> => { return observableConcat( observableOf(null), this._navigator.graphService.cacheSequence$(image.sequenceId).pipe( retry(3), catchError( (e: Error): Observable<Sequence> => { console.error("Failed to cache sequence", e); return observableOf(null); }))); }), startWith(null), publishReplay(1), refCount()); const subs = this._subscriptions; subs.push(sequence$.subscribe()); const rendererId$ = this._sequenceDOMRenderer.index$.pipe( withLatestFrom(sequence$), map( ([index, sequence]: [number, Sequence]): string => { return sequence != null ? sequence.imageIds[index] : null; }), filter( (id: string): boolean => { return !!id; }), distinctUntilChanged(), publish(), refCount()); subs.push(observableMerge( rendererId$.pipe(debounceTime(100, this._scheduler)), rendererId$.pipe(auditTime(400, this._scheduler))).pipe( distinctUntilChanged(), switchMap( (id: string): Observable<Image> => { return this._navigator.moveTo$(id).pipe( catchError( (): Observable<Image> => { return observableEmpty(); })); })) .subscribe()); subs.push(this._sequenceDOMRenderer.changingPositionChanged$.pipe( filter( (changing: boolean): boolean => { return changing; })) .subscribe( (): void => { this._navigator.graphService.setGraphMode(GraphMode.Sequence); })); subs.push(this._sequenceDOMRenderer.changingPositionChanged$.pipe( filter( (changing: boolean): boolean => { return !changing; })) .subscribe( (): void => { this._navigator.graphService.setGraphMode(GraphMode.Spatial); })); this._navigator.graphService.graphMode$.pipe( switchMap( (mode: GraphMode): Observable<Image> => { return mode === GraphMode.Spatial ? this._navigator.stateService.currentImage$.pipe( take(2)) : observableEmpty(); }), filter( (image: Image): boolean => { return !image.spatialEdges.cached; }), switchMap( (image: Image): Observable<Image> => { return this._navigator.graphService.cacheImage$(image.id).pipe( catchError( (): Observable<Image> => { return observableEmpty(); })); })) .subscribe(); subs.push(this._sequenceDOMRenderer.changingPositionChanged$.pipe( filter( (changing: boolean): boolean => { return changing; })) .subscribe( (): void => { this._navigator.playService.stop(); })); subs.push(observableCombineLatest( this._navigator.graphService.graphMode$, this._sequenceDOMRenderer.changingPositionChanged$.pipe( startWith(false), distinctUntilChanged())).pipe( withLatestFrom(this._navigator.stateService.currentImage$), switchMap( ([[mode, changing], image]: [[GraphMode, boolean], Image]): Observable<Sequence> => { return changing && mode === GraphMode.Sequence ? this._navigator.graphService.cacheSequenceImages$(image.sequenceId, image.id).pipe( retry(3), catchError( (error: Error): Observable<Sequence> => { console.error("Failed to cache sequence images.", error); return observableEmpty(); })) : observableEmpty(); })) .subscribe()); const position$: Observable<{ index: number, max: number }> = sequence$.pipe( switchMap( (sequence: Sequence): Observable<{ index: number, max: number }> => { if (!sequence) { return observableOf({ index: null, max: null }); } let firstCurrentId: boolean = true; return this._sequenceDOMRenderer.changingPositionChanged$.pipe( startWith(false), distinctUntilChanged(), switchMap( (changingPosition: boolean): Observable<string> => { const skipCount: number = !changingPosition && firstCurrentId ? 0 : 1; firstCurrentId = false; return changingPosition ? rendererId$ : this._navigator.stateService.currentImage$.pipe( map( (image: Image): string => { return image.id; }), distinctUntilChanged(), skip(skipCount)); }), map( (imageId: string): { index: number, max: number } => { const index: number = sequence.imageIds.indexOf(imageId); if (index === -1) { return { index: null, max: null }; } return { index: index, max: sequence.imageIds.length - 1 }; })); })); const earth$ = this._navigator.stateService.state$.pipe( map( (state: State): boolean => { return state === State.Earth; }), distinctUntilChanged()); subs.push(observableCombineLatest( edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.pipe(startWith(this._sequenceDOMRenderer)), this._navigator.playService.speed$, position$, earth$).pipe( map( ( [edgeStatus, configuration, containerWidth, , speed, position, earth]: [ NavigationEdgeStatus, SequenceConfiguration, number, SequenceDOMRenderer, number, { index: number, max: number }, boolean, ]): VirtualNodeHash => { const vNode: vd.VNode = this._sequenceDOMRenderer .render( edgeStatus, configuration, containerWidth, speed, position.index, position.max, !earth, this, this._navigator); return { name: this._name, vNode: vNode }; })) .subscribe(this._container.domRenderer.render$)); subs.push(this._sequenceDOMRenderer.speed$ .subscribe( (speed: number): void => { this._navigator.playService.setSpeed(speed); })); subs.push(this._configuration$.pipe( map( (configuration: SequenceConfiguration): NavigationDirection => { return configuration.direction; }), distinctUntilChanged()) .subscribe( (direction: NavigationDirection): void => { this._navigator.playService.setDirection(direction); })); subs.push(observableCombineLatest( this._container.renderService.size$, this._configuration$.pipe( distinctUntilChanged( (value1: [number, number], value2: [number, number]): boolean => { return value1[0] === value2[0] && value1[1] === value2[1]; }, (configuration: SequenceConfiguration) => { return [configuration.minWidth, configuration.maxWidth]; }))).pipe( map( ([size, configuration]: [ViewportSize, SequenceConfiguration]): number => { return this._sequenceDOMRenderer.getContainerWidth( size, configuration); })) .subscribe(this._containerWidth$)); subs.push(this._configuration$.pipe( map( (configuration: SequenceConfiguration): boolean => { return configuration.playing; }), distinctUntilChanged()) .subscribe( (playing: boolean) => { if (playing) { this._navigator.playService.play(); } else { this._navigator.playService.stop(); } })); subs.push(this._sequenceDOMRenderer.mouseEnterDirection$.pipe( switchMap( (direction: NavigationDirection): Observable<string> => { const edgeTo$: Observable<string> = edgeStatus$.pipe( map( (edgeStatus: NavigationEdgeStatus): string => { for (let edge of edgeStatus.edges) { if (edge.data.direction === direction) { return edge.target; } } return null; }), takeUntil(this._sequenceDOMRenderer.mouseLeaveDirection$)); return observableConcat(edgeTo$, observableOf<string>(null)); }), distinctUntilChanged()) .subscribe(this._hoveredIdSubject$)); subs.push(this._hoveredId$ .subscribe( (id: string): void => { const type: ComponentEventType = "hover"; const event: ComponentHoverEvent = { id, target: this, type, } this.fire(type, event); })); } protected _deactivate(): void { this._subscriptions.unsubscribe(); this._sequenceDOMRenderer.deactivate(); } protected _getDefaultConfiguration(): SequenceConfiguration { return { direction: NavigationDirection.Next, maxWidth: 108, minWidth: 70, playing: false, visible: true, }; } }
the_stack
import { Component, Prop, Element, State, Event, EventEmitter, Method } from "@stencil/core"; enum Mode { Inactive = 1, CameraReady, Countdown, TakingPicture, CheckingPicture, Error, UserHappy, UserUnhappy } @Component({ tag: "smile-to-unlock", styleUrl: "smile-to-unlock.scss" }) export class SmileToUnlock { @Prop() apiKey: string; @Prop() apiUrl: string = "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize"; @State() state: Mode; @State() countdown: number; @State() happiness: number; @State() errorMessage: string; @Element() el: HTMLElement; @Event() userSmiled: EventEmitter; video: HTMLVideoElement; canvas: HTMLCanvasElement; @Method() start() { this.init(); this.startCamera(); this.show(); } @Method() end() { this.hide(); this.endCamera(); } hide() { this.el.style.display = "none"; } show() { this.el.style.display = "block"; } init() { this.state = Mode.Inactive; // This makes the overlay appear, once the video is setup the overlay with disappear this.video = this.el.querySelector("#video") as HTMLVideoElement; this.canvas = this.el.querySelector("canvas") as HTMLCanvasElement; } takeSnapshot() { let context = this.canvas.getContext("2d"), width = this.video.videoWidth, height = this.video.videoHeight; if (width && height) { // Setup a canvas with the same dimensions as the video. this.canvas.width = width; this.canvas.height = height; // Make a copy of the current frame in the video on the canvas. context.drawImage(this.video, 0, 0, width, height); this.calculateHappiness(); } } startCamera() { navigator.mediaDevices .getUserMedia({ video: true }) .then(stream => { this.video.src = window.URL.createObjectURL(stream); return this.video.play(); }) // Now the video is ready set this state so it's actually displayed .then(_ => (this.state = Mode.CameraReady)) .catch(err => { console.error(err); this.state = Mode.Error; this.errorMessage = "There was a problem starting your camera"; }); } endCamera() { this.video.pause(); this.video.src = ""; } startCountdown(event) { event.preventDefault(); this.state = Mode.Countdown; // This shows the numbers this.countdown = 3; // XXX: Move to setting const refreshId = setInterval(() => { this.countdown -= 1; if (this.countdown === 0) { clearInterval(refreshId); // Show the flash animation, this takes 0.5s this.state = Mode.TakingPicture; setTimeout(() => { // 0.25s into the Flash (at the white peak) take the snapshot this.takeSnapshot(); }, 250); } }, 1000); } getImageBlob(): Promise<Blob> { return new Promise(resolve => { this.canvas.toBlob(blob => resolve(blob)); }); } async calculateHappiness() { this.state = Mode.CheckingPicture; let blob = await this.getImageBlob(); let response = await fetch(this.apiUrl, { headers: { "Ocp-Apim-Subscription-Key": this.apiKey, "Content-Type": "application/octet-stream" }, method: "POST", body: blob }); let faces = await response.json(); if (faces.length > 0) { let face = faces[0]; this.happiness = face.scores.happiness; console.debug(this.happiness); this.state = this.isUserHappy ? Mode.UserHappy : Mode.UserUnhappy; } else { // Handle when no faces or error returned this.state = Mode.Error; this.errorMessage = "You don't seem to have a face? Try again!"; } } unlockContent() { // Don't hide yourself, let the outer component decide what to do. this.userSmiled.emit({ score: this.happiness }); } componentWillLoad() { if (!this.apiKey) { console.error("smile-to-unlock missing required attribute 'apiKey'"); return false; } } get percentHappy() { return Math.floor(this.happiness * 100); } get isUserHappy() { return this.happiness && this.happiness > 0.9; } get showInactive() { return this.state === Mode.Inactive; } get showFlash() { return this.state === Mode.TakingPicture; } get showCamera() { return ( this.state === Mode.Inactive || this.state === Mode.CameraReady || this.state === Mode.Countdown || this.state === Mode.TakingPicture || this.state === Mode.Error ); } get showPicture() { return ( this.state === Mode.CheckingPicture || this.state === Mode.UserHappy || this.state === Mode.UserUnhappy ); } get emotionalDescription() { if (this.happiness > 0.9) { return `(${this.percentHappy}% Happy) 😁 There you go, wasn't so hard was it?`; } else if (this.happiness > 0.6) { return `(${this.percentHappy}% Happy) 😀 Almost, just a little more…`; } else if (this.happiness > 0.5) { return `(${this.percentHappy}% Happy) 🙂 Getting there… show me those teeth!`; } else if (this.happiness > 0.3) { return `(${this.percentHappy}% Happy) 😐 Well… at least it's not a frown`; } else if (this.happiness > 0.2) { return `(${this.percentHappy}% Happy) 😕 Maybe if you think of something funny?`; } else if (this.happiness > 0.1) { return `(${this.percentHappy}% Happy) 🙁 It's not called 'frown to unlock'`; } else if (this.happiness > 0.05) { return `(${this.percentHappy}% Happy) ☹️ Do you even know what a smile is?`; } else { return `(${this.percentHappy}% Happy) 😭 Do you want a tissue?`; } } render() { return ( <div class="app"> {/*<!-- The controls and header -->*/} <div class="controls"> <div class="header"> <span class="promo"> <a target="_blank" href="https://smiletounlock.com/">Smile to Unlock</a> | <a target="_blank" href="http://bit.ly/emotive-api-stu">Powered by Azure</a> </span> <a onClick={this.end.bind(this)} class="icon" href="#"> <i class="material-icons">close</i> </a> </div> {(() => { switch (this.state) { case Mode.CameraReady: // This shows the instructions screen return ( <div class="message"> <span> Smile and then press </span> <span class="arrow-icon"> <i class="material-icons">arrow_forward</i> </span> <a href="#" class="icon" onClick={this.startCountdown.bind(this)} > <i class="material-icons">camera_alt</i> </a> </div> ); case Mode.Countdown: // This shows the countdown screen return [ <div class="message"> <span class="countdown">{this.countdown}</span> </div>, <div class="spacer">&nbsp;</div> ]; case Mode.CheckingPicture: // This shows the detecting message return ( <div class="message"> <span class="checking"> Detecting happiness <span class="spinner" /> </span> </div> ); case Mode.Error: // This shows the error message return ( <div class="message"> <span class="arrow-icon"> <i class="material-icons">error_outline</i> </span> <span class="error">&nbsp;{this.errorMessage}</span> <span class="arrow-icon"> <i class="material-icons">arrow_forward</i> </span> <a href="#" class="icon" onClick={this.startCountdown.bind(this)} > <i class="material-icons">camera_alt</i> </a> </div> ); case Mode.UserUnhappy: return ( <div class="message"> <span>{this.emotionalDescription}</span> <span class="arrow-icon"> <i class="material-icons">arrow_forward</i> </span> <a href="#" class="icon" onClick={this.startCountdown.bind(this)} > <i class="material-icons">camera_alt</i> </a> </div> ); case Mode.UserHappy: return ( <div class="message"> <span>{this.emotionalDescription}</span> <span class="arrow-icon"> <i class="material-icons">arrow_forward</i> </span> <a href="#" class="icon" onClick={this.unlockContent.bind(this)} > <i class="material-icons">lock_open</i> </a> </div> ); default: return; } })()} </div> <div class="overlay" style={{ display: this.showInactive ? "block" : "none" }} /> <div class="flash" style={{ display: this.showFlash ? "block" : "none" }} /> <div class="video-wrapper" style={{ display: this.showCamera ? "block" : "none" }} > <video id="video">Video stream not available.</video> </div> <div class="picture-wrapper" style={{ display: this.showPicture ? "block" : "none" }} > <canvas id="picture">&nbsp;</canvas> </div> </div> ); } }
the_stack
import React from 'react'; import {screen, render} from '@testing-library/react'; import {expectTypeOf} from 'expect-type'; import { composeHooks, createComponent, useForkRef, useLocalRef, ElementComponent, mergeProps, createHook, Model, BehaviorHook, } from '@workday/canvas-kit-react/common'; describe('createComponent', () => { it('should assign an element-base component as an ElementComponent', () => { const component = createComponent('div')({Component: (props: {foo: 'bar'}) => null}); expectTypeOf(component).toEqualTypeOf<ElementComponent<'div', {foo: 'bar'}>>(); }); it('should add sub-components to the signature', () => { const component = createComponent('div')({ Component: (props: {foo: 'bar'}) => null, subComponents: { Foo: 'bar', }, }); expectTypeOf(component).toEqualTypeOf<ElementComponent<'div', {foo: 'bar'}> & {Foo: string}>(); }); it('should assign ref and Element correctly for element components', () => { createComponent('div')({ Component: (props: {}, ref, Element) => { expectTypeOf(ref).toEqualTypeOf<React.Ref<HTMLDivElement>>(); expectTypeOf(Element).toEqualTypeOf<'div'>(); return null; }, }); }); it('should assign ref and Element correctly for createComponent components', () => { const component = createComponent('article')({Component: (props: {}) => null}); createComponent(component)({ Component: (props: {}, ref, Element) => { expectTypeOf(ref).toEqualTypeOf<React.Ref<HTMLElement>>(); expectTypeOf(Element).toEqualTypeOf<ElementComponent<'article', {}>>(); return null; }, }); }); it('should allow a valid ref when wrapping components', () => { const Component = createComponent('button')({Component: (props: {}) => null}); const ref: React.RefObject<HTMLButtonElement> = {current: null}; // No expectation, but the next line will fail if the ref signature isn't valid and it should be const temp = <Component ref={ref} />; }); it('create assign a displayName', () => { const Component = createComponent('div')({ displayName: 'Test', Component: () => null, }); expect(Component).toHaveProperty('displayName', 'Test'); }); it('should assign sub components', () => { const SubComponent = () => null; const Component = createComponent('div')({ Component: () => null, subComponents: { SubComponent, }, }); expect(Component).toHaveProperty('SubComponent', SubComponent); }); it('should forward the ref', () => { const ref = {current: null}; const Component = createComponent('div')({ displayName: 'Test', Component: (props, ref) => <div id="test" ref={ref} />, }); render(<Component ref={ref} />); expect(ref.current).toHaveAttribute('id', 'test'); }); it('should render whatever element is passed through the "as" prop', () => { const Component = createComponent('div')({ displayName: 'Test', Component: (props, ref, Element) => <Element data-testid="test" />, }); render(<Component as="button" />); expect(screen.getByTestId('test')).toHaveProperty('tagName', 'BUTTON'); }); }); describe('createHook', () => { const emptyModel = {state: {}, events: {}}; it('should return a BehaviorHook type', () => { const useMyHook = createHook((model: typeof emptyModel) => { return { foo: 'bar', }; }); expectTypeOf(useMyHook).toEqualTypeOf<BehaviorHook<typeof emptyModel, {foo: string}>>(); }); it('should return props that are merged together correctly when no ref is given', () => { const hook = createHook((model: any) => ({foo: 'bar'})); const props = hook(emptyModel, {bar: 'baz'}); expectTypeOf(props).toEqualTypeOf<{foo: string} & {bar: string}>(); expect(props).toEqual({foo: 'bar', bar: 'baz'}); }); it('should return props that are merged together correctly when a ref is given', () => { const divElement = document.createElement('div'); const hook = createHook((model: any) => ({foo: 'bar'})); const props = hook(emptyModel, {bar: 'baz'}, {current: divElement}); expectTypeOf(props).toEqualTypeOf< {foo: string} & {bar: string} & {ref: React.Ref<HTMLDivElement>} >(); expect(props).toEqual({foo: 'bar', bar: 'baz', ref: {current: divElement}}); }); it('should return the ref if the hook provides a ref and the component does not', () => { const ref = {current: 'foo'}; const hook = createHook((model: any) => ({ref})); const props = hook(emptyModel, {}, undefined); expect(props).toHaveProperty('ref', ref); }); it('should return the ref if the hook does not provide a ref and the component does', () => { const ref = {current: 'foo'}; const hook = createHook((model: any) => ({})); const props = hook(emptyModel, {}, ref); expect(props).toHaveProperty('ref', ref); }); it('should return the ref elemProps contains a ref and the hook and component do not', () => { const ref = {current: 'foo'}; const hook = createHook((model: any) => ({})); const props = hook(emptyModel, {ref}, null); expect(props).toHaveProperty('ref', ref); }); it('should not return the a ref prop if not ref was defined', () => { const hook = createHook((model: any) => ({})); const props = hook(emptyModel, {}, null); expect(props).not.toHaveProperty('ref'); }); it('should merge provided props over hook props', () => { const hook = createHook((model: any) => ({foo: 'bar'})); const props = hook(emptyModel, {foo: 'baz'}); expect(props).toEqual({foo: 'baz'}); }); }); describe('useForkRef', () => { it('should set the current value of the second ref if the first ref is undefined', () => { const ref1 = undefined; const ref2 = {current: null}; const ref = useForkRef(ref1, ref2); ref('bar'); expect(ref2).toHaveProperty('current', 'bar'); }); it('should set the current value of the first ref if the second ref is undefined', () => { const ref1 = {current: null}; const ref2 = undefined; const ref = useForkRef(ref1, ref2); ref('bar'); expect(ref1).toHaveProperty('current', 'bar'); }); it('should set the current value of both refs if both refs are RefObjects', () => { const ref1 = {current: null}; const ref2 = {current: null}; const ref = useForkRef(ref1, ref2); ref('bar'); expect(ref1).toHaveProperty('current', 'bar'); expect(ref2).toHaveProperty('current', 'bar'); }); it('should call the ref function of the second ref if the first ref is undefined', () => { const ref1 = undefined; const ref2 = jest.fn(); const ref = useForkRef(ref1, ref2); ref('bar'); expect(ref2).toHaveBeenCalledWith('bar'); }); it('should call the ref function of the first ref if the second ref is undefined', () => { const ref1 = jest.fn(); const ref2 = undefined; const ref = useForkRef(ref1, ref2); ref('bar'); expect(ref1).toHaveBeenCalledWith('bar'); }); it('should call the ref function of both refs if both refs are ref functions', () => { const ref1 = jest.fn(); const ref2 = jest.fn(); const ref = useForkRef(ref1, ref2); ref('bar'); expect(ref1).toHaveBeenCalledWith('bar'); expect(ref2).toHaveBeenCalledWith('bar'); }); }); describe('useLocalRef', () => { it('should return a localRef and an elementRef', () => { let localRefTest, elementRefTest; const CustomComponent = React.forwardRef<HTMLDivElement>((_, ref) => { const {localRef, elementRef} = useLocalRef(ref); localRefTest = localRef; elementRefTest = elementRef; return <div ref={ref} />; }); render(<CustomComponent />); expect(localRefTest).toHaveProperty('current'); expect(elementRefTest).toEqual(expect.any(Function)); }); }); describe('composeHooks', () => { let spy1, spy2; const myModel = {state: {first: 'first', second: 'second'}, events: {}}; const hook1 = createHook((model: typeof myModel) => { return { id: 'hook1', hook1: 'hook1', first: model.state.first, onClick: spy1, }; }); const hook2 = createHook((model: typeof myModel) => { return { id: 'hook2', hook2: 'hook2', second: model.state.second, onClick: spy2, }; }); beforeEach(() => { spy1 = jest.fn(); spy2 = jest.fn(); }); it('should merge properties from both hooks', () => { const props = composeHooks(hook1, hook2)(myModel, {}, null); expect(props).toHaveProperty('hook1', 'hook1'); expect(props).toHaveProperty('hook2', 'hook2'); }); it('should overwrite props of the first hook with props from the second hook', () => { const props = composeHooks(hook1, hook2)(myModel, {}, null); expect(props).toHaveProperty('id', 'hook2'); }); it('should overwrite hook props with props passed in', () => { const props = composeHooks(hook1, hook2)(myModel, {id: 'foo'}, null); expect(props).toHaveProperty('id', 'foo'); }); it('should set props that are derived from the model on both hooks', () => { const props = composeHooks(hook1, hook2)(myModel, {}, null); expect(props).toHaveProperty('first', 'first'); expect(props).toHaveProperty('second', 'second'); }); it('should call hook both callbacks', () => { const props = composeHooks(hook1, hook2)(myModel, {}, null) as {onClick: Function}; props.onClick({event: 'foo'}); expect(spy1).toHaveBeenCalled(); expect(spy1).toHaveBeenCalledWith({event: 'foo'}); expect(spy2).toHaveBeenCalled(); expect(spy2).toHaveBeenCalledWith({event: 'foo'}); }); it('should call both hook callbacks and passed in callback', () => { const spy3 = jest.fn(); const props = composeHooks(hook1, hook2)(myModel, {onClick: spy3}, null) as {onClick: Function}; props.onClick({event: 'foo'}); expect(spy1).toHaveBeenCalled(); expect(spy1).toHaveBeenCalledWith({event: 'foo'}); expect(spy2).toHaveBeenCalled(); expect(spy2).toHaveBeenCalledWith({event: 'foo'}); expect(spy3).toHaveBeenCalled(); expect(spy3).toHaveBeenCalledWith({event: 'foo'}); }); it('should handle any number of hooks with the correct merging', () => { // This test is covering all previous tests, but with more hooks. // This test should only fail if the implementation doesn't handle more than 2 hooks const model = {state: {foo: 'bar'}, events: {}}; const hooks = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(number => (myModel, props) => mergeProps({id: number, foo: number, [`hook${number}`]: model.state.foo}, props) ); const props = composeHooks.apply(null, hooks as any)(myModel, {foo: 'baz'}, null); expect(props).toHaveProperty('id', 9); expect(props).toHaveProperty('hook1', 'bar'); expect(props).toHaveProperty('foo', 'baz'); }); it('should compose hooks where first hook has a ref', () => { const ref = {current: 'foo'}; const hook1 = createHook(() => { return {ref}; }); const hook2 = createHook(() => { return {}; }); const props = composeHooks(hook1, hook2)(myModel, {}); expect(props).toHaveProperty('ref', ref); }); it('should compose hooks where second hook has a ref', () => { const ref = {current: 'foo'}; const hook1 = createHook(() => { return {}; }); const hook2 = createHook(() => { return {ref}; }); const props = composeHooks(hook1, hook2)(myModel, {}); expect(props).toHaveProperty('ref', ref); }); it('should compose hooks where second hook has a ref', () => { const ref = {current: 'foo'}; const hook1 = createHook(() => { return {}; }); const hook2 = createHook(() => { return {}; }); const props = composeHooks(hook1, hook2)(myModel, {}, ref); expect(props).toHaveProperty('ref', ref); }); });
the_stack
import { ComparisonResult } from "../ComparisonResult"; import { ComparisonResultType } from "../ComparisonResult"; import { defaultLocalSymbolTable, makeReader, ReaderOctetBuffer } from "../Ion"; import { BinaryReader } from "../IonBinaryReader"; import { Reader } from "../IonReader"; import { BinarySpan } from "../IonSpan"; import { IonType } from "../IonType"; import { IonTypes } from "../IonTypes"; import { Writer } from "../IonWriter"; import { EventStreamError } from "./EventStreamError"; import { IonEvent, IonEventFactory, IonEventType } from "./IonEvent"; // constants to be used for EventStream error const READ = "READ"; const WRITE = "WRITE"; export class IonEventStream { events: IonEvent[]; private reader: Reader; private eventFactory: IonEventFactory; isEventStream: boolean; // whether the reader has an event stream as input constructor(reader: Reader) { this.events = []; this.reader = reader; this.eventFactory = new IonEventFactory(); this.isEventStream = false; this.generateStream(); } writeEventStream(writer: Writer) { writer.writeSymbol("$ion_event_stream"); for (let i: number = 0; i < this.events.length; i++) { this.events[i].write(writer); } } writeIon(writer: Writer) { try { let tempEvent: IonEvent; let isEmbedded = false; for (let indice: number = 0; indice < this.events.length; indice++) { tempEvent = this.events[indice]; if (tempEvent.fieldName !== null) { writer.writeFieldName(tempEvent.fieldName); } if ( (tempEvent.ionType == IonTypes.SEXP || tempEvent.ionType == IonTypes.LIST) && this.isEmbedded(tempEvent) ) { isEmbedded = true; } writer.setAnnotations(tempEvent.annotations); switch (tempEvent.eventType) { case IonEventType.SCALAR: if (tempEvent.ionValue == null) { writer.writeNull(tempEvent.ionType!); return; } if (isEmbedded) { writer.writeString(tempEvent.ionValue.toString()); break; } switch (tempEvent.ionType) { case IonTypes.BOOL: writer.writeBoolean(tempEvent.ionValue); break; case IonTypes.STRING: writer.writeString(tempEvent.ionValue); break; case IonTypes.SYMBOL: writer.writeSymbol(tempEvent.ionValue); break; case IonTypes.INT: writer.writeInt(tempEvent.ionValue); break; case IonTypes.DECIMAL: writer.writeDecimal(tempEvent.ionValue); break; case IonTypes.FLOAT: writer.writeFloat64(tempEvent.ionValue); break; case IonTypes.NULL: writer.writeNull(tempEvent.ionType); break; case IonTypes.TIMESTAMP: writer.writeTimestamp(tempEvent.ionValue); break; case IonTypes.CLOB: writer.writeClob(tempEvent.ionValue); break; case IonTypes.BLOB: writer.writeBlob(tempEvent.ionValue); break; default: throw new Error("unexpected type: " + tempEvent.ionType!.name); } break; case IonEventType.CONTAINER_START: writer.stepIn(tempEvent.ionType!); break; case IonEventType.CONTAINER_END: if (isEmbedded) { isEmbedded = false; } writer.stepOut(); break; case IonEventType.STREAM_END: break; case IonEventType.SYMBOL_TABLE: throw new Error("Symboltables unsupported."); default: throw new Error("Unexpected event type: " + tempEvent.eventType); } } writer.close(); } catch (error) { // This Error will be used by the test-driver to differentiate errors using error types. throw new EventStreamError( WRITE, error.message, this.events.length, this.events ); } } getEvents(): IonEvent[] { return this.events; } equals(expected: IonEventStream): boolean { return this.compare(expected).result == ComparisonResultType.EQUAL; } /** * compares eventstreams and generates comparison result */ compare(expected: IonEventStream): ComparisonResult { let actualIndex: number = 0; let expectedIndex: number = 0; if (this.events.length != expected.events.length) { return new ComparisonResult( ComparisonResultType.NOT_EQUAL, "The event streams have different lengths" ); } while ( actualIndex < this.events.length && expectedIndex < expected.events.length ) { const actualEvent = this.events[actualIndex]; const expectedEvent = expected.events[expectedIndex]; if (actualEvent.eventType === IonEventType.SYMBOL_TABLE) { actualIndex++; } if (expectedEvent.eventType === IonEventType.SYMBOL_TABLE) { expectedIndex++; } if ( actualEvent.eventType === IonEventType.SYMBOL_TABLE || expectedEvent.eventType === IonEventType.SYMBOL_TABLE ) { continue; } switch (actualEvent.eventType) { case IonEventType.SCALAR: { const eventResult = actualEvent.compare(expectedEvent); if (eventResult.result == ComparisonResultType.NOT_EQUAL) { eventResult.actualIndex = actualIndex; eventResult.expectedIndex = expectedIndex; return eventResult; } break; } case IonEventType.CONTAINER_START: { const eventResult = actualEvent.compare(expectedEvent); if (eventResult.result == ComparisonResultType.NOT_EQUAL) { actualIndex += eventResult.actualIndex; expectedIndex += eventResult.expectedIndex; eventResult.actualIndex = actualIndex; eventResult.expectedIndex = expectedIndex; return eventResult; } else { if ( actualEvent.ionValue !== null && expectedEvent.ionValue !== null ) { actualIndex = actualIndex + actualEvent.ionValue.length; expectedIndex = expectedIndex + expectedEvent.ionValue.length; } } break; } case IonEventType.CONTAINER_END: case IonEventType.STREAM_END: { // no op break; } default: { throw new Error("Unexpected event type: " + actualEvent.eventType); } } actualIndex++; expectedIndex++; } return new ComparisonResult(ComparisonResultType.EQUAL); } isEmbedded(event: IonEvent): boolean { if (event.annotations[0] === "embedded_documents") { return true; } return false; } private generateStream(): void { try { let tid: IonType | null = this.reader.next(); if ( tid === IonTypes.SYMBOL && this.reader.stringValue() === "$ion_event_stream" ) { this.marshalStream(); this.isEventStream = true; return; } const currentContainer: IonEvent[] = []; const currentContainerIndex: number[] = []; while (true) { if (this.reader.isNull()) { this.events.push( this.eventFactory.makeEvent( IonEventType.SCALAR, tid!, this.reader.fieldName(), this.reader.depth(), this.reader.annotations(), true, this.reader.value() ) ); } else { switch (tid) { case IonTypes.LIST: case IonTypes.SEXP: case IonTypes.STRUCT: { const containerEvent = this.eventFactory.makeEvent( IonEventType.CONTAINER_START, tid, this.reader.fieldName(), this.reader.depth(), this.reader.annotations(), false, null ); this.events.push(containerEvent); currentContainer.push(containerEvent); currentContainerIndex.push(this.events.length); this.reader.stepIn(); break; } case null: { if (this.reader.depth() === 0) { this.events.push( this.eventFactory.makeEvent( IonEventType.STREAM_END, IonTypes.NULL, null, this.reader.depth(), [], false, undefined ) ); return; } else { this.reader.stepOut(); this.endContainer( currentContainer.pop()!, currentContainerIndex.pop()! ); } break; } default: { this.events.push( this.eventFactory.makeEvent( IonEventType.SCALAR, tid, this.reader.fieldName(), this.reader.depth(), this.reader.annotations(), false, this.reader.value() ) ); break; } } } tid = this.reader.next(); } } catch (error) { // This Error will be used by the test-driver to differentiate errors using error types. throw new EventStreamError( READ, error.message, this.events.length, this.events ); } } private endContainer(thisContainer: IonEvent, thisContainerIndex: number) { this.events.push( this.eventFactory.makeEvent( IonEventType.CONTAINER_END, thisContainer.ionType!, null, thisContainer.depth, [], false, null ) ); thisContainer.ionValue = this.events.slice( thisContainerIndex, this.events.length ); } // (event_type: EventType, ion_type: IonType, field_name: SymbolToken, annotations: list<SymbolToken>, value_text: string, value_binary: list<byte>, imports: list<ImportDescriptor>, depth: int) private marshalStream(): void { this.events = []; const currentContainer: IonEvent[] = []; const currentContainerIndex: number[] = []; for ( let tid: IonType | null = this.reader.next(); tid === IonTypes.STRUCT; tid = this.reader.next() ) { this.reader.stepIn(); const tempEvent: IonEvent = this.marshalEvent(); if (tempEvent.eventType === IonEventType.CONTAINER_START) { currentContainer.push(tempEvent); this.events.push(tempEvent); currentContainerIndex.push(this.events.length); } else if (tempEvent.eventType === IonEventType.CONTAINER_END) { this.endContainer( currentContainer.pop()!, currentContainerIndex.pop()! ); } else if ( tempEvent.eventType === IonEventType.SCALAR || tempEvent.eventType === IonEventType.STREAM_END ) { this.events.push(tempEvent); } else { throw new Error("Unexpected eventType: " + tempEvent.eventType); } this.reader.stepOut(); } } private marshalEvent(): IonEvent { const currentEvent = {}; for (let tid: IonType | null; (tid = this.reader.next()); ) { const fieldName = this.reader.fieldName(); if (fieldName && currentEvent[fieldName] !== undefined) { throw new Error("Repeated event field: " + fieldName); } switch (fieldName) { case "event_type": { currentEvent[fieldName] = this.reader.stringValue(); break; } case "ion_type": { currentEvent[fieldName] = this.parseIonType(); break; } case "field_name": { currentEvent[ fieldName ] = this.resolveFieldNameFromSerializedSymbolToken(); break; } case "annotations": { currentEvent[fieldName] = this.parseAnnotations(); break; } case "value_text": { let tempString: string = this.reader.stringValue()!; if (tempString.substr(0, 5) === "$ion_") { tempString = "$ion_user_value::" + tempString; } const tempReader: Reader = makeReader(tempString); tempReader.next(); const tempValue = tempReader.value(); currentEvent["isNull"] = tempReader.isNull(); currentEvent[fieldName] = tempValue; break; } case "value_binary": { currentEvent[fieldName] = this.parseBinaryValue(); break; } case "imports": { currentEvent[fieldName] = this.parseImports(); break; } case "depth": { currentEvent[fieldName] = this.reader.numberValue(); break; } default: throw new Error("Unexpected event field: " + fieldName); } } let eventType: IonEventType; switch (currentEvent["event_type"]) { case "CONTAINER_START": eventType = IonEventType.CONTAINER_START; break; case "STREAM_END": eventType = IonEventType.STREAM_END; break; case "CONTAINER_END": eventType = IonEventType.CONTAINER_END; break; case "SCALAR": eventType = IonEventType.SCALAR; break; case "SYMBOL_TABLE": throw new Error("Symbol tables unsupported"); } const fieldname = currentEvent["field_name"] !== undefined ? currentEvent["field_name"] : null; if (!currentEvent["annotations"]) { currentEvent["annotations"] = []; } const textEvent = this.eventFactory.makeEvent( eventType!, currentEvent["ion_type"], fieldname, currentEvent["depth"], currentEvent["annotations"], currentEvent["isNull"], currentEvent["value_text"] ); if (eventType! === IonEventType.SCALAR) { const binaryEvent = this.eventFactory.makeEvent( eventType, currentEvent["ion_type"], fieldname, currentEvent["depth"], currentEvent["annotations"], currentEvent["isNull"], currentEvent["value_binary"] ); if (!textEvent.equals(binaryEvent)) { throw new Error( `Text event ${currentEvent["value_text"]} does not equal binary event ${currentEvent["value_binary"]}` ); } } return textEvent; } private parseIonType(): IonType { const input: string = this.reader.stringValue()!.toLowerCase(); switch (input) { case "null": { return IonTypes.NULL; } case "bool": { return IonTypes.BOOL; } case "int": { return IonTypes.INT; } case "float": { return IonTypes.FLOAT; } case "decimal": { return IonTypes.DECIMAL; } case "timestamp": { return IonTypes.TIMESTAMP; } case "symbol": { return IonTypes.SYMBOL; } case "string": { return IonTypes.STRING; } case "clob": { return IonTypes.CLOB; } case "blob": { return IonTypes.BLOB; } case "list": { return IonTypes.LIST; } case "sexp": { return IonTypes.SEXP; } case "struct": { return IonTypes.STRUCT; } default: { throw new Error("i: " + input); } } } private parseAnnotations(): string[] { const annotations: string[] = []; if (this.reader.isNull()) { return annotations; } else { this.reader.stepIn(); for (let tid; (tid = this.reader.next()); ) { if (tid == IonTypes.STRUCT) { this.reader.stepIn(); const type = this.reader.next(); if (this.reader.fieldName() == "text" && type == IonTypes.STRING) { const text = this.reader.stringValue(); if (text !== null) { annotations.push(text!); } } else if ( this.reader.fieldName() == "importLocation" && type == IonTypes.INT ) { const symtab = defaultLocalSymbolTable(); const symbol = symtab.getSymbolText(this.reader.numberValue()!); if (symbol === undefined || symbol === null) { throw new Error( "Unresolvable symbol ID, symboltokens unsupported." ); } annotations.push(symbol); } this.reader.stepOut(); } } this.reader.stepOut(); return annotations; } } private parseBinaryValue(): any { // convert list of ints to array of bytes and pass the currentBuffer to a binary reader, generate value from factory. // start with a null check if (this.reader.isNull()) { return null; } const numBuffer: number[] = []; this.reader.stepIn(); let tid: IonType | null = this.reader.next(); while (tid) { numBuffer.push(this.reader.numberValue()!); tid = this.reader.next(); } this.reader.stepOut(); const bufArray = new Uint8Array(numBuffer as ReaderOctetBuffer); const tempReader: Reader = new BinaryReader(new BinarySpan(bufArray)); tempReader.next(); return tempReader.value(); } private parseImports(): any { // TODO needed for symboltoken support. return this.reader.value(); } /** Parse the field name (Symbol Token) into text/symbol * example: {event_type: SCALAR, ion_type: INT, field_name: {text:"foo"}, value_text: "1", value_binary: [0x21, 0x01], depth:1} * for more information: https://github.com/amzn/ion-test-driver#symboltoken-1 */ private resolveFieldNameFromSerializedSymbolToken(): string | null { if (this.reader.isNull()) { return null; } this.reader.stepIn(); const type = this.reader.next(); if (this.reader.fieldName() == "text" && type == IonTypes.STRING) { const text = this.reader.stringValue(); if (text !== null) { this.reader.stepOut(); return text; } } else if ( this.reader.fieldName() == "importLocation" && type == IonTypes.INT ) { const symtab = defaultLocalSymbolTable(); const symbol = symtab.getSymbolText(this.reader.numberValue()!); if (symbol === undefined || symbol === null) { throw new Error("Unresolvable symbol ID, symboltokens unsupported."); } this.reader.stepOut(); return symbol; } return null; } }
the_stack
import "mocha"; import * as expect from "expect"; import * as fs from "fs"; import * as path from "path"; import { MachineApi } from "../../../src/renderer/machines/wa-api"; import { importObject } from "../../import-object"; import { CambridgeZ88 } from "../../../src/renderer/machines/cz88/CambridgeZ88"; const buffer = fs.readFileSync( path.join(__dirname, "../../../build/cz88.wasm") ); let api: MachineApi; let machine: CambridgeZ88; /** * Random sequences used for testing */ const RANDOM_SEQ = [0xe2, 0xc5, 0x62]; describe("Cambridge Z88 - Memory write", function () { before(async () => { const wasm = await WebAssembly.instantiate(buffer, importObject); api = (wasm.instance.exports as unknown) as MachineApi; machine = new CambridgeZ88(api); }); beforeEach(() => { machine.turnOnMachine(); }); const addresses: number[] = [ 0x0000, 0x1234, 0x1fff, 0x2000, 0x2345, 0x2fff, 0x3000, 0x3456, 0x3fff, 0x4000, 0x5678, 0x5fff, 0x6000, 0x6789, 0x7fff, 0x8000, 0x89ab, 0x9fff, 0xa000, 0xbcde, 0xbfff, 0xc000, 0xcdef, 0xdfff, 0xe000, 0xef01, 0xffff, ]; addresses.forEach((addr) => { it(`ROM (${addr}) cannot be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0); }); }); addresses.forEach((addr) => { it(`RAMS turned on (${addr})`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xb0, 0x04); // Set COM.RAMS machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if (addr <= 0x1fff) { expect(value).toBe(0x23); } else { expect(value).toBe(0); } }); }); addresses.forEach((addr) => { it(`Internal RAM (${addr}) can be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xd1, 0x20); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if ((addr & 0xc000) === 0x4000) { // RAM area expect(value).toBe(0x23); } else { // ROM area expect(value).toBe(0); } }); }); addresses.forEach((addr) => { it(`Card 1 RAM (${addr}) can be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xd1, 0x40); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if ((addr & 0xc000) === 0x4000) { // RAM area expect(value).toBe(0x23); } else { // ROM area expect(value).toBe(0); } }); }); addresses.forEach((addr) => { it(`Card 2 RAM (${addr}) can be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xd2, 0x80); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if ((addr & 0xc000) === 0x8000) { // RAM area expect(value).toBe(0x23); } else { // ROM area expect(value).toBe(0); } }); }); addresses.forEach((addr) => { it(`Card 3 RAM (${addr}) can be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xd3, 0xc0); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if ((addr & 0xc000) === 0xc000) { // RAM area expect(value).toBe(0x23); } else { // ROM area expect(value).toBe(0); } }); }); addresses.forEach((addr) => { it(`Card 3 RAM in segment 2 (${addr}) can be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xd3, 0x80); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if ((addr & 0xc000) === 0xc000) { // RAM area expect(value).toBe(0x23); } else { // ROM area expect(value).toBe(0); } }); }); // addresses.forEach((addr) => { // it(`Card 3 EPROM (${addr}) cannot be written`, () => { // machine.reset(); // machine.api.setZ88RndSeed(0); // machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K // machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K // machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M // machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M // machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M // machine.api.setZ88Card3Rom(true); // Chip 4 is ROM // machine.api.writePortCz88(0xd3, 0xc0); // machine.api.testWriteCz88Memory(addr, 0x23); // const value = machine.api.testReadCz88Memory(addr); // expect(value).toBe(0); // }); // }); addresses.forEach((addr) => { it(`Multiple paged-in RAM (${addr}) can be written`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, 0x3f); // Slot 2 RAM 1M machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M machine.api.writePortCz88(0xd2, 0x80); machine.api.writePortCz88(0xd3, 0xc0); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); if ((addr & 0xc000) >= 0x8000) { // RAM area expect(value).toBe(0x23); } else { // ROM area expect(value).toBe(0); } }); }); const repeatingAddresses: number[] = [0x4000, 0x4567, 0x5f00]; const sizeMasks: number[] = [0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f]; sizeMasks.forEach((size) => { repeatingAddresses.forEach((addr) => { it(`Write/read repeats in internal RAM ${size}/(${addr})`, () => { machine.reset(); machine.api.setZ88RndSeed(0); machine.api.setZ88ChipMask(0, 0x1f); // Slot 0 ROM 512K machine.api.setZ88ChipMask(1, 0x1f); // Slot 1 RAM 512K machine.api.setZ88ChipMask(2, size); // Passed size machine.api.setZ88ChipMask(3, 0x3f); // Slot 3 RAM 1M machine.api.setZ88ChipMask(4, 0x3f); // Slot 4 RAM 1M // Even pages console.log("Start"); for (let i = 0x40; i < 0x80; i += size + 1) { machine.api.writePortCz88(0xd1, i); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0x23); for (let j = 0x40 + (size + 1); j < 0x80; j += size + 1) { machine.api.writePortCz88(0xd1, j); console.log(i, j); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0x23); for (let k = j + 2; k < j + size + 1; k += 2) { machine.api.writePortCz88(0xd1, k); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0x00); } } } // Odd pages for (let i = 0x41; i < 0x80; i += size + 1) { machine.api.writePortCz88(0xd1, i); machine.api.testWriteCz88Memory(addr, 0x23); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0x23); for (let j = 0x41 + (size + 1); j < 0x80; j += size + 1) { machine.api.writePortCz88(0xd1, j); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0x23); for (let k = j + 2; k < j + size + 1; k += 2) { machine.api.writePortCz88(0xd1, k); const value = machine.api.testReadCz88Memory(addr); expect(value).toBe(0x00); } } } }); }); }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { VirtualMachines } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DevTestLabsClient } from "../devTestLabsClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { LabVirtualMachine, VirtualMachinesListNextOptionalParams, VirtualMachinesListOptionalParams, VirtualMachinesListResponse, VirtualMachinesGetOptionalParams, VirtualMachinesGetResponse, VirtualMachinesCreateOrUpdateOptionalParams, VirtualMachinesCreateOrUpdateResponse, VirtualMachinesDeleteOptionalParams, LabVirtualMachineFragment, VirtualMachinesUpdateOptionalParams, VirtualMachinesUpdateResponse, DataDiskProperties, VirtualMachinesAddDataDiskOptionalParams, ApplyArtifactsRequest, VirtualMachinesApplyArtifactsOptionalParams, VirtualMachinesClaimOptionalParams, DetachDataDiskProperties, VirtualMachinesDetachDataDiskOptionalParams, VirtualMachinesGetRdpFileContentsOptionalParams, VirtualMachinesGetRdpFileContentsResponse, VirtualMachinesListApplicableSchedulesOptionalParams, VirtualMachinesListApplicableSchedulesResponse, VirtualMachinesRedeployOptionalParams, ResizeLabVirtualMachineProperties, VirtualMachinesResizeOptionalParams, VirtualMachinesRestartOptionalParams, VirtualMachinesStartOptionalParams, VirtualMachinesStopOptionalParams, VirtualMachinesTransferDisksOptionalParams, VirtualMachinesUnClaimOptionalParams, VirtualMachinesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing VirtualMachines operations. */ export class VirtualMachinesImpl implements VirtualMachines { private readonly client: DevTestLabsClient; /** * Initialize a new instance of the class VirtualMachines class. * @param client Reference to the service client */ constructor(client: DevTestLabsClient) { this.client = client; } /** * List virtual machines in a given lab. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param options The options parameters. */ public list( resourceGroupName: string, labName: string, options?: VirtualMachinesListOptionalParams ): PagedAsyncIterableIterator<LabVirtualMachine> { const iter = this.listPagingAll(resourceGroupName, labName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, labName, options); } }; } private async *listPagingPage( resourceGroupName: string, labName: string, options?: VirtualMachinesListOptionalParams ): AsyncIterableIterator<LabVirtualMachine[]> { let result = await this._list(resourceGroupName, labName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, labName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, labName: string, options?: VirtualMachinesListOptionalParams ): AsyncIterableIterator<LabVirtualMachine> { for await (const page of this.listPagingPage( resourceGroupName, labName, options )) { yield* page; } } /** * List virtual machines in a given lab. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param options The options parameters. */ private _list( resourceGroupName: string, labName: string, options?: VirtualMachinesListOptionalParams ): Promise<VirtualMachinesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, options }, listOperationSpec ); } /** * Get virtual machine. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ get( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesGetOptionalParams ): Promise<VirtualMachinesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, name, options }, getOperationSpec ); } /** * Create or replace an existing virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param labVirtualMachine A virtual machine. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, labName: string, name: string, labVirtualMachine: LabVirtualMachine, options?: VirtualMachinesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<VirtualMachinesCreateOrUpdateResponse>, VirtualMachinesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<VirtualMachinesCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, labVirtualMachine, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Create or replace an existing virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param labVirtualMachine A virtual machine. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, labName: string, name: string, labVirtualMachine: LabVirtualMachine, options?: VirtualMachinesCreateOrUpdateOptionalParams ): Promise<VirtualMachinesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, labName, name, labVirtualMachine, options ); return poller.pollUntilDone(); } /** * Delete virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Delete virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Allows modifying tags of virtual machines. All other properties will be ignored. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param labVirtualMachine A virtual machine. * @param options The options parameters. */ update( resourceGroupName: string, labName: string, name: string, labVirtualMachine: LabVirtualMachineFragment, options?: VirtualMachinesUpdateOptionalParams ): Promise<VirtualMachinesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, name, labVirtualMachine, options }, updateOperationSpec ); } /** * Attach a new or existing data disk to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param dataDiskProperties Request body for adding a new or existing data disk to a virtual machine. * @param options The options parameters. */ async beginAddDataDisk( resourceGroupName: string, labName: string, name: string, dataDiskProperties: DataDiskProperties, options?: VirtualMachinesAddDataDiskOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, dataDiskProperties, options }, addDataDiskOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Attach a new or existing data disk to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param dataDiskProperties Request body for adding a new or existing data disk to a virtual machine. * @param options The options parameters. */ async beginAddDataDiskAndWait( resourceGroupName: string, labName: string, name: string, dataDiskProperties: DataDiskProperties, options?: VirtualMachinesAddDataDiskOptionalParams ): Promise<void> { const poller = await this.beginAddDataDisk( resourceGroupName, labName, name, dataDiskProperties, options ); return poller.pollUntilDone(); } /** * Apply artifacts to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param applyArtifactsRequest Request body for applying artifacts to a virtual machine. * @param options The options parameters. */ async beginApplyArtifacts( resourceGroupName: string, labName: string, name: string, applyArtifactsRequest: ApplyArtifactsRequest, options?: VirtualMachinesApplyArtifactsOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, applyArtifactsRequest, options }, applyArtifactsOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Apply artifacts to virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param applyArtifactsRequest Request body for applying artifacts to a virtual machine. * @param options The options parameters. */ async beginApplyArtifactsAndWait( resourceGroupName: string, labName: string, name: string, applyArtifactsRequest: ApplyArtifactsRequest, options?: VirtualMachinesApplyArtifactsOptionalParams ): Promise<void> { const poller = await this.beginApplyArtifacts( resourceGroupName, labName, name, applyArtifactsRequest, options ); return poller.pollUntilDone(); } /** * Take ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginClaim( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesClaimOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, claimOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Take ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginClaimAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesClaimOptionalParams ): Promise<void> { const poller = await this.beginClaim( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Detach the specified disk from the virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param detachDataDiskProperties Request body for detaching data disk from a virtual machine. * @param options The options parameters. */ async beginDetachDataDisk( resourceGroupName: string, labName: string, name: string, detachDataDiskProperties: DetachDataDiskProperties, options?: VirtualMachinesDetachDataDiskOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, detachDataDiskProperties, options }, detachDataDiskOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Detach the specified disk from the virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param detachDataDiskProperties Request body for detaching data disk from a virtual machine. * @param options The options parameters. */ async beginDetachDataDiskAndWait( resourceGroupName: string, labName: string, name: string, detachDataDiskProperties: DetachDataDiskProperties, options?: VirtualMachinesDetachDataDiskOptionalParams ): Promise<void> { const poller = await this.beginDetachDataDisk( resourceGroupName, labName, name, detachDataDiskProperties, options ); return poller.pollUntilDone(); } /** * Gets a string that represents the contents of the RDP file for the virtual machine * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ getRdpFileContents( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesGetRdpFileContentsOptionalParams ): Promise<VirtualMachinesGetRdpFileContentsResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, name, options }, getRdpFileContentsOperationSpec ); } /** * Lists the applicable start/stop schedules, if any. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ listApplicableSchedules( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesListApplicableSchedulesOptionalParams ): Promise<VirtualMachinesListApplicableSchedulesResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, name, options }, listApplicableSchedulesOperationSpec ); } /** * Redeploy a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginRedeploy( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRedeployOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, redeployOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Redeploy a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginRedeployAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRedeployOptionalParams ): Promise<void> { const poller = await this.beginRedeploy( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Resize Virtual Machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param resizeLabVirtualMachineProperties Request body for resizing a virtual machine. * @param options The options parameters. */ async beginResize( resourceGroupName: string, labName: string, name: string, resizeLabVirtualMachineProperties: ResizeLabVirtualMachineProperties, options?: VirtualMachinesResizeOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, resizeLabVirtualMachineProperties, options }, resizeOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Resize Virtual Machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param resizeLabVirtualMachineProperties Request body for resizing a virtual machine. * @param options The options parameters. */ async beginResizeAndWait( resourceGroupName: string, labName: string, name: string, resizeLabVirtualMachineProperties: ResizeLabVirtualMachineProperties, options?: VirtualMachinesResizeOptionalParams ): Promise<void> { const poller = await this.beginResize( resourceGroupName, labName, name, resizeLabVirtualMachineProperties, options ); return poller.pollUntilDone(); } /** * Restart a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginRestart( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRestartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, restartOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Restart a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginRestartAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesRestartOptionalParams ): Promise<void> { const poller = await this.beginRestart( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Start a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginStart( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStartOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, startOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Start a virtual machine. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginStartAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStartOptionalParams ): Promise<void> { const poller = await this.beginStart( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Stop a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginStop( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStopOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, stopOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Stop a virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginStopAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesStopOptionalParams ): Promise<void> { const poller = await this.beginStop( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Transfers all data disks attached to the virtual machine to be owned by the current user. This * operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginTransferDisks( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesTransferDisksOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, transferDisksOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Transfers all data disks attached to the virtual machine to be owned by the current user. This * operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginTransferDisksAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesTransferDisksOptionalParams ): Promise<void> { const poller = await this.beginTransferDisks( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * Release ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginUnClaim( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesUnClaimOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; 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, { resourceGroupName, labName, name, options }, unClaimOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Release ownership of an existing virtual machine This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param name The name of the virtual machine. * @param options The options parameters. */ async beginUnClaimAndWait( resourceGroupName: string, labName: string, name: string, options?: VirtualMachinesUnClaimOptionalParams ): Promise<void> { const poller = await this.beginUnClaim( resourceGroupName, labName, name, options ); return poller.pollUntilDone(); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, labName: string, nextLink: string, options?: VirtualMachinesListNextOptionalParams ): Promise<VirtualMachinesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LabVirtualMachineList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LabVirtualMachine }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.LabVirtualMachine }, 201: { bodyMapper: Mappers.LabVirtualMachine }, 202: { bodyMapper: Mappers.LabVirtualMachine }, 204: { bodyMapper: Mappers.LabVirtualMachine }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.labVirtualMachine, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.LabVirtualMachine }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.labVirtualMachine1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const addDataDiskOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/addDataDisk", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.dataDiskProperties, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const applyArtifactsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/applyArtifacts", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.applyArtifactsRequest, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const claimOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/claim", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const detachDataDiskOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/detachDataDisk", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.detachDataDiskProperties, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getRdpFileContentsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/getRdpFileContents", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.RdpConnection }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const listApplicableSchedulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/listApplicableSchedules", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApplicableSchedule }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const redeployOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/redeploy", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const resizeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/resize", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.resizeLabVirtualMachineProperties, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const restartOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/restart", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const startOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/start", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const stopOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/stop", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const transferDisksOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/transferDisks", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const unClaimOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/virtualmachines/{name}/unClaim", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LabVirtualMachineList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labName ], headerParameters: [Parameters.accept], serializer };
the_stack
import ddb from "./aws/ddb/internal"; import CustomError from "./Error"; import utils from "./utils"; import {Condition, ConditionInitializer, BasicOperators} from "./Condition"; import {Model} from "./Model"; import {Item} from "./Item"; import {CallbackType, ObjectType, ItemArray, SortOrder} from "./General"; import {PopulateItems} from "./Populate"; import Internal from "./Internal"; import {InternalPropertiesClass} from "./InternalPropertiesClass"; const {internalProperties} = Internal.General; enum ItemRetrieverTypes { scan = "scan", query = "query" } interface ItemRetrieverTypeInformation { type: ItemRetrieverTypes; pastTense: string; } interface ItemRetrieverInternalProperties { internalSettings: { model: Model<Item>; typeInformation: ItemRetrieverTypeInformation; }; settings: { condition: Condition; sort?: SortOrder | `${SortOrder}`; parallel?: number; all?: { delay?: number; max?: number; }; attributes?: string[]; count?: number; consistent?: boolean; index?: string; startAt?: ObjectType; limit?: number; } } // ItemRetriever is used for both Scan and Query since a lot of the code is shared between the two // type ItemRetriever = BasicOperators; abstract class ItemRetriever extends InternalPropertiesClass<ItemRetrieverInternalProperties> { getRequest: (this: ItemRetriever) => Promise<any>; all: (this: ItemRetriever, delay?: number, max?: number) => ItemRetriever; limit: (this: ItemRetriever, value: number) => ItemRetriever; startAt: (this: ItemRetriever, value: ObjectType) => ItemRetriever; attributes: (this: ItemRetriever, value: string[]) => ItemRetriever; count: (this: ItemRetriever) => ItemRetriever; consistent: (this: ItemRetriever) => ItemRetriever; using: (this: ItemRetriever, value: string) => ItemRetriever; exec (this: ItemRetriever, callback?: any): any { let timesRequested = 0; const {model} = this.getInternalProperties(internalProperties).internalSettings; const table = model.getInternalProperties(internalProperties).table(); const prepareForReturn = async (result): Promise<any> => { if (Array.isArray(result)) { result = utils.merge_objects(...result); } if (this.getInternalProperties(internalProperties).settings.count) { return { "count": result.Count, [`${this.getInternalProperties(internalProperties).internalSettings.typeInformation.pastTense}Count`]: result[`${utils.capitalize_first_letter(this.getInternalProperties(internalProperties).internalSettings.typeInformation.pastTense)}Count`] }; } const array: any = (await Promise.all(result.Items.map(async (item) => await new model.Item(item, {"type": "fromDynamo"}).conformToSchema({"customTypesDynamo": true, "checkExpiredItem": true, "saveUnknown": true, "modifiers": ["get"], "type": "fromDynamo"})))).filter((a) => Boolean(a)); array.lastKey = result.LastEvaluatedKey ? Array.isArray(result.LastEvaluatedKey) ? result.LastEvaluatedKey.map((key) => model.Item.fromDynamo(key)) : model.Item.fromDynamo(result.LastEvaluatedKey) : undefined; array.count = result.Count; array[`${this.getInternalProperties(internalProperties).internalSettings.typeInformation.pastTense}Count`] = result[`${utils.capitalize_first_letter(this.getInternalProperties(internalProperties).internalSettings.typeInformation.pastTense)}Count`]; array[`times${utils.capitalize_first_letter(this.getInternalProperties(internalProperties).internalSettings.typeInformation.pastTense)}`] = timesRequested; array["populate"] = PopulateItems; array["toJSON"] = utils.dynamoose.itemToJSON; return array; }; const promise = table.getInternalProperties(internalProperties).pendingTaskPromise().then(() => this.getRequest()).then((request) => { const allRequest = (extraParameters = {}): any => { let promise: Promise<any> = ddb(table.getInternalProperties(internalProperties).instance, this.getInternalProperties(internalProperties).internalSettings.typeInformation.type as any, {...request, ...extraParameters}); timesRequested++; if (this.getInternalProperties(internalProperties).settings.all) { promise = promise.then(async (result) => { if (this.getInternalProperties(internalProperties).settings.all.delay && this.getInternalProperties(internalProperties).settings.all.delay > 0) { await utils.timeout(this.getInternalProperties(internalProperties).settings.all.delay); } let lastKey = result.LastEvaluatedKey; let requestedTimes = 1; while (lastKey && (this.getInternalProperties(internalProperties).settings.all.max === 0 || requestedTimes < this.getInternalProperties(internalProperties).settings.all.max)) { if (this.getInternalProperties(internalProperties).settings.all.delay && this.getInternalProperties(internalProperties).settings.all.delay > 0) { await utils.timeout(this.getInternalProperties(internalProperties).settings.all.delay); } const nextRequest: any = await ddb(table.getInternalProperties(internalProperties).instance, this.getInternalProperties(internalProperties).internalSettings.typeInformation.type as any, {...request, ...extraParameters, "ExclusiveStartKey": lastKey}); timesRequested++; result = utils.merge_objects(result, nextRequest); // The operation below is safe because right above we are overwriting the entire `result` variable, so there is no chance it'll be reassigned based on an outdated value since it's already been overwritten. There might be a better way to do this than ignoring the rule on the line below. result.LastEvaluatedKey = nextRequest.LastEvaluatedKey; // eslint-disable-line require-atomic-updates lastKey = nextRequest.LastEvaluatedKey; requestedTimes++; } return result; }); } return promise; }; if (this.getInternalProperties(internalProperties).settings.parallel) { return Promise.all(new Array(this.getInternalProperties(internalProperties).settings.parallel).fill(0).map((a, index) => allRequest({"Segment": index}))); } else { return allRequest(); } }); if (callback) { promise.then((result) => prepareForReturn(result)).then((result) => callback(null, result)).catch((error) => callback(error)); } else { return (async (): Promise<any> => { const result = await promise; const finalResult = await prepareForReturn(result); return finalResult; })(); } } constructor (model: Model<Item>, typeInformation: ItemRetrieverTypeInformation, object?: ConditionInitializer) { super(); let condition: Condition; try { condition = new Condition(object); } catch (e) { e.message = `${e.message.replace(" is invalid.", "")} is invalid for the ${typeInformation.type} operation.`; throw e; } this.setInternalProperties(internalProperties, { "internalSettings": { model, typeInformation }, "settings": { condition } }); } } Object.getOwnPropertyNames(Condition.prototype).forEach((key: string) => { if (!["requestObject", "constructor"].includes(key)) { ItemRetriever.prototype[key] = function (this: ItemRetriever, ...args): ItemRetriever { Condition.prototype[key].bind(this.getInternalProperties(internalProperties).settings.condition)(...args); return this; }; } }); ItemRetriever.prototype.getRequest = async function (this: ItemRetriever): Promise<any> { const {model} = this.getInternalProperties(internalProperties).internalSettings; const table = model.getInternalProperties(internalProperties).table(); const object: any = { ...await this.getInternalProperties(internalProperties).settings.condition.getInternalProperties(internalProperties).requestObject(model, {"conditionString": "FilterExpression", "conditionStringType": "array"}), "TableName": table.getInternalProperties(internalProperties).name }; if (this.getInternalProperties(internalProperties).settings.limit) { object.Limit = this.getInternalProperties(internalProperties).settings.limit; } if (this.getInternalProperties(internalProperties).settings.startAt) { object.ExclusiveStartKey = Item.isDynamoObject(this.getInternalProperties(internalProperties).settings.startAt) ? this.getInternalProperties(internalProperties).settings.startAt : model.Item.objectToDynamo(this.getInternalProperties(internalProperties).settings.startAt); } const indexes = await model.getInternalProperties(internalProperties).getIndexes(); if (this.getInternalProperties(internalProperties).settings.index) { object.IndexName = this.getInternalProperties(internalProperties).settings.index; } else if (this.getInternalProperties(internalProperties).internalSettings.typeInformation.type === "query") { const comparisonChart = this.getInternalProperties(internalProperties).settings.condition.getInternalProperties(internalProperties).settings.conditions.reduce((res, item) => { const myItem = Object.entries(item)[0]; res[myItem[0]] = {"type": (myItem[1] as any).type}; return res; }, {}); const indexSpec = utils.find_best_index(indexes, comparisonChart); if (!indexSpec.tableIndex) { if (!indexSpec.indexName) { throw new CustomError.InvalidParameter("Index can't be found for query."); } object.IndexName = indexSpec.indexName; } } function moveParameterNames (val, prefix): void { const entry = Object.entries(object.ExpressionAttributeNames).find((entry) => entry[1] === val); if (!entry) { return; } const [key, value] = entry; const filterExpressionIndex = object.FilterExpression.findIndex((item) => item.includes(key)); const filterExpression = object.FilterExpression[filterExpressionIndex]; if (filterExpression.includes("attribute_exists") || filterExpression.includes("contains")) { return; } object.ExpressionAttributeNames[`#${prefix}a`] = value; delete object.ExpressionAttributeNames[key]; const valueKey = key.replace("#a", ":v"); Object.keys(object.ExpressionAttributeValues).filter((key) => key.startsWith(valueKey)).forEach((key) => { object.ExpressionAttributeValues[key.replace(new RegExp(":v\\d"), `:${prefix}v`)] = object.ExpressionAttributeValues[key]; delete object.ExpressionAttributeValues[key]; }); const newExpression = filterExpression.replace(key, `#${prefix}a`).replace(new RegExp(valueKey, "g"), `:${prefix}v`); object.KeyConditionExpression = `${object.KeyConditionExpression || ""}${object.KeyConditionExpression ? " AND " : ""}${newExpression}`; utils.object.delete(object.FilterExpression, filterExpressionIndex); const previousElementIndex = filterExpressionIndex === 0 ? 0 : filterExpressionIndex - 1; if (object.FilterExpression[previousElementIndex] === "AND") { utils.object.delete(object.FilterExpression, previousElementIndex); } } if (this.getInternalProperties(internalProperties).internalSettings.typeInformation.type === "query") { const index = utils.array_flatten(Object.values(indexes)).find((index) => index.IndexName === object.IndexName) || indexes.TableIndex; const {hash, range} = index.KeySchema.reduce((res, item) => { res[item.KeyType.toLowerCase()] = item.AttributeName; return res; }, {}); moveParameterNames(hash, "qh"); if (range) { moveParameterNames(range, "qr"); } } if (this.getInternalProperties(internalProperties).settings.consistent) { object.ConsistentRead = this.getInternalProperties(internalProperties).settings.consistent; } if (this.getInternalProperties(internalProperties).settings.count) { object.Select = "COUNT"; } if (this.getInternalProperties(internalProperties).settings.parallel) { object.TotalSegments = this.getInternalProperties(internalProperties).settings.parallel; } if (this.getInternalProperties(internalProperties).settings.sort === SortOrder.descending) { object.ScanIndexForward = false; } if (this.getInternalProperties(internalProperties).settings.attributes) { if (!object.ExpressionAttributeNames) { object.ExpressionAttributeNames = {}; } object.ProjectionExpression = this.getInternalProperties(internalProperties).settings.attributes.map((attribute) => { let expressionAttributeName = ""; expressionAttributeName = (Object.entries(object.ExpressionAttributeNames).find((entry) => entry[1] === attribute) || [])[0]; if (!expressionAttributeName) { const nextIndex = (Object.keys(object.ExpressionAttributeNames).map((item) => parseInt(item.replace("#a", ""))).filter((item) => !isNaN(item)).reduce((existing, item) => Math.max(item, existing), 0) || 0) + 1; expressionAttributeName = `#a${nextIndex}`; object.ExpressionAttributeNames[expressionAttributeName] = attribute; } return expressionAttributeName; }).sort().join(", "); } if (object.FilterExpression && Array.isArray(object.FilterExpression)) { object.FilterExpression = utils.dynamoose.convertConditionArrayRequestObjectToString(object.FilterExpression); } if (object.FilterExpression === "") { delete object.FilterExpression; } return object; }; interface ItemRetrieverResponse<T> extends ItemArray<T> { lastKey?: ObjectType; count: number; } export interface ScanResponse<T> extends ItemRetrieverResponse<T> { scannedCount: number; timesScanned: number; } export interface QueryResponse<T> extends ItemRetrieverResponse<T> { queriedCount: number; timesQueried: number; } interface SettingDefinition { name: string; only?: string[]; boolean?: boolean; settingsName?: string; } const settings: (SettingDefinition | string)[] = [ "limit", "startAt", "attributes", {"name": "count", "boolean": true}, {"name": "consistent", "boolean": true}, {"name": "using", "settingsName": "index"} ]; settings.forEach((item) => { ItemRetriever.prototype[(item as SettingDefinition).name || (item as string)] = function (value): ItemRetriever { const key: string = (item as SettingDefinition).settingsName || (item as SettingDefinition).name || (item as string); this.getInternalProperties(internalProperties).settings[key] = (item as SettingDefinition).boolean ? !this.getInternalProperties(internalProperties).settings[key] : value; return this; }; }); ItemRetriever.prototype.all = function (this: ItemRetriever, delay = 0, max = 0): ItemRetriever { this.getInternalProperties(internalProperties).settings.all = {delay, max}; return this; }; export interface Scan<T> extends ItemRetriever, BasicOperators<Scan<T>> { exec(): Promise<ScanResponse<T>>; exec(callback: CallbackType<ScanResponse<T>, any>): void; } export class Scan<T> extends ItemRetriever { exec (callback?: CallbackType<ScanResponse<T>, any>): Promise<ScanResponse<T>> | void { return super.exec(callback); } parallel (value: number): Scan<T> { this.getInternalProperties(internalProperties).settings.parallel = value; return this; } constructor (model: Model<Item>, object?: ConditionInitializer) { super(model, {"type": ItemRetrieverTypes.scan, "pastTense": "scanned"}, object); } } export interface Query<T> extends ItemRetriever, BasicOperators<Query<T>> { exec(): Promise<QueryResponse<T>>; exec(callback: CallbackType<QueryResponse<T>, any>): void; } export class Query<T> extends ItemRetriever { exec (callback?: CallbackType<QueryResponse<T>, any>): Promise<QueryResponse<T>> | void { return super.exec(callback); } sort (order: SortOrder | `${SortOrder}`): Query<T> { this.getInternalProperties(internalProperties).settings.sort = order; return this; } constructor (model: Model<Item>, object?: ConditionInitializer) { super(model, {"type": ItemRetrieverTypes.query, "pastTense": "queried"}, object); } }
the_stack
import { getRemoteLogger } from "../../logging"; import { PdfjsFindQueryWidget } from "../pdfjs/PdfjsFindQueryWidget"; import * as selectors from "../../selectors"; import { SymbolFilters } from "../../state"; import { SymbolFindQueryWidget } from "./SymbolFindQueryWidget"; import TermFindQueryWidget from "./TermFindQueryWidget"; import { Symbol, Term } from "../../api/types"; import { PDFViewerApplication } from "../../types/pdfjs-viewer"; import * as uiUtils from "../../utils/ui"; import Card from "@material-ui/core/Card"; import CircularProgress from "@material-ui/core/CircularProgress"; import IconButton from "@material-ui/core/IconButton"; import CloseIcon from "@material-ui/icons/Close"; import NavigateBeforeIcon from "@material-ui/icons/NavigateBefore"; import NavigateNextIcon from "@material-ui/icons/NavigateNext"; import classNames from "classnames"; import React from "react"; const logger = getRemoteLogger(); export type FindMode = null | "pdfjs-builtin-find" | "symbol" | "term"; export type FindQuery = null | string | Term | SymbolFilters; export interface SymbolFilter { symbol: Symbol; active?: boolean; } interface Props { className?: string; pdfViewerApplication: PDFViewerApplication; mode: FindMode; query: FindQuery; matchIndex: number | null; matchCount: number | null; handleClose: () => void; handleChangeMatchIndex: (matchIndex: number | null) => void; handleChangeMatchCount: (matchCount: number | null) => void; handleChangeQuery: (query: FindQuery | null) => void; } class FindBar extends React.PureComponent<Props> { constructor(props: Props) { super(props); this.onPdfjsQueryChanged = this.onPdfjsQueryChanged.bind(this); this.onClickNext = this.onClickNext.bind(this); this.onClickPrevious = this.onClickPrevious.bind(this); this.onKeyDown = this.onKeyDown.bind(this); this.close = this.close.bind(this); } componentDidMount() { const { mode, query } = this.props; let queryInfo; if (mode === "pdfjs-builtin-find") { queryInfo = query; } else if (mode === "symbol") { const symbolQuery = query as SymbolFilters; queryInfo = symbolQuery.all .map((id) => symbolQuery.byId[id]) .filter((f) => f !== undefined) .map((f) => f as SymbolFilter) .map((f) => selectors.symbolLogData(f.symbol)); } else if (mode === "term") { queryInfo = selectors.termLogData(query as Term); } logger.log("debug", "find-bar-show", { mode, query: queryInfo, }); } /* * The code for creating the match count message is based on 'PDFFindBar.updateResultsCount' in pdf.js: * https://github.com/mozilla/pdf.js/blob/49f59eb627646ae9a6e166ee2e0ef2cac9390b4f/web/pdf_find_bar.js#L152 */ createMatchCountMessage() { const MATCH_COUNT_LIMIT = 1000; const { query, matchIndex, matchCount } = this.props; if (query === null || matchIndex === null || matchCount === null) { return null; } if (matchCount === 0) { return "No matches found"; } if ((matchCount || 0) > MATCH_COUNT_LIMIT) { return `More than ${MATCH_COUNT_LIMIT} matches`; } return `${matchIndex + 1} of ${matchCount} matches`; } wrapIndex(index: number, len: number) { return ((index % len) + len) % len; } onClickNext() { const { mode, matchIndex, matchCount, query, handleChangeMatchIndex, } = this.props; logger.log("debug", "find-next", { mode, matchIndexBefore: matchIndex, matchCount, query, }); /* * The default behavior when the find widget is controlled is to change which entity is * selected as the 'match' and advance the global match index. */ if (mode !== "pdfjs-builtin-find") { if (matchIndex !== null && matchCount !== null) { handleChangeMatchIndex(this.wrapIndex(matchIndex + 1, matchCount)); } } /* * If the find widget is for the pdf.js built-in find functionality, then instead pdf.js needs * to be notified that the user has requested that the next match gets selected. */ if (mode === "pdfjs-builtin-find" && this.pdfjsFindQueryWidget !== null) { this.pdfjsFindQueryWidget.next(); } } /* * See 'onClickNext' for implementation notes. */ onClickPrevious() { const { mode, matchIndex, matchCount, query, handleChangeMatchIndex, } = this.props; logger.log("debug", "find-previous", { mode, matchIndexBefore: matchIndex, matchCount, query, }); if (mode !== "pdfjs-builtin-find") { if (matchIndex !== null && matchCount !== null) { handleChangeMatchIndex(this.wrapIndex(matchIndex - 1, matchCount)); } } if (mode === "pdfjs-builtin-find" && this.pdfjsFindQueryWidget !== null) { this.pdfjsFindQueryWidget.previous(); } } onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) { const { previousButton, nextButton } = this; const { mode } = this.props; if (mode === "pdfjs-builtin-find" && event.key.startsWith("Arrow")) { return; } if ( previousButton !== null && (event.key === "ArrowLeft" || (event.shiftKey && event.key === "Enter")) ) { logger.log("debug", "find-previous-triggered-by-keypress"); uiUtils.simulateMaterialUiButtonClick(previousButton); event.stopPropagation(); } else if ( nextButton !== null && (event.key === "ArrowRight" || event.key === "Enter") ) { logger.log("debug", "find-next-triggered-by-keypress"); uiUtils.simulateMaterialUiButtonClick(nextButton); event.stopPropagation(); } } onPdfjsQueryChanged(query: string | null) { this.props.handleChangeQuery(query); /* * If the query has changed, a new search has been submitted to 'pdf.js' for processing. Set * the match index and count to 'null' while they get recomputed. */ this.props.handleChangeMatchIndex(null); this.props.handleChangeMatchCount(null); } close() { this.props.handleClose(); } render() { const { matchCount, matchIndex, mode, pdfViewerApplication, query, } = this.props; if (mode !== null) { return ( <Card className={classNames("find-bar", this.props.className)} raised={true} /* * Find next / previous when hot keys are pressed. Assign the find-bar focus whenever it * is rendered so that it will automatically process hot keys until user clicks out of it. * The one exception is when a widget with text input is rendered (as is the case when * the widget for pdf.js builtin find functionality is rendered); in that case, * don't auto-focus this parent widget, as the text input will need the focus. */ ref={(ref) => { if (ref instanceof HTMLDivElement) { if (mode !== "pdfjs-builtin-find") { ref.focus(); } } }} tabIndex={0} onKeyDown={this.onKeyDown} > <div className="find-bar__query"> { /* Custom find widgets, depending on the type of search being performed. */ (() => { switch (mode) { case "pdfjs-builtin-find": { if (pdfViewerApplication === null) { return null; } return ( <PdfjsFindQueryWidget ref={(ref) => (this.pdfjsFindQueryWidget = ref)} pdfViewerApplication={pdfViewerApplication} query={query as string | null} onQueryChanged={this.onPdfjsQueryChanged} onMatchIndexChanged={this.props.handleChangeMatchIndex} onMatchCountChanged={this.props.handleChangeMatchCount} /> ); } case "symbol": { return ( <SymbolFindQueryWidget filters={query as SymbolFilters} handleFilterChange={this.props.handleChangeQuery} /> ); } case "term": { return <TermFindQueryWidget term={query as Term} />; } default: return; } })() } </div> {/* Common components for finding: next, back, and close. */} <div className="find-bar__navigation"> <IconButton ref={(ref) => (this.previousButton = ref)} disabled={matchCount === null || matchCount === 0} onClick={this.onClickPrevious} size="small" > <NavigateBeforeIcon /> </IconButton> <IconButton ref={(ref) => (this.nextButton = ref)} disabled={matchCount === null || matchCount === 0} onClick={this.onClickNext} size="small" > <NavigateNextIcon /> </IconButton> </div> {query !== null ? ( <div className="find-bar__message"> <span className="find-bar__message__span"> {matchCount !== null && matchIndex !== null ? ( this.createMatchCountMessage() ) : ( <CircularProgress className="find-bar__progress" size={"1rem"} /> )} </span> </div> ) : null} <IconButton onClick={this.close} size="small"> <CloseIcon /> </IconButton> </Card> ); } } pdfjsFindQueryWidget: PdfjsFindQueryWidget | null = null; nextButton: HTMLButtonElement | null = null; previousButton: HTMLButtonElement | null = null; } export default FindBar;
the_stack
import { SWRResponse } from 'swr'; import { IPageToDeleteWithMeta, IPageToRenameWithMeta } from '~/interfaces/page'; import { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction, OnPutBackedFunction, } from '~/interfaces/ui'; import { IUserGroupHasId } from '~/interfaces/user'; import { useStaticSWR } from './use-static-swr'; /* * PageCreateModal */ type CreateModalStatus = { isOpened: boolean, path?: string, } type CreateModalStatusUtils = { open(path?: string): Promise<CreateModalStatus | undefined> close(): Promise<CreateModalStatus | undefined> } export const usePageCreateModal = (status?: CreateModalStatus): SWRResponse<CreateModalStatus, Error> & CreateModalStatusUtils => { const initialData: CreateModalStatus = { isOpened: false }; const swrResponse = useStaticSWR<CreateModalStatus, Error>('pageCreateModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: (path?: string) => swrResponse.mutate({ isOpened: true, path }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * PageDeleteModal */ export type IDeleteModalOption = { onDeleted?: OnDeletedFunction, } type DeleteModalStatus = { isOpened: boolean, pages?: IPageToDeleteWithMeta[], opts?: IDeleteModalOption, } type DeleteModalStatusUtils = { open( pages?: IPageToDeleteWithMeta[], opts?: IDeleteModalOption, ): Promise<DeleteModalStatus | undefined>, close(): Promise<DeleteModalStatus | undefined>, } export const usePageDeleteModal = (status?: DeleteModalStatus): SWRResponse<DeleteModalStatus, Error> & DeleteModalStatusUtils => { const initialData: DeleteModalStatus = { isOpened: false, pages: [], }; const swrResponse = useStaticSWR<DeleteModalStatus, Error>('deleteModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: ( pages?: IPageToDeleteWithMeta[], opts?: IDeleteModalOption, ) => swrResponse.mutate({ isOpened: true, pages, opts, }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * EmptyTrashModal */ type IEmptyTrashModalOption = { onEmptiedTrash?: () => void, canDelepeAllPages: boolean, } type EmptyTrashModalStatus = { isOpened: boolean, pages?: IPageToDeleteWithMeta[], opts?: IEmptyTrashModalOption, } type EmptyTrashModalStatusUtils = { open( pages?: IPageToDeleteWithMeta[], opts?: IEmptyTrashModalOption, ): Promise<EmptyTrashModalStatus | undefined>, close(): Promise<EmptyTrashModalStatus | undefined>, } export const useEmptyTrashModal = (status?: EmptyTrashModalStatus): SWRResponse<EmptyTrashModalStatus, Error> & EmptyTrashModalStatusUtils => { const initialData: EmptyTrashModalStatus = { isOpened: false, pages: [], }; const swrResponse = useStaticSWR<EmptyTrashModalStatus, Error>('emptyTrashModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: ( pages?: IPageToDeleteWithMeta[], opts?: IEmptyTrashModalOption, ) => swrResponse.mutate({ isOpened: true, pages, opts, }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * PageDuplicateModal */ export type IPageForPageDuplicateModal = { pageId: string, path: string } export type IDuplicateModalOption = { onDuplicated?: OnDuplicatedFunction, } type DuplicateModalStatus = { isOpened: boolean, page?: IPageForPageDuplicateModal, opts?: IDuplicateModalOption, } type DuplicateModalStatusUtils = { open( page?: IPageForPageDuplicateModal, opts?: IDuplicateModalOption ): Promise<DuplicateModalStatus | undefined> close(): Promise<DuplicateModalStatus | undefined> } export const usePageDuplicateModal = (status?: DuplicateModalStatus): SWRResponse<DuplicateModalStatus, Error> & DuplicateModalStatusUtils => { const initialData: DuplicateModalStatus = { isOpened: false }; const swrResponse = useStaticSWR<DuplicateModalStatus, Error>('duplicateModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: ( page?: IPageForPageDuplicateModal, opts?: IDuplicateModalOption, ) => swrResponse.mutate({ isOpened: true, page, opts }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * PageRenameModal */ export type IRenameModalOption = { onRenamed?: OnRenamedFunction, } type RenameModalStatus = { isOpened: boolean, page?: IPageToRenameWithMeta, opts?: IRenameModalOption } type RenameModalStatusUtils = { open( page?: IPageToRenameWithMeta, opts?: IRenameModalOption ): Promise<RenameModalStatus | undefined> close(): Promise<RenameModalStatus | undefined> } export const usePageRenameModal = (status?: RenameModalStatus): SWRResponse<RenameModalStatus, Error> & RenameModalStatusUtils => { const initialData: RenameModalStatus = { isOpened: false }; const swrResponse = useStaticSWR<RenameModalStatus, Error>('renameModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: ( page?: IPageToRenameWithMeta, opts?: IRenameModalOption, ) => swrResponse.mutate({ isOpened: true, page, opts, }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * PutBackPageModal */ export type IPageForPagePutBackModal = { pageId: string, path: string } export type IPutBackPageModalOption = { onPutBacked?: OnPutBackedFunction, } type PutBackPageModalStatus = { isOpened: boolean, page?: IPageForPagePutBackModal, opts?: IPutBackPageModalOption, } type PutBackPageModalUtils = { open( page?: IPageForPagePutBackModal, opts?: IPutBackPageModalOption, ): Promise<PutBackPageModalStatus | undefined> close():Promise<PutBackPageModalStatus | undefined> } export const usePutBackPageModal = (status?: PutBackPageModalStatus): SWRResponse<PutBackPageModalStatus, Error> & PutBackPageModalUtils => { const initialData: PutBackPageModalStatus = { isOpened: false, page: { pageId: '', path: '' }, }; const swrResponse = useStaticSWR<PutBackPageModalStatus, Error>('putBackPageModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: ( page: IPageForPagePutBackModal, opts?: IPutBackPageModalOption, ) => swrResponse.mutate({ isOpened: true, page, opts, }), close: () => swrResponse.mutate({ isOpened: false, page: { pageId: '', path: '' } }), }; }; /* * PagePresentationModal */ type PresentationModalStatus = { isOpened: boolean, href?: string } type PresentationModalStatusUtils = { open(href: string): Promise<PresentationModalStatus | undefined> close(): Promise<PresentationModalStatus | undefined> } export const usePagePresentationModal = ( status?: PresentationModalStatus, ): SWRResponse<PresentationModalStatus, Error> & PresentationModalStatusUtils => { const initialData: PresentationModalStatus = { isOpened: false, href: '?presentation=1', }; const swrResponse = useStaticSWR<PresentationModalStatus, Error>('presentationModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: (href: string) => swrResponse.mutate({ isOpened: true, href }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * PrivateLegacyPagesMigrationModal */ export type ILegacyPrivatePage = { pageId: string, path: string }; export type PrivateLegacyPagesMigrationModalSubmitedHandler = (pages: ILegacyPrivatePage[], isRecursively?: boolean) => void; type PrivateLegacyPagesMigrationModalStatus = { isOpened: boolean, pages?: ILegacyPrivatePage[], onSubmited?: PrivateLegacyPagesMigrationModalSubmitedHandler, } type PrivateLegacyPagesMigrationModalStatusUtils = { open(pages: ILegacyPrivatePage[], onSubmited?: PrivateLegacyPagesMigrationModalSubmitedHandler): Promise<PrivateLegacyPagesMigrationModalStatus | undefined>, close(): Promise<PrivateLegacyPagesMigrationModalStatus | undefined>, } export const usePrivateLegacyPagesMigrationModal = ( status?: PrivateLegacyPagesMigrationModalStatus, ): SWRResponse<PrivateLegacyPagesMigrationModalStatus, Error> & PrivateLegacyPagesMigrationModalStatusUtils => { const initialData: PrivateLegacyPagesMigrationModalStatus = { isOpened: false, pages: [], }; const swrResponse = useStaticSWR<PrivateLegacyPagesMigrationModalStatus, Error>('privateLegacyPagesMigrationModal', status, { fallbackData: initialData }); return { ...swrResponse, open: (pages, onSubmited?) => swrResponse.mutate({ isOpened: true, pages, onSubmited, }), close: () => swrResponse.mutate({ isOpened: false, pages: [], onSubmited: undefined }), }; }; /* * DescendantsPageListModal */ type DescendantsPageListModalStatus = { isOpened: boolean, path?: string, } type DescendantsPageListUtils = { open(path: string): Promise<DescendantsPageListModalStatus | undefined> close(): Promise<DuplicateModalStatus | undefined> } export const useDescendantsPageListModal = ( status?: DescendantsPageListModalStatus, ): SWRResponse<DescendantsPageListModalStatus, Error> & DescendantsPageListUtils => { const initialData: DescendantsPageListModalStatus = { isOpened: false }; const swrResponse = useStaticSWR<DescendantsPageListModalStatus, Error>('descendantsPageListModalStatus', status, { fallbackData: initialData }); return { ...swrResponse, open: (path: string) => swrResponse.mutate({ isOpened: true, path }), close: () => swrResponse.mutate({ isOpened: false }), }; }; /* * PageAccessoriesModal */ export const PageAccessoriesModalContents = { PageHistory: 'PageHistory', Attachment: 'Attachment', ShareLink: 'ShareLink', } as const; export type PageAccessoriesModalContents = typeof PageAccessoriesModalContents[keyof typeof PageAccessoriesModalContents]; type PageAccessoriesModalStatus = { isOpened: boolean, onOpened?: (initialActivatedContents: PageAccessoriesModalContents) => void, } type PageAccessoriesModalUtils = { open(activatedContents: PageAccessoriesModalContents): void close(): void } export const usePageAccessoriesModal = (): SWRResponse<PageAccessoriesModalStatus, Error> & PageAccessoriesModalUtils => { const initialStatus = { isOpened: false }; const swrResponse = useStaticSWR<PageAccessoriesModalStatus, Error>('pageAccessoriesModalStatus', undefined, { fallbackData: initialStatus }); return { ...swrResponse, open: (activatedContents: PageAccessoriesModalContents) => { if (swrResponse.data == null) { return; } swrResponse.mutate({ isOpened: true }); if (swrResponse.data.onOpened != null) { swrResponse.data.onOpened(activatedContents); } }, close: () => { if (swrResponse.data == null) { return; } swrResponse.mutate({ isOpened: false }); }, }; }; /* * UpdateUserGroupConfirmModal */ type UpdateUserGroupConfirmModalStatus = { isOpened: boolean, targetGroup?: IUserGroupHasId, updateData?: Partial<IUserGroupHasId>, onConfirm?: (targetGroup: IUserGroupHasId, updateData: Partial<IUserGroupHasId>, forceUpdateParents: boolean) => any, } type UpdateUserGroupConfirmModalUtils = { open(targetGroup: IUserGroupHasId, updateData: Partial<IUserGroupHasId>, onConfirm?: (...args: any[]) => any): Promise<void>, close(): Promise<void>, } export const useUpdateUserGroupConfirmModal = (): SWRResponse<UpdateUserGroupConfirmModalStatus, Error> & UpdateUserGroupConfirmModalUtils => { const initialStatus: UpdateUserGroupConfirmModalStatus = { isOpened: false }; const swrResponse = useStaticSWR<UpdateUserGroupConfirmModalStatus, Error>('updateParentConfirmModal', undefined, { fallbackData: initialStatus }); return { ...swrResponse, async open(targetGroup: IUserGroupHasId, updateData: Partial<IUserGroupHasId>, onConfirm?: (...args: any[]) => any) { await swrResponse.mutate({ isOpened: true, targetGroup, updateData, onConfirm, }); }, async close() { await swrResponse.mutate({ isOpened: false }); }, }; };
the_stack
import * as fs from 'fs/promises'; import * as path from 'path'; const OUTPUT_PATH = path.join(__dirname, '..', 'src', 'ops.ts'); // The idea here is to parse the ops json file from https://github.com/izik1/gbops/ // and automatically generate function definitions that for the assembly DSL. // The position in the array provides the opcode, and the name provides arguments // and obviously the instruction name. // With an instruction like `LD A,u8`, the u8 indicates that we need to take an 8-bit // numeric argument to the function (or possibly a symbol/label). type TimingEntry = { Type: string; Comment: string; }; type InstructionEntry = { Name: string, Group: string, TCyclesBranch: number, TCyclesNoBranch: number, Length: number, Flags: { Z: string, N: string, H: string, C: string }, TimingNoBranch: TimingEntry[], TimingBranch?: TimingEntry[], }; type OpsJson = { Unprefixed: InstructionEntry[]; CBPrefixed: InstructionEntry[]; }; const is8BitReg = (arg: string) => [ 'A', 'B', 'C', 'D', 'E', 'H', 'L', ].includes(arg); const is16BitReg = (arg: string) => [ 'BC', 'DE', 'AF', 'SP', 'HL' ].includes(arg); const is16BitRegPtr = (arg: string) => [ '(BC)', '(DE)', '(SP)', '(HL)', '(HL+)', '(HL-)' ].includes(arg); const isFlagCondition = (arg: string) => [ 'NC', 'NZ', 'Z', 'C' ].includes(arg); const isHexOffset = (arg: string) => [ '00h', '08h', '10h', '18h', '20h', '28h', '30h', '38h', ].includes(arg); const isBitIndex = (arg: string) => [ '0', '1', '2', '3', '4', '5', '6', '7' ].includes(arg); const isU16Imm = (arg: string) => arg === 'u16'; const isU8Imm = (arg: string) => arg === 'u8'; const isI8Imm = (arg: string) => arg === 'i8'; const isImmPtr = (arg: string) => arg === '(u16)'; const isFFPageOffset = (arg: string) => arg === '(FF00+u8)'; const isFFPageC = (arg: string) => arg === '(FF00+C)'; const isSPOffset = (arg: string) => arg === 'SP+i8'; const isCBPrefix = (arg: string) => arg === 'CB'; const getArgTypeName = (arg: string, opName: string) => { // We need to disambiguate between registers and flags here if (['JP', 'JR', 'CALL', 'RET'].includes(opName) && isFlagCondition(arg)) { return 'flagCondition'; } switch (true) { case isBitIndex(arg): return 'bitIndex'; case is8BitReg(arg): return 'reg8'; case is16BitReg(arg): return 'reg16'; case is16BitRegPtr(arg): return 'reg16ptr'; case isU8Imm(arg): return 'u8imm'; case isU16Imm(arg): return 'u16imm'; case isImmPtr(arg): return 'u16ptr'; case isI8Imm(arg): return 'i8imm'; case isFFPageOffset(arg): return 'ffPageOffset'; case isFFPageC(arg): return 'ffPageC'; case isSPOffset(arg): return 'spOffset'; case isFlagCondition(arg): return 'flagCondition'; case isHexOffset(arg): return 'hexOffset'; case isCBPrefix(arg): return 'CBPrefix'; default: throw new Error(`Not implemented: ${arg}`); } } const groupBy = <T>(keyFn: (x: T) => string, arr: T[]): Record<string, T[]> => { const out: Record<string, T[]> = {}; arr.forEach(x => { const key = keyFn(x); if (!(key in out)) { out[key] = []; } out[key].push(x); }); return out; } const mapObjValues = <T, R>(fn: (x: T) => R, obj: Record<string, T>): Record<string, R> => { return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)])); } const toHex = (opcode: number) => `0x${opcode.toString(16).padStart(2, '0')}`; const toArgName = (argType: string, position: 'a' | 'b') => { switch (argType) { case 'bitIndex': return `bitIndex`; case 'reg8': return `r8${position}`; case 'reg16': return `r16${position}`; case 'reg16ptr': return `r16ptr${position}`; case 'u8imm': return `u8`; case 'u16imm': return `u16`; case 'u16ptr': return `u16ptr`; case 'i8imm': return `i8`; case 'ffPageOffset': return `ffPageOffset`; case 'ffPageC': return `ffPageC`; case 'spOffset': return `spOffset`; case 'flagCondition': return `flag`; case 'hexOffset': return `offset`; default: throw new Error(`Not implemented: ${argType}`); } } const instRegex = /^([A-Z]+)(?:\s(?:(.+),)?(.+)?)?$/g; const getInstructionParts = (instruction: string) => { let m; const groups: string[] = []; while ((m = instRegex.exec(instruction)) !== null) { if (m.index === instRegex.lastIndex) { instRegex.lastIndex++; } groups.push(...m.slice(1)); } instRegex.lastIndex = 0; return groups.filter(x => typeof x !== 'undefined'); } const immToTypeName = (immOrPtr: string) => { switch (immOrPtr) { case 'u8imm': return `SymbolOr<U8Imm>`; case 'u16imm': return `SymbolOr<U16Imm>`; case 'u16ptr': return `SymbolOr<U16Ptr>`; case 'i8imm': return `SymbolOr<I8Imm>`; case 'ffPageOffset': return `SymbolOr<FFPageOffset>`; case 'spOffset': return `SymbolOr<SPOffset>`; default: throw new Error(`Not implemented: ${immOrPtr}`); } } const generateFunctions = (fnGroup: Record<string, [string[], number][]>, isPrefix: boolean) => { const fnName = Object.values(fnGroup)[0][0][0][0]; // 😵 const minArgs = Object.keys(fnGroup) .map(pair => pair === 'noArgs' ? 0 : pair.split(',').length) .reduce((a, b) => Math.min(a, b)); const signatures: string[] = []; const mainFnLines: string[] = []; Object.entries(fnGroup).forEach(([argTypeStr, fns]) => { const argTypes = argTypeStr.split(','); if (argTypes[0] === 'noArgs') { const opcode = fns[0][1]; signatures.push(`export function ${fnName}(): OpDescription;`); mainFnLines.push(`if (arguments.length === 0) return { type: 'opDescription', opcode: ${toHex(opcode)}, isPrefix: ${isPrefix} };`); } else if (argTypes.length === 1) { mainFnLines.push('if (arguments.length === 1) {'); if (['i8imm', 'u16imm'].includes(argTypes[0])) { fns.forEach(([_, opcode]) => { const argA = toArgName(argTypes[0], 'a'); const argAType = immToTypeName(argTypes[0]); signatures.push(`export function ${fnName}(${argA}: ${argAType}): OpDescription;`); mainFnLines.push( ` if (a0.type === '${argTypes[0]}' || isSymbolRef(a0.type)) {`, ` return { type: 'opDescription', opcode: ${toHex(opcode)}, ${argA}: a0, isPrefix: ${isPrefix} };`, ` }` ); }); } else if (['reg8', 'reg16', 'reg16ptr', 'hexOffset', 'flagCondition'].includes(argTypes[0])) { fns.forEach(([[_, arg0], opcode]) => { const argA = toArgName(argTypes[0], 'a'); signatures.push(`export function ${fnName}(${argA}: '${arg0}'): OpDescription;`); mainFnLines.push(` if (a0 === '${arg0}') return { type: 'opDescription', opcode: ${toHex(opcode)}, isPrefix: ${isPrefix} };`); }); } else { debugger; } mainFnLines.push('}'); } else if (argTypes.length === 2) { const groupedByArg0 = groupBy(([opParts]) => opParts[1], fns); mainFnLines.push('if (arguments.length === 2) {'); const allowedArg0s = Object.keys(groupedByArg0); allowedArg0s.forEach(arg0 => { const opsPerArg0 = groupedByArg0[arg0]; const allowedArg1s = opsPerArg0.map(([parts]) => parts[2]); const arg1Union = allowedArg1s.map(x => `'${x}'`).join(' | '); const argA = toArgName(argTypes[0], 'a'); const argB = toArgName(argTypes[1], 'b'); if ( (argTypes[0] === 'reg16' && argTypes[1] === 'reg16') || (argTypes[0] === 'reg8' && argTypes[1] === 'reg8') || (argTypes[0] === 'reg8' && argTypes[1] === 'reg16ptr') || (argTypes[0] === 'reg16ptr' && argTypes[1] === 'reg8') || (argTypes[0] === 'ffPageC' && argTypes[1] === 'reg8') || (argTypes[0] === 'reg8' && argTypes[1] === 'ffPageC') || (argTypes[0] === 'bitIndex' && argTypes[1] === 'reg8') || (argTypes[0] === 'bitIndex' && argTypes[1] === 'reg16ptr') ) { signatures.push(`export function ${fnName}(${argA}: '${arg0}', ${argB}: ${arg1Union}): OpDescription;`); mainFnLines.push(` if (a0 === '${arg0}') {`); opsPerArg0.forEach(([[_, __, arg1], opcode]) => { mainFnLines.push( ` if (a1 === '${arg1}') return { type: 'opDescription', opcode: ${toHex(opcode)}, isPrefix: ${isPrefix} };`, ); }); mainFnLines.push(' }'); } else if ( (argTypes[0] === 'reg8' && argTypes[1] === 'u8imm') || (argTypes[0] === 'reg16' && argTypes[1] === 'i8imm') || (argTypes[0] === 'reg8' && argTypes[1] === 'u16imm') || (argTypes[0] === 'reg16' && argTypes[1] === 'u16imm') || (argTypes[0] === 'reg16ptr' && argTypes[1] === 'u8imm') || (argTypes[0] === 'reg8' && argTypes[1] === 'ffPageOffset') || (argTypes[0] === 'flagCondition' && argTypes[1] === 'u16imm') || (argTypes[0] === 'flagCondition' && argTypes[1] === 'i8imm') || (argTypes[0] === 'reg8' && argTypes[1] === 'u16ptr') || (argTypes[0] === 'reg16' && argTypes[1] === 'spOffset') ) { signatures.push(`export function ${fnName}(${argA}: '${arg0}', ${argB}: ${immToTypeName(argTypes[1])}): OpDescription;`); const opcode = opsPerArg0[0][1]; mainFnLines.push( ` if (a0 === '${arg0}' && (a1.type === '${argTypes[1]}' || isSymbolRef(a1.type))) {`, ` return { type: 'opDescription', opcode: ${toHex(opcode)}, ${argB}: a1, isPrefix: ${isPrefix} };`, ' }' ); } else if ( (argTypes[0] === 'u16ptr' && argTypes[1] === 'reg16') || (argTypes[0] === 'u16ptr' && argTypes[1] === 'reg8') || (argTypes[0] === 'ffPageOffset' && argTypes[1] === 'reg8') ) { signatures.push(`export function ${fnName}(${argA}: ${immToTypeName(argTypes[0])}, ${argB}: ${arg1Union}): OpDescription;`); const opcode = opsPerArg0[0][1]; allowedArg1s.forEach(arg1 => { mainFnLines.push( ` if ((a0.type === '${argTypes[0]}' || isSymbolRef(a0.type)) && a1 === '${arg1}') {`, ` return { type: 'opDescription', opcode: ${toHex(opcode)}, ${argA}: a0, isPrefix: ${isPrefix} };`, ' }' ); }); } else { debugger; } }); mainFnLines.push('}'); } }); const mainFnDecl = signatures.length === 1 ? signatures.pop()?.replace(';', ' {') : `export function ${fnName}(a0${minArgs < 1 ? '?' : ''}: any, a1${minArgs < 2 ? '?' : ''}: any): OpDescription {`; const fnDef = [ mainFnDecl, mainFnLines.map(line => ' ' + line).join('\n'), ` throw new Error('${fnName}: Invalid argument combination provided');`, '}', ].join('\n'); return [ ...signatures, fnDef ].join('\n'); }; const typeImports = [ 'import {', ' FFPageOffset,', ' I8Imm,', ' OpDescription,', ' SPOffset,', ' SymbolOr,', ' U16Imm,', ' U16Ptr,', ' U8Imm', '} from "./types";', '', ].join('\n'); const fns = [ 'const isSymbolRef = (x: string) => [', ' "symbolReference",', ' "sizeOfReference",', '].includes(x);', '' ].join('\n'); const autogenMessage = [ `// =============================================================================`, `// TEGA: TypeScript Embedded GameBoy Macro Assembler`, `//`, `// This file is autogenerated - do not edit by hand.`, `// Instead edit ${path.basename(__filename)} and run "npm run generate"`, `// =============================================================================`, '', ].join('\n'); const main = async () => { const ops: OpsJson = JSON.parse(await fs.readFile(path.join(__dirname, '..', 'dmgops.json'), { encoding: 'utf-8' })); const grouped = groupBy( op => op[0][0], ops.Unprefixed.map<[string[], number]>((x, i) => [getInstructionParts(x.Name), i]) ); const groupedCB = groupBy( op => op[0][0], ops.CBPrefixed.map<[string[], number]>((x, i) => [getInstructionParts(x.Name), i]) ); const groupOnArg0 = (instrs: [string[], number][]) => groupBy(([inst]) => { const [opName, arg0, arg1] = inst; const numArgs = inst.length - 1; if (numArgs === 0) return 'noArgs'; if (numArgs === 1) return getArgTypeName(arg0, opName); return `${getArgTypeName(arg0, opName)},${getArgTypeName(arg1, opName)}`; }, instrs); const groupedGroups = mapObjValues(groupOnArg0, grouped); const groupedCBGroups = mapObjValues(groupOnArg0, groupedCB); // These can be handled independantly delete groupedGroups['PREFIX']; // These should be added later as the undocumented instructions delete groupedGroups['UNUSED']; const generatedBaseAPI = Object.values(groupedGroups) .map(fnGroup => generateFunctions(fnGroup, false)) .join('\n\n'); const generatedCBAPI = Object.values(groupedCBGroups) .map(fnGroup => generateFunctions(fnGroup, true)) .join('\n\n'); const file = [ autogenMessage, typeImports, fns, generatedBaseAPI, generatedCBAPI, ].join('\n'); return fs.writeFile(OUTPUT_PATH, file); }; main();
the_stack
import { aws_events, aws_events_targets, aws_lambda, Duration, Stack, } from "aws-cdk-lib"; import { ExpressStepFunction, StepFunction } from "../src"; import { EventBus, Rule, Event, ScheduledEvent } from "../src/event-bridge"; import { synthesizeEventPattern } from "../src/event-bridge/event-pattern"; import { EventTransform } from "../src/event-bridge/transform"; import { Function } from "../src/function"; let stack: Stack; beforeEach(() => { stack = new Stack(); }); test("new bus from aws bus", () => { const bus = new aws_events.EventBus(stack, "bus"); EventBus.fromBus(bus); }); test("new bus without wrapper", () => { new EventBus(stack, "bus"); }); test("new rule without when", () => { const bus = new EventBus(stack, "bus"); const rule = new Rule(stack, "rule", bus, (_event) => true); expect(rule.resource._renderEventPattern()).toEqual({ source: [{ prefix: "" }], }); }); test("new transform without map", () => { const bus = new EventBus(stack, "bus"); const rule = new Rule(stack, "rule", bus, (_event) => true); const transform = new EventTransform((event) => event.source, rule); expect(transform.targetInput.bind(rule.resource)).toEqual({ inputPath: "$.source", } as aws_events.RuleTargetInputProperties); }); test("rule from existing rule", () => { const awsRule = new aws_events.Rule(stack, "rule"); const rule = Rule.fromRule(awsRule); const transform = new EventTransform((event) => event.source, rule); expect(transform.targetInput.bind(rule.resource)).toEqual({ inputPath: "$.source", } as aws_events.RuleTargetInputProperties); }); test("new bus with when", () => { const rule = new EventBus(stack, "bus").when(stack, "rule", () => true); expect(rule.resource._renderEventPattern()).toEqual({ source: [{ prefix: "" }], }); }); test("when using auto-source", () => { const bus = new EventBus(stack, "bus"); bus.when("rule", () => true).pipe(bus); expect(bus.resource.node.tryFindChild("rule")).not.toBeUndefined(); }); test("rule when using auto-source", () => { const bus = new EventBus(stack, "bus"); const rule1 = bus.when("rule", () => true); rule1.when("rule2", () => true).pipe(bus); expect(bus.resource.node.tryFindChild("rule2")).not.toBeUndefined(); }); test("refine rule", () => { const rule = new EventBus(stack, "bus").when( stack, "rule", (event) => event.source === "lambda" ); const rule2 = rule.when( stack, "rule1", (event) => event["detail-type"] === "something" ); expect(rule2.resource._renderEventPattern()).toEqual({ source: ["lambda"], "detail-type": ["something"], }); }); test("new bus with when pipe event bus", () => { const busBus = new EventBus(stack, "bus"); const rule = busBus.when(stack, "rule", () => true); rule.pipe(busBus); expect((rule.resource as any).targets.length).toEqual(1); expect( (rule.resource as any).targets[0] as aws_events.IRuleTarget ).toHaveProperty("arn"); }); test("refined bus with when pipe event bus", () => { const busBus = new EventBus(stack, "bus"); const rule = busBus.when(stack, "rule", (event) => event.source === "lambda"); const rule2 = rule.when( stack, "rule1", (event) => event["detail-type"] === "something" ); rule2.pipe(busBus); expect((rule.resource as any).targets.length).toEqual(0); expect((rule2.resource as any).targets.length).toEqual(1); expect( (rule2.resource as any).targets[0] as aws_events.IRuleTarget ).toHaveProperty("arn"); }); test("new bus with when map pipe function", () => { const busBus = new EventBus(stack, "bus"); const func = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const rule = busBus .when(stack, "rule", () => true) .map((event) => event.source); rule.pipe(func); expect(rule.targetInput.bind(rule.rule.resource)).toEqual({ inputPath: "$.source", } as aws_events.RuleTargetInputProperties); expect((rule.rule.resource as any).targets.length).toEqual(1); expect( (rule.rule.resource as any).targets[0] as aws_events.IRuleTarget ).toHaveProperty("arn"); }); test("refined bus with when pipe function", () => { const func = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const rule = new EventBus(stack, "bus").when( stack, "rule", (event) => event.source === "lambda" ); const rule2 = rule.when( stack, "rule1", (event) => event["detail-type"] === "something" ); const map = rule2.map((event) => event.source); map.pipe(func); expect((rule.resource as any).targets.length).toEqual(0); expect((rule2.resource as any).targets.length).toEqual(1); expect( (map.rule.resource as any).targets[0] as aws_events.IRuleTarget ).toHaveProperty("arn"); }); test("new bus with when map pipe step function", () => { const busBus = new EventBus(stack, "bus"); const func = new StepFunction<{ source: string }, void>( stack, "sfn", () => {} ); const rule = busBus .when(stack, "rule", () => true) .map((event) => ({ source: event.source })); rule.pipe(func); expect(stack.resolve(rule.targetInput.bind(rule.rule.resource))).toEqual({ inputPathsMap: { source: "$.source" }, inputTemplate: '{"source":<source>}', } as aws_events.RuleTargetInputProperties); expect((rule.rule.resource as any).targets.length).toEqual(1); expect( (rule.rule.resource as any).targets[0] as aws_events.IRuleTarget ).toHaveProperty("arn"); }); test("new bus with when map pipe express step function", () => { const busBus = new EventBus(stack, "bus"); const func = new ExpressStepFunction<{ source: string }, void>( stack, "sfn", () => {} ); const rule = busBus .when(stack, "rule", () => true) .map((event) => ({ source: event.source })); rule.pipe(func); expect(stack.resolve(rule.targetInput.bind(rule.rule.resource))).toEqual({ inputPathsMap: { source: "$.source" }, inputTemplate: '{"source":<source>}', } as aws_events.RuleTargetInputProperties); expect((rule.rule.resource as any).targets.length).toEqual(1); expect( (rule.rule.resource as any).targets[0] as aws_events.IRuleTarget ).toHaveProperty("arn"); }); test("new bus with when map pipe function props", () => { const busBus = new EventBus(stack, "bus"); const func = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const rule = busBus .when(stack, "rule", () => true) .map((event) => event.source); rule.pipe(func, { retryAttempts: 10 }); expect(rule.targetInput.bind(rule.rule.resource)).toEqual({ inputPath: "$.source", } as aws_events.RuleTargetInputProperties); expect((rule.rule.resource as any).targets.length).toEqual(1); expect( (rule.rule.resource as any).targets[0] as aws_events.RuleTargetConfig ).toHaveProperty("arn"); expect( ((rule.rule.resource as any).targets[0] as aws_events.RuleTargetConfig) .retryPolicy?.maximumRetryAttempts ).toEqual(10); }); test("pipe escape hatch", () => { const busBus = new EventBus(stack, "bus"); const func = Function.fromFunction( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const rule = busBus.when(stack, "rule", () => true); rule.pipe(() => new aws_events_targets.LambdaFunction(func.resource)); expect( (rule.resource as any).targets[0] as aws_events.RuleTargetConfig ).toHaveProperty("arn"); }); test("pipe map escape hatch", () => { const busBus = new EventBus(stack, "bus"); const func = Function.fromFunction( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const rule = busBus .when(stack, "rule", () => true) .map((event) => event.source); rule.pipe( (targetInput) => new aws_events_targets.LambdaFunction(func.resource, { event: targetInput, }) ); expect( (rule.rule.resource as any).targets[0] as aws_events.RuleTargetConfig ).toHaveProperty("arn"); }); interface t1 { type: "one"; one: string; } interface t2 { type: "two"; two: string; } interface tt extends Event<t1 | t2> {} test("when narrows type to map", () => { const bus = EventBus.default<tt>(stack); bus .when( stack, "rule", (event): event is Event<t1> => event.detail.type === "one" ) .map((event) => event.detail.one); }); test("when narrows type to map", () => { const bus = EventBus.default<tt>(stack); bus .when( stack, "rule", (event): event is Event<t2> => event.detail.type === "two" ) .when(stack, "rule2", (event) => event.detail.two === "something"); }); test("map narrows type and pipe enforces", () => { const lambda = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus .when( stack, "rule", (event): event is Event<t1> => event.detail.type === "one" ) .map((event) => event.detail.one) .pipe(lambda); }); test("a scheduled rule can be mapped and pipped", () => { const lambda = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus .when( stack, "rule", (event): event is Event<t1> => event.detail.type === "one" ) .map((event) => event.detail) // is object // @ts-expect-error should fail compilation if the types don't match .pipe(lambda); // expects strings }); test("pipe typesafe sfn", () => { const sfn = new StepFunction(stack, "machine", (payload: { id: string }) => { return payload.id; }); const bus = EventBus.default<tt>(stack); bus .when( stack, "rule", (event): event is Event<t1> => event.detail.type === "one" ) .map((event) => ({ id: event.detail.one })) // is object .pipe(sfn); // expects strings }); test("pipe typesafe error sfn", () => { const sfn = new StepFunction(stack, "machine", (payload: { id: string }) => { return payload.id; }); const bus = EventBus.default<tt>(stack); bus .when( stack, "rule", (event): event is Event<t1> => event.detail.type === "one" ) .map((event) => ({ id: event.detail })) // is object // @ts-expect-error .pipe(sfn); // expects strings }); test("map cannot pipe to a bus", () => { const bus = EventBus.default<tt>(stack); expect(() => bus .when( stack, "rule", (event): event is Event<t1> => event.detail.type === "one" ) .map((event) => event) // @ts-expect-error .pipe(bus) ).toThrow(); }); test("pipe typesafe", () => { const lambda = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus .schedule(stack, "rule", aws_events.Schedule.rate(Duration.hours(1))) .map((event) => event.id) // should fail compilation if the types don't match .pipe(lambda); }); test("a scheduled rule can be pipped", () => { const lambda = Function.fromFunction<ScheduledEvent, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus .schedule(stack, "rule", aws_events.Schedule.rate(Duration.hours(1))) .pipe(lambda); }); test("when any", () => { const lambda = Function.fromFunction<string, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus .all() .map((event) => event.id) // should fail compilation if the types don't match .pipe(lambda); const rule = bus.resource.node.tryFindChild("all"); expect(rule).not.toBeUndefined(); }); test("when any pipe", () => { const lambda = Function.fromFunction<Event, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus.all().pipe(lambda); const rule = bus.resource.node.tryFindChild("all"); expect(rule).not.toBeUndefined(); }); test("when any multiple times does not create new rules", () => { const lambda = Function.fromFunction<Event, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus.all().pipe(lambda); bus.all().pipe(lambda); bus.all().pipe(lambda); const rule = bus.resource.node.tryFindChild("all"); expect(rule).not.toBeUndefined(); }); test("when any pipe", () => { const lambda = Function.fromFunction<Event, void>( aws_lambda.Function.fromFunctionArn(stack, "func", "") ); const bus = EventBus.default<tt>(stack); bus.all(stack, "anyRule").pipe(lambda); const rule = stack.node.tryFindChild("anyRule"); expect(rule).not.toBeUndefined(); }); test("when any when pipe", () => { const bus = EventBus.default<tt>(stack); const rule = bus .all(stack, "anyRule") .when("rule1", (event) => event.id === "test"); expect(synthesizeEventPattern(rule.document)).toEqual({ id: ["test"] }); });
the_stack
import React, { useState, useMemo, useEffect } from "react"; import { Component } from "@ui_types"; import { Api, Client, Model } from "@core/types"; import * as g from "@core/lib/graph"; import { HomeContainer } from "./home_container"; import * as styles from "@styles"; import { MIN_ACTION_DELAY_MS } from "@constants"; import { wait } from "@core/lib/utils/wait"; import { logAndAlertError } from "@ui_lib/errors"; const INVITE_TOKEN_REGEX = /^(i|dg)_[a-zA-Z0-9]{22}_.+$/; const ENCRYPTION_TOKEN_REGEX = /^[a-fA-F0-9]{64}_[a-zA-Z0-9]{22}$/; let runningLoop = false; export const AcceptInvite: Component = (props) => { const [emailToken, setEmailToken] = useState(""); const [encryptionToken, setEncryptionToken] = useState(""); const [deviceName, setDeviceName] = useState(props.core.defaultDeviceName); const [isLoading, setIsLoading] = useState(false); const [isAccepting, setIsAccepting] = useState(false); const [awaitingMinDelay, setIsAwaitingMinDelay] = useState(false); const [acceptedUserId, setAcceptedUserId] = useState<string>(); const [acceptedSender, setAcceptedSender] = useState<string>(); const [needsExternalAuthError, setNeedsExternalAuthError] = useState< Api.Net.RequiresExternalAuthResult | undefined >(undefined); const [externalAuthErrorMessage, setExternalAuthErrorMessage] = useState< string | undefined >(); const [loadActionType, acceptActionType] = useMemo(() => { if (!emailToken) { return [undefined, undefined]; } const split = emailToken.split("_"); if (!split || split.length != 3) { return [undefined, undefined]; } const [prefix] = split as ["i" | "dg", string, string]; return { i: [Client.ActionType.LOAD_INVITE, Client.ActionType.ACCEPT_INVITE], dg: [ Client.ActionType.LOAD_DEVICE_GRANT, Client.ActionType.ACCEPT_DEVICE_GRANT, ], }[prefix] as [ Client.Action.ClientActions["LoadInvite" | "LoadDeviceGrant"]["type"], Client.Action.ClientActions["AcceptInvite" | "AcceptDeviceGrant"]["type"] ]; }, [emailToken]); const loadedInviteOrDeviceGrant = props.core.loadedInvite ?? props.core.loadedDeviceGrant; const inviteeOrGranteeId = loadedInviteOrDeviceGrant ? "inviteeId" in loadedInviteOrDeviceGrant ? loadedInviteOrDeviceGrant.inviteeId : loadedInviteOrDeviceGrant.granteeId : undefined; useEffect(() => { if (inviteeOrGranteeId && inviteeOrGranteeId != props.ui.accountId) { props.setUiState({ accountId: inviteeOrGranteeId, }); } }, [ Boolean(loadedInviteOrDeviceGrant), inviteeOrGranteeId == props.ui.accountId, ]); useEffect(() => { if (loadedInviteOrDeviceGrant && isLoading && !awaitingMinDelay) { setIsLoading(false); } }, [Boolean(loadedInviteOrDeviceGrant), awaitingMinDelay]); useEffect(() => { const error = props.core.loadInviteError || props.core.loadDeviceGrantError; if (!error || error.type !== "requiresExternalAuthError") { setNeedsExternalAuthError(undefined); if (error) { setIsLoading(false); setEmailToken(""); setEncryptionToken(""); } return; } setNeedsExternalAuthError(error as Api.Net.RequiresExternalAuthResult); setIsLoading(false); }, [props.core.loadInviteError, props.core.loadDeviceGrantError]); // Capture any external auth errors useEffect(() => { const e = props.core.startingExternalAuthSessionError || props.core.createSessionError || props.core.startingExternalAuthSessionInviteError || props.core.externalAuthSessionCreationError || props.core.authorizingExternallyErrorMessage; if (!e) { setExternalAuthErrorMessage(undefined); return; } console.error("External auth error", e); runningLoop = false; setExternalAuthErrorMessage( typeof e === "string" ? e : "errorReason" in e ? e.errorReason : e.type ); }, [ props.core.startingExternalAuthSessionError, props.core.createSessionError, props.core.startingExternalAuthSessionInviteError, props.core.externalAuthSessionCreationError, props.core.authorizingExternallyErrorMessage, ]); // Creation of session from successful external auth. useEffect(() => { if (props.core.completedInviteExternalAuth) { if (runningLoop) { runningLoop = false; } return; } if ( !needsExternalAuthError || loadedInviteOrDeviceGrant || props.core.creatingExternalAuthSession || runningLoop ) { return; } console.log( "CREATE_EXTERNAL_AUTH_SESSION_FOR_INVITE", needsExternalAuthError ); props .dispatch({ type: Client.ActionType.CREATE_EXTERNAL_AUTH_SESSION_FOR_INVITE, payload: { authMethod: "saml", provider: "saml", authType: loadActionType === Client.ActionType.LOAD_INVITE ? "accept_invite" : "accept_device_grant", authObjectId: needsExternalAuthError.id!, externalAuthProviderId: needsExternalAuthError.externalAuthProviderId!, orgId: needsExternalAuthError.orgId!, loadActionType: loadActionType!, emailToken, encryptionToken, }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem starting a SAML sign in session.`, (res.resultAction as any).payload ); } }); }, [needsExternalAuthError, props.core.completedInviteExternalAuth]); useEffect(() => { (async () => { if (!props.core.startingExternalAuthSessionInvite) { return; } if (runningLoop) { console.log("runningLoop already started"); return; } console.log("starting runningLoop"); runningLoop = true; await props.refreshCoreState(); while (runningLoop) { console.log("runningLoop waiting for saml invite"); await wait(500); await props.refreshCoreState(); } })(); }, [props.core.startingExternalAuthSessionInvite]); useEffect(() => { if (props.core.completedExternalAuth) { setNeedsExternalAuthError(undefined); return; } }, [props.core.completedExternalAuth]); const existingDeviceNames = useMemo(() => { if (!inviteeOrGranteeId) { return new Set<string>(); } return new Set( ( g.getActiveOrgUserDevicesByUserId(props.core.graph)[ inviteeOrGranteeId ] ?? [] ).map(({ name }) => name.trim().toLowerCase()) ); }, [props.core.graphUpdatedAt, inviteeOrGranteeId]); const deviceNameUnique = useMemo(() => { if (!deviceName) { return true; } return !existingDeviceNames.has(deviceName.trim().toLowerCase()); }, [deviceName, existingDeviceNames]); const emailTokenInvalid = emailToken && !emailToken.match(INVITE_TOKEN_REGEX); const encryptionTokenInvalid = encryptionToken && !encryptionToken.match(ENCRYPTION_TOKEN_REGEX); const externalAuthValid = !needsExternalAuthError || (needsExternalAuthError && props.core.completedExternalAuth); const formValid = (loadedInviteOrDeviceGrant && acceptActionType && externalAuthValid && deviceName && deviceNameUnique) || (!loadedInviteOrDeviceGrant && loadActionType && externalAuthValid && emailToken && !emailTokenInvalid && encryptionToken && !encryptionTokenInvalid); const numAccounts = Object.keys(props.core.orgUserAccounts).length; const shouldRedirect = Boolean( !loadedInviteOrDeviceGrant && props.ui.loadedAccountId && acceptedUserId && acceptedUserId === props.ui.loadedAccountId && props.core.orgUserAccounts[props.ui.loadedAccountId] && !awaitingMinDelay ); useEffect(() => { if (shouldRedirect) { const orgId = props.core.orgUserAccounts[props.ui.loadedAccountId!]!.orgId; props.history.push(`/org/${orgId}/welcome`); } }, [shouldRedirect]); if (shouldRedirect) { return <HomeContainer />; } const loadedOrgId = props.core.loadedInviteOrgId ?? props.core.loadedDeviceGrantOrgId; const loadedOrg = loadedOrgId ? (props.core.graph[loadedOrgId] as Model.Org) : undefined; const inviteeOrGrantee = inviteeOrGranteeId ? (props.core.graph[inviteeOrGranteeId] as Model.OrgUser) : undefined; const invitedOrGrantedBy = loadedInviteOrDeviceGrant ? (props.core.graph[ "invitedByUserId" in loadedInviteOrDeviceGrant ? loadedInviteOrDeviceGrant.invitedByUserId : loadedInviteOrDeviceGrant.grantedByUserId ] as Model.OrgUser | Model.CliUser) : undefined; let senderId: string | undefined; let sender: string | undefined; if (invitedOrGrantedBy) { if (invitedOrGrantedBy.type == "orgUser") { senderId = invitedOrGrantedBy.id; } else if (invitedOrGrantedBy.type == "cliUser") { senderId = invitedOrGrantedBy.signedById; } if (senderId) { const { email, firstName, lastName } = props.core.graph[ senderId ] as Model.OrgUser; sender = `${firstName} ${lastName} <${email}>`; } } const onLoad = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!emailToken || !encryptionToken || !loadActionType) { return; } setIsLoading(true); setIsAwaitingMinDelay(true); wait(MIN_ACTION_DELAY_MS).then(() => setIsAwaitingMinDelay(false)); props.dispatch({ type: Client.ActionType.RESET_EXTERNAL_AUTH }).then(() => props.dispatch({ type: loadActionType, payload: { emailToken, encryptionToken }, }) ); }; const onAccept = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!acceptActionType || !inviteeOrGrantee || !deviceName || !formValid) { return; } const inviteeOrGranteeId = inviteeOrGrantee.id; setIsAccepting(true); setAcceptedSender(sender); setIsAwaitingMinDelay(true); wait(MIN_ACTION_DELAY_MS).then(() => setIsAwaitingMinDelay(false)); const res = await props .dispatch({ type: acceptActionType, payload: { deviceName, emailToken, encryptionToken }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem accepting the invite.`, (res.resultAction as any)?.payload ); } return res; }); if (!res.success) { return; } props.setUiState({ accountId: inviteeOrGranteeId, loadedAccountId: inviteeOrGranteeId, lastLoadedAccountId: inviteeOrGranteeId, }); setAcceptedUserId(inviteeOrGranteeId); }; const renderButtons = () => { const samlWaiting = runningLoop || (needsExternalAuthError && !props.core.completedExternalAuth); const disabledDueToLoading = samlWaiting || !formValid || isLoading || isAccepting; let label: string; if (isLoading) { label = "Loading and Verifying..."; } else if (samlWaiting) { label = "Authenticating with SSO..."; } else if (isAccepting) { label = "Signing In..."; } else if (loadedInviteOrDeviceGrant) { label = "Sign In"; } else { label = "Next"; } return ( <div> <div className="buttons"> <input className="primary" type="submit" disabled={disabledDueToLoading} value={label} /> </div> <div className="back-link"> <a onClick={(e) => { e.preventDefault(); if (loadedInviteOrDeviceGrant) { setEmailToken(""); setEncryptionToken(""); setDeviceName(props.core.defaultDeviceName); } props.dispatch({ type: Client.ActionType.RESET_EXTERNAL_AUTH }); if (props.core.loadedInvite) { props.dispatch({ type: Client.ActionType.RESET_INVITE }); } else if (props.core.loadedDeviceGrant) { props.dispatch({ type: Client.ActionType.RESET_DEVICE_GRANT, }); } else { props.history.length > 1 ? props.history.goBack() : props.history.replace(`/home`); } }} > ← Back </a> </div> </div> ); }; /* Begin Render */ const isReadyToAccept = isAccepting || (loadedInviteOrDeviceGrant && loadedOrg && inviteeOrGrantee && sender && !isLoading); // Second screen. Invite is loaded, and need to if (isReadyToAccept) { const deviceNameInput = ( <div className="field"> <label>Device Name</label> <input type="text" placeholder="Device name" value={deviceName || ""} disabled={isAccepting} required onChange={(e) => setDeviceName(e.target.value)} autoFocus /> {deviceNameUnique || isAccepting ? ( "" ) : ( <p className="error">You already have a device with the same name</p> )} </div> ); return ( <HomeContainer> <form className={styles.AcceptInvite} onSubmit={loadedInviteOrDeviceGrant ? onAccept : onLoad} > <div className="fields"> <h3> Invitation <strong>loaded and verified.</strong> </h3> <div className="field sent-by"> <label>Sent By</label> <p> <strong>{sender ?? acceptedSender!}</strong> </p> </div> <p> Please ensure you know and trust this sender before proceeding. </p> {deviceNameInput} </div> {renderButtons()} </form> </HomeContainer> ); } // First screen helpers const loadingInviteError = props.core.loadInviteError ?? props.core.loadDeviceGrantError; const loadInviteErrorComponent = !needsExternalAuthError && loadingInviteError ? ( <p className="error"> There was a problem loading and verifying your invite. Please ensure you copied both tokens correctly and try again. </p> ) : ( "" ); // First screen render. Inputs for the tokens. Maybe wait for external auth. return ( <HomeContainer> <form className={styles.AcceptInvite} onSubmit={loadedInviteOrDeviceGrant ? onAccept : onLoad} > <div className="fields"> {loadInviteErrorComponent} <div className="field invite-token"> <label> <span className="number">1</span> <span className="label"> An <strong>Invite Token</strong>, received by email. </span> </label> <input type="password" placeholder="Paste in your Invite Token..." value={emailToken} disabled={isLoading} required autoFocus onChange={(e) => setEmailToken(e.target.value)} /> {emailTokenInvalid ? ( <p className="error">Invite Token invalid.</p> ) : ( "" )} </div> <div className="field encryption-token"> <label> <span className="number">2</span> <span className="label"> An <strong>Encryption Token</strong>, received directly from the person who invited you. </span> </label> <input type="password" placeholder="Paste in your Encryption Token..." disabled={isLoading} value={encryptionToken} required onChange={(e) => setEncryptionToken(e.target.value)} /> {encryptionTokenInvalid ? ( <p className="error">Encryption Token invalid.</p> ) : ( "" )} </div> {externalAuthErrorMessage ? ( <p className={"error"}>{externalAuthErrorMessage}</p> ) : null} </div> {renderButtons()} </form> </HomeContainer> ); };
the_stack
/* * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info. */ namespace LiteMol.Visualization.Molecule.Cartoons { "use strict"; export enum CartoonsModelType { Default, AlphaTrace }; export interface Parameters { tessalation?: number, drawingType?: CartoonsModelType, showDirectionCones?: boolean } export const DefaultCartoonsModelParameters: Parameters = { tessalation: 3, drawingType: CartoonsModelType.Default, showDirectionCones: true } export class Model extends Visualization.Model { private model: Core.Structure.Molecule.Model; private material: THREE.ShaderMaterial; private gapMaterial: THREE.MeshPhongMaterial; private directionConeMaterial: THREE.MeshPhongMaterial; private pickMaterial: THREE.Material; private queryContext: Core.Structure.Query.Context; private cartoons: Geometry.Data; protected applySelectionInternal(indices: number[], action: Selection.Action): boolean { let buffer = this.cartoons.vertexStateBuffer, array = <any>buffer.array as Float32Array, map = this.cartoons.vertexMap, vertexRanges = map.vertexRanges, changed = false, residueIndex = this.model.data.atoms.residueIndex; for (let a = 0, _a = indices.length; a < _a; a++) { let index = residueIndex[indices[a]]; a++; while (residueIndex[indices[a]] === index) { a++ } a--; if (!map.elementMap.has(index)) continue; let indexOffset = map.elementMap.get(index)!, rangeStart = map.elementRanges[2 * indexOffset], rangeEnd = map.elementRanges[2 * indexOffset + 1]; if (rangeStart === rangeEnd) continue; for (let i = rangeStart; i < rangeEnd; i += 2) { let vStart = vertexRanges[i], vEnd = vertexRanges[i + 1]; changed = Selection.applyActionToRange(array, vStart, vEnd, action) || changed; } } if (!changed) return false; buffer.needsUpdate = true; return true; } getPickElements(pickId: number): number[] { let { atomStartIndex, atomEndIndex } = this.model.data.residues; let elements: number[] = []; for (let i = atomStartIndex[pickId], _b = atomEndIndex[pickId]; i < _b; i++) { if (this.queryContext.hasAtom(i)) elements.push(i); } return elements; } highlightElement(pickId: number, highlight: boolean): boolean { return this.applySelection([this.model.data.residues.atomStartIndex[pickId]], highlight ? Selection.Action.Highlight : Selection.Action.RemoveHighlight); } protected highlightInternal(isOn: boolean) { return Selection.applyActionToBuffer(this.cartoons.vertexStateBuffer, isOn ? Selection.Action.Highlight : Selection.Action.RemoveHighlight); } private applyColoring(theme: Theme) { let {atomStartIndex, atomEndIndex} = this.model.data.residues; let color = { r: 0.1, g: 0.1, b: 0.1 }; let avgColor = { r: 0.1, g: 0.1, b: 0.1 }; let map = this.cartoons.vertexMap; let bufferAttribute: THREE.BufferAttribute = (<any>this.cartoons.geometry.attributes).color; let buffer = bufferAttribute.array; let vertexRanges = map.vertexRanges for (let rI = 0, _bRi = this.model.data.residues.count; rI < _bRi; rI++) { avgColor.r = 0; avgColor.g = 0; avgColor.b = 0; let count = 0; for (let aI = atomStartIndex[rI], _bAi = atomEndIndex[rI]; aI < _bAi; aI++) { if (!this.queryContext.hasAtom(aI)) continue; theme.setElementColor(aI, color); avgColor.r += color.r; avgColor.g += color.g; avgColor.b += color.b; count++; } if (!count) continue; color.r = avgColor.r / count; color.g = avgColor.g / count; color.b = avgColor.b / count; let elementOffset = map.elementMap.get(rI)!; let rangeStart = map.elementRanges[2 * elementOffset], rangeEnd = map.elementRanges[2 * elementOffset + 1]; if (rangeStart === rangeEnd) continue; for (let i = rangeStart; i < rangeEnd; i += 2) { let vStart = vertexRanges[i], vEnd = vertexRanges[i + 1]; for (let j = vStart; j < vEnd; j++) { buffer[j * 3] = color.r, buffer[j * 3 + 1] = color.g, buffer[j * 3 + 2] = color.b; } } } bufferAttribute.needsUpdate = true; // const gapColor = Theme.getColor(theme, 'Gap', Colors.DefaultBondColor); // const gc = this.gapMaterial.color; // if (gapColor.r !== gc.r || gapColor.g !== gc.g || gapColor.b !== gc.b) { // this.gapMaterial.color = new THREE.Color(gapColor.r, gapColor.g, gapColor.b); // this.gapMaterial.needsUpdate = true; // } // const dcColor = Theme.getColor(theme, 'DirectionCone', Colors.DefaultCartoonDirectionConeColor); // const dc = this.gapMaterial.color; // if (dcColor.r !== dc.r || dcColor.g !== dc.g || dcColor.b !== dc.b) { // this.directionConeMaterial.color = new THREE.Color(dcColor.r, dcColor.g, dcColor.b); // this.directionConeMaterial.needsUpdate = true; // } } protected applyThemeInternal(theme: Theme) { this.applyColoring(theme); MaterialsHelper.updateMaterial(this.material, theme, this.object); MaterialsHelper.updateMaterial(this.gapMaterial, theme, this.object); MaterialsHelper.updateMaterial(this.directionConeMaterial, theme, this.object); } private createObjects(): { main: THREE.Object3D; pick: THREE.Object3D } { const main = new THREE.Object3D(); main.add(new THREE.Mesh(this.cartoons.geometry, this.material)) if (this.cartoons.gapsGeometry) { main.add(new THREE.Mesh(this.cartoons.gapsGeometry, this.gapMaterial)); } if (this.cartoons.directionConesGeometry) { main.add(new THREE.Mesh(this.cartoons.directionConesGeometry, this.directionConeMaterial)); } return { main: main.children.length > 1 ? main : main.children[0], pick: new THREE.Mesh(this.cartoons.pickGeometry, this.pickMaterial) }; } static create(entity: any, { model, queryContext, atomIndices, theme, params, props }: { model: Core.Structure.Molecule.Model; queryContext: Core.Structure.Query.Context, atomIndices: number[]; theme: Theme; params: Parameters; props?: Model.Props }): Core.Computation<Model> { return Core.computation<Model>(async ctx => { let linearSegments = 0, radialSements = 0; await ctx.updateProgress('Computing cartoons...'); params = Core.Utils.extend({}, params, DefaultCartoonsModelParameters); switch (params.tessalation) { case 0: linearSegments = 2; radialSements = 2; break; case 1: linearSegments = 4; radialSements = 3; break; case 2: linearSegments = 6; radialSements = 5; break; case 3: linearSegments = 10; radialSements = 8; break; case 4: linearSegments = 12; radialSements = 10; break; case 5: linearSegments = 16; radialSements = 14; break; default: linearSegments = 18; radialSements = 16; break; } let cartoons = await Geometry.create(model, atomIndices, linearSegments, { radialSegmentCount: radialSements, tessalation: +params.tessalation!, showDirectionCones: !!params.showDirectionCones }, params.drawingType === CartoonsModelType.AlphaTrace, ctx) let ret = new Model(); ret.cartoons = cartoons; ret.queryContext = queryContext; ret.material = MaterialsHelper.getMeshMaterial(); ret.gapMaterial = new THREE.MeshPhongMaterial({ color: 0x777777, shading: THREE.FlatShading }); ret.directionConeMaterial = new THREE.MeshPhongMaterial({ color: 0x999999, shading: THREE.FlatShading }); ret.pickMaterial = MaterialsHelper.getPickMaterial(); if (props) ret.props = props; ret.entity = entity; ret.cartoons.geometry.computeBoundingSphere(); ret.centroid = ret.cartoons.geometry.boundingSphere.center; ret.radius = ret.cartoons.geometry.boundingSphere.radius; let obj = ret.createObjects(); ret.object = obj.main; ret.pickObject = obj.pick; ret.pickBufferAttributes = [(<any>ret.cartoons.pickGeometry.attributes).pColor]; ret.model = model; ret.applyTheme(theme); ret.disposeList.push(ret.cartoons, ret.material, ret.pickMaterial, ret.gapMaterial, ret.directionConeMaterial); return ret; }); } } }
the_stack
var ast = require('./SwiftAst') function makeFile(file: any[], accessLevel: string, globalAttrs: GlobalAttrs, filename: string): string[] { const accessLevelPrefix = accessLevel == null ? '' : accessLevel + ' ' function constructorExists(struct: Struct) : boolean { const paramNames = struct.varDecls.map(vd => vd.name + ':') const paramTypes = struct.varDecls.map(vd => typeString(vd.type)) const paramsString = paramNames.join('') + '||' + paramTypes.join(', ') const constructors = globalAttrs.constructors[struct.baseName] || [] return constructors.contains(paramsString); } function decoderExists(typeName: string) : boolean { return globalAttrs.decoders.contains(typeName); } function encoderExists(typeName: string) : boolean { return globalAttrs.encoders.contains(typeName); } var structs = ast.structs(file, globalAttrs.typeAliases) .filter(s => !constructorExists(s) || !decoderExists(s.baseName) || !encoderExists(s.baseName)); var enums = ast.enums(file, globalAttrs.typeAliases) .filter(e => !decoderExists(e.baseName) || !encoderExists(e.baseName)); var lines = []; lines.push('//'); lines.push('// ' + filename); lines.push('//'); lines.push('// Auto generated by swift-json-gen on ' + new Date().toUTCString()); lines.push('// See for details: https://github.com/tomlokhorst/swift-json-gen') lines.push('//'); lines.push(''); lines.push('import Foundation'); lines.push('import Statham'); lines.push(''); enums.forEach(function (s) { var createDecoder = !decoderExists(s.baseName); var createEncoder = !encoderExists(s.baseName); lines.push('extension ' + escaped(s.baseName) + ' {') if (createDecoder) { lines = lines.concat(makeEnumDecoder(s, accessLevelPrefix)); } if (createDecoder && createEncoder) { lines.push(''); } if (createEncoder) { lines = lines.concat(makeEnumEncoder(s, accessLevelPrefix)); } lines.push('}'); lines.push(''); }); structs.forEach(function (s) { var createConstructor = !constructorExists(s); var createDecoder = !decoderExists(s.baseName); var createEncoder = !encoderExists(s.baseName); lines.push('extension ' + escaped(s.baseName) + ' {') if (createDecoder) { lines = lines.concat(makeStructDecoder(s, accessLevelPrefix)); } if (createDecoder && (createConstructor || createEncoder)) { lines.push(''); } if (createConstructor) { lines = lines.concat(makeStructConstructor(s, accessLevelPrefix)); } if (createConstructor && createEncoder) { lines.push(''); } if (createEncoder) { lines = lines.concat(makeStructEncoder(s, enums, accessLevelPrefix)); } lines.push('}'); lines.push(''); }); return lines; } exports.makeFile = makeFile; function makeEnumDecoder(en: Enum, accessLevelPrefix: string) : string { var lines = []; lines.push(' ' + accessLevelPrefix + 'static func decodeJson(_ json: Any) throws -> ' + escaped(en.baseName) + ' {'); lines.push(' guard let rawValue = json as? ' + escaped(en.rawTypeName) + ' else {'); lines.push(' throw JsonDecodeError.wrongType(rawValue: json, expectedType: "' + en.rawTypeName + '")'); lines.push(' }'); lines.push(' guard let value = ' + escaped(en.baseName) + '(rawValue: rawValue) else {'); lines.push(' throw JsonDecodeError.wrongEnumRawValue(rawValue: rawValue, enumType: "' + en.baseName + '")'); lines.push(' }'); lines.push(''); lines.push(' return value'); lines.push(' }'); return lines.join('\n'); } function makeEnumEncoder(en: Enum, accessLevelPrefix: string) : string { var lines = []; lines.push(' ' + accessLevelPrefix + 'func encodeJson() -> ' + escaped(en.rawTypeName) + ' {'); lines.push(' return rawValue'); lines.push(' }'); return lines.join('\n'); } function makeStructConstructor(struct: Struct, accessLevelPrefix: string) : string { var lines = []; const paramsStrings = struct.varDecls.map(vd => vd.name + ': ' + typeString(vd.type)) lines.push('fileprivate init(' + paramsStrings.join(', ') + ') {'); struct.varDecls.forEach(varDecl => { lines.push(' self.' + varDecl.name + ' = ' + escaped(varDecl.name)) }) lines.push('}'); return lines.map(indent(2)).join('\n'); } function makeStructDecoder(struct: Struct, accessLevelPrefix: string) : string { var lines = []; var curried = struct.typeArguments.length > 0; if (curried) { lines.push(' ' + accessLevelPrefix + 'static func decodeJson' + decodeArguments(struct) + ' -> (Any) throws -> ' + escaped(struct.baseName) + ' {'); lines.push(' return { json in'); } else { lines.push(' ' + accessLevelPrefix + 'static func decodeJson(_ json: Any) throws -> ' + escaped(struct.baseName) + ' {'); } var body = makeStructDecoderBody(struct).map(indent(curried ? 6 : 4)); lines = lines.concat(body); if (curried) { lines.push(' }'); } lines.push(' }'); return lines.join('\n'); } function decodeArguments(struct: Struct) : string { var parts = struct.typeArguments .map(typeVar => '_ decode' + typeVar + ': @escaping (Any) throws -> ' + escaped(typeVar)) return '(' + parts.join(', ') + ')'; } function makeStructDecoderBody(struct: Struct) : string[] { if (struct.varDecls.length == 0) { return ['return ' + struct.baseName + '()']; } var lines = []; lines.push('let decoder = try JsonDecoder(json: json)'); lines.push(''); struct.varDecls.forEach(function (field, ix) { var decoder = decodeFunction(field.type, struct.typeArguments) var line = 'let _' + field.name + ' = ' + 'try decoder.decode("' + field.name + '", decoder: ' + decoder + ')'; lines.push(line) }); lines.push(''); var fieldDecodes = struct.varDecls.map(function (field, ix) { var isLast = struct.varDecls.length == ix + 1 var commaOrBrace = isLast ? '' : ',' var line = 'let ' + escaped(field.name) + ' = _' + field.name + commaOrBrace; return line }); if (fieldDecodes.length == 1) { lines.push('guard ' + fieldDecodes[0] + ' else {'); } else { lines.push('guard'); lines = lines.concat(fieldDecodes.map(indent(2))); lines.push('else {'); } var params = struct.varDecls.map(decl => decl.name + ': ' + escaped(decl.name)) lines.push(' throw JsonDecodeError.structErrors(type: "' + struct.baseName + '", errors: decoder.errors)') lines.push('}'); lines.push('') lines.push('return ' + escaped(struct.baseName) + '(' + params.join(', ') + ')') return lines } function typeString(type: Type) : string { var args = type.genericArguments .map(typeString) var argList = args.length ? '<' + args.join(', ') + '>' : ''; var typeName = type.alias || type.baseName; if (typeName == 'Optional' && args.length == 1) { return args[0] + '?' } if (typeName == 'Array' && args.length == 1) { return '[' + args[0] + ']' } if (typeName == 'Dictionary' && args.length == 2) { return '[' + args[0] + ' : ' + args[1] + ']' } if (type.alias) { return type.alias; } return typeName + argList; } function decodeFunction(type: Type, genericDecoders: string[]) : string { if (isKnownType(type)) return '{ $0 }'; var args = type.genericArguments .map(a => decodeFunction(a, genericDecoders)) .join(', '); var argList = args.length ? '(' + args + ')' : ''; var typeName = type.alias || type.baseName; if (genericDecoders.contains(typeName)) return 'decode' + typeName + argList; return typeName + '.decodeJson' + argList; } function makeStructEncoder(struct: Struct, enums: Enum[], accessLevelPrefix: string) : string { var lines = []; lines.push(' ' + accessLevelPrefix + 'func encodeJson' + encodeArguments(struct) + ' -> [String: Any] {'); var body = makeStructEncoderBody(struct, enums).map(indent(4)); lines = lines.concat(body); lines.push(' }'); return lines.join('\n'); } function encodeArguments(struct: Struct) : string { var parts = struct.typeArguments .map(typeVar => '_ encode' + typeVar + ': (' + escaped(typeVar) + ') -> Any') return '(' + parts.join(', ') + ')'; } function makeStructEncoderBody(struct: Struct, enums: Enum[]) : string[] { if (struct.varDecls.length == 0) { return ['return [:]']; } var lines = []; lines.push('var dict: [String: Any] = [:]'); lines.push(''); struct.varDecls.forEach(function (d) { var subs = makeFieldEncode(d, struct.typeArguments, enums); lines = lines.concat(subs); }); lines.push(''); lines.push('return dict'); return lines; } function encodeFunction(name: string, type: Type, genericEncoders: string[]) : string { if (isKnownType(type)) return name; if (genericEncoders.contains(type.baseName)) return 'encode' + type.baseName + '(' + name + ')'; var args = type.genericArguments .map(t => '{ ' + encodeFunction('$0', t, genericEncoders) + ' }') .join(', '); return escaped(name) + '.encodeJson(' + args + ')'; } function makeFieldEncode(field: VarDecl, structTypeArguments: string[], enums: Enum[]) { var lines = []; var name = field.name; var type = field.type; var prefix = '' if (type.baseName == 'Dictionary' && type.genericArguments.length == 2) { var keyType = type.genericArguments[0].baseName; var enum_ = enums.filter(e => e.baseName == keyType)[0]; if (keyType != 'String' && enum_.rawTypeName != 'String') { lines.push('/* WARNING: Json only supports Strings as keys in dictionaries */'); } } lines.push('dict["' + name + '"] = ' + encodeFunction(name, type, structTypeArguments)); return lines; } function indent(nr) { return function (s) { return s == '' ? s : Array(nr + 1).join(' ') + s; }; } function isKnownType(type: Type) : boolean { var types = [ 'Any', 'AnyObject', 'AnyJson' ]; return types.contains(type.alias) || types.contains(type.baseName); } // Copied from R.swift: // Based on https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID413 let swiftKeywords = [ // Keywords used in declarations "associatedtype", "class", "deinit", "enum", "extension", "func", "import", "init", "inout", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var", // Keywords used in statements "break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while", // Keywords used in expressions and types "as", "catch", "dynamicType", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw", "throws", "true", "try", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", ] function escaped(name: string) : string { if (swiftKeywords.contains(name)) { return '`' + name + '`' } else { return name } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [discovery](https://docs.aws.amazon.com/service-authorization/latest/reference/list_applicationdiscovery.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Discovery extends PolicyStatement { public servicePrefix = 'discovery'; /** * Statement provider for service [discovery](https://docs.aws.amazon.com/service-authorization/latest/reference/list_applicationdiscovery.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Associates one or more configuration items with an application. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_AssociateConfigurationItemsToApplication.html */ public toAssociateConfigurationItemsToApplication() { return this.to('AssociateConfigurationItemsToApplication'); } /** * Deletes one or more Migration Hub import tasks, each identified by their import ID. Each import task has a number of records, which can identify servers or applications. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_BatchDeleteImportData.html */ public toBatchDeleteImportData() { return this.to('BatchDeleteImportData'); } /** * Creates an application with the given name and description. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_CreateApplication.html */ public toCreateApplication() { return this.to('CreateApplication'); } /** * Creates one or more tags for configuration items. Tags are metadata that help you categorize IT assets. This API accepts a list of multiple configuration items. * * Access Level: Tagging * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_CreateTags.html */ public toCreateTags() { return this.to('CreateTags'); } /** * Deletes a list of applications and their associations with configuration items. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DeleteApplications.html */ public toDeleteApplications() { return this.to('DeleteApplications'); } /** * Deletes the association between configuration items and one or more tags. This API accepts a list of multiple configuration items. * * Access Level: Tagging * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DeleteTags.html */ public toDeleteTags() { return this.to('DeleteTags'); } /** * Lists agents or the Connector by ID or lists all agents/Connectors associated with your user account if you did not specify an ID. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeAgents.html */ public toDescribeAgents() { return this.to('DescribeAgents'); } /** * Retrieves attributes for a list of configuration item IDs. All of the supplied IDs must be for the same asset type (server, application, process, or connection). Output fields are specific to the asset type selected. For example, the output for a server configuration item includes a list of attributes about the server, such as host name, operating system, and number of network cards. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeConfigurations.html */ public toDescribeConfigurations() { return this.to('DescribeConfigurations'); } /** * Lists exports as specified by ID. All continuous exports associated with your user account can be listed if you call DescribeContinuousExports as is without passing any parameters. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeContinuousExports.html */ public toDescribeContinuousExports() { return this.to('DescribeContinuousExports'); } /** * Retrieves the status of a given export process. You can retrieve status from a maximum of 100 processes. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeExportConfigurations.html */ public toDescribeExportConfigurations() { return this.to('DescribeExportConfigurations'); } /** * Retrieve status of one or more export tasks. You can retrieve the status of up to 100 export tasks. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeExportTasks.html */ public toDescribeExportTasks() { return this.to('DescribeExportTasks'); } /** * Returns an array of import tasks for your account, including status information, times, IDs, the Amazon S3 Object URL for the import file, and more. * * Access Level: List * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeImportTasks.html */ public toDescribeImportTasks() { return this.to('DescribeImportTasks'); } /** * Retrieves a list of configuration items that are tagged with a specific tag. Or retrieves a list of all tags assigned to a specific configuration item. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DescribeTags.html */ public toDescribeTags() { return this.to('DescribeTags'); } /** * Disassociates one or more configuration items from an application. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_DisassociateConfigurationItemsFromApplication.html */ public toDisassociateConfigurationItemsFromApplication() { return this.to('DisassociateConfigurationItemsFromApplication'); } /** * Exports all discovered configuration data to an Amazon S3 bucket or an application that enables you to view and evaluate the data. Data includes tags and tag associations, processes, connections, servers, and system performance. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_ExportConfigurations.html */ public toExportConfigurations() { return this.to('ExportConfigurations'); } /** * Retrieves a short summary of discovered assets. * * Access Level: Read * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_GetDiscoverySummary.html */ public toGetDiscoverySummary() { return this.to('GetDiscoverySummary'); } /** * Retrieves a list of configuration items according to criteria you specify in a filter. The filter criteria identify relationship requirements. * * Access Level: List * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_ListConfigurations.html */ public toListConfigurations() { return this.to('ListConfigurations'); } /** * Retrieves a list of servers which are one network hop away from a specified server. * * Access Level: List * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_ListServerNeighbors.html */ public toListServerNeighbors() { return this.to('ListServerNeighbors'); } /** * Start the continuous flow of agent's discovered data into Amazon Athena. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_StartContinuousExport.html */ public toStartContinuousExport() { return this.to('StartContinuousExport'); } /** * Instructs the specified agents or Connectors to start collecting data. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_StartDataCollectionByAgentIds.html */ public toStartDataCollectionByAgentIds() { return this.to('StartDataCollectionByAgentIds'); } /** * Export the configuration data about discovered configuration items and relationships to an S3 bucket in a specified format. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_StartExportTask.html */ public toStartExportTask() { return this.to('StartExportTask'); } /** * Starts an import task. The Migration Hub import feature allows you to import details of your on-premises environment directly into AWS without having to use the Application Discovery Service (ADS) tools such as the Discovery Connector or Discovery Agent. This gives you the option to perform migration assessment and planning directly from your imported data including the ability to group your devices as applications and track their migration status. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_StartImportTask.html */ public toStartImportTask() { return this.to('StartImportTask'); } /** * Stop the continuous flow of agent's discovered data into Amazon Athena. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_StopContinuousExport.html */ public toStopContinuousExport() { return this.to('StopContinuousExport'); } /** * Instructs the specified agents or Connectors to stop collecting data. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_StopDataCollectionByAgentIds.html */ public toStopDataCollectionByAgentIds() { return this.to('StopDataCollectionByAgentIds'); } /** * Updates metadata about an application. * * Access Level: Write * * https://docs.aws.amazon.com/application-discovery/latest/APIReference/API_UpdateApplication.html */ public toUpdateApplication() { return this.to('UpdateApplication'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateConfigurationItemsToApplication", "BatchDeleteImportData", "CreateApplication", "DeleteApplications", "DisassociateConfigurationItemsFromApplication", "ExportConfigurations", "StartContinuousExport", "StartDataCollectionByAgentIds", "StartExportTask", "StartImportTask", "StopContinuousExport", "StopDataCollectionByAgentIds", "UpdateApplication" ], "Tagging": [ "CreateTags", "DeleteTags" ], "Read": [ "DescribeAgents", "DescribeConfigurations", "DescribeContinuousExports", "DescribeExportConfigurations", "DescribeExportTasks", "DescribeTags", "GetDiscoverySummary" ], "List": [ "DescribeImportTasks", "ListConfigurations", "ListServerNeighbors" ] }; }
the_stack
import { Constants } from "../Engines/constants"; import { Engine } from "../Engines/engine"; import { Effect } from "../Materials/effect"; import { MultiRenderTarget } from "../Materials/Textures/multiRenderTarget"; import { InternalTextureCreationOptions } from "../Materials/Textures/textureCreationOptions"; import { Color4 } from "../Maths/math.color"; import { SubMesh } from "../Meshes/subMesh"; import { SmartArray } from "../Misc/smartArray"; import { Scene } from "../scene"; import { ThinTexture } from "../Materials/Textures/thinTexture"; import { EffectRenderer, EffectWrapper } from "../Materials/effectRenderer"; import { PrePassEffectConfiguration } from "./prePassEffectConfiguration"; import { PrePassRenderer } from "./prePassRenderer"; import { InternalTexture } from "../Materials/Textures/internalTexture"; import { Logger } from "../Misc/logger"; import "../Shaders/postprocess.vertex"; import "../Shaders/oitFinal.fragment"; import "../Shaders/oitBackBlend.fragment"; class DepthPeelingEffectConfiguration implements PrePassEffectConfiguration { /** * Is this effect enabled */ public enabled = true; /** * Name of the configuration */ public name = "depthPeeling"; /** * Textures that should be present in the MRT for this effect to work */ public readonly texturesRequired: number[] = [Constants.PREPASS_COLOR_TEXTURE_TYPE]; } /** * The depth peeling renderer that performs * Order independant transparency (OIT). * This should not be instanciated directly, as it is part of a scene component */ export class DepthPeelingRenderer { private _scene: Scene; private _engine: Engine; private _depthMrts: MultiRenderTarget[]; private _thinTextures: ThinTexture[] = []; private _colorMrts: MultiRenderTarget[]; private _blendBackMrt: MultiRenderTarget; private _blendBackEffectWrapper: EffectWrapper; private _finalEffectWrapper: EffectWrapper; private _effectRenderer: EffectRenderer; private _passCount: number; private _currentPingPongState: number = 0; private _prePassEffectConfiguration: DepthPeelingEffectConfiguration; private _blendBackTexture: InternalTexture; private _layoutCache = [[true], [true, true], [true, true, true]]; private static _DEPTH_CLEAR_VALUE = -99999.0; private static _MIN_DEPTH = 0; private static _MAX_DEPTH = 1; private _colorCache = [ new Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE, DepthPeelingRenderer._DEPTH_CLEAR_VALUE, 0, 0), new Color4(-DepthPeelingRenderer._MIN_DEPTH, DepthPeelingRenderer._MAX_DEPTH, 0, 0), new Color4(0, 0, 0, 0) ]; /** * Instanciates the depth peeling renderer * @param scene Scene to attach to * @param passCount Number of depth layers to peel * @returns The depth peeling renderer */ constructor(scene: Scene, passCount: number = 5) { this._scene = scene; this._engine = scene.getEngine(); this._passCount = passCount; // We need a depth texture for opaque if (!scene.enablePrePassRenderer()) { Logger.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting."); return; } this._prePassEffectConfiguration = new DepthPeelingEffectConfiguration(); this._createTextures(); this._createEffects(); } private _createTextures() { const size = { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight(), }; // 2 for ping pong this._depthMrts = [new MultiRenderTarget("depthPeelingDepth0", size, 1, this._scene), new MultiRenderTarget("depthPeelingDepth1", size, 1, this._scene)]; this._colorMrts = [new MultiRenderTarget("depthPeelingColor0", size, 1, this._scene), new MultiRenderTarget("depthPeelingColor1", size, 1, this._scene)]; this._blendBackMrt = new MultiRenderTarget("depthPeelingBack", size, 1, this._scene); // 0 is a depth texture // 1 is a color texture const optionsArray = [ { format: Constants.TEXTUREFORMAT_RG, samplingMode: Constants.TEXTURE_NEAREST_SAMPLINGMODE, type: Constants.TEXTURETYPE_FLOAT, } as InternalTextureCreationOptions, { format: Constants.TEXTUREFORMAT_RGBA, samplingMode: Constants.TEXTURE_NEAREST_SAMPLINGMODE, type: Constants.TEXTURETYPE_HALF_FLOAT, } as InternalTextureCreationOptions, ]; for (let i = 0; i < 2; i++) { const depthTexture = this._engine._createInternalTexture(size, optionsArray[0]); const frontColorTexture = this._engine._createInternalTexture(size, optionsArray[1]); const backColorTexture = this._engine._createInternalTexture(size, optionsArray[1]); this._depthMrts[i].setInternalTexture(depthTexture, 0); this._depthMrts[i].setInternalTexture(frontColorTexture, 1); this._depthMrts[i].setInternalTexture(backColorTexture, 2); this._colorMrts[i].setInternalTexture(frontColorTexture, 0); this._colorMrts[i].setInternalTexture(backColorTexture, 1); this._thinTextures.push(new ThinTexture(depthTexture), new ThinTexture(frontColorTexture), new ThinTexture(backColorTexture)); } } private _disposeTextures() { for (let i = 0; i < this._thinTextures.length; i++) { if (i === 6) { // Do not dispose the shared texture with the prepass continue; } this._thinTextures[i].dispose(); } for (let i = 0; i < 2; i++) { this._depthMrts[i].dispose(true); this._colorMrts[i].dispose(true); this._blendBackMrt.dispose(true); } this._thinTextures = []; this._colorMrts = []; this._depthMrts = []; } private _updateTextures() { if (this._depthMrts[0].getSize().width !== this._engine.getRenderWidth() || this._depthMrts[0].getSize().height !== this._engine.getRenderHeight()) { this._disposeTextures(); this._createTextures(); } return this._updateTextureReferences(); } private _updateTextureReferences() { const prePassRenderer = this._scene.prePassRenderer; if (!prePassRenderer) { return false; } // Retrieve opaque color texture const textureIndex = prePassRenderer.getIndex(Constants.PREPASS_COLOR_TEXTURE_TYPE); const prePassTexture = prePassRenderer.defaultRT.textures?.length ? prePassRenderer.defaultRT.textures[textureIndex].getInternalTexture() : null; if (!prePassTexture) { return false; } if (this._blendBackTexture !== prePassTexture) { this._blendBackTexture = prePassTexture; this._blendBackMrt.setInternalTexture(this._blendBackTexture, 0); if (this._thinTextures[6]) { this._thinTextures[6].dispose(); } this._thinTextures[6] = new ThinTexture(this._blendBackTexture); prePassRenderer.defaultRT.renderTarget!._shareDepth(this._depthMrts[0].renderTarget!); } return true; } private _createEffects() { this._blendBackEffectWrapper = new EffectWrapper({ fragmentShader: "oitBackBlend", useShaderStore: true, engine: this._engine, samplerNames: ["uBackColor"], uniformNames: [], }); this._finalEffectWrapper = new EffectWrapper({ fragmentShader: "oitFinal", useShaderStore: true, engine: this._engine, samplerNames: ["uFrontColor", "uBackColor"], uniformNames: [], }); this._effectRenderer = new EffectRenderer(this._engine); } /** * Links to the prepass renderer * @param prePassRenderer The scene PrePassRenderer */ public setPrePassRenderer(prePassRenderer: PrePassRenderer) { prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration); } /** * Binds depth peeling textures on an effect * @param effect The effect to bind textures on */ public bind(effect: Effect) { effect.setTexture("oitDepthSampler", this._thinTextures[this._currentPingPongState * 3]); effect.setTexture("oitFrontColorSampler", this._thinTextures[this._currentPingPongState * 3 + 1]); } private _renderSubMeshes(transparentSubMeshes: SmartArray<SubMesh>) { for (let j = 0; j < transparentSubMeshes.length; j++) { const material = transparentSubMeshes.data[j].getMaterial(); let previousShaderHotSwapping = true; let previousBFC = false; if (material) { previousShaderHotSwapping = material.allowShaderHotSwapping; previousBFC = material.backFaceCulling; material.allowShaderHotSwapping = false; material.backFaceCulling = false; } transparentSubMeshes.data[j].render(false); if (material) { material.allowShaderHotSwapping = previousShaderHotSwapping; material.backFaceCulling = previousBFC; } } } private _finalCompose(writeId: number) { this._engine._bindUnboundFramebuffer(null); this._engine.setAlphaMode(Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA); this._engine._alphaState.alphaBlend = false; this._engine.applyStates(); this._engine.enableEffect(this._finalEffectWrapper._drawWrapper); this._finalEffectWrapper.effect.setTexture("uFrontColor", this._thinTextures[writeId * 3 + 1]); this._finalEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[6]); this._effectRenderer.render(this._finalEffectWrapper); } /** * Renders transparent submeshes with depth peeling * @param transparentSubMeshes List of transparent meshes to render */ public render(transparentSubMeshes: SmartArray<SubMesh>): void { if (!this._blendBackEffectWrapper.effect.isReady() || !this._finalEffectWrapper.effect.isReady() || !this._updateTextures()) { return; } if (!transparentSubMeshes.length) { this._finalCompose(1); return; } (this._scene.prePassRenderer! as any)._enabled = false; // Clears this._engine.bindFramebuffer(this._depthMrts[0].renderTarget!); let attachments = this._engine.buildTextureLayout(this._layoutCache[0]); this._engine.bindAttachments(attachments); this._engine.clear(this._colorCache[0], true, false, false); this._engine.bindFramebuffer(this._depthMrts[1].renderTarget!); this._engine.clear(this._colorCache[1], true, false, false); this._engine.bindFramebuffer(this._colorMrts[0].renderTarget!); attachments = this._engine.buildTextureLayout(this._layoutCache[1]); this._engine.bindAttachments(attachments); this._engine.clear(this._colorCache[2], true, false, false); this._engine.bindFramebuffer(this._colorMrts[1].renderTarget!); this._engine.clear(this._colorCache[2], true, false, false); // Draw depth for first pass this._engine.bindFramebuffer(this._depthMrts[0].renderTarget!); attachments = this._engine.buildTextureLayout(this._layoutCache[0]); this._engine.bindAttachments(attachments); this._engine.setAlphaEquation(Constants.ALPHA_EQUATION_MAX); this._engine._alphaState.alphaBlend = true; this._engine.depthCullingState.depthMask = false; this._engine.depthCullingState.depthTest = true; this._engine.depthCullingState.cull = false; this._engine.applyStates(); this._currentPingPongState = 1; // Render this._renderSubMeshes(transparentSubMeshes); // depth peeling ping-pong let readId = 0; let writeId = 0; for (let i = 0; i < this._passCount; i++) { readId = i % 2; writeId = 1 - readId; this._currentPingPongState = readId; // Clears this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget!); attachments = this._engine.buildTextureLayout(this._layoutCache[0]); this._engine.bindAttachments(attachments); this._engine.clear(this._colorCache[0], true, false, false); this._engine.bindFramebuffer(this._colorMrts[writeId].renderTarget!); attachments = this._engine.buildTextureLayout(this._layoutCache[1]); this._engine.bindAttachments(attachments); this._engine.clear(this._colorCache[2], true, false, false); this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget!); attachments = this._engine.buildTextureLayout(this._layoutCache[2]); this._engine.bindAttachments(attachments); this._engine.setAlphaEquation(Constants.ALPHA_EQUATION_MAX); this._engine._alphaState.alphaBlend = true; this._engine.depthCullingState.depthTest = false; this._engine.applyStates(); // Render this._renderSubMeshes(transparentSubMeshes); // Back color this._engine.bindFramebuffer(this._blendBackMrt.renderTarget!); attachments = this._engine.buildTextureLayout(this._layoutCache[0]); this._engine.bindAttachments(attachments); this._engine.setAlphaEquation(Constants.ALPHA_EQUATION_ADD); this._engine.setAlphaMode(Constants.ALPHA_LAYER_ACCUMULATE); this._engine.applyStates(); this._engine.enableEffect(this._blendBackEffectWrapper._drawWrapper); this._blendBackEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[writeId * 3 + 2]); this._effectRenderer.render(this._blendBackEffectWrapper); } // Final composition on default FB this._finalCompose(writeId); (this._scene.prePassRenderer! as any)._enabled = true; this._engine.depthCullingState.depthMask = true; } /** * Disposes the depth peeling renderer and associated ressources */ public dispose() { this._disposeTextures(); this._blendBackEffectWrapper.dispose(); this._finalEffectWrapper.dispose(); this._effectRenderer.dispose(); } }
the_stack
// SVGPathSeg API polyfill // https://github.com/progers/pathseg // // This is a drop-in replacement for the SVGPathSeg and SVGPathSegList APIs that were removed from // SVG2 (https://lists.w3.org/Archives/Public/www-svg/2015Jun/0044.html), including the latest spec // changes which were implemented in Firefox 43 and Chrome 46. ;(function() { 'use strict' if (!('SVGPathSeg' in window)) { // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg window.SVGPathSeg = function(type, typeAsLetter, owningPathSegList) { this.pathSegType = type this.pathSegTypeAsLetter = typeAsLetter this._owningPathSegList = owningPathSegList } window.SVGPathSeg.prototype.classname = 'SVGPathSeg' window.SVGPathSeg.PATHSEG_UNKNOWN = 0 window.SVGPathSeg.PATHSEG_CLOSEPATH = 1 window.SVGPathSeg.PATHSEG_MOVETO_ABS = 2 window.SVGPathSeg.PATHSEG_MOVETO_REL = 3 window.SVGPathSeg.PATHSEG_LINETO_ABS = 4 window.SVGPathSeg.PATHSEG_LINETO_REL = 5 window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6 window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7 window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8 window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9 window.SVGPathSeg.PATHSEG_ARC_ABS = 10 window.SVGPathSeg.PATHSEG_ARC_REL = 11 window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12 window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13 window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14 window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15 window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16 window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17 window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18 window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19 // Notify owning PathSegList on any changes so they can be synchronized back to the path element. window.SVGPathSeg.prototype._segmentChanged = function() { if (this._owningPathSegList) this._owningPathSegList.segmentChanged(this) } window.SVGPathSegClosePath = function(owningPathSegList) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CLOSEPATH, 'z', owningPathSegList ) } window.SVGPathSegClosePath.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegClosePath.prototype.toString = function() { return '[object SVGPathSegClosePath]' } window.SVGPathSegClosePath.prototype._asPathString = function() { return this.pathSegTypeAsLetter } window.SVGPathSegClosePath.prototype.clone = function() { return new window.SVGPathSegClosePath(undefined) } window.SVGPathSegMovetoAbs = function(owningPathSegList, x, y) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_MOVETO_ABS, 'M', owningPathSegList ) this._x = x this._y = y } window.SVGPathSegMovetoAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegMovetoAbs.prototype.toString = function() { return '[object SVGPathSegMovetoAbs]' } window.SVGPathSegMovetoAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y } window.SVGPathSegMovetoAbs.prototype.clone = function() { return new window.SVGPathSegMovetoAbs(undefined, this._x, this._y) } Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) window.SVGPathSegMovetoRel = function(owningPathSegList, x, y) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_MOVETO_REL, 'm', owningPathSegList ) this._x = x this._y = y } window.SVGPathSegMovetoRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegMovetoRel.prototype.toString = function() { return '[object SVGPathSegMovetoRel]' } window.SVGPathSegMovetoRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y } window.SVGPathSegMovetoRel.prototype.clone = function() { return new window.SVGPathSegMovetoRel(undefined, this._x, this._y) } Object.defineProperty(window.SVGPathSegMovetoRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegMovetoRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) window.SVGPathSegLinetoAbs = function(owningPathSegList, x, y) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_LINETO_ABS, 'L', owningPathSegList ) this._x = x this._y = y } window.SVGPathSegLinetoAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegLinetoAbs.prototype.toString = function() { return '[object SVGPathSegLinetoAbs]' } window.SVGPathSegLinetoAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y } window.SVGPathSegLinetoAbs.prototype.clone = function() { return new window.SVGPathSegLinetoAbs(undefined, this._x, this._y) } Object.defineProperty(window.SVGPathSegLinetoAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegLinetoAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) window.SVGPathSegLinetoRel = function(owningPathSegList, x, y) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_LINETO_REL, 'l', owningPathSegList ) this._x = x this._y = y } window.SVGPathSegLinetoRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegLinetoRel.prototype.toString = function() { return '[object SVGPathSegLinetoRel]' } window.SVGPathSegLinetoRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y } window.SVGPathSegLinetoRel.prototype.clone = function() { return new window.SVGPathSegLinetoRel(undefined, this._x, this._y) } Object.defineProperty(window.SVGPathSegLinetoRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegLinetoRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) window.SVGPathSegCurvetoCubicAbs = function( owningPathSegList, x, y, x1, y1, x2, y2 ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS, 'C', owningPathSegList ) this._x = x this._y = y this._x1 = x1 this._y1 = y1 this._x2 = x2 this._y2 = y2 } window.SVGPathSegCurvetoCubicAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoCubicAbs.prototype.toString = function() { return '[object SVGPathSegCurvetoCubicAbs]' } window.SVGPathSegCurvetoCubicAbs.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegCurvetoCubicAbs.prototype.clone = function() { return new window.SVGPathSegCurvetoCubicAbs( undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2 ) } Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, 'x1', { get: function() { return this._x1 }, set: function(x1) { this._x1 = x1 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, 'y1', { get: function() { return this._y1 }, set: function(y1) { this._y1 = y1 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, 'x2', { get: function() { return this._x2 }, set: function(x2) { this._x2 = x2 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicAbs.prototype, 'y2', { get: function() { return this._y2 }, set: function(y2) { this._y2 = y2 this._segmentChanged() }, enumerable: true }) window.SVGPathSegCurvetoCubicRel = function( owningPathSegList, x, y, x1, y1, x2, y2 ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL, 'c', owningPathSegList ) this._x = x this._y = y this._x1 = x1 this._y1 = y1 this._x2 = x2 this._y2 = y2 } window.SVGPathSegCurvetoCubicRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoCubicRel.prototype.toString = function() { return '[object SVGPathSegCurvetoCubicRel]' } window.SVGPathSegCurvetoCubicRel.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegCurvetoCubicRel.prototype.clone = function() { return new window.SVGPathSegCurvetoCubicRel( undefined, this._x, this._y, this._x1, this._y1, this._x2, this._y2 ) } Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, 'x1', { get: function() { return this._x1 }, set: function(x1) { this._x1 = x1 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, 'y1', { get: function() { return this._y1 }, set: function(y1) { this._y1 = y1 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, 'x2', { get: function() { return this._x2 }, set: function(x2) { this._x2 = x2 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoCubicRel.prototype, 'y2', { get: function() { return this._y2 }, set: function(y2) { this._y2 = y2 this._segmentChanged() }, enumerable: true }) window.SVGPathSegCurvetoQuadraticAbs = function( owningPathSegList, x, y, x1, y1 ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS, 'Q', owningPathSegList ) this._x = x this._y = y this._x1 = x1 this._y1 = y1 } window.SVGPathSegCurvetoQuadraticAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoQuadraticAbs.prototype.toString = function() { return '[object SVGPathSegCurvetoQuadraticAbs]' } window.SVGPathSegCurvetoQuadraticAbs.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegCurvetoQuadraticAbs.prototype.clone = function() { return new window.SVGPathSegCurvetoQuadraticAbs( undefined, this._x, this._y, this._x1, this._y1 ) } Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoQuadraticAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) Object.defineProperty( window.SVGPathSegCurvetoQuadraticAbs.prototype, 'x1', { get: function() { return this._x1 }, set: function(x1) { this._x1 = x1 this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoQuadraticAbs.prototype, 'y1', { get: function() { return this._y1 }, set: function(y1) { this._y1 = y1 this._segmentChanged() }, enumerable: true } ) window.SVGPathSegCurvetoQuadraticRel = function( owningPathSegList, x, y, x1, y1 ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL, 'q', owningPathSegList ) this._x = x this._y = y this._x1 = x1 this._y1 = y1 } window.SVGPathSegCurvetoQuadraticRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoQuadraticRel.prototype.toString = function() { return '[object SVGPathSegCurvetoQuadraticRel]' } window.SVGPathSegCurvetoQuadraticRel.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._x1 + ' ' + this._y1 + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegCurvetoQuadraticRel.prototype.clone = function() { return new window.SVGPathSegCurvetoQuadraticRel( undefined, this._x, this._y, this._x1, this._y1 ) } Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegCurvetoQuadraticRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) Object.defineProperty( window.SVGPathSegCurvetoQuadraticRel.prototype, 'x1', { get: function() { return this._x1 }, set: function(x1) { this._x1 = x1 this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoQuadraticRel.prototype, 'y1', { get: function() { return this._y1 }, set: function(y1) { this._y1 = y1 this._segmentChanged() }, enumerable: true } ) window.SVGPathSegArcAbs = function( owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_ARC_ABS, 'A', owningPathSegList ) this._x = x this._y = y this._r1 = r1 this._r2 = r2 this._angle = angle this._largeArcFlag = largeArcFlag this._sweepFlag = sweepFlag } window.SVGPathSegArcAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegArcAbs.prototype.toString = function() { return '[object SVGPathSegArcAbs]' } window.SVGPathSegArcAbs.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegArcAbs.prototype.clone = function() { return new window.SVGPathSegArcAbs( undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag ) } Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'r1', { get: function() { return this._r1 }, set: function(r1) { this._r1 = r1 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'r2', { get: function() { return this._r2 }, set: function(r2) { this._r2 = r2 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'angle', { get: function() { return this._angle }, set: function(angle) { this._angle = angle this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'largeArcFlag', { get: function() { return this._largeArcFlag }, set: function(largeArcFlag) { this._largeArcFlag = largeArcFlag this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcAbs.prototype, 'sweepFlag', { get: function() { return this._sweepFlag }, set: function(sweepFlag) { this._sweepFlag = sweepFlag this._segmentChanged() }, enumerable: true }) window.SVGPathSegArcRel = function( owningPathSegList, x, y, r1, r2, angle, largeArcFlag, sweepFlag ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_ARC_REL, 'a', owningPathSegList ) this._x = x this._y = y this._r1 = r1 this._r2 = r2 this._angle = angle this._largeArcFlag = largeArcFlag this._sweepFlag = sweepFlag } window.SVGPathSegArcRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegArcRel.prototype.toString = function() { return '[object SVGPathSegArcRel]' } window.SVGPathSegArcRel.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._r1 + ' ' + this._r2 + ' ' + this._angle + ' ' + (this._largeArcFlag ? '1' : '0') + ' ' + (this._sweepFlag ? '1' : '0') + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegArcRel.prototype.clone = function() { return new window.SVGPathSegArcRel( undefined, this._x, this._y, this._r1, this._r2, this._angle, this._largeArcFlag, this._sweepFlag ) } Object.defineProperty(window.SVGPathSegArcRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcRel.prototype, 'r1', { get: function() { return this._r1 }, set: function(r1) { this._r1 = r1 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcRel.prototype, 'r2', { get: function() { return this._r2 }, set: function(r2) { this._r2 = r2 this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcRel.prototype, 'angle', { get: function() { return this._angle }, set: function(angle) { this._angle = angle this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcRel.prototype, 'largeArcFlag', { get: function() { return this._largeArcFlag }, set: function(largeArcFlag) { this._largeArcFlag = largeArcFlag this._segmentChanged() }, enumerable: true }) Object.defineProperty(window.SVGPathSegArcRel.prototype, 'sweepFlag', { get: function() { return this._sweepFlag }, set: function(sweepFlag) { this._sweepFlag = sweepFlag this._segmentChanged() }, enumerable: true }) window.SVGPathSegLinetoHorizontalAbs = function(owningPathSegList, x) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS, 'H', owningPathSegList ) this._x = x } window.SVGPathSegLinetoHorizontalAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegLinetoHorizontalAbs.prototype.toString = function() { return '[object SVGPathSegLinetoHorizontalAbs]' } window.SVGPathSegLinetoHorizontalAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x } window.SVGPathSegLinetoHorizontalAbs.prototype.clone = function() { return new window.SVGPathSegLinetoHorizontalAbs(undefined, this._x) } Object.defineProperty(window.SVGPathSegLinetoHorizontalAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) window.SVGPathSegLinetoHorizontalRel = function(owningPathSegList, x) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL, 'h', owningPathSegList ) this._x = x } window.SVGPathSegLinetoHorizontalRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegLinetoHorizontalRel.prototype.toString = function() { return '[object SVGPathSegLinetoHorizontalRel]' } window.SVGPathSegLinetoHorizontalRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x } window.SVGPathSegLinetoHorizontalRel.prototype.clone = function() { return new window.SVGPathSegLinetoHorizontalRel(undefined, this._x) } Object.defineProperty(window.SVGPathSegLinetoHorizontalRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true }) window.SVGPathSegLinetoVerticalAbs = function(owningPathSegList, y) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS, 'V', owningPathSegList ) this._y = y } window.SVGPathSegLinetoVerticalAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegLinetoVerticalAbs.prototype.toString = function() { return '[object SVGPathSegLinetoVerticalAbs]' } window.SVGPathSegLinetoVerticalAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._y } window.SVGPathSegLinetoVerticalAbs.prototype.clone = function() { return new window.SVGPathSegLinetoVerticalAbs(undefined, this._y) } Object.defineProperty(window.SVGPathSegLinetoVerticalAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) window.SVGPathSegLinetoVerticalRel = function(owningPathSegList, y) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL, 'v', owningPathSegList ) this._y = y } window.SVGPathSegLinetoVerticalRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegLinetoVerticalRel.prototype.toString = function() { return '[object SVGPathSegLinetoVerticalRel]' } window.SVGPathSegLinetoVerticalRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._y } window.SVGPathSegLinetoVerticalRel.prototype.clone = function() { return new window.SVGPathSegLinetoVerticalRel(undefined, this._y) } Object.defineProperty(window.SVGPathSegLinetoVerticalRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true }) window.SVGPathSegCurvetoCubicSmoothAbs = function( owningPathSegList, x, y, x2, y2 ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS, 'S', owningPathSegList ) this._x = x this._y = y this._x2 = x2 this._y2 = y2 } window.SVGPathSegCurvetoCubicSmoothAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoCubicSmoothAbs.prototype.toString = function() { return '[object SVGPathSegCurvetoCubicSmoothAbs]' } window.SVGPathSegCurvetoCubicSmoothAbs.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegCurvetoCubicSmoothAbs.prototype.clone = function() { return new window.SVGPathSegCurvetoCubicSmoothAbs( undefined, this._x, this._y, this._x2, this._y2 ) } Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothAbs.prototype, 'x2', { get: function() { return this._x2 }, set: function(x2) { this._x2 = x2 this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothAbs.prototype, 'y2', { get: function() { return this._y2 }, set: function(y2) { this._y2 = y2 this._segmentChanged() }, enumerable: true } ) window.SVGPathSegCurvetoCubicSmoothRel = function( owningPathSegList, x, y, x2, y2 ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL, 's', owningPathSegList ) this._x = x this._y = y this._x2 = x2 this._y2 = y2 } window.SVGPathSegCurvetoCubicSmoothRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoCubicSmoothRel.prototype.toString = function() { return '[object SVGPathSegCurvetoCubicSmoothRel]' } window.SVGPathSegCurvetoCubicSmoothRel.prototype._asPathString = function() { return ( this.pathSegTypeAsLetter + ' ' + this._x2 + ' ' + this._y2 + ' ' + this._x + ' ' + this._y ) } window.SVGPathSegCurvetoCubicSmoothRel.prototype.clone = function() { return new window.SVGPathSegCurvetoCubicSmoothRel( undefined, this._x, this._y, this._x2, this._y2 ) } Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothRel.prototype, 'x2', { get: function() { return this._x2 }, set: function(x2) { this._x2 = x2 this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoCubicSmoothRel.prototype, 'y2', { get: function() { return this._y2 }, set: function(y2) { this._y2 = y2 this._segmentChanged() }, enumerable: true } ) window.SVGPathSegCurvetoQuadraticSmoothAbs = function( owningPathSegList, x, y ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS, 'T', owningPathSegList ) this._x = x this._y = y } window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.toString = function() { return '[object SVGPathSegCurvetoQuadraticSmoothAbs]' } window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y } window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype.clone = function() { return new window.SVGPathSegCurvetoQuadraticSmoothAbs( undefined, this._x, this._y ) } Object.defineProperty( window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoQuadraticSmoothAbs.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true } ) window.SVGPathSegCurvetoQuadraticSmoothRel = function( owningPathSegList, x, y ) { window.SVGPathSeg.call( this, window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL, 't', owningPathSegList ) this._x = x this._y = y } window.SVGPathSegCurvetoQuadraticSmoothRel.prototype = Object.create( window.SVGPathSeg.prototype ) window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.toString = function() { return '[object SVGPathSegCurvetoQuadraticSmoothRel]' } window.SVGPathSegCurvetoQuadraticSmoothRel.prototype._asPathString = function() { return this.pathSegTypeAsLetter + ' ' + this._x + ' ' + this._y } window.SVGPathSegCurvetoQuadraticSmoothRel.prototype.clone = function() { return new window.SVGPathSegCurvetoQuadraticSmoothRel( undefined, this._x, this._y ) } Object.defineProperty( window.SVGPathSegCurvetoQuadraticSmoothRel.prototype, 'x', { get: function() { return this._x }, set: function(x) { this._x = x this._segmentChanged() }, enumerable: true } ) Object.defineProperty( window.SVGPathSegCurvetoQuadraticSmoothRel.prototype, 'y', { get: function() { return this._y }, set: function(y) { this._y = y this._segmentChanged() }, enumerable: true } ) // Add createSVGPathSeg* functions to window.SVGPathElement. // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-Interfacewindow.SVGPathElement. window.SVGPathElement.prototype.createSVGPathSegClosePath = function() { return new window.SVGPathSegClosePath(undefined) } window.SVGPathElement.prototype.createSVGPathSegMovetoAbs = function(x, y) { return new window.SVGPathSegMovetoAbs(undefined, x, y) } window.SVGPathElement.prototype.createSVGPathSegMovetoRel = function(x, y) { return new window.SVGPathSegMovetoRel(undefined, x, y) } window.SVGPathElement.prototype.createSVGPathSegLinetoAbs = function(x, y) { return new window.SVGPathSegLinetoAbs(undefined, x, y) } window.SVGPathElement.prototype.createSVGPathSegLinetoRel = function(x, y) { return new window.SVGPathSegLinetoRel(undefined, x, y) } window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicAbs = function( x, y, x1, y1, x2, y2 ) { return new window.SVGPathSegCurvetoCubicAbs( undefined, x, y, x1, y1, x2, y2 ) } window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicRel = function( x, y, x1, y1, x2, y2 ) { return new window.SVGPathSegCurvetoCubicRel( undefined, x, y, x1, y1, x2, y2 ) } window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticAbs = function( x, y, x1, y1 ) { return new window.SVGPathSegCurvetoQuadraticAbs(undefined, x, y, x1, y1) } window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticRel = function( x, y, x1, y1 ) { return new window.SVGPathSegCurvetoQuadraticRel(undefined, x, y, x1, y1) } window.SVGPathElement.prototype.createSVGPathSegArcAbs = function( x, y, r1, r2, angle, largeArcFlag, sweepFlag ) { return new window.SVGPathSegArcAbs( undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag ) } window.SVGPathElement.prototype.createSVGPathSegArcRel = function( x, y, r1, r2, angle, largeArcFlag, sweepFlag ) { return new window.SVGPathSegArcRel( undefined, x, y, r1, r2, angle, largeArcFlag, sweepFlag ) } window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalAbs = function( x ) { return new window.SVGPathSegLinetoHorizontalAbs(undefined, x) } window.SVGPathElement.prototype.createSVGPathSegLinetoHorizontalRel = function( x ) { return new window.SVGPathSegLinetoHorizontalRel(undefined, x) } window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalAbs = function( y ) { return new window.SVGPathSegLinetoVerticalAbs(undefined, y) } window.SVGPathElement.prototype.createSVGPathSegLinetoVerticalRel = function( y ) { return new window.SVGPathSegLinetoVerticalRel(undefined, y) } window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothAbs = function( x, y, x2, y2 ) { return new window.SVGPathSegCurvetoCubicSmoothAbs(undefined, x, y, x2, y2) } window.SVGPathElement.prototype.createSVGPathSegCurvetoCubicSmoothRel = function( x, y, x2, y2 ) { return new window.SVGPathSegCurvetoCubicSmoothRel(undefined, x, y, x2, y2) } window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothAbs = function( x, y ) { return new window.SVGPathSegCurvetoQuadraticSmoothAbs(undefined, x, y) } window.SVGPathElement.prototype.createSVGPathSegCurvetoQuadraticSmoothRel = function( x, y ) { return new window.SVGPathSegCurvetoQuadraticSmoothRel(undefined, x, y) } if (!('getPathSegAtLength' in window.SVGPathElement.prototype)) { // Add getPathSegAtLength to SVGPathElement. // Spec: https://www.w3.org/TR/SVG11/single-page.html#paths-__svg__SVGPathElement__getPathSegAtLength // This polyfill requires SVGPathElement.getTotalLength to implement the distance-along-a-path algorithm. window.SVGPathElement.prototype.getPathSegAtLength = function(distance) { if (distance === undefined || !isFinite(distance)) throw 'Invalid arguments.' var measurementElement = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' ) measurementElement.setAttribute('d', this.getAttribute('d')) var lastPathSegment = measurementElement.pathSegList.numberOfItems - 1 // If the path is empty, return 0. if (lastPathSegment <= 0) return 0 do { measurementElement.pathSegList.removeItem(lastPathSegment) if (distance > measurementElement.getTotalLength()) break lastPathSegment-- } while (lastPathSegment > 0) return lastPathSegment } } } if (!('SVGPathSegList' in window)) { // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSegList window.SVGPathSegList = function(pathElement) { this._pathElement = pathElement this._list = this._parsePath(this._pathElement.getAttribute('d')) // Use a MutationObserver to catch changes to the path's "d" attribute. this._mutationObserverConfig = { attributes: true, attributeFilter: ['d'] } this._pathElementMutationObserver = new MutationObserver( this._updateListFromPathMutations.bind(this) ) this._pathElementMutationObserver.observe( this._pathElement, this._mutationObserverConfig ) } window.SVGPathSegList.prototype.classname = 'SVGPathSegList' Object.defineProperty(window.SVGPathSegList.prototype, 'numberOfItems', { get: function() { this._checkPathSynchronizedToList() return this._list.length }, enumerable: true }) // Add the pathSegList accessors to window.SVGPathElement. // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGAnimatedPathData Object.defineProperty(window.SVGPathElement.prototype, 'pathSegList', { get: function() { if (!this._pathSegList) this._pathSegList = new window.SVGPathSegList(this) return this._pathSegList }, enumerable: true }) // FIXME: The following are not implemented and simply return window.SVGPathElement.pathSegList. Object.defineProperty( window.SVGPathElement.prototype, 'normalizedPathSegList', { get: function() { return this.pathSegList }, enumerable: true } ) Object.defineProperty( window.SVGPathElement.prototype, 'animatedPathSegList', { get: function() { return this.pathSegList }, enumerable: true } ) Object.defineProperty( window.SVGPathElement.prototype, 'animatedNormalizedPathSegList', { get: function() { return this.pathSegList }, enumerable: true } ) // Process any pending mutations to the path element and update the list as needed. // This should be the first call of all public functions and is needed because // MutationObservers are not synchronous so we can have pending asynchronous mutations. window.SVGPathSegList.prototype._checkPathSynchronizedToList = function() { this._updateListFromPathMutations( this._pathElementMutationObserver.takeRecords() ) } window.SVGPathSegList.prototype._updateListFromPathMutations = function( mutationRecords ) { if (!this._pathElement) return var hasPathMutations = false mutationRecords.forEach(function(record) { if (record.attributeName == 'd') hasPathMutations = true }) if (hasPathMutations) this._list = this._parsePath(this._pathElement.getAttribute('d')) } // Serialize the list and update the path's 'd' attribute. window.SVGPathSegList.prototype._writeListToPath = function() { this._pathElementMutationObserver.disconnect() this._pathElement.setAttribute( 'd', window.SVGPathSegList._pathSegArrayAsString(this._list) ) this._pathElementMutationObserver.observe( this._pathElement, this._mutationObserverConfig ) } // When a path segment changes the list needs to be synchronized back to the path element. window.SVGPathSegList.prototype.segmentChanged = function(pathSeg) { this._writeListToPath() } window.SVGPathSegList.prototype.clear = function() { this._checkPathSynchronizedToList() this._list.forEach(function(pathSeg) { pathSeg._owningPathSegList = null }) this._list = [] this._writeListToPath() } window.SVGPathSegList.prototype.initialize = function(newItem) { this._checkPathSynchronizedToList() this._list = [newItem] newItem._owningPathSegList = this this._writeListToPath() return newItem } window.SVGPathSegList.prototype._checkValidIndex = function(index) { if (isNaN(index) || index < 0 || index >= this.numberOfItems) throw 'INDEX_SIZE_ERR' } window.SVGPathSegList.prototype.getItem = function(index) { this._checkPathSynchronizedToList() this._checkValidIndex(index) return this._list[index] } window.SVGPathSegList.prototype.insertItemBefore = function( newItem, index ) { this._checkPathSynchronizedToList() // Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list. if (index > this.numberOfItems) index = this.numberOfItems if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone() } this._list.splice(index, 0, newItem) newItem._owningPathSegList = this this._writeListToPath() return newItem } window.SVGPathSegList.prototype.replaceItem = function(newItem, index) { this._checkPathSynchronizedToList() if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone() } this._checkValidIndex(index) this._list[index] = newItem newItem._owningPathSegList = this this._writeListToPath() return newItem } window.SVGPathSegList.prototype.removeItem = function(index) { this._checkPathSynchronizedToList() this._checkValidIndex(index) var item = this._list[index] this._list.splice(index, 1) this._writeListToPath() return item } window.SVGPathSegList.prototype.appendItem = function(newItem) { this._checkPathSynchronizedToList() if (newItem._owningPathSegList) { // SVG2 spec says to make a copy. newItem = newItem.clone() } this._list.push(newItem) newItem._owningPathSegList = this // TODO: Optimize this to just append to the existing attribute. this._writeListToPath() return newItem } window.SVGPathSegList._pathSegArrayAsString = function(pathSegArray) { var string = '' var first = true pathSegArray.forEach(function(pathSeg) { if (first) { first = false string += pathSeg._asPathString() } else { string += ' ' + pathSeg._asPathString() } }) return string } // This closely follows SVGPathParser::parsePath from Source/core/svg/SVGPathParser.cpp. window.SVGPathSegList.prototype._parsePath = function(string) { if (!string || string.length == 0) return [] var owningPathSegList = this var Builder = function() { this.pathSegList = [] } Builder.prototype.appendSegment = function(pathSeg) { this.pathSegList.push(pathSeg) } var Source = function(string) { this._string = string this._currentIndex = 0 this._endIndex = this._string.length this._previousCommand = window.SVGPathSeg.PATHSEG_UNKNOWN this._skipOptionalSpaces() } Source.prototype._isCurrentSpace = function() { var character = this._string[this._currentIndex] return ( character <= ' ' && (character == ' ' || character == '\n' || character == '\t' || character == '\r' || character == '\f') ) } Source.prototype._skipOptionalSpaces = function() { while (this._currentIndex < this._endIndex && this._isCurrentSpace()) this._currentIndex++ return this._currentIndex < this._endIndex } Source.prototype._skipOptionalSpacesOrDelimiter = function() { if ( this._currentIndex < this._endIndex && !this._isCurrentSpace() && this._string.charAt(this._currentIndex) != ',' ) return false if (this._skipOptionalSpaces()) { if ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == ',' ) { this._currentIndex++ this._skipOptionalSpaces() } } return this._currentIndex < this._endIndex } Source.prototype.hasMoreData = function() { return this._currentIndex < this._endIndex } Source.prototype.peekSegmentType = function() { var lookahead = this._string[this._currentIndex] return this._pathSegTypeFromChar(lookahead) } Source.prototype._pathSegTypeFromChar = function(lookahead) { switch (lookahead) { case 'Z': case 'z': return window.SVGPathSeg.PATHSEG_CLOSEPATH case 'M': return window.SVGPathSeg.PATHSEG_MOVETO_ABS case 'm': return window.SVGPathSeg.PATHSEG_MOVETO_REL case 'L': return window.SVGPathSeg.PATHSEG_LINETO_ABS case 'l': return window.SVGPathSeg.PATHSEG_LINETO_REL case 'C': return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS case 'c': return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL case 'Q': return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS case 'q': return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL case 'A': return window.SVGPathSeg.PATHSEG_ARC_ABS case 'a': return window.SVGPathSeg.PATHSEG_ARC_REL case 'H': return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS case 'h': return window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL case 'V': return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS case 'v': return window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL case 'S': return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS case 's': return window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL case 'T': return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS case 't': return window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL default: return window.SVGPathSeg.PATHSEG_UNKNOWN } } Source.prototype._nextCommandHelper = function( lookahead, previousCommand ) { // Check for remaining coordinates in the current command. if ( (lookahead == '+' || lookahead == '-' || lookahead == '.' || (lookahead >= '0' && lookahead <= '9')) && previousCommand != window.SVGPathSeg.PATHSEG_CLOSEPATH ) { if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_ABS) return window.SVGPathSeg.PATHSEG_LINETO_ABS if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_REL) return window.SVGPathSeg.PATHSEG_LINETO_REL return previousCommand } return window.SVGPathSeg.PATHSEG_UNKNOWN } Source.prototype.initialCommandIsMoveTo = function() { // If the path is empty it is still valid, so return true. if (!this.hasMoreData()) return true var command = this.peekSegmentType() // Path must start with moveTo. return ( command == window.SVGPathSeg.PATHSEG_MOVETO_ABS || command == window.SVGPathSeg.PATHSEG_MOVETO_REL ) } // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp. // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF Source.prototype._parseNumber = function() { var exponent = 0 var integer = 0 var frac = 1 var decimal = 0 var sign = 1 var expsign = 1 var startIndex = this._currentIndex this._skipOptionalSpaces() // Read the sign. if ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == '+' ) this._currentIndex++ else if ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == '-' ) { this._currentIndex++ sign = -1 } if ( this._currentIndex == this._endIndex || ((this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) != '.') ) // The first character of a number must be one of [0-9+-.]. return undefined // Read the integer part, build right-to-left. var startIntPartIndex = this._currentIndex while ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9' ) this._currentIndex++ // Advance to first non-digit. if (this._currentIndex != startIntPartIndex) { var scanIntPartIndex = this._currentIndex - 1 var multiplier = 1 while (scanIntPartIndex >= startIntPartIndex) { integer += multiplier * (this._string.charAt(scanIntPartIndex--) - '0') multiplier *= 10 } } // Read the decimals. if ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) == '.' ) { this._currentIndex++ // There must be a least one digit following the . if ( this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9' ) return undefined while ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9' ) { frac *= 10 decimal += (this._string.charAt(this._currentIndex) - '0') / frac this._currentIndex += 1 } } // Read the exponent part. if ( this._currentIndex != startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) == 'e' || this._string.charAt(this._currentIndex) == 'E') && this._string.charAt(this._currentIndex + 1) != 'x' && this._string.charAt(this._currentIndex + 1) != 'm' ) { this._currentIndex++ // Read the sign of the exponent. if (this._string.charAt(this._currentIndex) == '+') { this._currentIndex++ } else if (this._string.charAt(this._currentIndex) == '-') { this._currentIndex++ expsign = -1 } // There must be an exponent. if ( this._currentIndex >= this._endIndex || this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9' ) return undefined while ( this._currentIndex < this._endIndex && this._string.charAt(this._currentIndex) >= '0' && this._string.charAt(this._currentIndex) <= '9' ) { exponent *= 10 exponent += this._string.charAt(this._currentIndex) - '0' this._currentIndex++ } } var number = integer + decimal number *= sign if (exponent) number *= Math.pow(10, expsign * exponent) if (startIndex == this._currentIndex) return undefined this._skipOptionalSpacesOrDelimiter() return number } Source.prototype._parseArcFlag = function() { if (this._currentIndex >= this._endIndex) return undefined var flag = false var flagChar = this._string.charAt(this._currentIndex++) if (flagChar == '0') flag = false else if (flagChar == '1') flag = true else return undefined this._skipOptionalSpacesOrDelimiter() return flag } Source.prototype.parseSegment = function() { var lookahead = this._string[this._currentIndex] var command = this._pathSegTypeFromChar(lookahead) if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) { // Possibly an implicit command. Not allowed if this is the first command. if (this._previousCommand == window.SVGPathSeg.PATHSEG_UNKNOWN) return null command = this._nextCommandHelper(lookahead, this._previousCommand) if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) return null } else { this._currentIndex++ } this._previousCommand = command switch (command) { case window.SVGPathSeg.PATHSEG_MOVETO_REL: return new window.SVGPathSegMovetoRel( owningPathSegList, this._parseNumber(), this._parseNumber() ) case window.SVGPathSeg.PATHSEG_MOVETO_ABS: return new window.SVGPathSegMovetoAbs( owningPathSegList, this._parseNumber(), this._parseNumber() ) case window.SVGPathSeg.PATHSEG_LINETO_REL: return new window.SVGPathSegLinetoRel( owningPathSegList, this._parseNumber(), this._parseNumber() ) case window.SVGPathSeg.PATHSEG_LINETO_ABS: return new window.SVGPathSegLinetoAbs( owningPathSegList, this._parseNumber(), this._parseNumber() ) case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL: return new window.SVGPathSegLinetoHorizontalRel( owningPathSegList, this._parseNumber() ) case window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS: return new window.SVGPathSegLinetoHorizontalAbs( owningPathSegList, this._parseNumber() ) case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL: return new window.SVGPathSegLinetoVerticalRel( owningPathSegList, this._parseNumber() ) case window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS: return new window.SVGPathSegLinetoVerticalAbs( owningPathSegList, this._parseNumber() ) case window.SVGPathSeg.PATHSEG_CLOSEPATH: this._skipOptionalSpaces() return new window.SVGPathSegClosePath(owningPathSegList) case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: var points = { x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegCurvetoCubicRel( owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2 ) case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: var points = { x1: this._parseNumber(), y1: this._parseNumber(), x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegCurvetoCubicAbs( owningPathSegList, points.x, points.y, points.x1, points.y1, points.x2, points.y2 ) case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: var points = { x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegCurvetoCubicSmoothRel( owningPathSegList, points.x, points.y, points.x2, points.y2 ) case window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: var points = { x2: this._parseNumber(), y2: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegCurvetoCubicSmoothAbs( owningPathSegList, points.x, points.y, points.x2, points.y2 ) case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: var points = { x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegCurvetoQuadraticRel( owningPathSegList, points.x, points.y, points.x1, points.y1 ) case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: var points = { x1: this._parseNumber(), y1: this._parseNumber(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegCurvetoQuadraticAbs( owningPathSegList, points.x, points.y, points.x1, points.y1 ) case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: return new window.SVGPathSegCurvetoQuadraticSmoothRel( owningPathSegList, this._parseNumber(), this._parseNumber() ) case window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: return new window.SVGPathSegCurvetoQuadraticSmoothAbs( owningPathSegList, this._parseNumber(), this._parseNumber() ) case window.SVGPathSeg.PATHSEG_ARC_REL: var points = { x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegArcRel( owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep ) case window.SVGPathSeg.PATHSEG_ARC_ABS: var points = { x1: this._parseNumber(), y1: this._parseNumber(), arcAngle: this._parseNumber(), arcLarge: this._parseArcFlag(), arcSweep: this._parseArcFlag(), x: this._parseNumber(), y: this._parseNumber() } return new window.SVGPathSegArcAbs( owningPathSegList, points.x, points.y, points.x1, points.y1, points.arcAngle, points.arcLarge, points.arcSweep ) default: throw 'Unknown path seg type.' } } var builder = new Builder() var source = new Source(string) if (!source.initialCommandIsMoveTo()) return [] while (source.hasMoreData()) { var pathSeg = source.parseSegment() if (!pathSeg) return [] builder.appendSegment(pathSeg) } return builder.pathSegList } } })() // String.padEnd polyfill for IE11 // // https://github.com/uxitten/polyfill/blob/master/string.polyfill.js // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd if (!String.prototype.padEnd) { String.prototype.padEnd = function padEnd(targetLength, padString) { targetLength = targetLength >> 0 //floor if number or convert non-number to 0; padString = String(typeof padString !== 'undefined' ? padString : ' ') if (this.length > targetLength) { return String(this) } else { targetLength = targetLength - this.length if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length) //append to original to ensure we are longer than needed } return String(this) + padString.slice(0, targetLength) } } } // Object.assign polyfill for IE11 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill if (typeof Object.assign !== 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, 'assign', { value: function assign(target, varArgs) { // .length of function is 2 'use strict' if (target === null || target === undefined) { throw new TypeError('Cannot convert undefined or null to object') } var to = Object(target) for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index] if (nextSource !== null && nextSource !== undefined) { for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey] } } } } return to }, writable: true, configurable: true }) } /* jshint ignore:end */
the_stack
import React, {useState, useEffect, useCallback, FC} from 'react'; import {Text, StyleSheet, View} from 'react-native'; import * as SecureStore from 'expo-secure-store'; import {useTranslation} from 'react-i18next'; import {RouteProp} from '@react-navigation/native'; import {StackNavigationProp} from '@react-navigation/stack'; import {useExposure} from 'react-native-exposure-notification-service'; import {add, isPast} from 'date-fns'; import {useApplication} from '../../providers/context'; import {saveMetric, METRIC_TYPES} from '../../services/api/utils'; import { validateCode, uploadExposureKeys, ValidationResult } from '../../services/api/exposures'; import {usePause} from '../../providers/reminders/pause-reminder'; import {useSettings} from '../../providers/settings'; import {setAccessibilityFocusRef, useFocusRef} from '../../hooks/accessibility'; import {DataProtectionLink} from './data-protection-policy'; import {Heading} from '../atoms/heading'; import {Spacing} from '../atoms/layout'; import {Markdown} from '../atoms/markdown'; import {Button} from '../atoms/button'; import {Card} from '../atoms/card'; import {Toast} from '../atoms/toast'; import {CodeInput} from '../molecules/code-input'; import {SingleCodeInput} from '../molecules/single-code-input'; import {colors} from '../../constants/colors'; import Layouts from '../../theme/layouts'; import {text, baseStyles} from '../../theme'; type UploadStatus = | 'initialising' | 'validate' | 'upload' | 'uploadOnly' | 'success' | 'permissionError' | 'error'; interface Props { navigation: StackNavigationProp<any>; route: RouteProp<any, any>; } const MAX_SETTINGS_AGE = 5; // hours export const UploadKeys: FC<Props> = ({navigation, route}) => { const {t} = useTranslation(); const exposure = useExposure(); const {paused} = usePause(); const { showActivityIndicator, hideActivityIndicator, pendingCode, setContext, user } = useApplication(); const { appConfig: {codeLength, deepLinkLength}, loaded, loadedTime, reload } = useSettings(); const [status, setStatus] = useState<UploadStatus>('initialising'); const [presetCode, setPresetCode] = useState(pendingCode || ''); const codeInParams: string | undefined = route.params?.c; const hasPresetCode = !!(presetCode || codeInParams); const show6DigitInput = !hasPresetCode && codeLength === 6; const expectedCodeLength = hasPresetCode ? deepLinkLength : codeLength; const [code, setCode] = useState(presetCode); const [validationError, setValidationError] = useState<string>(''); const [uploadToken, setUploadToken] = useState(''); const [headingRef, toastRef, successRef, uploadRef, errorRef] = useFocusRef({ count: 5 }); const isRegistered = !!user; const isPresetCode = presetCode.length > 0 && code === presetCode; const updateCode = useCallback((input: string) => { setValidationError(''); setCode(input); }, []); const clearPresetCode = () => { setPresetCode(''); updateCode(''); setAccessibilityFocusRef(headingRef); }; useEffect(() => { // Handle code set in params by deep link if (!codeInParams) { return; } if (!isRegistered) { // Store code so we can bring new user back with it when they onboard setContext({pendingCode: codeInParams}); navigation.reset({ index: 0, routes: [{name: 'over16'}] }); return; } if (status === 'validate' && typeof codeInParams === 'string') { // Move the code out of params and clear any current code so that // re-trying a deep link re-applies it (e.g. if user had been offline) navigation.setParams({c: ''}); updateCode(''); setPresetCode(''); // Apply deep link params code in next render after clearing setTimeout(() => { updateCode(codeInParams); setPresetCode(codeInParams); }); } }, [codeInParams, navigation, updateCode, status, isRegistered, setContext]); useEffect(() => { if ( loaded && loadedTime && isPast(add(loadedTime, {hours: MAX_SETTINGS_AGE})) ) { console.log( `Settings are older than ${MAX_SETTINGS_AGE} hours, reloading in background` ); reload(); } }, [loaded, loadedTime, reload]); useEffect(() => { const readUploadToken = async () => { try { const token = await SecureStore.getItemAsync('uploadToken'); if (token) { setUploadToken(token); setStatus('uploadOnly'); return; } } catch (e) {} setStatus('validate'); }; readUploadToken(); }, []); const codeValidationHandler = useCallback(async () => { showActivityIndicator(); console.log(`Validating ${code.length} character code...`); const {result, token} = await validateCode(code); hideActivityIndicator(); if (result !== ValidationResult.Valid) { let errorMessage; if (result === ValidationResult.NetworkError) { errorMessage = t('common:networkError'); } else if (result === ValidationResult.Expired) { errorMessage = t('uploadKeys:code:expiredError'); } else if (result === ValidationResult.Invalid) { errorMessage = t('uploadKeys:code:invalidError'); } else { errorMessage = t('uploadKeys:code:error'); } console.log( `${code.length}-character code validation ${ errorMessage ? `failed with error "${errorMessage}"` : 'passed' }` ); setValidationError(errorMessage); setTimeout(() => { setAccessibilityFocusRef(isPresetCode ? headingRef : errorRef); }, 350); return; } try { await SecureStore.setItemAsync('uploadToken', token!); } catch (e) { console.log('Error (secure) storing upload token', e); } setValidationError(''); setUploadToken(token!); setStatus('upload'); setTimeout(() => { setAccessibilityFocusRef(isPresetCode ? headingRef : uploadRef); }, 350); }, [ code, isPresetCode, showActivityIndicator, hideActivityIndicator, t, errorRef, uploadRef, headingRef ]); const shouldValidate = code.length && (code.length === expectedCodeLength || isPresetCode); useEffect(() => { if (isRegistered) { if (shouldValidate) { codeValidationHandler(); } else { setValidationError(''); } } }, [codeValidationHandler, isRegistered, shouldValidate]); const uploadDataHandler = async () => { let exposureKeys; try { if (paused) { try { await exposure.start(); } catch (e) { console.log(e); } } exposureKeys = await exposure.getDiagnosisKeys(); } catch (err) { console.log('getDiagnosisKeys error:', err); if (paused) { try { await exposure.pause(); } catch (e) { console.log(e); } } setStatus('permissionError'); setTimeout(() => { setAccessibilityFocusRef(toastRef); }, 350); return; } try { showActivityIndicator(); await uploadExposureKeys(uploadToken, exposureKeys); hideActivityIndicator(); setContext({uploadDate: Date.now()}); setStatus('success'); setTimeout(() => { setAccessibilityFocusRef(successRef); }, 350); } catch (err) { console.log('error uploading exposure keys:', err); saveMetric({ event: METRIC_TYPES.LOG_ERROR, payload: JSON.stringify({ where: 'uploadExposureKeys', error: JSON.stringify(err) }) }); hideActivityIndicator(); setStatus('error'); setTimeout(() => { setAccessibilityFocusRef(toastRef); }, 350); } finally { if (paused) { try { await exposure.pause(); } catch (e) { console.log(e); } } } try { await SecureStore.deleteItemAsync('uploadToken'); } catch (e) {} }; const renderValidation = () => { // Remount and clear input if a new presetCode is provided const inputKey = `code-input-${presetCode}`; const validationDone = status !== 'validate'; const showValidationError = !!validationError && !validationDone && (code.length === codeLength || !!presetCode); const onDoneHandler = () => validationError && setAccessibilityFocusRef(errorRef); return ( <View key={inputKey}> <Markdown markdownStyles={{block: {...text.default, marginBottom: 16}}}> {isPresetCode ? t('uploadKeys:code:deepLink', {deepLinkLength}) : t('uploadKeys:code:intro', {codeLength})} </Markdown> <Spacing s={16} /> {show6DigitInput ? ( <CodeInput error={showValidationError} onChange={updateCode} disabled={validationDone} code={code} onDone={onDoneHandler} count={codeLength} /> ) : ( <SingleCodeInput error={showValidationError} onChange={updateCode} disabled={validationDone} code={code} onDone={onDoneHandler} isPreset={!!presetCode} /> )} {showValidationError && ( <> <Spacing s={8} /> <Text ref={errorRef} style={baseStyles.error}> {validationError} </Text> {isPresetCode && ( <> <Spacing s={40} /> <Button type="default" onPress={clearPresetCode}> {t('codeInput:accessibilityHint', {count: codeLength})} </Button> </> )} </> )} <Spacing s={24} /> </View> ); }; const renderUpload = () => { return ( <> <View accessible ref={uploadRef}> <Markdown>{t('uploadKeys:upload:intro', {codeLength})}</Markdown> </View> <Spacing s={8} /> <Button type="default" onPress={uploadDataHandler}> {t('uploadKeys:upload:button')} </Button> <Spacing s={16} /> <DataProtectionLink /> </> ); }; const renderErrorToast = () => { return ( <> <Toast ref={toastRef} color={colors.red} message={ status === 'permissionError' ? t('uploadKeys:permissionError') : t('uploadKeys:uploadError') } icon={require('../../assets/images/alert/alert.png')} /> <Spacing s={8} /> </> ); }; const renderUploadSuccess = () => { return ( <Card padding={{v: 4}} cardRef={successRef}> <Spacing s={16} /> <Toast color="rgba(0, 207, 104, 0.16)" message={t('uploadKeys:uploadSuccess:toast')} icon={require('../../assets/images/success/green.png')} /> <Text style={[text.default, styles.successText]}> {t('uploadKeys:uploadSuccess:thanks')} </Text> <Button type="empty" onPress={() => navigation.navigate('main', {screen: 'dashboard'})}> {t('uploadKeys:uploadSuccess:updates')} </Button> <Spacing s={16} /> </Card> ); }; if (!isRegistered) { return null; } const showErrorToast = status === 'permissionError' || status === 'error'; const showValidation = status === 'validate' || status === 'upload'; const showUpload = status === 'upload' || status === 'uploadOnly' || status === 'error' || status === 'permissionError'; const showUploadSuccess = status === 'success'; return ( <Layouts.KeyboardScrollable> <Heading accessibilityFocus text={t('uploadKeys:title')} headingRef={headingRef} /> {showValidation && renderValidation()} {showErrorToast && renderErrorToast()} {showUpload && renderUpload()} {showUploadSuccess && renderUploadSuccess()} </Layouts.KeyboardScrollable> ); }; const styles = StyleSheet.create({ markdownStyle: { backgroundColor: colors.background }, successText: { marginTop: 16, marginBottom: 16 }, codeInput: { marginTop: -12 } });
the_stack
import { Observable, ReplaySubject, Subject } from 'rxjs'; import { assert, log, logIf, LogLevel, logVerbosity } from './auxiliaries'; import { clamp } from './gl-matrix-extensions'; /* spellchecker: enable */ /** * This internal interface is not intended for module export and should not be used as generic rendering/controller * interface. The renderer interface should be used for rendering related tasks instead. */ export interface Controllable { /** * Used to trigger an renderer update. Returns true iff rendering is invalidated and * a new multi-frame should be rendered- */ update(multiFrameNumber: number): boolean; /** * Used to prepare rendering of a multi-frame. */ prepare(): void; /** * Used to trigger rendering of a single, intermediate frame. */ frame(frameNumber: number): void; /** * Used to swap/blit frame from back to front buffer. */ swap(): void; } /** * This class controls the rendering flow by means of triggering rendering of a well defined amount of frames * (multi-frame number) for frame accumulation. Single frame rendering is handled with a multi-frame number of 1. If a * full multi-frame is accumulated, rendering halts. The rendering is not intended to be controlled by owning objects, * but via invalidation from within the renderer instead. However, an explicit redraw of a full single or multi-frame * can be invoked by calling `update()`. Furthermore, when using multi-frame rendering, the renderer can be halted at a * specific frame by setting a debug-frame number. * * Terminology: a multi-frame is the final result after accumulating a number of intermediate frames (frame). The * number of intermediate frames is defined by the multi-frame number. For a multi-frame, the controller invokes the * `prepare` on a controllable first, followed by multiple `frame` and `swap` calls. Please note that the * adaptive batch mode is yet experimental (can be enabled using `batchSize`). */ export class Controller { /** * Toggle for debug outputs; if true control flow will be logged. */ protected static _debug = false; set debug(value: boolean) { if (value && logVerbosity() < LogLevel.Debug) { logVerbosity(LogLevel.Debug); log(LogLevel.Debug, `changed log verbosity to ${LogLevel.Debug} (debug)`); } Controller._debug = value; } /** * Number of intermediate frames that are rendered during one browser frame */ protected _batchSize = 1; set batch(size: number) { log(LogLevel.Warning, `(adaptive) batch multi-frame rendering is experimental for now`); this._batchSize = Math.max(1, size); } /** * @see {@link multiFrameNumber} * This property can be observed, e.g., `aController.multiFrameNumberObservable.subscribe()`. */ protected _multiFrameNumber = 1; protected _multiFrameNumberSubject = new ReplaySubject<number>(1); /** * @see {@link debugFrameNumber} * This property can be observed, e.g., `aController.debugFrameNumberObservable.subscribe()`. */ protected _debugFrameNumber = 0; protected _debugFrameNumberSubject = new ReplaySubject<number>(1); /** * @see {@link frameNumber} * This property can be observed, e.g., `aController.frameNumberObservable.subscribe()`. */ protected _frameNumber = 0; protected _frameNumberSubject = new ReplaySubject<number>(1); /** @see {@link multiFrameDelay} */ protected _multiFrameDelay = 0; // protected _delayedRequestTimeout: number | undefined; /** Observable event that is triggered after frame invocation (renderer). */ protected _postFrameEventSubject = new Subject<number>(); /** Observable event that is triggered after swap invocation (renderer). */ protected _postSwapEventSubject = new Subject<number>(); /** * Controllable, e.g., an instance of a Renderer. */ protected _controllable: Controllable | undefined; /** * Holds the handle of the pending / executed animate frame request, if requested. Throughout the controller, only a * single request at a time is allowed. */ protected _animationFrameID = 0; /** * Holds the handle of the running timeout to execute a new multi frame. Undefined if we currently do not wait for * a new multi frame. */ protected _timeoutID: number | undefined; /** * Blocking updates can be used to re-configure the controller without triggering */ protected _block = false; /** * Number of update requested while being in blocked mode. If there is one or more blocked requests, an update will * be triggered when unblocked. */ protected _blockedUpdates = 0; /* Debug and reporting facilities. */ /** * Total number of rendered intermediate frames. */ protected _intermediateFrameCount = 0; /** * Total number of completed multi-frames. */ protected _multiFrameCount = 0; /** * Time tracker used to the minimum and maximum frame time of an intermediate frame (per multi-frame). */ protected _intermediateFrameTimes = new Array<number>(2); /** * Time tracker used to accumulate all durations of executed frame and swap callbacks per multi-frame. This is the * net rendering time and is used to derive the average frame time. */ protected _multiFrameTime: number; /** * Time tracker used to capture the time the update callback took. */ protected _updateFrameTime: number; /** * Used to measure the gross rendering time of a multi-frame. The first point in time denotes the start of the * rendering, the second, the point in time the last frame was rendered. * * Note: point in times might be shifted due to (un)pausing. Their intent is to allow measuring the rendering * duration, nothing else. */ protected _multiTime: Array<number> = [0.0, 0.0]; protected _invalidated = false; protected _force = false; protected request(source: Controller.RequestType = Controller.RequestType.Frame): void { this._animationFrameID = 0; if (this._block) { this._blockedUpdates++; return; } this._animationFrameID = window.requestAnimationFrame(() => this.invoke(source)); } protected invoke(source: Controller.RequestType): void { if (this._animationFrameID === 0) { // We got a former request animation frame that was already canceled return; } assert(this._controllable !== undefined, `frame sequence invoked without controllable set`); if (this._invalidated) { this._invalidated = false; const redraw = this.invokeUpdate(); if (redraw || this._force) { this._force = false; this._frameNumber = 0; this.cancelWaitMultiFrame(); this.invokePrepare(); } } if (source === Controller.RequestType.Frame && this._frameNumber === 1) { if (this._timeoutID === undefined) { this.startWaitMultiFrame(); } this._animationFrameID = 0; return; } if (this.isMultiFrameFinished()) { this._animationFrameID = 0; return; } this.invokeFrameAndSwap(); this.request(); } /** * Actual invocation of the controllable's update method. Returns true if multi frame rendering should be restarted, * false otherwise. */ protected invokeUpdate(): boolean { logIf(Controller._debug, LogLevel.Debug, `c invoke update | ` + `pending: '${this._animationFrameID}', mfnum: ${this._multiFrameNumber}`); const redraw: boolean = (this._controllable as Controllable).update(this._multiFrameNumber); return redraw; } /** * Actual invocation of the controllable's prepare method. */ protected invokePrepare(): void { logIf(Controller._debug, LogLevel.Debug, `c invoke prepare |`); this._multiFrameTime = 0.0; this._intermediateFrameTimes[0] = Number.MAX_VALUE; this._intermediateFrameTimes[1] = Number.MIN_VALUE; /* Trigger preparation of a new multi-frame and measure execution time. */ this._multiTime[0] = performance.now(); (this._controllable as Controllable).prepare(); this._multiTime[1] = performance.now(); const updateDuration = this._multiTime[1] - this._multiTime[0]; this._multiFrameTime = updateDuration; this._updateFrameTime = updateDuration; } /** * Invokes rendering of an intermediate frame, increments the frame counter, and requests rendering of the next * frame. The rendering is invoked by means of a callback to the canvas renderer. This function implements various * asserts to assure correct control logic and absolutely prevent unnecessary frame requests. */ protected invokeFrameAndSwap(): void { logIf(Controller._debug, LogLevel.Debug, `c invoke frame | pending: '${this._animationFrameID}'`); const debug = this._debugFrameNumber > 0; assert(!debug || this._frameNumber < this._debugFrameNumber, `frame number about to exceed debug-frame number`); /* Trigger an intermediate frame and measure and accumulate execution time for average frame time. This should be the only place, any renderer frame method is invoked. */ const t0 = performance.now(); let batchEnd = Math.min(this._multiFrameNumber, this._frameNumber + this._batchSize); if (this._debugFrameNumber > 0) { batchEnd = Math.min(batchEnd, this._debugFrameNumber); } for (; this._frameNumber < batchEnd; ++this._frameNumber) { logIf(Controller._debug, LogLevel.Debug, `c -> frame | frame: ${this._frameNumber}`); (this._controllable as Controllable).frame(this._frameNumber); this._postFrameEventSubject.next(this._frameNumber); ++this._intermediateFrameCount; } logIf(Controller._debug, LogLevel.Debug, `c -> swap |`); (this._controllable as Controllable).swap(); this._postSwapEventSubject.next(this._frameNumber); this._multiTime[1] = performance.now(); /* Note: critical call sequence; be careful when changing the following lines. */ const frameDuration = this._multiTime[1] - t0; this._multiFrameTime += frameDuration; /* Keep track of minimum and maximum intermediate frame durations. */ this._intermediateFrameTimes[0] = Math.min(this._intermediateFrameTimes[0], frameDuration); /* Note that the first frame is probably the slowest due to lazy initialization of stages/passes. */ this._intermediateFrameTimes[1] = Math.max(this._intermediateFrameTimes[1], frameDuration); this.frameNumberNext(); } protected startWaitMultiFrame(): void { const startMultiFrame = () => { this.request(Controller.RequestType.MultiFrame); this._timeoutID = undefined; }; this._timeoutID = window.setTimeout(startMultiFrame, this._multiFrameDelay); } protected cancelWaitMultiFrame(): void { if (this._timeoutID !== undefined) { window.clearTimeout(this._timeoutID); this._timeoutID = undefined; } } protected isMultiFrameFinished(): boolean { if (this._debugFrameNumber > 0) { return this._frameNumber === this._debugFrameNumber; } return this._frameNumber === this._multiFrameNumber; } /** * Utility for communicating this._multiFrameNumber changes to its associated subject. */ protected multiFrameNumberNext(): void { this._multiFrameNumberSubject.next(this._multiFrameNumber); } /** * Utility for communicating this._debugFrameNumber changes to its associated subject. */ protected debugFrameNumberNext(): void { this._debugFrameNumberSubject.next(this._debugFrameNumber); } /** * Utility for communicating this._frameNumber changes to its associated subject. */ protected frameNumberNext(): void { this._frameNumberSubject.next(this._frameNumber); } update(force: boolean = false): void { this._invalidated = true; this._force = this._force || force; if (this._animationFrameID === 0) { this.request(); } } /** * Block implicit updates, e.g., caused by various setters. This can be used to reconfigure the controller without * triggering to multiple intermediate updates. The block updates mode can be exited using `unblock`. */ block(): void { logIf(Controller._debug, LogLevel.Debug, `c block ${this._block ? '(ignored) ' : ' '}|`); this._block = true; } /** * Unblock updates. If there was at least one blocked update request, an immediate update is invoked. */ unblock(): void { logIf(Controller._debug, LogLevel.Debug, `c unblock ${!this._block ? '(ignored) ' : ' '}` + `| blocked: #${this._blockedUpdates}`); if (!this._block) { return; } this._block = false; if (this._blockedUpdates > 0) { this._blockedUpdates = 0; this.update(); } } cancel(): void { if (this._animationFrameID === 0) { return; } window.cancelAnimationFrame(this._animationFrameID); this._animationFrameID = 0; } /** * Returns whether or not the control is blocking updates. * @returns - True if blocked, else false. */ get blocked(): boolean { return this._block; } /** * Sets the controllable, for which updates, frames, and swaps are invoked whenever rendering is * invalidated and an updated multi-frame is required. Swap is detached from frame since rendering an intermediate * frame is usually done offscreen and explicit swap control can be useful. * @param controllable - Controllable for update, frame, and swap invocation. */ set controllable(controllable: Controllable | undefined) { if (controllable === this._controllable) { return; } this._controllable = controllable; this.update(true); } /** * Returns the multi-frame number. The number is greater than or equal to zero. Multi-frame number is implemented * as a property and allows for change callback. * @returns - Multi-frame number. */ get multiFrameNumber(): number { return this._multiFrameNumber; } /** * Changes the multi-frame number. If the provided value equals the current number set, nothing happens. If the * provided value is negative, the multi-frame number is set to 1. * @param multiFrameNumber - The multi-frame number targeted for rendering. */ set multiFrameNumber(multiFrameNumber: number) { const value: number = Math.max(1, isNaN(multiFrameNumber) ? 1 : multiFrameNumber); if (value === this._multiFrameNumber) { return; } this._multiFrameNumber = value; this.multiFrameNumberNext(); logIf(value !== multiFrameNumber, LogLevel.Debug, `multi-frame number adjusted to ${value}, given ${multiFrameNumber}`); if (this.debugFrameNumber > this.multiFrameNumber) { this.debugFrameNumber = this.multiFrameNumber; } else { this.update(); } } /** * Observable that can be used to subscribe to multi-frame number changes. */ get multiFrameNumber$(): Observable<number> { return this._multiFrameNumberSubject.asObservable(); } /** * Returns the debug-frame number greater than or equal to zero. * @returns - Debug-frame number. */ get debugFrameNumber(): number { return this._debugFrameNumber; } /** * Sets the debug.-frame number (debug number) that, if greater than zero, causes the rendering to halt when the * current frame number (frame number) equals the debug number. Debugging can be disabled by setting the debug * number to zero. * * If the debug number is greater than the frame number rendering is restarted by means of an update(). If the * debug number is less than the frame number the rendering continues and halts accordingly. If the debug number * equals the current debug number set, nothing happens. If the debug number is greater than the multi-frame * number, it is reduced to the multi-frame number. * * Note: in contrast to setting the multi-frame number, setting the debug-frame number unpauses the controller. * * @param debugFrameNumber - Debug-frame number. */ set debugFrameNumber(debugFrameNumber: number) { const value: number = clamp(isNaN(debugFrameNumber) ? 0 : debugFrameNumber, 0, this.multiFrameNumber); if (value === this._debugFrameNumber) { return; } this._debugFrameNumber = value; this.debugFrameNumberNext(); logIf(value !== debugFrameNumber, LogLevel.Debug, `debug-frame number adjusted to ${value}, given ${debugFrameNumber}`); this.update(this.debugFrameNumber < this._frameNumber); } /** * Observable that can be used to subscribe to debug-frame number changes. */ get debugFrameNumber$(): Observable<number> { return this._debugFrameNumberSubject.asObservable(); } /** * Sets the multi-frame delay in milliseconds. This is used to delay rendering of subsequent intermediate frames * after an update. * @param multiFrameDelay - A multi-frame delay in milliseconds. */ set multiFrameDelay(multiFrameDelay: number) { const value: number = Math.max(0, multiFrameDelay); if (value === this._multiFrameDelay) { return; } this._multiFrameDelay = value; } /** * Time in milliseconds used to delay rendering of subsequent intermediate frames after an update. * @returns - The current multi-frame delay in milliseconds. */ get multiFrameDelay(): number { return this._multiFrameDelay; } /** * The current multi-frame number; it is less than or equal to the multi-frame number and enumerates the last * rendered frame. Note that this does not denote the number of 'completed' multi-frames rendered (not a continuous * frame count). * @returns - The current (intermediate) frame number. */ get frameNumber(): number { return this._frameNumber; } /** * Observable that can be used to subscribe to frame number changes. */ get frameNumber$(): Observable<number> { return this._frameNumberSubject.asObservable(); } /** * Returns the total number of rendered (requested and probably completed) intermediate frames. * @returns - The total number of intermediate frames rendered. */ get intermediateFrameCount(): number { return this._intermediateFrameCount; } /** * Returns the total number of completed multi-frames. * @returns - The total number of multi-frames completed. */ get multiFrameCount(): number { return this._multiFrameCount; } /** * Provides the average time it takes to render an intermediate frame within the current displayed multi-frame (if * a new multi-frame is triggered, the average frame time is reset). * @returns - Average frame time (intermediate frame rendering) in ms */ get averageFrameTime(): number { return this._frameNumber === 0 ? 0.0 : this._multiFrameTime / this._frameNumber; } /** * Provides the update time tracked for the current multi-frame. * @returns - Time of the multi-frame update (before first intermediate frame is rendered) in ms */ get updateFrameTime(): number { return this._updateFrameTime; } /** * Provides the minimum rendering time tracked over all intermediate frames of the current multi-frame. * @returns - Minimum intermediate frame time in ms */ get minimumFrameTime(): number { return this._intermediateFrameTimes[0]; } /** * Provides the maximum rendering time tracked over all intermediate frames of the current multi-frame. Note that * the maximum frame time is most often caused by the first intermediate frame within a multi-frame due to lazy * stage initialization or reconfiguration. * @returns - Maximum intermediate frame time in ms */ get maximumFrameTime(): number { return this._intermediateFrameTimes[1]; } /** * The time in milliseconds that passed since the current multi-frame (up to the current frame number) was * requested. This time excludes time spent paused (e.g., caused by halting rendering at debug-frame number). * Note that this is not a measure of frame rendering performance. The number of frame requests per second might be * limited to 60Hz even though the rendering of an intermediate frame takes only a few milliseconds. * @returns - Time passed for current multi-frame in milliseconds. */ get multiFrameTime(): number { return this._frameNumber === 0 ? 0.0 : this._multiTime[1] - this._multiTime[0]; } /** * The frames per second is based on the average number of a full intermediate frame request up to the current * frame number. * @returns - Number of frames per second based on the current multi-frame */ get framesPerSecond(): number { return this._frameNumber === 0 ? 0.0 : 1000.0 / (this.multiFrameTime / this._frameNumber); } /** * Observable that can be used to subscribe to post frame events. */ get postFrameEvent$(): Observable<number> { return this._postFrameEventSubject.asObservable(); } /** * Observable that can be used to subscribe to post swap events. */ get postSwapEvent$(): Observable<number> { return this._postSwapEventSubject.asObservable(); } } export namespace Controller { export enum RequestType { Frame, MultiFrame } }
the_stack
import { NgxCarouselItemDirective, NgxCarouselNextDirective, NgxCarouselPrevDirective } from './ngx-carousel.directive'; import { Component, ElementRef, Renderer, Input, Output, OnInit, OnDestroy, AfterViewInit, HostListener, EventEmitter, ContentChildren, QueryList, ViewChild, AfterContentInit, ViewChildren, ContentChild, OnChanges, SimpleChanges } from '@angular/core'; import { NgxCarousel, NgxCarouselStore } from './ngx-carousel.interface'; import { Subscription } from 'rxjs/Subscription'; import * as Hammer from 'hammerjs' @Component({ // tslint:disable-next-line:component-selector selector: 'ngx-carousel', template: `<div #ngxcarousel class="ngxcarousel"><div #forTouch class="ngxcarousel-inner"><div #ngxitems class="ngxcarousel-items"><ng-content select="[NgxCarouselItem]"></ng-content></div><div style="clear: both"></div></div><ng-content select="[NgxCarouselPrev]"></ng-content><ng-content select="[NgxCarouselNext]"></ng-content></div><div #points *ngIf="userData.point.visible"><ul class="ngxcarouselPoint"><li #pointInner *ngFor="let i of pointNumbers; let i=index" [class.active]="i==pointers" (click)="moveTo(i)"></li></ul></div>`, styles: [ ` :host { display: block; position: relative; } .ngxcarousel .ngxcarousel-inner { position: relative; overflow: hidden; } .ngxcarousel .ngxcarousel-inner .ngxcarousel-items { white-space: nowrap; position: relative; } .banner .ngxcarouselPointDefault .ngxcarouselPoint { position: absolute; width: 100%; bottom: 20px; } .banner .ngxcarouselPointDefault .ngxcarouselPoint li { background: rgba(255, 255, 255, 0.55); } .banner .ngxcarouselPointDefault .ngxcarouselPoint li.active { background: white; } .banner .ngxcarouselPointDefault .ngxcarouselPoint li:hover { cursor: pointer; } .ngxcarouselPointDefault .ngxcarouselPoint { list-style-type: none; text-align: center; padding: 12px; margin: 0; white-space: nowrap; overflow: auto; box-sizing: border-box; } .ngxcarouselPointDefault .ngxcarouselPoint li { display: inline-block; border-radius: 50%; background: rgba(0, 0, 0, 0.55); padding: 4px; margin: 0 4px; transition-timing-function: cubic-bezier(0.17, 0.67, 0.83, 0.67); transition: 0.4s; } .ngxcarouselPointDefault .ngxcarouselPoint li.active { background: #6b6b6b; transform: scale(1.8); } .ngxcarouselPointDefault .ngxcarouselPoint li:hover { cursor: pointer; } ` ] }) export class NgxCarouselComponent implements OnInit, AfterContentInit, AfterViewInit, OnDestroy, OnChanges { itemsSubscribe: Subscription; carouselCssNode: any; pointIndex: number; pointers: number; // tslint:disable-next-line:no-input-rename @Input('inputs') userData: any; @Input('moveToSlide') moveToSlide: number; @Output('carouselLoad') carouselLoad = new EventEmitter(); @Output('onMove') onMove = new EventEmitter(); @Output('afterCarouselViewed') afterCarouselViewed = new EventEmitter(); @ContentChildren(NgxCarouselItemDirective) private items: QueryList<NgxCarouselItemDirective>; @ViewChildren('pointInner', { read: ElementRef }) private points: QueryList<ElementRef>; @ContentChild(NgxCarouselNextDirective, { read: ElementRef }) private next: ElementRef; @ContentChild(NgxCarouselPrevDirective, { read: ElementRef }) private prev: ElementRef; @ViewChild('ngxcarousel', { read: ElementRef }) private carouselMain1: ElementRef; @ViewChild('ngxitems', { read: ElementRef }) private carouselInner1: ElementRef; @ViewChild('main', { read: ElementRef }) private carousel1: ElementRef; @ViewChild('points', { read: ElementRef }) private pointMain: ElementRef; @ViewChild('forTouch', { read: ElementRef }) private forTouch: ElementRef; private leftBtn: any; private rightBtn: any; private evtValue: number; private pauseCarousel = false; private pauseInterval: any; private carousel: any; private carouselMain: any; private carouselInner: any; private carouselItems: any; private onResize: any; private onScrolling: any; private carouselInt: any; public Arr1 = Array; public pointNumbers: Array<any> = []; public data: NgxCarouselStore = { type: 'fixed', classText: '', deviceType: 'lg', items: 0, load: 0, deviceWidth: 0, carouselWidth: 0, itemWidth: 0, visibleItems: { start: 0, end: 0 }, slideItems: 0, itemWidthPer: 0, itemLength: 0, currentSlide: 0, easing: 'cubic-bezier(0, 0, 0.2, 1)', speed: 400, transform: { xs: 0, sm: 0, md: 0, lg: 0, all: 0 }, loop: false, dexVal: 0, touchTransform: 0, touch: { active: false, swipe: '', velocity: 0 }, isEnd: false, isFirst: true, isLast: false }; constructor(private el: ElementRef, private renderer: Renderer) {} ngOnInit() { this.carousel = this.el.nativeElement; this.carouselMain = this.carouselMain1.nativeElement; this.carouselInner = this.carouselInner1.nativeElement; this.carouselItems = this.carouselInner.getElementsByClassName('item'); this.rightBtn = this.next.nativeElement; this.leftBtn = this.prev.nativeElement; this.data.type = this.userData.grid.all !== 0 ? 'fixed' : 'responsive'; this.data.loop = this.userData.loop || false; this.data.easing = this.userData.easing || 'cubic-bezier(0, 0, 0.2, 1)'; this.data.touch.active = this.userData.touch || false; this.carouselSize(); // const datas = this.itemsElements.first.nativeElement.getBoundingClientRect().width; } ngAfterContentInit() { this.renderer.listen(this.leftBtn, 'click', () => this.carouselScrollOne(0) ); this.renderer.listen(this.rightBtn, 'click', () => this.carouselScrollOne(1) ); this.carouselCssNode = this.renderer.createElement(this.carousel, 'style'); this.storeCarouselData(); this.carouselInterval(); this.onWindowScrolling(); this.buttonControl(); this.touch(); this.itemsSubscribe = this.items.changes.subscribe(val => { this.data.isLast = false; this.carouselPoint(); this.buttonControl(); }); // tslint:disable-next-line:no-unused-expression this.moveToSlide && this.moveTo(this.moveToSlide); } ngAfterViewInit() { if (this.userData.point.pointStyles) { const datas = this.userData.point.pointStyles.replace( /.ngxcarouselPoint/g, `.${this.data.classText} .ngxcarouselPoint` ); const pointNode = this.renderer.createElement(this.carousel, 'style'); this.renderer.createText(pointNode, datas); } else if (this.userData.point && this.userData.point.visible) { this.renderer.setElementClass( this.pointMain.nativeElement, 'ngxcarouselPointDefault', true ); } this.afterCarouselViewed.emit(this.data); } ngOnDestroy() { clearInterval(this.carouselInt); // tslint:disable-next-line:no-unused-expression this.itemsSubscribe && this.itemsSubscribe.unsubscribe(); } @HostListener('window:resize', ['$event']) onResizing(event: any) { clearTimeout(this.onResize); this.onResize = setTimeout(() => { // tslint:disable-next-line:no-unused-expression this.data.deviceWidth !== event.target.outerWidth && this.storeCarouselData(); }, 500); } ngOnChanges(changes: SimpleChanges) { // tslint:disable-next-line:no-unused-expression this.moveToSlide > -1 && this.moveTo(changes.moveToSlide.currentValue); } /* store data based on width of the screen for the carousel */ private storeCarouselData(): void { this.data.deviceWidth = window.innerWidth; this.data.carouselWidth = this.carouselMain.offsetWidth; // const datas = this.items.first.nativeElement.getBoundingClientRect().width; if (this.data.type === 'responsive') { this.data.deviceType = this.data.deviceWidth >= 1200 ? 'lg' : this.data.deviceWidth >= 992 ? 'md' : this.data.deviceWidth >= 768 ? 'sm' : 'xs'; this.data.items = this.userData.grid[this.data.deviceType]; this.data.itemWidth = this.data.carouselWidth / this.data.items; } else { this.data.items = Math.trunc( this.data.carouselWidth / this.userData.grid.all ); this.data.itemWidth = this.userData.grid.all; this.data.deviceType = 'all'; } this.data.slideItems = +(this.userData.slide < this.data.items ? this.userData.slide : this.data.items); this.data.load = this.userData.load >= this.data.slideItems ? this.userData.load : this.data.slideItems; this.data.speed = this.userData.speed || this.userData.speed > -1 ? this.userData.speed : 400; this.carouselPoint(); } /* Get Touch input */ private touch(): void { if (this.data.touch.active) { const hammertime = new Hammer(this.forTouch.nativeElement); hammertime.get('pan').set({ direction: Hammer.DIRECTION_HORIZONTAL }); hammertime.on('panstart', (ev: any) => { this.data.carouselWidth = this.carouselInner.offsetWidth; this.data.touchTransform = this.data.transform[this.data.deviceType]; this.data.dexVal = 0; this.setStyle(this.carouselInner, 'transition', ''); }); hammertime.on('panleft', (ev: any) => { this.touchHandling('panleft', ev); }); hammertime.on('panright', (ev: any) => { this.touchHandling('panright', ev); }); hammertime.on('panend', (ev: any) => { // this.setStyle(this.carouselInner, 'transform', ''); if (_this.data.shouldSlide) { this.data.touch.velocity = ev.velocity; this.data.touch.swipe === 'panright' ? this.carouselScrollOne(0) : this.carouselScrollOne(1); } else { _this.data.dexVal = 0; _this.data.touchTransform = _this.data.transform[_this.data.deviceType]; _this.setStyle(_this.carouselInner, 'transition', 'transform 324ms cubic-bezier(0, 0, 0.2, 1)'); var tran = _this.data.touchTransform * -1; _this.setStyle(_this.carouselInner, 'transform', 'translate3d(' + tran + '%, 0px, 0px)'); } }); hammertime.on("hammer.input", function(ev) { // allow nested touch events to no propagate, this may have other side affects but works for now. // TODO: It is probably better to check the source element of the event and only apply the handle to the correct carousel ev.srcEvent.stopPropagation() }); } } /* handle touch input */ private touchHandling(e: string, ev: any): void { // vertical touch events seem to cause to panstart event with an odd delta // and a center of {x:0,y:0} so this will ignore them if (ev.center.x === 0) { return } ev = Math.abs(ev.deltaX); let valt = ev - this.data.dexVal; valt = this.data.type === 'responsive' ? Math.abs(ev - this.data.dexVal) / this.data.carouselWidth * 100 : valt; this.data.dexVal = ev; this.data.touch.swipe = e; this.data.touchTransform = e === 'panleft' ? valt + this.data.touchTransform : this.data.touchTransform - valt; this.data.shouldSlide = (ev > this.data.carouselWidth * 0.1); if (this.data.touchTransform > 0) { this.setStyle( this.carouselInner, 'transform', this.data.type === 'responsive' ? `translate3d(-${this.data.touchTransform}%, 0px, 0px)` : `translate3d(-${this.data.touchTransform}px, 0px, 0px)` ); } else { this.data.touchTransform = 0; } } /* this used to disable the scroll when it is not on the display */ private onWindowScrolling(): void { const top = this.carousel.offsetTop; const scrollY = window.scrollY; const heightt = window.innerHeight; const carouselHeight = this.carousel.offsetHeight; if ( top <= scrollY + heightt - carouselHeight / 4 && top + carouselHeight / 2 >= scrollY ) { this.carouselIntervalEvent(0); } else { this.carouselIntervalEvent(1); } } /* Init carousel point */ private carouselPoint(): void { // if (this.userData.point.visible === true) { const Nos = this.items.length - (this.data.items - this.data.slideItems); this.pointIndex = Math.ceil(Nos / this.data.slideItems); const pointers = []; if (this.pointIndex > 1 || !this.userData.point.hideOnSingleSlide) { for (let i = 0; i < this.pointIndex; i++) { pointers.push(i); } } this.pointNumbers = pointers; this.carouselPointActiver(); if (this.pointIndex <= 1) { this.btnBoolean(1, 1); // this.data.isFirst = true; // this.data.isLast = true; } else { if (this.data.currentSlide === 0 && !this.data.loop) { this.btnBoolean(1, 0); } else { this.btnBoolean(0, 0); } } this.buttonControl(); // } } /* change the active point in carousel */ private carouselPointActiver(): void { const i = Math.ceil(this.data.currentSlide / this.data.slideItems); this.pointers = i; } /* this function is used to scoll the carousel when point is clicked */ public moveTo(index: number) { if (this.pointers !== index && index < this.pointIndex) { let slideremains = 0; const btns = this.data.currentSlide < index ? 1 : 0; if (index === 0) { this.btnBoolean(1, 0); slideremains = index * this.data.slideItems; } else if (index === this.pointIndex - 1) { this.btnBoolean(0, 1); slideremains = this.items.length - this.data.items; } else { this.btnBoolean(0, 0); slideremains = index * this.data.slideItems; } this.carouselScrollTwo(btns, slideremains, this.data.speed); } } /* set the style of the carousel based the inputs data */ private carouselSize(): void { this.data.classText = this.generateID(); let dism = ''; const styleid = '.' + this.data.classText + ' > .ngxcarousel > .ngxcarousel-inner > .ngxcarousel-items >'; if (this.userData.custom === 'banner') { this.renderer.setElementClass(this.carousel, 'banner', true); } // if (this.userData.animation && this.userData.animation.animateStyles) { // dism += `${styleid} .customAnimation {${this.userData.animation // .animateStyles.style}} ${styleid} .item {transition: .3s ease all}`; // } if (this.userData.animation === 'lazy') { dism += `${styleid} .item {transition: transform .6s ease;}`; } let itemStyle = ''; if (this.data.type === 'responsive') { const itemWidth_xs = this.userData.type === 'mobile' ? `${styleid} .item {width: ${95 / this.userData.grid.xs}%}` : `${styleid} .item {width: ${100 / this.userData.grid.xs}%}`; const itemWidth_sm = styleid + ' .item {width: ' + 100 / this.userData.grid.sm + '%}'; const itemWidth_md = styleid + ' .item {width: ' + 100 / this.userData.grid.md + '%}'; const itemWidth_lg = styleid + ' .item {width: ' + 100 / this.userData.grid.lg + '%}'; itemStyle = `@media (max-width:767px){${itemWidth_xs}} @media (min-width:768px){${itemWidth_sm}} @media (min-width:992px){${itemWidth_md}} @media (min-width:1200px){${itemWidth_lg}}`; } else { itemStyle = `${styleid} .item {width: ${this.userData.grid.all}px}`; } this.renderer.setElementClass(this.carousel, this.data.classText, true); const styleItem = this.renderer.createElement(this.carousel, 'style'); this.renderer.createText(styleItem, `${dism} ${itemStyle}`); } /* logic to scroll the carousel step 1 */ private carouselScrollOne(Btn: number): void { let itemSpeed = this.data.speed; let translateXval, currentSlide = 0; const touchMove = Math.ceil(this.data.dexVal / this.data.itemWidth); this.setStyle(this.carouselInner, 'transform', ''); if (this.pointIndex === 1) { return; } else if ( Btn === 0 && ((!this.data.loop && !this.data.isFirst) || this.data.loop) ) { const slide = this.data.slideItems * this.pointIndex; const currentSlideD = this.data.currentSlide - this.data.slideItems; const MoveSlide = currentSlideD + this.data.slideItems; this.btnBoolean(0, 1); if (this.data.currentSlide === 0) { currentSlide = this.items.length - this.data.items; itemSpeed = 400; this.btnBoolean(0, 1); } else if (this.data.slideItems >= MoveSlide) { currentSlide = translateXval = 0; this.btnBoolean(1, 0); } else { this.btnBoolean(0, 0); if (touchMove > this.data.slideItems) { currentSlide = this.data.currentSlide - touchMove; itemSpeed = 200; } else { currentSlide = this.data.currentSlide - this.data.slideItems; } } this.carouselScrollTwo(Btn, currentSlide, itemSpeed); } else if (Btn === 1 && ((!this.data.loop && !this.data.isLast) || this.data.loop)) { if ( this.items.length <= this.data.currentSlide + this.data.items + this.data.slideItems && !this.data.isLast ) { currentSlide = this.items.length - this.data.items; this.btnBoolean(0, 1); } else if (this.data.isLast) { currentSlide = translateXval = 0; itemSpeed = 400; this.btnBoolean(1, 0); } else { this.btnBoolean(0, 0); if (touchMove > this.data.slideItems) { currentSlide = this.data.currentSlide + this.data.slideItems + (touchMove - this.data.slideItems); itemSpeed = 200; } else { currentSlide = this.data.currentSlide + this.data.slideItems; } } this.carouselScrollTwo(Btn, currentSlide, itemSpeed); } // cubic-bezier(0.15, 1.04, 0.54, 1.13) } /* logic to scroll the carousel step 2 */ private carouselScrollTwo( Btn: number, currentSlide: number, itemSpeed: number ): void { this.data.visibleItems.start = currentSlide; this.data.visibleItems.end = currentSlide + this.data.items - 1; // tslint:disable-next-line:no-unused-expression this.userData.animation && this.carouselAnimator( Btn, currentSlide + 1, currentSlide + this.data.items, itemSpeed, Math.abs(this.data.currentSlide - currentSlide) ); if (this.data.dexVal !== 0) { // const first = .5; // const second = .50; // tslint:disable-next-line:max-line-length // this.setStyle(this.carouselInner, 'transition', `transform ${itemSpeed}ms ${this.userData.easing}`); // } else { const val = Math.abs(this.data.touch.velocity); // const first = .7 / val < .5 ? .7 / val : .5; // const second = (2.9 * val / 10 < 1.3) ? (2.9 * val) / 10 : 1.3; let somt = Math.floor( this.data.dexVal / val / this.data.dexVal * (this.data.deviceWidth - this.data.dexVal) ); somt = somt > itemSpeed ? itemSpeed : somt; itemSpeed = somt < 200 ? 200 : somt; // tslint:disable-next-line:max-line-length // this.setStyle(this.carouselInner, 'transition', `transform ${itemSpeed}ms ${this.userData.easing}`); // this.carouselInner.style.transition = `transform ${itemSpeed}ms cubic-bezier(0.15, 1.04, 0.54, 1.13) `; this.data.dexVal = 0; } this.setStyle( this.carouselInner, 'transition', `transform ${itemSpeed}ms ${this.data.easing}` ); this.data.itemLength = this.items.length; this.transformStyle(currentSlide); this.data.currentSlide = currentSlide; this.onMove.emit(this.data); this.carouselPointActiver(); this.carouselLoadTrigger(); this.buttonControl(); } /* boolean function for making isFirst and isLast */ private btnBoolean(first: number, last: number) { this.data.isFirst = first ? true : false; this.data.isLast = last ? true : false; } /* set the transform style to scroll the carousel */ private transformStyle(slide: number): void { let slideCss = ''; if (this.data.type === 'responsive') { this.data.transform.xs = 100 / this.userData.grid.xs * slide; this.data.transform.sm = 100 / this.userData.grid.sm * slide; this.data.transform.md = 100 / this.userData.grid.md * slide; this.data.transform.lg = 100 / this.userData.grid.lg * slide; slideCss = `@media (max-width: 767px) { .${this.data .classText} > .ngxcarousel > .ngxcarousel-inner > .ngxcarousel-items { transform: translate3d(-${this .data.transform.xs}%, 0, 0); } } @media (min-width: 768px) { .${this.data .classText} > .ngxcarousel > .ngxcarousel-inner > .ngxcarousel-items { transform: translate3d(-${this .data.transform.sm}%, 0, 0); } } @media (min-width: 992px) { .${this.data .classText} > .ngxcarousel > .ngxcarousel-inner > .ngxcarousel-items { transform: translate3d(-${this .data.transform.md}%, 0, 0); } } @media (min-width: 1200px) { .${this.data .classText} > .ngxcarousel > .ngxcarousel-inner > .ngxcarousel-items { transform: translate3d(-${this .data.transform.lg}%, 0, 0); } }`; } else { this.data.transform.all = this.userData.grid.all * slide; slideCss = `.${this.data .classText} > .ngxcarousel > .ngxcarousel-inner > .ngxcarousel-items { transform: translate3d(-${this.data .transform.all}px, 0, 0);`; } // this.renderer.createText(this.carouselCssNode, slideCss); this.carouselCssNode.innerHTML = slideCss; } /* this will trigger the carousel to load the items */ private carouselLoadTrigger(): void { if (typeof this.userData.load === 'number') { // tslint:disable-next-line:no-unused-expression this.items.length - this.data.load <= this.data.currentSlide + this.data.items && this.carouselLoad.emit(this.data.currentSlide); } } /* generate Class for each carousel to set specific style */ private generateID(): string { let text = ''; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 6; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return `ngxcarousel${text}`; } /* handle the auto slide */ private carouselInterval(): void { if (typeof this.userData.interval === 'number' && this.data.loop) { this.renderer.listen(this.carouselMain, 'touchstart', () => { this.carouselIntervalEvent(1); }); this.renderer.listen(this.carouselMain, 'touchend', () => { this.carouselIntervalEvent(0); }); this.renderer.listen(this.carouselMain, 'mouseenter', () => { this.carouselIntervalEvent(1); }); this.renderer.listen(this.carouselMain, 'mouseleave', () => { this.carouselIntervalEvent(0); }); this.renderer.listenGlobal('window', 'scroll', () => { clearTimeout(this.onScrolling); this.onScrolling = setTimeout(() => { this.onWindowScrolling(); }, 600); }); this.carouselInt = setInterval(() => { // tslint:disable-next-line:no-unused-expression !this.pauseCarousel && this.carouselScrollOne(1); }, this.userData.interval); } } /* pause interval for specific time */ private carouselIntervalEvent(ev: number): void { this.evtValue = ev; if (this.evtValue === 0) { clearTimeout(this.pauseInterval); this.pauseInterval = setTimeout(() => { // tslint:disable-next-line:no-unused-expression this.evtValue === 0 && (this.pauseCarousel = false); }, this.userData.interval); } else { this.pauseCarousel = true; } } /* animate the carousel items */ private carouselAnimator(direction: number, start: number, end: number, speed: number, length: number): void { let val = length < 5 ? length : 5; val = val === 1 ? 3 : val; if (direction === 1) { for (let i = start - 1; i < end; i++) { val = val * 2; // tslint:disable-next-line:no-unused-expression this.carouselItems[i] && this.setStyle(this.carouselItems[i], 'transform', `translate3d(${val}px, 0, 0)`); } } else { for (let i = end - 1; i >= start - 1; i--) { val = val * 2; // tslint:disable-next-line:no-unused-expression this.carouselItems[i] && this.setStyle(this.carouselItems[i], 'transform', `translate3d(-${val}px, 0, 0)`); } } setTimeout(() => { for (let i = 0; i < this.items.length; i++) { this.setStyle(this.carouselItems[i], 'transform', 'translate3d(0, 0, 0)'); } }, speed * .7); } /* control button for loop */ private buttonControl(): void { if (!this.data.loop || (this.data.isFirst && this.data.isLast)) { this.setStyle( this.leftBtn, 'display', this.data.isFirst ? 'none' : 'block' ); this.setStyle( this.rightBtn, 'display', this.data.isLast ? 'none' : 'block' ); } else { this.setStyle(this.leftBtn, 'display', 'block'); this.setStyle(this.rightBtn, 'display', 'block'); } } private setStyle(el: any, prop: any, val: any): void { this.renderer.setElementStyle(el, prop, val); } }
the_stack
import * as React from "react" import { DateConstants } from "./DateRange" import WebpackLoader from "../../modules/WebpackLoader" import { getInternalTextInput } from "./TextInput" import Button from "./Button" import ReactDOM = require("react-dom") import * as DatePicker from "react-datepicker"; export type DateInputProps = { className?: string, dateFormat?: string, defaultValue: Date, filterDate?: () => any, isModalInput?: boolean, maxDate?: Date, minDate?: Date, onChange?: (value:Date, name:string) => void, selectsStart?: boolean, showMonthYearPicker?: boolean, startDate?: Date, endDate?: Date style?: React.CSSProperties, name: string, selectsEnd?: boolean } let _datefns export function getDateFNS():typeof import("date-fns"){ return _datefns || (_datefns = require("date-fns")) } export function getEmotion():typeof import("emotion"){ return window["__SECRET_EMOTION__"] } let DateInputModules export default class DateInput extends React.Component<DateInputProps, { inputResetKey: number, isCalendarPickerOpen: boolean, calendarRight: number, calendarTop: number, value: Date }> { static defaultProps:Partial<DateInputProps> = { dateFormat: DateConstants.DATE_FORMAT, isModalInput: true } constructor(props:DateInputProps){ super(props) this.state = { inputResetKey: 0, isCalendarPickerOpen: false, calendarRight: null, calendarTop: null, value: props.defaultValue } } get modules(){ return DateInputModules || (DateInputModules = [ WebpackLoader.find(e => e.default && e.default.displayName === "Clickable"), WebpackLoader.find(e => e.default && e.default.displayName === "TransitionGroup") ]) } inputRef:React.Component componentDidUpdate(e:DateInputProps){ const defaultValue = this.props.defaultValue const dateFormat = this.props.dateFormat if (e.defaultValue !== defaultValue && null != defaultValue) { if(!this.inputRef)return let str = getDateFNS().format(defaultValue, dateFormat) this.inputRef["value"] = str } } closeCalendarPicker(){ this.setState({ isCalendarPickerOpen: false }) } getCurrentValue(){ let value = this.state.value let dateFormat = this.props.dateFormat; if(!value)return if(isDateValid(value))return getDateFNS().format(value, dateFormat) return null } handleDateChange(value){ this.closeCalendarPicker() const onChange = this.props.onChange const name = this.props.name this.setState((state) => { return { value: value, inputResetKey: state.inputResetKey + 1 } }, function() { null != onChange && onChange(value, name) }) } handleInputBlur(ev){ const value = this.state.value const newvalue = ev.currentTarget.value const iso = getDateFNS().parseISO(newvalue); if(isDateValid(iso) && value){ if(iso.valueOf() !== value.valueOf())this.setState(function(state) { return { value: iso, inputResetKey: state.inputResetKey + 1 } }, function() { const props = this.props const onChange = props.onChange const name = props.name; if(onChange)onChange(iso, name) }) } } toggleCalendarVisibility(ev){ const rect:DOMRect = ev.currentTarget.getBoundingClientRect() const bottom = rect.bottom const right = rect.right const innerWidth = window.innerWidth; this.setState(function(state) { return { isCalendarPickerOpen: !state.isCalendarPickerOpen, calendarRight: innerWidth - right, calendarTop: bottom } }) } setRef(ref){ this.inputRef = ref } renderCalendarPicker(){ let state = this.state let calendarRight = state.calendarRight let calendarTop = state.calendarTop let isCalendarPickerOpen = state.isCalendarPickerOpen let value = state.value let props = this.props let minDate = props.minDate let maxDate = props.maxDate let endDate = props.endDate let filterDate = props.filterDate let startDate = props.startDate let selectsEnd = props.selectsEnd let selectsStart = props.selectsStart let isModalInput = props.isModalInput let y = props.showMonthYearPicker; return isCalendarPickerOpen ? React.createElement(AnimatedCalendarPicker, { value: value ? value : undefined, onClickOutside: this.closeCalendarPicker.bind(this), onSelect: this.handleDateChange.bind(this), minDate: minDate, maxDate: maxDate, endDate: endDate, filterDate: filterDate, startDate: startDate, selectsEnd: selectsEnd, selectsStart: selectsStart, right: calendarRight, top: calendarTop, isModalInput: isModalInput, showMonthYearPicker: y }) : null } render(){ const [ Clickable, TransitionGroup ] = this.modules let name = this.props.name return React.createElement(Clickable.default, { className: getEmotion().css({ position: "relative" }) }, React.createElement(getInternalTextInput(), { inputClassName: getEmotion().css({ paddingRight: "32px" }), name: name, onBlur: this.handleInputBlur.bind(this), defaultValue: this.getCurrentValue(), inputRef: this.setRef.bind(this) }), React.createElement(Button, { className: getEmotion().css({ "&:hover": { opacity: 1 }, position: "absolute", right: 0, top: "50%", opacity: .6, padding: "8px", transform: "translateY(-50%)", transition: "opacity .125s" }), color: "transparent", onMouseDown: this.toggleCalendarVisibility.bind(this), wrapper: false //TODO: Add icon }, /*React.createElement(v.default, { className: _.default.calendarIcon, name: v.IconNames.CALENDAR })*/), ReactDOM.createPortal(React.createElement(TransitionGroup.default, { component: "div", transitionAppear: false }, this.renderCalendarPicker()), window.document.body)) } static help = { warn: "This component is still `experimental`. Please report issues to [Lightcord's developers](https://github.com/Lightcord/Lightcord/issues)." } static get AllPreviews(){ return AllPreviews || (AllPreviews = [ [ { dateFormat: DateConstants.DATE_FORMAT }, { dateFormat: "dd/MM/yyyy" }, { dateFormat: "MM/dd/yyyy" } ], [ { defaultValue: new Date() }, { defaultValue: null }, { defaultValue: new Date(1597061085498) } ], [ { filterDate: (date) => true }, { filterDate: (date) => { if(date.getDay() !== 0)return false return true } } ], [ { isModalInput: true }, { isModalInput: false } ], [ { maxDate: null }, { maxDate: new Date(Date.now() + 6.048e+8) } ], [ { minDate: null }, { minDate: new Date(Date.now() - 6.048e+8) } ], [ { onChange: (value, name) => {} } ], [ { selectsStart: null }, { selectsStart: new Date(Date.now() - (8.64e+7*2)) } ], [ { selectsEnd: null }, { selectsEnd: new Date(Date.now() + (8.64e+7*2)) } ], [ { showMonthYearPicker: false }, { showMonthYearPicker: true } ], [ { startDate: null }, { endDate: null } ], [ { name: "api-preview-dateinput" } ] ]) } } let AllPreviews export function isDateValid(date:Date){ return (date instanceof Date || typeof date === "object" || Object.prototype.toString.call(date) === "[object Date]") && !isNaN(date.valueOf()) } let AnimatedCalendarPickerModules export class AnimatedCalendarPicker extends React.Component<any, { menuAnimation: any }> { static displayName = "AnimatedCalendarPicker" constructor(props){ super(props) this.state = { menuAnimation: new this.modules[0].default.Value(0) } } get modules(){ return AnimatedCalendarPickerModules || (AnimatedCalendarPickerModules = [ WebpackLoader.findByUniqueProperties(["Value","timing"]) ]) } componentWillEnter(ev){ this.modules[0].default.timing(this.state.menuAnimation, { toValue: 1, duration: 150 }).start(ev) } componentWillLeave(e){ this.modules[0].default.timing(this.state.menuAnimation, { toValue: 0, duration: 150 }).start(e) } render(){ let props = this.props, value = props.value, onClickOutside = props.onClickOutside, onSelect = props.onSelect, minDate = props.minDate, maxDate = props.maxDate, endDate = props.endDate, filterDate = props.filterDate, startDate = props.startDate, selectsEnd = props.selectsEnd, selectsStart = props.selectsStart, top = props.top, right = props.right, isModalInput = props.isModalInput, showMonthYearPicker = props.showMonthYearPicker, menuAnimation = this.state.menuAnimation, interpolation = menuAnimation.interpolate({ inputRange: [0, 1], outputRange: ["-10px", "0px"] }); const emotion = getEmotion() return React.createElement(this.modules[0].default.div, { className: [emotion.css({ marginRight: "1px", margintop: "6px", position: "fixed", zIndex: 2 }), isModalInput ? emotion.css({ zIndex: 10000 }) : null].filter(e=>e).join(" "), style: { opacity: menuAnimation, right: right, top: top, transform: [{ translateY: interpolation }] } }, React.createElement(CalendarPicker, { minDate: minDate, maxDate: maxDate, endDate: endDate, filterDate: filterDate, startDate: startDate, selectsEnd: selectsEnd, selectsStart: selectsStart, value: value, onSelect: onSelect, onClickOutside: onClickOutside, showMonthYearPicker: showMonthYearPicker, onChange: console.log })) } } export class CalendarPicker extends React.Component<any> { static defaultProps = { value: new Date() } static displayName = "CalendarPicker" render(){ var e = this.props , t = e.onClickOutside , r = e.onSelect , n = e.locale , l = e.value , o = e.endDate , u = e.filterDate , f = e.startDate , c = e.minDate , d = e.maxDate , p = e.selectsEnd , y = e.selectsStart , v = e.showMonthYearPicker; return React.createElement("div", { className: "lc-calendarPicker" }, React.createElement(DatePicker.default, { fixedHeight: true, inline: true, selected: l, locale: n, onClickOutside: t, onSelect: r, onChange: r, endDate: o, filterDate: u, startDate: f, minDate: c, maxDate: d, selectsEnd: p, selectsStart: y, showMonthYearPicker: v })) } }
the_stack
import * as pigpio from 'pigpio'; import * as assert from 'assert'; (function alert_pwm_measurement(): void { const Gpio = pigpio.Gpio; pigpio.configureClock(1, pigpio.CLOCK_PWM); pigpio.configureSocketPort(23456); const led = new Gpio(18, { mode: Gpio.OUTPUT, alert: true }); led.digitalWrite(0); (function closure(): void { const pulseCounts: number[] = []; let pulses = 0; let risingTick = 0; let fallingTick: number; let i: number; led.on('alert', function event(level: number, tick: number): void { if (level === 1) { risingTick = tick; } else { fallingTick = tick; const pulseLength = fallingTick - risingTick; if (pulseCounts[pulseLength] === undefined) { pulseCounts[pulseLength] = 0; } pulseCounts[pulseLength] += 1; pulses += 1; if (pulses === 1000) { for (i = 0; i !== pulseCounts.length; i += 1) { if (pulseCounts[i] !== undefined) { console.log(i + 'us - ' + pulseCounts[i]); } } led.digitalWrite(0); led.disableAlert(); } } }); }()); // frequency 250Hz, duty cycle 7us led.hardwarePwmWrite(250, 250 * 7); })(); (function alert_trigger_pulse_measurement(): void { const Gpio = pigpio.Gpio; let iv: NodeJS.Timer; // pigpio.configureClock(1, pigpio.CLOCK_PCM); const led = new Gpio(17, { mode: Gpio.OUTPUT, alert: true }); led.digitalWrite(0); (function closure(): void { const pulseCounts: number[] = []; let pulses = 0; let risingTick: number; let fallingTick: number; let i: number; led.on('alert', function event(level: number, tick: number): void { if (level === 1) { risingTick = tick; } else { fallingTick = tick; const pulseLength = fallingTick - risingTick; if (pulseCounts[pulseLength] === undefined) { pulseCounts[pulseLength] = 0; } pulseCounts[pulseLength] += 1; pulses += 1; if (pulses === 1000) { for (i = 0; i !== pulseCounts.length; i += 1) { if (pulseCounts[i] !== undefined) { console.log(i + 'us - ' + pulseCounts[i]); } } clearInterval(iv); led.digitalWrite(0); led.disableAlert(); } } }); }()); iv = setInterval(function timer() { led.trigger(10, 1); }, 2); })(); (function alert(): void { const Gpio = pigpio.Gpio; const button = new Gpio(4, { alert: true }); button.on('alert', function event(level: number, tick: number): void { console.log(level + ' ' + tick); }); console.log(' press the momentary push button a few times'); })(); (function banked_leds(): void { const Gpio = pigpio.Gpio; const GpioBank = pigpio.GpioBank; const led17 = new Gpio(17, { mode: Gpio.OUTPUT }); const led18 = new Gpio(18, { mode: Gpio.OUTPUT }); const bank1 = new GpioBank(); let iv: NodeJS.Timer; bank1.clear(1 << 18 | 1 << 17); assert.strictEqual((bank1.read() >> 17) & 0x3, 0, 'expected 0'); iv = setInterval(function timer(): void { const bits = (bank1.read() >> 17) & 0x3; switch (bits) { case 0: bank1.set(1 << 17); assert.strictEqual((bank1.read() >> 17) & 0x3, 1, 'expected 1'); break; case 1: bank1.clear(1 << 17); bank1.set(1 << 18); assert.strictEqual((bank1.read() >> 17) & 0x3, 2, 'expected 2'); break; case 2: bank1.set(1 << 17); bank1.set(1 << 18); assert.strictEqual((bank1.read() >> 17) & 0x3, 3, 'expected 3'); break; case 3: bank1.clear(1 << 17); bank1.clear(1 << 18); assert.strictEqual((bank1.read() >> 17) & 0x3, 0, 'expected 0'); break; } }, 250); setTimeout(function timer() { bank1.clear(1 << 18 | 1 << 17); clearInterval(iv); }, 2000); })(); (function blinky_pwm(): void { const Gpio = pigpio.Gpio; const led = new Gpio(18, { mode: Gpio.OUTPUT }); led.hardwarePwmWrite(10, 500000); setTimeout(function timer() { led.digitalWrite(0); }, 2000); })(); (function blinky(): void { const Gpio = pigpio.Gpio; const led = new Gpio(17, { mode: Gpio.OUTPUT }); const iv: NodeJS.Timer = setInterval(function timer() { led.digitalWrite(led.digitalRead() ^ 1); }, 100); setTimeout(function timer() { led.digitalWrite(0); clearInterval(iv); }, 2000); })(); (function digital_read_performance(): void { const Gpio = pigpio.Gpio; const button = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN }); let time = process.hrtime(); const maxI = 2000000; for (let i = 0; i !== maxI; i += 1) { button.digitalRead(); } time = process.hrtime(time); const ops = Math.floor(maxI / (time[0] + time[1] / 1E9)); console.log(' ' + ops + ' read ops per second'); })(); (function digital_write_performance(): void { const Gpio = pigpio.Gpio; const led = new Gpio(17, { mode: Gpio.OUTPUT }); let time = process.hrtime(); const maxI = 2000000; for (let i = 0; i !== maxI; i += 1) { led.digitalWrite(1); led.digitalWrite(0); } time = process.hrtime(time); const ops = Math.floor((maxI * 2) / (time[0] + time[1] / 1E9)); console.log(' ' + ops + ' write ops per second'); })(); (function gpio_mode(): void { const Gpio = pigpio.Gpio; const gpio7 = new Gpio(7, { mode: Gpio.INPUT }); const gpio8 = new Gpio(8, { mode: Gpio.OUTPUT }); assert.strictEqual(gpio7.getMode(), Gpio.INPUT, 'expected INPUT mode for gpio7'); assert.strictEqual(gpio8.getMode(), Gpio.OUTPUT, 'expected OUTPUT mode for gpio8'); gpio8.mode(Gpio.INPUT); assert.strictEqual(gpio8.getMode(), Gpio.INPUT, 'expected INPUT mode for gpio8'); gpio7.mode(Gpio.OUTPUT); assert.strictEqual(gpio7.getMode(), Gpio.OUTPUT, 'expected OUTPUT mode for gpio7'); gpio7.mode(Gpio.INPUT); assert.strictEqual(gpio7.getMode(), Gpio.INPUT, 'expected INPUT mode for gpio7'); })(); (function gpio_numbers(): void { const Gpio = pigpio.Gpio; assert.strictEqual(Gpio.MIN_GPIO, 0, 'expected Gpio.MIN_GPIO to be 0'); assert.strictEqual(Gpio.MAX_GPIO, 53, 'expected Gpio.MAX_GPIO to be 53'); assert.strictEqual(Gpio.MAX_USER_GPIO, 31, 'expected Gpio.MAX_USER_GPIO to be 31'); })(); (function isr_enable_disable(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { mode: Gpio.INPUT }); const output = new Gpio(8, { mode: Gpio.OUTPUT }); let risingCount = 0; let fallingCount = 0; // Put output (and input) in a known state. output.digitalWrite(0); // Toggle output (and input) every 10 ms const iv = setInterval(function timer() { output.digitalWrite(output.digitalRead() ^ 1); }, 10); // ISR input.on('interrupt', function event(level: number) { if (level === 0) { fallingCount += 1; } else if (level === 1) { risingCount += 1; } }); function noEdge() { console.log(' no edge'); input.disableInterrupt(); risingCount = 0; fallingCount = 0; setTimeout(function timer() { console.log(' ' + risingCount + ' rising edge interrupts (0 expected)'); console.log(' ' + fallingCount + ' falling edge interrupts (0 expected)'); clearInterval(iv); input.disableInterrupt(); }, 1000); } function fallingEdge() { console.log(' falling edge'); input.enableInterrupt(Gpio.FALLING_EDGE); risingCount = 0; fallingCount = 0; setTimeout(function timer() { console.log(' ' + risingCount + ' rising edge interrupts (0 expected)'); console.log(' ' + fallingCount + ' falling edge interrupts (~50 expected)'); noEdge(); }, 1000); } function risingEdge() { console.log(' rising edge'); input.enableInterrupt(Gpio.RISING_EDGE); risingCount = 0; fallingCount = 0; setTimeout(function timer() { console.log(' ' + risingCount + ' rising edge interrupts (~50 expected)'); console.log(' ' + fallingCount + ' falling edge interrupts (0 expected)'); fallingEdge(); }, 1000); } (function eitherEdge() { console.log(' either edge'); input.enableInterrupt(Gpio.EITHER_EDGE); risingCount = 0; fallingCount = 0; setTimeout(function timer() { console.log(' ' + risingCount + ' rising edge interrupts (~50 expected)'); console.log(' ' + fallingCount + ' falling edge interrupts (~50 expected)'); risingEdge(); }, 1000); }()); })(); (function isr_multiple_sources(): void { const Gpio = pigpio.Gpio; [[7, 8], [9, 11]].forEach(function loop(gpioNos: [number, number]) { let interruptCount = 0; const input = new Gpio(gpioNos[0], { mode: Gpio.INPUT, edge: Gpio.EITHER_EDGE }); const output = new Gpio(gpioNos[1], { mode: Gpio.OUTPUT }); // Put input and output in a known state output.digitalWrite(0); input.on('interrupt', function event(level: number) { interruptCount += 1; output.digitalWrite(level ^ 1); if (interruptCount === 1000) { console.log(' ' + interruptCount + ' interrupts detected on GPIO' + gpioNos[0]); input.disableInterrupt(); } }); setTimeout(function timer() { // Trigger first interrupt output.digitalWrite(1); }, 1); }); })(); (function isr_performance(): void { const Gpio = pigpio.Gpio; let interruptCount = 0; const input = new Gpio(7, { mode: Gpio.INPUT, edge: Gpio.EITHER_EDGE }); const output = new Gpio(8, { mode: Gpio.OUTPUT }); output.digitalWrite(0); input.on('interrupt', function event(level: number) { interruptCount++; output.digitalWrite(level ^ 1); }); setTimeout(function timer() { let time = process.hrtime(); output.digitalWrite(1); setTimeout(function timer() { time = process.hrtime(time); const interruptsPerSec = Math.floor(interruptCount / (time[0] + time[1] / 1E9)); console.log(' ' + interruptsPerSec + ' interrupts per second'); input.disableInterrupt(); }, 1000); }, 1); })(); (function isr_timeouts_2(): void { const Gpio = pigpio.Gpio; let timeoutCount = 0; const input = new Gpio(7, { mode: Gpio.INPUT, edge: Gpio.EITHER_EDGE, timeout: 100 }); input.on('interrupt', function timer(level: number) { if (level === Gpio.TIMEOUT) { timeoutCount++; } }); setTimeout(function time() { console.log(' ' + timeoutCount + ' timeouts detected (~10 expected)'); input.enableInterrupt(Gpio.EITHER_EDGE, 1); timeoutCount = 0; setTimeout(function timer() { input.disableInterrupt(); console.log(' ' + timeoutCount + ' timeouts detected (~1000 expected)'); }, 1000); }, 1000); })(); (function isr_timeouts(): void { const Gpio = pigpio.Gpio; let timeoutCount = 0; const input = new Gpio(7, { mode: Gpio.INPUT, edge: Gpio.EITHER_EDGE, timeout: 10 }); input.on('interrupt', function timer(level: number) { if (level === Gpio.TIMEOUT) { timeoutCount++; } }); setTimeout(function timer() { console.log(' ' + timeoutCount + ' timeouts detected (~100 expected)'); input.enableInterrupt(Gpio.EITHER_EDGE); timeoutCount = 0; setTimeout(function timer() { input.disableInterrupt(); console.log(' ' + timeoutCount + ' timeouts detected (0 expected)'); }, 1000); }, 1000); })(); (function light_switch(): void { const Gpio = pigpio.Gpio; const button = new Gpio(4, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.EITHER_EDGE }); const led = new Gpio(17, { mode: Gpio.OUTPUT }); button.on('interrupt', function event(level: number) { led.digitalWrite(level); }); setTimeout(function timer() { led.digitalWrite(0); button.disableInterrupt(); }, 2000); console.log(' press the momentary push button a few times'); })(); (function notifier_leak_check(): void { const Gpio = pigpio.Gpio; const Notifier = pigpio.Notifier; let notifierCount = 0; const LED_GPIO = 18; const FREQUENCY = 25000; (function closure() { const led = new Gpio(LED_GPIO, { mode: Gpio.OUTPUT }); led.hardwarePwmWrite(FREQUENCY, 500000); }()); (function next() { const ledNotifier = new Notifier({ bits: 1 << LED_GPIO }); let closing = false; ledNotifier.stream().on('data', function event() { if (!closing) { ledNotifier.stream().on('close', function event() { notifierCount += 1; if (notifierCount % 1000 === 0) { console.log(notifierCount); } if (notifierCount < 100000) { next(); } }); ledNotifier.close(); closing = true; } }); }()); })(); (function notifier_pwm(): void { const Gpio = pigpio.Gpio; const Notifier = pigpio.Notifier; const LED_GPIO = 18; const FREQUENCY = 25000; (function closure() { const led = new Gpio(LED_GPIO, { mode: Gpio.OUTPUT }); led.hardwarePwmWrite(FREQUENCY, 500000); }()); (function closure() { const ledNotifier = new Notifier({ bits: 1 << LED_GPIO }); let notificationsReceived = 0; let seqnoErrors = 0; let ledStateErrors = 0; let lastSeqno: number; let lastLedState: number; let lastTick: number; let minTickDiff = 0xffffffff; let maxTickDiff = 0; ledNotifier.stream().on('data', function event(buf: Buffer) { for (let ix = 0; ix < buf.length; ix += Notifier.NOTIFICATION_LENGTH) { const seqno = buf.readUInt16LE(ix); const tick = buf.readUInt32LE(ix + 4); const level = buf.readUInt32LE(ix + 8); if (notificationsReceived > 0) { if (lastLedState === (level & (1 << LED_GPIO))) { console.log(' unexpected led state'); ledStateErrors += 1; } if ((lastSeqno + 1) !== seqno) { console.log(' seqno error, was %d, expected %d', seqno, lastSeqno + 1); seqnoErrors += 1; } if (tick - lastTick < minTickDiff) { minTickDiff = tick - lastTick; } if (tick - lastTick > maxTickDiff) { maxTickDiff = tick - lastTick; } } notificationsReceived += 1; lastSeqno = seqno; lastLedState = level & (1 << LED_GPIO); lastTick = tick; } if (notificationsReceived >= 50000) { ledNotifier.stream().pause(); ledNotifier.close(); console.log(' notifications: %d', notificationsReceived); console.log(' seqno errors: %d', seqnoErrors); console.log(' led state errors: %d', ledStateErrors); console.log(' expected tick diff: %d us', 1000000 / (FREQUENCY * 2)); console.log(' min tick diff: %d us', minTickDiff); console.log(' max tick diff: %d us', maxTickDiff); } }); }()); })(); (function notifier_stress(): void { const Gpio = pigpio.Gpio; const Notifier = pigpio.Notifier; const LED_GPIO = 18; const FREQUENCY = 150000; pigpio.configureClock(1, pigpio.CLOCK_PCM); (function closure() { const led = new Gpio(LED_GPIO, { mode: Gpio.OUTPUT }); led.hardwarePwmWrite(FREQUENCY, 500000); }()); (function closure() { const ledNotifier = new Notifier({ bits: 1 << LED_GPIO }); let notificationsReceived = 0; let events = 0; let seqnoErrors = 0; let ledStateErrors = 0; let lastSeqno: number; let lastLedState: number; let lastTick: number; let minTickDiff = 0xffffffff; let maxTickDiff = 0; let restBuf: Buffer | null = null; let iv: NodeJS.Timer; function printInfo() { console.log(); console.log(' events: %d', events); console.log(' notifications: %d', notificationsReceived); console.log(' seqno errors: %d', seqnoErrors); console.log(' led state errors: %d', ledStateErrors); console.log(' expected tick diff: %d us', 1000000 / (FREQUENCY * 2)); console.log(' min tick diff: %d us', minTickDiff); console.log(' max tick diff: %d us', maxTickDiff); minTickDiff = 0xffffffff; maxTickDiff = 0; } ledNotifier.stream().on('data', function event(buf: Buffer) { let entries: number; events += 1; if (restBuf !== null) { buf = Buffer.concat([restBuf, buf]); } entries = Math.floor(buf.length / Notifier.NOTIFICATION_LENGTH); const rest = buf.length % Notifier.NOTIFICATION_LENGTH; restBuf = rest === 0 ? null : new Buffer(buf.slice(buf.length - rest)); for (let ix = 0; ix < buf.length - rest; ix += Notifier.NOTIFICATION_LENGTH) { const seqno = buf.readUInt16LE(ix); const tick = buf.readUInt32LE(ix + 4); const level = buf.readUInt32LE(ix + 8); if (notificationsReceived > 0) { if (lastLedState === (level & (1 << LED_GPIO))) { console.log(' unexpected led state'); ledStateErrors += 1; } if (((lastSeqno + 1) & 0xffff) !== seqno) { console.log(' seqno error, was %d, expected %d', seqno, lastSeqno + 1); seqnoErrors += 1; } if (tick - lastTick < minTickDiff) { minTickDiff = tick - lastTick; } if (tick - lastTick > maxTickDiff) { maxTickDiff = tick - lastTick; } } notificationsReceived += 1; lastSeqno = seqno; lastLedState = level & (1 << LED_GPIO); lastTick = tick; } if (notificationsReceived >= 1e9) { ledNotifier.stream().pause(); ledNotifier.close(); clearInterval(iv); printInfo(); } }); iv = setInterval(printInfo, 5000); }()); })(); (function notifier(): void { const Gpio = pigpio.Gpio; const Notifier = pigpio.Notifier; const LED_GPIO = 17; const LED_TOGGLES = 1000; (function closure() { const led = new Gpio(LED_GPIO, { mode: Gpio.OUTPUT }); let ledToggles = 0; let lastTime = process.hrtime(); let minSetIntervalDiff = 0xffffffff; let maxSetIntervalDiff = 0; const iv = setInterval(function timer() { const time = process.hrtime(); const diff = Math.floor(((time[0] * 1e9 + time[1]) - (lastTime[0] * 1e9 + lastTime[1])) / 1000); lastTime = time; if (diff < minSetIntervalDiff) { minSetIntervalDiff = diff; } if (diff > maxSetIntervalDiff) { maxSetIntervalDiff = diff; } led.digitalWrite(led.digitalRead() ^ 1); ledToggles += 1; if (ledToggles === LED_TOGGLES) { clearInterval(iv); console.log(' led toggles: %d', ledToggles); console.log(' min setInterval diff: %d us', minSetIntervalDiff); console.log(' max setInterval diff: %d us', maxSetIntervalDiff); } }, 1); }()); (function closure() { const ledNotifier = new Notifier({ bits: 1 << LED_GPIO }); let notificationsReceived = 0; let seqnoErrors = 0; let ledStateErrors = 0; let lastSeqno: number; let lastLedState: number; let lastTick: number; let minTickDiff = 0xffffffff; let maxTickDiff = 0; ledNotifier.stream().on('data', function event(buf: Buffer) { for (let ix = 0; ix < buf.length; ix += Notifier.NOTIFICATION_LENGTH) { const seqno = buf.readUInt16LE(ix); const tick = buf.readUInt32LE(ix + 4); const level = buf.readUInt32LE(ix + 8); if (notificationsReceived > 0) { if (lastLedState === (level & (1 << LED_GPIO))) { console.log(' unexpected led state'); ledStateErrors += 1; } if ((lastSeqno + 1) !== seqno) { console.log(' seqno error, was %d, expected %d', seqno, lastSeqno + 1); seqnoErrors += 1; } if (tick - lastTick < minTickDiff) { minTickDiff = tick - lastTick; } if (tick - lastTick > maxTickDiff) { maxTickDiff = tick - lastTick; } } notificationsReceived += 1; lastSeqno = seqno; lastLedState = level & (1 << LED_GPIO); lastTick = tick; } if (notificationsReceived >= LED_TOGGLES) { ledNotifier.close(); console.log(' notifications: %d', notificationsReceived); console.log(' seqno errors: %d', seqnoErrors); console.log(' led state errors: %d', ledStateErrors); console.log(' min tick diff: %d us', minTickDiff); console.log(' max tick diff: %d us', maxTickDiff); } }); }()); })(); (function pull_up_down(): void { const Gpio = pigpio.Gpio; const input = new Gpio(22, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_UP }); assert.strictEqual(input.digitalRead(), 1, 'expected gpio22 to be 1'); input.pullUpDown(Gpio.PUD_DOWN); assert.strictEqual(input.digitalRead(), 0, 'expected gpio22 to be 0'); })(); (function pulse_led(): void { const Gpio = pigpio.Gpio; const led = new Gpio(17, { mode: Gpio.OUTPUT }); let dutyCycle = 0; const iv = setInterval(function timer() { led.pwmWrite(dutyCycle); const dutyCycleRead: number = led.getPwmDutyCycle(); assert.strictEqual(dutyCycleRead, dutyCycle, 'expected dutyCycle to be ' + dutyCycle + ', not ' + dutyCycleRead ); dutyCycle += 5; if (dutyCycle > 255) { dutyCycle = 0; } }, 20); setTimeout(function timer() { led.digitalWrite(0); clearInterval(iv); }, 2000); })(); (function pwm(): void { const Gpio = pigpio.Gpio; const led = new Gpio(18, { mode: Gpio.OUTPUT }); let dutyCycle: number; assert.strictEqual(led.getPwmRange(), 255, 'expected pwm range to be 255'); assert.strictEqual(led.getPwmRealRange(), 250, 'expected pwm real range to be 250'); assert.strictEqual(led.getPwmFrequency(), 800, 'expected get pwm frequency to be 800'); led.pwmRange(125); assert.strictEqual(led.getPwmRange(), 125, 'expected pwm range to be 125'); assert.strictEqual(led.getPwmRealRange(), 250, 'expected pwm real range to be 250'); assert.strictEqual(led.getPwmFrequency(), 800, 'expected get pwm frequency to be 800'); led.pwmFrequency(2000); assert.strictEqual(led.getPwmRange(), 125, 'expected pwm range to be 125'); assert.strictEqual(led.getPwmRealRange(), 100, 'expected pwm real range to be 100'); assert.strictEqual(led.getPwmFrequency(), 2000, 'expected get pwm frequency to be 2000'); dutyCycle = Math.floor(led.getPwmRange() / 2); led.pwmWrite(dutyCycle); assert.strictEqual(led.getPwmDutyCycle(), dutyCycle, 'expected duty cycle to be ' + dutyCycle); led.hardwarePwmWrite(1e7, 500000); assert.strictEqual(led.getPwmRange(), 1e6, 'expected pwm range to be 1e6'); assert.strictEqual(led.getPwmRealRange(), 25, 'expected pwm real range to be 25'); assert.strictEqual(led.getPwmFrequency(), 1e7, 'expected get pwm frequency to be 1e7'); assert.strictEqual(led.getPwmDutyCycle(), 500000, 'expected duty cycle to be 500000'); led.digitalWrite(0); assert.strictEqual(led.getPwmRange(), 125, 'expected pwm range to be 125'); assert.strictEqual(led.getPwmRealRange(), 100, 'expected pwm real range to be 100'); assert.strictEqual(led.getPwmFrequency(), 2000, 'expected get pwm frequency to be 2000'); }); (function servo_control(): void { const Gpio = pigpio.Gpio; let iv: NodeJS.Timer; const motor = new Gpio(17, { mode: Gpio.OUTPUT }); let pulseWidth = 500; motor.servoWrite(0); assert.strictEqual(motor.getServoPulseWidth(), 0, 'expected pulseWidth to be 0' ); iv = setInterval(function timer() { motor.servoWrite(pulseWidth); const pulseWidthRead = motor.getServoPulseWidth(); assert.strictEqual(pulseWidthRead, pulseWidth, 'expected pulseWidth to be ' + pulseWidth + ', not ' + pulseWidthRead ); pulseWidth += 25; if (pulseWidth > 2500) { pulseWidth = 500; } }, 20); setTimeout(function timer() { motor.digitalWrite(0); clearInterval(iv); }, 2000); })(); (function tirgger_led(): void { const Gpio = pigpio.Gpio; let iv: NodeJS.Timer; const led = new Gpio(17, { mode: Gpio.OUTPUT }); iv = setInterval(function timer() { led.trigger(100, 1); }, 2); setTimeout(function timer() { led.digitalWrite(0); clearInterval(iv); }, 2000); })(); (function tickAndTickDiff(): void { const startTick: number = pigpio.getTick(); setTimeout(() => { const endTick: number = pigpio.getTick(); const diff: number = pigpio.tickDiff(startTick, endTick); assert.ok(diff > 0, 'expected tick count to increase across a timer call'); }, 50); })(); (function gpio_glitch_filter(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { mode: Gpio.INPUT, pullUpDown: Gpio.PUD_OFF, alert: true }); const output = new Gpio(8, { mode: Gpio.OUTPUT }); let count = 0; output.digitalWrite(0); input.glitchFilter(50); input.on('alert', (level, tick) => { if (level === 1) { count++; console.log(' rising edge, count=' + count); } }); output.trigger(30, 1); // alert function should not be executed (blocked by glitchFilter) setTimeout(() => { output.trigger(70, 1); // alert function should be executed }, 500); setTimeout(() => { assert.strictEqual(count, 1, 'expected 1 alert function call instead of ' + count); console.log(" success..."); process.exit(0); }, 1000); })();
the_stack
import {Bounds} from '../css/layout/bounds'; import { isBodyElement, isCanvasElement, isElementNode, isHTMLElementNode, isIFrameElement, isImageElement, isScriptElement, isSelectElement, isStyleElement, isSVGElementNode, isTextareaElement, isTextNode } from './node-parser'; import {isIdentToken, nonFunctionArgSeparator} from '../css/syntax/parser'; import {TokenType} from '../css/syntax/tokenizer'; import {CounterState, createCounterText} from '../css/types/functions/counter'; import {LIST_STYLE_TYPE, listStyleType} from '../css/property-descriptors/list-style-type'; import {CSSParsedCounterDeclaration, CSSParsedPseudoDeclaration} from '../css/index'; import {getQuote} from '../css/property-descriptors/quotes'; import {Context} from '../core/context'; import {DebuggerType, isDebugging} from '../core/debugger'; export interface CloneOptions { ignoreElements?: (element: Element) => boolean; onclone?: (document: Document, element: HTMLElement) => void; allowTaint?: boolean; } export interface WindowOptions { scrollX: number; scrollY: number; windowWidth: number; windowHeight: number; } export type CloneConfigurations = CloneOptions & { inlineImages: boolean; copyStyles: boolean; }; const IGNORE_ATTRIBUTE = 'data-html2canvas-ignore'; export class DocumentCloner { private readonly scrolledElements: [Element, number, number][]; private readonly referenceElement: HTMLElement; clonedReferenceElement?: HTMLElement; private readonly documentElement: HTMLElement; private readonly counters: CounterState; private quoteDepth: number; constructor( private readonly context: Context, element: HTMLElement, private readonly options: CloneConfigurations ) { this.scrolledElements = []; this.referenceElement = element; this.counters = new CounterState(); this.quoteDepth = 0; if (!element.ownerDocument) { throw new Error('Cloned element does not have an owner document'); } this.documentElement = this.cloneNode(element.ownerDocument.documentElement) as HTMLElement; } toIFrame(ownerDocument: Document, windowSize: Bounds): Promise<HTMLIFrameElement> { const iframe: HTMLIFrameElement = createIFrameContainer(ownerDocument, windowSize); if (!iframe.contentWindow) { return Promise.reject(`Unable to find iframe window`); } const scrollX = (ownerDocument.defaultView as Window).pageXOffset; const scrollY = (ownerDocument.defaultView as Window).pageYOffset; const cloneWindow = iframe.contentWindow; const documentClone: Document = cloneWindow.document; /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle if window url is about:blank, we can assign the url to current by writing onto the document */ const iframeLoad = iframeLoader(iframe).then(async () => { this.scrolledElements.forEach(restoreNodeScroll); if (cloneWindow) { cloneWindow.scrollTo(windowSize.left, windowSize.top); if ( /(iPad|iPhone|iPod)/g.test(navigator.userAgent) && (cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left) ) { this.context.logger.warn('Unable to restore scroll position for cloned document'); this.context.windowBounds = this.context.windowBounds.add( cloneWindow.scrollX - windowSize.left, cloneWindow.scrollY - windowSize.top, 0, 0 ); } } const onclone = this.options.onclone; const referenceElement = this.clonedReferenceElement; if (typeof referenceElement === 'undefined') { return Promise.reject(`Error finding the ${this.referenceElement.nodeName} in the cloned document`); } if (documentClone.fonts && documentClone.fonts.ready) { await documentClone.fonts.ready; } if (/(AppleWebKit)/g.test(navigator.userAgent)) { await imagesReady(documentClone); } if (typeof onclone === 'function') { return Promise.resolve() .then(() => onclone(documentClone, referenceElement)) .then(() => iframe); } return iframe; }); documentClone.open(); documentClone.write(`${serializeDoctype(document.doctype)}<html></html>`); // Chrome scrolls the parent document for some reason after the write to the cloned window??? restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY); documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement); documentClone.close(); return iframeLoad; } createElementClone<T extends HTMLElement | SVGElement>(node: T): HTMLElement | SVGElement { if (isDebugging(node, DebuggerType.CLONE)) { debugger; } if (isCanvasElement(node)) { return this.createCanvasClone(node); } if (isStyleElement(node)) { return this.createStyleClone(node); } const clone = node.cloneNode(false) as T; if (isImageElement(clone)) { if (isImageElement(node) && node.currentSrc && node.currentSrc !== node.src) { clone.src = node.currentSrc; clone.srcset = ''; } if (clone.loading === 'lazy') { clone.loading = 'eager'; } } return clone; } createStyleClone(node: HTMLStyleElement): HTMLStyleElement { try { const sheet = node.sheet as CSSStyleSheet | undefined; if (sheet && sheet.cssRules) { const css: string = [].slice.call(sheet.cssRules, 0).reduce((css: string, rule: CSSRule) => { if (rule && typeof rule.cssText === 'string') { return css + rule.cssText; } return css; }, ''); const style = node.cloneNode(false) as HTMLStyleElement; style.textContent = css; return style; } } catch (e) { // accessing node.sheet.cssRules throws a DOMException this.context.logger.error('Unable to access cssRules property', e); if (e.name !== 'SecurityError') { throw e; } } return node.cloneNode(false) as HTMLStyleElement; } createCanvasClone(canvas: HTMLCanvasElement): HTMLImageElement | HTMLCanvasElement { if (this.options.inlineImages && canvas.ownerDocument) { const img = canvas.ownerDocument.createElement('img'); try { img.src = canvas.toDataURL(); return img; } catch (e) { this.context.logger.info(`Unable to inline canvas contents, canvas is tainted`, canvas); } } const clonedCanvas = canvas.cloneNode(false) as HTMLCanvasElement; try { clonedCanvas.width = canvas.width; clonedCanvas.height = canvas.height; const ctx = canvas.getContext('2d'); const clonedCtx = clonedCanvas.getContext('2d'); if (clonedCtx) { if (!this.options.allowTaint && ctx) { clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0); } else { const gl = canvas.getContext('webgl2') ?? canvas.getContext('webgl'); if (gl) { const attribs = gl.getContextAttributes(); if (attribs?.preserveDrawingBuffer === false) { this.context.logger.warn( 'Unable to clone WebGL context as it has preserveDrawingBuffer=false', canvas ); } } clonedCtx.drawImage(canvas, 0, 0); } } return clonedCanvas; } catch (e) { this.context.logger.info(`Unable to clone canvas as it is tainted`, canvas); } return clonedCanvas; } cloneNode(node: Node): Node { if (isTextNode(node)) { return document.createTextNode(node.data); } if (!node.ownerDocument) { return node.cloneNode(false); } const window = node.ownerDocument.defaultView; if (window && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) { const clone = this.createElementClone(node); clone.style.transitionProperty = 'none'; const style = window.getComputedStyle(node); const styleBefore = window.getComputedStyle(node, ':before'); const styleAfter = window.getComputedStyle(node, ':after'); if (this.referenceElement === node && isHTMLElementNode(clone)) { this.clonedReferenceElement = clone; } if (isBodyElement(clone)) { createPseudoHideStyles(clone); } const counters = this.counters.parse(new CSSParsedCounterDeclaration(this.context, style)); const before = this.resolvePseudoContent(node, clone, styleBefore, PseudoElementType.BEFORE); for (let child = node.firstChild; child; child = child.nextSibling) { if ( !isElementNode(child) || (!isScriptElement(child) && !child.hasAttribute(IGNORE_ATTRIBUTE) && (typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child))) ) { if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) { clone.appendChild(this.cloneNode(child)); } } } if (before) { clone.insertBefore(before, clone.firstChild); } const after = this.resolvePseudoContent(node, clone, styleAfter, PseudoElementType.AFTER); if (after) { clone.appendChild(after); } this.counters.pop(counters); if (style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) { copyCSSStyles(style, clone); } if (node.scrollTop !== 0 || node.scrollLeft !== 0) { this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]); } if ( (isTextareaElement(node) || isSelectElement(node)) && (isTextareaElement(clone) || isSelectElement(clone)) ) { clone.value = node.value; } return clone; } return node.cloneNode(false); } resolvePseudoContent( node: Element, clone: Element, style: CSSStyleDeclaration, pseudoElt: PseudoElementType ): HTMLElement | void { if (!style) { return; } const value = style.content; const document = clone.ownerDocument; if (!document || !value || value === 'none' || value === '-moz-alt-content' || style.display === 'none') { return; } this.counters.parse(new CSSParsedCounterDeclaration(this.context, style)); const declaration = new CSSParsedPseudoDeclaration(this.context, style); const anonymousReplacedElement = document.createElement('html2canvaspseudoelement'); copyCSSStyles(style, anonymousReplacedElement); declaration.content.forEach((token) => { if (token.type === TokenType.STRING_TOKEN) { anonymousReplacedElement.appendChild(document.createTextNode(token.value)); } else if (token.type === TokenType.URL_TOKEN) { const img = document.createElement('img'); img.src = token.value; img.style.opacity = '1'; anonymousReplacedElement.appendChild(img); } else if (token.type === TokenType.FUNCTION) { if (token.name === 'attr') { const attr = token.values.filter(isIdentToken); if (attr.length) { anonymousReplacedElement.appendChild( document.createTextNode(node.getAttribute(attr[0].value) || '') ); } } else if (token.name === 'counter') { const [counter, counterStyle] = token.values.filter(nonFunctionArgSeparator); if (counter && isIdentToken(counter)) { const counterState = this.counters.getCounterValue(counter.value); const counterType = counterStyle && isIdentToken(counterStyle) ? listStyleType.parse(this.context, counterStyle.value) : LIST_STYLE_TYPE.DECIMAL; anonymousReplacedElement.appendChild( document.createTextNode(createCounterText(counterState, counterType, false)) ); } } else if (token.name === 'counters') { const [counter, delim, counterStyle] = token.values.filter(nonFunctionArgSeparator); if (counter && isIdentToken(counter)) { const counterStates = this.counters.getCounterValues(counter.value); const counterType = counterStyle && isIdentToken(counterStyle) ? listStyleType.parse(this.context, counterStyle.value) : LIST_STYLE_TYPE.DECIMAL; const separator = delim && delim.type === TokenType.STRING_TOKEN ? delim.value : ''; const text = counterStates .map((value) => createCounterText(value, counterType, false)) .join(separator); anonymousReplacedElement.appendChild(document.createTextNode(text)); } } else { // console.log('FUNCTION_TOKEN', token); } } else if (token.type === TokenType.IDENT_TOKEN) { switch (token.value) { case 'open-quote': anonymousReplacedElement.appendChild( document.createTextNode(getQuote(declaration.quotes, this.quoteDepth++, true)) ); break; case 'close-quote': anonymousReplacedElement.appendChild( document.createTextNode(getQuote(declaration.quotes, --this.quoteDepth, false)) ); break; default: // safari doesn't parse string tokens correctly because of lack of quotes anonymousReplacedElement.appendChild(document.createTextNode(token.value)); } } }); anonymousReplacedElement.className = `${PSEUDO_HIDE_ELEMENT_CLASS_BEFORE} ${PSEUDO_HIDE_ELEMENT_CLASS_AFTER}`; const newClassName = pseudoElt === PseudoElementType.BEFORE ? ` ${PSEUDO_HIDE_ELEMENT_CLASS_BEFORE}` : ` ${PSEUDO_HIDE_ELEMENT_CLASS_AFTER}`; if (isSVGElementNode(clone)) { clone.className.baseValue += newClassName; } else { clone.className += newClassName; } return anonymousReplacedElement; } static destroy(container: HTMLIFrameElement): boolean { if (container.parentNode) { container.parentNode.removeChild(container); return true; } return false; } } enum PseudoElementType { BEFORE, AFTER } const createIFrameContainer = (ownerDocument: Document, bounds: Bounds): HTMLIFrameElement => { const cloneIframeContainer = ownerDocument.createElement('iframe'); cloneIframeContainer.className = 'html2canvas-container'; cloneIframeContainer.style.visibility = 'hidden'; cloneIframeContainer.style.position = 'fixed'; cloneIframeContainer.style.left = '-10000px'; cloneIframeContainer.style.top = '0px'; cloneIframeContainer.style.border = '0'; cloneIframeContainer.width = bounds.width.toString(); cloneIframeContainer.height = bounds.height.toString(); cloneIframeContainer.scrolling = 'no'; // ios won't scroll without it cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, 'true'); ownerDocument.body.appendChild(cloneIframeContainer); return cloneIframeContainer; }; const imageReady = (img: HTMLImageElement): Promise<Event | void | string> => { return new Promise((resolve) => { if (img.complete) { resolve(); return; } if (!img.src) { resolve(); return; } img.onload = resolve; img.onerror = resolve; }); }; const imagesReady = (document: HTMLDocument): Promise<unknown[]> => { return Promise.all([].slice.call(document.images, 0).map(imageReady)); }; const iframeLoader = (iframe: HTMLIFrameElement): Promise<HTMLIFrameElement> => { return new Promise((resolve, reject) => { const cloneWindow = iframe.contentWindow; if (!cloneWindow) { return reject(`No window assigned for iframe`); } const documentClone = cloneWindow.document; cloneWindow.onload = iframe.onload = () => { cloneWindow.onload = iframe.onload = null; const interval = setInterval(() => { if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') { clearInterval(interval); resolve(iframe); } }, 50); }; }); }; const ignoredStyleProperties = [ 'all', // #2476 'd', // #2483 'content' // Safari shows pseudoelements if content is set ]; export const copyCSSStyles = <T extends HTMLElement | SVGElement>(style: CSSStyleDeclaration, target: T): T => { // Edge does not provide value for cssText for (let i = style.length - 1; i >= 0; i--) { const property = style.item(i); if (ignoredStyleProperties.indexOf(property) === -1) { target.style.setProperty(property, style.getPropertyValue(property)); } } return target; }; const serializeDoctype = (doctype?: DocumentType | null): string => { let str = ''; if (doctype) { str += '<!DOCTYPE '; if (doctype.name) { str += doctype.name; } if (doctype.internalSubset) { str += doctype.internalSubset; } if (doctype.publicId) { str += `"${doctype.publicId}"`; } if (doctype.systemId) { str += `"${doctype.systemId}"`; } str += '>'; } return str; }; const restoreOwnerScroll = (ownerDocument: Document | null, x: number, y: number) => { if ( ownerDocument && ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset) ) { ownerDocument.defaultView.scrollTo(x, y); } }; const restoreNodeScroll = ([element, x, y]: [HTMLElement, number, number]) => { element.scrollLeft = x; element.scrollTop = y; }; const PSEUDO_BEFORE = ':before'; const PSEUDO_AFTER = ':after'; const PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = '___html2canvas___pseudoelement_before'; const PSEUDO_HIDE_ELEMENT_CLASS_AFTER = '___html2canvas___pseudoelement_after'; const PSEUDO_HIDE_ELEMENT_STYLE = `{ content: "" !important; display: none !important; }`; const createPseudoHideStyles = (body: HTMLElement) => { createStyles( body, `.${PSEUDO_HIDE_ELEMENT_CLASS_BEFORE}${PSEUDO_BEFORE}${PSEUDO_HIDE_ELEMENT_STYLE} .${PSEUDO_HIDE_ELEMENT_CLASS_AFTER}${PSEUDO_AFTER}${PSEUDO_HIDE_ELEMENT_STYLE}` ); }; const createStyles = (body: HTMLElement, styles: string) => { const document = body.ownerDocument; if (document) { const style = document.createElement('style'); style.textContent = styles; body.appendChild(style); } };
the_stack
import * as React from "react" import { Mark } from "semiotic-mark" import { line, area, curveStep, curveStepBefore, curveStepAfter, curveCardinal, curveBasis, curveLinear, curveCatmullRom, curveMonotoneX, curveMonotoneY, curveNatural } from "d3-shape" import { shapeBounds } from "../svg/areaDrawing" import { GenericObject, ProjectedSummary } from "../types/generalTypes" import { ScaleLinear } from "d3-scale" export const curveHash = { step: curveStep, stepbefore: curveStepBefore, stepafter: curveStepAfter, cardinal: curveCardinal, basis: curveBasis, linear: curveLinear, catmullrom: curveCatmullRom, monotone: curveMonotoneY, monotonex: curveMonotoneX, monotoney: curveMonotoneY, natural: curveNatural } export function lineGeneratorDecorator({ generator, projectedCoordinateNames, defined, xScale, yScale, interpolator, simpleLine }) { const { x, y, yTop, yBottom } = projectedCoordinateNames generator.x(d => xScale(d[x])).curve(interpolator) if (simpleLine) { generator.y(d => yScale(d[y])) } else { generator.y0(d => yScale(d[yBottom])).y1(d => yScale(d[yTop])) } if (defined) { generator.defined((p, q) => defined(p, q)) } else { generator.defined(p => !p._xyFrameUndefined) } } export function createPoints({ xScale, yScale, canvasDrawing, data, projectedCoordinateNames, customMark, canvasRender, styleFn, classFn, renderKeyFn, renderMode, baseMarkProps, showLinePoints: baseShowLinePoints }) { const { y, x, xMiddle, yMiddle, yTop, yBottom } = projectedCoordinateNames const showLinePoints: string = baseShowLinePoints === true ? undefined : baseShowLinePoints const whichPoints: { top: string bottom: string } = { top: yTop, bottom: yBottom } const whichWay = whichPoints[showLinePoints] const mappedPoints = [] data.forEach((d, i) => { const dX = xScale(d[xMiddle] !== undefined ? d[xMiddle] : d[x]) const dY = yScale( d[whichWay] !== undefined ? d[whichWay] : d[yMiddle] !== undefined ? d[yMiddle] : d[y] ) const pointAriaLabel = `Point at x ${d.x} and y ${d.y}` // CUSTOM MARK IMPLEMENTATION const renderedCustomMark = !customMark ? undefined : React.isValidElement(customMark) ? customMark : customMark({ d: d.data, xy: d, i, xScale, yScale }) const markProps = customMark ? Object.assign(baseMarkProps, renderedCustomMark.props, { "aria-label": pointAriaLabel }) : { ...baseMarkProps, key: `piece-${i}`, markType: "circle", r: 2, "aria-label": pointAriaLabel } if ( renderedCustomMark && renderedCustomMark.props && !renderedCustomMark.props.markType && (!canvasRender || canvasRender(d.data, i) !== true) ) { mappedPoints.push( <g transform={`translate(${dX},${dY})`} key={renderKeyFn ? renderKeyFn(d.data, i) : `custom-point-mark-${i}`} style={styleFn ? styleFn(d.data, i) : {}} className={classFn ? classFn(d.data, i) : ""} > {renderedCustomMark} </g> ) } else { if (canvasRender && canvasRender(d.data, i) === true) { const canvasPoint = { type: "point", baseClass: "frame-piece", tx: dX, ty: dY, d, i, markProps, styleFn, renderFn: renderMode, classFn } canvasDrawing.push(canvasPoint) } else { const yCoordinates = Array.isArray(d[y]) ? d[y].map(p => yScale(p)) : [dY] yCoordinates.forEach((yc, yi) => { const xCoordinates = Array.isArray(d[x]) ? d[x].map(p => xScale(p)) : [dX] xCoordinates.forEach((xc, xi) => { mappedPoints.push( clonedAppliedElement({ baseClass: "frame-piece", tx: xc, ty: yc, d: (d.data && { ...d, ...d.data }) || d, i: yi === 0 && xi === 0 ? i : `${i}-${yi}-${xi}`, markProps, styleFn, renderFn: renderMode, renderKeyFn, classFn, yi }) ) }) }) } } }) return mappedPoints } export function createLines({ xScale, yScale, canvasDrawing, data, projectedCoordinateNames, customMark, canvasRender, styleFn, classFn, renderMode, renderKeyFn, type, defined, baseMarkProps, ariaLabel, axesData = [] }) { const xAxis = axesData.find(d => d.orient === "bottom" || d.orient === "top") const yAxis = axesData.find(d => d.orient === "left" || d.orient === "right") const xAxisFormatter = (xAxis && xAxis.tickFormat) || (d => d) const yAxisFormatter = (yAxis && yAxis.tickFormat) || (d => d) const customLine = typeof type === "object" ? type : { type } const interpolator = typeof customLine.interpolator === "string" ? curveHash[customLine.interpolator] : customLine.interpolator || curveLinear const lineGenerator = customLine.simpleLine ? line() : area() lineGeneratorDecorator({ projectedCoordinateNames, defined, interpolator, generator: lineGenerator, xScale, yScale, simpleLine: customLine.simpleLine }) const dynamicLineGenerator = (interpolator.dynamicInterpolator && ((d, i) => { const dynLineGenerator = area() lineGeneratorDecorator({ projectedCoordinateNames, defined, interpolator: interpolator.dynamicInterpolator(d, i), generator: dynLineGenerator, xScale, yScale, simpleLine: customLine.simpleLine }) return dynLineGenerator })) || (() => lineGenerator) const mappedLines = [] data.forEach((d, i) => { if (customMark && typeof customMark === "function") { //shim to make customLineMark work until Semiotic 2 const compatibleData = { ...d, data: d.data.map(p => ({ ...p.data, ...p })) } mappedLines.push( customMark({ d: compatibleData, i, xScale, yScale, canvasDrawing }) ) } else { const builtInDisplayProps: { fill?: string; stroke?: string } = {} if (customLine.simpleLine) { builtInDisplayProps.fill = "none" builtInDisplayProps.stroke = "black" } const pathString = dynamicLineGenerator(d, i)( d.data.map(p => Object.assign({}, p.data, p)) ) const markProps = { ...builtInDisplayProps, ...baseMarkProps, markType: "path", d: pathString, "aria-label": d.data && d.data.length > 0 && `${d.data.length} point ${ ariaLabel.items } starting value ${yAxisFormatter(d.data[0].y)} at ${xAxisFormatter( d.data[0].x )} ending value ${yAxisFormatter( d.data[d.data.length - 1].y )} at ${xAxisFormatter(d.data[d.data.length - 1].x)}` } if (canvasRender && canvasRender(d, i) === true) { const canvasLine = { type: "line", baseClass: "xyframe-line", tx: 0, ty: 0, d, i, markProps, styleFn, renderFn: renderMode, classFn } canvasDrawing.push(canvasLine) } else { mappedLines.push( clonedAppliedElement({ baseClass: "xyframe-line", d, i, markProps, styleFn, renderFn: renderMode, renderKeyFn, classFn }) ) } } }) if (customLine.type === "difference" && data.length === 2) { //Create the overlay line for the difference chart const diffdataA = data[0].data.map((basedata, baseI) => { const linePoint = basedata.yTop > data[1].data[baseI].yTop ? basedata.yTop : basedata.yBottom return { x: basedata.x, y: linePoint, yBottom: linePoint, yTop: linePoint } }) const diffdataB = data[0].data.map((basedata, baseI) => { const linePoint = data[1].data[baseI].yTop > basedata.yTop ? data[1].data[baseI].yTop : data[1].data[baseI].yBottom return { x: basedata.x, y: linePoint, yBottom: linePoint, yTop: linePoint } }) const doClassname = classFn ? `xyframe-line ${classFn(diffdataA)}` : "xyframe-line" const overLine = line() lineGeneratorDecorator({ projectedCoordinateNames, defined, interpolator, generator: overLine, xScale, yScale, simpleLine: true }) // let baseStyle = props.lineStyle ? props.lineStyle(diffdata, 0) : {} const diffOverlayA = ( <Mark key={"xyline-diff-a"} className={`${doClassname} difference-overlay-a`} markType="path" d={overLine(diffdataA)} style={{ fill: "none", pointerEvents: "none" }} /> ) mappedLines.push(diffOverlayA) const diffOverlayB = ( <Mark key={"xyline-diff-b"} className={`${doClassname} difference-overlay-b`} markType="path" d={overLine(diffdataB)} style={{ fill: "none", pointerEvents: "none" }} /> ) mappedLines.push(diffOverlayB) } return mappedLines } export function createSummaries({ xScale, yScale, canvasDrawing, data, canvasRender, styleFn, classFn, renderKeyFn, renderMode, baseMarkProps, customMark }: { xScale: ScaleLinear<number, number> yScale: ScaleLinear<number, number> canvasDrawing?: object[] data: ProjectedSummary[] canvasRender?: Function styleFn?: Function classFn?: Function renderKeyFn?: Function renderMode?: Function baseMarkProps?: GenericObject customMark?: Function }) { const summaryClass = classFn || (() => "") const summaryStyle = styleFn || (() => ({})) const renderFn = renderMode if (!Array.isArray(data)) { data = [data] } const renderedSummaries = [] data.forEach((d, i) => { let className = "xyframe-summary" if (summaryClass) { className = `xyframe-summary ${summaryClass(d)}` } let drawD: string | React.ReactNode = "" let shouldBeValid = false if ( typeof d.customMark === "string" || React.isValidElement(d.customMark) ) { drawD = d.customMark shouldBeValid = true } else if (d.type === "MultiPolygon") { const polycoords = d.coordinates polycoords.forEach((coord: number[][]) => { coord.forEach(c => { drawD += `M${c .map(p => `${xScale(p[0])},${yScale(p[1])}`) .join("L")}Z ` }) }) } else if (customMark) { const xyfCoords = d._xyfCoordinates as number[][] const projectedCoordinates = xyfCoords.map(p => [ xScale(p[0]), yScale(p[1]) ]) // CUSTOM MARK IMPLEMENTATION drawD = customMark({ d, i, classFn: summaryClass, styleFn: summaryStyle, renderFn, projectedCoordinates, xScale, yScale, bounds: shapeBounds(projectedCoordinates) }) shouldBeValid = true } else { const xyfCoords = d._xyfCoordinates as number[][] if (d.curve) { const lineDrawing = line() .x(d => xScale(d[0])) .y(d => yScale(d[1])) .curve(d.curve) drawD = lineDrawing(xyfCoords) } else { drawD = `M${xyfCoords .map(p => `${xScale(p[0])},${yScale(p[1])}`) .join("L")}Z` } } const renderKey = renderKeyFn ? renderKeyFn(d, i) : `summary-${i}` if (shouldBeValid && React.isValidElement(drawD)) { renderedSummaries.push(drawD) } else if (canvasRender && canvasRender(d, i) === true) { const canvasSummary = { type: "summary", baseClass: "xyframe-summary", tx: 0, ty: 0, d, i, markProps: { markType: "path", d: drawD }, styleFn: summaryStyle, renderFn, classFn: () => className } canvasDrawing.push(canvasSummary) } else { renderedSummaries.push( <Mark {...baseMarkProps} key={renderKey} forceUpdate={true} renderMode={renderFn ? renderFn(d, i) : undefined} className={className} markType="path" d={drawD} style={summaryStyle(d, i)} /> ) } }) return renderedSummaries } export function clonedAppliedElement({ tx, ty, d, i, markProps, styleFn, renderFn, classFn, renderKeyFn, baseClass, yi }: { tx?: number ty?: number d: GenericObject i: number markProps: GenericObject styleFn: Function renderFn: Function classFn: Function renderKeyFn: Function baseClass: string yi?: number }) { markProps.style = styleFn ? styleFn(d, i, yi) : {} markProps.className = baseClass markProps.key = renderKeyFn ? renderKeyFn(d, i, yi) : `${baseClass}-${d.key === undefined ? i : d.key}` if (tx || ty) { markProps.transform = `translate(${tx || 0},${ty || 0})` } if (classFn) { markProps.className = `${baseClass} ${classFn(d, i, yi)}` } if (markProps.style.r) { markProps.r = markProps.style.r } if (!markProps.markType) { const RenderableMark = markProps as React.ComponentClass return React.createElement(RenderableMark) } markProps.renderMode = renderFn ? renderFn(d, i, yi) : undefined return <Mark {...markProps} /> }
the_stack
import DebugLogger from "debug" import { multicast, Observable, Subject } from "observable-fns" import { allSettled } from "../ponyfills" import { defaultPoolSize } from "./implementation" import { PoolEvent, PoolEventType, QueuedTask, TaskRunFunction, WorkerDescriptor } from "./pool-types" import { Thread } from "./thread" export { PoolEvent, PoolEventType, QueuedTask, Thread } // tslint:disable-next-line no-namespace export declare namespace Pool { type Event<ThreadType extends Thread = any> = PoolEvent<ThreadType> type EventType = PoolEventType } let nextPoolID = 1 function createArray(size: number): number[] { const array: number[] = [] for (let index = 0; index < size; index++) { array.push(index) } return array } function delay(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)) } function flatMap<In, Out>(array: In[], mapper: ((element: In) => Out[])): Out[] { return array.reduce<Out[]>( (flattened, element) => [...flattened, ...mapper(element)], [] ) } function slugify(text: string) { return text.replace(/\W/g, " ").trim().replace(/\s+/g, "-") } function spawnWorkers<ThreadType extends Thread>( spawnWorker: () => Promise<ThreadType>, count: number ): Array<WorkerDescriptor<ThreadType>> { return createArray(count).map((): WorkerDescriptor<ThreadType> => ({ init: spawnWorker(), runningTasks: [] })) } /** * Thread pool managing a set of worker threads. * Use it to queue tasks that are run on those threads with limited * concurrency. */ export interface Pool<ThreadType extends Thread> { /** * Returns a promise that resolves once the task queue is emptied. * Promise will be rejected if any task fails. * * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty. */ completed(allowResolvingImmediately?: boolean): Promise<any> /** * Returns a promise that resolves once the task queue is emptied. * Failing tasks will not cause the promise to be rejected. * * @param allowResolvingImmediately Set to `true` to resolve immediately if task queue is currently empty. */ settled(allowResolvingImmediately?: boolean): Promise<Error[]> /** * Returns an observable that yields pool events. */ events(): Observable<PoolEvent<ThreadType>> /** * Queue a task and return a promise that resolves once the task has been dequeued, * started and finished. * * @param task An async function that takes a thread instance and invokes it. */ queue<Return>(task: TaskRunFunction<ThreadType, Return>): QueuedTask<ThreadType, Return> /** * Terminate all pool threads. * * @param force Set to `true` to kill the thread even if it cannot be stopped gracefully. */ terminate(force?: boolean): Promise<void> } export interface PoolOptions { /** Maximum no. of tasks to run on one worker thread at a time. Defaults to one. */ concurrency?: number /** Maximum no. of jobs to be queued for execution before throwing an error. */ maxQueuedJobs?: number /** Gives that pool a name to be used for debug logging, letting you distinguish between log output of different pools. */ name?: string /** No. of worker threads to spawn and to be managed by the pool. */ size?: number } class WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> { public static EventType = PoolEventType private readonly debug: DebugLogger.Debugger private readonly eventObservable: Observable<PoolEvent<ThreadType>> private readonly options: PoolOptions private readonly workers: Array<WorkerDescriptor<ThreadType>> private readonly eventSubject = new Subject<PoolEvent<ThreadType>>() private initErrors: Error[] = [] private isClosing = false private nextTaskID = 1 private taskQueue: Array<QueuedTask<ThreadType, any>> = [] constructor( spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions ) { const options: PoolOptions = typeof optionsOrSize === "number" ? { size: optionsOrSize } : optionsOrSize || {} const { size = defaultPoolSize } = options this.debug = DebugLogger(`threads:pool:${slugify(options.name || String(nextPoolID++))}`) this.options = options this.workers = spawnWorkers(spawnWorker, size) this.eventObservable = multicast(Observable.from(this.eventSubject)) Promise.all(this.workers.map(worker => worker.init)).then( () => this.eventSubject.next({ type: PoolEventType.initialized, size: this.workers.length }), error => { this.debug("Error while initializing pool worker:", error) this.eventSubject.error(error) this.initErrors.push(error) } ) } private findIdlingWorker(): WorkerDescriptor<ThreadType> | undefined { const { concurrency = 1 } = this.options return this.workers.find(worker => worker.runningTasks.length < concurrency) } private async runPoolTask(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) { const workerID = this.workers.indexOf(worker) + 1 this.debug(`Running task #${task.id} on worker #${workerID}...`) this.eventSubject.next({ type: PoolEventType.taskStart, taskID: task.id, workerID }) try { const returnValue = await task.run(await worker.init) this.debug(`Task #${task.id} completed successfully`) this.eventSubject.next({ type: PoolEventType.taskCompleted, returnValue, taskID: task.id, workerID }) } catch (error) { this.debug(`Task #${task.id} failed`) this.eventSubject.next({ type: PoolEventType.taskFailed, taskID: task.id, error, workerID }) } } private async run(worker: WorkerDescriptor<ThreadType>, task: QueuedTask<ThreadType, any>) { const runPromise = (async () => { const removeTaskFromWorkersRunningTasks = () => { worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise) } // Defer task execution by one tick to give handlers time to subscribe await delay(0) try { await this.runPoolTask(worker, task) } finally { removeTaskFromWorkersRunningTasks() if (!this.isClosing) { this.scheduleWork() } } })() worker.runningTasks.push(runPromise) } private scheduleWork() { this.debug(`Attempt de-queueing a task in order to run it...`) const availableWorker = this.findIdlingWorker() if (!availableWorker) return const nextTask = this.taskQueue.shift() if (!nextTask) { this.debug(`Task queue is empty`) this.eventSubject.next({ type: PoolEventType.taskQueueDrained }) return } this.run(availableWorker, nextTask) } private taskCompletion(taskID: number) { return new Promise<any>((resolve, reject) => { const eventSubscription = this.events().subscribe(event => { if (event.type === PoolEventType.taskCompleted && event.taskID === taskID) { eventSubscription.unsubscribe() resolve(event.returnValue) } else if (event.type === PoolEventType.taskFailed && event.taskID === taskID) { eventSubscription.unsubscribe() reject(event.error) } else if (event.type === PoolEventType.terminated) { eventSubscription.unsubscribe() reject(Error("Pool has been terminated before task was run.")) } }) }) } public async settled(allowResolvingImmediately: boolean = false): Promise<Error[]> { const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks) const taskFailures: Error[] = [] const failureSubscription = this.eventObservable.subscribe(event => { if (event.type === PoolEventType.taskFailed) { taskFailures.push(event.error) } }) if (this.initErrors.length > 0) { return Promise.reject(this.initErrors[0]) } if (allowResolvingImmediately && this.taskQueue.length === 0) { await allSettled(getCurrentlyRunningTasks()) return taskFailures } await new Promise<void>((resolve, reject) => { const subscription = this.eventObservable.subscribe({ next(event) { if (event.type === PoolEventType.taskQueueDrained) { subscription.unsubscribe() resolve(void 0) } }, error: reject // make a pool-wide error reject the completed() result promise }) }) await allSettled(getCurrentlyRunningTasks()) failureSubscription.unsubscribe() return taskFailures } public async completed(allowResolvingImmediately: boolean = false) { const settlementPromise = this.settled(allowResolvingImmediately) const earlyExitPromise = new Promise<Error[]>((resolve, reject) => { const subscription = this.eventObservable.subscribe({ next(event) { if (event.type === PoolEventType.taskQueueDrained) { subscription.unsubscribe() resolve(settlementPromise) } else if (event.type === PoolEventType.taskFailed) { subscription.unsubscribe() reject(event.error) } }, error: reject // make a pool-wide error reject the completed() result promise }) }) const errors = await Promise.race([ settlementPromise, earlyExitPromise ]) if (errors.length > 0) { throw errors[0] } } public events() { return this.eventObservable } public queue(taskFunction: TaskRunFunction<ThreadType, any>) { const { maxQueuedJobs = Infinity } = this.options if (this.isClosing) { throw Error(`Cannot schedule pool tasks after terminate() has been called.`) } if (this.initErrors.length > 0) { throw this.initErrors[0] } const taskID = this.nextTaskID++ const taskCompletion = this.taskCompletion(taskID) taskCompletion.catch((error) => { // Prevent unhandled rejections here as we assume the user will use // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors this.debug(`Task #${taskID} errored:`, error) }) const task: QueuedTask<ThreadType, any> = { id: taskID, run: taskFunction, cancel: () => { if (this.taskQueue.indexOf(task) === -1) return this.taskQueue = this.taskQueue.filter(someTask => someTask !== task) this.eventSubject.next({ type: PoolEventType.taskCanceled, taskID: task.id }) }, then: taskCompletion.then.bind(taskCompletion) } if (this.taskQueue.length >= maxQueuedJobs) { throw Error( "Maximum number of pool tasks queued. Refusing to queue another one.\n" + "This usually happens for one of two reasons: We are either at peak " + "workload right now or some tasks just won't finish, thus blocking the pool." ) } this.debug(`Queueing task #${task.id}...`) this.taskQueue.push(task) this.eventSubject.next({ type: PoolEventType.taskQueued, taskID: task.id }) this.scheduleWork() return task } public async terminate(force?: boolean) { this.isClosing = true if (!force) { await this.completed(true) } this.eventSubject.next({ type: PoolEventType.terminated, remainingQueue: [...this.taskQueue] }) this.eventSubject.complete() await Promise.all( this.workers.map(async worker => Thread.terminate(await worker.init)) ) } } /** * Thread pool constructor. Creates a new pool and spawns its worker threads. */ function PoolConstructor<ThreadType extends Thread>( spawnWorker: () => Promise<ThreadType>, optionsOrSize?: number | PoolOptions ) { // The function exists only so we don't need to use `new` to create a pool (we still can, though). // If the Pool is a class or not is an implementation detail that should not concern the user. return new WorkerPool(spawnWorker, optionsOrSize) } (PoolConstructor as any).EventType = PoolEventType /** * Thread pool constructor. Creates a new pool and spawns its worker threads. */ export const Pool = PoolConstructor as typeof PoolConstructor & { EventType: typeof PoolEventType }
the_stack
import React from 'react'; import escapeHtml from 'escape-html'; import { ALLOWED_TAG_LIST, ATTRIBUTES, ATTRIBUTES_TO_PROPS, BANNED_TAG_LIST, FILTER_CAST_BOOL, FILTER_CAST_NUMBER, FILTER_DENY, FILTER_NO_CAST, TAGS, } from './constants'; import Element from './Element'; import StyleFilter from './StyleFilter'; import { Attributes, AttributeValue, ChildrenNode, ElementAttributes, ElementProps, FilterInterface, MatcherElementsMap, MatcherInterface, Node, NodeConfig, ParserProps, } from './types'; const ELEMENT_NODE = 1; const TEXT_NODE = 3; const INVALID_ROOTS = /^<(!doctype|(html|head|body)(\s|>))/i; const ALLOWED_ATTRS = /^(aria-|data-|\w+:)/iu; const OPEN_TOKEN = /{{{(\w+)\/?}}}/; function createDocument() { // Maybe SSR? Just do nothing instead of crashing! if (typeof window === 'undefined' || typeof document === 'undefined') { return undefined; } return document.implementation.createHTMLDocument('Interweave'); } export default class Parser { allowed: Set<string>; banned: Set<string>; blocked: Set<string>; container?: HTMLElement; content: Node[] = []; props: ParserProps; matchers: MatcherInterface[]; filters: FilterInterface[]; keyIndex: number; constructor( markup: string, props: ParserProps = {}, matchers: MatcherInterface[] = [], filters: FilterInterface[] = [], ) { if (__DEV__) { if (markup && typeof markup !== 'string') { throw new TypeError('Interweave parser requires a valid string.'); } } this.props = props; this.matchers = matchers; this.filters = [...filters, new StyleFilter()]; this.keyIndex = -1; this.container = this.createContainer(markup || ''); this.allowed = new Set(props.allowList || ALLOWED_TAG_LIST); this.banned = new Set(BANNED_TAG_LIST); this.blocked = new Set(props.blockList); } /** * Loop through and apply all registered attribute filters. */ applyAttributeFilters<K extends keyof ElementAttributes>( name: K, value: ElementAttributes[K], ): ElementAttributes[K] { return this.filters.reduce( (nextValue, filter) => nextValue !== null && typeof filter.attribute === 'function' ? filter.attribute(name, nextValue) : nextValue, value, ); } /** * Loop through and apply all registered node filters. */ applyNodeFilters(name: string, node: HTMLElement | null): HTMLElement | null { // Allow null to be returned return this.filters.reduce( (nextNode, filter) => nextNode !== null && typeof filter.node === 'function' ? filter.node(name, nextNode) : nextNode, node, ); } /** * Loop through and apply all registered matchers to the string. * If a match is found, create a React element, and build a new array. * This array allows React to interpolate and render accordingly. */ applyMatchers(string: string, parentConfig: NodeConfig): ChildrenNode { const elements: MatcherElementsMap = {}; const { props } = this; let matchedString = string; let elementIndex = 0; let parts = null; this.matchers.forEach((matcher) => { const tagName = matcher.asTag().toLowerCase(); const config = this.getTagConfig(tagName); // Skip matchers that have been disabled from props or are not supported if ( (props as { [key: string]: unknown })[matcher.inverseName] || !this.isTagAllowed(tagName) ) { return; } // Skip matchers in which the child cannot be rendered if (!this.canRenderChild(parentConfig, config)) { return; } // Continuously trigger the matcher until no matches are found let tokenizedString = ''; while (matchedString && (parts = matcher.match(matchedString))) { const { index, length, match, valid, void: isVoid, ...partProps } = parts; const tokenName = matcher.propName + elementIndex; // Piece together a new string with interpolated tokens if (index > 0) { tokenizedString += matchedString.slice(0, index); } if (valid) { tokenizedString += isVoid ? `{{{${tokenName}/}}}` : `{{{${tokenName}}}}${match}{{{/${tokenName}}}}`; this.keyIndex += 1; elementIndex += 1; elements[tokenName] = { children: match, matcher, props: { ...props, ...partProps, key: this.keyIndex, }, }; } else { tokenizedString += match; } // Reduce the string being matched against, // otherwise we end up in an infinite loop! if (matcher.greedy) { matchedString = tokenizedString + matchedString.slice(index + length); tokenizedString = ''; } else { // eslint-disable-next-line unicorn/explicit-length-check matchedString = matchedString.slice(index + (length || match.length)); } } // Update the matched string with the tokenized string, // so that the next matcher can apply to it. if (!matcher.greedy) { matchedString = tokenizedString + matchedString; } }); if (elementIndex === 0) { return string; } return this.replaceTokens(matchedString, elements); } /** * Determine whether the child can be rendered within the parent. */ canRenderChild(parentConfig: NodeConfig, childConfig: NodeConfig): boolean { if (!parentConfig.tagName || !childConfig.tagName) { return false; } // No children if (parentConfig.void) { return false; } // Valid children if (parentConfig.children.length > 0) { return parentConfig.children.includes(childConfig.tagName); } if (parentConfig.invalid.length > 0 && parentConfig.invalid.includes(childConfig.tagName)) { return false; } // Valid parent if (childConfig.parent.length > 0) { return childConfig.parent.includes(parentConfig.tagName); } // Self nesting if (!parentConfig.self && parentConfig.tagName === childConfig.tagName) { return false; } // Content category type return Boolean(parentConfig && parentConfig.content & childConfig.type); } /** * Convert line breaks in a string to HTML `<br/>` tags. * If the string contains HTML, we should not convert anything, * as line breaks should be handled by `<br/>`s in the markup itself. */ convertLineBreaks(markup: string): string { const { noHtml, disableLineBreaks } = this.props; if (noHtml || disableLineBreaks || markup.match(/<((?:\/[ a-z]+)|(?:[ a-z]+\/))>/gi)) { return markup; } // Replace carriage returns let nextMarkup = markup.replace(/\r\n/g, '\n'); // Replace long line feeds nextMarkup = nextMarkup.replace(/\n{3,}/g, '\n\n\n'); // Replace line feeds with `<br/>`s nextMarkup = nextMarkup.replace(/\n/g, '<br/>'); return nextMarkup; } /** * Create a detached HTML document that allows for easy HTML * parsing while not triggering scripts or loading external * resources. */ createContainer(markup: string): HTMLElement | undefined { const factory = (typeof global !== 'undefined' && global.INTERWEAVE_SSR_POLYFILL) || createDocument; const doc = factory(); if (!doc) { return undefined; } const tag = this.props.containerTagName || 'body'; const el = tag === 'body' || tag === 'fragment' ? doc.body : doc.createElement(tag); if (markup.match(INVALID_ROOTS)) { if (__DEV__) { throw new Error('HTML documents as Interweave content are not supported.'); } } else { el.innerHTML = this.convertLineBreaks(this.props.escapeHtml ? escapeHtml(markup) : markup); } return el; } /** * Convert an elements attribute map to an object map. * Returns null if no attributes are defined. */ extractAttributes(node: HTMLElement): Attributes | null { const { allowAttributes } = this.props; const attributes: Attributes = {}; let count = 0; if (node.nodeType !== ELEMENT_NODE || !node.attributes) { return null; } Array.from(node.attributes).forEach((attr) => { const { name, value } = attr; const newName = name.toLowerCase(); const filter = ATTRIBUTES[newName] || ATTRIBUTES[name]; // Verify the node is safe from attacks if (!this.isSafe(node)) { return; } // Do not allow denied attributes, excluding ARIA attributes // Do not allow events or XSS injections if (!newName.match(ALLOWED_ATTRS)) { if ( (!allowAttributes && (!filter || filter === FILTER_DENY)) || newName.startsWith('on') || value.replace(/(\s|\0|&#x0([9AD]);)/, '').match(/(javascript|vbscript|livescript|xss):/i) ) { return; } } // Apply attribute filters let newValue: AttributeValue = newName === 'style' ? this.extractStyleAttribute(node) : value; // Cast to boolean if (filter === FILTER_CAST_BOOL) { newValue = true; // Cast to number } else if (filter === FILTER_CAST_NUMBER) { newValue = Number.parseFloat(String(newValue)); // Cast to string } else if (filter !== FILTER_NO_CAST) { newValue = String(newValue); } attributes[ATTRIBUTES_TO_PROPS[newName] || newName] = this.applyAttributeFilters( newName as keyof ElementAttributes, newValue, ) as AttributeValue; count += 1; }); if (count === 0) { return null; } return attributes; } /** * Extract the style attribute as an object and remove values that allow for attack vectors. */ extractStyleAttribute(node: HTMLElement): object { const styles: { [key: string]: number | string } = {}; Array.from(node.style).forEach((key) => { const value = node.style[key as keyof CSSStyleDeclaration]; if (typeof value === 'string' || typeof value === 'number') { styles[key.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase())] = value; } }); return styles; } /** * Return configuration for a specific tag. */ getTagConfig(tagName: string): NodeConfig { const common = { children: [], content: 0, invalid: [], parent: [], self: true, tagName: '', type: 0, void: false, }; // Only spread when a tag config exists, // otherwise we use the empty `tagName` // for parent config inheritance. if (TAGS[tagName]) { return { ...common, ...TAGS[tagName], tagName, }; } return common; } /** * Verify that a node is safe from XSS and injection attacks. */ isSafe(node: HTMLElement): boolean { // URLs should only support HTTP, email and phone numbers if (typeof HTMLAnchorElement !== 'undefined' && node instanceof HTMLAnchorElement) { const href = node.getAttribute('href'); // Fragment protocols start with about: // So let's just allow them if (href && href.charAt(0) === '#') { return true; } const protocol = node.protocol.toLowerCase(); return ( protocol === ':' || protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:' || protocol === 'tel:' ); } return true; } /** * Verify that an HTML tag is allowed to render. */ isTagAllowed(tagName: string): boolean { if (this.banned.has(tagName) || this.blocked.has(tagName)) { return false; } return this.props.allowElements || this.allowed.has(tagName); } /** * Parse the markup by injecting it into a detached document, * while looping over all child nodes and generating an * array to interpolate into JSX. */ parse(): Node[] { if (!this.container) { return []; } return this.parseNode(this.container, this.getTagConfig(this.container.nodeName.toLowerCase())); } /** * Loop over the nodes children and generate a * list of text nodes and React elements. */ parseNode(parentNode: HTMLElement, parentConfig: NodeConfig): Node[] { const { noHtml, noHtmlExceptMatchers, allowElements, transform, transformOnlyAllowList, } = this.props; let content: Node[] = []; let mergedText = ''; Array.from(parentNode.childNodes).forEach((node) => { // Create React elements from HTML elements if (node.nodeType === ELEMENT_NODE) { const tagName = node.nodeName.toLowerCase(); const config = this.getTagConfig(tagName); // Persist any previous text if (mergedText) { content.push(mergedText); mergedText = ''; } // Apply node filters first const nextNode = this.applyNodeFilters(tagName, node as HTMLElement); if (!nextNode) { return; } // Apply transformation second let children; if (transform && !(transformOnlyAllowList && !this.isTagAllowed(tagName))) { this.keyIndex += 1; const key = this.keyIndex; // Must occur after key is set children = this.parseNode(nextNode, config); const transformed = transform(nextNode, children, config); if (transformed === null) { return; } else if (typeof transformed !== 'undefined') { content.push(React.cloneElement(transformed as React.ReactElement<unknown>, { key })); return; } // Reset as we're not using the transformation this.keyIndex = key - 1; } // Never allow these tags (except via a transformer) if (this.banned.has(tagName)) { return; } // Only render when the following criteria is met: // - HTML has not been disabled // - Tag is allowed // - Child is valid within the parent if ( !(noHtml || (noHtmlExceptMatchers && tagName !== 'br')) && this.isTagAllowed(tagName) && (allowElements || this.canRenderChild(parentConfig, config)) ) { this.keyIndex += 1; // Build the props as it makes it easier to test const attributes = this.extractAttributes(nextNode); const elementProps: ElementProps = { tagName, }; if (attributes) { elementProps.attributes = attributes; } if (config.void) { elementProps.selfClose = config.void; } content.push( React.createElement( Element, { ...elementProps, key: this.keyIndex }, children || this.parseNode(nextNode, config), ), ); // Render the children of the current element only. // Important: If the current element is not allowed, // use the parent element for the next scope. } else { content = content.concat( this.parseNode(nextNode, config.tagName ? config : parentConfig), ); } // Apply matchers if a text node } else if (node.nodeType === TEXT_NODE) { const text = noHtml && !noHtmlExceptMatchers ? node.textContent : this.applyMatchers(node.textContent || '', parentConfig); if (Array.isArray(text)) { content = content.concat(text); } else { mergedText += text; } } }); if (mergedText) { content.push(mergedText); } return content; } /** * Deconstruct the string into an array, by replacing custom tokens with React elements, * so that React can render it correctly. */ replaceTokens(tokenizedString: string, elements: MatcherElementsMap): ChildrenNode { if (!tokenizedString.includes('{{{')) { return tokenizedString; } const nodes: Node[] = []; let text = tokenizedString; let open: RegExpMatchArray | null = null; // Find an open token tag while ((open = text.match(OPEN_TOKEN))) { const [match, tokenName] = open; const startIndex = open.index!; const isVoid = match.includes('/'); if (__DEV__) { if (!elements[tokenName]) { throw new Error(`Token "${tokenName}" found but no matching element to replace with.`); } } // Extract the previous non-token text if (startIndex > 0) { nodes.push(text.slice(0, startIndex)); // Reduce text so that the closing tag will be found after the opening text = text.slice(startIndex); } const { children, matcher, props: elementProps } = elements[tokenName]; let endIndex: number; // Use tag as-is if void if (isVoid) { endIndex = match.length; nodes.push(matcher.createElement(children, elementProps)); // Find the closing tag if not void } else { const close = text.match(new RegExp(`{{{/${tokenName}}}}`))!; if (__DEV__) { if (!close) { throw new Error(`Closing token missing for interpolated element "${tokenName}".`); } } endIndex = close.index! + close[0].length; nodes.push( matcher.createElement( this.replaceTokens(text.slice(match.length, close.index!), elements), elementProps, ), ); } // Reduce text for the next interation text = text.slice(endIndex); } // Extra the remaining text if (text.length > 0) { nodes.push(text); } // Reduce to a string if possible if (nodes.length === 0) { return ''; } else if (nodes.length === 1 && typeof nodes[0] === 'string') { return nodes[0]; } return nodes; } }
the_stack
import {assert, isArray} from 'zrender/src/core/util'; import SeriesModel from '../model/Series'; import { Pipeline } from './Scheduler'; import { Payload } from '../util/types'; import SeriesData from '../data/SeriesData'; export interface TaskContext { outputData?: SeriesData; data?: SeriesData; payload?: Payload; model?: SeriesModel; }; export type TaskResetCallback<Ctx extends TaskContext> = ( this: Task<Ctx>, context: Ctx ) => TaskResetCallbackReturn<Ctx>; export type TaskResetCallbackReturn<Ctx extends TaskContext> = void | (TaskProgressCallback<Ctx> | TaskProgressCallback<Ctx>[]) | { forceFirstProgress?: boolean progress: TaskProgressCallback<Ctx> | TaskProgressCallback<Ctx>[] }; export type TaskProgressCallback<Ctx extends TaskContext> = ( this: Task<Ctx>, params: TaskProgressParams, context: Ctx ) => void; export type TaskProgressParams = { start: number, end: number, count: number, next?: TaskDataIteratorNext }; export type TaskPlanCallback<Ctx extends TaskContext> = ( this: Task<Ctx>, context: Ctx ) => TaskPlanCallbackReturn; export type TaskPlanCallbackReturn = 'reset' | false | null | undefined; export type TaskCountCallback<Ctx extends TaskContext> = ( this: Task<Ctx>, context: Ctx ) => number; export type TaskOnDirtyCallback<Ctx extends TaskContext> = ( this: Task<Ctx>, context: Ctx ) => void; type TaskDataIteratorNext = () => number; type TaskDataIterator = { reset: (s: number, e: number, sStep: number, sCount: number) => void, next?: TaskDataIteratorNext }; type TaskDefineParam<Ctx extends TaskContext> = { reset?: TaskResetCallback<Ctx>, // Returns 'reset' indicate reset immediately plan?: TaskPlanCallback<Ctx>, // count is used to determine data task. count?: TaskCountCallback<Ctx>, onDirty?: TaskOnDirtyCallback<Ctx> }; export type PerformArgs = { step?: number, skip?: boolean, modBy?: number, modDataCount?: number }; /** * @param {Object} define * @return See the return of `createTask`. */ export function createTask<Ctx extends TaskContext>( define: TaskDefineParam<Ctx> ): Task<Ctx> { return new Task<Ctx>(define); } export class Task<Ctx extends TaskContext> { private _reset: TaskResetCallback<Ctx>; private _plan: TaskPlanCallback<Ctx>; private _count: TaskCountCallback<Ctx>; private _onDirty: TaskOnDirtyCallback<Ctx>; private _progress: TaskProgressCallback<Ctx> | TaskProgressCallback<Ctx>[]; private _callingProgress: TaskProgressCallback<Ctx>; private _dirty: boolean; private _modBy: number; private _modDataCount: number; private _upstream: Task<Ctx>; private _downstream: Task<Ctx>; private _dueEnd: number; private _outputDueEnd: number; private _settedOutputEnd: number; private _dueIndex: number; private _disposed: boolean; // Injected in schedular __pipeline: Pipeline; __idxInPipeline: number; __block: boolean; // Context must be specified implicitly, to // avoid miss update context when model changed. context: Ctx; constructor(define: TaskDefineParam<Ctx>) { define = define || {}; this._reset = define.reset; this._plan = define.plan; this._count = define.count; this._onDirty = define.onDirty; this._dirty = true; } /** * @param step Specified step. * @param skip Skip customer perform call. * @param modBy Sampling window size. * @param modDataCount Sampling count. * @return whether unfinished. */ perform(performArgs?: PerformArgs): boolean { const upTask = this._upstream; const skip = performArgs && performArgs.skip; // TODO some refactor. // Pull data. Must pull data each time, because context.data // may be updated by Series.setData. if (this._dirty && upTask) { const context = this.context; context.data = context.outputData = upTask.context.outputData; } if (this.__pipeline) { this.__pipeline.currentTask = this; } let planResult; if (this._plan && !skip) { planResult = this._plan(this.context); } // Support sharding by mod, which changes the render sequence and makes the rendered graphic // elements uniformed distributed when progress, especially when moving or zooming. const lastModBy = normalizeModBy(this._modBy); const lastModDataCount = this._modDataCount || 0; const modBy = normalizeModBy(performArgs && performArgs.modBy); const modDataCount = performArgs && performArgs.modDataCount || 0; if (lastModBy !== modBy || lastModDataCount !== modDataCount) { planResult = 'reset'; } function normalizeModBy(val: number) { !(val >= 1) && (val = 1); // jshint ignore:line return val; } let forceFirstProgress; if (this._dirty || planResult === 'reset') { this._dirty = false; forceFirstProgress = this._doReset(skip); } this._modBy = modBy; this._modDataCount = modDataCount; const step = performArgs && performArgs.step; if (upTask) { if (__DEV__) { assert(upTask._outputDueEnd != null); } this._dueEnd = upTask._outputDueEnd; } // DataTask or overallTask else { if (__DEV__) { assert(!this._progress || this._count); } this._dueEnd = this._count ? this._count(this.context) : Infinity; } // Note: Stubs, that its host overall task let it has progress, has progress. // If no progress, pass index from upstream to downstream each time plan called. if (this._progress) { const start = this._dueIndex; const end = Math.min( step != null ? this._dueIndex + step : Infinity, this._dueEnd ); if (!skip && (forceFirstProgress || start < end)) { const progress = this._progress; if (isArray(progress)) { for (let i = 0; i < progress.length; i++) { this._doProgress(progress[i], start, end, modBy, modDataCount); } } else { this._doProgress(progress, start, end, modBy, modDataCount); } } this._dueIndex = end; // If no `outputDueEnd`, assume that output data and // input data is the same, so use `dueIndex` as `outputDueEnd`. const outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end; if (__DEV__) { // ??? Can not rollback. assert(outputDueEnd >= this._outputDueEnd); } this._outputDueEnd = outputDueEnd; } else { // (1) Some overall task has no progress. // (2) Stubs, that its host overall task do not let it has progress, has no progress. // This should always be performed so it can be passed to downstream. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd; } return this.unfinished(); } dirty(): void { this._dirty = true; this._onDirty && this._onDirty(this.context); } private _doProgress( progress: TaskProgressCallback<Ctx>, start: number, end: number, modBy: number, modDataCount: number ): void { iterator.reset(start, end, modBy, modDataCount); this._callingProgress = progress; this._callingProgress({ start: start, end: end, count: end - start, next: iterator.next }, this.context); } private _doReset(skip: boolean): boolean { this._dueIndex = this._outputDueEnd = this._dueEnd = 0; this._settedOutputEnd = null; let progress: TaskResetCallbackReturn<Ctx>; let forceFirstProgress: boolean; if (!skip && this._reset) { progress = this._reset(this.context); if (progress && (progress as any).progress) { forceFirstProgress = (progress as any).forceFirstProgress; progress = (progress as any).progress; } // To simplify no progress checking, array must has item. if (isArray(progress) && !progress.length) { progress = null; } } this._progress = progress as TaskProgressCallback<Ctx>; this._modBy = this._modDataCount = null; const downstream = this._downstream; downstream && downstream.dirty(); return forceFirstProgress; } unfinished(): boolean { return this._progress && this._dueIndex < this._dueEnd; } /** * @param downTask The downstream task. * @return The downstream task. */ pipe(downTask: Task<Ctx>): void { if (__DEV__) { assert(downTask && !downTask._disposed && downTask !== this); } // If already downstream, do not dirty downTask. if (this._downstream !== downTask || this._dirty) { this._downstream = downTask; downTask._upstream = this; downTask.dirty(); } } dispose(): void { if (this._disposed) { return; } this._upstream && (this._upstream._downstream = null); this._downstream && (this._downstream._upstream = null); this._dirty = false; this._disposed = true; } getUpstream(): Task<Ctx> { return this._upstream; } getDownstream(): Task<Ctx> { return this._downstream; } setOutputEnd(end: number): void { // This only happend in dataTask, dataZoom, map, currently. // where dataZoom do not set end each time, but only set // when reset. So we should record the setted end, in case // that the stub of dataZoom perform again and earse the // setted end by upstream. this._outputDueEnd = this._settedOutputEnd = end; } } const iterator: TaskDataIterator = (function () { let end: number; let current: number; let modBy: number; let modDataCount: number; let winCount: number; const it: TaskDataIterator = { reset: function (s: number, e: number, sStep: number, sCount: number): void { current = s; end = e; modBy = sStep; modDataCount = sCount; winCount = Math.ceil(modDataCount / modBy); it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext; } }; return it; function sequentialNext(): number { return current < end ? current++ : null; } function modNext(): number { const dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount); const result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case), // Use normal linear rendering mode. : current; current++; return result; } })(); /////////////////////////////////////////////////////////// // For stream debug (Should be commented out after used!) // @usage: printTask(this, 'begin'); // @usage: printTask(this, null, {someExtraProp}); // @usage: Use `__idxInPipeline` as conditional breakpiont. // // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void { // window.ecTaskUID == null && (window.ecTaskUID = 0); // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`); // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`); // let props = []; // if (task.__pipeline) { // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`; // props.push({text: '__idxInPipeline/total', value: val}); // } else { // let stubCount = 0; // task.agentStubMap.each(() => stubCount++); // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`}); // } // props.push({text: 'uid', value: task.uidDebug}); // if (task.__pipeline) { // props.push({text: 'pipelineId', value: task.__pipeline.id}); // task.agent && props.push( // {text: 'stubFor', value: task.agent.uidDebug} // ); // } // props.push( // {text: 'dirty', value: task._dirty}, // {text: 'dueIndex', value: task._dueIndex}, // {text: 'dueEnd', value: task._dueEnd}, // {text: 'outputDueEnd', value: task._outputDueEnd} // ); // if (extra) { // Object.keys(extra).forEach(key => { // props.push({text: key, value: extra[key]}); // }); // } // let args = ['color: blue']; // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => ( // args.push('color: green', 'color: red'), // `${item.text}: %c${item.value}` // )).join('%c, '); // console.log.apply(console, [msg].concat(args)); // // console.log(this); // }; // window.printPipeline = function (task: any, prefix: string) { // const pipeline = task.__pipeline; // let currTask = pipeline.head; // while (currTask) { // window.printTask(currTask, prefix); // currTask = currTask._downstream; // } // }; // window.showChain = function (chainHeadTask) { // var chain = []; // var task = chainHeadTask; // while (task) { // chain.push({ // task: task, // up: task._upstream, // down: task._downstream, // idxInPipeline: task.__idxInPipeline // }); // task = task._downstream; // } // return chain; // }; // window.findTaskInChain = function (task, chainHeadTask) { // let chain = window.showChain(chainHeadTask); // let result = []; // for (let i = 0; i < chain.length; i++) { // let chainItem = chain[i]; // if (chainItem.task === task) { // result.push(i); // } // } // return result; // }; // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) { // let chainA = window.showChain(chainHeadTaskA); // for (let i = 0; i < chainA.length; i++) { // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB)); // } // };
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, HostListener, Injector, Input, OnChanges, OnDestroy, Optional, Output, SimpleChanges, SkipSelf, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core'; import { TemplatePortal } from '@angular/cdk/portal'; import { Overlay, OverlayConfig, OverlayRef, PositionStrategy } from '@angular/cdk/overlay'; import { Subscription } from 'rxjs'; import { WindowRegistry } from '../window/window-state'; import { focusWatcher } from '../../core/utils'; import { isArray } from '@deepkit/core'; import { OverlayStack, OverlayStackItem, ReactiveChangeDetectionModule, unsubscribe } from '../app'; import { ButtonComponent } from './button.component'; @Component({ selector: 'dui-dropdown', template: ` <ng-template #dropdownTemplate> <div class="dui-body dui-dropdown" tabindex="1" #dropdown> <!-- <div *ngIf="overlay !== false" class="dui-dropdown-arrow"></div>--> <div class="content" [class.overlay-scrollbar-small]="scrollbars"> <ng-container *ngIf="!container"> <ng-content></ng-content> </ng-container> <ng-container *ngIf="container" [ngTemplateOutlet]="container"></ng-container> </div> </div> </ng-template> `, host: { '[class.overlay]': 'overlay !== false', }, styleUrls: ['./dropdown.component.scss'] }) export class DropdownComponent implements OnChanges, OnDestroy, AfterViewInit { public isOpen = false; public overlayRef?: OverlayRef; protected lastFocusWatcher?: Subscription; @Input() host?: HTMLElement | ElementRef; @Input() allowedFocus: (HTMLElement | ElementRef)[] | (HTMLElement | ElementRef) = []; /** * For debugging purposes. */ @Input() keepOpen?: true; @Input() height?: number | string; @Input() width?: number | string; @Input() minWidth?: number | string; @Input() minHeight?: number | string; @Input() maxWidth?: number | string; @Input() maxHeight?: number | string; @Input() scrollbars: boolean = true; /** * Whether the dropdown aligns to the horizontal center. */ @Input() center: boolean = false; /** * Whether is styled as overlay */ @Input() overlay: boolean | '' = false; @Input() show?: boolean; @Output() showChange = new EventEmitter<boolean>(); @Output() shown = new EventEmitter(); @Output() hidden = new EventEmitter(); @ViewChild('dropdownTemplate', { static: false, read: TemplateRef }) dropdownTemplate!: TemplateRef<any>; @ViewChild('dropdown', { static: false, read: ElementRef }) dropdown!: ElementRef<HTMLElement>; container?: TemplateRef<any> | undefined; protected lastOverlayStackItem?: OverlayStackItem; constructor( protected overlayService: Overlay, protected injector: Injector, protected registry: WindowRegistry, protected overlayStack: OverlayStack, protected viewContainerRef: ViewContainerRef, protected cd: ChangeDetectorRef, @SkipSelf() protected cdParent: ChangeDetectorRef, ) { } ngOnChanges(changes: SimpleChanges): void { if (changes.show && this.dropdownTemplate) { if (this.show === true) this.open(); if (this.show === false) this.close(); } } ngAfterViewInit() { if (this.show === true) this.open(); if (this.show === false) this.close(); } ngOnDestroy(): void { this.close(); } @HostListener('window:keyup', ['$event']) public key(event: KeyboardEvent) { if (this.isOpen && event.key.toLowerCase() === 'escape' && this.lastOverlayStackItem && this.lastOverlayStackItem.isLast()) { this.close(); } } public toggle(target?: HTMLElement | ElementRef | MouseEvent) { if (this.isOpen) { this.close(); } else { this.open(target); } } public setContainer(container: TemplateRef<any> | undefined) { this.container = container; } public open(target?: HTMLElement | ElementRef | MouseEvent | 'center') { if (this.lastFocusWatcher) { this.lastFocusWatcher.unsubscribe(); } if (!target) { target = this.host!; } target = target instanceof ElementRef ? target.nativeElement : target; if (!target) { throw new Error('No target or host specified for dropdown'); } let position: PositionStrategy | undefined; //this is necessary for multi-window environments, but doesn't work yet. // const document = this.registry.getCurrentViewContainerRef().element.nativeElement.ownerDocument; // const overlayContainer = new OverlayContainer(document); // const overlayContainer = new OverlayContainer(document); // const overlay = new Overlay( // this.injector.get(ScrollStrategyOptions), // overlayContainer, // this.injector.get(ComponentFactoryResolver), // new OverlayPositionBuilder(this.injector.get(ViewportRuler), document, this.injector.get(Platform), overlayContainer), // this.injector.get(OverlayKeyboardDispatcher), // this.injector, // this.injector.get(NgZone), // document, // this.injector.get(Directionality), // ); const overlay = this.overlayService; if (target instanceof MouseEvent) { const mousePosition = { x: target.pageX, y: target.pageY }; position = overlay .position() .flexibleConnectedTo(mousePosition) .withFlexibleDimensions(false) .withViewportMargin(12) .withPush(true) .withDefaultOffsetY(this.overlay !== false ? 15 : 0) .withPositions([ { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', }, { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', } ]); ; } else if (target === 'center') { position = overlay .position() .global().centerHorizontally().centerVertically(); } else { position = overlay .position() .flexibleConnectedTo(target) .withFlexibleDimensions(false) .withViewportMargin(12) .withPush(true) .withDefaultOffsetY(this.overlay !== false ? 15 : 0) .withPositions([ { originX: this.center ? 'center' : 'start', originY: 'bottom', overlayX: this.center ? 'center' : 'start', overlayY: 'top', }, { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', }, { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', } ]); } if (this.overlayRef) { this.overlayRef.updatePositionStrategy(position); this.overlayRef.updatePosition(); } else { this.isOpen = true; const options: OverlayConfig = { minWidth: 50, maxWidth: 450, maxHeight: '90%', hasBackdrop: false, scrollStrategy: overlay.scrollStrategies.reposition(), positionStrategy: position }; if (this.width) options.width = this.width; if (this.height) options.height = this.height; if (this.minWidth) options.minWidth = this.minWidth; if (this.minHeight) options.minHeight = this.minHeight; if (this.maxWidth) options.maxWidth = this.maxWidth; if (this.maxHeight) options.maxHeight = this.maxHeight; this.overlayRef = overlay.create(options); if (!this.dropdownTemplate) throw new Error('No dropdownTemplate set'); const portal = new TemplatePortal(this.dropdownTemplate, this.viewContainerRef); this.overlayRef!.attach(portal); this.cd.detectChanges(); this.overlayRef!.updatePosition(); this.shown.emit(); this.showChange.emit(true); setTimeout(() => { if (this.overlayRef) this.overlayRef.updatePosition(); }, 0); setTimeout(() => { if (this.overlayRef) this.overlayRef.updatePosition(); }, 50); if (this.lastOverlayStackItem) this.lastOverlayStackItem.release(); this.lastOverlayStackItem = this.overlayStack.register(this.overlayRef.hostElement); } const normalizedAllowedFocus = isArray(this.allowedFocus) ? this.allowedFocus : (this.allowedFocus ? [this.allowedFocus] : []); const allowedFocus = normalizedAllowedFocus.map(v => v instanceof ElementRef ? v.nativeElement : v) as HTMLElement[]; allowedFocus.push(this.overlayRef.hostElement); if (this.show === undefined) { this.overlayRef.hostElement.focus(); this.lastFocusWatcher = focusWatcher(this.dropdown.nativeElement, [...allowedFocus, target as any], (element) => { //if the element is a dialog as well, we don't close if (!element) return false; if (this.lastOverlayStackItem) { //when there's a overlay above ours we keep it open if (!this.lastOverlayStackItem.isLast()) return true; } return false; }).subscribe(() => { if (!this.keepOpen) { this.close(); ReactiveChangeDetectionModule.tick(); } }); } } public focus() { if (!this.dropdown) return; this.dropdown.nativeElement.focus(); } public close() { if (!this.isOpen) return; if (this.lastOverlayStackItem) this.lastOverlayStackItem.release(); this.isOpen = false; if (this.overlayRef) { this.overlayRef.dispose(); this.overlayRef = undefined; } this.cd.detectChanges(); this.hidden.emit(); this.showChange.emit(false); } } /** * A directive to open the given dropdown on regular left click. */ @Directive({ 'selector': '[openDropdown]', }) export class OpenDropdownDirective implements AfterViewInit, OnDestroy { @Input() openDropdown?: DropdownComponent; @unsubscribe() openSub?: Subscription; @unsubscribe() hiddenSub?: Subscription; constructor( protected elementRef: ElementRef, @Optional() protected button?: ButtonComponent, ) { } ngOnDestroy() { } ngAfterViewInit() { if (this.button && this.openDropdown) { this.openSub = this.openDropdown.shown.subscribe(() => { if (this.button) this.button.active = true; }); this.hiddenSub = this.openDropdown.hidden.subscribe(() => { if (this.button) this.button.active = false; }); } } @HostListener('click') onClick() { if (this.openDropdown) { this.openDropdown.toggle(this.elementRef); } } } /** * A directive to open the given dropdown on mouseenter, and closes automatically on mouseleave. * Dropdown keeps open when mouse enters the dropdown */ @Directive({ 'selector': '[openDropdownHover]', }) export class OpenDropdownHoverDirective implements OnDestroy { @Input() openDropdownHover?: DropdownComponent; /** * In milliseconds. */ @Input() openDropdownHoverCloseTimeout: number = 80; @unsubscribe() openSub?: Subscription; @unsubscribe() hiddenSub?: Subscription; lastHide?: any; constructor( protected elementRef: ElementRef, ) { } ngOnDestroy() { } @HostListener('mouseenter') onHover() { clearTimeout(this.lastHide); this.lastHide = undefined; if (this.openDropdownHover && !this.openDropdownHover.isOpen) { this.openDropdownHover.open(this.elementRef); if (this.openDropdownHover.overlayRef) { this.openDropdownHover.overlayRef.hostElement.addEventListener('mouseenter', () => { this.onHover(); }); this.openDropdownHover.overlayRef.hostElement.addEventListener('mouseleave', () => { this.onLeave(); }); } } } @HostListener('mouseleave') onLeave() { this.lastHide = setTimeout(() => { if (this.openDropdownHover && this.lastHide) this.openDropdownHover.close(); }, this.openDropdownHoverCloseTimeout); } } /** * A directive to open the given dropdown upon right click / context menu. */ @Directive({ 'selector': '[contextDropdown]', }) export class ContextDropdownDirective { @Input() contextDropdown?: DropdownComponent; @HostListener('contextmenu', ['$event']) onClick($event: MouseEvent) { if (this.contextDropdown && $event.button === 2) { this.contextDropdown.close(); $event.preventDefault(); $event.stopPropagation(); this.contextDropdown.open($event); } } } @Component({ selector: 'dui-dropdown-splitter,dui-dropdown-separator', template: ` <div></div> `, styles: [` :host { display: block; padding: 4px 0; } div { border-top: 1px solid var(--line-color-light); } `] }) export class DropdownSplitterComponent { } /** * This directive is necessary if you want to load and render the dialog content * only when opening the dialog. Without it, it is immediately rendered, which can cause * performance and injection issues. * * ```typescript * <dui-dropdown> * <ng-container *dropdownContainer> * Dynamically created upon dropdown instantiation. * </ng-container> * </dui-dropdown> * * ``` */ @Directive({ 'selector': '[dropdownContainer]', }) export class DropdownContainerDirective { constructor(protected dropdown: DropdownComponent, public template: TemplateRef<any>) { this.dropdown.setContainer(this.template); } } @Component({ selector: 'dui-dropdown-item', template: ` <dui-icon [size]="14" class="selected" *ngIf="selected" name="check"></dui-icon> <ng-content></ng-content> `, host: { '[class.selected]': 'selected !== false', '[class.disabled]': 'disabled !== false', }, styleUrls: ['./dropdown-item.component.scss'] }) export class DropdownItemComponent { @Input() selected = false; @Input() disabled: boolean | '' = false; @Input() closeOnClick: boolean = true; constructor(protected dropdown: DropdownComponent) { } @HostListener('click') onClick() { if (this.closeOnClick) { this.dropdown.close(); } } }
the_stack
* WARNING: This file has been deprecated and should now be considered locked against further changes. Its contents * have been partially or wholely superceded by functionality included in the @salesforce/core npm package, and exists * now to service prior uses in this repository only until they can be ported to use the new @salesforce/core library. * * If you need or want help deciding where to add new functionality or how to migrate to the new library, please * contact the CLI team at alm-cli@salesforce.com. * ----------------------------------------------------------------------------------------------------------------- */ // Node import * as path from 'path'; // Thirdparty import * as BBPromise from 'bluebird'; import * as moment from 'moment'; import * as optional from 'optional-js'; import * as _ from 'lodash'; import * as mkdirp from 'mkdirp'; // Local import { ConfigAggregator, Config as CoreConfig } from '@salesforce/core'; import { set } from '@salesforce/kit'; import { AuthInfo } from '@salesforce/core'; import * as OrgInfo from '../org/scratchOrgInfoApi'; import orgConfigAttributes = require('../org/orgConfigAttributes'); import MdapiDeployApi = require('../mdapi/mdapiDeployApi'); import Messages = require('../messages'); import { Config } from './configApi'; import Alias = require('./alias'); import * as almError from './almError'; import configValidator = require('./configValidator'); import logger = require('./logApi'); import srcDevUtil = require('./srcDevUtil'); const defaultConnectedAppInfo = require('./defaultConnectedApp'); const messages = Messages(); const urls = require('../urls'); const fs = BBPromise.promisifyAll(require('fs')); const _buildNoOrgError = (org) => { let message = messages.getMessage('defaultOrgNotFound', org.type); if (!_.isNil(org.name)) { message = messages.getMessage('namedOrgNotFound', org.name); } const noConfigError = new Error(message); noConfigError.name = 'NoOrgFound'; if (org.type === CoreConfig.DEFAULT_USERNAME) { set(noConfigError, 'action', messages.getMessage('defaultOrgNotFoundAction')); } else if (org.type === CoreConfig.DEFAULT_DEV_HUB_USERNAME) { set(noConfigError, 'action', messages.getMessage('defaultOrgNotFoundDevHubAction')); } return noConfigError; }; /** * Represents a config json file in the state folder that consumers can interact with. * * TODO Extract out * TODO Make async. Has huge implications on source*.js files * TODO remove config with workspace.js in sfdx-core */ class StateFile { // TODO: proper property typing [property: string]: any; constructor(config, filePath, contents = {}) { this.path = path.join(config.getProjectPath(), srcDevUtil.getWorkspaceStateFolderName(), filePath); this.backupPath = `${this.path}.bak`; this.contents = contents; } _read(filePath) { // TODO use readJSON when async try { return JSON.parse(fs.readFileSync(filePath)); } catch (e) { if (e.code === 'ENOENT') { return {}; } else { throw e; } } } _write(filePath, contents) { mkdirp.sync(path.dirname(filePath)); fs.writeFileSync(filePath, JSON.stringify(contents, null, 4)); } _exist(filePath) { try { return fs.statSync(filePath); } catch (err) { return false; } } _delete(filePath) { if (this._exist(filePath)) { return fs.unlinkSync(filePath); } return false; } read() { this.contents = this._read(this.path); return this.contents; } write(newContents) { if (!_.isNil(newContents)) { this.contents = newContents; } this._write(this.path, this.contents); return this.contents; } exist() { return this._exist(this.path); } delete() { return this._delete(this.path); } backup() { if (this.exist()) { this._write(this.backupPath, this.read()); } } revert() { if (this._exist(this.backupPath)) { this.write(this._read(this.backupPath)); this._delete(this.backupPath); } return this.contents; } } /** * reduce metaConfigs down to an object that contains a consolidated view of ScratchOrgInfo objects across all * locally configured dev hubs. * * @param {object} metaConfigs * @private */ const _localOrgMetaConfigsReduction = function (metaConfigs) { return metaConfigs.reduce((accum, currentValue) => { // Initialize the map to store scratchOrgInfos across all locally configured devHubs accum.mergedScratchOrgInfosAcrossLocalDevHubs = accum.mergedScratchOrgInfosAcrossLocalDevHubs || new Map(); // Place to store locally authenticated orgs. drawing a distinction here of: {scratchOrg, devHub, non ScratchOrg accum.orgs = accum.orgs || []; // devhubs have ScratchOrgInfo objects keyed by username. Need to consolidate down to one map. The third index // of current value will contain devHub member data. an error object otherwise. if (_.isError(currentValue[2])) { if (currentValue[2]['errorCode'] === 'INVALID_TYPE') { // Invalid type means we connected and there is not an sobject ScratchOrgInfo currentValue[1].connectedStatus = 'Connected'; } else { currentValue[1].connectedStatus = currentValue[2]['code'] || currentValue[2]['errorCode'] || currentValue[2].name; } } // Not nil and not an error it must be a hub org. else if (!_.isNil(currentValue[2])) { currentValue[1].connectedStatus = 'Connected'; currentValue[1].isDevHub = true; accum.mergedScratchOrgInfosAcrossLocalDevHubs = new Map([ ...accum.mergedScratchOrgInfosAcrossLocalDevHubs, ...currentValue[2], ]); } // nil - we know for a fact it's not a dev hub else { currentValue[1].connectedStatus = 'Unknown'; } // update the lastUsed value to the fstats returned from the previous handler. currentValue[1].lastUsed = currentValue[0].atime; accum.orgs.push(currentValue[1]); return accum; }, {}); }; /** * Helper to match orgMeta usernames against the project configuration for defaultdevhubusername and defaultusername * * @param {object} orgMeta - the metadata containing the username to check * @param {array} _defaultOrgs - an array containing the default username and devhub * @private */ const _identifyDefaultOrgs = function (orgMeta, _defaultOrgs) { if (orgMeta.username === _defaultOrgs[0]) { orgMeta.isDefaultDevHubUsername = true; } else if (orgMeta.username === _defaultOrgs[1]) { orgMeta.isDefaultUsername = true; } }; /** * Helper utility to remove sensitive information from a scratch org auth config. By default refreshTokens and client secrets are removed. * * @param {*} config - scratch org auth object. * @param {string[]} properties - properties to exclude ex ['refreshToken', 'clientSecret'] * @returns the config less the sensitive information. */ const _removeRestrictedInfoFromConfig = function (config, properties = ['refreshToken', 'clientSecret']) { return _.omit(config, properties); }; /** * Helper to group orgs by {devHub, scratchOrg, nonScratchOrgs} * * @param {object} configsAcrossDevHubs - The orgs and scratchOrgInfo map. See _localOrgMetaConfigsReduction * @param {object} orgClass - The scratchOrg prototype * @param {string[]} excludeProperties - properties to exclude from the grouped configs ex. ['refreshToken', 'clientSecret'] * @private */ const _groupOrgs = async function (configsAcrossDevHubs, orgClass, excludeProperties) { const self = this; const _accum = {}; _.set(_accum, 'scratchOrgs', new Map()); _.set(_accum, 'nonScratchOrgs', new Map()); _.set(_accum, 'devHubs', new Map()); // Since configsAcrossDevHubs can actually have no orgs we want to return a valid empty data structure. if (_.isNil(configsAcrossDevHubs.orgs)) { return BBPromise.resolve(_accum); } // This promise handler is used to find the default project configuration for targetusername and // targetdevhubusername return BBPromise.all([ orgClass .create(undefined, CoreConfig.DEFAULT_DEV_HUB_USERNAME) .then((org) => org.name) .catch(() => null), orgClass .create(undefined, CoreConfig.DEFAULT_USERNAME) .then((org) => org.name) .catch(() => null), ]).then((defaultOrgs) => configsAcrossDevHubs.orgs.reduce((accum, _currentValue) => { const currentValue = _removeRestrictedInfoFromConfig(_currentValue, excludeProperties); _identifyDefaultOrgs.call(self, currentValue, defaultOrgs); const info = configsAcrossDevHubs.mergedScratchOrgInfosAcrossLocalDevHubs.get(currentValue.username); // This means we found a scratchOrgInfo object from some dev hub so we can get the status. if (!_.isNil(info)) { // update the info object with an expiration indicator. info.isExpired = moment(info.expirationDate).isBefore(moment()); // Note that the info object contains a devHubUsername reference. It will be merged in/over. // This will ensure if we lose contact with a devHub we can determine this is a scratchOrg. accum.scratchOrgs.set(currentValue.username, _.merge(currentValue, info)); } else if (currentValue.devHubUsername) { // In this scenario there was no hit on this org as it pertains to being a member of a devhub. But this org // was tagged as a scratch org during either a local create:org command or a previous invocation of the // list command. The org could have been deleted after the last time org:list was executed. currentValue.isMissing = true; accum.scratchOrgs.set(currentValue.username, _.merge(currentValue, info)); } else { accum.nonScratchOrgs.set(currentValue.username, currentValue); } if (currentValue.isDevHub) { accum.devHubs.set(currentValue.username, currentValue); } return accum; }, _accum) ); }; /** * helper that updates all the org auth files with indicators to reduce the number of queries to the server. * * @param {Array} groupedOrgs - an array of scratchOrg, nonScratchOrgs, devHubs * @param {function} _orgUpdate - a function to perform the file update * @returns {BBPromise.<TResult>} */ const _updateOrgIndicators = function (groupedOrgs, _orgUpdate) { return BBPromise.map( groupedOrgs.scratchOrgs, (meta) => _orgUpdate(meta[1], { devHubUsername: meta[1].devHubUsername }), { concurrency: 1 } ) .catch((err) => { // by some remote chance we cannot update the cache value for isDevHub it's not the end of the world. If // there is a large number of orgs the performance could be slower each time the command is invoked. Putting a // warning in the log is appropriate. this.logger.warn(`error writing files: ${err.message} stack: ${err.stack}`); }) .then(() => groupedOrgs); }; /** * @deprecated The functionality is moving to sfdx-core */ class Org { // TODO: proper property typing [property: string]: any; /** * Org types that can be set as a default for local and global configs. * All commands target USERNAME, except commands that specify a different * default, like org:create specifing DEVHUB has a default. */ static Defaults = { DEVHUB: CoreConfig.DEFAULT_DEV_HUB_USERNAME, USERNAME: CoreConfig.DEFAULT_USERNAME, list() { return [CoreConfig.DEFAULT_DEV_HUB_USERNAME, CoreConfig.DEFAULT_USERNAME]; }, }; /** * Construct a new org. No configuration is initialized at this point. To * get any auth data, getConfig must first be called which will try to get * the default org of the given type unless the setName method is called. * Any calls to org.force will call getConfig. * * @param {Force} force The force api * @param {string} type The type of org for the CLI. This is used to store * and find defaults for the project. * @constructor */ constructor(force?, type = CoreConfig.DEFAULT_USERNAME) { // eslint-disable-next-line const Force = require('./force'); this.force = optional.ofNullable(force).orElse(new Force(new Config())); this.config = this.force.getConfig(); this.logger = logger.child('Org'); this.type = type; this.mdDeploy = new MdapiDeployApi(this); } retrieveMaxApiVersion() { // getting the max api version does not require auth. So if you think adding a call to refreshAuth here is the correct // thing to do. it's not! return this.force.getApiVersions(this).then((versions) => _.maxBy(versions, (_ver: any) => _ver.version)); } /** * Gets the name of this scratch org. */ getName() { return this.name; } resolveDefaultName() { // If the name is set, we don't want to resolve the default if (this.getName()) { return BBPromise.resolve(); } return this.resolvedAggregator().then((sfdxConfig) => { const name = sfdxConfig.getPropertyValue(this.type); return Alias.get(name).then((orgName) => { this.setName(orgName || name); }); }); } /** * Sets the name of this scratch org. After setting the name any call to getConfig will result in the org associated * with $HOME/.sfdx/[name].json being returned. * * @param name - the name of the org. */ setName(name) { this.name = name; this.logger.setConfig('username', name); this.force.logger.setConfig('username', name); } async resolvedAggregator() { if (!this.aggregator) { this.aggregator = ConfigAggregator.create(); } return this.aggregator; } async initializeConfig(): Promise<CoreConfig> { let config: CoreConfig; try { config = await CoreConfig.create({ isGlobal: false }); } catch (err) { if (err.name === 'InvalidProjectWorkspace') { config = await CoreConfig.create({ isGlobal: true }); } else { throw err; } } return config; } /** * Get if this org is the actual workspace org. The WORKSPACE type is set by default * so we can retrive the workspace org by default when getConfig is called. However, * if someone wants to know if an org is actually a workspace org, we need to make sure * that the current username is the actual name in the sfdx-config.json, otherwise * it is not the workspace org, even if it should be but isn't saved yet. i.e. * setName is called after which happens if the --username falg is set. */ isWorkspaceOrg() { return ( this.type === CoreConfig.DEFAULT_USERNAME && this.getName() === this.config.getAppConfigIfInWorkspace()[this.type] ); } getDataPath(filename?) { const username = this.getName(); if (!username) { throw _buildNoOrgError(this); } // Create a path like <project>/.sfdx/orgs/<username>/<filename> return path.join(...['orgs', username, filename].filter((e) => !!e)); } /** * Clean all data files in the org's data path, then remove the data directory. * Usually <workspace>/.sfdx/orgs/<username> */ cleanData(orgDataPath) { let dataPath; try { dataPath = path.join( this.config.getProjectPath(), srcDevUtil.getWorkspaceStateFolderName(), orgDataPath || this.getDataPath() ); } catch (err) { if (err.name === 'InvalidProjectWorkspace') { // If we aren't in a project dir, we can't clean up data files. // If the user deletes this org outside of the workspace they used it in, // data files will be left over. return; } throw err; } const removeDir = (dirPath) => { let stats; try { stats = fs .readdirSync(dirPath) .map((file) => path.join(dirPath, file)) .map((filePath) => ({ filePath, stat: fs.statSync(filePath) })); stats.filter(({ stat }) => stat.isDirectory()).forEach(({ filePath }) => removeDir(filePath)); stats.filter(({ stat }) => stat.isFile()).forEach(({ filePath }) => fs.unlinkSync(filePath)); fs.rmdirSync(dirPath); } catch (err) { this.logger.warn(`failed to read directory ${dirPath}`); } }; removeDir(dataPath); } /** * Get the full path to the file storing the maximum revision value from the last valid pull from workspace scratch org * * @param wsPath - The root path of the workspace * @returns {*} */ getMaxRevision() { return new StateFile(this.config, this.getDataPath('maxRevision.json')); } /** * Get the full path to the file storing the workspace source path information * * @param wsPath - The root path of the workspace * @returns {*} */ getSourcePathInfos() { return new StateFile(this.config, this.getDataPath('sourcePathInfos.json')); } /** * Returns a promise to retrieve the ScratchOrg configuration for this workspace. * * @returns {BBPromise} */ getConfig() { if (this.authConfig) { return BBPromise.resolve(this.authConfig); } return this.resolveDefaultName() .then(() => this.resolvedAggregator()) .then((sfdxConfig) => { const username = this.getName(); // The username of the org can be set by the username config var, env var, or command line. // If the username is not set, getName will resolve to the default username for the workspace. // If the username is an access token, use that instead of getting the username auth file. const accessTokenMatch = _.isString(username) && username.match(/^(00D\w{12,15})![\.\w]*$/); if (accessTokenMatch) { let instanceUrl; const orgId = accessTokenMatch[1]; this.usingAccessToken = true; // If it is an env var, use it instead of the local workspace sfdcLoginUrl property, // otherwise try to use the local sfdx-project property instead. if (sfdxConfig.getInfo('instanceUrl').isEnvVar()) { instanceUrl = sfdxConfig.getPropertyValue('instanceUrl'); } else { instanceUrl = sfdxConfig.getPropertyValue('instanceUrl') || urls.production; } // If the username isn't an email, is it as a accessToken return { accessToken: username, instanceUrl, orgId, }; } else { return srcDevUtil .getGlobalConfig(`${username}.json`) .then((config) => configValidator.getCleanObject(config, orgConfigAttributes, false)) .then((config) => { if (_.isNil(config.clientId)) { config.clientId = defaultConnectedAppInfo.legacyClientId; config.clientSecret = defaultConnectedAppInfo.legacyClientSecret; } return config; }) .catch((error) => { let returnError = error; if (error.code === 'ENOENT') { returnError = _buildNoOrgError(this); } return BBPromise.reject(returnError); }); } }) .then((config) => { this.authConfig = config; return config; }); } /** * Removes the scratch org config file at $HOME/.sfdx/[name].json, any project level org * files, all user auth files for the org, matching default config settings, and any * matching aliases. * * @deprecated See Org.ts in sfdx-core */ deleteConfig() { // If deleting via the access token there shouldn't be any auth config files // so just return; if (this.usingAccessToken) { return BBPromise.resolve(); } let orgFileName; const aliases = []; // If the org being deleted is the workspace org then we need to do this so that subsequent calls to the // cli won't fail when trying to retrieve scratch org info from ~/.sfdx const cleanup = (name) => { let alias; return Alias.byValue(name) .then((_alias) => { alias = _alias; _alias && aliases.push(_alias); }) .then(() => this.resolvedAggregator()) .then(async (aggregator) => { // Get the aggregated config for this type of org const info = aggregator.getInfo(this.type); // We only want to delete the default if it is in the local or global // config file. i.e. we can't delete an env var. if ((info.value === name || info.value === alias) && (info.isGlobal() || info.isLocal())) { const config = await CoreConfig.create({ isGlobal: info.isGlobal() }); config.unset(this.type); await config.write(); } return BBPromise.resolve(); }) .then(() => this.cleanData(path.join('orgs', name))) .then(() => { AuthInfo.clearCache(name); return srcDevUtil.deleteGlobalConfig(`${name}.json`); }); }; return this.getConfig() .then((orgData) => { orgFileName = `${orgData.orgId}.json`; return srcDevUtil.getGlobalConfig(orgFileName, {}); }) .then(({ usernames }) => { if (!usernames) { usernames = [this.getName()]; orgFileName = null; } return usernames; }) .then((usernames) => { this.logger.info(`Cleaning up usernames: ${usernames} in org: ${this.authConfig.orgId}`); return BBPromise.all(usernames.map((username) => cleanup(username))); }) .then(() => Alias.unset(aliases)) .then(() => { if (orgFileName) { return srcDevUtil.deleteGlobalConfig(orgFileName); } return BBPromise.resolve(); }); } getFileName() { return `${this.name}.json`; } /** * Returns a promise to save a valid workspace scratch org configuration to disk. * * @param configObject - The object to save. If the object isn't valid an error will be thrown. * { orgId:, redirectUri:, accessToken:, refreshToken:, instanceUrl:, clientId: } * @param saveAsDefault {boolean} - whether to save this org as the default for this workspace. * @returns {BBPromise.<Object>} Not the access tokens will be encrypted. Call get config to get decrypted access tokens. */ saveConfig(configObject, saveAsDefault?) { if (this.usingAccessToken) { return BBPromise.resolve(configObject); } this.name = configObject.username; let savedData; // For security reasons we don't want to arbitrarily write the configObject to disk. return configValidator .getCleanObject(configObject, orgConfigAttributes, true) .then((dataToSave) => { savedData = dataToSave; return srcDevUtil.saveGlobalConfig(this.getFileName(), savedData); }) .then(async () => { AuthInfo.clearCache(configObject.username); this.logger.info(`Saved org configuration: ${this.getFileName()}`); if (saveAsDefault) { const config = await this.initializeConfig(); config.set(this.type, this.alias || this.name); await config.write(); } this.authConfig = configObject; return BBPromise.resolve(savedData); }); } /** * Refresh a users access token. * * @returns {*|BBPromise.<{}>} * @deprecated See Org.ts in sfdx-core */ refreshAuth() { return this.force.describeData(this); } /** Use the settings to generate a package ZIP and deploy it to the scratch org. * * @param settings the settings generator * @returns {*|BBPromise.<{}>} */ applySettings(settings, apiVersion) { // Create our own options so we can control the MD deploy of the settings package. const options = { wait: -1, disableLogging: true, }; return ( settings .createDeployDir(apiVersion) // Package it all up and send to the scratch org .then((deploydir) => this.mdDeploy.deploy(Object.assign(options, { deploydir }))) .catch((err) => { this.mdDeploy._reporter._printComponentFailures(err.result); return BBPromise.reject(almError('ProblemDeployingSettings')); }) ); } /** * Reads and returns the global, hidden org file in $HOME/.sfdx for this org. * E.g., $HOME/.sfdx/00Dxx0000001gPFEAY.json * * @returns {Object} - The contents of the org file, or an empty object if not found. */ readOrgFile() { return this.getConfig().then((orgData) => srcDevUtil.getGlobalConfig(`${orgData.orgId}.json`, {})); } /** * Returns the regular expression that filters files stored in $HOME/.sfdx * * @returns {RegExp} - The auth file name filter regular expression */ static getAuthFilenameFilterRegEx() { return /^[^.][^@]*@[^.]+(\.[^.\s]+)+\.json$/; } /** * The intent of the function is to determine if a user has authenticated at least once. The only way to really do this * is to check to see if there are any org files. If so, then we can assume there is a keychain in use only if there is * no generic keychain file. This covers the new install or reset case. */ static hasAuthentications() { return Org.readAllUserFilenames() .then((users) => !_.isEmpty(users)) .catch((err) => { // ENOENT if (err.name === 'noOrgsFound' || err.code === 'ENOENT') { return false; } throw err; }); } /** * returns a list of all username auth file's stored in $HOME/.sfdx * * @deprecated See Org.js and Auth.js in sfdx-core */ static readAllUserFilenames() { return fs.readdirAsync(srcDevUtil.getGlobalHiddenFolder()).then((files) => { const sfdxFiles = files.filter((file) => file.match(Org.getAuthFilenameFilterRegEx())); // Want to throw a clean error if no files are found. if (_.isEmpty(sfdxFiles)) { throw almError( { keyName: 'noOrgsFound', bundle: 'scratchOrgApi' }, null, { keyName: 'noOrgsFoundAction', bundle: 'scratchOrgApi' }, null ); } else { // At least one org is here. Maybe it's a dev hub return sfdxFiles; } }); } /** * Returns a data structure containing all devhubs and scratch orgs stored locally in $HOME/.sfdx * * @param {array} userFilenames - use readAllUserFilenames() to get a list of everything configured locally. This also * supports providing a subset of filenames which is useful if one only wants status information on one org. We can * limit unnecessary calls to the server. * @param {number} concurrency - the max number of requests that can be sent to the server at a time. * @returns {BBPromise.<*>} */ static readMapOfLocallyValidatedMetaConfig(userFilenames, concurrency = 3) { if (concurrency < 1) { return BBPromise.reject(new Error('concurrency setting must be greater than zero.')); } const orgInfo = new OrgInfo(); if (_.isNil(userFilenames) || _.isEmpty(userFilenames)) { return BBPromise.reject(new Error('file names not specified.')); } const fileDoesntExistFilter = BBPromise.all( _.map(userFilenames, (fileName) => { const filePath = path.join(srcDevUtil.getGlobalHiddenFolder(), fileName); return BBPromise.all([ fs .statAsync(filePath) .then((stat) => stat) .catch(() => null), srcDevUtil .readJSON(filePath) .then((content) => content) .catch((err) => { logger.warn(`Problem reading file: ${filePath} skipping`); logger.warn(err.message); return null; }), ]); }) ) // also removes non-admin auth files; i.e., users created via user:create .filter( (statsAndContent) => !_.isNil(statsAndContent[0]) && !_.isNil(statsAndContent[1]) && _.isNil(statsAndContent[1].scratchAdminUsername) ); return fileDoesntExistFilter .then((fileContentsAndMeta) => { const orgIds15 = _.map(fileContentsAndMeta, (fileContentAndMeta) => { if (fileContentAndMeta && fileContentAndMeta.length > 0) { return srcDevUtil.trimTo15(fileContentAndMeta[1].orgId); } return null; }); return BBPromise.map( fileContentsAndMeta, (fileContentAndMeta) => { /** * If the org represented by filename is a devhub it will have the ScratchOrgInfo metadata at the third * position in the promise array returned in this peer scope. * * @returns {BBPromise.<array>} */ const promiseDevHubMetadata = (username) => { const org = new Org(); org.setName(username); return org .getConfig() .then((configData) => { // Do the query for orgs without a devHubUsername attribute. In some cases scratch org auth // files may not have a devHubUsername property; but that's ok. We will discover if it. if (_.isNil(configData.devHubUsername)) { return org .refreshAuth() .catch((err) => { org.logger.trace(`error refreshing auth for org: ${configData.username}`); org.logger.trace(err); return err; }) .then((result) => { if (_.isError(result)) { return result; } return orgInfo.retrieveScratchOrgInfosWhereInOrgIds(org, orgIds15); }) .catch((err) => { org.logger.trace( `error retrieving ScratchOrgInfo object for org: ${configData.username}. this is expected for non-devhubs` ); org.logger.trace(err); return err; }); } else { // only if we know for certain that an org isn't a dev hub. return null; } }) .catch((err) => err); }; // Get the file metadata attributes, content, also assume this org is devHub so attempt to get // ScratchOrgInfo objects.. return BBPromise.all([ fileContentAndMeta[0], fileContentAndMeta[1], promiseDevHubMetadata(fileContentAndMeta[1].username).catch(() => null), ]); }, { concurrency } ); }) .then((metaConfigs) => _localOrgMetaConfigsReduction(metaConfigs)); } /** * this methods takes all locally configured orgs and organizes them into the following buckets: * { devHubs: [{}], nonScratchOrgs: [{}], scratchOrgs: [{}] } * * @param [{string}] - an array of strings that are validated for devHubs against the server. * @param {number} concurrency - this is the max batch number of http requests that will be sent to the server for * the scratchOrgInfo query. * @param {string[]|null} excludeProperties - properties to exclude from the configs defaults. ['refreshToken', 'clientSecret']. Specify null to include all properties. */ static readLocallyValidatedMetaConfigsGroupedByOrgType(userFilenames, concurrency = 3, excludeProperties?) { return Org.readMapOfLocallyValidatedMetaConfig(userFilenames, concurrency) .then((configsAcrossDevHubs) => Alias.list().then((aliases) => { _.forEach(configsAcrossDevHubs.orgs, (org) => { org.alias = _.findKey(aliases, (alias) => alias === org.username); }); return configsAcrossDevHubs; }) ) .then((configsAcrossDevHubsWithAlias) => _groupOrgs.call(new Config(), configsAcrossDevHubsWithAlias, Org, excludeProperties) ) .then((groupedOrgs) => _updateOrgIndicators.call( { logger: logger.child('readLocallyValidatedMetaConfigGroupdByOrgType'), }, groupedOrgs, (meta, attributesToMerge) => { const org = new Org(); org.setName(meta.username); return org .getConfig() .then((configData) => { // we want to merge the attributes and save the config only if the attributes to merge are // different. if (!_.isNil(attributesToMerge)) { const matcher = _.matches(attributesToMerge); if (!matcher(configData)) { return org.saveConfig(_.merge(configData, attributesToMerge)); } } return null; }) .catch(() => null); } ) ); } /** * @deprecated See Org.ts in sfdx-core */ static async create(username?, defaultType?) { // If orgType is undefined, Org will use the right default. const org = new Org(undefined, defaultType); if (_.isString(username) && !_.isEmpty(username)) { // Check if the user is an alias const actualUsername = await Alias.get(username); const verbose = srcDevUtil.isVerbose(); if (_.isString(actualUsername) && !_.isEmpty(actualUsername)) { if (verbose) { logger.log(`Using resolved username ${actualUsername} from alias ${username}${logger.getEOL()}`); } org.alias = username; org.setName(actualUsername); } else { if (verbose) { logger.log(`Using specified username ${username}${logger.getEOL()}`); } org.setName(username); } } // If the username isn't set or passed in, the default username // will be resolved on config. await org.getConfig(); return org; } } export = Org;
the_stack
// The reporting system in use here is best described as a "hairball" or snowball design // as an initial approach. A large, informative set of contextual data is built by the // report providers. It is OK for a provider in the pipeline to depend on the data // collected before its execution. import os from 'os'; import fileSize from 'file-size'; import moment from 'moment'; import path from 'path'; import app from '../../app'; // import { buildConsolidatedMap as buildRecipientMap } from './consolidated'; import { build as organizationsBuild, consolidate as organizationsConsoldate, process as organizationsProcess } from './organizations'; import { build as repositoriesBuild, consolidate as repositoriesConsolidate, process as repositoriesProcess } from './repositories'; import { build as teamsBuild, consolidate as teamsConsolidate, process as teamsProcess, IReportsTeamContext } from './teams'; import mailer from './mailer'; import { Operations, Repository, Team } from '../../business'; import { ICacheHelper } from '../../lib/caching'; import { ICorporateLink, IReposJob, IReposJobResult } from '../../interfaces'; import { writeTextToFile } from '../../utils'; import { writeDeflatedTextFile } from './fileCompression'; // Debug-related values for convienience const fakeSend = false; const skipStore = false; const slice = undefined; // 250; const reportGeneratedFormat = 'h:mm a dddd, MMMM Do YYYY'; const providerNames = [ 'organizations', 'repositories', 'teams', ]; export interface IReportsContext { operations: Operations; insights: any; entities?: { repos?: Repository[]; teams?: Team[]; }; processing: any; reportsBy: { upn: Map<string, any>; email: Map<string, any>; }; providers: any; started: string; organizationData: any; teamData?: IReportsTeamContext[]; reports: { reportRedisClient: ICacheHelper; send: boolean; store: boolean; dataLake: boolean; }; consolidated?: any; visitedDefinitions: any; config: any; app: any; linkData?: Map<number, ICorporateLink>; repositoryData?: any[]; reportsByRecipient?: Map<string, any>; settings: { basedir: string; slice?: any; parallelRepoProcessing: number; repoDelayAfter: number; teamDelayAfter: number; tooManyOrgOwners: number; tooManyRepoAdministrators: number; orgPercentAvailablePrivateRepos: number; fakeSend?: string; storeLocalReportPath?: string; witnessEventKey: string; witnessEventReportsTimeToLiveMinutes: any; // ? consolidatedSchemaVersion: string; fromAddress: string; dataLakeAccount?: any; // ? campaign: { source: 'administrator-digest'; medium: 'email'; campaign: 'github-digests'; }; }; } async function buildReport(context): Promise<void> { try { await processReports(context); } catch (error) { console.dir(error); } try { await buildReports(context); } catch (error) { console.dir(error); } try { await consolidateReports(context); } catch (error) { console.dir(error); } try { await storeReports(context); } catch (error) { console.dir(error); } try { await sendReports(context); } catch (error) { console.dir(error); } try { await recordMetrics(context); } catch (error) { console.dir(error); } try { await dataLakeUpload(context); } catch (error) { console.dir(error); } try { await finalizeEvents(context); } catch (error) { console.dir(error); } } export default async function run({ providers, started }: IReposJob): Promise<IReposJobResult> { const { mailProvider, operations, config } = providers; const okToContinue = (config && config.github && config.github.jobs && config.github.jobs.reports && config.github.jobs.reports.enabled === true); if (!okToContinue) { console.log('config.github.jobs.reports.enabled is not set'); return {}; } console.log('OK, so, this job is actually not setup to work right now...'); return {}; // -- THIS JOB IS OFFLINE FOR NOW -- console.log(`Report run started ${started}`); const insights = providers.insights; if (!insights) { throw new Error('No app insights client available'); } insights.trackEvent({ name: 'JobReportsStarted', properties: { hostname: os.hostname(), }, }); if (!mailProvider) { throw new Error('No mail provider available'); } const reportConfig = config && config.github && config.github.jobs ? config.github.jobs.reports : {}; const context: IReportsContext = { providers, operations, insights, entities: {}, processing: {}, reportsBy: { upn: new Map(), email: new Map(), }, started: moment().format(), organizationData: {}, settings: { basedir: config.typescript.appDirectory, slice: slice || undefined, parallelRepoProcessing: 2, repoDelayAfter: 200, // 200ms to wait between repo actions, to help reduce GitHub load teamDelayAfter: 200, // 200ms to wait between team actions, to help reduce GitHub load tooManyOrgOwners: 5, tooManyRepoAdministrators: 15, orgPercentAvailablePrivateRepos: 0.15, fakeSend: fakeSend ? path.join(__dirname, 'sent') : undefined, storeLocalReportPath: skipStore ? path.join(__dirname, 'report.json') : undefined, witnessEventKey: reportConfig.witnessEventKey, witnessEventReportsTimeToLiveMinutes: reportConfig.witnessEventReportsTimeToLiveMinutes, consolidatedSchemaVersion: '170503', fromAddress: reportConfig.mail.from, dataLakeAccount: null, campaign: { source: 'administrator-digest', medium: 'email', campaign: 'github-digests', }, }, reports: { reportRedisClient: null, // reportRedisClient, send: true && (fakeSend || reportConfig.mail && reportConfig.mail.enabled), store: true && !skipStore, dataLake: true && !skipStore && reportConfig.dataLake && reportConfig.dataLake.enabled, }, visitedDefinitions: {}, consolidated: {}, config, app, }; if (context.reports.dataLake === true && reportConfig.dataLake && reportConfig.dataLake.azureStorage && reportConfig.dataLake.azureStorage.key) { context.settings.dataLakeAccount = reportConfig.dataLake.azureStorage; } await buildReport(context); console.log('reporting done'); return {}; } // ------------------------------------------------------------------ async function buildReports(context) { try { await organizationsBuild(context); } catch (globalBuildError) { console.dir(globalBuildError); } try { await repositoriesBuild(context); } catch (globalBuildError) { console.dir(globalBuildError); } try { await teamsBuild(context); } catch (globalBuildError) { console.dir(globalBuildError); } return context; } async function processReports(context) { try { await organizationsProcess(context); } catch (globalProcessError) { console.dir(globalProcessError); } try { await repositoriesProcess(context); } catch (globalProcessError) { console.dir(globalProcessError); } try { await teamsProcess(context); } catch (globalProcessError) { console.dir(globalProcessError); } return context; } async function consolidateReports(context: IReportsContext): Promise<IReportsContext> { try { await organizationsConsoldate(context); } catch (globalConsolidationError) { console.dir(globalConsolidationError); } try { await repositoriesConsolidate(context); } catch (globalConsolidationError) { console.dir(globalConsolidationError); } try { await teamsConsolidate(context); } catch (globalConsolidationError) { console.dir(globalConsolidationError); } return context; } // ------------------------------------------------------------------ async function finalizeEvents(context: IReportsContext) { context.insights.trackEvent({ name: 'JobReportsFinalizing' }); return context; } async function dataLakeUpload(context: IReportsContext) { const insights = context.insights; if (!context.reports.dataLake) { insights.trackEvent({ name: 'JobReportsReportDataLakeSkipped' }); return context; } insights.trackEvent({ name: 'JobReportsReportDataLakeStarted' }); // specific properties used for each row // issueProviderName: // issueTimestamp: started // issueTypeName: typeName let dataLakeOutput = []; const started = context.started; const consolidated = context.consolidated; for (let i = 0; i < providerNames.length; i++) { const providerName = providerNames[i]; const root = consolidated[providerName]; if (root) { const definitions = {}; for (let x = 0; x < root.definitions.length; x++) { const d = root.definitions[x]; definitions[d.name] = d; } if (root.entities) { for (let j = 0; j < root.entities.length; j++) { const entity = root.entities[j]; if (entity && entity.issues) { const issueList = Object.getOwnPropertyNames(entity.issues); for (let k = 0; k < issueList.length; k++) { const issueTypeName = issueList[k]; const issues = entity.issues[issueTypeName]; const definition = definitions[issueTypeName]; let targetCollectionName = null; if (definition && definition.hasTable) { targetCollectionName = 'rows'; } else if (definition && definition.hasList) { targetCollectionName = 'listItems'; } if (targetCollectionName && issues[targetCollectionName] && Array.isArray(issues[targetCollectionName])) { const collection = issues[targetCollectionName]; for (let l = 0; l < collection.length; l++) { const row = collection[l]; const rowValue = typeof (row) === 'object' ? row : { text: row }; if (!row.entityName) { rowValue.entityName = entity.name; } if (!row.entity) { const entityClone = Object.assign({}, entity); delete entityClone.recipients; delete entityClone.issues; rowValue.entity = entityClone; } const dataLakeRow = Object.assign({ issueProviderName: providerName, issueTimestamp: started, issueTypeName: issueTypeName, }, rowValue); dataLakeOutput.push(JSON.stringify(dataLakeRow)); } } } } } } } } } async function storeReports(context: IReportsContext): Promise<IReportsContext> { context.insights.trackEvent({ name: 'JobReportsReportStoringStarted' }); const report = Object.assign({}, context.consolidated); const consolidatedSchemaVersion = context.settings.consolidatedSchemaVersion; report.metadata = { started: context.started, startedText: moment(context.started).format(reportGeneratedFormat), finished: moment().format(), version: consolidatedSchemaVersion, }; const json = JSON.stringify(report); const storeLocalReportPath = context.settings.storeLocalReportPath; if (storeLocalReportPath) { await storeLocalReport(report, storeLocalReportPath, context); } if (!context.reports.store) { context.insights.trackEvent({ name: 'JobReportsReportStoringSkipped' }); return context; } const stringSizeUncompressed = fileSize(Buffer.byteLength(json, 'utf8')).human(); context.insights.trackEvent({ name: 'JobReportsReportStoring', properties: { size: stringSizeUncompressed, version: consolidatedSchemaVersion, }, }); const ttl = context.settings.witnessEventReportsTimeToLiveMinutes; if (!ttl) { throw new Error('No witnessEventReportsTimeToLiveMinutes configuration value defined for the report TTL. To make efficient use of Redis memory, a TTL must be provided.'); } const reportingRedis = context.reports.reportRedisClient; const reportingKey = context.settings.witnessEventKey; if (reportingRedis && reportingKey) { reportingRedis.setCompressedWithExpire(reportingKey, json, ttl) } return context; } async function storeLocalReport(report, storeLocalReportPath, context: IReportsContext): Promise<IReportsContext> { const prettyFile = JSON.stringify(report, undefined, 2); writeTextToFile(storeLocalReportPath, prettyFile); return context; } async function recordMetrics(context: IReportsContext): Promise<IReportsContext> { const insights = context.insights; const consolidated = context.consolidated; let overallIssues = 0; for (let i = 0; i < providerNames.length; i++) { const providerName = providerNames[i]; const root = consolidated[providerName]; if (root) { const metricRoot = `JobRepoReportIssues${providerName}`; const countByIssue = new Map(); const definitions = {}; for (let x = 0; x < root.definitions.length; x++) { const d = root.definitions[x]; definitions[d.name] = d; } if (root.entities) { for (let j = 0; j < root.entities.length; j++) { const entity = root.entities[j]; if (entity && entity.issues) { const issueList = Object.getOwnPropertyNames(entity.issues); for (let k = 0; k < issueList.length; k++) { const issues = entity.issues[issueList[k]]; const definition = definitions[issueList[k]]; let targetCollectionName = null; if (definition && definition.hasTable) { targetCollectionName = 'rows'; } else if (definition && definition.hasList) { targetCollectionName = 'listItems'; } if (targetCollectionName && issues[targetCollectionName] && Array.isArray(issues[targetCollectionName])) { const count = issues[targetCollectionName].length; let currentValue = countByIssue.get(issueList[k]); if (!currentValue) { currentValue = 0; } countByIssue.set(issueList[k], currentValue + count); } } } } } // Report metric for this provider and all of its issues (total) const issueNameList = Array.from(countByIssue.keys()); for (let j = 0; j < issueNameList.length; j++) { const issueName = issueNameList[j]; const count = countByIssue.get(issueName); const metricName = `${metricRoot}${issueName}`; insights.trackMetric({ name: metricName, value: count }); overallIssues += count; } } } insights.trackMetric({ name: 'JobRepoReportsIssuesOverall', properties: overallIssues, }); return context; } async function sendReports(context: IReportsContext): Promise<IReportsContext> { if (!context.reports.send) { context.insights.trackEvent({ name: 'JobReportsSendingSkipped' }); return context; } context.insights.trackEvent({ name: 'JobReportsReportSendingStarted' }); await mailer(context); return context; }
the_stack
import { ApiContract, ApiManagementServiceResource, BackendContract } from "@azure/arm-apimanagement/esm/models"; import { FunctionEnvelope, Site } from "@azure/arm-appservice/esm/models"; import { DeploymentExtended, DeploymentsListByResourceGroupResponse } from "@azure/arm-resources/esm/models"; import { HttpHeaders, HttpOperationResponse, HttpResponse, WebResource } from "@azure/ms-rest-js"; import { AuthResponse, LinkedSubscription, TokenCredentialsBase } from "@azure/ms-rest-nodeauth"; import { TokenClientCredentials, TokenResponse } from "@azure/ms-rest-nodeauth/dist/lib/credentials/tokenClientCredentials"; import { ServiceListContainersSegmentResponse } from "@azure/storage-blob/typings/lib/generated/lib/models"; import { AxiosRequestConfig, AxiosResponse } from "axios"; import yaml from "js-yaml"; import Serverless from "serverless"; import Service from "serverless/classes/Service"; import Utils from "serverless/classes/Utils"; import PluginManager from "serverless/lib/classes/PluginManager"; import { Runtime } from "../config/runtime"; import { ApiCorsPolicy, ApiJwtValidatePolicy, ApiManagementConfig } from "../models/apiManagement"; import { ArmDeployment, ArmParameters, ArmParamType, ArmResourceTemplate, ArmTemplateProvisioningState } from "../models/armTemplates"; import { ServicePrincipalEnvVariables } from "../models/azureProvider"; import { Logger } from "../models/generic"; import { ServerlessAzureConfig, ServerlessAzureFunctionBindingConfig, ServerlessAzureFunctionConfig, ServerlessAzureProvider, ServerlessCliCommand } from "../models/serverless"; import { constants } from "../shared/constants"; function getAttribute(object: any, prop: string, defaultValue: any): any { if (object && object[prop]) { return object[prop]; } return defaultValue; } export class MockFactory { public static createTestServerless(config?: any): Serverless { const sls = new Serverless(config); sls.utils = getAttribute(config, "utils", MockFactory.createTestUtils()); sls.cli = getAttribute(config, "cli", MockFactory.createTestCli()); sls.pluginManager = getAttribute(config, "pluginManager", MockFactory.createTestPluginManager()); sls.variables = getAttribute(config, "variables", MockFactory.createTestVariables()); sls.service = getAttribute(config, "service", MockFactory.createTestService()); sls.config.servicePath = ""; sls.setProvider = jest.fn(); sls["processedInput"] = { commands: [ServerlessCliCommand.DEPLOY], options: {} }; return sls; } public static createTestService(functions?): Service { if (!functions) { functions = MockFactory.createTestSlsFunctionConfig() } const serviceName = "serviceName"; return { getAllFunctions: jest.fn(() => Object.keys(functions)), getFunction: jest.fn((name: string) => functions[name]), getAllEventsInFunction: jest.fn(), getAllFunctionsNames: jest.fn(() => Object.keys(functions)), getEventInFunction: jest.fn(), getServiceName: jest.fn(() => serviceName), load: jest.fn(), mergeResourceArrays: jest.fn(), setFunctionNames: jest.fn(), update: jest.fn(), validate: jest.fn(), custom: null, provider: MockFactory.createTestAzureServiceProvider(), service: serviceName, artifact: "app.zip", functions, package: { exclude: [], include: [], } } as any as Service; } public static updateService(serverless: Serverless, functions) { Object.assign(serverless.service, { ...serverless.service, getAllFunctions: jest.fn(() => Object.keys(functions)), getFunction: jest.fn((name: string) => functions[name]), getAllFunctionsNames: jest.fn(() => Object.keys(functions)), functions }); } public static createTestServerlessOptions(options?: any): Serverless.Options { return { extraServicePath: null, function: null, noDeploy: null, region: null, stage: null, watch: null, ...options }; } public static createTestArmSdkResponse<R>(model: any, statusCode: number): Promise<R> { const response: HttpResponse = { headers: new HttpHeaders(), request: null, status: statusCode, }; const result: R = { ...model, _response: response, }; return Promise.resolve(result); } public static createTestAuthResponse(): AuthResponse { return { credentials: MockFactory.createTestVariables() .azureCredentials as any as TokenCredentialsBase, subscriptions: [ { id: "AZURE_SUBSCRIPTION_ID", }, ] as any as LinkedSubscription[], }; } public static createTestFunctions(functionCount = 3) { const functions = [] for (let i = 0; i < functionCount; i++) { functions.push(MockFactory.createTestFunction(`function${i + 1}`)); } return functions; } public static createTestFunction(name: string = "TestFunction") { return { properties: { name, config: { bindings: MockFactory.createTestBindings() } } } } public static createTestAzureCredentials(): TokenClientCredentials { const credentials = { getToken: jest.fn(() => { const token: TokenResponse = this.createTestTokenCacheEntries()[0]; return Promise.resolve(token); }), signRequest: jest.fn((resource) => Promise.resolve(resource)), }; return credentials; } public static createTestTokenCacheEntries(count: number = 1): TokenResponse[] { const token: TokenResponse = { tokenType: "Bearer", accessToken: "ABC123", userId: "example@user.com", }; const result = Array(count).fill(token); return result; } public static createTestSubscriptions(count: number = 1): any[] { const sub = { id: "abc-1234-5678", state: "Enabled", authorizationSource: "RoleBased", user: { name: "example@user.com", type: "user" }, environmentName: "AzureCloud", name: "Test Sub" }; const result = Array(count).fill(sub); return result; } public static createTestTimestamp(): string { return "1562184492"; } public static createTestDeployments(count: number = 5, includeTimestamp = false): DeploymentsListByResourceGroupResponse { const result = []; const originalTimestamp = +MockFactory.createTestTimestamp(); for (let i = 0; i < count; i++) { const name = (includeTimestamp) ? `${constants.naming.suffix.deployment}${i + 1}-t${originalTimestamp + i}` : `deployment${i + 1}`; result.push( MockFactory.createTestDeployment(name, i) ) } return result as DeploymentsListByResourceGroupResponse } public static createTestParameters(): ArmParameters { return { param1: { value: "1", type: ArmParamType.String }, param2: { value: "2", type: ArmParamType.String }, } } public static createTestDeployment(name?: string, second: number = 0): DeploymentExtended { return { name: name || `${constants.naming.suffix.deployment}1-t${MockFactory.createTestTimestamp()}`, properties: { timestamp: new Date(2019, 1, 1, 0, 0, second), parameters: MockFactory.createTestParameters(), provisioningState: ArmTemplateProvisioningState.SUCCEEDED } } } public static createTestAxiosResponse<T>( config: AxiosRequestConfig, responseJson: T, statusCode: number = 200, ): Promise<AxiosResponse> { let statusText; switch (statusCode) { case 200: statusText = "OK"; break; case 404: statusText = "NotFound"; break; } const response: AxiosResponse = { config, data: JSON.stringify(responseJson), headers: { "Content-Type": "application/json; charset=utf-8", }, status: statusCode, statusText, }; return Promise.resolve(response); } public static createTestAzureContainers(count: number = 5): ServiceListContainersSegmentResponse { const result = []; for (let i = 0; i < count; i++) { result.push({ name: `container${i}`, blobs: MockFactory.createTestAzureBlobItems(i), }); } return { containerItems: result } as ServiceListContainersSegmentResponse; } public static createTestBlockBlobUrl(containerName: string, blobName: string, contents: string = "test") { return { containerName, blobName, url: `http://storage.azure.com/${containerName}/${blobName}`, delete: jest.fn(), getProperties: jest.fn(() => Promise.resolve({ contentLength: contents.length })) } } public static createTestAzureBlobItems(id: number = 1, count: number = 5) { const result = []; for (let i = 0; i < count; i++) { result.push(MockFactory.createTestAzureBlobItem(id, i)); } return { segment: { blobItems: result } }; } public static createTestAzureBlobItem(id: number = 1, index: number = 1, ext: string = ".zip") { return { name: `blob-${id}-${index}${ext}` } } public static createTestAzureClientResponse<T>(responseJson: T, statusCode: number = 200): Promise<HttpOperationResponse> { const response: HttpOperationResponse = { request: new WebResource(), parsedBody: responseJson, bodyAsText: JSON.stringify(responseJson), headers: new HttpHeaders(), status: statusCode, }; return Promise.resolve(response); } public static createTestServerlessYml(asYaml = false, functionMetadata?): ServerlessAzureConfig { const data = { provider: { name: "azure", region: "West US 2" }, plugins: [ "serverless-azure-functions" ], functions: functionMetadata || MockFactory.createTestSlsFunctionConfig(), } return (asYaml) ? yaml.dump(data) : data; } public static createTestApimConfig(generateName: boolean = false): ApiManagementConfig { return { name: generateName ? null : "test-apim-resource", apis: [{ name: "test-apim-api1", subscriptionRequired: false, displayName: "API 1", description: "description of api 1", protocols: ["https"], path: "test-api1", }], backends: [], }; } public static createTestFunctionApimConfig(name: string) { return { apim: { operations: [ { method: "get", urlTemplate: name, displayName: name, }, ], }, }; } public static createTestKeyVaultConfig(name: string = "testVault") { return { name: name, resourceGroup: "testGroup", }; } public static createTestFunctionMetadata(name: string): ServerlessAzureFunctionConfig { return { "handler": `${name}.handler`, "events": MockFactory.createTestFunctionEvents(), } } public static createTestFunctionEvents(): ServerlessAzureFunctionBindingConfig[] { return [ { "http": true, "authLevel": "anonymous" }, { "http": true, "direction": "out", "name": "res" } ] } public static createTestFunctionMetadataWithXAzureSettings(name: string): ServerlessAzureFunctionConfig { return { "handler": `${name}.handler`, "events": MockFactory.createTestFunctionEventsWithXAzureSettings(), } } public static createTestFunctionEventsWithXAzureSettings(): ServerlessAzureFunctionBindingConfig[] { return [ { "http": true, "x-azure-settings": { "authLevel": "anonymous" } }, { "http": true, "x-azure-settings": { "direction": "out", "name": "res" } } ] } public static createTestFunctionsResponse(functions?) { const result = [] functions = functions || MockFactory.createTestSlsFunctionConfig(); for (const name of Object.keys(functions)) { result.push({ properties: MockFactory.createTestFunctionEnvelope(name) }); } return result; } public static createTestAzureServiceProvider(): ServerlessAzureProvider { return { name: "azure", prefix: "sls", resourceGroup: "myResourceGroup", deploymentName: "myDeploymentName", region: "eastus2", stage: "dev", runtime: Runtime.NODE10, } } public static createTestServicePrincipalEnvVariables(): ServicePrincipalEnvVariables { return { AZURE_SUBSCRIPTION_ID: "AZURE_SUBSCRIPTION_ID", AZURE_CLIENT_ID: "AZURE_CLIENT_ID", AZURE_CLIENT_SECRET: "AZURE_CLIENT_SECRET", AZURE_TENANT_ID: "AZURE_TENANT_ID", } } public static createTestVariables() { return { azureCredentials: this.createTestAzureCredentials(), subscriptionId: "AZURE_SUBSCRIPTION_ID", } } public static createTestSite(name: string = "Test"): Site { return { id: "appId", name: name, location: "West US", defaultHostName: "myHostName.azurewebsites.net", enabledHostNames: [ "myHostName.azurewebsites.net", "myHostName.scm.azurewebsites.net", ] }; } public static createTestFunctionEnvelope(name: string = "TestFunction"): FunctionEnvelope { return { name, config: { bindings: MockFactory.createTestBindings() } } } public static createTestBindings(bindingCount = 3) { const bindings = []; for (let i = 0; i < bindingCount; i++) { bindings.push(MockFactory.createTestBinding()); } return bindings; } public static createTestAzureFunctionConfig(route?: string, excludeDirection?: boolean): ServerlessAzureFunctionConfig { return { events: [ { http: true, "x-azure-settings": MockFactory.createTestHttpBinding((excludeDirection) ? undefined : "in", route), }, { http: true, "x-azure-settings": MockFactory.createTestHttpBinding("out"), } ], handler: "handler.js", } } public static createTestAzureFunctionConfigWithoutXAzureSettings( route?: string, excludeDirection?: boolean): ServerlessAzureFunctionConfig { return { events: [ { http: true, ...MockFactory.createTestHttpBinding((excludeDirection) ? undefined : "in", route) }, { http: true, ...MockFactory.createTestHttpBinding("out"), } ], handler: "handler.js", } } public static createTestEventHubFunctionConfig(): ServerlessAzureFunctionConfig { return { events: [ { http: true, "x-azure-settings": MockFactory.createTestEventHubBinding("in"), } ], handler: "handler.js", } } public static createTestBinding() { // Only supporting HTTP for now, could support others return MockFactory.createTestHttpBinding(); } public static createTestHttpBinding(direction?: string, route?: string) { if (!direction || direction === "in") { return { authLevel: "anonymous", type: "httpTrigger", direction, name: "req", route, } } else { return { type: "http", direction, name: "res" } } } public static createTestEventHubBinding(direction: string = "in") { return { event: "eventHubTrigger", direction, name: "item", eventhubname: "hello", consumerGroup: "$Default", connection: "EventHubsConnection" } } public static createTestBindingsObject(name: string = "index.js") { return { scriptFile: name, entryPoint: "handler", disabled: false, bindings: [ MockFactory.createTestHttpBinding("in"), MockFactory.createTestHttpBinding("out") ] } } public static createTestSlsFunctionConfig() { return { hello: { ...MockFactory.createTestFunctionMetadata("hello"), ...MockFactory.createTestFunctionApimConfig("hello"), }, goodbye: { ...MockFactory.createTestFunctionMetadata("goodbye"), ...MockFactory.createTestFunctionApimConfig("goodbye"), }, }; } public static createTestApimService(): ApiManagementServiceResource { return { name: "APIM Service Instance", location: "West US", publisherName: "Somebody", publisherEmail: "somebody@example.com", sku: { capacity: 0, name: "Consumption", } }; } public static createTestApimApis(count: number): ApiContract[] { const apis: ApiContract[] = []; for (let i = 1; i <= count; i++) { const api = MockFactory.createTestApimApi(i); apis.push(api); } return apis; } public static createTestApimApi(index: number = 1): ApiContract { return { displayName: `API ${index}`, description: `Description for API ${index}`, name: `Api${index}`, path: `/api${index}`, }; } public static createTestApimBackends(count: number): BackendContract[] { const backends: BackendContract[] = []; for (let i = 1; i <= count; i++) { const backend = MockFactory.createTestApimBackend(i); backends.push(backend); } return backends; } public static createTestApimBackend(index: number = 1): BackendContract { return { name: `backend-${index}`, description: `Description for Backend ${index}`, title: `Backend ${index}`, url: `/backend${index}`, protocol: "http", }; } private static createTestUtils(): Utils { return { appendFileSync: jest.fn(), copyDirContentsSync: jest.fn(), dirExistsSync: jest.fn(() => false), fileExistsSync: jest.fn(() => false), findServicePath: jest.fn(), generateShortId: jest.fn(), getVersion: jest.fn(), logStat: jest.fn(), readFile: jest.fn(), readFileSync: jest.fn((filename) => { if (filename === "serverless.yml") { return MockFactory.createTestServerlessYml(); } }), walkDirSync: jest.fn(), writeFile: jest.fn(), writeFileDir: jest.fn(), writeFileSync: jest.fn(), }; } /** * Create a mock "request" module factory used to mock request objects that support piping * @param response The expected HTTP response */ public static createTestMockRequestFactory(response: any = {}) { return jest.fn((options, callback) => { setImmediate(() => callback(null, response)); // Required interface for .pipe() return { on: jest.fn(), once: jest.fn(), emit: jest.fn(), write: jest.fn(), end: jest.fn(), }; }); } public static createTestMockApiCorsPolicy(): ApiCorsPolicy { return { allowCredentials: false, allowedOrigins: ["*"], allowedHeaders: ["*"], exposeHeaders: ["*"], allowedMethods: ["GET", "POST"], }; } public static createTestMockApiJwtPolicy(): ApiJwtValidatePolicy { return { headerName: "authorization", scheme: "bearer", audiences: ["audience1"], issuers: ["issuer1"], failedStatusCode: 401, failedErrorMessage: "Authorization required!" }; } public static createTestArmDeployment(): ArmDeployment { return { template: MockFactory.createTestArmTemplate(), parameters: MockFactory.createTestParameters(), } } public static createTestArmTemplate(): ArmResourceTemplate { return { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "param1": { "defaultValue": "", "type": "String" }, "param2": { "defaultValue": "", "type": "String" }, }, "variables": {}, "resources": [] }; } private static createTestCli(): Logger { return { log: jest.fn(), }; } private static createTestPluginManager(): PluginManager { return { addPlugin: jest.fn(), cliCommands: null, cliOptions: null, commands: null, deprecatedEvents: null, hooks: {}, loadAllPlugins: jest.fn(), loadCommand: jest.fn(), loadCommands: jest.fn(), loadCorePlugins: jest.fn(), loadPlugins: jest.fn(), loadServicePlugins: jest.fn(), plugins: null, serverless: null, setCliCommands: jest.fn(), setCliOptions: jest.fn(), spawn: jest.fn(), }; } }
the_stack
import { timeParse as d3TimeParse, timeFormat as d3TimeFormat, utcParse as d3UtcParse, utcFormat as d3UtcFormat } from "d3-time-format"; import {select as d3Select} from "d3-selection"; import {d3Selection} from "../../types/types"; import {checkModuleImport} from "../module/error"; import CLASS from "../config/classes"; import Store from "../config/Store/Store"; import Options from "../config/Options/Options"; import {document, window} from "../module/browser"; import Cache from "../module/Cache"; import {generateResize} from "../module/generator"; import {capitalize, extend, notEmpty, convertInputType, getOption, isFunction, isObject, isString, callFn, sortValue} from "../module/util"; // data import dataConvert from "./data/convert"; import data from "./data/data"; import dataLoad from "./data/load"; // interactions import interaction from "./interactions/interaction"; // internals import classModule from "./internals/class"; import category from "./internals/category"; // used to retrieve radar Axis name import color from "./internals/color"; import domain from "./internals/domain"; import format from "./internals/format"; import legend from "./internals/legend"; import redraw from "./internals/redraw"; import scale from "./internals/scale"; import shape from "./shape/shape"; import size from "./internals/size"; import text from "./internals/text"; import title from "./internals/title"; import tooltip from "./internals/tooltip"; import transform from "./internals/transform"; import type from "./internals/type"; /** * Internal chart class. * - Note: Instantiated internally, not exposed for public. * @class ChartInternal * @ignore * @private */ export default class ChartInternal { public api; // API interface public config; // config object public cache; // cache instance public $el; // elements public state; // state variables public charts; // all Chart instances array within page (equivalent of 'bb.instances') // data object public data = { xs: {}, targets: [] }; // Axis public axis; // Axis // scales public scale = { x: null, y: null, y2: null, subX: null, subY: null, subY2: null, zoom: null }; // original values public org = { xScale: null, xDomain: null }; // formatter function public color; public patterns; public levelColor; public point; public brush; // format function public format = { extraLineClasses: null, xAxisTick: null, dataTime: null, // dataTimeFormat defaultAxisTime: null, // defaultAxisTimeFormat axisTime: null // axisTimeFormat }; constructor(api) { const $$ = this; $$.api = api; // Chart class instance alias $$.config = new Options(); $$.cache = new Cache(); const store = new Store(); $$.$el = store.getStore("element"); $$.state = store.getStore("state"); $$.$T = $$.$T.bind($$); } /** * Get the selection based on transition config * @param {SVGElement|d3Selection} selection Target selection * @param {boolean} force Force transition * @param {string} name Transition name * @returns {d3Selection} * @private */ $T(selection: SVGElement | d3Selection, force?: boolean, name?: string): d3Selection { const {config, state} = this; const duration = config.transition_duration; const subchart = config.subchart_show; let t = selection; if (t) { // in case of non d3 selection, wrap with d3 selection if ("tagName" in t) { t = d3Select(t); } // do not transit on: // - wheel zoom (state.zooming = true) // - when has no subchart // - initialization // - resizing const transit = ((force !== false && duration) || force) && (!state.zooming || state.dragging) && !state.resizing && state.rendered && !subchart; t = (transit ? t.transition(name).duration(duration) : t) as d3Selection; } return t; } beforeInit(): void { const $$ = this; $$.callPluginHook("$beforeInit"); // can do something callFn($$.config.onbeforeinit, $$.api); } afterInit(): void { const $$ = this; $$.callPluginHook("$afterInit"); // can do something callFn($$.config.onafterinit, $$.api); } init(): void { const $$ = <any> this; const {config, state, $el} = $$; checkModuleImport($$); state.hasAxis = !$$.hasArcType(); state.hasRadar = !state.hasAxis && $$.hasType("radar"); $$.initParams(); const bindto = { element: config.bindto, classname: "bb" }; if (isObject(config.bindto)) { bindto.element = config.bindto.element || "#chart"; bindto.classname = config.bindto.classname || bindto.classname; } // select bind element $el.chart = isFunction(bindto.element.node) ? config.bindto.element : d3Select(bindto.element || []); if ($el.chart.empty()) { $el.chart = d3Select(document.body.appendChild(document.createElement("div"))); } $el.chart.html("").classed(bindto.classname, true); $$.initToRender(); } /** * Initialize the rendering process * @param {boolean} forced Force to render process * @private */ initToRender(forced?: boolean): void { const $$ = <any> this; const {config, state, $el: {chart}} = $$; const isHidden = () => chart.style("display") === "none" || chart.style("visibility") === "hidden"; const isLazy = config.render.lazy || isHidden(); const MutationObserver = window.MutationObserver; if (isLazy && MutationObserver && config.render.observe !== false && !forced) { new MutationObserver((mutation, observer) => { if (!isHidden()) { observer.disconnect(); !state.rendered && $$.initToRender(true); } }).observe(chart.node(), { attributes: true, attributeFilter: ["class", "style"] }); } if (!isLazy || forced) { const convertedData = $$.convertData(config, $$.initWithData); convertedData && $$.initWithData(convertedData); $$.afterInit(); } } initParams(): void { const $$ = <any> this; const {config, format, state} = <any> $$; const isRotated = config.axis_rotated; // datetime to be used for uniqueness state.datetimeId = `bb-${+new Date()}`; $$.color = $$.generateColor(); $$.levelColor = $$.generateLevelColor(); if ($$.hasPointType()) { $$.point = $$.generatePoint(); } if (state.hasAxis) { $$.initClip(); format.extraLineClasses = $$.generateExtraLineClass(); format.dataTime = config.data_xLocaltime ? d3TimeParse : d3UtcParse; format.axisTime = config.axis_x_localtime ? d3TimeFormat : d3UtcFormat; const isDragZoom = $$.config.zoom_enabled && $$.config.zoom_type === "drag"; format.defaultAxisTime = d => { const {x, zoom} = $$.scale; const isZoomed = isDragZoom ? zoom : zoom && x.orgDomain().toString() !== zoom.domain().toString(); const specifier: string = (d.getMilliseconds() && ".%L") || (d.getSeconds() && ".:%S") || (d.getMinutes() && "%I:%M") || (d.getHours() && "%I %p") || (d.getDate() !== 1 && "%b %d") || (isZoomed && d.getDate() === 1 && "%b\'%y") || (d.getMonth() && "%-m/%-d") || "%Y"; return format.axisTime(specifier)(d); }; } state.isLegendRight = config.legend_position === "right"; state.isLegendInset = config.legend_position === "inset"; state.isLegendTop = config.legend_inset_anchor === "top-left" || config.legend_inset_anchor === "top-right"; state.isLegendLeft = config.legend_inset_anchor === "top-left" || config.legend_inset_anchor === "bottom-left"; state.rotatedPaddingRight = isRotated && !config.axis_x_show ? 0 : 30; state.inputType = convertInputType( config.interaction_inputType_mouse, config.interaction_inputType_touch ); } initWithData(data): void { const $$ = <any> this; const {config, scale, state, $el, org} = $$; const {hasAxis} = state; const hasInteraction = config.interaction_enabled; // for arc type, set axes to not be shown // $$.hasArcType() && ["x", "y", "y2"].forEach(id => (config[`axis_${id}_show`] = false)); if (hasAxis) { $$.axis = $$.getAxisInstance(); config.zoom_enabled && $$.initZoom(); } // Init data as targets $$.data.xs = {}; $$.data.targets = $$.convertDataToTargets(data); if (config.data_filter) { $$.data.targets = $$.data.targets.filter(config.data_filter.bind($$.api)); } // Set targets to hide if needed if (config.data_hide) { $$.addHiddenTargetIds( config.data_hide === true ? $$.mapToIds($$.data.targets) : config.data_hide ); } if (config.legend_hide) { $$.addHiddenLegendIds( config.legend_hide === true ? $$.mapToIds($$.data.targets) : config.legend_hide ); } // Init sizes and scales $$.updateSizes(); $$.updateScales(true); // retrieve scale after the 'updateScales()' is called const {x, y, y2, subX, subY, subY2} = scale; // Set domains for each scale if (x) { x.domain(sortValue($$.getXDomain($$.data.targets))); subX.domain(x.domain()); // Save original x domain for zoom update org.xDomain = x.domain(); } if (y) { y.domain($$.getYDomain($$.data.targets, "y")); subY.domain(y.domain()); } if (y2) { y2.domain($$.getYDomain($$.data.targets, "y2")); subY2 && subY2.domain(y2.domain()); } // -- Basic Elements -- $el.svg = $el.chart.append("svg") .style("overflow", "hidden") .style("display", "block"); if (hasInteraction && state.inputType) { const isTouch = state.inputType === "touch"; $el.svg.on(isTouch ? "touchstart" : "mouseenter", () => callFn(config.onover, $$.api)) .on(isTouch ? "touchend" : "mouseleave", () => callFn(config.onout, $$.api)); } config.svg_classname && $el.svg.attr("class", config.svg_classname); // Define defs const hasColorPatterns = (isFunction(config.color_tiles) && $$.patterns); if (hasAxis || hasColorPatterns || config.data_labels_backgroundColors) { $el.defs = $el.svg.append("defs"); if (hasAxis) { ["id", "idXAxis", "idYAxis", "idGrid"].forEach(v => { $$.appendClip($el.defs, state.clip[v]); }); } // Append data backgound color filter definition $$.generateDataLabelBackgroundColorFilter(); // set color patterns if (hasColorPatterns) { $$.patterns.forEach(p => $el.defs.append(() => p.node)); } } $$.updateSvgSize(); // Bind resize event $$.bindResize(); // Define regions const main = $el.svg.append("g") .classed(CLASS.main, true) .attr("transform", $$.getTranslate("main")); $el.main = main; // initialize subchart when subchart show option is set config.subchart_show && $$.initSubchart(); config.tooltip_show && $$.initTooltip(); config.title_text && $$.initTitle(); config.legend_show && $$.initLegend(); // -- Main Region -- // text when empty if (config.data_empty_label_text) { main.append("text") .attr("class", `${CLASS.text} ${CLASS.empty}`) .attr("text-anchor", "middle") // horizontal centering of text at x position in all browsers. .attr("dominant-baseline", "middle"); // vertical centering of text at y position in all browsers, except IE. } if (hasAxis) { // Regions config.regions.length && $$.initRegion(); // Add Axis here, when clipPath is 'false' !config.clipPath && $$.axis.init(); } // Define g for chart area main.append("g").attr("class", CLASS.chart) .attr("clip-path", state.clip.path); $$.callPluginHook("$init"); if (hasAxis) { // Cover whole with rects for events hasInteraction && $$.initEventRect?.(); // Grids $$.initGrid(); // Add Axis here, when clipPath is 'true' config.clipPath && $$.axis?.init(); } $$.initChartElements(); // Set targets $$.updateTargets($$.data.targets); // Draw with targets $$.updateDimension(); // oninit callback callFn(config.oninit, $$.api); // Set background $$.setBackground(); $$.redraw({ withTransition: false, withTransform: true, withUpdateXDomain: true, withUpdateOrgXDomain: true, withTransitionForAxis: false, initializing: true }); // data.onmin/max callback if (config.data_onmin || config.data_onmax) { const minMax = $$.getMinMaxData(); callFn(config.data_onmin, $$.api, minMax.min); callFn(config.data_onmax, $$.api, minMax.max); } config.tooltip_show && $$.initShowTooltip(); state.rendered = true; } /** * Initialize chart elements * @private */ initChartElements(): void { const $$ = <any> this; const {hasAxis, hasRadar} = $$.state; const types: string[] = []; if (hasAxis) { ["bar", "bubble", "candlestick", "line"].forEach(v => { const name = capitalize(v); if ((v === "line" && $$.hasTypeOf(name)) || $$.hasType(v)) { types.push(name); } }); } else { if (!hasRadar) { types.push("Arc", "Pie"); } if ($$.hasType("gauge")) { types.push("Gauge"); } else if (hasRadar) { types.push("Radar"); } } types.forEach(v => { $$[`init${v}`](); }); notEmpty($$.config.data_labels) && !$$.hasArcType(null, ["radar"]) && $$.initText(); } /** * Set chart elements * @private */ setChartElements(): void { const $$ = this; const {$el: { chart, svg, defs, main, tooltip, legend, title, grid, arcs: arc, circle: circles, bar: bars, candlestick, line: lines, area: areas, text: texts }} = $$; $$.api.$ = { chart, svg, defs, main, tooltip, legend, title, grid, arc, circles, bar: {bars}, candlestick, line: {lines, areas}, text: {texts} }; } /** * Set background element/image * @private */ setBackground(): void { const $$ = this; const {config: {background: bg}, state, $el: {svg}} = $$; if (notEmpty(bg)) { const element = svg.select("g") .insert(bg.imgUrl ? "image" : "rect", ":first-child"); if (bg.imgUrl) { element.attr("href", bg.imgUrl); } else if (bg.color) { element .style("fill", bg.color) .attr("clip-path", state.clip.path); } element .attr("class", bg.class || null) .attr("width", "100%") .attr("height", "100%"); } } /** * Update targeted element with given data * @param {object} targets Data object formatted as 'target' * @private */ updateTargets(targets): void { const $$ = <any> this; const {hasAxis, hasRadar} = $$.state; // Text $$.updateTargetsForText(targets); if (hasAxis) { ["bar", "candlestick", "line"].forEach(v => { const name = capitalize(v); if ((v === "line" && $$.hasTypeOf(name)) || $$.hasType(v)) { $$[`updateTargetsFor${name}`]( targets.filter($$[`is${name}Type`].bind($$)) ); } }); // Sub Chart $$.updateTargetsForSubchart && $$.updateTargetsForSubchart(targets); } else { // Arc & Radar $$.hasArcType(targets) && ( hasRadar ? $$.updateTargetsForRadar(targets.filter($$.isRadarType.bind($$))) : $$.updateTargetsForArc(targets.filter($$.isArcType.bind($$))) ); } // circle if ($$.hasType("bubble") || $$.hasType("scatter")) { $$.updateTargetForCircle?.(); } // Fade-in each chart $$.showTargets(); } /** * Display targeted elements * @private */ showTargets(): void { const $$ = <any> this; const {$el: {svg}, $T} = $$; $T(svg.selectAll(`.${CLASS.target}`) .filter(d => $$.isTargetToShow(d.id)) ).style("opacity", null); } getWithOption(options) { const withOptions = { Dimension: true, EventRect: true, Legend: false, Subchart: true, Transform: false, Transition: true, TrimXDomain: true, UpdateXAxis: "UpdateXDomain", UpdateXDomain: false, UpdateOrgXDomain: false, TransitionForExit: "Transition", TransitionForAxis: "Transition", Y: true }; Object.keys(withOptions).forEach(key => { let defVal = withOptions[key]; if (isString(defVal)) { defVal = withOptions[defVal]; } withOptions[key] = getOption(options, `with${key}`, defVal); }); return withOptions; } initialOpacity(d): null | "0" { const $$ = <any> this; const {withoutFadeIn} = $$.state; return $$.getBaseValue(d) !== null && withoutFadeIn[d.id] ? null : "0"; } bindResize(): void { const $$ = <any> this; const {config, state} = $$; const resizeFunction = generateResize(); const list: Function[] = []; list.push(() => callFn(config.onresize, $$, $$.api)); if (config.resize_auto) { list.push(() => { state.resizing = true; $$.api.flush(false); }); } list.push(() => { callFn(config.onresized, $$, $$.api); state.resizing = false; }); // add resize functions list.forEach(v => resizeFunction.add(v)); $$.resizeFunction = resizeFunction; // attach resize event window.addEventListener("resize", $$.resizeFunction = resizeFunction); } /** * Call plugin hook * @param {string} phase The lifecycle phase * @param {Array} args Arguments * @private */ callPluginHook(phase, ...args): void { this.config.plugins.forEach(v => { if (phase === "$beforeInit") { v.$$ = this; this.api.plugins.push(v); } v[phase](...args); }); } } extend(ChartInternal.prototype, [ // common dataConvert, data, dataLoad, category, classModule, color, domain, interaction, format, legend, redraw, scale, shape, size, text, title, tooltip, transform, type ]);
the_stack
import React, { ChangeEvent } from "react"; import _ from 'lodash' import { withStyles, WithStyles, MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles' import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import {ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails, Typography, List, ListItem, ListItemText, InputBase, Input, Paper, FormGroup, FormControlLabel, Checkbox, Button} from '@material-ui/core'; import Context from "../context/contextStore"; import {ActionLoader} from './actionLoader' import {ActionGroupSpecs, ActionSpec, BoundAction, ActionGroupSpec, ActionContextType, ActionOutputCollector, ActionStreamOutputCollector, ActionChoiceMaker, ActionOnInfo} from './actionSpec' import styles from './actions.styles' import {actionsTheme} from '../theme/theme' import FilterUtil, {filter} from '../util/filterUtil' interface IState { actionGroupSpecs: ActionGroupSpecs filteredActions: ActionSpec[], autoRefresh: boolean invalidAutoRefreshDelay: boolean } interface IProps extends WithStyles<typeof styles> { showLoading: (string) => void onOutput: ActionOutputCollector onStreamOutput: ActionStreamOutputCollector onActionInitChoices: ActionChoiceMaker onActionChoices: ActionChoiceMaker onCancelActionChoice: () => void onShowInfo: ActionOnInfo onSetColumnWidths: (...widths) => void onSetScrollMode: (boolean) => void onAction: (BoundAction) => void onOutputLoading: (boolean) => void } export class Actions extends React.Component<IProps, IState> { state: IState = { actionGroupSpecs: [], filteredActions: [], autoRefresh: false, invalidAutoRefreshDelay: false, } currentAction?: BoundAction refreshTimer: any refreshChangeTimer: any lastRefreshed: any filterText: string = '' clickAllowed: boolean = true componentDidMount() { this.componentWillReceiveProps(this.props) this.loadActionPlugins() } componentWillReceiveProps(props: IProps) { ActionLoader.setOnOutput(props.onOutput, props.onStreamOutput) ActionLoader.setOnActionChoices(props.onActionInitChoices, props.onActionChoices, props.onCancelActionChoice) ActionLoader.setOnShowInfo(props.onShowInfo) ActionLoader.setOnSetColumnWidths(props.onSetColumnWidths) ActionLoader.setOnOutputLoading(props.onOutputLoading) } loadActionPlugins() { ActionLoader.setOnLoad(actionGroupSpecs => this.setState({actionGroupSpecs})) ActionLoader.loadActionPlugins() } runAction(name, ...params) { const {actionGroupSpecs} = this.state const action = _.flatten(actionGroupSpecs.map(spec => spec.actions)) .filter(action => action.name === name)[0] action && this.onRunAction(action, true, ...params) } onRunAction = (action: BoundAction, direct: boolean, ...params) => { if(!this.clickAllowed) return this.throttleClick() this.props.onAction(action) const prevAction = this.currentAction prevAction && prevAction.stop && prevAction.stop() ActionLoader.actionContext.inputText = undefined this.currentAction = action this.lastRefreshed = undefined if(direct && action.directAct) { action.directAct(params) this.setAutoRefresh(false) } else if(action.act) { action.loadingMessage && this.props.showLoading(action.loadingMessage) action.chooseAndAct() this.setAutoRefresh(false) } } onAction = (action: BoundAction) => { this.onRunAction(action, false) } throttleClick() { this.clickAllowed = false setTimeout(() => this.clickAllowed = true, 1000) } cancelRefreshTimers() { if(this.refreshTimer) { clearInterval(this.refreshTimer) this.refreshTimer = undefined } if(this.refreshChangeTimer) { clearTimeout(this.refreshChangeTimer) this.refreshChangeTimer = undefined } } setAutoRefresh(autoRefresh: boolean) { this.cancelRefreshTimers() if(autoRefresh && this.currentAction && this.currentAction.refresh) { this.refreshTimer = setInterval(() => { this.lastRefreshed = new Date() this.currentAction && this.currentAction.refresh && this.currentAction.refresh() }, this.currentAction.autoRefreshDelay ? this.currentAction.autoRefreshDelay * 1000 : 15000) } this.setState({autoRefresh}) } onAutoRefresh = (event) => { this.setAutoRefresh(event.target.checked) } onAutoRefreshChange = (event) => { this.cancelRefreshTimers() if(this.currentAction && this.currentAction.autoRefreshDelay) { const prev = this.currentAction.autoRefreshDelay try { let newVal = Number.parseInt(event.target.value) if(newVal >= 5) { this.setState({invalidAutoRefreshDelay: false}) this.currentAction.autoRefreshDelay = newVal if(this.state.autoRefresh) { this.refreshChangeTimer = setTimeout(this.setAutoRefresh.bind(this, this.state.autoRefresh), 500) } } else { this.setState({invalidAutoRefreshDelay: true}) } } catch(error) { this.setState({invalidAutoRefreshDelay: true}) this.currentAction.autoRefreshDelay = prev } } } onReRun = () => { if(this.currentAction) { if(this.currentAction.canReact) { this.currentAction.react && this.currentAction.react() } else if(this.currentAction.refresh) { this.currentAction.refresh() } else { this.currentAction.chooseAndAct() } } } onClearOutput = () => { this.currentAction && this.currentAction.clear && this.currentAction.clear() } onStopAction = () => { this.currentAction && this.currentAction.stop && this.currentAction.stop() } onFilterChange = (event: ChangeEvent<HTMLInputElement>) => { const {actionGroupSpecs} = this.state let text = event.target.value if(text && text.length > 0) { this.filterText = text if(text.length > 1) { const actions = _.flatten(actionGroupSpecs.map(group => group.actions)) const filteredActions = FilterUtil.filter(text, actions, "name") this.setState({filteredActions}) } } else { this.clearFilter() } this.forceUpdate() } clearFilter() { this.filterText = '' this.setState({filteredActions: []}) } onKeyDown = (event) => { if(event.which === 27 /*Esc*/) { this.clearFilter() } } renderExpansionPanel(title: string, actions: ActionSpec[], expanded: boolean = false) { const { classes } = this.props; return ( <ExpansionPanel key={title} className={classes.expansion} defaultExpanded={expanded}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />} className={classes.expansionHead}> <Typography>{title}</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails className={classes.expansionDetails}> <List component="nav"> {actions.map(action => <ListItem key={action.name} button disableGutters className={this.currentAction && action.name === this.currentAction.name && action.context === this.currentAction.context ? classes.selectedMenuItem : classes.menuItem}> <ListItemText className={classes.listText} onClick={this.onAction.bind(this, action as BoundAction)}> <Typography>{action.name}</Typography> </ListItemText> </ListItem> )} </List> </ExpansionPanelDetails> </ExpansionPanel> ) } render() { const { classes } = this.props; const {actionGroupSpecs, invalidAutoRefreshDelay, filteredActions} = this.state const useDarkTheme = global['useDarkTheme'] const theme = createMuiTheme(actionsTheme.getTheme(useDarkTheme)); const actionShowNoShow : Map<ActionContextType, boolean> = new Map actionShowNoShow.set(ActionContextType.Cluster, Context.hasClusters) actionShowNoShow.set(ActionContextType.Namespace, Context.hasClusters) actionShowNoShow.set(ActionContextType.Istio, Context.hasIstio) actionShowNoShow.set(ActionContextType.Other, true) return ( <MuiThemeProvider theme={theme}> {Context.hasClusters && <Paper className={classes.filterContainer}> <Input fullWidth autoFocus placeholder="Type here to find Recipes" value={this.filterText} onChange={this.onFilterChange} onKeyDown={this.onKeyDown} className={classes.filterInput} /> </Paper> } <div className={classes.root}> {filteredActions.length > 0 && this.renderExpansionPanel("Matching Recipes", filteredActions, true) } {actionGroupSpecs.map(actionGroupSpec => actionShowNoShow.get(actionGroupSpec.context || ActionContextType.Other) && this.renderExpansionPanel(actionGroupSpec.title||"", actionGroupSpec.actions) )} {this.currentAction && this.currentAction.refresh && <div> <FormGroup row> <FormControlLabel control={ <Checkbox checked={this.state.autoRefresh} onChange={this.onAutoRefresh} /> } label={"Auto Refresh: "} /> <InputBase defaultValue={this.currentAction.autoRefreshDelay} inputProps={{size: 2, maxLength: 2,}} classes={{ root: classes.refreshRoot, input: classes.refreshInput + " " + (invalidAutoRefreshDelay ? classes.invalidRefreshInput: "") }} onChange={this.onAutoRefreshChange} /> </FormGroup> <Typography style={{paddingTop: 0, paddingLeft: 35}}> Last Refreshed: {this.lastRefreshed ? this.lastRefreshed.toISOString() : 'None'} </Typography> </div> } {this.currentAction && this.currentAction.clear && <Button color="primary" variant="contained" size="small" className={classes.actionButton} onClick={this.onClearOutput} > Clear </Button> } {this.currentAction && this.currentAction.stop && <Button color="primary" variant="contained" size="small" className={classes.actionButton} onClick={this.onStopAction} > Stop </Button> } {this.currentAction && (this.currentAction.canReact || this.currentAction.refresh) && <Button color="primary" variant="contained" size="small" className={classes.actionButton} onClick={this.onReRun} > ReRun </Button> } </div> </MuiThemeProvider> ) } } export default withStyles(styles)(Actions)
the_stack
import { basename, normalize, strings } from '@angular-devkit/core'; import { Logger } from '@angular-devkit/core/src/logger'; import { apply, applyTemplates, mergeWith, move, Rule, schematic, SchematicContext, Source, source, Tree, url } from '@angular-devkit/schematics'; import { cosmiconfigSync } from 'cosmiconfig'; import { EOL } from 'os'; import { resolve } from 'path'; import { Change, InsertChange, RemoveChange } from '../../lib/utility/change'; import { getSpecFilePathName } from '../common/get-spec-file-name'; import { paths } from '../common/paths'; import { describeSource } from '../common/read/read'; import { updateCustomTemplateCut } from '../common/scuri-custom-update-template'; import { ClassDescription, FunctionDescription, isClassDescription, ClassTemplateData } from '../types'; import { addMissing, update as doUpdate } from './update/update'; class SpecOptions { name: string; update?: boolean; classTemplate?: string; functionTemplate?: string; config?: string; } type Config = Omit<SpecOptions, 'name' | 'update' | 'config'>; export function spec({ name, update, classTemplate, functionTemplate, config }: SpecOptions): Rule { return (tree: Tree, context: SchematicContext) => { const logger = context.logger.createChild('scuri.index'); logger.debug(`Params: name: ${name} update: ${update} classTemplate: ${classTemplate} config: ${config}`); let c: Config = {}; try { const res = config ? cosmiconfigSync('scuri').load(config) : cosmiconfigSync('scuri').search(); c = res?.config ?? {}; } catch (e) { // the config file is apparently missing/malformed (as per https://www.npmjs.com/package/cosmiconfig#explorersearch) logger.debug(e?.stack) throw new Error(`Looks like the configuration was missing/malformed. ${e?.message}`); } classTemplate = classTemplate ?? c.classTemplate; if (typeof classTemplate === 'string' && !tree.exists(classTemplate)) { throw new Error(`Class template configuration was [${resolve(classTemplate)}] but that file seems to be missing.`); } functionTemplate = functionTemplate ?? c.functionTemplate; if (typeof functionTemplate === 'string' && !tree.exists(functionTemplate)) { throw new Error(`Function template configuration was [${resolve(functionTemplate)}] but that file seems to be missing.`); } try { if (update) { if (classTemplate) { return schematic('update-custom', { name, classTemplate }); } return updateExistingSpec(name, tree, logger); } else { return createNewSpec(name, tree, logger, { classTemplate, functionTemplate }); } } catch (e) { e = e || {}; logger.error(e.message || 'An error occurred'); logger.debug( `---Error--- ${EOL}${e.message || 'Empty error message'} ${e.stack || 'Empty stack.' }` ); } }; } function sliceSpecFromFileName(path: string) { if (path.includes('.spec')) { return path.replace('.spec', ''); } else { return path; } } function updateExistingSpec(fullName: string, tree: Tree, logger: Logger) { const specFileName = sliceSpecFromFileName(fullName); const content = tree.read(specFileName); if (content == null) { logger.error(`The file ${specFileName} is missing or empty.`); } else { // the new spec full file name contents - null if file not exist const existingSpecFile = tree.get(getSpecFilePathName(specFileName)); if (existingSpecFile == null) { logger.error( `Can not update spec (for ${specFileName}) since it does not exist. Try running without the --update flag.` ); } else { const specFilePath = existingSpecFile.path; // if a spec exists we'll try to update it const { params, name, publicMethods } = getFirstClass(specFileName, content); const shorthand = typeShorthand(name); logger.debug(`Class name ${name} ${EOL}Constructor(${params}) {${publicMethods}}`); // start by adding missing things (like the setup function) const addMissingChanges = addMissing( specFilePath, tree.read(specFilePath)!.toString('utf8'), params, name ); applyChanges(tree, specFilePath, addMissingChanges, 'add'); // then on the resulting tree - remove unneeded deps const removeChanges = doUpdate( specFilePath, tree.read(specFilePath)!.toString('utf8'), params, name, 'remove', publicMethods, shorthand ); applyChanges(tree, specFilePath, removeChanges, 'remove'); // then add what needs to be added (new deps in the instantiation, 'it' for new methods, etc.) const changesToAdd = doUpdate( specFilePath, tree.read(specFilePath)!.toString('utf8'), params, name, 'add', publicMethods, shorthand ); applyChanges(tree, specFilePath, changesToAdd, 'add'); return tree; } } } function applyChanges(tree: Tree, specFilePath: string, changes: Change[], act: 'add' | 'remove') { const recorder = tree.beginUpdate(specFilePath); if (act === 'add') { changes .filter((c) => c instanceof InsertChange) .forEach((change: InsertChange) => { recorder.insertLeft(change.order, change.toAdd); }); } else { changes .filter((c) => c instanceof RemoveChange) .forEach((change: RemoveChange) => { recorder.remove(change.order, change.toRemove.length); }); } tree.commitUpdate(recorder); } function createNewSpec( fileNameRaw: string, tree: Tree, logger: Logger, o?: { classTemplate?: string, functionTemplate?: string } ) { const content = tree.read(fileNameRaw); if (content == null) { logger.error(`The file ${fileNameRaw} is missing or empty.`); } else { // we aim at creating a spec from the class/function under test (name) // for the spec name we'll need to parse the base file name and its extension and calculate the path const { specFileName, fileName, folderPathRaw: path, folderPathNormal: folder } = paths(fileNameRaw); let templateVariables: ClassTemplateData; try { const { params, name, publicMethods } = getFirstClass(fileNameRaw, content); // if there are no methods in the class - let's add one test case anyway if (Array.isArray(publicMethods) && publicMethods.length === 0) { publicMethods.push(''); } const shorthand = typeShorthand(name); templateVariables = { ...strings, // the name of the new spec file specFileName, normalizedName: fileName, name, className: name, folder, publicMethods, params, declaration: toDeclaration(), builderExports: toBuilderExports(), constructorParams: toConstructorParams(), shorthand, } const src = maybeUseCustomTemplate(tree, url('./files/class'), o?.classTemplate); const templateSource = apply(src, [ applyTemplates(templateVariables), move(path), ]); return mergeWith(templateSource); /** * End of the create function * Below are the in-scope functions */ // functions defined in the scope of the else to use params and such // for getting called in the template - todo - just call the functions and get the result function toConstructorParams() { return params.map((p) => p.name).join(','); } function toDeclaration() { return params .map((p) => p.type === 'string' || p.type === 'number' ? `let ${p.name}:${p.type};` : `const ${p.name} = autoSpy(${p.type});` ) .join(EOL); } function toBuilderExports() { return params.length > 0 ? params .map((p) => p.name) .join(',' + EOL) .concat(',') : ''; } } catch (e) { if (e != null && e.message === 'No classes found to be spec-ed!') { const funktion = getFirstFunction(fileNameRaw, content); if (funktion == null) { throw new Error('No exported class or function to be spec-ed!'); } const src = maybeUseCustomTemplate(tree, url('./files/function'), o?.functionTemplate); const templateSource = apply(src, [ applyTemplates({ ...strings, // the name of the new spec file specFileName, fileName, normalizedName: fileName, name: funktion.name, }), move(path), ]); return mergeWith(templateSource); } else { throw e; } } } } function maybeUseCustomTemplate( tree: Tree, src: Source, templateFileName?: string ): Source { if (typeof templateFileName === 'string' && tree.exists(templateFileName)) { const template = tree.read(templateFileName); if (template != null) { const [rest] = updateCustomTemplateCut(template.toString('utf8')); const t = Tree.empty(); t.create(basename(normalize(templateFileName)), rest); src = source(t); } } return src; } function getFirstClass(fileName: string, fileContents: Buffer) { const descriptions = describeSource(fileName, fileContents.toString('utf8')); const classes = descriptions.filter((c) => isClassDescription(c)) as ClassDescription[]; // we'll take the first class with any number of constructor params or just the first if there are none const classWithConstructorParamsOrFirst: ClassDescription = classes.filter((c: ClassDescription) => c.constructorParams.length > 0)[0] || classes[0]; if (classWithConstructorParamsOrFirst == null) { throw new Error('No classes found to be spec-ed!'); } const { constructorParams: params, name, publicMethods, type, } = classWithConstructorParamsOrFirst; return { params, name, publicMethods, type }; } function getFirstFunction(fileName: string, fileContents: Buffer) { const descriptions = describeSource(fileName, fileContents.toString('utf8')); return (descriptions.filter((f) => f.type === 'function') as FunctionDescription[])[0]; } function typeShorthand(name: string) { return typeof name === 'string' && name.length > 0 ? name.toLocaleLowerCase()[0] : 'x'; }
the_stack
import * as clone from 'clone'; import {PackageRelativeUrl, ResolvedUrl, UrlResolver} from 'polymer-analyzer'; import {getSuperBundleUrl} from './deps-index'; import {getFileExtension} from './url-utils'; import {partitionMap, uniq} from './utils'; /** * A bundle strategy function is used to transform an array of bundles. */ export type BundleStrategy = (bundles: Bundle[]) => Bundle[]; /** * A bundle URL mapper function produces a map of URLs to bundles. */ export type BundleUrlMapper = (bundles: Bundle[]) => Map<ResolvedUrl, Bundle>; /** * A mapping of entrypoints to their full set of transitive dependencies, * such that a dependency graph `a->c, c->d, d->e, b->d, b->f` would be * represented `{a:[a,c,d,e], b:[b,d,e,f]}`. Please note that there is an * explicit identity dependency (`a` depends on `a`, `b` depends on `b`). */ export type TransitiveDependenciesMap = Map<ResolvedUrl, Set<ResolvedUrl>>; /** * The output format of the bundle. */ export type BundleType = 'html-fragment' | 'es6-module'; export const bundleTypeExtnames = new Map<BundleType, string>([ ['es6-module', '.js'], ['html-fragment', '.html'], ]); /** * A bundle is a grouping of files which serve the need of one or more * entrypoint files. */ export class Bundle { // Set of imports which should be removed when encountered. stripImports = new Set<ResolvedUrl>(); // Set of imports which could not be loaded. missingImports = new Set<ResolvedUrl>(); // These sets are updated as bundling occurs. inlinedHtmlImports = new Set<ResolvedUrl>(); inlinedScripts = new Set<ResolvedUrl>(); inlinedStyles = new Set<ResolvedUrl>(); // Maps the URLs of bundled ES6 modules to a map of their original exported // names to names which may have been rewritten to prevent conflicts. bundledExports = new Map<ResolvedUrl, Map<string, string>>(); constructor( // Filetype discriminator for Bundles. public type: BundleType, // Set of all dependant entrypoint URLs of this bundle. public entrypoints = new Set<ResolvedUrl>(), // Set of all files included in the bundle. public files = new Set<ResolvedUrl>()) { } get extname() { return bundleTypeExtnames.get(this.type); } } /** * Represents a bundle assigned to an output URL. */ export class AssignedBundle { bundle: Bundle; url: ResolvedUrl; } export interface BundleManifestJson { [entrypoint: string]: PackageRelativeUrl[]; } /** * A bundle manifest is a mapping of URLs to bundles. */ export class BundleManifest { // Map of bundle URL to bundle. bundles: Map<ResolvedUrl, Bundle>; // Map of file URL to bundle URL. private _bundleUrlForFile: Map<ResolvedUrl, ResolvedUrl>; /** * Given a collection of bundles and a BundleUrlMapper to generate URLs for * them, the constructor populates the `bundles` and `files` index properties. */ constructor(bundles: Bundle[], urlMapper: BundleUrlMapper) { this.bundles = urlMapper(Array.from(bundles)); this._bundleUrlForFile = new Map(); for (const bundleMapEntry of this.bundles) { const bundleUrl = bundleMapEntry[0]; const bundle = bundleMapEntry[1]; for (const fileUrl of bundle.files) { console.assert(!this._bundleUrlForFile.has(fileUrl)); this._bundleUrlForFile.set(fileUrl, bundleUrl); } } } // Returns a clone of the manifest. fork(): BundleManifest { return clone(this); } // Convenience method to return a bundle for a constituent file URL. getBundleForFile(url: ResolvedUrl): AssignedBundle|undefined { const bundleUrl = this._bundleUrlForFile.get(url); if (bundleUrl) { return {bundle: this.bundles.get(bundleUrl)!, url: bundleUrl}; } } toJson(urlResolver: UrlResolver): BundleManifestJson { const json = {}; const missingImports: Set<ResolvedUrl> = new Set(); for (const [url, bundle] of this.bundles) { json[urlResolver.relative(url)] = [...new Set([ // `files` and `inlinedHtmlImports` will be partially // duplicative, but use of both ensures the basis document // for a file is included since there is no other specific // property that currently expresses it. ...bundle.files, ...bundle.inlinedHtmlImports, ...bundle.inlinedScripts, ...bundle.inlinedStyles ])].map((url: ResolvedUrl) => urlResolver.relative(url)); for (const missingImport of bundle.missingImports) { missingImports.add(missingImport); } } if (missingImports.size > 0) { json['_missing'] = [...missingImports].map( (url: ResolvedUrl) => urlResolver.relative(url)); } return json; } } /** * Chains multiple bundle strategy functions together so the output of one * becomes the input of the next and so-on. */ export function composeStrategies(strategies: BundleStrategy[]): BundleStrategy { return strategies.reduce((s1, s2) => (b) => s2(s1(b))); } /** * Given an index of files and their dependencies, produce an array of bundles, * where a bundle is defined for each set of dependencies. * * For example, a dependency index representing the graph: * `a->b, b->c, b->d, e->c, e->f` * * Would produce an array of three bundles: * `[a]->[a,b,d], [e]->[e,f], [a,e]->[c]` */ export function generateBundles(depsIndex: TransitiveDependenciesMap): Bundle[] { const bundles: Bundle[] = []; // TODO(usergenic): Assert a valid transitive dependencies map; i.e. // entrypoints should include themselves as dependencies and entrypoints // should *probably* not include other entrypoints as dependencies. const invertedIndex = invertMultimap(depsIndex); for (const entry of invertedIndex.entries()) { const dep: ResolvedUrl = entry[0]; const entrypoints: Set<ResolvedUrl> = entry[1]; // Find the bundle defined by the specific set of shared dependant // entrypoints. let bundle = bundles.find((bundle) => setEquals(entrypoints, bundle.entrypoints)); if (!bundle) { const type = getBundleTypeForUrl([...entrypoints][0]); bundle = new Bundle(type, entrypoints); bundles.push(bundle); } bundle.files.add(dep); } return bundles; } /** * Instances of `<script type="module">` generate synthetic entrypoints in the * depsIndex and are treated as entrypoints during the initial phase of * `generateBundles`. Any bundle which provides dependencies to a single * synthetic entrypoint of this type (aka a single entrypoint sub-bundle) are * merged back into the bundle for the HTML containing the script tag. * * For example, the following bundles: * `[a]->[a], [a>1]->[x], [a>1,a>2]->[y], [a>2]->[z]` * * Would be merged into the following set of bundles: * `[a]->[a,x,z], [a>1,a>2]->[y]` * * `a>1` and `a>2` represent script tag entrypoints. Only `x` and `z` are * bundled with `a` because they each serve only a single script tag entrypoint. * `y` has to be in a separate bundle so that it is not inlined into bundle `a` * in both script tags. */ export function mergeSingleEntrypointSubBundles(bundles: Bundle[]) { for (const subBundle of [...bundles]) { if (subBundle.entrypoints.size !== 1) { continue; } const entrypointUrl = [...subBundle.entrypoints][0]; const superBundleUrl = getSuperBundleUrl(entrypointUrl); // If the entrypoint URL is the same as the super bundle URL then the // entrypoint URL has not changed and did not represent a sub bundle, so // continue to next candidate sub bundle. if (entrypointUrl === superBundleUrl) { continue; } const superBundleIndex = bundles.findIndex((b) => b.files.has(superBundleUrl)); if (superBundleIndex < 0) { continue; } const superBundle = bundles[superBundleIndex]; // The synthetic entrypoint identifier does not need to be represented in // the super bundle's entrypoints list, so we'll clear the sub-bundle's // entrypoints in the bundle before merging. subBundle.entrypoints.clear(); const mergedBundle = mergeBundles([superBundle, subBundle], true); bundles.splice(superBundleIndex, 1, mergedBundle); const subBundleIndex = bundles.findIndex((b) => b === subBundle); bundles.splice(subBundleIndex, 1); } } /** * Creates a bundle URL mapper function which takes a prefix and appends an * incrementing value, starting with `1` to the filename. */ export function generateCountingSharedBundleUrlMapper(urlPrefix: ResolvedUrl): BundleUrlMapper { return generateSharedBundleUrlMapper( (sharedBundles: Bundle[]): ResolvedUrl[] => { let counter = 0; return sharedBundles.map( (b) => `${urlPrefix}${++counter}${b.extname}` as ResolvedUrl); }); } /** * Generates a strategy function which finds all non-entrypoint bundles which * are dependencies of the given entrypoint and merges them into that * entrypoint's bundle. */ export function generateEagerMergeStrategy(entrypoint: ResolvedUrl): BundleStrategy { return generateMatchMergeStrategy( (b) => b.files.has(entrypoint) || b.entrypoints.has(entrypoint) && !getBundleEntrypoint(b)); } /** * Generates a strategy function which finds all bundles matching the predicate * function and merges them into the bundle containing the target file. */ export function generateMatchMergeStrategy(predicate: (b: Bundle) => boolean): BundleStrategy { return (bundles: Bundle[]) => mergeMatchingBundles(bundles, predicate); } /** * Creates a bundle URL mapper function which maps non-shared bundles to the * URLs of their single entrypoint and yields responsibility for naming * remaining shared bundle URLs to the `mapper` function argument. The * mapper function takes a collection of shared bundles and a URL map, calling * `.set(url, bundle)` for each. */ export function generateSharedBundleUrlMapper( mapper: (sharedBundles: Bundle[]) => ResolvedUrl[]): BundleUrlMapper { return (bundles: Bundle[]) => { const urlMap = new Map<ResolvedUrl, Bundle>(); const sharedBundles: Bundle[] = []; for (const bundle of bundles) { const bundleUrl = getBundleEntrypoint(bundle); if (bundleUrl) { urlMap.set(bundleUrl, bundle); } else { sharedBundles.push(bundle); } } mapper(sharedBundles) .forEach((url, i) => urlMap.set(url, sharedBundles[i])); return urlMap; }; } /** * Generates a strategy function to merge all bundles where the dependencies * for a bundle are shared by at least 2 entrypoints (default; set * `minEntrypoints` to change threshold). * * This function will convert an array of 4 bundles: * `[a]->[a,b], [a,c]->[d], [c]->[c,e], [f,g]->[f,g,h]` * * Into the following 3 bundles, including a single bundle for all of the * dependencies which are shared by at least 2 entrypoints: * `[a]->[a,b], [c]->[c,e], [a,c,f,g]->[d,f,g,h]` */ export function generateSharedDepsMergeStrategy(maybeMinEntrypoints?: number): BundleStrategy { const minEntrypoints = maybeMinEntrypoints === undefined ? 2 : maybeMinEntrypoints; if (minEntrypoints < 0) { throw new Error(`Minimum entrypoints argument must be non-negative`); } return generateMatchMergeStrategy( (b) => b.entrypoints.size >= minEntrypoints && !getBundleEntrypoint(b)); } /** * A bundle strategy function which merges all shared dependencies into a * bundle for an application shell. */ export function generateShellMergeStrategy( shell: ResolvedUrl, maybeMinEntrypoints?: number): BundleStrategy { const minEntrypoints = maybeMinEntrypoints === undefined ? 2 : maybeMinEntrypoints; if (minEntrypoints < 0) { throw new Error(`Minimum entrypoints argument must be non-negative`); } return composeStrategies([ // Merge all bundles that are direct dependencies of the shell into the // shell. generateEagerMergeStrategy(shell), // Create a new bundle which contains the contents of all bundles which // either... generateMatchMergeStrategy((bundle) => { // ...contain the shell file return bundle.files.has(shell) || // or are dependencies of at least the minimum number of // entrypoints and are not entrypoints themselves. bundle.entrypoints.size >= minEntrypoints && !getBundleEntrypoint(bundle); }), // Don't link to the shell from other bundles. generateNoBackLinkStrategy([shell]), ]); } /** * Generates a strategy function that ensures bundles do not link to given URLs. * Bundles which contain matching files will still have them inlined. */ export function generateNoBackLinkStrategy(urls: ResolvedUrl[]): BundleStrategy { return (bundles) => { for (const bundle of bundles) { for (const url of urls) { if (!bundle.files.has(url)) { bundle.stripImports.add(url); } } } return bundles; }; } /** * Given an Array of bundles, produce a single bundle with the entrypoints and * files of all bundles represented. By default, bundles of different types * can not be merged, but this constraint can be skipped by providing * `ignoreTypeCheck` argument with value `true`, which is necessary to merge a * bundle containining an inline document's unique transitive dependencies, as * inline documents typically are of different type (`<script type="module">` * within HTML document contains JavaScript document). */ export function mergeBundles( bundles: Bundle[], ignoreTypeCheck: boolean = false): Bundle { if (bundles.length === 0) { throw new Error('Can not merge 0 bundles.'); } const bundleTypes = uniq(bundles, (b: Bundle) => b.type); if (!ignoreTypeCheck && bundleTypes.size > 1) { throw new Error( 'Can not merge bundles of different types: ' + [...bundleTypes].join(' and ')); } const bundleType = bundles[0].type; const newBundle = new Bundle(bundleType); for (const { entrypoints, files, inlinedHtmlImports, inlinedScripts, inlinedStyles, bundledExports, } of bundles) { newBundle.entrypoints = new Set<ResolvedUrl>([...newBundle.entrypoints, ...entrypoints]); newBundle.files = new Set<ResolvedUrl>([...newBundle.files, ...files]); newBundle.inlinedHtmlImports = new Set<ResolvedUrl>( [...newBundle.inlinedHtmlImports, ...inlinedHtmlImports]); newBundle.inlinedScripts = new Set<ResolvedUrl>([...newBundle.inlinedScripts, ...inlinedScripts]); newBundle.inlinedStyles = new Set<ResolvedUrl>([...newBundle.inlinedStyles, ...inlinedStyles]); newBundle.bundledExports = new Map<ResolvedUrl, Map<string, string>>( [...newBundle.bundledExports, ...bundledExports]); } return newBundle; } /** * Return a new bundle array where bundles within it matching the predicate * are merged together. Note that merge operations are segregated by type so * that no attempt to merge bundles of different types will occur. */ export function mergeMatchingBundles( bundles: Bundle[], predicate: (bundle: Bundle) => boolean): Bundle[] { const newBundles = bundles.filter((b) => !predicate(b)); const bundlesToMerge = partitionMap( bundles.filter((b) => !newBundles.includes(b)), (b) => b.type); for (const bundlesOfType of bundlesToMerge.values()) { newBundles.push(mergeBundles(bundlesOfType)); } return newBundles; } /** * Return the single entrypoint that represents the given bundle, or null * if bundle contains more or less than a single file URL matching URLs * in its entrypoints set. This makes it convenient to identify whether a * bundle is a named fragment or whether it is simply a shared bundle * of some kind. */ function getBundleEntrypoint(bundle: Bundle): ResolvedUrl|null { let bundleEntrypoint = null; for (const entrypoint of bundle.entrypoints) { if (bundle.files.has(entrypoint)) { if (bundleEntrypoint) { return null; } bundleEntrypoint = entrypoint; } } return bundleEntrypoint; } /** * Generally bundle types are determined by the file extension of the URL, * though in the case of sub-bundles, the bundle type is the last segment of the * `>` delimited URL, (e.g. `page1.html>inline#1>es6-module`). */ function getBundleTypeForUrl(url: ResolvedUrl): BundleType { const segments = url.split('>'); if (segments.length === 1) { const extname = getFileExtension(segments[0]); return extname === '.js' ? 'es6-module' : 'html-fragment'; } if (segments.length === 0) { throw new Error(`ResolvedUrl "${url}" is empty/invalid.`); } return segments.pop() as BundleType; } /** * Inverts a map of collections such that `{a:[c,d], b:[c,e]}` would become * `{c:[a,b], d:[a], e:[b]}`. */ function invertMultimap(multimap: Map<any, Set<any>>): Map<any, Set<any>> { const inverted = new Map<any, Set<any>>(); for (const entry of multimap.entries()) { const value = entry[0], keys = entry[1]; for (const key of keys) { const set = inverted.get(key) || new Set(); set.add(value); inverted.set(key, set); } } return inverted; } /** * Returns true if both sets contain exactly the same items. This check is * order-independent. */ function setEquals(set1: Set<any>, set2: Set<any>): boolean { if (set1.size !== set2.size) { return false; } for (const item of set1) { if (!set2.has(item)) { return false; } } return true; }
the_stack
import { distinct, flatten } from 'vs/base/common/arrays'; import { Emitter, Event } from 'vs/base/common/event'; import { parse } from 'vs/base/common/json'; import { Disposable } from 'vs/base/common/lifecycle'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { FileKind, IFileService } from 'vs/platform/files/common/files'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { isWorkspace, IWorkspace, IWorkspaceContextService, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IQuickInputService, IQuickPickItem, IQuickPickSeparator } from 'vs/platform/quickinput/common/quickInput'; import { IModelService } from 'vs/editor/common/services/model'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { localize } from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { IJSONEditingService, IJSONValue } from 'vs/workbench/services/configuration/common/jsonEditing'; import { ResourceMap } from 'vs/base/common/map'; export const EXTENSIONS_CONFIG = '.vscode/extensions.json'; export interface IExtensionsConfigContent { recommendations?: string[]; unwantedRecommendations?: string[]; } export const IWorkspaceExtensionsConfigService = createDecorator<IWorkspaceExtensionsConfigService>('IWorkspaceExtensionsConfigService'); export interface IWorkspaceExtensionsConfigService { readonly _serviceBrand: undefined; onDidChangeExtensionsConfigs: Event<void>; getExtensionsConfigs(): Promise<IExtensionsConfigContent[]>; getRecommendations(): Promise<string[]>; getUnwantedRecommendations(): Promise<string[]>; toggleRecommendation(extensionId: string): Promise<void>; toggleUnwantedRecommendation(extensionId: string): Promise<void>; } export class WorkspaceExtensionsConfigService extends Disposable implements IWorkspaceExtensionsConfigService { declare readonly _serviceBrand: undefined; private readonly _onDidChangeExtensionsConfigs = this._register(new Emitter<void>()); readonly onDidChangeExtensionsConfigs = this._onDidChangeExtensionsConfigs.event; constructor( @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @IFileService private readonly fileService: IFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IModelService private readonly modelService: IModelService, @ILanguageService private readonly languageService: ILanguageService, @IJSONEditingService private readonly jsonEditingService: IJSONEditingService, ) { super(); this._register(workspaceContextService.onDidChangeWorkspaceFolders(e => this._onDidChangeExtensionsConfigs.fire())); this._register(fileService.onDidFilesChange(e => { const workspace = workspaceContextService.getWorkspace(); if ((workspace.configuration && e.affects(workspace.configuration)) || workspace.folders.some(folder => e.affects(folder.toResource(EXTENSIONS_CONFIG))) ) { this._onDidChangeExtensionsConfigs.fire(); } })); } async getExtensionsConfigs(): Promise<IExtensionsConfigContent[]> { const workspace = this.workspaceContextService.getWorkspace(); const result: IExtensionsConfigContent[] = []; const workspaceExtensionsConfigContent = workspace.configuration ? await this.resolveWorkspaceExtensionConfig(workspace.configuration) : undefined; if (workspaceExtensionsConfigContent) { result.push(workspaceExtensionsConfigContent); } result.push(...await Promise.all(workspace.folders.map(workspaceFolder => this.resolveWorkspaceFolderExtensionConfig(workspaceFolder)))); return result; } async getRecommendations(): Promise<string[]> { const configs = await this.getExtensionsConfigs(); return distinct(flatten(configs.map(c => c.recommendations ? c.recommendations.map(c => c.toLowerCase()) : []))); } async getUnwantedRecommendations(): Promise<string[]> { const configs = await this.getExtensionsConfigs(); return distinct(flatten(configs.map(c => c.unwantedRecommendations ? c.unwantedRecommendations.map(c => c.toLowerCase()) : []))); } async toggleRecommendation(extensionId: string): Promise<void> { const workspace = this.workspaceContextService.getWorkspace(); const workspaceExtensionsConfigContent = workspace.configuration ? await this.resolveWorkspaceExtensionConfig(workspace.configuration) : undefined; const workspaceFolderExtensionsConfigContents = new ResourceMap<IExtensionsConfigContent>(); await Promise.all(workspace.folders.map(async workspaceFolder => { const extensionsConfigContent = await this.resolveWorkspaceFolderExtensionConfig(workspaceFolder); workspaceFolderExtensionsConfigContents.set(workspaceFolder.uri, extensionsConfigContent); })); const isWorkspaceRecommended = workspaceExtensionsConfigContent && workspaceExtensionsConfigContent.recommendations?.some(r => r === extensionId); const recommendedWorksapceFolders = workspace.folders.filter(workspaceFolder => workspaceFolderExtensionsConfigContents.get(workspaceFolder.uri)?.recommendations?.some(r => r === extensionId)); const isRecommended = isWorkspaceRecommended || recommendedWorksapceFolders.length > 0; const workspaceOrFolders = isRecommended ? await this.pickWorkspaceOrFolders(recommendedWorksapceFolders, isWorkspaceRecommended ? workspace : undefined, localize('select for remove', "Remove extension recommendation from")) : await this.pickWorkspaceOrFolders(workspace.folders, workspace.configuration ? workspace : undefined, localize('select for add', "Add extension recommendation to")); for (const workspaceOrWorkspaceFolder of workspaceOrFolders) { if (isWorkspace(workspaceOrWorkspaceFolder)) { await this.addOrRemoveWorkspaceRecommendation(extensionId, workspaceOrWorkspaceFolder, workspaceExtensionsConfigContent, !isRecommended); } else { await this.addOrRemoveWorkspaceFolderRecommendation(extensionId, workspaceOrWorkspaceFolder, workspaceFolderExtensionsConfigContents.get(workspaceOrWorkspaceFolder.uri)!, !isRecommended); } } } async toggleUnwantedRecommendation(extensionId: string): Promise<void> { const workspace = this.workspaceContextService.getWorkspace(); const workspaceExtensionsConfigContent = workspace.configuration ? await this.resolveWorkspaceExtensionConfig(workspace.configuration) : undefined; const workspaceFolderExtensionsConfigContents = new ResourceMap<IExtensionsConfigContent>(); await Promise.all(workspace.folders.map(async workspaceFolder => { const extensionsConfigContent = await this.resolveWorkspaceFolderExtensionConfig(workspaceFolder); workspaceFolderExtensionsConfigContents.set(workspaceFolder.uri, extensionsConfigContent); })); const isWorkspaceUnwanted = workspaceExtensionsConfigContent && workspaceExtensionsConfigContent.unwantedRecommendations?.some(r => r === extensionId); const unWantedWorksapceFolders = workspace.folders.filter(workspaceFolder => workspaceFolderExtensionsConfigContents.get(workspaceFolder.uri)?.unwantedRecommendations?.some(r => r === extensionId)); const isUnwanted = isWorkspaceUnwanted || unWantedWorksapceFolders.length > 0; const workspaceOrFolders = isUnwanted ? await this.pickWorkspaceOrFolders(unWantedWorksapceFolders, isWorkspaceUnwanted ? workspace : undefined, localize('select for remove', "Remove extension recommendation from")) : await this.pickWorkspaceOrFolders(workspace.folders, workspace.configuration ? workspace : undefined, localize('select for add', "Add extension recommendation to")); for (const workspaceOrWorkspaceFolder of workspaceOrFolders) { if (isWorkspace(workspaceOrWorkspaceFolder)) { await this.addOrRemoveWorkspaceUnwantedRecommendation(extensionId, workspaceOrWorkspaceFolder, workspaceExtensionsConfigContent, !isUnwanted); } else { await this.addOrRemoveWorkspaceFolderUnwantedRecommendation(extensionId, workspaceOrWorkspaceFolder, workspaceFolderExtensionsConfigContents.get(workspaceOrWorkspaceFolder.uri)!, !isUnwanted); } } } private async addOrRemoveWorkspaceFolderRecommendation(extensionId: string, workspaceFolder: IWorkspaceFolder, extensionsConfigContent: IExtensionsConfigContent, add: boolean): Promise<void> { const values: IJSONValue[] = []; if (add) { values.push({ path: ['recommendations'], value: [...extensionsConfigContent.recommendations || [], extensionId] }); if (extensionsConfigContent.unwantedRecommendations && extensionsConfigContent.unwantedRecommendations.some(e => e === extensionId)) { values.push({ path: ['unwantedRecommendations'], value: extensionsConfigContent.unwantedRecommendations.filter(e => e !== extensionId) }); } } else if (extensionsConfigContent.recommendations) { values.push({ path: ['recommendations'], value: extensionsConfigContent.recommendations.filter(e => e !== extensionId) }); } if (values.length) { return this.jsonEditingService.write(workspaceFolder.toResource(EXTENSIONS_CONFIG), values, true); } } private async addOrRemoveWorkspaceRecommendation(extensionId: string, workspace: IWorkspace, extensionsConfigContent: IExtensionsConfigContent | undefined, add: boolean): Promise<void> { const values: IJSONValue[] = []; if (extensionsConfigContent) { if (add) { values.push({ path: ['extensions', 'recommendations'], value: [...extensionsConfigContent.recommendations || [], extensionId] }); if (extensionsConfigContent.unwantedRecommendations && extensionsConfigContent.unwantedRecommendations.some(e => e === extensionId)) { values.push({ path: ['extensions', 'unwantedRecommendations'], value: extensionsConfigContent.unwantedRecommendations.filter(e => e !== extensionId) }); } } else if (extensionsConfigContent.recommendations) { values.push({ path: ['extensions', 'recommendations'], value: extensionsConfigContent.recommendations.filter(e => e !== extensionId) }); } } else if (add) { values.push({ path: ['extensions'], value: { recommendations: [extensionId] } }); } if (values.length) { return this.jsonEditingService.write(workspace.configuration!, values, true); } } private async addOrRemoveWorkspaceFolderUnwantedRecommendation(extensionId: string, workspaceFolder: IWorkspaceFolder, extensionsConfigContent: IExtensionsConfigContent, add: boolean): Promise<void> { const values: IJSONValue[] = []; if (add) { values.push({ path: ['unwantedRecommendations'], value: [...extensionsConfigContent.unwantedRecommendations || [], extensionId] }); if (extensionsConfigContent.recommendations && extensionsConfigContent.recommendations.some(e => e === extensionId)) { values.push({ path: ['recommendations'], value: extensionsConfigContent.recommendations.filter(e => e !== extensionId) }); } } else if (extensionsConfigContent.unwantedRecommendations) { values.push({ path: ['unwantedRecommendations'], value: extensionsConfigContent.unwantedRecommendations.filter(e => e !== extensionId) }); } if (values.length) { return this.jsonEditingService.write(workspaceFolder.toResource(EXTENSIONS_CONFIG), values, true); } } private async addOrRemoveWorkspaceUnwantedRecommendation(extensionId: string, workspace: IWorkspace, extensionsConfigContent: IExtensionsConfigContent | undefined, add: boolean): Promise<void> { const values: IJSONValue[] = []; if (extensionsConfigContent) { if (add) { values.push({ path: ['extensions', 'unwantedRecommendations'], value: [...extensionsConfigContent.unwantedRecommendations || [], extensionId] }); if (extensionsConfigContent.recommendations && extensionsConfigContent.recommendations.some(e => e === extensionId)) { values.push({ path: ['extensions', 'recommendations'], value: extensionsConfigContent.recommendations.filter(e => e !== extensionId) }); } } else if (extensionsConfigContent.unwantedRecommendations) { values.push({ path: ['extensions', 'unwantedRecommendations'], value: extensionsConfigContent.unwantedRecommendations.filter(e => e !== extensionId) }); } } else if (add) { values.push({ path: ['extensions'], value: { unwantedRecommendations: [extensionId] } }); } if (values.length) { return this.jsonEditingService.write(workspace.configuration!, values, true); } } private async pickWorkspaceOrFolders(workspaceFolders: IWorkspaceFolder[], workspace: IWorkspace | undefined, placeHolder: string): Promise<(IWorkspace | IWorkspaceFolder)[]> { const workspaceOrFolders = workspace ? [...workspaceFolders, workspace] : [...workspaceFolders]; if (workspaceOrFolders.length === 1) { return workspaceOrFolders; } const folderPicks: (IQuickPickItem & { workspaceOrFolder: IWorkspace | IWorkspaceFolder } | IQuickPickSeparator)[] = workspaceFolders.map(workspaceFolder => { return { label: workspaceFolder.name, description: localize('workspace folder', "Workspace Folder"), workspaceOrFolder: workspaceFolder, iconClasses: getIconClasses(this.modelService, this.languageService, workspaceFolder.uri, FileKind.ROOT_FOLDER) }; }); if (workspace) { folderPicks.push({ type: 'separator' }); folderPicks.push({ label: localize('workspace', "Workspace"), workspaceOrFolder: workspace, }); } const result = await this.quickInputService.pick(folderPicks, { placeHolder, canPickMany: true }) || []; return result.map(r => r.workspaceOrFolder!); } private async resolveWorkspaceExtensionConfig(workspaceConfigurationResource: URI): Promise<IExtensionsConfigContent | undefined> { try { const content = await this.fileService.readFile(workspaceConfigurationResource); const extensionsConfigContent = <IExtensionsConfigContent | undefined>parse(content.value.toString())['extensions']; return extensionsConfigContent ? this.parseExtensionConfig(extensionsConfigContent) : undefined; } catch (e) { /* Ignore */ } return undefined; } private async resolveWorkspaceFolderExtensionConfig(workspaceFolder: IWorkspaceFolder): Promise<IExtensionsConfigContent> { try { const content = await this.fileService.readFile(workspaceFolder.toResource(EXTENSIONS_CONFIG)); const extensionsConfigContent = <IExtensionsConfigContent>parse(content.value.toString()); return this.parseExtensionConfig(extensionsConfigContent); } catch (e) { /* ignore */ } return {}; } private parseExtensionConfig(extensionsConfigContent: IExtensionsConfigContent): IExtensionsConfigContent { return { recommendations: distinct((extensionsConfigContent.recommendations || []).map(e => e.toLowerCase())), unwantedRecommendations: distinct((extensionsConfigContent.unwantedRecommendations || []).map(e => e.toLowerCase())) }; } } registerSingleton(IWorkspaceExtensionsConfigService, WorkspaceExtensionsConfigService);
the_stack
import { type, ipairs, pairs, wipe, truthy, LuaArray, LuaObj, } from "@wowts/lua"; import { find } from "@wowts/string"; import { isNumber, oneTimeMessage } from "../tools/tools"; import { HasteType } from "../states/PaperDoll"; import { PowerType } from "../states/Power"; import { GetSpellInfo, SpellId } from "@wowts/wow-mock"; import { AstItemRequireNode, AstSpellAuraListNode, AstSpellRequireNode, } from "./ast"; import { Runner } from "./runner"; import { OptionUiAll } from "../ui/acegui-helpers"; import { concat, insert } from "@wowts/table"; import { DebugTools } from "./debug"; const bloodelfClasses: LuaObj<boolean> = { ["DEATHKNIGHT"]: true, ["DEMONHUNTER"]: true, ["DRUID"]: false, ["HUNTER"]: true, ["MAGE"]: true, ["MONK"]: true, ["PALADIN"]: true, ["PRIEST"]: true, ["ROGUE"]: true, ["SHAMAN"]: false, ["WARLOCK"]: true, ["WARRIOR"]: true, }; const pandarenClasses: LuaObj<boolean> = { ["DEATHKNIGHT"]: false, ["DEMONHUNTER"]: false, ["DRUID"]: false, ["HUNTER"]: true, ["MAGE"]: true, ["MONK"]: true, ["PALADIN"]: false, ["PRIEST"]: true, ["ROGUE"]: true, ["SHAMAN"]: true, ["WARLOCK"]: false, ["WARRIOR"]: true, }; const taurenClasses: LuaObj<boolean> = { ["DEATHKNIGHT"]: true, ["DEMONHUNTER"]: false, ["DRUID"]: true, ["HUNTER"]: true, ["MAGE"]: false, ["MONK"]: true, ["PALADIN"]: true, ["PRIEST"]: true, ["ROGUE"]: false, ["SHAMAN"]: true, ["WARLOCK"]: false, ["WARRIOR"]: true, }; const statNames: LuaArray<string> = { 1: "agility", 2: "bonus_armor", 3: "critical_strike", 4: "haste", 5: "intellect", 6: "mastery", 7: "spirit", 8: "spellpower", 9: "strength", 10: "versatility", }; const startShortNames: LuaObj<string> = { agility: "agi", critical_strike: "crit", intellect: "int", strength: "str", spirit: "spi", }; const statUseNames: LuaArray<string> = { 1: "trinket_proc", 2: "trinket_stacking_proc", 3: "trinket_stacking_stat", 4: "trinket_stat", 5: "trinket_stack_proc", }; type SpellAuraInfo = AstSpellAuraListNode; type SpellAddAurasById = { [key: number]: SpellAuraInfo; [key: string]: SpellAuraInfo; }; export interface SpellAddAurasByType { HARMFUL: SpellAddAurasById; HELPFUL: SpellAddAurasById; } export type AuraType = keyof SpellAddAurasByType; export interface SpellAddAuras { damage: SpellAddAurasByType; pet: SpellAddAurasByType; target: SpellAddAurasByType; player: SpellAddAurasByType; } //type Auras = LuaObj<LuaObj<LuaArray<SpellData>>>; export type SpellInfoProperty = keyof SpellInfoValues; type SpellInfoPowerValues = { [K in PowerType]?: number; }; type SpellInfoPowerSetValues = { [K in PowerType as `set_${K}`]?: number; }; type SpellInfoPowerMaxValues = { [K in PowerType as `max_${K}`]?: number; }; type SpellInfoPowerRefundValues = { [K in PowerType as `refund_${K}`]?: number | "cost"; }; export interface SpellInfoValues extends SpellInfoPowerValues, SpellInfoPowerSetValues, SpellInfoPowerMaxValues, SpellInfoPowerRefundValues { duration?: number; add_duration_combopoints?: number; half_duration?: number; tick?: number; stacking?: number; max_stacks?: number; // stat?: string | LuaArray<string>; // buff?: number | LuaArray<number>; // Cooldown gcd?: number; shared_cd?: string; cd?: number; /** Internal cooldown (mainly on items) */ icd?: number; rppm?: number; charge_cd?: number; forcecd?: number; buff_cd?: number; // Internal cooldown, rename? buff_cdr?: number; // Cooldown reduction TODO // Haste haste?: HasteType; cd_haste?: string; gcd_haste?: HasteType; // Damage Calculations bonusmainhand?: number; bonusoffhand?: number; bonuscp?: number; bonusap?: number; bonusapcp?: number; bonussp?: number; damage?: number; base?: number; // base damage physical?: number; // Icon tag?: string; texture?: string; // Spells replaced_by?: number; max_travel_time?: number; travel_time?: number; canStopChannelling?: number; channel?: number; unusable?: number; to_stance?: number; // Totems totem?: number; buff_totem?: number; max_totems?: number; // (custom) Counter inccounter?: number; resetcounter?: number; runes?: number; interrupt?: number; add_duration?: number; add_cd?: number; // flash?:boolean; // target?:string; // soundtime?:number; // enemies?:number; offgcd?: number; casttime?: number; health?: number; addlist?: string; dummy_replace?: string; learn?: number; pertrait?: number; proc?: number; effect?: "HELPFUL" | "HARMFUL"; } export type SpellInfoNumberProperty = { [k in keyof Required<SpellInfoValues>]: Required<SpellInfoValues>[k] extends number ? k : never; }[keyof SpellInfoValues]; export interface SpellInfo extends SpellInfoValues { //[key:string]: LuaObj<Requirements> | number | string | LuaArray<string> | LuaArray<number> | Auras; require: { [k in SpellInfoProperty]?: LuaArray< AstSpellRequireNode | AstItemRequireNode >; }; // Aura aura?: SpellAddAuras; } interface SpellDebug { auraSeen?: boolean; spellCast?: boolean; auraAsked?: boolean; spellAsked?: boolean; } export class OvaleDataClass { statNames = statNames; shortNames = startShortNames; statUseNames = statUseNames; bloodElfClasses = bloodelfClasses; pandarenClasses = pandarenClasses; taurenClasses = taurenClasses; itemInfo: LuaArray<SpellInfo> = {}; itemList: LuaObj<LuaArray<number>> = {}; spellInfo: LuaObj<SpellInfo> = {}; private spellDebug: LuaObj<Record<number, SpellDebug>> = {}; private debugOptions: LuaObj<OptionUiAll> = { data: { name: "Data", type: "group", args: { spells: { name: "Spell data", type: "input", multiline: 25, width: "full", get: (info: LuaArray<string>) => { const array: LuaArray<string> = {}; const properties: LuaArray<string> = {}; for (const [spellName, spellNameDebug] of pairs( this.spellDebug )) { let display = false; for (const [, spellDebug] of pairs( spellNameDebug )) { if ( spellDebug.auraAsked || spellDebug.spellAsked ) { display = true; break; } } if (display) { insert(array, `${spellName}:`); for (const [spellId, spellDebug] of pairs( spellNameDebug )) { wipe(properties); if (spellDebug.auraAsked) insert(properties, "aura asked"); if (spellDebug.auraSeen) insert(properties, "aura seen"); if (spellDebug.spellAsked) insert(properties, "spell asked"); if (spellDebug.spellCast) insert(properties, "spell cast"); insert( array, ` ${spellId}: ${concat( properties, ", " )}` ); } } } return concat(array, "\n"); }, }, }, }, }; buffSpellList: LuaObj<LuaArray<boolean>> = { attack_power_multiplier_buff: { [SpellId.battle_shout]: true, }, critical_strike_buff: { [SpellId.arcane_intellect]: true, }, haste_buff: {}, mastery_buff: {}, spell_power_multiplier_buff: { [SpellId.arcane_intellect]: true, }, stamina_buff: { [SpellId.power_word_fortitude]: true, }, str_agi_int_buff: {}, versatility_buff: {}, bleed_debuff: { [SpellId.bloodbath_debuff]: true, [SpellId.crimson_tempest]: true, [SpellId.deep_wounds_debuff]: true, [SpellId.garrote]: true, [SpellId.internal_bleeding_debuff]: true, [SpellId.rake_debuff]: true, [SpellId.rend]: true, [SpellId.rip]: true, [SpellId.rupture]: true, [SpellId.thrash_debuff]: true, [SpellId.serrated_bone_spike]: true, }, healing_reduced_debuff: { [8680]: true, // Wound Poison debuff [SpellId.mortal_wounds_debuff]: true, }, stealthed_buff: { [SpellId.incarnation_king_of_the_jungle]: true, [SpellId.prowl]: true, [SpellId.shadowmeld]: true, [SpellId.shadow_dance_buff]: true, [SpellId.stealth]: true, [SpellId.subterfuge_buff]: true, [SpellId.vanish]: true, [11327]: true, // Vanish buff [115191]: true, // Stealth (Subterfuge) [115193]: true, // Vanish buff [347037]: true, // Sepsis debuff }, rogue_stealthed_buff: { [SpellId.stealth]: true, [SpellId.shadow_dance_buff]: true, [SpellId.subterfuge_buff]: true, [SpellId.vanish]: true, [11327]: true, // Vanish buff [115191]: true, // Stealth (Subterfuge) [115193]: true, // Vanish buff [347037]: true, // Sepsis debuff }, mantle_stealthed_buff: { [SpellId.stealth]: true, [SpellId.vanish]: true, [11327]: true, // Vanish buff [115193]: true, // Vanish buff }, burst_haste_buff: { [SpellId.bloodlust]: true, [SpellId.drums_of_deathly_ferocity]: true, [SpellId.drums_of_fury]: true, [SpellId.drums_of_rage]: true, [SpellId.drums_of_the_maelstrom]: true, [SpellId.drums_of_the_mountain]: true, [SpellId.heroism]: true, [SpellId.primal_rage_pet]: true, [SpellId.time_warp]: true, }, burst_haste_debuff: { [SpellId.exhaustion_debuff]: true, [SpellId.sated_debuff]: true, [SpellId.temporal_displacement_debuff]: true, }, raid_movement_buff: { [SpellId.stampeding_roar]: true, [SpellId.wind_rush_buff]: true, }, roll_the_bones_buff: { [SpellId.broadside_buff]: true, [SpellId.buried_treasure_buff]: true, [SpellId.grand_melee_buff]: true, [SpellId.ruthless_precision_buff]: true, [SpellId.skull_and_crossbones_buff]: true, [SpellId.true_bearing_buff]: true, }, lethal_poison_buff: { [SpellId.deadly_poison]: true, [SpellId.instant_poison]: true, [SpellId.wound_poison]: true, }, non_lethal_poison_buff: { [SpellId.crippling_poison]: true, [SpellId.numbing_poison]: true, }, }; constructor(private runner: Runner, ovaleDebug: DebugTools) { for (const [, useName] of pairs(statUseNames)) { let name; for (const [, statName] of pairs(statNames)) { name = `${useName}_${statName}_buff`; this.buffSpellList[name] = {}; const shortName = startShortNames[statName]; if (shortName) { name = `${useName}_${shortName}_buff`; this.buffSpellList[name] = {}; } } name = `${useName}_any_buff`; this.buffSpellList[name] = {}; } { for (const [name] of pairs(this.buffSpellList)) { this.defaultSpellLists[name] = true; } } for (const [k, v] of pairs(this.debugOptions)) { ovaleDebug.defaultOptions.args[k] = v; } } private getSpellDebug(spellId: number) { let [spellName] = GetSpellInfo(spellId); if (!spellName) spellName = "unknown"; let spellDebugName = this.spellDebug[spellName]; if (!spellDebugName) { spellDebugName = {}; this.spellDebug[spellName] = spellDebugName; } let spellDebug = spellDebugName[spellId]; if (!spellDebug) { spellDebug = {}; spellDebugName[spellId] = spellDebug; } return spellDebug; } registerSpellCast(spellId: number) { this.getSpellDebug(spellId).spellCast = true; } registerAuraSeen(spellId: number) { this.getSpellDebug(spellId).auraSeen = true; } registerAuraAsked(spellId: number) { this.getSpellDebug(spellId).auraAsked = true; } registerSpellAsked(spellId: number) { this.getSpellDebug(spellId).spellAsked = true; } defaultSpellLists: LuaObj<boolean> = {}; reset() { wipe(this.itemInfo); wipe(this.spellInfo); for (const [k, v] of pairs(this.buffSpellList)) { if (!this.defaultSpellLists[k]) { wipe(v); delete this.buffSpellList[k]; } else if (truthy(find(k, "^trinket_"))) { wipe(v); } } } getSpellInfo(spellId: number) { let si = this.spellInfo[spellId]; if (!si) { si = { aura: { player: { HELPFUL: {}, HARMFUL: {}, }, target: { HELPFUL: {}, HARMFUL: {}, }, pet: { HELPFUL: {}, HARMFUL: {}, }, damage: { HELPFUL: {}, HARMFUL: {}, }, }, require: {}, }; this.spellInfo[spellId] = si; } return si; } getSpellOrListInfo(spellId: number | string) { if (type(spellId) == "number") { return this.spellInfo[spellId]; } else if (this.buffSpellList[spellId]) { for (const [auraId] of pairs(this.buffSpellList[spellId])) { if (this.spellInfo[auraId]) { return this.spellInfo[auraId]; } } } } getItemInfo(itemId: number) { let ii = this.itemInfo[itemId]; if (!ii) { ii = { require: {}, }; this.itemInfo[itemId] = ii; } return ii; } getItemTagInfo(spellId: number | string): [string, boolean] { return ["cd", false]; } getSpellTagInfo(spellId: number | string): [string, boolean] { let tag: string | undefined = "main"; let invokesGCD = true; const si = this.spellInfo[spellId]; if (si) { invokesGCD = !si.gcd || si.gcd > 0; tag = si.tag; if (!tag) { const cd = si.cd; if (cd) { if (cd > 90) { tag = "cd"; } else if (cd > 29 || !invokesGCD) { tag = "shortcd"; } } else if (!invokesGCD) { tag = "shortcd"; } si.tag = tag; } tag = tag || "main"; } return [tag, invokesGCD]; } checkSpellAuraData( auraId: number | string, spellData: SpellAuraInfo, atTime: number, guid: string | undefined ) { const [, named] = this.runner.computeParameters(spellData, atTime); return named; } // CheckSpellInfo( // spellId: number, // atTime: number, // targetGUID: string | undefined // ): [boolean, string?] { // targetGUID = // targetGUID || // this.ovaleGuid.UnitGUID( // this.baseState.next.defaultTarget || "target" // ); // let verified = true; // let requirement: string | undefined; // for (const [name, handler] of pairs(this.requirement.nowRequirements)) { // let value = this.GetSpellInfoProperty( // spellId, // atTime, // <any>name, // targetGUID // ); // if (value) { // if (!isString(value) && isLuaArray<string>(value)) { // [verified, requirement] = handler( // spellId, // atTime, // name, // value, // 1, // targetGUID // ); // } else { // tempTokens[1] = <string>value; // [verified, requirement] = handler( // spellId, // atTime, // name, // tempTokens, // 1, // targetGUID // ); // } // if (!verified) { // break; // } // } // } // return [verified, requirement]; // } getItemInfoProperty( itemId: number, atTime: number, property: SpellInfoProperty ) { const ii = this.getItemInfo(itemId); if (ii) { return this.getProperty(ii, atTime, property); } return undefined; } //GetSpellInfoProperty(spellId, atTime, property:"gcd"|"duration"|"combopoints"|"inccounter"|"resetcounter", targetGUID):number; /** * * @param spellId * @param atTime * @param property * @param targetGUID * @param noCalculation Checks only SpellInfo and SpellRequire for the property itself. No `add_${property}` or `${property}_percent` * @returns value or [value, ratio] */ getSpellInfoProperty<T extends SpellInfoProperty>( spellId: number, atTime: number | undefined, property: T, targetGUID: string | undefined ): SpellInfo[T] { const si = this.spellInfo[spellId]; if (si) { return this.getProperty(si, atTime, property); } return undefined; } public getProperty<T extends SpellInfoProperty>( si: SpellInfo, atTime: number | undefined, property: T ): SpellInfo[T] { let value = si[property]; if (atTime) { const requirements: | LuaArray<AstSpellRequireNode | AstItemRequireNode> | undefined = si.require[property]; if (requirements) { for (const [_, requirement] of ipairs(requirements)) { const [, named] = this.runner.computeParameters( requirement, atTime ); if (named.enabled === undefined || named.enabled) { if (named.set !== undefined) value = named.set as SpellInfo[T]; if ( named.add !== undefined && isNumber(value) && isNumber(named.add) ) { value = (value + named.add) as SpellInfo[T]; } if ( named.percent !== undefined && isNumber(value) && isNumber(named.percent) ) { value = ((value * named.percent) / 100) as SpellInfo[T]; } } } } } return value; } /** * * @param spellId * @param atTime If undefined, will not check SpellRequire * @param property * @param targetGUID * @param splitRatio Split the value and ratio into separate return values instead of multiplying them together * @returns value or [value, ratio] */ getSpellInfoPropertyNumber( spellId: number, atTime: number | undefined, property: SpellInfoNumberProperty, targetGUID: string | undefined, splitRatio?: boolean ): number[] { const si = this.spellInfo[spellId]; if (!si) return []; const ratioParam = `${property}_percent` as SpellInfoNumberProperty; // TODO TS 4.1 let ratio = this.getProperty(si, atTime, ratioParam); if (ratio !== undefined) { ratio = ratio / 100; } else { ratio = 1; } let value = this.getProperty(si, atTime, property); if (ratio != 0 && value !== undefined) { const addParam = `add_${property}` as SpellInfoNumberProperty; // TODO TS 4.1 const addProperty = this.getProperty(si, atTime, addParam); if (addProperty) { value = value + addProperty; } } else { // If ratio is 0, value must be 0. value = 0; } if (splitRatio) { return [value, ratio]; } return [value * ratio]; } resolveSpell( spellId: number, atTime: number | undefined, targetGUID: string | undefined ): number | undefined { const maxGuard = 20; let guard = 0; let nextId; let id: number | undefined = spellId; while (id && guard < maxGuard) { guard += 1; nextId = id; id = this.getSpellInfoProperty( nextId, atTime, "replaced_by", targetGUID ); } if (guard >= maxGuard) { oneTimeMessage( `Recursive 'replaced_by' chain for spell ID '${spellId}'.` ); } return nextId; } getDamage( spellId: number, attackpower: number, spellpower: number, mainHandWeaponDPS: number, offHandWeaponDPS: number, combopoints: number ): number | undefined { const si = this.spellInfo[spellId]; if (!si) { return undefined; } let damage = si.base || 0; attackpower = attackpower || 0; spellpower = spellpower || 0; mainHandWeaponDPS = mainHandWeaponDPS || 0; offHandWeaponDPS = offHandWeaponDPS || 0; combopoints = combopoints || 0; if (si.bonusmainhand) { damage = damage + si.bonusmainhand * mainHandWeaponDPS; } if (si.bonusoffhand) { damage = damage + si.bonusoffhand * offHandWeaponDPS; } if (si.bonuscp) { damage = damage + si.bonuscp * combopoints; } if (si.bonusap) { damage = damage + si.bonusap * attackpower; } if (si.bonusapcp) { damage = damage + si.bonusapcp * attackpower * combopoints; } if (si.bonussp) { damage = damage + si.bonussp * spellpower; } return damage; } }
the_stack
// Class 00 — Successful Completion export const SUCCESSFUL_COMPLETION = '00000' // Class 01 — Warning export const WARNING = '01000' export const DYNAMIC_RESULT_SETS_RETURNED = '0100C' export const IMPLICIT_ZERO_BIT_PADDING = '01008' export const NULL_VALUE_ELIMINATED_IN_SET_FUNCTION = '01003' export const PRIVILEGE_NOT_GRANTED = '01007' export const PRIVILEGE_NOT_REVOKED = '01006' export const STRING_DATA_RIGHT_TRUNCATION1 = '01004' export const DEPRECATED_FEATURE = '01P01' // Class 02 — No Data (this is also a warning class per the SQL standard) export const NO_DATA = '02000' export const NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED = '02001' // Class 03 — SQL Statement Not Yet Complete export const SQL_STATEMENT_NOT_YET_COMPLETE = '03000' // Class 08 — Connection Exception export const CONNECTION_EXCEPTION = '08000' export const CONNECTION_DOES_NOT_EXIST = '08003' export const CONNECTION_FAILURE = '08006' export const SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION = '08001' export const SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION = '08004' export const TRANSACTION_RESOLUTION_UNKNOWN = '08007' export const PROTOCOL_VIOLATION = '08P01' // Class 09 — Triggered Action Exception export const TRIGGERED_ACTION_EXCEPTION = '09000' // Class 0A — Feature Not Supported export const FEATURE_NOT_SUPPORTED = '0A000' // Class 0B — Invalid Transaction Initiation export const INVALID_TRANSACTION_INITIATION = '0B000' // Class 0F — Locator Exception export const LOCATOR_EXCEPTION = '0F000' export const INVALID_LOCATOR_SPECIFICATION = '0F001' // Class 0L — Invalid Grantor export const INVALID_GRANTOR = '0L000' export const INVALID_GRANT_OPERATION = '0LP01' // Class 0P — Invalid Role Specification export const INVALID_ROLE_SPECIFICATION = '0P000' // Class 0Z — Diagnostics Exception export const DIAGNOSTICS_EXCEPTION = '0Z000' export const STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER = '0Z002' // Class 20 — Case Not Found export const CASE_NOT_FOUND = '20000' // Class 21 — Cardinality Violation export const CARDINALITY_VIOLATION = '21000' // Class 22 — Data Exception export const DATA_EXCEPTION = '22000' export const ARRAY_SUBSCRIPT_ERROR = '2202E' export const CHARACTER_NOT_IN_REPERTOIRE = '22021' export const DATETIME_FIELD_OVERFLOW = '22008' export const DIVISION_BY_ZERO = '22012' export const ERROR_IN_ASSIGNMENT = '22005' export const ESCAPE_CHARACTER_CONFLICT = '2200B' export const INDICATOR_OVERFLOW = '22022' export const INTERVAL_FIELD_OVERFLOW = '22015' export const INVALID_ARGUMENT_FOR_LOGARITHM = '2201E' export const INVALID_ARGUMENT_FOR_NTILE_FUNCTION = '22014' export const INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION = '22016' export const INVALID_ARGUMENT_FOR_POWER_FUNCTION = '2201F' export const INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION = '2201G' export const INVALID_CHARACTER_VALUE_FOR_CAST = '22018' export const INVALID_DATETIME_FORMAT = '22007' export const INVALID_ESCAPE_CHARACTER = '22019' export const INVALID_ESCAPE_OCTET = '2200D' export const INVALID_ESCAPE_SEQUENCE = '22025' export const NONSTANDARD_USE_OF_ESCAPE_CHARACTER = '22P06' export const INVALID_INDICATOR_PARAMETER_VALUE = '22010' export const INVALID_PARAMETER_VALUE = '22023' export const INVALID_REGULAR_EXPRESSION = '2201B' export const INVALID_ROW_COUNT_IN_LIMIT_CLAUSE = '2201W' export const INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE = '2201X' export const INVALID_TIME_ZONE_DISPLACEMENT_VALUE = '22009' export const INVALID_USE_OF_ESCAPE_CHARACTER = '2200C' export const MOST_SPECIFIC_TYPE_MISMATCH = '2200G' export const NULL_VALUE_NOT_ALLOWED1 = '22004' export const NULL_VALUE_NO_INDICATOR_PARAMETER = '22002' export const NUMERIC_VALUE_OUT_OF_RANGE = '22003' export const STRING_DATA_LENGTH_MISMATCH = '22026' export const STRING_DATA_RIGHT_TRUNCATION2 = '22001' export const SUBSTRING_ERROR = '22011' export const TRIM_ERROR = '22027' export const UNTERMINATED_C_STRING = '22024' export const ZERO_LENGTH_CHARACTER_STRING = '2200F' export const FLOATING_POINT_EXCEPTION = '22P01' export const INVALID_TEXT_REPRESENTATION = '22P02' export const INVALID_BINARY_REPRESENTATION = '22P03' export const BAD_COPY_FILE_FORMAT = '22P04' export const UNTRANSLATABLE_CHARACTER = '22P05' export const NOT_AN_XML_DOCUMENT = '2200L' export const INVALID_XML_DOCUMENT = '2200M' export const INVALID_XML_CONTENT = '2200N' export const INVALID_XML_COMMENT = '2200S' export const INVALID_XML_PROCESSING_INSTRUCTION = '2200T' // Class 23 — Integrity Constraint Violation export const INTEGRITY_CONSTRAINT_VIOLATION = '23000' export const RESTRICT_VIOLATION = '23001' export const NOT_NULL_VIOLATION = '23502' export const FOREIGN_KEY_VIOLATION = '23503' export const UNIQUE_VIOLATION = '23505' export const CHECK_VIOLATION = '23514' export const EXCLUSION_VIOLATION = '23P01' // Class 24 — Invalid Cursor State export const INVALID_CURSOR_STATE = '24000' // Class 25 — Invalid Transaction State export const INVALID_TRANSACTION_STATE = '25000' export const ACTIVE_SQL_TRANSACTION = '25001' export const BRANCH_TRANSACTION_ALREADY_ACTIVE = '25002' export const HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL = '25008' export const INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION = '25003' export const INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION = '25004' export const NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION = '25005' export const READ_ONLY_SQL_TRANSACTION = '25006' export const SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED = '25007' export const NO_ACTIVE_SQL_TRANSACTION = '25P01' export const IN_FAILED_SQL_TRANSACTION = '25P02' // Class 26 — Invalid SQL Statement Name export const INVALID_SQL_STATEMENT_NAME = '26000' // Class 27 — Triggered Data Change Violation export const TRIGGERED_DATA_CHANGE_VIOLATION = '27000' // Class 28 — Invalid Authorization Specification export const INVALID_AUTHORIZATION_SPECIFICATION = '28000' export const INVALID_PASSWORD = '28P01' // Class 2B — Dependent Privilege Descriptors Still Exist export const DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST = '2B000' export const DEPENDENT_OBJECTS_STILL_EXIST = '2BP01' // Class 2D — Invalid Transaction Termination export const INVALID_TRANSACTION_TERMINATION = '2D000' // Class 2F — SQL Routine Exception export const SQL_ROUTINE_EXCEPTION = '2F000' export const FUNCTION_EXECUTED_NO_RETURN_STATEMENT = '2F005' export const MODIFYING_SQL_DATA_NOT_PERMITTED1 = '2F002' export const PROHIBITED_SQL_STATEMENT_ATTEMPTED1 = '2F003' export const READING_SQL_DATA_NOT_PERMITTED1 = '2F004' // Class 34 — Invalid Cursor Name export const INVALID_CURSOR_NAME = '34000' // Class 38 — External Routine Exception export const EXTERNAL_ROUTINE_EXCEPTION = '38000' export const CONTAINING_SQL_NOT_PERMITTED = '38001' export const MODIFYING_SQL_DATA_NOT_PERMITTED2 = '38002' export const PROHIBITED_SQL_STATEMENT_ATTEMPTED2 = '38003' export const READING_SQL_DATA_NOT_PERMITTED2 = '38004' // Class 39 — External Routine Invocation Exception export const EXTERNAL_ROUTINE_INVOCATION_EXCEPTION = '39000' export const INVALID_SQLSTATE_RETURNED = '39001' export const NULL_VALUE_NOT_ALLOWED2 = '39004' export const TRIGGER_PROTOCOL_VIOLATED = '39P01' export const SRF_PROTOCOL_VIOLATED = '39P02' // Class 3B — Savepoint Exception export const SAVEPOINT_EXCEPTION = '3B000' export const INVALID_SAVEPOINT_SPECIFICATION = '3B001' // Class 3D — Invalid Catalog Name export const INVALID_CATALOG_NAME = '3D000' // Class 3F — Invalid Schema Name export const INVALID_SCHEMA_NAME = '3F000' // Class 40 — Transaction Rollback export const TRANSACTION_ROLLBACK = '40000' export const TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION = '40002' export const SERIALIZATION_FAILURE = '40001' export const STATEMENT_COMPLETION_UNKNOWN = '40003' export const DEADLOCK_DETECTED = '40P01' // Class 42 — Syntax Error or Access Rule Violation export const SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION = '42000' export const SYNTAX_ERROR = '42601' export const INSUFFICIENT_PRIVILEGE = '42501' export const CANNOT_COERCE = '42846' export const GROUPING_ERROR = '42803' export const WINDOWING_ERROR = '42P20' export const INVALID_RECURSION = '42P19' export const INVALID_FOREIGN_KEY = '42830' export const INVALID_NAME = '42602' export const NAME_TOO_LONG = '42622' export const RESERVED_NAME = '42939' export const DATATYPE_MISMATCH = '42804' export const INDETERMINATE_DATATYPE = '42P18' export const COLLATION_MISMATCH = '42P21' export const INDETERMINATE_COLLATION = '42P22' export const WRONG_OBJECT_TYPE = '42809' export const UNDEFINED_COLUMN = '42703' export const UNDEFINED_FUNCTION = '42883' export const UNDEFINED_TABLE = '42P01' export const UNDEFINED_PARAMETER = '42P02' export const UNDEFINED_OBJECT = '42704' export const DUPLICATE_COLUMN = '42701' export const DUPLICATE_CURSOR = '42P03' export const DUPLICATE_DATABASE = '42P04' export const DUPLICATE_FUNCTION = '42723' export const DUPLICATE_PREPARED_STATEMENT = '42P05' export const DUPLICATE_SCHEMA = '42P06' export const DUPLICATE_TABLE = '42P07' export const DUPLICATE_ALIAS = '42712' export const DUPLICATE_OBJECT = '42710' export const AMBIGUOUS_COLUMN = '42702' export const AMBIGUOUS_FUNCTION = '42725' export const AMBIGUOUS_PARAMETER = '42P08' export const AMBIGUOUS_ALIAS = '42P09' export const INVALID_COLUMN_REFERENCE = '42P10' export const INVALID_COLUMN_DEFINITION = '42611' export const INVALID_CURSOR_DEFINITION = '42P11' export const INVALID_DATABASE_DEFINITION = '42P12' export const INVALID_FUNCTION_DEFINITION = '42P13' export const INVALID_PREPARED_STATEMENT_DEFINITION = '42P14' export const INVALID_SCHEMA_DEFINITION = '42P15' export const INVALID_TABLE_DEFINITION = '42P16' export const INVALID_OBJECT_DEFINITION = '42P17' // Class 44 — WITH CHECK OPTION Violation export const WITH_CHECK_OPTION_VIOLATION = '44000' // Class 53 — Insufficient Resources export const INSUFFICIENT_RESOURCES = '53000' export const DISK_FULL = '53100' export const OUT_OF_MEMORY = '53200' export const TOO_MANY_CONNECTIONS = '53300' export const CONFIGURATION_LIMIT_EXCEEDED = '53400' // Class 54 — Program Limit Exceeded export const PROGRAM_LIMIT_EXCEEDED = '54000' export const STATEMENT_TOO_COMPLEX = '54001' export const TOO_MANY_COLUMNS = '54011' export const TOO_MANY_ARGUMENTS = '54023' // Class 55 — Object Not In Prerequisite State export const OBJECT_NOT_IN_PREREQUISITE_STATE = '55000' export const OBJECT_IN_USE = '55006' export const CANT_CHANGE_RUNTIME_PARAM = '55P02' export const LOCK_NOT_AVAILABLE = '55P03' // Class 57 — Operator Intervention export const OPERATOR_INTERVENTION = '57000' export const QUERY_CANCELED = '57014' export const ADMIN_SHUTDOWN = '57P01' export const CRASH_SHUTDOWN = '57P02' export const CANNOT_CONNECT_NOW = '57P03' export const DATABASE_DROPPED = '57P04' // Class 58 — System Error (errors external to PostgreSQL itself) export const SYSTEM_ERROR = '58000' export const IO_ERROR = '58030' export const UNDEFINED_FILE = '58P01' export const DUPLICATE_FILE = '58P02' // Class F0 — Configuration File Error export const CONFIG_FILE_ERROR = 'F0000' export const LOCK_FILE_EXISTS = 'F0001' // Class HV — Foreign Data Wrapper Error (SQL/MED) export const FDW_ERROR = 'HV000' export const FDW_COLUMN_NAME_NOT_FOUND = 'HV005' export const FDW_DYNAMIC_PARAMETER_VALUE_NEEDED = 'HV002' export const FDW_FUNCTION_SEQUENCE_ERROR = 'HV010' export const FDW_INCONSISTENT_DESCRIPTOR_INFORMATION = 'HV021' export const FDW_INVALID_ATTRIBUTE_VALUE = 'HV024' export const FDW_INVALID_COLUMN_NAME = 'HV007' export const FDW_INVALID_COLUMN_NUMBER = 'HV008' export const FDW_INVALID_DATA_TYPE = 'HV004' export const FDW_INVALID_DATA_TYPE_DESCRIPTORS = 'HV006' export const FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER = 'HV091' export const FDW_INVALID_HANDLE = 'HV00B' export const FDW_INVALID_OPTION_INDEX = 'HV00C' export const FDW_INVALID_OPTION_NAME = 'HV00D' export const FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH = 'HV090' export const FDW_INVALID_STRING_FORMAT = 'HV00A' export const FDW_INVALID_USE_OF_NULL_POINTER = 'HV009' export const FDW_TOO_MANY_HANDLES = 'HV014' export const FDW_OUT_OF_MEMORY = 'HV001' export const FDW_NO_SCHEMAS = 'HV00P' export const FDW_OPTION_NAME_NOT_FOUND = 'HV00J' export const FDW_REPLY_HANDLE = 'HV00K' export const FDW_SCHEMA_NOT_FOUND = 'HV00Q' export const FDW_TABLE_NOT_FOUND = 'HV00R' export const FDW_UNABLE_TO_CREATE_EXECUTION = 'HV00L' export const FDW_UNABLE_TO_CREATE_REPLY = 'HV00M' export const FDW_UNABLE_TO_ESTABLISH_CONNECTION = 'HV00N' // Class P0 — PL/pgSQL Error export const PLPGSQL_ERROR = 'P0000' export const RAISE_EXCEPTION = 'P0001' export const NO_DATA_FOUND = 'P0002' export const TOO_MANY_ROWS = 'P0003' // Class XX — Internal Error export const INTERNAL_ERROR = 'XX000' export const DATA_CORRUPTED = 'XX001' export const INDEX_CORRUPTED = 'XX002'
the_stack
import { autoinject } from 'aurelia-dependency-injection'; import { SessionService, SessionPort } from './session'; import { Event, getEntityPositionInReferenceFrame, getEntityOrientationInReferenceFrame, getSerializedEntityState, jsonEquals } from './utils'; import { SerializedEntityState, SerializedEntityStateMap } from './common'; import { PermissionServiceProvider } from './permission' import { defined, Cartesian3, Cartographic, Entity, EntityCollection, ConstantPositionProperty, ConstantProperty, JulianDate, Matrix3, Matrix4, ReferenceFrame, ReferenceEntity, Transforms, Quaternion } from './cesium/cesium-imports' /** * Represents the pose of an entity relative to a particular reference frame. * * The `update` method must be called in order to update the position / orientation / poseStatus. */ export class EntityPose { constructor( private _collection:EntityCollection, entityOrId:Entity|string, referenceFrameId:Entity|ReferenceFrame|string ){ if (typeof entityOrId === 'string') { let entity:Entity|ReferenceEntity|undefined = this._collection.getById(entityOrId); if (!entity) entity = <Entity><any> new ReferenceEntity(this._collection, entityOrId); this._entity = entity; } else { this._entity = entityOrId; } if (typeof referenceFrameId === 'string') { let referenceFrame:Entity|ReferenceEntity|ReferenceFrame|undefined = this._collection.getById(referenceFrameId); if (!defined(referenceFrame)) referenceFrame = <Entity><any> new ReferenceEntity(this._collection, referenceFrameId); this._referenceFrame = referenceFrame; } else { this._referenceFrame = referenceFrameId; } } private _entity:Entity; private _referenceFrame:Entity|ReferenceFrame; get entity() { return this._entity } get referenceFrame() { return this._referenceFrame; } /** * The status of this pose, as a bitmask. * * If the current pose is known, then the KNOWN bit is 1. * If the current pose is not known, then the KNOWN bit is 0. * * If the previous pose was known and the current pose is unknown, * then the LOST bit is 1. * If the previous pose was unknown and the current pose status is known, * then the FOUND bit is 1. * In all other cases, both the LOST bit and the FOUND bit are 0. */ status:PoseStatus = 0; /** * alias for status */ get poseStatus() { return this.status }; position = new Cartesian3; orientation = new Quaternion; time = new JulianDate(0,0) private _previousTime:JulianDate; private _previousStatus:PoseStatus = 0; private _getEntityPositionInReferenceFrame = getEntityPositionInReferenceFrame; private _getEntityOrientationInReferenceFrame = getEntityOrientationInReferenceFrame; update(time:JulianDate) { const _JulianDate = JulianDate; const _PoseStatus = PoseStatus; _JulianDate.clone(time, this.time); if (!_JulianDate.equals(this._previousTime, time)) { this._previousStatus = this.status; this._previousTime = _JulianDate.clone(time, this._previousTime) } const entity = this.entity; const referenceFrame = this.referenceFrame; let position = this._getEntityPositionInReferenceFrame( entity, time, referenceFrame, this.position ); let orientation = this._getEntityOrientationInReferenceFrame( entity, time, referenceFrame, this.orientation ); const hasPose = position && orientation; let currentStatus: PoseStatus = 0; const previousStatus = this._previousStatus; if (hasPose) { currentStatus |= _PoseStatus.KNOWN; } if (hasPose && !(previousStatus & _PoseStatus.KNOWN)) { currentStatus |= _PoseStatus.FOUND; } else if (!hasPose && previousStatus & _PoseStatus.KNOWN) { currentStatus |= _PoseStatus.LOST; } this.status = currentStatus; } } /** * A bitmask that provides metadata about the pose of an EntityPose. * KNOWN - the pose of the entity state is defined. * KNOWN & FOUND - the pose was undefined when the entity state was last queried, and is now defined. * LOST - the pose was defined when the entity state was last queried, and is now undefined */ export enum PoseStatus { KNOWN = 1, FOUND = 2, LOST = 4 } /** * A service for subscribing/unsubscribing to entities */ @autoinject() export class EntityService { constructor(protected sessionService: SessionService) {} public collection = new EntityCollection; public subscribedEvent = new Event<{id:string, options?:{}}>(); public unsubscribedEvent = new Event<{id:string}>(); public subscriptions = new Map<string, {}>(); private _handleSubscribed(evt:{id:string, options?:{}}) { const s = this.subscriptions.get(evt.id); const stringifiedOptions = evt.options && JSON.stringify(evt.options); if (!s || JSON.stringify(s) === stringifiedOptions) { if (s) this._handleUnsubscribed(evt.id); this.subscriptions.set(evt.id, stringifiedOptions && JSON.parse(stringifiedOptions)); this.subscribedEvent.raiseEvent(evt); }; } private _handleUnsubscribed(id:string) { if (this.subscriptions.has(id)) { this.subscriptions.delete(id); this.unsubscribedEvent.raiseEvent({id}); }; } private _scratchCartesian = new Cartesian3; private _scratchQuaternion = new Quaternion; private _scratchMatrix3 = new Matrix3; private _scratchMatrix4 = new Matrix4; private _getEntityPositionInReferenceFrame = getEntityPositionInReferenceFrame; /** * Get the cartographic position of an Entity at the given time */ public getCartographic(entity:Entity, time:JulianDate, result?:Cartographic) : Cartographic|undefined { const fixedPosition = this._getEntityPositionInReferenceFrame(entity, time, ReferenceFrame.FIXED, this._scratchCartesian); if (fixedPosition) { result = result || new Cartographic(); return Cartographic.fromCartesian(fixedPosition, undefined, result); } return undefined; } /** * Create an entity that is positioned at the given cartographic location, * with an orientation computed according to the provided `localToFixed` transform function. * * For the `localToFixed` parameter, you can pass any of the following: * * ``` * Argon.Cesium.Transforms.eastNorthUpToFixedFrame * Argon.Cesium.Transforms.northEastDownToFixedFrame * Argon.Cesium.Transforms.northUpEastToFixedFrame * Argon.Cesium.Transforms.northWestUpToFixedFrame * ``` * * Additionally, argon.js provides: * * ``` * Argon.eastUpSouthToFixedFrame * ``` * * Alternative transform functions can be created with: * * ``` * Argon.Cesium.Transforms.localFrameToFixedFrameGenerator * ``` */ public createFixed(cartographic: Cartographic, localToFixed: typeof Transforms.northUpEastToFixedFrame) : Entity { // Convert the cartographic location to an ECEF position var position = Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height, undefined, this._scratchCartesian); // compute an appropriate orientation on the surface of the earth var transformMatrix = localToFixed(position, undefined, this._scratchMatrix4); var rotationMatrix = Matrix4.getRotation(transformMatrix,this._scratchMatrix3) var orientation = Quaternion.fromRotationMatrix(rotationMatrix, this._scratchQuaternion); // create the entity var entity = new Entity({ position, orientation }); return entity; } /** * Subscribe to pose updates for the given entity id * @returns A Promise that resolves to a new or existing entity */ public subscribe(idOrEntity: string|Entity) : Promise<Entity>; public subscribe(idOrEntity: string|Entity, options?:{}, session?:SessionPort) : Promise<Entity>; public subscribe(idOrEntity: string|Entity, options?:{}, session=this.sessionService.manager) : Promise<Entity> { const id = (<Entity>idOrEntity).id || <string>idOrEntity; const evt = {id, options}; return session.whenConnected().then(()=>{ if (session.version[0] === 0 && session.version[1] < 2) return session.request('ar.context.subscribe', evt) else return session.request('ar.entity.subscribe', evt) }).then(()=>{ const entity = this.collection.getOrCreateEntity(id); this._handleSubscribed(evt); return entity; }); } /** * Unsubscribe from pose updates for the given entity id */ public unsubscribe(idOrEntity) : void; public unsubscribe(idOrEntity: string|Entity, session?:SessionPort) : void; public unsubscribe(idOrEntity: string|Entity, session=this.sessionService.manager) : void { const id = (<Entity>idOrEntity).id || <string>idOrEntity; session.whenConnected().then(()=>{ if (session.version[0] === 0 && session.version[1] < 2) session.send('ar.context.unsubscribe', {id}); else session.send('ar.entity.unsubscribe', {id}); }).then(()=>{ this._handleUnsubscribed(id); }) } /** * Create a new EntityPose instance to represent the pose of an entity * relative to a given reference frame. If no reference frame is specified, * then the pose is based on the context's defaultReferenceFrame. * * @param entity - the entity to track * @param referenceFrameOrId - the reference frame to use */ public createEntityPose(entityOrId: Entity|string, referenceFrameOrId: string | ReferenceFrame | Entity) { return new EntityPose(this.collection, entityOrId, referenceFrameOrId); } /** * * @param id * @param entityState */ public updateEntityFromSerializedState(id:string, entityState:SerializedEntityState|null) { const entity = this.collection.getOrCreateEntity(id); if (!entityState) { if (entity.position) { (entity.position as ConstantPositionProperty).setValue(undefined); } if (entity.orientation) { (entity.orientation as ConstantProperty).setValue(undefined); } entity['meta'] = undefined; return entity; } const positionValue = entityState.p; const orientationValue = Quaternion.clone(entityState.o, this._scratchQuaternion); // workaround for https://github.com/AnalyticalGraphicsInc/cesium/issues/5031 const referenceFrame:Entity|ReferenceFrame = typeof entityState.r === 'number' ? entityState.r : this.collection.getOrCreateEntity(entityState.r); let entityPosition = entity.position; let entityOrientation = entity.orientation; if (entityPosition instanceof ConstantPositionProperty) { entityPosition.setValue(positionValue, referenceFrame); } else { entity.position = new ConstantPositionProperty(positionValue, referenceFrame); } if (entityOrientation instanceof ConstantProperty) { entityOrientation.setValue(orientationValue); } else { entity.orientation = new ConstantProperty(orientationValue); } entity['meta'] = entityState.meta; return entity; } } /** * A service for publishing entity states to managed sessions */ @autoinject export class EntityServiceProvider { public subscriptionsBySubscriber = new WeakMap<SessionPort, Map<string,{}|undefined>>(); public subscribersByEntity = new Map<string, Set<SessionPort>>(); public sessionSubscribedEvent = new Event<{session:SessionPort, id:string, options:{}}>(); public sessionUnsubscribedEvent = new Event<{session:SessionPort, id:string}>(); public targetReferenceFrameMap = new Map<string, string|ReferenceFrame>(); constructor( private sessionService: SessionService, private entityService: EntityService, private permissionServiceProvider: PermissionServiceProvider ) { this.sessionService.ensureIsRealityManager(); this.sessionService.connectEvent.addEventListener((session) => { const subscriptions = new Map<string, {}|undefined>(); this.subscriptionsBySubscriber.set(session, subscriptions); session.on['ar.entity.subscribe'] = session.on['ar.context.subscribe'] = ({id, options}:{id:string, options:any}) => { const currentOptions = subscriptions.get(id); if (currentOptions && jsonEquals(currentOptions,options)) return; const subscribers = this.subscribersByEntity.get(id) || new Set<SessionPort>(); this.subscribersByEntity.set(id, subscribers); subscribers.add(session); subscriptions.set(id,options); this.sessionSubscribedEvent.raiseEvent({session, id, options}); return this.permissionServiceProvider.handlePermissionRequest(session, id, options).then(()=>{}); } session.on['ar.entity.unsubscribe'] = session.on['ar.context.unsubscribe'] = ({id}:{id:string}) => { if (!subscriptions.has(id)) return; const subscribers = this.subscribersByEntity.get(id); subscribers && subscribers.delete(session); subscriptions.delete(id); this.sessionUnsubscribedEvent.raiseEvent({id, session}); } session.closeEvent.addEventListener(()=>{ this.subscriptionsBySubscriber.delete(session); subscriptions.forEach((options, id)=>{ const subscribers = this.subscribersByEntity.get(id); subscribers && subscribers.delete(session); this.sessionUnsubscribedEvent.raiseEvent({id, session}); }); }) }); } public fillEntityStateMapForSession(session:SessionPort, time:JulianDate, entities:SerializedEntityStateMap) { const subscriptions = this.subscriptionsBySubscriber.get(session); if (!subscriptions) return; const iter = subscriptions.keys(); let item:IteratorResult<string>; while (item = iter.next(), !item.done) { // not using for-of since typescript converts this to broken es5 const id = item.value; const entity = this.entityService.collection.getById(id); entities[id] = entity ? this.getCachedSerializedEntityState(entity, time) : null; } } private _cacheTime = new JulianDate(0,0) private _entityPoseCache: SerializedEntityStateMap = {}; private _getSerializedEntityState = getSerializedEntityState; public getCachedSerializedEntityState(entity: Entity|undefined, time: JulianDate) { if (!entity) return null; const id = entity.id; if (!defined(this._entityPoseCache[id]) || !this._cacheTime.equalsEpsilon(time, 0.000001)) { const referenceFrameId = this.targetReferenceFrameMap.get(id); const referenceFrame = defined(referenceFrameId) && typeof referenceFrameId === 'string' ? this.entityService.collection.getById(referenceFrameId) : defined(referenceFrameId) ? referenceFrameId : this.entityService.collection.getById('ar.stage'); this._entityPoseCache[id] = this._getSerializedEntityState(entity, time, referenceFrame); } return this._entityPoseCache[id]; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { DataCollectionEndpoints } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { MonitorClient } from "../monitorClient"; import { DataCollectionEndpointResource, DataCollectionEndpointsListByResourceGroupNextOptionalParams, DataCollectionEndpointsListByResourceGroupOptionalParams, DataCollectionEndpointsListBySubscriptionNextOptionalParams, DataCollectionEndpointsListBySubscriptionOptionalParams, DataCollectionEndpointsListByResourceGroupResponse, DataCollectionEndpointsListBySubscriptionResponse, DataCollectionEndpointsGetOptionalParams, DataCollectionEndpointsGetResponse, DataCollectionEndpointsCreateOptionalParams, DataCollectionEndpointsCreateResponse, DataCollectionEndpointsUpdateOptionalParams, DataCollectionEndpointsUpdateResponse, DataCollectionEndpointsDeleteOptionalParams, DataCollectionEndpointsListByResourceGroupNextResponse, DataCollectionEndpointsListBySubscriptionNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing DataCollectionEndpoints operations. */ export class DataCollectionEndpointsImpl implements DataCollectionEndpoints { private readonly client: MonitorClient; /** * Initialize a new instance of the class DataCollectionEndpoints class. * @param client Reference to the service client */ constructor(client: MonitorClient) { this.client = client; } /** * Lists all data collection endpoints in the specified resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: DataCollectionEndpointsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<DataCollectionEndpointResource> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: DataCollectionEndpointsListByResourceGroupOptionalParams ): AsyncIterableIterator<DataCollectionEndpointResource[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: DataCollectionEndpointsListByResourceGroupOptionalParams ): AsyncIterableIterator<DataCollectionEndpointResource> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Lists all data collection endpoints in the specified subscription * @param options The options parameters. */ public listBySubscription( options?: DataCollectionEndpointsListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<DataCollectionEndpointResource> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: DataCollectionEndpointsListBySubscriptionOptionalParams ): AsyncIterableIterator<DataCollectionEndpointResource[]> { let result = await this._listBySubscription(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listBySubscriptionNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listBySubscriptionPagingAll( options?: DataCollectionEndpointsListBySubscriptionOptionalParams ): AsyncIterableIterator<DataCollectionEndpointResource> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Lists all data collection endpoints in the specified resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: DataCollectionEndpointsListByResourceGroupOptionalParams ): Promise<DataCollectionEndpointsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Lists all data collection endpoints in the specified subscription * @param options The options parameters. */ private _listBySubscription( options?: DataCollectionEndpointsListBySubscriptionOptionalParams ): Promise<DataCollectionEndpointsListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * Returns the specified data collection endpoint. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param dataCollectionEndpointName The name of the data collection endpoint. The name is case * insensitive. * @param options The options parameters. */ get( resourceGroupName: string, dataCollectionEndpointName: string, options?: DataCollectionEndpointsGetOptionalParams ): Promise<DataCollectionEndpointsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, dataCollectionEndpointName, options }, getOperationSpec ); } /** * Creates or updates a data collection endpoint. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param dataCollectionEndpointName The name of the data collection endpoint. The name is case * insensitive. * @param options The options parameters. */ create( resourceGroupName: string, dataCollectionEndpointName: string, options?: DataCollectionEndpointsCreateOptionalParams ): Promise<DataCollectionEndpointsCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, dataCollectionEndpointName, options }, createOperationSpec ); } /** * Updates part of a data collection endpoint. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param dataCollectionEndpointName The name of the data collection endpoint. The name is case * insensitive. * @param options The options parameters. */ update( resourceGroupName: string, dataCollectionEndpointName: string, options?: DataCollectionEndpointsUpdateOptionalParams ): Promise<DataCollectionEndpointsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, dataCollectionEndpointName, options }, updateOperationSpec ); } /** * Deletes a data collection endpoint. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param dataCollectionEndpointName The name of the data collection endpoint. The name is case * insensitive. * @param options The options parameters. */ delete( resourceGroupName: string, dataCollectionEndpointName: string, options?: DataCollectionEndpointsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, dataCollectionEndpointName, options }, deleteOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: DataCollectionEndpointsListByResourceGroupNextOptionalParams ): Promise<DataCollectionEndpointsListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListBySubscriptionNext * @param nextLink The nextLink from the previous successful call to the ListBySubscription method. * @param options The options parameters. */ private _listBySubscriptionNext( nextLink: string, options?: DataCollectionEndpointsListBySubscriptionNextOptionalParams ): Promise<DataCollectionEndpointsListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listBySubscriptionNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResourceListResult }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/dataCollectionEndpoints", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResourceListResult }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, queryParameters: [Parameters.apiVersion12], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResource }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.dataCollectionEndpointName ], headerParameters: [Parameters.accept], serializer }; const createOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResource }, 201: { bodyMapper: Mappers.DataCollectionEndpointResource }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, requestBody: Parameters.body, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.dataCollectionEndpointName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResource }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, requestBody: Parameters.body1, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.dataCollectionEndpointName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/dataCollectionEndpoints/{dataCollectionEndpointName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.dataCollectionEndpointName ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResourceListResult }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DataCollectionEndpointResourceListResult }, default: { bodyMapper: Mappers.ErrorResponseCommonV2 } }, queryParameters: [Parameters.apiVersion12], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import SecuredField from './SecuredField'; import { AriaConfig, CVCPolicyType, DatePolicyType } from './AbstractSecuredField'; import Language from '../../../../../language/Language'; import LANG from '../../../../../language/locales/en-US.json'; import { ERROR_CODES, ERROR_MSG_CARD_TOO_OLD, ERROR_MSG_INVALID_FIELD, ERROR_MSG_LUHN_CHECK_FAILED } from '../../../../../core/Errors/constants'; import { ERROR_MSG_INCOMPLETE_FIELD } from '../../../../../core/Errors/constants'; import { CVC_POLICY_REQUIRED, DATE_POLICY_REQUIRED } from '../configuration/constants'; const ENCRYPTED_CARD_NUMBER = 'encryptedCardNumber'; const ENCRYPTED_EXPIRY_DATE = 'encryptedExpiryDate'; const ENCRYPTED_SECURITY_CODE = 'encryptedSecurityCode'; export const ENCRYPTED_SECURITY_CODE_3_DIGITS = 'encryptedSecurityCode3digits'; export const ENCRYPTED_SECURITY_CODE_4_DIGITS = 'encryptedSecurityCode4digits'; const TRANSLATED_NUMBER_IFRAME_TITLE = LANG['creditCard.encryptedCardNumber.aria.iframeTitle']; const TRANSLATED_NUMBER_IFRAME_LABEL = LANG['creditCard.encryptedCardNumber.aria.label']; const TRANSLATED_DATE_IFRAME_TITLE = LANG['creditCard.encryptedExpiryDate.aria.iframeTitle']; const TRANSLATED_DATE_IFRAME_LABEL = LANG['creditCard.encryptedExpiryDate.aria.label']; const TRANSLATED_CVC_IFRAME_TITLE = LANG['creditCard.encryptedSecurityCode.aria.iframeTitle']; const TRANSLATED_CVC_IFRAME_LABEL = LANG['creditCard.encryptedSecurityCode.aria.label']; const GENERAL_ERROR_CODE = ERROR_CODES[ERROR_MSG_INCOMPLETE_FIELD]; const CARD_TOO_OLD_ERROR_CODE = ERROR_CODES[ERROR_MSG_CARD_TOO_OLD]; const TRANSLATED_INCOMPLETE_FIELD_ERROR = LANG[GENERAL_ERROR_CODE]; const TRANSLATED_CARD_TOO_OLD_ERROR = LANG[CARD_TOO_OLD_ERROR_CODE]; const TRANSLATED_NUMBER_PLACEHOLDER = LANG['creditCard.numberField.placeholder']; const TRANSLATED_DATE_PLACEHOLDER = LANG['creditCard.expiryDateField.placeholder']; const TRANSLATED_CVC_PLACEHOLDER_3_DIGITS = LANG['creditCard.cvcField.placeholder.3digits']; const TRANSLATED_CVC_PLACEHOLDER_4_DIGITS = LANG['creditCard.cvcField.placeholder.4digits']; const nodeHolder = document.createElement('div'); let i18n = new Language('en-US', {}); const iframeUIConfig = { placeholders: null, sfStyles: null, ariaConfig: {} }; const setupObj = { extraFieldData: null, txVariant: 'card', cardGroupTypes: ['amex', 'mc', 'visa'], iframeUIConfig, sfLogAtStart: false, trimTrailingSeparator: false, isCreditCardType: true, showWarnings: false, // fieldType: ENCRYPTED_CARD_NUMBER, cvcPolicy: CVC_POLICY_REQUIRED as CVCPolicyType, datePolicy: DATE_POLICY_REQUIRED as DatePolicyType, iframeSrc: null, loadingContext: null, holderEl: nodeHolder, legacyInputMode: null, minimumExpiryDate: null, uid: null, implementationType: null }; /** * AriaConfig */ describe('SecuredField handling ariaConfig object - should set defaults', () => { // test('Card number field should get translated title, label & error props plus a lang prop that equals the i18n.locale', () => { const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].iframeTitle).toEqual(TRANSLATED_NUMBER_IFRAME_TITLE); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].label).toEqual(TRANSLATED_NUMBER_IFRAME_LABEL); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].error[GENERAL_ERROR_CODE]).toEqual(TRANSLATED_INCOMPLETE_FIELD_ERROR); expect(card.config.iframeUIConfig.ariaConfig.lang).toEqual(i18n.locale); // = 'en-US' }); test('Date field should get translated title, label & error props plus a lang prop that equals the i18n.locale', () => { setupObj.fieldType = ENCRYPTED_EXPIRY_DATE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE].iframeTitle).toEqual(TRANSLATED_DATE_IFRAME_TITLE); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE].label).toEqual(TRANSLATED_DATE_IFRAME_LABEL); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE].error[GENERAL_ERROR_CODE]).toEqual(TRANSLATED_INCOMPLETE_FIELD_ERROR); expect(card.config.iframeUIConfig.ariaConfig.lang).toEqual(i18n.locale); }); test('CVC field should get translated title, label & error props plus a lang prop that equals the i18n.locale', () => { setupObj.fieldType = ENCRYPTED_SECURITY_CODE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_SECURITY_CODE].iframeTitle).toEqual(TRANSLATED_CVC_IFRAME_TITLE); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_SECURITY_CODE].label).toEqual(TRANSLATED_CVC_IFRAME_LABEL); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_SECURITY_CODE].error[GENERAL_ERROR_CODE]).toEqual(TRANSLATED_INCOMPLETE_FIELD_ERROR); expect(card.config.iframeUIConfig.ariaConfig.lang).toEqual(i18n.locale); }); }); describe('SecuredField handling ariaConfig object - should trim the config object to match the field', () => { // test('Card number field with default ariaConfig should only have a property related to the cardNumber and nothing for date or cvc', () => { setupObj.fieldType = ENCRYPTED_CARD_NUMBER; setupObj.iframeUIConfig.ariaConfig = {}; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER]).not.toBe(undefined); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE]).toBe(undefined); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_SECURITY_CODE]).toBe(undefined); }); test('cvc field, with default ariaConfig, should only have a property related to the cvc and nothing for date or number', () => { setupObj.fieldType = ENCRYPTED_SECURITY_CODE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_SECURITY_CODE]).not.toBe(undefined); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER]).toBe(undefined); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE]).toBe(undefined); }); test('Card number field with default ariaConfig should have an error object containing certain keys relating to securedFields', () => { setupObj.fieldType = ENCRYPTED_CARD_NUMBER; setupObj.iframeUIConfig.ariaConfig = {}; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].error[GENERAL_ERROR_CODE]).not.toBe(undefined); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].error[ERROR_CODES[ERROR_MSG_LUHN_CHECK_FAILED]]).not.toBe(undefined); // non sf-related key should not be present expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].error[ERROR_CODES[ERROR_MSG_INVALID_FIELD]]).toBe(undefined); }); test('date field, with default ariaConfig, should have expected, translated, error strings', () => { setupObj.fieldType = ENCRYPTED_EXPIRY_DATE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE].error[GENERAL_ERROR_CODE]).toEqual(TRANSLATED_INCOMPLETE_FIELD_ERROR); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_EXPIRY_DATE].error[ERROR_CODES[ERROR_MSG_CARD_TOO_OLD]]).toEqual( TRANSLATED_CARD_TOO_OLD_ERROR ); }); test('Card number field with default ariaConfig should have an error object containing certain keys whose values are the correct translations', () => { setupObj.fieldType = ENCRYPTED_CARD_NUMBER; setupObj.iframeUIConfig.ariaConfig = {}; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].error[GENERAL_ERROR_CODE]).toEqual(i18n.get(GENERAL_ERROR_CODE)); const errorCode = ERROR_CODES[ERROR_MSG_LUHN_CHECK_FAILED]; expect(card.config.iframeUIConfig.ariaConfig[ENCRYPTED_CARD_NUMBER].error[errorCode]).toEqual(i18n.get(errorCode)); }); }); /** * Placeholders */ describe('SecuredField handling undefined placeholders config object - should set defaults', () => { // test('Card number field with no defined placeholders config should get default value from translation field', () => { setupObj.fieldType = ENCRYPTED_CARD_NUMBER; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toEqual(TRANSLATED_NUMBER_PLACEHOLDER); // Placeholders object should only contain a value for cardNumber expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_EXPIRY_DATE]).toBe(undefined); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE]).toBe(undefined); }); test('Date field with no defined placeholders config should get default value from translation field', () => { setupObj.fieldType = ENCRYPTED_EXPIRY_DATE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_EXPIRY_DATE]).toEqual(TRANSLATED_DATE_PLACEHOLDER); }); test('CVC field with no defined placeholders config should get default values from translation field', () => { setupObj.fieldType = ENCRYPTED_SECURITY_CODE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_3_DIGITS]).toEqual(TRANSLATED_CVC_PLACEHOLDER_3_DIGITS); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_4_DIGITS]).toEqual(TRANSLATED_CVC_PLACEHOLDER_4_DIGITS); }); }); describe('SecuredField handling placeholders config object that is set to null or {} - should set defaults', () => { // test('Card number field with a placeholders config set to null should get default value from translation field', () => { setupObj.iframeUIConfig.placeholders = null; setupObj.fieldType = ENCRYPTED_CARD_NUMBER; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toEqual(TRANSLATED_NUMBER_PLACEHOLDER); }); test('Date field with a placeholders config set to an empty object should get default value from translation field', () => { setupObj.iframeUIConfig.placeholders = {}; setupObj.fieldType = ENCRYPTED_EXPIRY_DATE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_EXPIRY_DATE]).toEqual(TRANSLATED_DATE_PLACEHOLDER); // Placeholders object should only contain a value for expiryDate expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toBe(undefined); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_3_DIGITS]).toBe(undefined); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_4_DIGITS]).toBe(undefined); }); test('CVC field with a placeholders config set to null should get default values from translation field', () => { setupObj.iframeUIConfig.placeholders = null; setupObj.fieldType = ENCRYPTED_SECURITY_CODE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_3_DIGITS]).toEqual(TRANSLATED_CVC_PLACEHOLDER_3_DIGITS); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_4_DIGITS]).toEqual(TRANSLATED_CVC_PLACEHOLDER_4_DIGITS); // Placeholders object should only contain a value for cvc field expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toBe(undefined); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_EXPIRY_DATE]).toBe(undefined); }); }); describe('SecuredField handling placeholders overridden with translations config object - overridden placeholders should be used', () => { // test('Card number field with overridden placeholder should use that value', () => { // expect.assertions(1); i18n = new Language('en-US', { 'en-US': { 'creditCard.numberField.placeholder': '9999 9999 9999 9999', 'creditCard.expiryDateField.placeholder': 'mo/ye', 'creditCard.cvcField.placeholder.3digits': 'digits3', 'creditCard.cvcField.placeholder.4digits': 'digits4' } }); i18n.loaded.then(() => { setupObj.fieldType = ENCRYPTED_CARD_NUMBER; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toEqual('9999 9999 9999 9999'); }); }); test('Date field with overridden placeholder should use that value', () => { setupObj.fieldType = ENCRYPTED_EXPIRY_DATE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_EXPIRY_DATE]).toEqual('mo/ye'); }); test('CVC field with overridden placeholders should use those values', () => { setupObj.fieldType = ENCRYPTED_SECURITY_CODE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_3_DIGITS]).toEqual('digits3'); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_4_DIGITS]).toEqual('digits4'); // Placeholders object should only contain a value for cvc expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toBe(undefined); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_EXPIRY_DATE]).toBe(undefined); }); // Setting empty placeholder test('Card number field with overridden placeholder set to an empty string should use that value', () => { i18n = new Language('en-US', { 'en-US': { 'creditCard.numberField.placeholder': '', 'creditCard.expiryDateField.placeholder': '', 'creditCard.cvcField.placeholder.3digits': '', 'creditCard.cvcField.placeholder.4digits': '' } }); i18n.loaded.then(() => { setupObj.fieldType = ENCRYPTED_CARD_NUMBER; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_CARD_NUMBER]).toEqual(''); }); }); test('CVC field with overridden placeholders set to an empty string should use those values', () => { setupObj.fieldType = ENCRYPTED_SECURITY_CODE; const card = new SecuredField(setupObj, i18n); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_3_DIGITS]).toEqual(''); expect(card.config.iframeUIConfig.placeholders[ENCRYPTED_SECURITY_CODE_4_DIGITS]).toEqual(''); }); });
the_stack
import { TemplateHandler } from 'src/templateHandler'; import { readFixture } from './fixtureUtils'; describe('loop fixtures', () => { it("replaces paragraph loops correctly", async () => { const handler = new TemplateHandler(); const template = readFixture('loop - simple.docx'); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop_prop}{simple_prop}!{/loop_prop}"); const data = { loop_prop: [ { simple_prop: 'first' }, { simple_prop: 'second' } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("first!second!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('simple loop - output.docx', doc); }); it("replaces table row loops correctly", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - table.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop}Repeat this text {prop} And this also…{/loop}"); const data = { outProp: 'I am out!', loop: [ { prop: 'first' }, { prop: 'second' } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("Repeat this text first And this also…Repeat this text second And this also…"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('loop - table - output.docx', doc); }); it("replaces list loops correctly", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - list.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop1}Hi{#loop2}{prop}{/loop2}{/loop1}"); const data = { loop1: [ { loop2: [ { prop: 'first' }, { prop: 'second' } ] }, { loop2: [ { prop: 'third' }, { prop: 'forth' } ] }] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("HifirstsecondHithirdforth"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('loop - list - output.docx', doc); }); it("supports custom loop delimiters", async () => { const handler = new TemplateHandler({ delimiters: { containerTagOpen: '>>>', containerTagClose: '<<<' } }); const template = readFixture('loop - custom delimiters.docx'); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{>>> loop_prop}{simple_prop}!{<<< loop_prop}"); const data = { loop_prop: [ { simple_prop: 'first' }, { simple_prop: 'second' } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("first!second!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('loop - custom delimiters - output.docx', doc); }); it("supports boolean conditions", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - conditions.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop_prop1}hi!{#condition1}yes!{/}{#condition2}no!{/}{/}"); const data = { loop_prop1: [ { condition1: true, condition2: false }, { condition1: false, condition2: true }, { condition1: false, condition2: false }, { condition1: true, condition2: true } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("hi!yes!hi!no!hi!hi!yes!no!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('loop - conditions - output.docx', doc); }); it("ignores the name of the closing tag", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - nested - ignore closing tag name.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop_prop1}hi!{#loop_prop2}{simple_prop}!{/some_name}{/}"); const data = { loop_prop1: [ { loop_prop2: [ { simple_prop: 'first' }, { simple_prop: 'second' } ] }, { loop_prop2: [ { simple_prop: 'third' }, { simple_prop: 'forth' } ] } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("hi!first!second!hi!third!forth!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('nested loop ignore closing tag name - output.docx', doc); }); it("replaces a loop with open and close tag in the same paragraph correctly", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - same line.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop_prop}{simple_prop}!{/loop_prop}"); const data = { loop_prop: [ { simple_prop: 'first' }, { simple_prop: 'second' } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("first!second!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('simple loop - same line - output.docx', doc); }); it("replaces a loop whose items have several properties", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - multi props.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual( "{#loop_prop}{simple_prop1}!{simple_prop2}!{simple_prop3}!{/loop_prop}" ); const data = { loop_prop: [ { simple_prop1: 'first', simple_prop2: 'second', simple_prop3: 'third' }, { simple_prop1: 'forth', simple_prop2: 'fifth', simple_prop3: 'sixth' } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("first!second!third!forth!fifth!sixth!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('loop - multi props - output.docx', doc); }); it("replaces nested loops correctly", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - nested.docx"); const templateText = await handler.getText(template); expect(templateText.trim()).toEqual("{#loop_prop1}hi!{#loop_prop2}{simple_prop}!{/loop_prop2}{/loop_prop1}"); const data = { loop_prop1: [ { loop_prop2: [ { simple_prop: 'first' }, { simple_prop: 'second' } ] }, { loop_prop2: [ { simple_prop: 'third' }, { simple_prop: 'forth' } ] } ] }; const doc = await handler.process(template, data); const docText = await handler.getText(doc); expect(docText).toEqual("hi!first!second!hi!third!forth!"); const docXml = await handler.getXml(doc); expect(docXml).toMatchSnapshot(); // writeTempFile('nested loop - output.docx', doc); }); it("replaces nested loops fast enough", async () => { const handler = new TemplateHandler(); const template = readFixture("loop - nested with image.docx"); const data = { loop_prop1: [ { loop_prop2: [ { simple_prop: 'some string' } ] } ] }; // generate lots of data const maxOuterLoop = 1000; const maxInnerLoop = 20; for (let i = 0; i < maxOuterLoop; i++) { data.loop_prop1[i] = { loop_prop2: [] }; for (let j = 0; j < maxInnerLoop; j++) { data.loop_prop1[i].loop_prop2[j] = { simple_prop: (i * maxOuterLoop + j).toString() }; } } await handler.process(template, data); // writeTempFile('nested loop speed test - output.docx', doc); }, 5 * 1000); });
the_stack
import { CollateralGainTransferDetails, Decimalish, LiquidationDetails, RedemptionDetails, SendableLiquity, StabilityDepositChangeDetails, StabilityPoolGainsWithdrawalDetails, TroveAdjustmentDetails, TroveAdjustmentParams, TroveClosureDetails, TroveCreationDetails, TroveCreationParams } from "@liquity/lib-base"; import { EthersTransactionOverrides, EthersTransactionReceipt, EthersTransactionResponse } from "./types"; import { BorrowingOperationOptionalParams, PopulatableEthersLiquity, PopulatedEthersLiquityTransaction, SentEthersLiquityTransaction } from "./PopulatableEthersLiquity"; const sendTransaction = <T>(tx: PopulatedEthersLiquityTransaction<T>) => tx.send(); /** * Ethers-based implementation of {@link @liquity/lib-base#SendableLiquity}. * * @public */ export class SendableEthersLiquity implements SendableLiquity<EthersTransactionReceipt, EthersTransactionResponse> { private _populate: PopulatableEthersLiquity; constructor(populatable: PopulatableEthersLiquity) { this._populate = populatable; } /** {@inheritDoc @liquity/lib-base#SendableLiquity.openTrove} */ async openTrove( params: TroveCreationParams<Decimalish>, maxBorrowingRateOrOptionalParams?: Decimalish | BorrowingOperationOptionalParams, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveCreationDetails>> { return this._populate .openTrove(params, maxBorrowingRateOrOptionalParams, overrides) .then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.closeTrove} */ closeTrove( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveClosureDetails>> { return this._populate.closeTrove(overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.adjustTrove} */ adjustTrove( params: TroveAdjustmentParams<Decimalish>, maxBorrowingRateOrOptionalParams?: Decimalish | BorrowingOperationOptionalParams, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveAdjustmentDetails>> { return this._populate .adjustTrove(params, maxBorrowingRateOrOptionalParams, overrides) .then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.depositCollateral} */ depositCollateral( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveAdjustmentDetails>> { return this._populate.depositCollateral(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.withdrawCollateral} */ withdrawCollateral( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveAdjustmentDetails>> { return this._populate.withdrawCollateral(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.borrowLUSD} */ borrowLUSD( amount: Decimalish, maxBorrowingRate?: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveAdjustmentDetails>> { return this._populate.borrowLUSD(amount, maxBorrowingRate, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.repayLUSD} */ repayLUSD( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<TroveAdjustmentDetails>> { return this._populate.repayLUSD(amount, overrides).then(sendTransaction); } /** @internal */ setPrice( price: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.setPrice(price, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.liquidate} */ liquidate( address: string | string[], overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<LiquidationDetails>> { return this._populate.liquidate(address, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.liquidateUpTo} */ liquidateUpTo( maximumNumberOfTrovesToLiquidate: number, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<LiquidationDetails>> { return this._populate .liquidateUpTo(maximumNumberOfTrovesToLiquidate, overrides) .then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.depositLUSDInStabilityPool} */ depositLUSDInStabilityPool( amount: Decimalish, frontendTag?: string, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<StabilityDepositChangeDetails>> { return this._populate .depositLUSDInStabilityPool(amount, frontendTag, overrides) .then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.withdrawLUSDFromStabilityPool} */ withdrawLUSDFromStabilityPool( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<StabilityDepositChangeDetails>> { return this._populate.withdrawLUSDFromStabilityPool(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.withdrawGainsFromStabilityPool} */ withdrawGainsFromStabilityPool( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<StabilityPoolGainsWithdrawalDetails>> { return this._populate.withdrawGainsFromStabilityPool(overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.transferCollateralGainToTrove} */ transferCollateralGainToTrove( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<CollateralGainTransferDetails>> { return this._populate.transferCollateralGainToTrove(overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.sendLUSD} */ sendLUSD( toAddress: string, amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.sendLUSD(toAddress, amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.sendLQTY} */ sendLQTY( toAddress: string, amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.sendLQTY(toAddress, amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.redeemLUSD} */ redeemLUSD( amount: Decimalish, maxRedemptionRate?: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<RedemptionDetails>> { return this._populate.redeemLUSD(amount, maxRedemptionRate, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.claimCollateralSurplus} */ claimCollateralSurplus( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.claimCollateralSurplus(overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.stakeLQTY} */ stakeLQTY( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.stakeLQTY(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.unstakeLQTY} */ unstakeLQTY( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.unstakeLQTY(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.withdrawGainsFromStaking} */ withdrawGainsFromStaking( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.withdrawGainsFromStaking(overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.registerFrontend} */ registerFrontend( kickbackRate: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.registerFrontend(kickbackRate, overrides).then(sendTransaction); } /** @internal */ _mintUniToken( amount: Decimalish, address?: string, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate._mintUniToken(amount, address, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.approveUniTokens} */ approveUniTokens( allowance?: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.approveUniTokens(allowance, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.stakeUniTokens} */ stakeUniTokens( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.stakeUniTokens(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.unstakeUniTokens} */ unstakeUniTokens( amount: Decimalish, overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.unstakeUniTokens(amount, overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.withdrawLQTYRewardFromLiquidityMining} */ withdrawLQTYRewardFromLiquidityMining( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.withdrawLQTYRewardFromLiquidityMining(overrides).then(sendTransaction); } /** {@inheritDoc @liquity/lib-base#SendableLiquity.exitLiquidityMining} */ exitLiquidityMining( overrides?: EthersTransactionOverrides ): Promise<SentEthersLiquityTransaction<void>> { return this._populate.exitLiquidityMining(overrides).then(sendTransaction); } }
the_stack
import * as React from "react"; import { IServiceCatalogState } from "reducers/catalog"; import { IClusterServiceClass } from "../../shared/ClusterServiceClass"; import { IServicePlan } from "../../shared/ServiceCatalog"; import { IServiceInstance } from "../../shared/ServiceInstance"; import { IRBACRole, NotFoundError } from "../../shared/types"; import BindingList from "../BindingList"; import "../DeploymentStatus/DeploymentStatus.css"; import { ErrorSelector, MessageAlert } from "../ErrorAlert"; import LoadingWrapper from "../LoadingWrapper"; import AddBindingButton from "./AddBindingButton"; import DeprovisionButton from "./DeprovisionButton"; import ServiceInstanceInfo from "./ServiceInstanceInfo"; import ServiceInstanceStatus from "./ServiceInstanceStatus"; interface IServiceInstanceViewProps { errors: { fetch?: Error; create?: Error; delete?: Error; deprovision?: Error; }; instances: IServiceCatalogState["instances"]; bindingsWithSecrets: IServiceCatalogState["bindingsWithSecrets"]; name: string; namespace: string; classes: IServiceCatalogState["classes"]; plans: IServiceCatalogState["plans"]; getInstances: (ns: string) => Promise<any>; getClasses: () => Promise<any>; getPlans: () => Promise<any>; getBindings: (ns: string) => Promise<any>; deprovision: (instance: IServiceInstance) => Promise<boolean>; addBinding: ( bindingName: string, instanceName: string, namespace: string, parameters: {}, ) => Promise<boolean>; removeBinding: (name: string, ns: string) => Promise<boolean>; } const RequiredRBACRoles: { [s: string]: IRBACRole[] } = { delete: [ { apiGroup: "servicecatalog.k8s.io", resource: "servicebindings", verbs: ["delete"], }, ], deprovision: [ { apiGroup: "servicecatalog.k8s.io", resource: "serviceinstances", verbs: ["delete"], }, ], list: [ { apiGroup: "servicecatalog.k8s.io", clusterWide: true, resource: "clusterserviceclasses", verbs: ["list"], }, { apiGroup: "servicecatalog.k8s.io", resource: "serviceinstances", verbs: ["list"], }, { apiGroup: "servicecatalog.k8s.io", resource: "servicebindings", verbs: ["list"], }, { apiGroup: "servicecatalog.k8s.io", clusterWide: true, resource: "clusterserviceplans", verbs: ["list"], }, ], }; class ServiceInstanceView extends React.Component<IServiceInstanceViewProps> { public componentDidMount() { this.props.getInstances(this.props.namespace); this.props.getBindings(this.props.namespace); this.props.getClasses(); this.props.getPlans(); } public componentWillReceiveProps(nextProps: IServiceInstanceViewProps) { const { getInstances, getBindings, namespace } = this.props; if (nextProps.namespace !== namespace) { getInstances(nextProps.namespace); getBindings(nextProps.namespace); } } public render() { const { name, namespace, instances, bindingsWithSecrets, classes, plans, deprovision, } = this.props; let body = <span />; let bindingSection = <span />; let instance: IServiceInstance | undefined; let svcPlan: IServicePlan | undefined; let svcClass: IClusterServiceClass | undefined; let isPending: boolean = true; const loaded = !instances.isFetching && !classes.isFetching && !plans.isFetching && !bindingsWithSecrets.isFetching; if (loaded && instances.list.length > 0) { instance = instances.list.find( i => i.metadata.name === name && i.metadata.namespace === namespace, ); if (!instance) { return ( <ErrorSelector error={new NotFoundError(`Instance ${name} not found in ${namespace}`)} resource={`Instance ${name}`} action="get" namespace={namespace} /> ); } body = this.renderInstance(instance); // Check if the instance is being provisioned or deprovisioned to disable // certain actions const status = instance.status.conditions[0]; isPending = !!(status && status.reason && status.reason.match(/provisioning/i)); // TODO(prydonius): We should probably show an error if the svcClass or // svcPlan cannot be found for some reason. svcClass = instance && classes.list.find( c => !!instance && !!instance.spec.clusterServiceClassRef && c.metadata.name === instance.spec.clusterServiceClassRef.name, ); svcPlan = instance && plans.list.find( p => !!instance && !!instance.spec.clusterServicePlanRef && p.metadata.name === instance.spec.clusterServicePlanRef.name, ); if (svcClass && svcClass.spec.bindable) { const bindings = instance && bindingsWithSecrets.list.filter( b => b.binding.spec.instanceRef.name === name && b.binding.metadata.namespace === namespace, ); bindingSection = ( <div> {this.props.errors.delete && ( <ErrorSelector error={this.props.errors.delete} resource="Binding" action="delete" defaultRequiredRBACRoles={RequiredRBACRoles} /> )} <BindingList bindingsWithSecrets={bindings} removeBinding={this.props.removeBinding} /> <AddBindingButton disabled={isPending} bindingSchema={svcPlan && svcPlan.spec.serviceBindingCreateParameterSchema} instanceRefName={instance.metadata.name} namespace={instance.metadata.namespace} addBinding={this.props.addBinding} onAddBinding={this.onAddBinding} error={this.props.errors.create} /> </div> ); } else { bindingSection = <p>This instance cannot be bound to applications.</p>; } } return ( <section className="ServiceInstanceView padding-b-big"> <main> <LoadingWrapper loaded={loaded}> <div className="container"> {this.props.errors.fetch && ( <ErrorSelector error={this.props.errors.fetch} resource={`Instance ${name}`} action="list" defaultRequiredRBACRoles={RequiredRBACRoles} /> )} {this.props.errors.deprovision && ( <ErrorSelector error={this.props.errors.deprovision} resource={`Instance ${name}`} action="deprovision" defaultRequiredRBACRoles={RequiredRBACRoles} /> )} {instance && ( <div className="row collapse-b-tablet"> <div className="col-12"> <MessageAlert level="warning"> <div> <div>Refresh the page to update the status of this Service Instance.</div> Service Catalog integration is under heavy development. If you find an issue please report it{" "} <a target="_blank" href="https://github.com/kubeapps/kubeapps/issues"> {" "} here </a> . </div> </MessageAlert> </div> <div className="col-3"> <ServiceInstanceInfo instance={instance} svcClass={svcClass} plan={svcPlan} /> </div> <div className="col-9"> <div className="row padding-t-bigger"> <div className="col-4"> <ServiceInstanceStatus instance={instance} /> </div> <div className="col-8 text-r"> <DeprovisionButton deprovision={deprovision} instance={instance} disabled={isPending} /> </div> </div> <div className="ServiceInstanceView__details"> <div>{body}</div> <h2>Bindings</h2> <hr /> {bindingSection} </div> </div> </div> )} </div> </LoadingWrapper> </main> </section> ); } private renderInstance(instance: IServiceInstance) { const conditions = [...instance.status.conditions]; return ( <div> <div> <h2>Status</h2> <hr /> <table> <thead> <tr> <th>Type</th> <th>Status</th> <th>Last Transition Time</th> <th>Reason</th> <th>Message</th> </tr> </thead> <tbody> {conditions.length > 0 ? ( conditions.map(condition => { return ( <tr key={condition.lastTransitionTime}> <td>{condition.type}</td> <td>{condition.status}</td> <td>{condition.lastTransitionTime}</td> <td> <code>{condition.reason}</code> </td> <td>{condition.message}</td> </tr> ); }) ) : ( <tr> <td colSpan={5}> <p>No statuses</p> </td> </tr> )} </tbody> </table> </div> </div> ); } private onAddBinding = () => { const { namespace, getBindings } = this.props; getBindings(namespace); }; } export default ServiceInstanceView;
the_stack
import { FieldModel, Field, RoSGNode } from "./RoSGNode"; import { BrsType } from ".."; import { ValueKind, BrsString, BrsBoolean } from "../BrsType"; import { Interpreter } from "../../interpreter"; import { Int32 } from "../Int32"; import { Callable, StdlibArgument } from "../Callable"; import { RoArray } from "./RoArray"; import { RoAssociativeArray } from "./RoAssociativeArray"; export class ContentNode extends RoSGNode { readonly defaultFields: FieldModel[] = [ { name: "ContentType", type: "string", hidden: true }, { name: "Title", type: "string", hidden: true }, { name: "TitleSeason", type: "string", hidden: true }, { name: "Description", type: "string", hidden: true }, { name: "SDPosterUrl", type: "string", hidden: true }, { name: "HDPosterUrl", type: "string", hidden: true }, { name: "FHDPosterUrl", type: "string", hidden: true }, { name: "ReleaseDate", type: "string", hidden: true }, { name: "Rating", type: "string", hidden: true }, { name: "StarRating", type: "integer", hidden: true }, { name: "UserStarRating", type: "integer", hidden: true }, { name: "ShortDescriptionLine1", type: "string", hidden: true }, { name: "ShortDescriptionLine2", type: "string", hidden: true }, { name: "EpisodeNumber", type: "string", hidden: true }, { name: "NumEpisodes", type: "integer", hidden: true }, { name: "Actors", type: "array", hidden: true }, { name: "Actors", type: "string", hidden: true }, { name: "Directors", type: "array", hidden: true }, { name: "Director", type: "string", hidden: true }, { name: "Categories", type: "array", hidden: true }, { name: "Categories", type: "string", hidden: true }, { name: "Album", type: "string", hidden: true }, { name: "Artist", type: "string", hidden: true }, { name: "TextOverlayUL", type: "string", hidden: true }, { name: "TextOverlayUR", type: "string", hidden: true }, { name: "TextOverlayBody", type: "string", hidden: true }, { name: "appData", type: "string", value: "", hidden: true }, { name: "encodingKey", type: "string", value: "", hidden: true }, { name: "encodingType", type: "string", value: "", hidden: true }, { name: "KeySystem", type: "string", value: "", hidden: true }, { name: "licenseRenewURL", type: "string", value: "", hidden: true }, { name: "licenseServerURL", type: "string", value: "", hidden: true }, { name: "serializationURL", type: "string", value: "", hidden: true }, { name: "serviceCert", type: "string", value: "", hidden: true }, { name: "Live", type: "boolean", hidden: true }, { name: "Url", type: "string", hidden: true }, { name: "SDBifUrl", type: "string", hidden: true }, { name: "HDBifUrl", type: "string", hidden: true }, { name: "FHDBifUrl", type: "string", hidden: true }, { name: "Stream", type: "assocarray", hidden: true }, { name: "Streams", type: "assocarray", hidden: true }, { name: "StreamBitrates", type: "array", hidden: true }, { name: "StreamUrls", type: "array", hidden: true }, { name: "StreamQualities", type: "array", hidden: true }, { name: "StreamContentIDs", type: "array", hidden: true }, { name: "StreamStickyHttpRedirects", type: "array", hidden: true }, { name: "StreamStartTimeOffset", type: "integer", hidden: true }, { name: "StreamFormat", type: "string", hidden: true }, { name: "Length", type: "integer", hidden: true }, { name: "BookmarkPosition", type: "integer", hidden: true }, { name: "PlayStart", type: "integer", hidden: true }, { name: "PlayDuration", type: "integer", hidden: true }, { name: "ClosedCaptions", type: "boolean", hidden: true }, { name: "HDBranded", type: "boolean", hidden: true }, { name: "IsHD", type: "boolean", hidden: true }, { name: "SubtitleColor", type: "string", hidden: true }, { name: "SubtitleConfig", type: "assocarray", hidden: true }, { name: "SubtitleTracks", type: "assocarray", hidden: true }, { name: "SubtitleUrl", type: "string", hidden: true }, { name: "VideoDisableUI", type: "boolean", hidden: true }, { name: "EncodingType", type: "string", hidden: true }, { name: "EncodingKey", type: "string", hidden: true }, { name: "SwitchingStrategy", type: "string", hidden: true }, { name: "Watched", type: "boolean", hidden: true }, { name: "ForwardQueryStringParams", type: "boolean", hidden: true }, { name: "IgnoreStreamErrors", type: "boolean", hidden: true }, { name: "AdaptiveMinStartBitrate", type: "integer", hidden: true }, { name: "AdaptiveMaxStartBitrate", type: "integer", hidden: true }, { name: "filterCodecProfiles", type: "boolean", hidden: true }, { name: "LiveBoundsPauseBehavior", type: "string", hidden: true }, { name: "ClipStart", type: "float", hidden: true }, { name: "ClipEnd", type: "float", hidden: true }, { name: "preferredaudiocodec", type: "string", hidden: true }, { name: "CdnConfig", type: "array", hidden: true }, { name: "HttpCertificatesFile", type: "string", hidden: true }, { name: "HttpCookies", type: "array", hidden: true }, { name: "HttpHeaders", type: "array", hidden: true }, { name: "HttpSendClientCertificate", type: "boolean", hidden: true }, { name: "MinBandwidth", type: "integer", hidden: true }, { name: "MaxBandwidth", type: "integer", hidden: true }, { name: "AudioPIDPref", type: "integer", hidden: true }, { name: "FullHD", type: "boolean", hidden: true }, { name: "FrameRate", type: "integer", hidden: true }, { name: "TrackIDAudio", type: "string", hidden: true }, { name: "TrackIDVideo", type: "string", hidden: true }, { name: "TrackIDSubtitle", type: "string", hidden: true }, { name: "AudioFormat", type: "string", hidden: true }, { name: "AudioLanguageSelected", type: "string", hidden: true }, { name: "SDBackgroundImageUrl", type: "string", hidden: true }, { name: "HDBackgroundImageUrl", type: "string", hidden: true }, { name: "SourceRect", type: "assocarray", hidden: true }, { name: "TargetRect", type: "assocarray", hidden: true }, { name: "TargetTranslation", type: "assocarray", hidden: true }, { name: "TargetRotation", type: "float", hidden: true }, { name: "CompositionMode", type: "string", hidden: true }, { name: "Text", type: "string", hidden: true }, { name: "TextAttrs", type: "assocarray", hidden: true }, ]; /** * This creates an easy way to track whether a field is a metadata field or not. * The reason to keep track is because metadata fields should print out in all caps. */ private metaDataFields = new Set<string>( this.defaultFields.map((field) => field.name.toLowerCase()) ); constructor(readonly name: string = "ContentNode") { super([], name); this.registerDefaultFields(this.defaultFields); this.registerMethods({ ifAssociativeArray: [this.count, this.keys, this.items], ifSGNodeField: [this.hasfield], }); } private getVisibleFields() { let fields = this.getFields(); return Array.from(fields).filter(([key, value]) => !value.isHidden()); } /** @override */ toString(parent?: BrsType): string { let componentName = "roSGNode:" + this.nodeSubtype; if (parent) { return `<Component: ${componentName}>`; } let fields = this.getVisibleFields(); return [ `<Component: ${componentName}> =`, "{", ...fields.map(([key, value]) => { // If it's a meta-data field, it should print out in all caps. key = this.metaDataFields.has(key.toLowerCase()) ? key.toUpperCase() : key; return ` ${key}: ${value.toString(this)}`; }), "}", ].join("\n"); } /** @override */ getElements() { return this.getVisibleFields() .map(([key, value]) => key) .sort() .map((key) => new BrsString(key)); } /** @override */ getValues() { return this.getVisibleFields() .map(([key, value]) => value) .sort() .map((field: Field) => field.getValue()); } /** * @override * Returns the number of visible fields in the node. */ protected count = new Callable("count", { signature: { args: [], returns: ValueKind.Int32, }, impl: (interpreter: Interpreter) => { return new Int32(this.getVisibleFields().length); }, }); /** * @override * Returns an array of visible keys from the node in lexicographical order. */ protected keys = new Callable("keys", { signature: { args: [], returns: ValueKind.Object, }, impl: (interpreter: Interpreter) => { return new RoArray(this.getElements()); }, }); /** * @override * Returns an array of visible values from the node in lexicographical order. */ protected items = new Callable("items", { signature: { args: [], returns: ValueKind.Object, }, impl: (interpreter: Interpreter) => { return new RoArray( this.getElements().map((key: BrsString) => { return new RoAssociativeArray([ { name: new BrsString("key"), value: key, }, { name: new BrsString("value"), value: this.get(key), }, ]); }) ); }, }); /** * @override * Returns true if the field exists. Marks the field as not hidden. */ protected hasfield = new Callable("hasfield", { signature: { args: [new StdlibArgument("fieldname", ValueKind.String)], returns: ValueKind.Boolean, }, impl: (interpreter: Interpreter, fieldname: BrsString) => { let field = this.getFields().get(fieldname.value.toLowerCase()); if (field) { field.setHidden(false); return BrsBoolean.True; } else { return BrsBoolean.False; } }, }); }
the_stack
import { validator } from '@liskhq/lisk-validator'; import { objects } from '@liskhq/lisk-utils'; import { ApplyAssetContext, ValidateAssetContext } from '../../../../../src/types'; import { VoteTransactionAsset } from '../../../../../src/modules/dpos/transaction_assets/vote_transaction_asset'; import { DPOSAccountProps, DPoSModule, VoteTransactionAssetContext, } from '../../../../../src/modules/dpos'; import { liskToBeddows } from '../../../../utils/assets'; import * as testing from '../../../../../src/testing'; const { StateStoreMock } = testing.mocks; describe('VoteTransactionAsset', () => { const lastBlockHeight = 200; let transactionAsset: VoteTransactionAsset; let applyContext: ApplyAssetContext<VoteTransactionAssetContext>; let validateContext: ValidateAssetContext<VoteTransactionAssetContext>; let sender: any; let stateStoreMock: testing.mocks.StateStoreMock; const delegate1 = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: 'delegate1' } }, }); const delegate2 = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: 'delegate2' } }, }); const delegate3 = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: 'delegate3' } }, }); beforeEach(() => { sender = testing.fixtures.createDefaultAccount([DPoSModule]); stateStoreMock = new StateStoreMock({ accounts: objects.cloneDeep([sender, delegate1, delegate2, delegate3]), lastBlockHeaders: [{ height: lastBlockHeight }] as any, }); transactionAsset = new VoteTransactionAsset(); const transaction = { senderAddress: sender.address, } as any; const asset = { votes: [], }; applyContext = testing.createApplyAssetContext({ transaction, asset, stateStore: stateStoreMock, }); validateContext = testing.createValidateAssetContext<VoteTransactionAssetContext>({ asset, transaction, }); jest.spyOn(applyContext.reducerHandler, 'invoke'); jest.spyOn(stateStoreMock.account, 'get'); jest.spyOn(stateStoreMock.account, 'set'); }); describe('constructor', () => { it('should have valid id', () => { expect(transactionAsset.id).toEqual(1); }); it('should have valid name', () => { expect(transactionAsset.name).toEqual('voteDelegate'); }); it('should have valid schema', () => { expect(transactionAsset.schema).toMatchSnapshot(); }); }); describe('validate', () => { describe('schema validation', () => { describe('when asset.votes does not include any vote', () => { it('should return errors', () => { validateContext.asset = { votes: [], }; const errors = validator.validate(transactionAsset.schema, validateContext.asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('must NOT have fewer than 1 items'); }); }); describe('when asset.votes includes more than 20 elements', () => { it('should return errors', () => { // Arrange validateContext.asset = { votes: Array(21) .fill(0) .map(() => ({ delegateAddress: delegate1.address, amount: liskToBeddows(0) })), }; const errors = validator.validate(transactionAsset.schema, validateContext.asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('must NOT have more than 20 items'); }); }); describe('when asset.votes includes amount which is less than int64 range', () => { it('should return errors', () => { // Arrange validateContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: BigInt(-1) * BigInt(2) ** BigInt(63) - BigInt(1), }, ], }; // Act & Assert const errors = validator.validate(transactionAsset.schema, validateContext.asset); expect(errors[0].message).toInclude('should pass "dataType" keyword validation'); }); }); describe('when asset.votes includes amount which is greater than int64 range', () => { it('should return errors', () => { // Arrange validateContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: BigInt(2) ** BigInt(63) + BigInt(1), }, ], }; // Act & Assert const errors = validator.validate(transactionAsset.schema, validateContext.asset); expect(errors[0].message).toInclude('should pass "dataType" keyword validation'); }); }); }); describe('when asset.votes contains valid contents', () => { it('should not throw errors with valid upvote case', () => { // Arrange validateContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: liskToBeddows(20) }], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).not.toThrow(); }); it('should not throw errors with valid downvote case', () => { // Arrange validateContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: liskToBeddows(-20) }], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).not.toThrow(); }); it('should not throw errors with valid mix votes case', () => { // Arrange validateContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: liskToBeddows(-20) }, { delegateAddress: delegate2.address, amount: liskToBeddows(20) }, ], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).not.toThrow(); }); }); describe('when asset.votes includes more than 10 positive votes', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: Array(11) .fill(0) .map(() => ({ delegateAddress: delegate1.address, amount: liskToBeddows(10) })), }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow( 'Upvote can only be casted upto 10', ); }); }); describe('when asset.votes includes more than 10 negative votes', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: Array(11) .fill(0) .map(() => ({ delegateAddress: delegate1.address, amount: liskToBeddows(-10) })), }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow( 'Downvote can only be casted upto 10', ); }); }); describe('when asset.votes includes duplicate delegates within positive amount', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: Array(2) .fill(0) .map(() => ({ delegateAddress: delegate1.address, amount: liskToBeddows(-10) })), }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow( 'Delegate address must be unique', ); }); }); describe('when asset.votes includes duplicate delegates within positive and negative amount', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: liskToBeddows(-10) }, { delegateAddress: delegate1.address, amount: liskToBeddows(20) }, ], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow( 'Delegate address must be unique', ); }); }); describe('when asset.votes includes zero amount', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: liskToBeddows(0) }], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow('Amount cannot be 0'); }); }); describe('when asset.votes includes positive amount which is not multiple of 10 * 10^8', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: BigInt(20) }], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow( 'Amount should be multiple of 10 * 10^8', ); }); }); describe('when asset.votes includes negative amount which is not multiple of 10 * 10^8', () => { it('should throw error', () => { // Arrange validateContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: BigInt(-20) }], }; // Act & Assert expect(() => transactionAsset.validate(validateContext)).toThrow( 'Amount should be multiple of 10 * 10^8', ); }); }); }); describe('apply', () => { const delegate1VoteAmount = liskToBeddows(90); const delegate2VoteAmount = liskToBeddows(50); beforeEach(() => { applyContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: delegate1VoteAmount }, { delegateAddress: delegate2.address, amount: delegate2VoteAmount }, ].sort((a, b) => a.delegateAddress.compare(b.delegateAddress)), }; }); describe('when asset.votes contain positive amount', () => { it('should not throw error', async () => { await expect(transactionAsset.apply(applyContext)).resolves.toBeUndefined(); }); it('should throw error if vote amount is more than balance', async () => { (applyContext.reducerHandler.invoke as jest.Mock).mockImplementation(() => { throw new Error('Do not have enough balance'); }); await expect(transactionAsset.apply(applyContext)).rejects.toThrow( 'Do not have enough balance', ); }); it('should make account to have correct balance', async () => { await transactionAsset.apply(applyContext); expect(applyContext.reducerHandler.invoke).toHaveBeenCalledTimes(2); expect(applyContext.reducerHandler.invoke).toHaveBeenCalledWith('token:debit', { address: applyContext.transaction.senderAddress, amount: delegate1VoteAmount, }); expect(applyContext.reducerHandler.invoke).toHaveBeenCalledWith('token:debit', { address: applyContext.transaction.senderAddress, amount: delegate2VoteAmount, }); }); it('should not change account.dpos.unlocking', async () => { await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.unlocking).toHaveLength(0); }); it('should order account.dpos.sentVotes', async () => { applyContext.asset = { votes: [...applyContext.asset.votes].reverse(), }; await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); const senderVotesCopy = updatedSender.dpos.sentVotes.slice(0); senderVotesCopy.sort((a: any, b: any) => a.delegateAddress.compare(b.delegateAddress)); expect(updatedSender.dpos.sentVotes).toStrictEqual(senderVotesCopy); }); it('should make upvoted delegate account to have correct totalVotesReceived', async () => { await transactionAsset.apply(applyContext); const updatedDelegate1 = await stateStoreMock.account.get<DPOSAccountProps>( delegate1.address, ); const updatedDelegate2 = await stateStoreMock.account.get<DPOSAccountProps>( delegate2.address, ); expect(updatedDelegate1.dpos.delegate.totalVotesReceived).toEqual(delegate1VoteAmount); expect(updatedDelegate2.dpos.delegate.totalVotesReceived).toEqual(delegate2VoteAmount); }); it('should create vote object when it does not exist before', async () => { await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(sender.dpos.sentVotes).toEqual([]); expect(updatedSender.dpos.sentVotes).toEqual(applyContext.asset.votes); }); it('should update vote object when it exists before and create if it does not exist', async () => { await transactionAsset.apply(applyContext); // Send votes second time await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(sender.dpos.sentVotes).toEqual([]); expect(updatedSender.dpos.sentVotes[0]).toEqual({ delegateAddress: applyContext.asset.votes[0].delegateAddress, amount: applyContext.asset.votes[0].amount * BigInt(2), }); expect(updatedSender.dpos.sentVotes[1]).toEqual({ delegateAddress: applyContext.asset.votes[1].delegateAddress, amount: applyContext.asset.votes[1].amount * BigInt(2), }); }); }); describe('when asset.votes contain negative amount which makes account.dpos.sentVotes to be 0 entries', () => { beforeEach(async () => { const votesContext = objects.cloneDeep(applyContext); votesContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: delegate1VoteAmount }, { delegateAddress: delegate2.address, amount: delegate2VoteAmount }, ], }; await transactionAsset.apply(votesContext); // Clears mock calls for earlier apply asset (applyContext.reducerHandler.invoke as jest.Mock).mockClear(); applyContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: BigInt(-1) * delegate1VoteAmount }, { delegateAddress: delegate2.address, amount: BigInt(-1) * delegate2VoteAmount }, ].sort((a, b) => -1 * a.delegateAddress.compare(b.delegateAddress)), }; }); it('should not throw error', async () => { await expect(transactionAsset.apply(applyContext)).resolves.toBeUndefined(); }); it('should not change account balance', async () => { await transactionAsset.apply(applyContext); expect(applyContext.reducerHandler.invoke).not.toHaveBeenCalled(); }); it('should remove vote which has zero amount', async () => { applyContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: BigInt(-1) * delegate1VoteAmount }], }; await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.sentVotes).toHaveLength(1); expect(updatedSender.dpos.sentVotes[0].delegateAddress).not.toEqual(delegate1.address); }); it('should update vote which has non-zero amount', async () => { const downVoteAmount = liskToBeddows(10); applyContext.asset = { votes: [{ delegateAddress: delegate1.address, amount: BigInt(-1) * downVoteAmount }], }; await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.sentVotes).toHaveLength(2); expect( updatedSender.dpos.sentVotes.find(v => v.delegateAddress.equals(delegate1.address)), ).toEqual({ delegateAddress: delegate1.address, amount: delegate1VoteAmount - downVoteAmount, }); }); it('should make account to have correct unlocking', async () => { await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.unlocking).toHaveLength(2); expect(updatedSender.dpos.unlocking).toEqual( [ { delegateAddress: delegate1.address, amount: delegate1VoteAmount, unvoteHeight: lastBlockHeight + 1, }, { delegateAddress: delegate2.address, amount: delegate2VoteAmount, unvoteHeight: lastBlockHeight + 1, }, ].sort((a, b) => a.delegateAddress.compare(b.delegateAddress)), ); }); it('should order account.dpos.unlocking', async () => { await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.unlocking).toHaveLength(2); expect(updatedSender.dpos.unlocking.map(d => d.delegateAddress)).toEqual( [delegate1.address, delegate2.address].sort((a, b) => a.compare(b)), ); }); it('should make downvoted delegate account to have correct totalVotesReceived', async () => { await transactionAsset.apply(applyContext); const updatedDelegate1 = await stateStoreMock.account.get<DPOSAccountProps>( delegate1.address, ); const updatedDelegate2 = await stateStoreMock.account.get<DPOSAccountProps>( delegate2.address, ); expect(updatedDelegate1.dpos.delegate.totalVotesReceived).toEqual(BigInt(0)); expect(updatedDelegate2.dpos.delegate.totalVotesReceived).toEqual(BigInt(0)); }); it('should throw error when downvoted delegate is not already upvoted', async () => { applyContext.asset = { votes: [{ delegateAddress: delegate3.address, amount: BigInt(-1) * delegate1VoteAmount }], }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow( 'Cannot cast downvote to delegate who is not upvoted', ); }); }); describe('when asset.votes contain negative and positive amount', () => { const positiveVoteDelegate1 = liskToBeddows(10); const negativeVoteDelegate2 = liskToBeddows(-20); beforeEach(async () => { const votesContext = objects.cloneDeep(applyContext); votesContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: delegate1VoteAmount }, { delegateAddress: delegate2.address, amount: delegate2VoteAmount }, ], }; await transactionAsset.apply(votesContext); // Clears mock calls for earlier apply asset (applyContext.reducerHandler.invoke as jest.Mock).mockClear(); applyContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: positiveVoteDelegate1 }, { delegateAddress: delegate2.address, amount: negativeVoteDelegate2 }, ].sort((a, b) => -1 * a.delegateAddress.compare(b.delegateAddress)), }; }); it('should not throw error', async () => { await expect(transactionAsset.apply(applyContext)).resolves.toBeUndefined(); }); it('should make account to have correct balance', async () => { await transactionAsset.apply(applyContext); expect(applyContext.reducerHandler.invoke).toHaveBeenCalledTimes(1); expect(applyContext.reducerHandler.invoke).toHaveBeenCalledWith('token:debit', { address: applyContext.transaction.senderAddress, amount: positiveVoteDelegate1, }); }); it('should make account to have correct unlocking', async () => { await transactionAsset.apply(applyContext); const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.unlocking).toHaveLength(1); expect(updatedSender.dpos.unlocking).toEqual([ { delegateAddress: delegate2.address, amount: BigInt(-1) * negativeVoteDelegate2, unvoteHeight: lastBlockHeight + 1, }, ]); }); it('should make upvoted delegate account to have correct totalVotesReceived', async () => { await transactionAsset.apply(applyContext); const updatedDelegate1 = await stateStoreMock.account.get<DPOSAccountProps>( delegate1.address, ); expect(updatedDelegate1.dpos.delegate.totalVotesReceived).toEqual( delegate1VoteAmount + positiveVoteDelegate1, ); }); it('should make downvoted delegate account to have correct totalVotesReceived', async () => { await transactionAsset.apply(applyContext); const updatedDelegate2 = await stateStoreMock.account.get<DPOSAccountProps>( delegate2.address, ); expect(updatedDelegate2.dpos.delegate.totalVotesReceived).toEqual( delegate2VoteAmount + negativeVoteDelegate2, ); }); }); describe('when asset.votes contain invalid data', () => { beforeEach(() => { applyContext.asset = { votes: [ { delegateAddress: delegate1.address, amount: delegate1VoteAmount }, { delegateAddress: delegate2.address, amount: delegate2VoteAmount }, ].sort((a, b) => -1 * a.delegateAddress.compare(b.delegateAddress)), }; }); describe('when asset.votes contain delegate address which account does not exists', () => { it('should throw error', async () => { const nonExistingAccount = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: '' } }, }); applyContext.asset = { votes: [ ...applyContext.asset.votes, { delegateAddress: nonExistingAccount.address, amount: liskToBeddows(76) }, ], }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow('Account not defined'); }); }); describe('when asset.votes contain delegate address which is not registered delegate', () => { it('should throw error', async () => { const nonRegisteredDelegate = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: '' } }, }); await stateStoreMock.account.set(nonRegisteredDelegate.address, nonRegisteredDelegate); applyContext.asset = { votes: [ ...applyContext.asset.votes, { delegateAddress: nonRegisteredDelegate.address, amount: liskToBeddows(76) }, ], }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow( `Voted delegate address ${nonRegisteredDelegate.address.toString( 'hex', )} is not registered`, ); }); }); describe('when asset.votes positive amount makes account.dpos.sentVotes entries more than 10', () => { it('should throw error', async () => { const votes = []; for (let i = 0; i < 12; i += 1) { const delegate = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: `newdelegate${i}` } }, }); await stateStoreMock.account.set(delegate.address, delegate); votes.push({ delegateAddress: delegate.address, amount: liskToBeddows(10), }); } applyContext.asset = { votes, }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow( 'Account can only vote upto 10', ); }); }); describe('when asset.votes negative amount decrease account.dpos.sentVotes entries yet positive amount makes account exceeds more than 10', () => { it('should throw error', async () => { const updatedSender = objects.cloneDeep(sender); // Suppose account already voted for 8 delegates for (let i = 0; i < 8; i += 1) { const delegate = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: `existingdelegate${i}` } }, }); await stateStoreMock.account.set(delegate.address, delegate); updatedSender.dpos.sentVotes.push({ delegateAddress: delegate.address, amount: liskToBeddows(20), }); } await stateStoreMock.account.set(sender.address, updatedSender); // We have 2 negative votes const votes = [ { delegateAddress: updatedSender.dpos.sentVotes[0].delegateAddress, amount: liskToBeddows(-10), }, { delegateAddress: updatedSender.dpos.sentVotes[1].delegateAddress, amount: liskToBeddows(-10), }, ]; // We have 3 positive votes for (let i = 0; i < 3; i += 1) { const delegate = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: `newdelegate${i}` } }, }); await stateStoreMock.account.set(delegate.address, delegate); votes.push({ delegateAddress: delegate.address, amount: liskToBeddows(10), }); } applyContext.asset = { // Account already contains 8 positive votes // now we added 2 negative votes and 3 new positive votes // which will make total positive votes to grow over 10 votes, }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow( 'Account can only vote upto 10', ); }); }); describe('when asset.votes negative amount and makes account.dpos.unlocking more than 20 entries', () => { it('should throw error', async () => { const updatedSender = objects.cloneDeep(sender); // Suppose account already 19 unlocking for (let i = 0; i < 19; i += 1) { const delegate = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: `existingdelegate${i}` } }, }); await stateStoreMock.account.set(delegate.address, delegate); updatedSender.dpos.unlocking.push({ delegateAddress: delegate.address, amount: liskToBeddows(20), unvoteHeight: i, }); } // Suppose account have 5 positive votes for (let i = 0; i < 5; i += 1) { const delegate = testing.fixtures.createDefaultAccount([DPoSModule], { dpos: { delegate: { username: `existingdelegate${i}` } }, }); await stateStoreMock.account.set(delegate.address, delegate); updatedSender.dpos.sentVotes.push({ delegateAddress: delegate.address, amount: liskToBeddows(20), }); } await stateStoreMock.account.set(sender.address, updatedSender); // We have 2 negative votes const votes = [ { delegateAddress: updatedSender.dpos.sentVotes[0].delegateAddress, amount: liskToBeddows(-10), }, { delegateAddress: updatedSender.dpos.sentVotes[1].delegateAddress, amount: liskToBeddows(-10), }, ]; applyContext.asset = { // Account already contains 19 unlocking and 5 positive votes // now we added 2 negative votes // which will make total unlocking to grow over 20 votes, }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow( 'Cannot downvote which exceeds account.dpos.unlocking to have more than 20', ); }); }); describe('when asset.votes negative amount exceeds the previously voted amount', () => { it('should throw error', async () => { const updatedSender = objects.cloneDeep(sender); updatedSender.dpos.sentVotes.push({ delegateAddress: delegate1.address, amount: liskToBeddows(70), }); await stateStoreMock.account.set(sender.address, updatedSender); applyContext.asset = { // Negative vote for more than what was earlier voted votes: [ { delegateAddress: delegate1.address, amount: liskToBeddows(-80), }, ], }; await expect(transactionAsset.apply(applyContext)).rejects.toThrow( 'The downvote amount cannot be greater than upvoted amount.', ); }); }); }); describe('when asset.votes contains self-vote', () => { const senderVoteAmount = liskToBeddows(80); beforeEach(async () => { // Make sender a delegate const updatedSender = objects.cloneDeep(sender); updatedSender.dpos.delegate.username = 'sender_delegate'; await stateStoreMock.account.set(sender.address, updatedSender); applyContext.asset = { votes: [{ delegateAddress: sender.address, amount: senderVoteAmount }], }; }); it('should update votes and totalVotesReceived', async () => { // Act await transactionAsset.apply(applyContext); // Assert const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.delegate.totalVotesReceived).toEqual(senderVoteAmount); expect(updatedSender.dpos.sentVotes).toHaveLength(1); expect(applyContext.reducerHandler.invoke).toHaveBeenCalledWith('token:debit', { address: sender.address, amount: senderVoteAmount, }); }); }); describe('when asset.votes contains self-downvote', () => { const senderUpVoteAmount = liskToBeddows(80); const senderDownVoteAmount = liskToBeddows(30); beforeEach(async () => { // Make sender a delegate and make it sure it have a self vote already const updatedSender = objects.cloneDeep(sender); updatedSender.dpos.delegate.username = 'sender_delegate'; updatedSender.dpos.delegate.totalVotesReceived = senderUpVoteAmount; updatedSender.dpos.sentVotes = [ { delegateAddress: updatedSender.address, amount: senderUpVoteAmount }, ]; await stateStoreMock.account.set(sender.address, updatedSender); applyContext.asset = { votes: [{ delegateAddress: sender.address, amount: BigInt(-1) * senderDownVoteAmount }], }; }); it('should update votes, totalVotesReceived and unlocking', async () => { // Act await transactionAsset.apply(applyContext); // Assert const updatedSender = await stateStoreMock.account.get<DPOSAccountProps>(sender.address); expect(updatedSender.dpos.delegate.totalVotesReceived).toEqual( senderUpVoteAmount - senderDownVoteAmount, ); expect(updatedSender.dpos.sentVotes).toHaveLength(1); expect(updatedSender.dpos.sentVotes).toEqual([ { delegateAddress: sender.address, amount: senderUpVoteAmount - senderDownVoteAmount }, ]); expect(updatedSender.dpos.unlocking).toHaveLength(1); expect(updatedSender.dpos.unlocking).toEqual([ { delegateAddress: sender.address, amount: senderDownVoteAmount, unvoteHeight: lastBlockHeight + 1, }, ]); expect(applyContext.reducerHandler.invoke).not.toHaveBeenCalled(); }); }); }); });
the_stack
import { LBA2BodyType, LBA1BodyType } from './bodyType'; import { getParams } from '../../params'; // Note that slots are for the inventory are defined as starting from 0 in the // top left and increasing to the right row by row. const isLBA1 = getParams().game === 'lba1'; const LBA2InventoryColumns = 7; const LBA2InventoryRows = 6; // Original: 5, but it overloaded some slots. const LBA1InventoryColumns = 7; const LBA1InventoryRows = 4; // This list corresponds with the game vars for each item, which is mostly but not entirely the // same as the indices used for the item modems and strings. export enum LBA2Items { HOLOMAP = 0, MAGIC_BALL = 1, DARTS = 2, SENDELLS_BALL = 3, TUNIC = 4, PEARL_OF_INCANDESCENCE = 5, PYRAMID_KEY = 6, CAR_PART = 7, KASHES = 8, LASER_PISTOL = 9, SWORD = 10, WANNIE_GLOVE = 11, PROTO_PACK = 12, FERRY_TICKET = 13, MECA_PENGUIN = 14, GAZOGEM = 15, DISSIDENTS_RING = 16, GALLIC_ACID = 17, FERRYMAN_SONG = 18, RING_OF_LIGHTNING = 19, UMBRELLA = 20, GEM = 21, HORN = 22, BLOWGUN = 23, MEMORY_VIEWER = 24, SLICE_OF_TART = 25, RADIO = 26, GARDEN_BALSAM = 27, MAGIC_SLATE = 28, TRANSLATOR = 29, DIPLOMA = 30, FRAGMENT_FRANCOS = 31, FRAGMENT_SUPS = 32, FRAGMENT_MOSQUIBEES = 33, FRAGMENT_WANNIES = 34, ISLAND_CX_KEY = 35, PICKAXE = 36, BURGERMASTER_KEY = 37, BURGERMASTER_NOTES = 38, PROTECTIVE_SPELL = 39, // Items below this point are "virtual" - they do not have associated game vars. GREEN_MAGIC_BALL = 40, RED_MAGIC_BALL = 41, FIRE_MAGIC_BALL = 42, ZLITOS = 43, DARK_MONK_KEY = 44, TRAVEL_TOKEN = 45, BLOWTRON = 46, WIZARDS_TUNIC = 47, JET_PACK = 48, LASER_PISTOL_CRYSTAL_PIECE = 49, LASER_PISTOL_BODY = 50, GREEN_RING_OF_LIGHTNING = 51, RED_RING_OF_LIGHTNING = 52, FIRE_RING_OF_LIGHTNING = 53, } export enum LBA1Items { HOLOMAP = 0, MAGIC_BALL = 1, FUNFROCK_SABER = 2, GAWLEYS_HORN = 3, TUNIC = 4, BOOK_OF_BU = 5, SENDELLS_MEDALLION = 6, FLASK_CLEAR_WATER = 7, RED_CARD = 8, BLUE_CARD = 9, ID_CARD = 10, MR_MIERS_PASS = 11, PROTO_PACK = 12, SNOWBOARD = 13, MECA_PINGUIN = 14, GAS = 15, PIRATE_FLAG = 16, MAGIC_FLUTE = 17, SPACE_GUITAR = 18, HAIR_DRYER = 19, ANCESTRAL_KEY = 20, BOTTLE_SIRUP = 21, BOTTLE_SIRUP_EMPTY = 22, FERRY_TICKET = 23, KEYPAD = 24, COFFEE_CAN = 25, BONUS_LIST = 26, CLOVER_LEAF = 27, } // LBA2InventoryMapping maps from inventory slot ID to item ID. const LBA2InventoryMapping = { 0: LBA2Items.MAGIC_BALL, 1: LBA2Items.DARTS, 2: LBA2Items.BLOWGUN, 3: LBA2Items.HORN, 4: LBA2Items.WANNIE_GLOVE, 5: LBA2Items.LASER_PISTOL, 6: LBA2Items.SWORD, 7: LBA2Items.TUNIC, 8: LBA2Items.SENDELLS_BALL, 9: LBA2Items.RING_OF_LIGHTNING, 10: LBA2Items.PROTECTIVE_SPELL, 11: LBA2Items.MAGIC_SLATE, 12: LBA2Items.DIPLOMA, 13: LBA2Items.FRAGMENT_FRANCOS, 14: LBA2Items.HOLOMAP, 15: LBA2Items.PROTO_PACK, 16: LBA2Items.RADIO, 17: LBA2Items.TRANSLATOR, // Original: also CAR_PART 18: LBA2Items.MECA_PENGUIN, 19: LBA2Items.KASHES, 20: LBA2Items.FRAGMENT_SUPS, 21: LBA2Items.FERRYMAN_SONG, 22: LBA2Items.SLICE_OF_TART, 23: LBA2Items.ISLAND_CX_KEY, // Original: also GARDEN_BALSAM 24: LBA2Items.GEM, 25: LBA2Items.PEARL_OF_INCANDESCENCE, 26: LBA2Items.PICKAXE, // Original: also GALLIC_ACID 27: LBA2Items.FRAGMENT_MOSQUIBEES, 28: LBA2Items.GAZOGEM, 29: LBA2Items.DISSIDENTS_RING, 30: LBA2Items.UMBRELLA, 31: LBA2Items.MEMORY_VIEWER, 32: LBA2Items.FERRY_TICKET, 33: LBA2Items.BURGERMASTER_NOTES, // Original: also PYRAMID_KEY, BURGERMASTER_KEY 34: LBA2Items.FRAGMENT_WANNIES, // The following items are overloaded onto other item slots in the original but we don't need // to keep the same design. 35: LBA2Items.PYRAMID_KEY, 36: LBA2Items.GALLIC_ACID, 37: LBA2Items.GARDEN_BALSAM, 38: LBA2Items.CAR_PART, 39: LBA2Items.BURGERMASTER_KEY, }; const LBA1InventoryMapping = { 0: LBA1Items.HOLOMAP, 1: LBA1Items.TUNIC, 2: LBA1Items.RED_CARD, 3: LBA1Items.PROTO_PACK, 4: LBA1Items.PIRATE_FLAG, 5: LBA1Items.ANCESTRAL_KEY, 6: LBA1Items.KEYPAD, 7: LBA1Items.MAGIC_BALL, 8: LBA1Items.BOOK_OF_BU, 9: LBA1Items.BLUE_CARD, 10: LBA1Items.SNOWBOARD, 11: LBA1Items.MAGIC_FLUTE, 12: LBA1Items.BOTTLE_SIRUP, 13: LBA1Items.COFFEE_CAN, 14: LBA1Items.FUNFROCK_SABER, 15: LBA1Items.SENDELLS_MEDALLION, 16: LBA1Items.ID_CARD, 17: LBA1Items.MECA_PINGUIN, 18: LBA1Items.SPACE_GUITAR, 19: LBA1Items.BOTTLE_SIRUP_EMPTY, 20: LBA1Items.BONUS_LIST, 21: LBA1Items.GAWLEYS_HORN, 22: LBA1Items.FLASK_CLEAR_WATER, 23: LBA1Items.MR_MIERS_PASS, 24: LBA1Items.GAS, 25: LBA1Items.HAIR_DRYER, 26: LBA1Items.FERRY_TICKET, 27: LBA1Items.CLOVER_LEAF, }; export const LBA2WeaponToBodyMapping = { [LBA2Items.MAGIC_BALL]: LBA2BodyType.TWINSEN_TUNIC, [LBA2Items.GREEN_MAGIC_BALL]: LBA2BodyType.TWINSEN_TUNIC, [LBA2Items.RED_MAGIC_BALL]: LBA2BodyType.TWINSEN_TUNIC, [LBA2Items.FIRE_MAGIC_BALL]: LBA2BodyType.TWINSEN_TUNIC, [LBA2Items.DARTS]: LBA2BodyType.TWINSEN_TUNIC, [LBA2Items.LASER_PISTOL]: LBA2BodyType.TWINSEN_LASER_PISTOL, [LBA2Items.SWORD]: LBA2BodyType.TWINSEN_SWORD, [LBA2Items.WANNIE_GLOVE]: LBA2BodyType.TWINSEN_WANNIE_GLOVE, [LBA2Items.BLOWGUN]: LBA2BodyType.TWINSEN_BLOWGUN, [LBA2Items.BLOWTRON]: LBA2BodyType.TWINSEN_BLOWTRON, }; export const LBA1WeaponToBodyMapping = { [LBA1Items.MAGIC_BALL]: LBA1BodyType.TWINSEN_TUNIC, [LBA1Items.FUNFROCK_SABER]: LBA1BodyType.TWINSEN_SWORD, }; export function GetInventoryMapping() { return isLBA1 ? LBA1InventoryMapping : LBA2InventoryMapping; } export function GetInventoryRows() { return isLBA1 ? LBA1InventoryRows : LBA2InventoryRows; } export function GetInventoryColumns() { return isLBA1 ? LBA1InventoryColumns : LBA2InventoryColumns; } export function GetInventoryItems() { return isLBA1 ? LBA1Items : LBA2Items; } export const LBA1InventorySize = 28; export const LBA2InventorySize = 40; export function GetInventorySize() { return isLBA1 ? LBA1InventorySize : LBA2InventorySize; } function CanUseItemLBA1(_item: LBA1Items) { // Not implemented - assume all items are always usable. return true; } function CanUseItemLBA2(item: LBA2Items) { switch (item) { case LBA2Items.LASER_PISTOL_CRYSTAL_PIECE: case LBA2Items.LASER_PISTOL_BODY: return false; default: return true; } } export function CanUseItem(item: LBA1Items|LBA2Items) { return isLBA1 ? CanUseItemLBA1(item as LBA1Items) : CanUseItemLBA2(item as LBA2Items); } function MapItemLBA1(item: number, _state: number) { // Not implemented. return item; } function MapItemLBA2(item: number, state: number) { switch (item as LBA2Items) { case LBA2Items.MAGIC_BALL: return GetLBA2MagicBallForLevel(state); case LBA2Items.TUNIC: return (state === 1) ? LBA2Items.WIZARDS_TUNIC : LBA2Items.TUNIC; case LBA2Items.PEARL_OF_INCANDESCENCE: return (state === 1) ? LBA2Items.TRAVEL_TOKEN : LBA2Items.PEARL_OF_INCANDESCENCE; case LBA2Items.KASHES: // TODO: how does original LBA2 decide Kashes vs Zlitos here? return LBA2Items.ZLITOS; case LBA2Items.LASER_PISTOL: if (state === 0) { return LBA2Items.LASER_PISTOL_CRYSTAL_PIECE; } if (state === 1) { return LBA2Items.LASER_PISTOL_BODY; } return LBA2Items.LASER_PISTOL; case LBA2Items.PROTO_PACK: return (state === 1) ? LBA2Items.JET_PACK : LBA2Items.PROTO_PACK; case LBA2Items.RING_OF_LIGHTNING: return GetLBA2RingOfLightningForLevel(state); case LBA2Items.BLOWGUN: return (state === 1) ? LBA2Items.BLOWTRON : LBA2Items.BLOWGUN; case LBA2Items.FRAGMENT_FRANCOS: return (state === 1) ? LBA2Items.DARK_MONK_KEY : LBA2Items.FRAGMENT_FRANCOS; default: // Most items have no special states. return item; } } export function MapItem(item: number, state: number) { return isLBA1 ? MapItemLBA1(item, state) : MapItemLBA2(item, state); } export function GetLBA2MagicBallForLevel(level: number) { switch (level) { case 2: return LBA2Items.GREEN_MAGIC_BALL; case 3: return LBA2Items.RED_MAGIC_BALL; case 4: return LBA2Items.FIRE_MAGIC_BALL; case 0: case 1: default: return LBA2Items.MAGIC_BALL; } } export function GetLBA2RingOfLightningForLevel(level: number) { switch (level) { case 2: return LBA2Items.GREEN_RING_OF_LIGHTNING; case 3: return LBA2Items.RED_RING_OF_LIGHTNING; case 4: return LBA2Items.FIRE_RING_OF_LIGHTNING; case 0: case 1: default: return LBA2Items.RING_OF_LIGHTNING; } } function GetLBA1ItemResourceIndex(item: LBA1Items) { // TODO: check if any mapping is needed. return item as number; } function GetLBA2ItemResourceIndex(item: LBA2Items) { switch (item) { case LBA2Items.LASER_PISTOL: return 50; case LBA2Items.MEMORY_VIEWER: return 45; case LBA2Items.TRAVEL_TOKEN: return 24; case LBA2Items.LASER_PISTOL_BODY: return 9; default: // Most items require no mapping. return item as number; } } export function GetItemResourceIndex(item: LBA1Items|LBA2Items) { return isLBA1 ? GetLBA1ItemResourceIndex(item as LBA1Items) : GetLBA2ItemResourceIndex(item as LBA2Items); }
the_stack
import 'jest-extended'; import path from 'path'; import { DataEntity, get, cloneDeep } from '@terascope/utils'; import { xLuceneFieldType } from '@terascope/types'; import TestHarness from './test-harness'; import { WatcherConfig } from '../src'; import Plugins from './fixtures/plugins'; describe('can transform matches', () => { let opTest: TestHarness; beforeEach(() => { opTest = new TestHarness('transform'); }); function getPath(fileName: string) { return path.join(__dirname, `./fixtures/${fileName}`); } function encode(str: string, type: string) { const buff = Buffer.from(str); return buff.toString(type as any); } it('should transform matching data', async () => { const config: WatcherConfig = { rules: [getPath('transformRules1.txt')], type_config: { _created: xLuceneFieldType.Date }, }; const data = DataEntity.makeArray([ { some: 'data', bytes: 200, myfield: 'hello' }, { some: 'data', bytes: 200 }, { some: 'other', bytes: 1200 }, { other: 'xabcd', myfield: 'hello' }, { _created: '2018-12-16T15:16:09.076Z', myfield: 'hello' }, ]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); results.forEach((d) => { expect(DataEntity.isDataEntity(d)).toEqual(true); expect(get(d, 'topfield.value1')).toEqual('hello'); expect(d.getMetadata('selectors')).toBeDefined(); }); }); it('can uses typeConifg', async () => { const config: WatcherConfig = { rules: [getPath('transformRules1.txt')], type_config: { location: xLuceneFieldType.Geo }, }; const data = DataEntity.makeArray([ { hostname: 'www.other.com', location: '33.435967, -111.867710 ' }, // true { hostname: 'www.other.com', location: '33.435967412341452595678, -111.8677102345324523452345467456 ' }, // true { hostname: 'www.example.com', location: '22.435967,-150.867710' }, // false ]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(2); expect(results[0]).toEqual({ point: data[0].location }); expect(results[1]).toEqual({ point: data[1].location }); }); it('should transform matching data with no selector', async () => { const config: WatcherConfig = { rules: [getPath('transformRules3.txt')], }; const data = DataEntity.makeArray([{ data: 'someData' }, { data: 'otherData' }, {}]); const resultSet = data.map((obj) => obj.data); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(2); results.forEach((d, index) => { expect(DataEntity.isDataEntity(d)).toEqual(true); expect(d.other).toEqual(resultSet[index]); expect(d.getMetadata('selectors').includes('*')).toBeTrue(); }); }); it('can work with regex transform queries', async () => { const config: WatcherConfig = { rules: [getPath('transformRules1.txt')], }; const data = DataEntity.makeArray([ { some: 'data', someField: 'something' }, { some: 'data', someField: 'otherthing' }, // should not return anyting { some: 'data' }, // should not return anyting ]); const test = await opTest.init(config); const results = await test.run(data); // NOTE: 'regex': 'some.*?$' // - will give you the entire matched string => wholeRegexResponse // NOTE: 'regex': 'some(.*?)$' // - will give you the captured part of the string => partRegexResponse expect(results.length).toEqual(1); expect(results[0]).toEqual({ wholeRegexResponse: 'something', partRegexResponse: 'thing' }); }); it('can extract using start/end', async () => { const config: WatcherConfig = { rules: [getPath('transformRules1.txt')], }; const data1 = DataEntity.makeArray([{ some: 'data', bytes: 1200, myfield: 'http:// google.com?field1=helloThere&other=things' }]); const data2 = DataEntity.makeArray([{ some: 'data', bytes: 1200, myfield: 'http:// google.com?field1=helloThere' }]); const test = await opTest.init(config); const results1 = await test.run(data1); expect(results1.length).toEqual(1); expect(results1[0]).toEqual({ topfield: { value1: 'helloThere' } }); const results2 = await test.run(data2); expect(results2.length).toEqual(1); expect(results2[0]).toEqual({ topfield: { value1: 'helloThere' } }); }); it('can extract using start/end on fields that are arrays', async () => { const config: WatcherConfig = { rules: [getPath('transformRules10.txt')], }; const urls = [ 'http:// www.example.com/path?field1=blah', 'http:// www.example.com/path?field2=moreblah', 'http:// www.example.com/path?field3=evenmoreblah', ]; const data = DataEntity.makeArray([{ domain: 'example.com', url: urls }]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ field1: ['blah'], field2: ['moreblah'], field3: ['evenmoreblah'] }); expect(DataEntity.isDataEntity(results[0])).toEqual(true); }); it('can merge extacted results', async () => { const config: WatcherConfig = { rules: [getPath('transformRules1.txt')], }; const data = DataEntity.makeArray([ { hostname: 'www.example.com', pathLat: '/path/tiles/latitude/33.435967', pathLon: '/path/tiles/longitude/-111.867710', }, // true { hostname: 'www.other.com', location: '33.435967, -111.867710 ', }, // false { hostname: 'www.example.com', location: '22.435967,-150.867710', }, // false ]); const test = await opTest.init(config); const results = await test.run(data); expect(results).toBeArrayOfSize(2); expect(results[0]).toEqual({ location: { lat: '33.435967', lon: '-111.867710' } }); expect(results[1]).toEqual({ point: '33.435967, -111.867710 ' }); }); it('can use post process operations', async () => { const config: WatcherConfig = { rules: [getPath('transformRules2.txt')], }; const data = DataEntity.makeArray([{ hello: 'world', first: 'John', last: 'Doe' }]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ full_name: 'John Doe' }); }); it('false validations remove the fields', async () => { const config: WatcherConfig = { rules: [getPath('transformRules2.txt')], }; const data = DataEntity.makeArray([{ geo: true, lat: '2233', other: 'data' }, { geo: true, lon: '2233' }]); const data2 = DataEntity.makeArray([{ geo: true, lat: '2233' }, { geo: true, lon: '2233' }]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ other: 'data' }); const results2 = await test.run(data2); expect(results2).toEqual([]); }); it('refs can target the right field', async () => { const config: WatcherConfig = { rules: [getPath('transformRules4.txt')], }; const data = DataEntity.makeArray([ { hello: 'world', lat: 23.423, lon: 93.33, first: 'John', last: 'Doe' }, // all good { hello: 'world', lat: 123.423, lon: 93.33, first: 'John', last: 'Doe' }, // bad geo { hello: 'world', lat: 123.423, lon: 93.33, first: 'John', last: 'Doe' }, // bad geo { hello: 'world', lat: 23.423, lon: 93.33, full_name: 3243423 }, // full_name is not string ]); const resultSet = [ { location: { lat: 23.423, lon: 93.33 }, first_name: 'John', last_name: 'Doe', full_name: 'John Doe' }, { first_name: 'John', last_name: 'Doe', full_name: 'John Doe' }, { first_name: 'John', last_name: 'Doe', full_name: 'John Doe' }, { location: { lat: 23.423, lon: 93.33 } }, ]; const test = await opTest.init(config); const results = await test.run(data); results.forEach((d, index) => { // console.log('what is d', d) expect(DataEntity.isDataEntity(d)).toEqual(true); expect(d).toEqual(resultSet[index]); expect(d.getMetadata('selectors')).toBeDefined(); }); }); it('can chain selection => transform => selection', async () => { const config: WatcherConfig = { rules: [getPath('transformRules5.txt')], }; const data = DataEntity.makeArray([ { hello: 'world', first: 'John', last: 'Doe' }, { hello: 'world', first: 'Jane', last: 'Austin' }, { hello: 'world', first: 'Jane', last: 'Doe' }, { hello: 'world' }, ]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ first_name: 'Jane', last_name: 'Doe', full_name: 'Jane Doe' }); const metaData = results[0].getMetadata(); expect(metaData.selectors).toEqual(['hello:world', 'full_name:"Jane Doe"']); }); it('can chain selection => transform => selection => transform', async () => { const config: WatcherConfig = { rules: [getPath('transformRules6.txt')], }; const data = DataEntity.makeArray([ { hello: 'world', first: 'John', last: 'Doe' }, { hello: 'world', first: 'Jane', last: 'Austin' }, { hello: 'world', first: 'Jane', last: 'Doe' }, { hello: 'world' }, ]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ first_name: 'Jane', full_name: 'Jane Doe', last_name: 'Doe', transfered_name: 'Jane Doe', }); const metaData = results[0].getMetadata(); expect(metaData.selectors).toEqual(['hello:world', 'full_name:"Jane Doe"']); }); it('can chain selection => validation => post_process', async () => { const config: WatcherConfig = { rules: [getPath('transformRules26.txt')], }; const data = DataEntity.makeArray([ { some: 'value', field: 'some@gmail.com' }, { some: 'value', field: '12398074##&*' }, { some: 'value', field: 'other@tera.io' }, ]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(2); expect(results[0]).toEqual({ newField: 'some@gmail.com', final: ['gmail'] }); expect(results[1]).toEqual({ newField: 'other@tera.io', final: ['tera'] }); }); it('validations work with the different ways to configure them', async () => { const config: WatcherConfig = { rules: [getPath('transformRules7.txt')], }; const config2: WatcherConfig = { rules: [getPath('transformRules8.txt')], }; const config3: WatcherConfig = { rules: [getPath('transformRules9.txt')], }; const data = [ { hello: 'world', txt: 'first' }, { hello: 'world', txt: 'second' }, { hello: 'world', txt: 'third' }, { hello: 'world' }, ]; const transformedData = data.map((doc) => { if (doc.txt) { const txt = Buffer.from(doc.txt).toString('hex'); return Object.assign({}, doc, { txt }); } return doc; }); const resultsData1 = data.map((doc) => ({ hex: doc.txt })); const data1 = DataEntity.makeArray(cloneDeep(transformedData)); const data2 = DataEntity.makeArray(cloneDeep(transformedData)); const data3 = DataEntity.makeArray(cloneDeep(transformedData)); const test1 = await opTest.init(config); const results1 = await test1.run(data1); expect(results1.length).toEqual(3); results1.forEach((result, ind) => { expect(result).toEqual(resultsData1[ind]); expect(DataEntity.isDataEntity(result)).toEqual(true); }); const test2 = await opTest.init(config2); const results2 = await test2.run(data2); expect(results2.length).toEqual(3); results2.forEach((result, ind) => { expect(result).toEqual(resultsData1[ind]); expect(DataEntity.isDataEntity(result)).toEqual(true); }); const test3 = await opTest.init(config3); const results3 = await test3.run(data3); expect(results3.length).toEqual(3); results3.forEach((result, ind) => { expect(result).toEqual(resultsData1[ind]); expect(DataEntity.isDataEntity(result)).toEqual(true); }); }); it('can target multiple transforms on the same field', async () => { const config: WatcherConfig = { rules: [getPath('transformRules10.txt')], }; const data = DataEntity.makeArray([ { domain: 'example.com', url: 'http:// www.example.com/path?field1=blah&field2=moreblah&field3=evenmoreblah' }, { domain: 'other.com', url: 'http:// www.example.com/path?field1=blah&field2=moreblah&field3=evenmoreblah' }, { domain: 'example.com', url: 'http:// www.example.com/path?field5=blah&field6=moreblah&field7=evenmoreblah' }, ]); const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ field1: 'blah', field2: 'moreblah', field3: 'evenmoreblah' }); expect(DataEntity.isDataEntity(results[0])).toEqual(true); }); it('can run the two variations of the same config', async () => { const config: WatcherConfig = { rules: [getPath('transformRules11.txt')], }; const config2: WatcherConfig = { rules: [getPath('transformRules12.txt')], }; const formatedWord = Buffer.from('evenmoreblah').toString('base64'); const url = `http:// www.example.com/path?field1=blah&field2=moreblah&field3=${formatedWord}`; const data = [ { domain: 'example.com', url }, { domain: 'other.com', url }, { domain: 'example.com', url: 'http:// www.example.com/path?field5=blah&field6=moreblah&field7=evenmoreblah' }, ]; const data1 = DataEntity.makeArray(cloneDeep(data)); const data2 = DataEntity.makeArray(cloneDeep(data)); const test1 = await opTest.init(config); const results1 = await test1.run(data1); expect(results1.length).toEqual(1); expect(results1[0]).toEqual({ field3: 'evenmoreblah' }); expect(DataEntity.isDataEntity(results1[0])).toEqual(true); const test2 = await opTest.init(config2); const results2 = await test2.run(data2); expect(results2.length).toEqual(1); expect(results2[0]).toEqual({ field3: 'evenmoreblah' }); expect(DataEntity.isDataEntity(results2[0])).toEqual(true); }); it('do more basic extractions', async () => { const config: WatcherConfig = { rules: [getPath('transformRules13.txt')], }; const data = DataEntity.makeArray([{ hello: 'world', data: 'someData' }, { hello: 'world', data: 'otherData' }]); const resultSet = [{ other: 'someData' }, { other: 'otherData' }]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(2); results.forEach((d, index) => { expect(DataEntity.isDataEntity(d)).toEqual(true); expect(d).toEqual(resultSet[index]); }); }); it('should transform data if previous transforms had occured', async () => { const config: WatcherConfig = { rules: [getPath('transformRules14.txt')], }; const date = new Date().toISOString(); const key = '123456789'; const data = DataEntity.makeArray([ { domain: 'example.com', url: 'http:// www.example.com/path?value=blah&value2=moreblah&value3=evenmoreblah', date, key }, ]); // should not expect anything back const data2 = DataEntity.makeArray([{ domain: 'example.com', hello: 'world', data: 'otherData', date, key }, {}]); // should not expect anything back const data3 = DataEntity.makeArray([ { domain: 'example.com', url: 'http:// www.example.com/path?value=blah&value2=moreblah&value3=evenmoreblah', date }, {}, ]); const test1 = await opTest.init(config); const results1 = await test1.run(data); expect(results1.length).toEqual(1); expect(results1[0]).toEqual({ value: 'blah', value2: 'moreblah', key, date, }); const test2 = await opTest.init(config); const results2 = await test2.run(data2); expect(results2.length).toEqual(0); expect(results2).toEqual([]); const test3 = await opTest.init(config); const results3 = await test3.run(data3); expect(results3.length).toEqual(1); expect(results3[0]).toEqual({ value: 'blah', value2: 'moreblah', date, }); }); it('should transform data if previous transforms had occured with other post_processing', async () => { const config: WatcherConfig = { rules: [getPath('transformRules15.txt')], }; const date = new Date().toISOString(); const key = '123456789'; const data = DataEntity.makeArray([ { host: 'fc2.com', field1: `http://www.example.com/path?field1=${encode(key, 'base64')}&value2=moreblah&value3=evenmoreblah`, date, key, }, { host: 'fc2.com', key, date }, { host: 'fc2.com', field1: 'someRandomStr', key, date }, { host: 'fc2.com', field1: [ 'someRandomStr', `http://www.example.com/path?field1=${encode(key, 'base64')}&value2=moreblah&value3=evenmoreblah`, ], key, date, }, ]); // should not expect anything back const data2 = DataEntity.makeArray([{ domain: 'example.com', hello: 'world', data: 'otherData', date, key }, {}]); // should not expect anything back const data3 = DataEntity.makeArray([ { domain: 'example.com', url: 'http://www.example.com/path?value=blah&value2=moreblah&value3=evenmoreblah', date }, {}, ]); const test1 = await opTest.init(config); const results1 = await test1.run(data); expect(results1.length).toEqual(2); expect(results1[0]).toEqual({ field1: key, date, }); expect(results1[1]).toEqual({ field1: [key], date, }); const test2 = await opTest.init(config); const results2 = await test2.run(data2); expect(results2.length).toEqual(0); expect(results2).toEqual([]); const test3 = await opTest.init(config); const results3 = await test3.run(data3); expect(results3.length).toEqual(0); expect(results3).toEqual([]); }); // TODO fix this test description is ambiguous, use describe blocks to group tests it('should work like the test before but with different config layout', async () => { const config: WatcherConfig = { rules: [getPath('transformRules16.txt')], }; const date = new Date().toISOString(); const key = '123456789'; const data = DataEntity.makeArray([ { host: 'fc2.com', field1: `http://www.example.com/path?field1=${encode(key, 'base64')}&value2=moreblah&value3=evenmoreblah`, date, key, }, { host: 'fc2.com', key, date }, { host: 'fc2.com', field1: 'someRandomStr', key, date }, { host: 'fc2.com', field1: [ 'someRandomStr', `http://www.example.com/path?field1=${encode(key, 'base64')}&value2=moreblah&value3=evenmoreblah`, ], key, date, }, { date, other: 'things' }, ]); // should not expect anything back const data2 = DataEntity.makeArray([{ domain: 'example.com', hello: 'world', data: 'otherData', date, key }, {}]); // should not expect anything back const data3 = DataEntity.makeArray([ { domain: 'example.com', url: 'http://www.example.com/path?value=blah&value2=moreblah&value3=evenmoreblah', date }, {}, ]); const test1 = await opTest.init(config); const results1 = await test1.run(data); expect(results1.length).toEqual(2); expect(results1[0]).toEqual({ field1: key, date, }); expect(results1[1]).toEqual({ field1: [key], date, }); const test2 = await opTest.init(config); const results2 = await test2.run(data2); expect(results2.length).toEqual(0); expect(results2).toEqual([]); const test3 = await opTest.init(config); const results3 = await test3.run(data3); expect(results3.length).toEqual(0); expect(results3).toEqual([]); }); it('chaining configurations sample 1', async () => { const config: WatcherConfig = { rules: [getPath('transformRules17.txt')], }; const key = '123456789'; const data = DataEntity.makeArray([ { host: 'example.com', field1: `http://www.example.com/path?field1=${encode(key, 'base64')}&value2=moreblah&value3=evenmoreblah`, }, { host: 'example.com' }, { host: 'example.com', field1: 'someRandomStr' }, { host: 'example.com', field1: [ 'someRandomStr', `http://www.example.com/path?field1=${encode(key, 'base64')}&value2=moreblah&value3=evenmoreblah`, ], }, ]); const test1 = await opTest.init(config); const results1 = await test1.run(data); expect(results1.length).toEqual(2); expect(results1[0]).toEqual({ field1: key, }); expect(results1[1]).toEqual({ field1: [key], }); }); it('build an array with post_process array', async () => { const config: WatcherConfig = { rules: [getPath('transformRules19.txt')], }; const key = '123456789'; const data = DataEntity.makeArray([ { selectfield: 'value' }, { selectfield: 'value', url: `http://www.example.com/path?field1=${key}&field2=moreblah&field3=evenmoreblah` }, ]); const test1 = await opTest.init(config); const results1 = await test1.run(data); expect(results1.length).toEqual(1); expect(results1[0]).toEqual({ myfield: [key, 'moreblah'], }); }); it('build an array with post_process array with validations', async () => { const config: WatcherConfig = { rules: [getPath('transformRules20.txt')], }; const key = '123456789'; const data = DataEntity.makeArray([ { selectfield: 'value' }, { selectfield: 'value', url: `http://www.example.com/path?field1=${key}&field2=moreblah&field3=evenmoreblah&field4=finalCountdown`, }, ]); const test1 = await opTest.init(config); const results1 = await test1.run(data); expect(results1.length).toEqual(1); expect(results1[0]).toEqual({ firstSet: [Number(key), 'moreblah'], secondSet: ['evenmoreblah', 'finalCountdown'], }); }); it('can load plugins', async () => { const config: WatcherConfig = { rules: [getPath('transformRules18.txt')], }; const key = '123456789'; const data = DataEntity.makeArray([ { host: 'example.com', field1: `http://www.example.com/path?field1=${key}&value2=moreblah&value3=evenmoreblah` }, { host: 'example.com' }, { host: 'example.com', field1: 'someRandomStr' }, { host: 'example.com', field1: ['someRandomStr', `http://www.example.com/path?field1=${key}&value2=moreblah&value3=evenmoreblah`], }, { size: 2 }, ]); const test1 = await opTest.init(config, [Plugins]); const results1 = await test1.run(data); expect(results1.length).toEqual(3); expect(results1[0]).toEqual({ field1: key, }); expect(results1[1]).toEqual({ field1: [key], }); expect(results1[2]).toEqual({ height: 4, }); }); it('can extract json and omit intermediate fields', async () => { const config: WatcherConfig = { rules: [getPath('transformRules21.txt')], }; const data = [ new DataEntity({ some: 'value', field: JSON.stringify('something') }), new DataEntity({ some: 'value', field: JSON.stringify({ field: 'value' }) }), ]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ myfield: 'value' }); }); it('can run and omit fields', async () => { const config: WatcherConfig = { rules: [getPath('transformRules22.txt')], }; const data = [ new DataEntity({ some: 'value', field: 'something' }), new DataEntity({ some: 'value', field: 'null' }), new DataEntity({ some: 'value', field: 'otherthing' }), ]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(2); expect(results[0]).toEqual({ newField: 'something' }); expect(results[1]).toEqual({ newField: 'otherthing' }); }); it('other_match_required can have selectors to narrow their fields', async () => { const config: WatcherConfig = { rules: [getPath('transformRules24.txt')], }; const date = new Date().toISOString(); const key = '123456789'; const data1 = DataEntity.makeArray([ { some: 'value', input: 'stuff' }, { some: 'value', date }, { some: 'value', input: 'stuff', date }, { some: 'value', input: 'stuff', date, key }, ]); const data2 = DataEntity.makeArray([ { other: 'value', other_input: 'stuff' }, { other: 'value', date }, { other: 'value', other_input: 'stuff', date }, { other: 'value', other_input: 'stuff', date, key }, ]); const data1Results = data1.reduce<Record<string, any>[]>((arr, obj) => { if (obj.input) { const results: any = {}; results.output = obj.input; if (obj.date) results.date = obj.date; arr.push(results); } return arr; }, []); const data2Results = data2.reduce<Record<string, any>[]>((arr, obj) => { if (obj.other_input) { const results: any = {}; results.other_output = obj.other_input; if (obj.date) results.date = obj.date; if (obj.key) results.output_key = obj.key; arr.push(results); } return arr; }, []); const test = await opTest.init(config); const results1 = await test.run(data1); expect(results1.length).toEqual(3); results1.forEach((result, ind) => { expect(result).toEqual(data1Results[ind]); }); const test2 = await opTest.init(config); const results2 = await test2.run(data2); expect(results2.length).toEqual(3); results2.forEach((result, ind) => { expect(result).toEqual(data2Results[ind]); }); }); it('other_match_required regression test', async () => { const config: WatcherConfig = { rules: [getPath('warnRules.txt')], }; const data = DataEntity.makeArray([ { some: 'data', field: 'hello', otherField: 'world' }, { some: 'data', field: 'hello' }, ]); const finalData = DataEntity.makeArray([ { final: 'hello', lastField: 'world' }, ]); const test = await opTest.init(config); const results = await test.run(data); expect(results).toBeArrayOfSize(1); expect(results).toEqual(finalData); }); it('can run a regression test1', async () => { const config: WatcherConfig = { rules: [getPath('transformRules23.txt')], }; const data = [ new DataEntity({ somefield: `something&value=${encode('{%20"some":%20"data"}', 'base64')}` }), new DataEntity({ field: 'null' }), ]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ hashoutput: { some: 'data' } }); }); it('can run a array post_process operation', async () => { const config: WatcherConfig = { rules: [getPath('transformRules28.txt')], }; const data = [new DataEntity({ hello: 'world', field1: 'hello', field2: 'world' }), new DataEntity({ field: 'null' })]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ results: ['hello', 'world'] }); }); it('can run a dedup post_process operation', async () => { const config: WatcherConfig = { rules: [getPath('transformRules29.txt')], }; const data = [ new DataEntity({ hello: 'world', field1: 'hello', field2: 'world', field3: 'world' }), new DataEntity({ field: 'null' }), ]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ results: ['hello', 'world'] }); }); it('can run multivalue on two different post_process extractions', async () => { const config: WatcherConfig = { rules: [getPath('transformRules25.txt')], }; const data = [new DataEntity({ some: 'value', other: 'some_data' })]; const test = await opTest.init(config); const results = await test.run(data); expect(results[0]).toEqual({ field: 'some_data', first_copy: ['some_data'], second_copy: ['data'], third_copy: ['some'], }); }); it('can apply other_match_required in post_process extraction rule', async () => { const config: WatcherConfig = { rules: [getPath('transformRules41.txt')], }; const data = [ new DataEntity({ some: 'data', field1: 'field1=12345', field2: 'yo' }), new DataEntity({ some: 'data', field1: 'field1=12345' }) ]; const test = await opTest.init(config); const results = test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ field3: '1234', field2: 'yo' }); }); it('can catch all selector extractions for transformRules31', async () => { const config: WatcherConfig = { rules: [getPath('transformRules31.txt')], }; const data = [ new DataEntity({ some: 'value', other: 'some_data', first: '1234' }), new DataEntity({ some: 'stuff', field: 'some_data', id: '12345' }), ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results[0]).toEqual({ double: 2468, thing: 'value', data: 'data', last: 1234, }); expect(results[1]).toEqual({ thing: 'stuff', valid_id: 12345, double: 24690, }); }); it('*-match-required, no-match-regular-selector and *-selector rule bug', async () => { const config: WatcherConfig = { rules: [getPath('transformRules32.txt')], }; const data = [new DataEntity({ some: 'stuff', field: 'some_data', id: '12345' })]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results[0]).toEqual({ thing: 'stuff', valid_id: '12345', }); }); it('can catch all selector extractions for sameSourceDifferentSelector', async () => { const config: WatcherConfig = { rules: [getPath('sameSourceDifferentSelector.txt')], }; const data = [ new DataEntity({ some: 'selector', inputarray: ['Value1=email1@gmail.com', 'Value1=asdfasdf'] }), new DataEntity({ some: 'selector2', inputarray: ['Value2=email2@gmail.com', 'Value2=asdfasdf'] }), ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results[0]).toEqual({ email: ['email1@gmail.com'] }); expect(results[1]).toEqual({ email: ['email2@gmail.com'] }); }); it('properly extract multiple fields, regression test', async () => { const config: WatcherConfig = { rules: [getPath('transformRules33.txt')], }; const data = [ new DataEntity({ field1: 'value' }) ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([ { fields: [ 'value', ] } ]); }); it('can set values in extractions', async () => { const config: WatcherConfig = { rules: [getPath('transformRules37.txt')], }; const data = [ new DataEntity({ field1: 'value' }) ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([ { wasSet: true } ]); }); it('can conditionally set values in extractions', async () => { const config: WatcherConfig = { rules: [getPath('transformRules38.txt')], }; const data = [ new DataEntity({ html: '<value>' }), new DataEntity({ some: 'otherValue' }) ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([ { output: 'value', count: 20 } ]); }); it('can transform with source/target instead of source/target', async () => { const config: WatcherConfig = { rules: [getPath('transformRules39.txt')], }; const data = [ new DataEntity({ html: '<value>' }), new DataEntity({ some: 'otherValue' }) ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([ { output: 'value', count: 20 } ]); }); it('missing fields test', async () => { const config: WatcherConfig = { rules: [getPath('transformRules40.txt')], }; const data = [ new DataEntity({ badField: 'value' }), ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([]); }); it('should be able to turn a value into an array with jexl', async () => { const config: WatcherConfig = { rules: [getPath('regression-test1.txt')], }; const data = [ new DataEntity({ other: 'stuff' }), new DataEntity({ field: 'value', other: 'stuff' }), new DataEntity({ field: 'value' }), ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([ { field: ['value'], other: 'stuff' }, { field: ['value'] } ]); }); it('should be able to turn a value into an array with array post_process', async () => { const config: WatcherConfig = { rules: [getPath('regression-test2.txt')], }; const data = [ new DataEntity({ other: 'stuff' }), new DataEntity({ field: 'value', other: 'stuff' }), new DataEntity({ field: 'value' }), ]; const test = await opTest.init(config, [Plugins]); const results = await test.run(data); expect(results).toEqual([ { field: ['value'], other: 'stuff' }, { field: ['value'] } ]); }); it('can run with variables', async () => { const config: WatcherConfig = { rules: [getPath('transformRules28.txt')], variables: { hello: 'world' } }; const data = [new DataEntity({ hello: 'world', field1: 'hello', field2: 'world' }), new DataEntity({ field: 'null' })]; const test = await opTest.init(config); const results = await test.run(data); expect(results.length).toEqual(1); expect(results[0]).toEqual({ results: ['hello', 'world'] }); }); it('should ignore empty strings', async () => { const config: WatcherConfig = { rules: [getPath('regression-test3.txt')], }; const data = [ new DataEntity({ field1: false }), new DataEntity({ field1: '' }), new DataEntity({ field1: null }), ]; const test = await opTest.init(config); const results = await test.run(data); expect(results).toBeArrayOfSize(0); }); });
the_stack
* @module Core */ import { BeEvent, CompressedId64Set, IDisposable, OrderedId64Iterable } from "@itwin/core-bentley"; import { IModelConnection, IpcApp } from "@itwin/core-frontend"; import { UnitSystemKey } from "@itwin/core-quantity"; import { Content, ContentDescriptorRequestOptions, ContentInstanceKeysRequestOptions, ContentRequestOptions, ContentSourcesRequestOptions, ContentUpdateInfo, Descriptor, DescriptorOverrides, DisplayLabelRequestOptions, DisplayLabelsRequestOptions, DisplayValueGroup, DistinctValuesRequestOptions, ElementProperties, FilterByInstancePathsHierarchyRequestOptions, FilterByTextHierarchyRequestOptions, HierarchyRequestOptions, HierarchyUpdateInfo, InstanceKey, Item, Key, KeySet, LabelDefinition, Node, NodeKey, NodeKeyJSON, NodePathElement, Paged, PagedResponse, PageOptions, PresentationIpcEvents, RpcRequestsHandler, Ruleset, RulesetVariable, SelectClassInfo, SingleElementPropertiesRequestOptions, UpdateInfo, UpdateInfoJSON, VariableValueTypes, } from "@itwin/presentation-common"; import { IpcRequestsHandler } from "./IpcRequestsHandler"; import { LocalizationHelper } from "./LocalizationHelper"; import { RulesetManager, RulesetManagerImpl } from "./RulesetManager"; import { RulesetVariablesManager, RulesetVariablesManagerImpl } from "./RulesetVariablesManager"; import { TRANSIENT_ELEMENT_CLASSNAME } from "./selection/SelectionManager"; import { StateTracker } from "./StateTracker"; /** * Data structure that describes IModel hierarchy change event arguments. * @alpha */ export interface IModelHierarchyChangeEventArgs { /** Id of ruleset that was used to create hierarchy. */ rulesetId: string; /** Hierarchy changes info. */ updateInfo: HierarchyUpdateInfo; /** Key of iModel that was used to create hierarchy. It matches [[IModelConnection.key]] property. */ imodelKey: string; } /** * Data structure that describes iModel content change event arguments. * @alpha */ export interface IModelContentChangeEventArgs { /** Id of ruleset that was used to create content. */ rulesetId: string; /** Content changes info. */ updateInfo: ContentUpdateInfo; /** Key of iModel that was used to create content. It matches [[IModelConnection.key]] property. */ imodelKey: string; } /** * Properties used to configure [[PresentationManager]] * @public */ export interface PresentationManagerProps { /** * Sets the active locale to use when localizing presentation-related * strings. It can later be changed through [[PresentationManager]]. */ activeLocale?: string; /** * Sets the active unit system to use for formatting property values with * units. Default presentation units are used if this is not specified. The active unit * system can later be changed through [[PresentationManager]] or overriden for each request. */ activeUnitSystem?: UnitSystemKey; /** * ID used to identify client that requests data. Generally, clients should * store this ID in their local storage so the ID can be reused across * sessions - this allows reusing some caches. * * Defaults to a unique GUID as a client id. */ clientId?: string; /** @internal */ rpcRequestsHandler?: RpcRequestsHandler; /** @internal */ ipcRequestsHandler?: IpcRequestsHandler; /** @internal */ stateTracker?: StateTracker; } /** * Frontend Presentation manager which basically just forwards all calls to * the backend implementation. * * @public */ export class PresentationManager implements IDisposable { private _requestsHandler: RpcRequestsHandler; private _rulesets: RulesetManager; private _localizationHelper: LocalizationHelper; private _rulesetVars: Map<string, RulesetVariablesManager>; private _clearEventListener?: () => void; private _connections: Map<IModelConnection, Promise<void>>; private _ipcRequestsHandler?: IpcRequestsHandler; private _stateTracker?: StateTracker; /** * An event raised when hierarchies created using specific ruleset change * @alpha */ public onIModelHierarchyChanged = new BeEvent<(args: IModelHierarchyChangeEventArgs) => void>(); /** * An event raised when content created using specific ruleset changes * @alpha */ public onIModelContentChanged = new BeEvent<(args: IModelContentChangeEventArgs) => void>(); /** Get / set active locale used for localizing presentation data */ public activeLocale: string | undefined; /** Get / set active unit system used to format property values with units */ public activeUnitSystem: UnitSystemKey | undefined; private constructor(props?: PresentationManagerProps) { if (props) { this.activeLocale = props.activeLocale; this.activeUnitSystem = props.activeUnitSystem; } this._requestsHandler = props?.rpcRequestsHandler ?? new RpcRequestsHandler(props ? { clientId: props.clientId } : undefined); this._rulesetVars = new Map<string, RulesetVariablesManager>(); this._rulesets = RulesetManagerImpl.create(); this._localizationHelper = new LocalizationHelper(); this._connections = new Map<IModelConnection, Promise<void>>(); if (IpcApp.isValid) { // Ipc only works in ipc apps, so the `onUpdate` callback will only be called there. this._clearEventListener = IpcApp.addListener(PresentationIpcEvents.Update, this.onUpdate); this._ipcRequestsHandler = props?.ipcRequestsHandler ?? new IpcRequestsHandler(this._requestsHandler.clientId); this._stateTracker = props?.stateTracker ?? new StateTracker(this._ipcRequestsHandler); } } public dispose() { this._requestsHandler.dispose(); if (this._clearEventListener) { this._clearEventListener(); this._clearEventListener = undefined; } } private async onConnection(imodel: IModelConnection) { if (!this._connections.has(imodel)) this._connections.set(imodel, this.initializeIModel(imodel)); await this._connections.get(imodel); } private async initializeIModel(imodel: IModelConnection) { imodel.onClose.addOnce(() => { this._connections.delete(imodel); }); await this.onNewiModelConnection(imodel); } // eslint-disable-next-line @typescript-eslint/naming-convention private onUpdate = (_evt: Event, report: UpdateInfoJSON) => { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.handleUpdateAsync(UpdateInfo.fromJSON(report)); }; /** @note This is only called in native apps after changes in iModels */ private async handleUpdateAsync(report: UpdateInfo) { for (const imodelKey in report) { // istanbul ignore if if (!report.hasOwnProperty(imodelKey)) continue; const imodelReport = report[imodelKey]; for (const rulesetId in imodelReport) { // istanbul ignore if if (!imodelReport.hasOwnProperty(rulesetId)) continue; const updateInfo = imodelReport[rulesetId]; if (updateInfo.content) this.onIModelContentChanged.raiseEvent({ rulesetId, updateInfo: updateInfo.content, imodelKey }); if (updateInfo.hierarchy) this.onIModelHierarchyChanged.raiseEvent({ rulesetId, updateInfo: updateInfo.hierarchy, imodelKey }); } } } /** Function that is called when a new IModelConnection is used to retrieve data. * @internal */ public async onNewiModelConnection(_: IModelConnection) { } /** * Create a new PresentationManager instance * @param props Optional properties used to configure the manager */ public static create(props?: PresentationManagerProps) { return new PresentationManager(props); } /** @internal */ public get rpcRequestsHandler() { return this._requestsHandler; } /** @internal */ public get ipcRequestsHandler() { return this._ipcRequestsHandler; } /** @internal */ public get stateTracker() { return this._stateTracker; } /** * Get rulesets manager */ public rulesets() { return this._rulesets; } /** * Get ruleset variables manager for specific ruleset * @param rulesetId Id of the ruleset to get the vars manager for */ public vars(rulesetId: string) { if (!this._rulesetVars.has(rulesetId)) { const varsManager = new RulesetVariablesManagerImpl(rulesetId, this._ipcRequestsHandler); this._rulesetVars.set(rulesetId, varsManager); } return this._rulesetVars.get(rulesetId)!; } private toRpcTokenOptions<TOptions extends { imodel: IModelConnection, locale?: string, unitSystem?: UnitSystemKey, rulesetVariables?: RulesetVariable[] }>(requestOptions: TOptions) { // 1. put default `locale` and `unitSystem` // 2. put all `requestOptions` members (if `locale` or `unitSystem` are set, they'll override the defaults put at #1) // 3. put `imodel` of type `IModelRpcProps` which overwrites the `imodel` from `requestOptions` put at #2 const defaultOptions: Pick<TOptions, "locale" | "unitSystem"> = {}; if (this.activeLocale) defaultOptions.locale = this.activeLocale; if (this.activeUnitSystem) defaultOptions.unitSystem = this.activeUnitSystem; const { imodel, rulesetVariables, ...rpcRequestOptions } = requestOptions; return { ...defaultOptions, ...rpcRequestOptions, ...(rulesetVariables ? { rulesetVariables: rulesetVariables.map(RulesetVariable.toJSON) } : {}), imodel: imodel.getRpcProps(), }; } private async addRulesetAndVariablesToOptions<TOptions extends { rulesetOrId: Ruleset | string, rulesetVariables?: RulesetVariable[] }>(options: TOptions) { const { rulesetOrId, rulesetVariables } = options; let foundRulesetOrId: Ruleset | string; if (typeof rulesetOrId === "object") { foundRulesetOrId = rulesetOrId; } else { const foundRuleset = await this._rulesets.get(rulesetOrId); foundRulesetOrId = foundRuleset ? foundRuleset.toJSON() : rulesetOrId; } const rulesetId = (typeof foundRulesetOrId === "object") ? foundRulesetOrId.id : foundRulesetOrId; // All Id64Array variable values must be sorted for serialization to JSON to work. RulesetVariablesManager // sorts them before storing, so that part is taken care of, but we need to ensure that variables coming from // request options are also sorted. const variables = (rulesetVariables ?? []).map((variable) => { if (variable.type === VariableValueTypes.Id64Array) return { ...variable, value: OrderedId64Iterable.sortArray(variable.value) }; return variable; }); if (!this._ipcRequestsHandler) { // only need to add variables from variables manager if there's no IPC // handler - if there is one, the variables are already known by the backend variables.push(...this.vars(rulesetId).getAllVariables()); } return { ...options, rulesetOrId: foundRulesetOrId, rulesetVariables: variables }; } /** Retrieves nodes */ public async getNodes(requestOptions: Paged<HierarchyRequestOptions<IModelConnection, NodeKey, RulesetVariable>>): Promise<Node[]> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, parentKey: optionalNodeKeyToJson(options.parentKey) }); const result = await buildPagedArrayResponse(options.paging, async (partialPageOptions) => this._requestsHandler.getPagedNodes({ ...rpcOptions, paging: partialPageOptions })); return this._localizationHelper.getLocalizedNodes(result.items.map(Node.fromJSON)); } /** Retrieves nodes count. */ public async getNodesCount(requestOptions: HierarchyRequestOptions<IModelConnection, NodeKey, RulesetVariable>): Promise<number> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, parentKey: optionalNodeKeyToJson(options.parentKey) }); return this._requestsHandler.getNodesCount(rpcOptions); } /** Retrieves total nodes count and a single page of nodes. */ public async getNodesAndCount(requestOptions: Paged<HierarchyRequestOptions<IModelConnection, NodeKey, RulesetVariable>>): Promise<{ count: number, nodes: Node[] }> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, parentKey: optionalNodeKeyToJson(options.parentKey) }); const result = await buildPagedArrayResponse(options.paging, async (partialPageOptions) => this._requestsHandler.getPagedNodes({ ...rpcOptions, paging: partialPageOptions })); return { count: result.total, nodes: this._localizationHelper.getLocalizedNodes(result.items.map(Node.fromJSON)), }; } /** Retrieves paths from root nodes to children nodes according to specified keys. Intersecting paths will be merged. */ public async getNodePaths(requestOptions: FilterByInstancePathsHierarchyRequestOptions<IModelConnection, RulesetVariable>): Promise<NodePathElement[]> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, instancePaths: options.instancePaths.map((p) => p.map(InstanceKey.toJSON)) }); const result = await this._requestsHandler.getNodePaths(rpcOptions); return result.map(NodePathElement.fromJSON); } /** Retrieves paths from root nodes to nodes containing filter text in their label. */ public async getFilteredNodePaths(requestOptions: FilterByTextHierarchyRequestOptions<IModelConnection, RulesetVariable>): Promise<NodePathElement[]> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const result = await this._requestsHandler.getFilteredNodePaths(this.toRpcTokenOptions(options)); return result.map(NodePathElement.fromJSON); } /** * Get all content sources for a given list of classes. * @beta */ public async getContentSources(requestOptions: ContentSourcesRequestOptions<IModelConnection>): Promise<SelectClassInfo[]> { await this.onConnection(requestOptions.imodel); const rpcOptions = this.toRpcTokenOptions(requestOptions); const result = await this._requestsHandler.getContentSources(rpcOptions); return SelectClassInfo.listFromCompressedJSON(result.sources, result.classesMap); } /** Retrieves the content descriptor which describes the content and can be used to customize it. */ public async getContentDescriptor(requestOptions: ContentDescriptorRequestOptions<IModelConnection, KeySet, RulesetVariable>): Promise<Descriptor | undefined> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, keys: stripTransientElementKeys(options.keys).toJSON(), }); const result = await this._requestsHandler.getContentDescriptor(rpcOptions); return Descriptor.fromJSON(result); } /** Retrieves overall content set size. */ public async getContentSetSize(requestOptions: ContentRequestOptions<IModelConnection, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>): Promise<number> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, descriptor: getDescriptorOverrides(requestOptions.descriptor), keys: stripTransientElementKeys(requestOptions.keys).toJSON(), }); return this._requestsHandler.getContentSetSize(rpcOptions); } /** Retrieves content which consists of a content descriptor and a page of records. */ public async getContent(requestOptions: Paged<ContentRequestOptions<IModelConnection, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>): Promise<Content | undefined> { return (await this.getContentAndSize(requestOptions))?.content; } /** Retrieves content set size and content which consists of a content descriptor and a page of records. */ public async getContentAndSize(requestOptions: Paged<ContentRequestOptions<IModelConnection, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>): Promise<{ content: Content, size: number } | undefined> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = this.toRpcTokenOptions({ ...options, descriptor: getDescriptorOverrides(requestOptions.descriptor), keys: stripTransientElementKeys(requestOptions.keys).toJSON(), }); let descriptor = (requestOptions.descriptor instanceof Descriptor) ? requestOptions.descriptor : undefined; const result = await buildPagedArrayResponse(options.paging, async (partialPageOptions, requestIndex) => { if (0 === requestIndex && !descriptor) { const content = await this._requestsHandler.getPagedContent({ ...rpcOptions, paging: partialPageOptions }); if (content) { descriptor = Descriptor.fromJSON(content.descriptor); return content.contentSet; } return { total: 0, items: [] }; } return this._requestsHandler.getPagedContentSet({ ...rpcOptions, paging: partialPageOptions }); }); if (!descriptor) return undefined; const items = result.items.map((itemJson) => Item.fromJSON(itemJson)).filter<Item>((item): item is Item => (item !== undefined)); return { size: result.total, content: this._localizationHelper.getLocalizedContent(new Content(descriptor, items)), }; } /** Retrieves distinct values of specific field from the content. */ public async getPagedDistinctValues(requestOptions: DistinctValuesRequestOptions<IModelConnection, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>): Promise<PagedResponse<DisplayValueGroup>> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = { ...this.toRpcTokenOptions(options), descriptor: getDescriptorOverrides(options.descriptor), keys: stripTransientElementKeys(options.keys).toJSON(), }; const result = await buildPagedArrayResponse(requestOptions.paging, async (partialPageOptions) => this._requestsHandler.getPagedDistinctValues({ ...rpcOptions, paging: partialPageOptions })); return { ...result, items: result.items.map(DisplayValueGroup.fromJSON), }; } /** * Retrieves property data in a simplified format for a single element specified by ID. * @beta */ public async getElementProperties(requestOptions: SingleElementPropertiesRequestOptions<IModelConnection>): Promise<ElementProperties | undefined> { await this.onConnection(requestOptions.imodel); return this._requestsHandler.getElementProperties(this.toRpcTokenOptions(requestOptions)); } /** * Retrieves content item instance keys. * @beta */ public async getContentInstanceKeys(requestOptions: ContentInstanceKeysRequestOptions<IModelConnection, KeySet, RulesetVariable>): Promise<{ total: number, items: () => AsyncGenerator<InstanceKey> }> { await this.onConnection(requestOptions.imodel); const options = await this.addRulesetAndVariablesToOptions(requestOptions); const rpcOptions = { ...this.toRpcTokenOptions(options), keys: stripTransientElementKeys(options.keys).toJSON(), }; const props = { page: requestOptions.paging, get: async (page: Required<PageOptions>) => { const keys = await this._requestsHandler.getContentInstanceKeys({ ...rpcOptions, paging: page }); return { total: keys.total, items: keys.items.instanceKeys.reduce((instanceKeys, entry) => { for (const id of CompressedId64Set.iterable(entry[1])) { instanceKeys.push({ className: entry[0], id }); } return instanceKeys; }, new Array<InstanceKey>()), }; }, }; return createPagedGeneratorResponse(props); } /** Retrieves display label definition of specific item. */ public async getDisplayLabelDefinition(requestOptions: DisplayLabelRequestOptions<IModelConnection, InstanceKey>): Promise<LabelDefinition> { await this.onConnection(requestOptions.imodel); const rpcOptions = this.toRpcTokenOptions({ ...requestOptions, key: InstanceKey.toJSON(requestOptions.key) }); const result = await this._requestsHandler.getDisplayLabelDefinition(rpcOptions); return this._localizationHelper.getLocalizedLabelDefinition(LabelDefinition.fromJSON(result)); } /** Retrieves display label definition of specific items. */ public async getDisplayLabelDefinitions(requestOptions: DisplayLabelsRequestOptions<IModelConnection, InstanceKey>): Promise<LabelDefinition[]> { await this.onConnection(requestOptions.imodel); const rpcOptions = this.toRpcTokenOptions({ ...requestOptions, keys: requestOptions.keys.map(InstanceKey.toJSON) }); const result = await buildPagedArrayResponse(undefined, async (partialPageOptions) => { const partialKeys = (!partialPageOptions.start) ? rpcOptions.keys : rpcOptions.keys.slice(partialPageOptions.start); return this._requestsHandler.getPagedDisplayLabelDefinitions({ ...rpcOptions, keys: partialKeys }); }); return this._localizationHelper.getLocalizedLabelDefinitions(result.items.map(LabelDefinition.fromJSON)); } } const getDescriptorOverrides = (descriptorOrOverrides: Descriptor | DescriptorOverrides): DescriptorOverrides => { if (descriptorOrOverrides instanceof Descriptor) return descriptorOrOverrides.createDescriptorOverrides(); return descriptorOrOverrides; }; const optionalNodeKeyToJson = (key: NodeKey | undefined): NodeKeyJSON | undefined => key ? NodeKey.toJSON(key) : undefined; interface PagedGeneratorCreateProps<TPagedResponseItem> { page: PageOptions | undefined; get: (pageStart: Required<PageOptions>, requestIndex: number) => Promise<{ total: number, items: TPagedResponseItem[] }>; } async function createPagedGeneratorResponse<TPagedResponseItem>(props: PagedGeneratorCreateProps<TPagedResponseItem>) { let pageStart = props.page?.start ?? 0; let pageSize = props.page?.size ?? 0; let requestIndex = 0; const firstPage = await props.get({ start: pageStart, size: pageSize }, requestIndex++); return { total: firstPage.total, async *items() { let partialResult = firstPage; while (true) { for (const item of partialResult.items) { yield item; } const receivedItemsCount = partialResult.items.length; if (partialResult.total !== 0 && receivedItemsCount === 0) { if (pageStart >= partialResult.total) throw new Error(`Requested page with start index ${pageStart} is out of bounds. Total number of items: ${partialResult.total}`); throw new Error("Paged request returned non zero total count but no items"); } if (pageSize !== 0 && receivedItemsCount >= pageSize || receivedItemsCount >= (partialResult.total - pageStart)) break; if (pageSize !== 0) pageSize -= receivedItemsCount; pageStart += receivedItemsCount; partialResult = await props.get({ start: pageStart, size: pageSize }, requestIndex++); } }, }; } /** @internal */ export const buildPagedArrayResponse = async <TItem>(requestedPage: PageOptions | undefined, getter: (page: Required<PageOptions>, requestIndex: number) => Promise<PagedResponse<TItem>>): Promise<PagedResponse<TItem>> => { try { const items = new Array<TItem>(); const gen = await createPagedGeneratorResponse({ page: requestedPage, get: getter }); for await (const item of gen.items()) { items.push(item); } return { total: gen.total, items }; } catch { return { total: 0, items: [] }; } }; const stripTransientElementKeys = (keys: KeySet) => { if (!keys.some((key) => Key.isInstanceKey(key) && key.className === TRANSIENT_ELEMENT_CLASSNAME)) return keys; const copy = new KeySet(); copy.add(keys, (key) => { // the callback is not going to be called with EntityProps as KeySet converts them // to InstanceKeys, but we want to keep the EntityProps case for correctness // istanbul ignore next const isTransient = Key.isInstanceKey(key) && key.className === TRANSIENT_ELEMENT_CLASSNAME || Key.isEntityProps(key) && key.classFullName === TRANSIENT_ELEMENT_CLASSNAME; return !isTransient; }); return copy; };
the_stack
"use strict"; // IMPORTS // import tm = require("./projectManager"); import tu = require("./testUtil"); import su = require("./serverUtil"); import platform = require("./platform"); import path = require("path"); import assert = require("assert"); import Q = require("q"); // GLOBALS // var express = require("express"); var bodyparser = require("body-parser"); var projectManager = tm.ProjectManager; var testUtil = tu.TestUtil; var templatePath = testUtil.templatePath; var thisPluginPath = testUtil.readPluginPath(); var testRunDirectory = testUtil.readTestRunDirectory(); var updatesDirectory = testUtil.readTestUpdatesDirectory(); var onlyRunCoreTests = testUtil.readCoreTestsOnly(); var targetPlatforms: platform.IPlatform[] = platform.PlatformResolver.resolvePlatforms(testUtil.readTargetPlatforms()); var shouldUseWkWebView = testUtil.readShouldUseWkWebView(); var shouldSetup: boolean = testUtil.readShouldSetup(); var restartEmulators: boolean = testUtil.readRestartEmulators(); const TestAppName = "CodePushTest"; const TestNamespace = "com.microsoft.codepush.test"; const AcquisitionSDKPluginName = "code-push"; const WkWebViewEnginePluginName = "cordova-plugin-wkwebview-engine"; const ScenarioCheckForUpdatePath = "js/scenarioCheckForUpdate.js"; const ScenarioCheckForUpdateCustomKey = "js/scenarioCheckForUpdateCustomKey.js"; const ScenarioDownloadUpdate = "js/scenarioDownloadUpdate.js"; const ScenarioInstall = "js/scenarioInstall.js"; const ScenarioInstallOnResumeWithRevert = "js/scenarioInstallOnResumeWithRevert.js"; const ScenarioInstallOnRestartWithRevert = "js/scenarioInstallOnRestartWithRevert.js"; const ScenarioInstallOnRestart2xWithRevert = "js/scenarioInstallOnRestart2xWithRevert.js"; const ScenarioInstallWithRevert = "js/scenarioInstallWithRevert.js"; const ScenarioSync1x = "js/scenarioSync.js"; const ScenarioSyncResume = "js/scenarioSyncResume.js"; const ScenarioSyncResumeDelay = "js/scenarioSyncResumeDelay.js"; const ScenarioSyncRestartDelay = "js/scenarioSyncResumeDelay.js"; const ScenarioSync2x = "js/scenarioSync2x.js"; const ScenarioRestart = "js/scenarioRestart.js"; const ScenarioSyncMandatoryDefault = "js/scenarioSyncMandatoryDefault.js"; const ScenarioSyncMandatoryResume = "js/scenarioSyncMandatoryResume.js"; const ScenarioSyncMandatoryRestart = "js/scenarioSyncMandatoryRestart.js"; const UpdateDeviceReady = "js/updateDeviceReady.js"; const UpdateNotifyApplicationReady = "js/updateNotifyApplicationReady.js"; const UpdateSync = "js/updateSync.js"; const UpdateSync2x = "js/updateSync2x.js"; const UpdateNotifyApplicationReadyConditional = "js/updateNARConditional.js"; var mockResponse: any; var testMessageResponse: any; var testMessageCallback: (requestBody: any) => void; var updateCheckCallback: (requestBody: any) => void; var mockUpdatePackagePath: string; // FUNCTIONS // function cleanupTest(): void { console.log("Cleaning up!"); mockResponse = undefined; testMessageCallback = undefined; updateCheckCallback = undefined; testMessageResponse = undefined; } function setupTests(): void { it("sets up tests correctly", (done: any) => { var promises: Q.Promise<string>[] = []; targetPlatforms.forEach(platform => { promises.push(platform.getEmulatorManager().bootEmulator(restartEmulators)); }); console.log("Building test project."); promises.push(createTestProject(testRunDirectory)); console.log("Building update project."); promises.push(createTestProject(updatesDirectory)); Q.all<string>(promises).then(() => { done(); }, (error) => { done(error); }); }); } function createTestProject(directory: string): Q.Promise<string> { return projectManager.setupProject(directory, templatePath, TestAppName, TestNamespace) .then(() => { var promises: Q.Promise<string>[] = []; targetPlatforms.forEach(platform => { promises.push(projectManager.addPlatform(directory, platform)); }); return Q.all<string>(promises); }) .then(() => { return projectManager.addPlugin(directory, thisPluginPath); }); } function createDefaultResponse(): su.CheckForUpdateResponseMock { var defaultResponse = new su.CheckForUpdateResponseMock(); defaultResponse.download_url = ""; defaultResponse.description = ""; defaultResponse.is_available = false; defaultResponse.is_mandatory = false; defaultResponse.is_disabled = false; defaultResponse.target_binary_range = ""; defaultResponse.package_hash = ""; defaultResponse.label = ""; defaultResponse.package_size = 0; defaultResponse.should_run_binary_version = false; defaultResponse.update_app_version = false; return defaultResponse; } function createMockResponse(mandatory: boolean = false): su.CheckForUpdateResponseMock { var updateResponse = new su.CheckForUpdateResponseMock(); updateResponse.is_available = true; updateResponse.target_binary_range = "1.0.0"; updateResponse.download_url = "mock.url/download"; updateResponse.is_disabled = false; updateResponse.is_mandatory = mandatory; updateResponse.label = "mock-update"; updateResponse.package_hash = "12345-67890"; updateResponse.package_size = 12345; updateResponse.should_run_binary_version = false; updateResponse.update_app_version = false; return updateResponse; } function verifyMessages(expectedMessages: (string | su.AppMessage)[], deferred: Q.Deferred<void>): (requestBody: any) => void { var messageIndex = 0; return (requestBody: su.AppMessage) => { try { console.log("Message index: " + messageIndex); if (typeof expectedMessages[messageIndex] === "string") { assert.equal(requestBody.message, expectedMessages[messageIndex]); } else { assert(su.areEqual(requestBody, <su.AppMessage>expectedMessages[messageIndex])); } /* end of message array */ if (++messageIndex === expectedMessages.length) { deferred.resolve(undefined); } } catch (e) { deferred.reject(e); } }; } function runTests(targetPlatform: platform.IPlatform, useWkWebView: boolean): void { var server: any; function setupServer() { console.log("Setting up server at " + targetPlatform.getServerUrl()); var app = express(); app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: true })); app.use(function(req: any, res: any, next: any) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "*"); res.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, X-CodePush-SDK-Version, X-CodePush-Plugin-Version, X-CodePush-Plugin-Name"); next(); }); app.get("/v0.1/public/codepush/update_check", function(req: any, res: any) { updateCheckCallback && updateCheckCallback(req); res.send(mockResponse); console.log("Update check called from the app."); console.log("Request: " + JSON.stringify(req.query)); console.log("Response: " + JSON.stringify(mockResponse)); }); app.get("/v0.1/public/codepush/report_status/download", function(req: any, res: any) { console.log("Application downloading the package."); res.download(mockUpdatePackagePath); }); app.post("/reportTestMessage", function(req: any, res: any) { console.log("Application reported a test message."); console.log("Body: " + JSON.stringify(req.body)); if (!testMessageResponse) { console.log("Sending OK"); res.sendStatus(200); } else { console.log("Sending body: " + testMessageResponse); res.status(200).send(testMessageResponse); } testMessageCallback && testMessageCallback(req.body); }); var serverPortRegEx = /:([0-9]+)/; server = app.listen(+targetPlatform.getServerUrl().match(serverPortRegEx)[1]); } function cleanupServer(): void { if (server) { server.close(); server = undefined; } } function prepareTest(): Q.Promise<string> { return projectManager.prepareEmulatorForTest(TestNamespace, targetPlatform); } function getMockResponse(mandatory: boolean = false, randomHash: boolean = true): su.CheckForUpdateResponseMock { var updateResponse = createMockResponse(mandatory); updateResponse.download_url = targetPlatform.getServerUrl() + "/v0.1/public/codepush/report_status/download"; // we need unique hashes to avoid conflicts - the application is not uninstalled between tests // and we store the failed hashes in preferences if (randomHash) { updateResponse.package_hash = "randomHash-" + Math.floor(Math.random() * 10000); } return updateResponse; } function setupScenario(scenarioPath: string): Q.Promise<string> { console.log("\nScenario: " + scenarioPath); return projectManager.setupScenario(testRunDirectory, TestNamespace, templatePath, scenarioPath, targetPlatform); } function setupUpdateScenario(updateScenarioPath: string, version: string): Q.Promise<string> { console.log("Creating an update at location: " + updatesDirectory); return projectManager.setupScenario(updatesDirectory, TestNamespace, templatePath, updateScenarioPath, targetPlatform, false, version); } describe("window.codePush", function() { before(() => { setupServer(); return projectManager.uninstallApplication(TestNamespace, targetPlatform) .then(() => { return useWkWebView ? projectManager.addPlugin(testRunDirectory, WkWebViewEnginePluginName).then(() => { return projectManager.addPlugin(updatesDirectory, WkWebViewEnginePluginName); }) : null; }); }); after(() => { cleanupServer(); return useWkWebView ? projectManager.removePlugin(testRunDirectory, WkWebViewEnginePluginName).then(() => { return projectManager.removePlugin(updatesDirectory, WkWebViewEnginePluginName); }) : null; }); describe("#window.codePush.checkForUpdate", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioCheckForUpdatePath); }); beforeEach(() => { return prepareTest(); }); if (!onlyRunCoreTests) { it("window.codePush.checkForUpdate.noUpdate", function(done: any) { var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UP_TO_DATE, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); it("window.codePush.checkForUpdate.sendsBinaryHash", function(done: any) { var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; updateCheckCallback = (request: any) => { try { assert(request.query.package_hash); } catch (e) { done(e); } }; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UP_TO_DATE, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); it("window.codePush.checkForUpdate.noUpdate.updateAppVersion", function(done: any) { var updateAppVersionResponse = createDefaultResponse(); updateAppVersionResponse.update_app_version = true; updateAppVersionResponse.target_binary_range = "2.0.0"; mockResponse = { update_info: updateAppVersionResponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UP_TO_DATE, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); } // CORE TEST it("window.codePush.checkForUpdate.update", function(done: any) { var updateResponse = createMockResponse(); mockResponse = { update_info: updateResponse }; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_UPDATE_AVAILABLE, requestBody.message); assert.notEqual(null, requestBody.args[0]); var remotePackage: IRemotePackage = requestBody.args[0]; assert.equal(remotePackage.downloadUrl, updateResponse.download_url); assert.equal(remotePackage.isMandatory, updateResponse.is_mandatory); assert.equal(remotePackage.label, updateResponse.label); assert.equal(remotePackage.packageHash, updateResponse.package_hash); assert.equal(remotePackage.packageSize, updateResponse.package_size); assert.equal(remotePackage.deploymentKey, targetPlatform.getDefaultDeploymentKey()); done(); } catch (e) { done(e); } }; updateCheckCallback = (request: any) => { try { assert.notEqual(null, request); assert.equal(request.query.deployment_key, targetPlatform.getDefaultDeploymentKey()); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); if (!onlyRunCoreTests) { it("window.codePush.checkForUpdate.error", function(done: any) { mockResponse = "invalid {{ json"; testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.CHECK_ERROR, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); } }); if (!onlyRunCoreTests) { describe("#window.codePush.checkForUpdate.customKey", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioCheckForUpdateCustomKey); }); beforeEach(() => { return prepareTest(); }); it("window.codePush.checkForUpdate.customKey.update", function(done: any) { var updateResponse = createMockResponse(); mockResponse = { update_info: updateResponse }; updateCheckCallback = (request: any) => { try { assert.notEqual(null, request); assert.equal(request.query.deployment_key, "CUSTOM-DEPLOYMENT-KEY"); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); }); describe("#remotePackage.download", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioDownloadUpdate); }); beforeEach(() => { return prepareTest(); }); var getMockResponse = (): su.CheckForUpdateResponseMock => { var updateResponse = createMockResponse(); updateResponse.download_url = targetPlatform.getServerUrl() + "/v0.1/public/codepush/report_status/download"; return updateResponse; }; it("remotePackage.download.success", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* pass the path to any file for download (here, config.xml) to make sure the download completed callback is invoked */ mockUpdatePackagePath = path.join(templatePath, "config.xml"); testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.DOWNLOAD_SUCCEEDED, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); it("remotePackage.download.error", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* pass an invalid path */ mockUpdatePackagePath = path.join(templatePath, "invalid_path.zip"); testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.DOWNLOAD_ERROR, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); }); describe("#localPackage.install", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioInstall); }); beforeEach(() => { return prepareTest(); }); var getMockResponse = (): su.CheckForUpdateResponseMock => { var updateResponse = createMockResponse(); updateResponse.download_url = targetPlatform.getServerUrl() + "/v0.1/public/codepush/report_status/download"; return updateResponse; }; it("localPackage.install.unzip.error", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* pass an invalid zip file, here, config.xml */ mockUpdatePackagePath = path.join(templatePath, "config.xml"); testMessageCallback = (requestBody: any) => { try { assert.equal(su.TestMessage.INSTALL_ERROR, requestBody.message); done(); } catch (e) { done(e); } }; projectManager.runPlatform(testRunDirectory, targetPlatform); }); it("localPackage.install.handlesDiff.againstBinary", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateNotifyApplicationReady, "Diff Update 1") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform, /*isDiff*/ true)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED, su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the app again to ensure it was not reverted */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); it("localPackage.install.immediately", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupScenario(ScenarioInstall).then<string>(() => { return setupUpdateScenario(UpdateNotifyApplicationReadyConditional, "Update 1"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED, su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the app again to ensure it was not reverted */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); }); describe("#localPackage.install.revert", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioInstallWithRevert); }); beforeEach(() => { return prepareTest(); }); it("localPackage.install.revert.dorevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateDeviceReady, "Update 1 (bad update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED, su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the app again to ensure it was reverted */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* create a second failed update */ console.log("Creating a second failed update."); var deferred = Q.defer<void>(); mockResponse = { update_info: getMockResponse() }; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED, su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the app again to ensure it was reverted */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); it("localPackage.install.revert.norevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateNotifyApplicationReady, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED, su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the app again to ensure it was not reverted */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); }); } describe("#localPackage.installOnNextResume", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioInstallOnResumeWithRevert); }); beforeEach(() => { return prepareTest(); }); // CORE TEST it("localPackage.installOnNextResume.dorevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupUpdateScenario(UpdateDeviceReady, "Update 1") .then<string>(() => { return projectManager.createUpdateArchive(updatesDirectory, targetPlatform); }) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* resume the application */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.resumeApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* restart to revert it */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); if (!onlyRunCoreTests) { it("localPackage.installOnNextResume.norevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateNotifyApplicationReady, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* resume the application */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.resumeApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* restart to make sure it did not revert */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); } }); describe("#localPackage.installOnNextRestart", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioInstallOnRestartWithRevert); }); beforeEach(() => { return prepareTest(); }); if (!onlyRunCoreTests) { it("localPackage.installOnNextRestart.dorevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupUpdateScenario(UpdateDeviceReady, "Update 1") .then<string>(() => { return projectManager.createUpdateArchive(updatesDirectory, targetPlatform); }) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* restart the application */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); console.log("Update hash: " + mockResponse.update_info.packageHash); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* restart the application */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); console.log("Update hash: " + mockResponse.update_info.packageHash); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); } // CORE TEST it("localPackage.installOnNextRestart.norevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateNotifyApplicationReady, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* "resume" the application - run it again */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run again to make sure it did not revert */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); if (!onlyRunCoreTests) { it("localPackage.installOnNextRestart.revertToPrevious", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupScenario(ScenarioInstallOnRestartWithRevert).then<string>(() => { return setupUpdateScenario(UpdateNotifyApplicationReadyConditional, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run good update, set up another (bad) update */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS, su.TestMessage.UPDATE_INSTALLED], deferred); mockResponse = { update_info: getMockResponse() }; setupUpdateScenario(UpdateDeviceReady, "Update 2 (bad update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then(() => { return projectManager.restartApplication(TestNamespace, targetPlatform); }); return deferred.promise; }) .then<void>(() => { /* run the bad update without calling notifyApplicationReady */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the good update and don't call notifyApplicationReady - it should not revert */ var deferred = Q.defer<void>(); testMessageResponse = su.TestMessageResponse.SKIP_NOTIFY_APPLICATION_READY; testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.SKIPPED_NOTIFY_APPLICATION_READY], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* run the application again */ var deferred = Q.defer<void>(); testMessageResponse = undefined; testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS, su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); } }); if (!onlyRunCoreTests) { describe("#localPackage.installOnNextRestart2x", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioInstallOnRestart2xWithRevert); }); beforeEach(() => { return prepareTest(); }); it("localPackage.installOnNextRestart2x.revertToFirst", function(done: any) { mockResponse = { update_info: getMockResponse() }; updateCheckCallback = () => { // Update the packageHash so we can install the same update twice. mockResponse.packageHash = "randomHash-" + Math.floor(Math.random() * 10000); }; /* create an update */ setupUpdateScenario(UpdateDeviceReady, "Bad Update") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([su.TestMessage.UPDATE_INSTALLED, su.TestMessage.UPDATE_INSTALLED], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* verify that the bad update is run, then restart it */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .then<void>(() => { /* verify the app rolls back to the binary, ignoring the first unconfirmed version */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([su.TestMessage.UPDATE_FAILED_PREVIOUSLY], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); }); } describe("#codePush.restartApplication", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioRestart); }); beforeEach(() => { return prepareTest(); }); it("codePush.restartApplication.checkPackages", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupUpdateScenario(UpdateNotifyApplicationReady, "Update 1") .then<string>(() => { return projectManager.createUpdateArchive(updatesDirectory, targetPlatform); }) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.PENDING_PACKAGE, [null]), new su.AppMessage(su.TestMessage.CURRENT_PACKAGE, [null]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_INSTALLING_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), new su.AppMessage(su.TestMessage.PENDING_PACKAGE, [mockResponse.update_info.package_hash]), new su.AppMessage(su.TestMessage.CURRENT_PACKAGE, [null]), su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS ], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform); return deferred.promise; }) .then<void>(() => { /* restart the application */ var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ su.TestMessage.DEVICE_READY_AFTER_UPDATE, su.TestMessage.NOTIFY_APP_READY_SUCCESS ], deferred); projectManager.restartApplication(TestNamespace, targetPlatform); return deferred.promise; }) .done(done, done); }); }); describe("#window.codePush.sync", function() { /* We test the functionality with sync twice--first, with sync only called one, * then, with sync called again while the first sync is still running /* Tests where sync is called just once */ if (!onlyRunCoreTests) { describe("#window.codePush.sync 1x", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioSync1x); }); beforeEach(() => { return prepareTest(); }); it("window.codePush.sync.noupdate", function(done: any) { var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; Q({}) .then<void>(p => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UP_TO_DATE])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.checkerror", function(done: any) { mockResponse = "invalid {{ json"; Q({}) .then<void>(p => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_ERROR])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.downloaderror", function(done: any) { var invalidUrlResponse = createMockResponse(); invalidUrlResponse.download_url = path.join(templatePath, "invalid_path.zip"); mockResponse = { update_info: invalidUrlResponse }; Q({}) .then<void>(p => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_ERROR])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.dorevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateDeviceReady, "Update 1 (bad update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_INSTALLING_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UP_TO_DATE])], deferred); projectManager.restartApplication(TestNamespace, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.update", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateSync, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_INSTALLING_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), // the update is immediate so the update will install su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { // restart the app and make sure it didn't roll out! var deferred = Q.defer<void>(); var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.restartApplication(TestNamespace, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); }); } /* Tests where sync is called again before the first sync finishes */ describe("#window.codePush.sync 2x", function() { afterEach(() => { cleanupTest(); }); before(() => { return setupScenario(ScenarioSync2x); }); beforeEach(() => { return prepareTest(); }); if (!onlyRunCoreTests) { it("window.codePush.sync.2x.noupdate", function(done: any) { var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; Q({}) .then<void>(p => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UP_TO_DATE])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.2x.checkerror", function(done: any) { mockResponse = "invalid {{ json"; Q({}) .then<void>(p => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_ERROR])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.2x.downloaderror", function(done: any) { var invalidUrlResponse = createMockResponse(); invalidUrlResponse.download_url = path.join(templatePath, "invalid_path.zip"); mockResponse = { update_info: invalidUrlResponse }; Q({}) .then<void>(p => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_ERROR])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("window.codePush.sync.2x.dorevert", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateDeviceReady, "Update 1 (bad update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_INSTALLING_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UP_TO_DATE])], deferred); projectManager.restartApplication(TestNamespace, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); } it("window.codePush.sync.2x.update", function(done: any) { mockResponse = { update_info: getMockResponse() }; /* create an update */ setupUpdateScenario(UpdateSync2x, "Update 1 (good update)") .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_CHECKING_FOR_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_DOWNLOADING_PACKAGE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_INSTALLING_UPDATE]), new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), // the update is immediate so the update will install su.TestMessage.DEVICE_READY_AFTER_UPDATE, new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { // restart the app and make sure it didn't roll out! var deferred = Q.defer<void>(); var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = verifyMessages([ su.TestMessage.DEVICE_READY_AFTER_UPDATE, new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_IN_PROGRESS])], deferred); projectManager.restartApplication(TestNamespace, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); }); if (!onlyRunCoreTests) { describe("#window.codePush.sync minimum background duration tests", function() { afterEach(() => { cleanupTest(); }); beforeEach(() => { return prepareTest(); }); it("defaults to no minimum", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupScenario(ScenarioSyncResume).then<string>(() => { return setupUpdateScenario(UpdateSync, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { var deferred = Q.defer<void>(); var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = verifyMessages([ su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.resumeApplication(TestNamespace, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("min background duration 5s", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupScenario(ScenarioSyncResumeDelay).then<string>(() => { return setupUpdateScenario(UpdateSync, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<string>(() => { var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; return projectManager.resumeApplication(TestNamespace, targetPlatform, 3 * 1000); }) .then<void>(() => { var deferred = Q.defer<void>(); testMessageCallback = verifyMessages([ su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.resumeApplication(TestNamespace, targetPlatform, 6 * 1000).done(); return deferred.promise; }) .done(done, done); }); it("has no effect on restart", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupScenario(ScenarioSyncRestartDelay).then<string>(() => { return setupUpdateScenario(UpdateSync, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { var deferred = Q.defer<void>(); var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = verifyMessages([su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.restartApplication(TestNamespace, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); }); describe("#window.codePush.sync mandatory install mode tests", function() { afterEach(() => { cleanupTest(); }); beforeEach(() => { return prepareTest(); }); it("defaults to IMMEDIATE", function(done: any) { mockResponse = { update_info: getMockResponse(true) }; setupScenario(ScenarioSyncMandatoryDefault).then<string>(() => { return setupUpdateScenario(UpdateDeviceReady, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); it("works correctly when update is mandatory and mandatory install mode is specified", function(done: any) { mockResponse = { update_info: getMockResponse(true) }; setupScenario(ScenarioSyncMandatoryResume).then<string>(() => { return setupUpdateScenario(UpdateDeviceReady, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED])], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .then<void>(() => { var deferred = Q.defer<void>(); var noUpdateResponse = createDefaultResponse(); noUpdateResponse.is_available = false; noUpdateResponse.target_binary_range = "0.0.1"; mockResponse = { update_info: noUpdateResponse }; testMessageCallback = verifyMessages([ su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.resumeApplication(TestNamespace, targetPlatform, 5 * 1000).done(); return deferred.promise; }) .done(done, done); }); it("has no effect on updates that are not mandatory", function(done: any) { mockResponse = { update_info: getMockResponse() }; setupScenario(ScenarioSyncMandatoryRestart).then<string>(() => { return setupUpdateScenario(UpdateDeviceReady, "Update 1 (good update)"); }) .then<string>(projectManager.createUpdateArchive.bind(undefined, updatesDirectory, targetPlatform)) .then<void>((updatePath: string) => { var deferred = Q.defer<void>(); mockUpdatePackagePath = updatePath; testMessageCallback = verifyMessages([ new su.AppMessage(su.TestMessage.SYNC_STATUS, [su.TestMessage.SYNC_UPDATE_INSTALLED]), su.TestMessage.DEVICE_READY_AFTER_UPDATE], deferred); projectManager.runPlatform(testRunDirectory, targetPlatform).done(); return deferred.promise; }) .done(done, done); }); }); } }); }); } // CODE THAT EXECUTES THE TESTS // describe("CodePush Cordova Plugin", function () { this.timeout(100 * 60 * 1000); if (shouldSetup) describe("Setting Up For Tests", () => setupTests()); else { targetPlatforms.forEach(platform => { var prefix: string = (onlyRunCoreTests ? "Core Tests " : "Tests ") + thisPluginPath + " on "; if (platform.getCordovaName() === "ios") { // handle UIWebView if (shouldUseWkWebView === 0 || shouldUseWkWebView === 2) describe(prefix + platform.getCordovaName() + " with UIWebView", () => runTests(platform, false)); // handle WkWebView if (shouldUseWkWebView === 1 || shouldUseWkWebView === 2) describe(prefix + platform.getCordovaName() + " with WkWebView", () => runTests(platform, true)); } else { describe(prefix + platform.getCordovaName(), () => runTests(platform, false)); } }); } });
the_stack
"use strict"; import { Socket } from "socket.io"; import { NameColorPair, Stopwatch, Colors } from "./utils"; import { Game } from "./game"; //set this to what the admin password should be const password = "goat"; export interface Phrase { text: string; color?: Colors; backgroundColor?: Colors; italic?: boolean; } export type Message = Array<Phrase>; export class User { //true if the user has a username private _registered: boolean = false; private _sockets: Array<Socket> = []; private _inGame: boolean = false; private _username: string = "randomuser"; //index of the game the user is in in the server's 'games' array private _game: undefined | Game = undefined; //true if the user has disconnected entirely private _disconnected: boolean = false; private _admin: boolean = false; private _startVote: boolean = false; //username color private _color: Colors = Colors.none; private _gameClickedLast: string = ""; private _session: string = ""; //true if already playing in another tab private _cannotRegister: boolean = false; private _id: string; private _cache: Array<{ msg: Message; color?: Colors }> = []; private _leftMessageCache: Array<Message> = []; private _time: number = 0; private _stopwatch: Stopwatch; private _warn: number = 0; private _canVote: boolean = false; private _selectedUserName: string = ""; private _host: boolean = false; //store a list of all the dead players so they get removed when the page is reloaded. private _deadCache: Array<string> = []; public constructor(user: User); public constructor(id: string, session: string); public constructor(id: string | User, session?: string) { if (id instanceof User) { Object.assign(this, id); this._stopwatch = id._stopwatch; this._id = id._id; } else { this._id = id; this._username = "randomuser"; if (session) { this._session = session; } this._stopwatch = new Stopwatch(); this._stopwatch.stop(); } } public resetAfterGame(): void { this._game = undefined; this._inGame = false; this._startVote = false; this._color = Colors.none; this.gameClickedLast = ""; this._cache = []; this._leftMessageCache = []; this._deadCache = []; this._host = false; } public reloadClient(): void { this.emit("reloadClient"); } public banFromRegistering(): void { this._cannotRegister = true; } get cannotRegister() { return this._cannotRegister; } set gameClickedLast(game: string) { this._gameClickedLast = game; } get gameClickedLast() { return this._gameClickedLast; } /** * Sends event to this user * * @param {string} event * @memberof User */ public emit( event: string, ...args: Array< | string | number | string[] | boolean | undefined | Array<{ text: string; color: string | Colors }> | Message | Array<{ roleName: string; color: Colors }> > ) { for (let i = 0; i < this._sockets.length; i++) { this._sockets[i].emit(event, ...args); } } public makeHost(roles: Array<{ roleName: string; color: Colors }>) { this._host = true; this.emit("makeHost", roles); } public removeHostPrivileges() { this._host = false; this.emit("removeHostPrivileges"); } get isHost() { return this._host; } public addSocket(socket: Socket) { this._sockets.push(socket); } public removeSocket(socket: Socket) { let index = this._sockets.indexOf(socket); if (index != -1) { this._sockets.splice(index, 1); } } get socketCount() { return this._sockets.length; } /** * Causes the client to emit a notification sound */ public sound(sound: string) { this.emit("sound", sound); } get session() { return this._session; } get disconnected() { return this._disconnected; } public disconnect() { this._disconnected = true; } get game(): undefined | Game { return this._game; } get id() { return this._id; } get inGame() { return this._inGame; } set game(game: undefined | Game) { this._game = game; } set inGame(isInGame: boolean) { this._inGame = isInGame; } /** * Sets html title of client. */ set title(title: string) { this.emit("setTitle", title); } get registered() { return this._registered; } public register() { this.emit("registered", this.username); this._registered = true; } public setUsername(username: string) { this._username = username; } get username() { return this._username; } public updateGameListing( name: string, userNameColorPairs: Array<NameColorPair>, uid: string, inPlay: boolean, ) { let usernames: Array<string> = []; let userColors: Array<string> = []; for (let i = 0; i < userNameColorPairs.length; i++) { userColors.push(userNameColorPairs[i].color); usernames.push(userNameColorPairs[i].username); } this.emit("updateGame", name, usernames, userColors, uid, inPlay); } public verifyAsAdmin(msg: string): boolean { if (msg == "!" + password) { this._admin = true; return true; } else { return false; } } get admin(): boolean { return this._admin; } /** * send message to this user and only this user * @param msg */ public send( text: Message | string, textColor?: Colors, backgroundColor?: Colors, usernameColor?: Colors, ) { if (typeof text == "string") { this.emit( "message", [ { text: text, color: textColor, //backgroundColor: backgroundColor, }, ], backgroundColor, ); this._cache.push({ msg: [ { text: text, color: textColor, }, ], color: backgroundColor, }); if (this._cache.length > 50) { this._cache.splice(0, 1); } } else { this.emit("message", text, textColor); this._cache.push({ msg: text, color: textColor }); } } get cache() { return this._cache; } get leftCache() { return this._leftMessageCache; } //These functions manipulate the two boxes either side of the central chatbox public rightSend( msg: string | Message, textColor?: Colors, backgroundColor?: Colors, ): void { if (typeof msg == "string") { this.emit("rightMessage", [ { text: msg, color: textColor, backgroundColor: backgroundColor }, ]); } else { this.emit("rightMessage", msg); } } public leftSend( message: string, textColor?: Colors, backgroundColor?: Colors, ): void { this.emit("leftMessage", [ { text: message, color: textColor, backgroundColor: backgroundColor }, ]); this._leftMessageCache.push([ { text: message, color: textColor, backgroundColor: backgroundColor }, ]); } public removeRight(msg: string) { this.emit("removeRight", msg); } public removeLeft(msg: string) { this.emit("removeLeft", msg); } public lineThroughUser(msg: string, color: string) { this.emit("lineThroughPlayer", msg, color); } public markAsDead(msg: string) { this.emit("markAsDead", msg); this._deadCache.push(msg); } /** * Removes another user's username from the lobby * E.g the other user has left. * @param username * @param game */ public removePlayerListingFromGame(username: string, game: Game) { this.emit("removePlayerFromGameList", username, game.uid); } public addListingToGame(username: string, color: string, game: Game) { this.emit("addPlayerToGameList", username, color, game.uid); } public markGameStatusInLobby(game: Game, status: string) { this.emit("markGameStatusInLobby", game.uid, status); } public addPlayerToLobbyList(username: string) { this.emit("addPlayerToLobbyList", username); } public removePlayerFromLobbyList(username: string) { this.emit("removePlayerFromLobbyList", username); } public get deadCache(): Array<string> { return this._deadCache; } public lobbyMessage( msg: string, textColor: Colors, backgroundColor?: Colors, ) { this.emit("lobbyMessage", [ { text: msg, color: textColor, backgroundColor: backgroundColor }, ]); } public setTime(time: number, warn: number) { this.emit("setTime", time, warn); this._time = time; this._warn = warn; this._stopwatch.restart(); this._stopwatch.start(); } public getTime() { return this._time - this._stopwatch.time; } public getWarn() { return this._warn; } get startVote() { return this._startVote; } set startVote(startVote: boolean) { this._startVote = startVote; } set color(color: Colors) { this._color = color; } get color() { return this._color; } public equals(otherUser: User): boolean { return this.id == otherUser.id; } public registrationError(message: string) { this.emit("registrationError", message); } public addNewGameToLobby(name: string, type: string, uid: string) { this.emit("addNewGameToLobby", name, type, uid); } public removeGameFromLobby(uid: string) { this.emit("removeGameFromLobby", uid); } public headerSend(message: Message) { this.emit("headerTextMessage", message); } public cancelVoteEffect() { this.emit("cancelVoteEffect"); } public selectUser(username: string) { this.emit("selectPlayer", username); this._selectedUserName = username; } get selectedUsername() { return this._selectedUserName; } public canVote() { this.emit("canVote"); this._canVote = true; } public cannotVote() { this.emit("cannotVote"); this._canVote = false; } get ifCanVote() { return this._canVote; } public hang(usernames: Array<string>) { this.emit("hang", usernames); } public resetGallows() { this.emit("resetGallows"); } }
the_stack
* @module Tiles */ import { request, RequestOptions } from "./request/Request"; import { AccessToken, assert, GuidString, Logger } from "@itwin/core-bentley"; import { RealityData, RealityDataFormat, RealityDataProvider, RealityDataSourceKey, RealityDataSourceProps } from "@itwin/core-common"; import { FrontendLoggerCategory } from "./FrontendLoggerCategory"; import { IModelApp } from "./IModelApp"; import { PublisherProductInfo, RealityDataSource, SpatialLocationAndExtents } from "./RealityDataSource"; import { OPCFormatInterpreter, ThreeDTileFormatInterpreter } from "./tile/internal"; /** This class provides access to the reality data provider services. * It encapsulates access to a reality data weiter it be from local access, http or ProjectWise Context Share. * The key provided at the creation determines if this is ProjectWise Context Share reference. * If not then it is considered local (ex: C:\temp\TileRoot.json) or plain http access (http://someserver.com/data/TileRoot.json) * There is a one to one relationship between a reality data and the instances of present class. * @internal */ export class RealityDataSourceContextShareImpl implements RealityDataSource { public readonly key: RealityDataSourceKey; /** The URL that supplies the 3d tiles for displaying the reality model. */ private _tilesetUrl: string | undefined; private _isUrlResolved: boolean = false; private _rd: RealityData | undefined; /** For use by all Reality Data. For RD stored on PW Context Share, represents the portion from the root of the Azure Blob Container*/ private _baseUrl: string = ""; /** Construct a new reality data source. * @param props JSON representation of the reality data source */ protected constructor(props: RealityDataSourceProps) { // this implementaiton is specific to ContextShare provider assert(props.sourceKey.provider === RealityDataProvider.ContextShare); this.key = props.sourceKey; this._isUrlResolved = false; } /** * Create an instance of this class from a source key and iTwin context/ */ public static async createFromKey(sourceKey: RealityDataSourceKey, iTwinId: GuidString | undefined): Promise<RealityDataSource | undefined> { if (sourceKey.provider !== RealityDataProvider.ContextShare) return undefined; const rdSource = new RealityDataSourceContextShareImpl({ sourceKey }); let tilesetUrl: string | undefined; try { await rdSource.queryRealityData(iTwinId); tilesetUrl = await rdSource.getServiceUrl(iTwinId); } catch (e) { } return (tilesetUrl !== undefined) ? rdSource : undefined; } public get isContextShare(): boolean { return (this.key.provider === RealityDataProvider.ContextShare); } /** * Returns Reality Data if available */ public get realityData(): RealityData | undefined { return this._rd; } public get realityDataId(): string | undefined { const realityDataId = this.key.id; return realityDataId; } /** * Returns Reality Data type if available */ public get realityDataType(): string | undefined { return this._rd?.type; } /** * Query Reality Data from provider */ private async queryRealityData(iTwinId: GuidString | undefined) { if (!this._rd) { const token = await IModelApp.getAccessToken(); if (token && this.realityDataId) { if (undefined === IModelApp.realityDataAccess) throw new Error("Missing an implementation of RealityDataAccess on IModelApp, it is required to access reality data. Please provide an implementation to the IModelApp.startup using IModelAppOptions.realityDataAccess."); this._rd = await IModelApp.realityDataAccess.getRealityData(token, iTwinId, this.realityDataId); // A reality data that has not root document set should not be considered. const rootDocument: string = this._rd.rootDocument ?? ""; this.setBaseUrl(rootDocument); } } } // This is to set the root url from the provided root document path. // If the root document is stored on PW Context Share then the root document property of the Reality Data is provided, // otherwise the full path to root document is given. // The base URL contains the base URL from which tile relative path are constructed. // The tile's path root will need to be reinserted for child tiles to return a 200 private setBaseUrl(url: string): void { const urlParts = url.split("/"); urlParts.pop(); if (urlParts.length === 0) this._baseUrl = ""; else this._baseUrl = `${urlParts.join("/")}/`; } /** * Gets a tileset's app data json * @param name name or path of tile * @returns app data json object * @internal */ public async getRealityDataTileJson(accessToken: AccessToken, name: string, realityData: RealityData): Promise<any> { const url = await realityData.getBlobUrl(accessToken, name); const data = await request(url.toString(), { method: "GET", responseType: "json", }); return data.body; } /** * This method returns the URL to access the actual 3d tiles from the service provider. * @returns string containing the URL to reality data. */ public async getServiceUrl(iTwinId: GuidString | undefined): Promise<string | undefined> { // If url was not resolved - resolve it if (!this._isUrlResolved) { const rdSourceKey = this.key; // we need to resolve tilesetURl from realityDataId and iTwinId if (undefined === IModelApp.realityDataAccess) throw new Error("Missing an implementation of RealityDataAccess on IModelApp, it is required to access reality data. Please provide an implementation to the IModelApp.startup using IModelAppOptions.realityDataAccess."); try { const resolvedITwinId = iTwinId ? iTwinId : rdSourceKey.iTwinId; this._tilesetUrl = await IModelApp.realityDataAccess.getRealityDataUrl(resolvedITwinId, rdSourceKey.id); this._isUrlResolved = true; } catch (e) { const errMsg = `Error getting URL from ContextShare using realityDataId=${rdSourceKey.id} and iTwinId=${iTwinId}`; Logger.logError(FrontendLoggerCategory.RealityData, errMsg); } } return this._tilesetUrl; } public async getRootDocument(_iTwinId: GuidString | undefined): Promise<any> { const token = await IModelApp.getAccessToken(); if (token) { const realityData = this.realityData; if (!realityData) throw new Error(`Reality Data not defined`); if (!realityData.rootDocument) throw new Error(`Root document not defined for reality data: ${realityData.id}`); return this.getRealityDataTileJson(token, realityData.rootDocument, realityData); } } /** * Gets tile content * @param name name or path of tile * @returns array buffer of tile content */ public async getRealityDataTileContent(accessToken: AccessToken, name: string, realityData: RealityData): Promise<any> { const url = await realityData.getBlobUrl(accessToken, name); const options: RequestOptions = { method: "GET", responseType: "arraybuffer", }; const data = await request(url.toString(), options); return data.body; } /** * Returns the tile content. The path to the tile is relative to the base url of present reality data whatever the type. */ public async getTileContent(name: string): Promise<any> { const token = await IModelApp.getAccessToken(); const tileUrl = this._baseUrl + name; if (this.realityData) { return this.getRealityDataTileContent(token, tileUrl, this.realityData); } return undefined; } /** * Returns the tile content in json format. The path to the tile is relative to the base url of present reality data whatever the type. */ public async getTileJson(name: string): Promise<any> { const token = await IModelApp.getAccessToken(); const tileUrl = this._baseUrl + name; if (this.realityData) { return this.getRealityDataTileJson(token, tileUrl, this.realityData); } return undefined; } /** * Gets spatial location and extents of this reality data source * @returns spatial location and extents * @internal */ public async getSpatialLocationAndExtents(): Promise<SpatialLocationAndExtents | undefined> { let spatialLocation: SpatialLocationAndExtents | undefined; const fileType = this.realityDataType; // Mapping Resource are not currenlty supported if (fileType === "OMR") return undefined; if (this.key.format === RealityDataFormat.ThreeDTile) { const rootDocument = await this.getRootDocument(undefined); spatialLocation = ThreeDTileFormatInterpreter.getSpatialLocationAndExtents(rootDocument); } else if (this.key.format === RealityDataFormat.OPC) { if (this.realityData === undefined) return undefined; const token = await IModelApp.getAccessToken(); const docRootName = this.realityData.rootDocument; if (!docRootName) return undefined; const blobUrl = await this.realityData.getBlobUrl(token, docRootName); if (!blobUrl) return undefined; const blobStringUrl = blobUrl.toString(); const filereader = await OPCFormatInterpreter.getFileReaderFromBlobFileURL(blobStringUrl); spatialLocation = await OPCFormatInterpreter.getSpatialLocationAndExtents(filereader); } return spatialLocation; } /** * Gets information to identify the product and engine that create this reality data * Will return undefined if cannot be resolved * @returns information to identify the product and engine that create this reality data * @alpha */ public async getPublisherProductInfo(): Promise<PublisherProductInfo | undefined> { let publisherInfo: PublisherProductInfo | undefined; if (this.key.format === RealityDataFormat.ThreeDTile) { const rootDocument = await this.getRootDocument(undefined); publisherInfo = ThreeDTileFormatInterpreter.getPublisherProductInfo(rootDocument); } return publisherInfo; } }
the_stack
import { sm } from '../jssm'; const r639 = require('reduce-to-639-1').reduce; test.todo('Most of this machine_attributes stuff should be rewritten as table-driven and/or stoch'); describe('machine_name', () => { test('atom', () => expect(() => { const _foo = sm`machine_name: bob; a->b;`; }) .not.toThrow() ); test('quoted string', () => expect(() => { const _foo = sm`machine_name: "bo b"; a->b;`; }) .not.toThrow() ); test('retval correct', () => expect(sm`machine_name: testval; a->b;`.machine_name() ) .toBe('testval') ); }); describe('machine_language', () => { const eachTest = (name, lang) => { test(`${name} machine_language with transclusion is correct for sm\`machine_language: ${lang}; a->b;\``, () => expect( ((sm`machine_language: ${lang}; a->b;`).machine_language()) ) .toBe( r639(lang) ) ); test.todo('machine_attributes spec more available'); // test(`${name} machine_language with transclusion is correct for sm\`machine_language: "${lang}"; a->b;\``, () => // t.is(r639(lang), ((sm`machine_language: "${lang}"; a->b;`).machine_language()) ) ); }; test(`Eng hand-written is correct without quotes`, () => expect(((sm`machine_language: EnGlIsH; a->b;`).machine_language() )) .toBe('en') ); test(`Eng hand-written is correct with quotes`, () => expect(((sm`machine_language: "EnGlIsH"; a->b;`).machine_language() )) .toBe('en') ); test(`Amharic hand-written is correct without quotes`, () => expect(((sm`machine_language: አማርኛ; a->b;`).machine_language() )) .toBe('am') ); test.todo('machine_attributes spec more available 2'); // test(`Amharic hand-written is correct with quotes`, () => // t.is('am', ((sm`machine_language: "አማርኛ"; a->b;`).machine_language()) ) ); eachTest('atom correct case', 'English'); eachTest('atom lowercase', 'english'); eachTest('atom mixedcase', 'eNGliSH'); eachTest('amharic', 'አማርኛ'); }); describe('machine_author', () => { test('single atom', () => expect( () => { const _foo = sm`machine_author: bob; a->b;`; }) .not.toThrow() ); test('single quoted string', () => expect( () => { const _foo = sm`machine_author: "bo b"; a->b;`; }) .not.toThrow() ); test('atom list', () => expect( () => { const _foo = sm`machine_author: [bob dobbs]; a->b;`; }) .not.toThrow() ); test('quoted string list', () => expect( () => { const _foo = sm`machine_author: ["bo b" "do bbs"]; a->b;`; }) .not.toThrow() ); test('mixed list a/q', () => expect( () => { const _foo = sm`machine_author: [bob "do bbs"]; a->b;`; }) .not.toThrow() ); test('mixed list q/a', () => expect( () => { const _foo = sm`machine_author: ["bo b" dobbs]; a->b;`; }) .not.toThrow() ); test('single retval', () => expect(sm`machine_author: testval; a->b;`.machine_author() ) .toEqual(['testval']) ); test('multiple retval', () => expect(sm`machine_author: [bob david]; a->b;`.machine_author() ) .toEqual(['bob','david']) ); }); describe('machine_contributor', () => { test('atom', () => expect( () => { const _ = sm`machine_contributor: bob; a->b;`; }) .not.toThrow() ); test('quoted string', () => expect( () => { const _ = sm`machine_contributor: "bo b"; a->b;`; }) .not.toThrow() ); test('atom list', () => expect( () => { const _ = sm`machine_contributor: [bob dobbs]; a->b;`; }) .not.toThrow() ); test('quoted string list', () => expect( () => { const _ = sm`machine_contributor: ["bo b" "do bbs"]; a->b;`; }) .not.toThrow() ); test('mixed list a/q', () => expect( () => { const _ = sm`machine_contributor: [bob "do bbs"]; a->b;`; }) .not.toThrow() ); test('mixed list q/a', () => expect( () => { const _ = sm`machine_contributor: ["bo b" dobbs]; a->b;`; }) .not.toThrow() ); test('single retval', () => expect(sm`machine_contributor: testval; a->b;`.machine_contributor() ) .toEqual(["testval"]) ); test('multiple retval', () => expect(sm`machine_contributor: [bob david]; a->b;`.machine_contributor() ) .toEqual(['bob','david']) ); }); describe('machine_comment', () => { test('atom', () => expect( () => { const _foo = sm`machine_comment: bob; a->b;`; }) .not.toThrow() ); test('quoted string', () => expect( () => { const _foo = sm`machine_comment: "bo b"; a->b;`; }) .not.toThrow() ); test('retval correct', () => expect(sm`machine_comment: testval; a->b;`.machine_comment() ) .toBe("testval") ); }); describe('machine_definition', () => { test('url', () => expect( () => { const _foo = sm`machine_definition: http://google.com/ ; a->b;`; }) .not.toThrow() ); test('url botched', () => expect( () => { const _foo = sm`machine_definition: "not a url"; a->b;`; }) .toThrow() ); test('retval correct', () => expect(sm`machine_definition: http://google.com/ ; a->b;`.machine_definition() ) .toBe("http://google.com/") ); }); describe('machine_version', () => { test('semver 0.0.0', () => expect( () => { const _f = sm`machine_version: 0.0.0; a->b;`; }) .not.toThrow() ); test('semver 0.0.1', () => expect( () => { const _f = sm`machine_version: 0.0.1; a->b;`; }) .not.toThrow() ); test('semver 0.1.0', () => expect( () => { const _f = sm`machine_version: 0.1.0; a->b;`; }) .not.toThrow() ); test('semver 1.0.0', () => expect( () => { const _f = sm`machine_version: 1.0.0; a->b;`; }) .not.toThrow() ); test('semver 1.0.1', () => expect( () => { const _f = sm`machine_version: 1.0.1; a->b;`; }) .not.toThrow() ); test('semver 1.1.1', () => expect( () => { const _f = sm`machine_version: 1.1.1; a->b;`; }) .not.toThrow() ); test('semver 2.0.0', () => expect( () => { const _f = sm`machine_version: 2.0.0; a->b;`; }) .not.toThrow() ); test('semver notAS', () => expect(() => { const _f = sm`machine_version: "Not a semver"; a->b;`; }) .toThrow() ); test('retval correct', () => expect(sm`machine_version: 0.0.0; a->b;`.machine_version()) .toEqual({full:"0.0.0", major:0, minor:0, patch:0}) ); }); describe('machine_license', () => { test('retval correct', () => expect( sm`machine_license: testval; a->b;`.machine_license() ) .toBe("testval") ); describe('near', () => { test('Public domain', () => expect( () => { const _ = sm`machine_license:Public domain; a->b;`; }) .not.toThrow() ); test('MIT', () => expect( () => { const _ = sm`machine_license:MIT; a->b;`; }) .not.toThrow() ); test('BSD 2-clause', () => expect( () => { const _ = sm`machine_license:BSD 2-clause; a->b;`; }) .not.toThrow() ); test('BSD 3-clause', () => expect( () => { const _ = sm`machine_license:BSD 3-clause; a->b;`; }) .not.toThrow() ); test('Apache 2.0', () => expect( () => { const _ = sm`machine_license:Apache 2.0; a->b;`; }) .not.toThrow() ); test('Mozilla 2.0', () => expect( () => { const _ = sm`machine_license:Mozilla 2.0; a->b;`; }) .not.toThrow() ); test('GPL v2', () => expect( () => { const _ = sm`machine_license:GPL v2; a->b;`; }) .not.toThrow() ); test('GPL v3', () => expect( () => { const _ = sm`machine_license:GPL v3; a->b;`; }) .not.toThrow() ); test('LGPL v2.1', () => expect( () => { const _ = sm`machine_license:LGPL v2.1; a->b;`; }) .not.toThrow() ); test('LGPL v3.0', () => expect( () => { const _ = sm`machine_license:LGPL v3.0; a->b;`; }) .not.toThrow() ); }); describe('spaced', () => { test('Public domain', () => expect( () => { const _ = sm`machine_license: Public domain ; a->b;`; }) .not.toThrow() ); test('MIT', () => expect( () => { const _ = sm`machine_license: MIT ; a->b;`; }) .not.toThrow() ); test('BSD 2-clause', () => expect( () => { const _ = sm`machine_license: BSD 2-clause ; a->b;`; }) .not.toThrow() ); test('BSD 3-clause', () => expect( () => { const _ = sm`machine_license: BSD 3-clause ; a->b;`; }) .not.toThrow() ); test('Apache 2.0', () => expect( () => { const _ = sm`machine_license: Apache 2.0 ; a->b;`; }) .not.toThrow() ); test('Mozilla 2.0', () => expect( () => { const _ = sm`machine_license: Mozilla 2.0 ; a->b;`; }) .not.toThrow() ); test('GPL v2', () => expect( () => { const _ = sm`machine_license: GPL v2 ; a->b;`; }) .not.toThrow() ); test('GPL v3', () => expect( () => { const _ = sm`machine_license: GPL v3 ; a->b;`; }) .not.toThrow() ); test('LGPL v2.1', () => expect( () => { const _ = sm`machine_license: LGPL v2.1 ; a->b;`; }) .not.toThrow() ); test('LGPL v3.0', () => expect( () => { const _ = sm`machine_license: LGPL v3.0 ; a->b;`; }) .not.toThrow() ); }); test('single atom', () => expect( () => { const _ = sm`machine_license: bob; a->b;`; }) .not.toThrow() ); test('single quoted string', () => expect( () => { const _ = sm`machine_license: "bo b"; a->b;`; }) .not.toThrow() ); }); describe('fsl_version', () => { test('semver 0.0.0', () => expect( () => { const _f = sm`fsl_version: 0.0.0; a->b;`; }) .not.toThrow() ); test('semver 0.0.1', () => expect( () => { const _f = sm`fsl_version: 0.0.1; a->b;`; }) .not.toThrow() ); test('semver 0.1.0', () => expect( () => { const _f = sm`fsl_version: 0.1.0; a->b;`; }) .not.toThrow() ); test('semver 1.0.0', () => expect( () => { const _f = sm`fsl_version: 1.0.0; a->b;`; }) .not.toThrow() ); test('semver 1.0.1', () => expect( () => { const _f = sm`fsl_version: 1.0.1; a->b;`; }) .not.toThrow() ); test('semver 1.1.1', () => expect( () => { const _f = sm`fsl_version: 1.1.1; a->b;`; }) .not.toThrow() ); test('semver 2.0.0', () => expect( () => { const _f = sm`fsl_version: 2.0.0; a->b;`; }) .not.toThrow() ); test('semver notAS', () => expect(() => { const _f = sm`fsl_version: "Not a semver"; a->b;`; }) .toThrow() ); test('retval correct', () => expect(sm`fsl_version: 0.0.0; a->b;`.fsl_version()) .toEqual({full:"0.0.0", major:0, minor:0, patch:0}) ); });
the_stack